theater

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 18, 2026 License: MIT Imports: 44 Imported by: 0

README

Theater

Tests Go Reference Go Report Card Go Version License

Theater runs repeatable API and workflow checks from .thtr or YAML files. Validate a stage before execution, reuse scenarios across flows, and get a run report that points back to the exact act, action, or expectation that passed or failed.

It is a verification runner, not an application framework or a general scripting host. Production behavior stays in the system under test. Theater files describe the checks another developer or CI job should be able to run again.

Shape

A Theater file is a stage that calls reusable scenarios. This example logs in to a local fixture server, reuses the HTTP session, and checks a JSON response field from the profile endpoint.

stage http-profile

http
  session browser = http.session.browser()

scenario http/profile
  act login
    prop login_url = inventory.env(name: "THEATER_DOC_LOGIN_URL")
    do action.http(method: "GET", url: $login_url, session: "browser")
    expect login-ok: field(status_code) == 200
    on pass -> fetch-profile

  act fetch-profile
    prop profile_url = inventory.env(name: "THEATER_DOC_PROFILE_URL")
    do action.http(method: "GET", url: $profile_url, session: "browser")
    expect status-ok: field(status_code) == 200
    expect profile-id: field(body) | decode(json) | path("/data/id") == "user-123"

call run = http/profile()

Run The HTTP Check

From a repository checkout, validate the HTTP profile example:

go run ./cmd/theater validate docs/examples/http-flow/profile.thtr

Expected output: docs/examples/http-flow/profile.thtr: valid.

Then run it with the local fixture server. The fixture starts a loopback HTTP server, sets the THEATER_DOC_* URLs for the child process, and runs the Theater command after --.

go run ./docs/examples/http-state/fixture -- go run ./cmd/theater run docs/examples/http-flow/profile.thtr --live off

Output starts with docs/examples/http-flow/profile.thtr: passed (passed=1 failed=0 canceled=0 skipped=0; the duration value varies.

Authoring Surfaces

Theater DSL (.thtr) is the compact authoring format. It lowers to the same runtime stage model that YAML uses; it is not a separate runtime.

YAML is a first-class authoring option and the canonical interchange form. The YAML twin of the HTTP example is docs/examples/http-flow/profile.yaml:

go run ./cmd/theater validate docs/examples/http-flow/profile.yaml

Use theater lower when you want to inspect the YAML produced from a .thtr file.

Why Use It

  • Keep verification flows in readable repository files instead of one-off scripts.
  • Validate authoring mistakes before running a real flow.
  • Reuse scenarios for setup, login, creation, cleanup, or domain-specific checks.
  • Emit human, JSON, and JUnit run output for local development and CI.
  • Capture source-linked expectations and scenario-authored logs in the run report.

Install

Released CLI archives are attached to GitHub Releases. Choose the archive for your OS and CPU:

  • theater_<version>_linux_amd64.tar.gz
  • theater_<version>_linux_arm64.tar.gz
  • theater_<version>_darwin_amd64.tar.gz
  • theater_<version>_darwin_arm64.tar.gz

Each release also includes SHA256SUMS.

macOS assets use the Go darwin OS name. After downloading the archive and SHA256SUMS, verify with sha256sum -c SHA256SUMS, unpack with tar -xzf theater_<version>_<os>_<arch>.tar.gz, then run ./theater help or move theater onto your PATH.

If Go 1.25 or newer is installed, you can run Theater directly from a source checkout:

go run ./cmd/theater help

Build a local binary when you want a reusable executable inside the checkout: run go build -o ./bin/theater ./cmd/theater, then run ./bin/theater help.

Install from the checkout into GOBIN, or into GOPATH/bin when GOBIN is not set, with go install ./cmd/theater. Make sure that install directory is on your PATH, then run theater help.

After the repository is public, the same Go toolchain can install a released version directly from GitHub with go install github.com/alex-poliushkin/theater/cmd/theater@latest.

JetBrains IDE users can install the released jetbrains-thtr-plugin-<version>.zip through Settings | Plugins | Install Plugin from Disk. The native plugin enables .thtr syntax highlighting, completion, diagnostics, formatting, navigation, structure view, folding, quick documentation, find usages and rename support. For compatibility details, use the Editor Tooling reference.

Where To Go Next

Goal Start here
Follow the guided tutorial path First Run tutorial
Understand the project model Why Theater
Inspect runnable files Examples
Validate and run your own flow Validate and run a flow
Look up CLI behavior CLI reference
Look up .thtr syntax Theater DSL reference
Look up YAML syntax YAML reference
Inspect run reports and output formats Reports and output formats

The full documentation map is in docs/index.md.

License

MIT - see LICENSE.

Documentation

Overview

Package theater provides the orchestration API for compiling, validating, and running declarative stages.

The root package owns the common runtime entry points and extension seams, such as Catalog, Runner, Validator, Action, Inventory, and decorators. Canonical authoring model types live in package spec, canonical report document types live in package report, and canonical persistent-state types live in package state.

Index

Examples

Constants

View Source
const (
	CapabilityFamilyAction         CapabilityFamily = "action"
	CapabilityFamilyGenerator      CapabilityFamily = "generator"
	CapabilityFamilyInventory      CapabilityFamily = "inventory"
	CapabilityFamilyMatcher        CapabilityFamily = "matcher"
	CapabilityFamilyReportExporter CapabilityFamily = "report-exporter"
	CapabilityFamilyStateBackend   CapabilityFamily = "state-backend"
	CapabilityFamilyTransform      CapabilityFamily = "transform"

	CapabilityProviderBuiltin CapabilityProviderKind = "builtin"
	CapabilityProviderPlugin  CapabilityProviderKind = "plugin"
)
View Source
const (
	DebugBoundaryKindScenarioCall DebugBoundaryKind = debugBoundaryKindScenarioCall
	DebugBoundaryKindAct          DebugBoundaryKind = debugBoundaryKindAct
	DebugBoundaryKindAction       DebugBoundaryKind = debugBoundaryKindAction
	DebugBoundaryKindExpectation  DebugBoundaryKind = debugBoundaryKindExpectation

	DebugBoundaryPhaseBefore DebugBoundaryPhase = debugBoundaryPhaseBefore
	DebugBoundaryPhaseAfter  DebugBoundaryPhase = debugBoundaryPhaseAfter
)

Public status, failure-kind, and phase values used by runtime outcomes.

View Source
const (
	RunDocumentSchemaVersion = reportmodel.RunDocumentSchemaVersion

	DefaultScenarioLogPreviewLimitBytes = reportmodel.DefaultScenarioLogPreviewLimitBytes
	DefaultScenarioLogRecordsPerAct     = reportmodel.DefaultScenarioLogRecordsPerAct
	DefaultScenarioLogRecordsPerRun     = reportmodel.DefaultScenarioLogRecordsPerRun

	EventKindStageRunning        = reportmodel.EventKindStageRunning
	EventKindStageFinished       = reportmodel.EventKindStageFinished
	EventKindScenarioRunning     = reportmodel.EventKindScenarioRunning
	EventKindScenarioFinished    = reportmodel.EventKindScenarioFinished
	EventKindActRunning          = reportmodel.EventKindActRunning
	EventKindActFinished         = reportmodel.EventKindActFinished
	EventKindActionRunning       = reportmodel.EventKindActionRunning
	EventKindActionFinished      = reportmodel.EventKindActionFinished
	EventKindExpectationFinished = reportmodel.EventKindExpectationFinished
	EventKindLogEmitted          = reportmodel.EventKindLogEmitted

	NodeKindScenario    NodeKind = reportmodel.NodeKindScenario
	NodeKindAct         NodeKind = reportmodel.NodeKindAct
	NodeKindAction      NodeKind = reportmodel.NodeKindAction
	NodeKindExpectation NodeKind = reportmodel.NodeKindExpectation
	NodeKindLog         NodeKind = reportmodel.NodeKindLog

	NodeDiagnosticKindHTTP      NodeDiagnosticKind = reportmodel.NodeDiagnosticKindHTTP
	NodeDiagnosticKindPreflight NodeDiagnosticKind = reportmodel.NodeDiagnosticKindPreflight

	HTTPDiagnosticFailureNetwork     HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureNetwork
	HTTPDiagnosticFailureTimeout     HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureTimeout
	HTTPDiagnosticFailureTLS         HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureTLS
	HTTPDiagnosticFailureStatus      HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureStatus
	HTTPDiagnosticFailureHeader      HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureHeader
	HTTPDiagnosticFailureBodyParse   HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureBodyParse
	HTTPDiagnosticFailureExpectation HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureExpectation
	HTTPDiagnosticFailureRequest     HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureRequest

	LogStatusEmitted LogStatus = reportmodel.LogStatusEmitted
	LogStatusOmitted LogStatus = reportmodel.LogStatusOmitted
	LogStatusError   LogStatus = reportmodel.LogStatusError

	SensitivityNone     Sensitivity = reportmodel.SensitivityNone
	SensitivityInternal Sensitivity = reportmodel.SensitivityInternal
	SensitivityPersonal Sensitivity = reportmodel.SensitivityPersonal
	SensitivitySecret   Sensitivity = reportmodel.SensitivitySecret

	CaptureOmit        Capture = reportmodel.CaptureOmit
	CaptureSummary     Capture = reportmodel.CaptureSummary
	CaptureArtifactRef Capture = reportmodel.CaptureArtifactRef

	TerminationReasonConverged        TerminationReason = reportmodel.TerminationReasonConverged
	TerminationReasonDeadlineExceeded TerminationReason = reportmodel.TerminationReasonDeadlineExceeded
	TerminationReasonTerminalFailure  TerminationReason = reportmodel.TerminationReasonTerminalFailure
	TerminationReasonParentCanceled   TerminationReason = reportmodel.TerminationReasonParentCanceled

	SkipReasonExplicit     SkipReason = reportmodel.SkipReasonExplicit
	SkipReasonStageAborted SkipReason = reportmodel.SkipReasonStageAborted
)

Public report schema version and enum values used by run documents.

View Source
const (
	SeverityError DiagnosticSeverity = specmodel.SeverityError
	SeverityHint  DiagnosticSeverity = specmodel.SeverityHint

	BindingKindLiteral  BindingKind = specmodel.BindingKindLiteral
	BindingKindRef      BindingKind = specmodel.BindingKindRef
	BindingKindObject   BindingKind = specmodel.BindingKindObject
	BindingKindList     BindingKind = specmodel.BindingKindList
	BindingKindString   BindingKind = specmodel.BindingKindString
	BindingKindGenerate BindingKind = specmodel.BindingKindGenerate
	BindingKindCoalesce BindingKind = specmodel.BindingKindCoalesce
	BindingKindEnv      BindingKind = specmodel.BindingKindEnv

	LogFormatText LogFormat = specmodel.LogFormatText
	LogFormatJSON LogFormat = specmodel.LogFormatJSON

	DecodeJSON          DecodeKind        = specmodel.DecodeJSON
	SubjectFromProperty SubjectSourceKind = specmodel.SubjectFromProperty

	TriggerPredicateSuccess TriggerPredicate = specmodel.TriggerPredicateSuccess
	TriggerPredicateFailure TriggerPredicate = specmodel.TriggerPredicateFailure
	TriggerPredicateDone    TriggerPredicate = specmodel.TriggerPredicateDone

	TransitionOnPass    TransitionOutcome = specmodel.TransitionOnPass
	TransitionOnFail    TransitionOutcome = specmodel.TransitionOnFail
	TransitionOnTimeout TransitionOutcome = specmodel.TransitionOnTimeout
	TransitionOnCancel  TransitionOutcome = specmodel.TransitionOnCancel

	HTTPSessionNone                 = specmodel.HTTPSessionNone
	HTTPAuthNone                    = specmodel.HTTPAuthNone
	HTTPAPIKeyInHeader HTTPAPIKeyIn = specmodel.HTTPAPIKeyInHeader
	HTTPAPIKeyInQuery  HTTPAPIKeyIn = specmodel.HTTPAPIKeyInQuery
)

Public enum values used by the authoring and diagnostic model.

Variables

This section is empty.

Functions

func ExportRunDocument

func ExportRunDocument(
	ctx context.Context,
	resolver ReportExporterResolver,
	document RunDocument,
	specs []ReportExportSpec,
) error

ExportRunDocument invokes the requested exporters against one frozen run document.

func IsMatcherMismatch

func IsMatcherMismatch(err error) bool

IsMatcherMismatch reports whether err represents an ordinary matcher mismatch.

func MismatchError

func MismatchError(err error) error

MismatchError wraps err so matcher wrappers such as expectation.not can distinguish ordinary non-match results from matcher-internal failures.

func ValidateTerminalOutcome

func ValidateTerminalOutcome(status Status, failure *Failure) error

ValidateTerminalOutcome checks that a terminal status/failure pair is internally consistent.

func Version added in v0.5.0

func Version() string

Version returns the Theater build version embedded in the current binary.

Types

type ActSpec

type ActSpec = specmodel.ActSpec

ActSpec defines one executable act inside a scenario.

type Action

type Action interface {
	Contract() ActionContract
	Run(ctx context.Context, request ActionRequest) (Outputs, error)
}

Action executes one act action and exposes the contract used for validation and observation.

type ActionCapabilityDescriptor

type ActionCapabilityDescriptor struct {
	Inputs  map[string]ValueContract
	Outputs map[string]ValueContract
}

ActionCapabilityDescriptor describes one action contract.

type ActionContract

type ActionContract = specmodel.ActionContract

ActionContract describes the declared inputs and outputs of an action.

type ActionErrorDetails

type ActionErrorDetails interface {
	error
	FailureSummary() string
	PartialOutputs() Outputs
}

ActionErrorDetails exposes failure details that can still preserve a summary and partial outputs for reporting.

type ActionObservations

type ActionObservations = reportmodel.ActionObservations

ActionObservations groups observed action inputs, outputs, and streams.

type ActionRegistrar

type ActionRegistrar interface {
	RegisterAction(ref string, action Action) error
}

ActionRegistrar registers actions by stable reference.

type ActionRequest

type ActionRequest struct {
	Args        Args
	HTTP        *HTTPSpec
	State       *statemodel.Manager
	HTTPCapture *HTTPAuthCaptureSpec
	Reporter    observe.Reporter
	Diagnostics DiagnosticRecorder
	Paths       PathContext
	Attempt     int
	Resources   ResourceScope
}

ActionRequest is the runtime request passed to Action.Run.

type ActionResolver

type ActionResolver interface {
	ResolveAction(ref string) (Action, error)
}

ActionResolver resolves actions by registered ref.

type ActionSpec

type ActionSpec = specmodel.ActionSpec

ActionSpec selects the action implementation and bound inputs for an act.

type ArgSpec

type ArgSpec = specmodel.ArgSpec

ArgSpec describes one inventory call-site argument.

type Args

type Args = specmodel.Args

Args is the runtime argument bag passed to actions and inventories.

type ArtifactRef

type ArtifactRef = reportmodel.ArtifactRef

ArtifactRef points to payload content stored outside the report document.

type AssertSpec

type AssertSpec = specmodel.AssertSpec

AssertSpec selects a matcher and its bound args.

type AttemptReport

type AttemptReport = reportmodel.AttemptReport

AttemptReport summarizes one eventually attempt.

type BindingKind

type BindingKind = specmodel.BindingKind

BindingKind identifies the wire form used by a binding.

type BindingSpec

type BindingSpec = specmodel.BindingSpec

BindingSpec describes a literal, ref, object, list, string, generator, coalesce, or environment binding.

type CapabilityDescriptor

CapabilityDescriptor describes one discoverable runtime capability together with the contract relevant to its family.

func DescribeCapabilities

func DescribeCapabilities(catalog *Catalog, matchers *MatcherCatalog) []CapabilityDescriptor

DescribeCapabilities returns the discoverable built-in runtime capabilities from the provided catalog and matcher catalog.

func DescribePluginCapabilities

func DescribePluginCapabilities(catalog *PluginCatalog) []CapabilityDescriptor

DescribePluginCapabilities returns the discoverable capability surface for a plugin overlay, including the base built-ins and plugin-provided additions.

type CapabilityFamily

type CapabilityFamily string

CapabilityFamily identifies one discoverable runtime capability family.

func CapabilityFamilies

func CapabilityFamilies() []CapabilityFamily

CapabilityFamilies returns the canonical family order used by discovery and CLI rendering.

type CapabilityProvider

type CapabilityProvider struct {
	Kind          CapabilityProviderKind
	PluginID      string
	PluginVersion string
}

CapabilityProvider describes whether a capability is built-in or comes from a loaded plugin overlay.

type CapabilityProviderKind

type CapabilityProviderKind string

CapabilityProviderKind identifies where one capability came from.

type Capture

type Capture = reportmodel.Capture

Capture defines how much of a value may appear in previews or artifact payloads.

type Catalog

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

Catalog stores runtime adapters and scenario-scope initializers used by the validator and runner.

func NewCatalog

func NewCatalog() *Catalog

NewCatalog creates an empty catalog ready for adapter registration.

func (*Catalog) RegisterAction

func (c *Catalog) RegisterAction(ref string, action Action) error

RegisterAction stores an action implementation under ref.

func (*Catalog) RegisterDecorator

func (c *Catalog) RegisterDecorator(ref string, decorator DecoratorDef) error

RegisterDecorator stores a decorator implementation under ref.

func (*Catalog) RegisterGenerator

func (c *Catalog) RegisterGenerator(ref string, generator GeneratorDef) error

RegisterGenerator stores a generator implementation under ref.

func (*Catalog) RegisterInventory

func (c *Catalog) RegisterInventory(ref string, inventory Inventory) error

RegisterInventory stores an inventory implementation under ref.

func (*Catalog) RegisterReportExporter

func (c *Catalog) RegisterReportExporter(ref string, exporter ReportExporterDef) error

RegisterReportExporter stores a report exporter implementation under ref.

func (*Catalog) RegisterScenarioScopeInitializer

func (c *Catalog) RegisterScenarioScopeInitializer(ref string, factory ScenarioScopeInitializerFactory) error

RegisterScenarioScopeInitializer registers a factory that prepares scenario-local resources for each run.

func (*Catalog) RegisterStateBackend

func (c *Catalog) RegisterStateBackend(ref string, backend StateBackendDef) error

RegisterStateBackend stores a persistent-state backend implementation under ref.

func (*Catalog) ResolveAction

func (c *Catalog) ResolveAction(ref string) (Action, error)

ResolveAction returns the action previously registered for ref.

func (*Catalog) ResolveDecorator

func (c *Catalog) ResolveDecorator(ref string) (DecoratorDef, error)

ResolveDecorator returns the decorator previously registered for ref.

func (*Catalog) ResolveGenerator

func (c *Catalog) ResolveGenerator(ref string) (GeneratorDef, error)

ResolveGenerator returns the generator previously registered for ref.

func (*Catalog) ResolveInventory

func (c *Catalog) ResolveInventory(ref string) (Inventory, error)

ResolveInventory returns the inventory previously registered for ref.

func (*Catalog) ResolveReportExporter

func (c *Catalog) ResolveReportExporter(ref string) (ReportExporterDef, error)

ResolveReportExporter returns the report exporter definition previously registered for ref.

func (*Catalog) ResolveStateBackend

func (c *Catalog) ResolveStateBackend(ref string) (StateBackendDef, error)

ResolveStateBackend returns the state backend definition previously registered for ref.

type CatalogResolver

CatalogResolver resolves the adapters and backend definitions required by validators and runners.

type Contrast

type Contrast = reportmodel.Contrast

Contrast describes expected-versus-actual mismatch details.

type DebugBoundaryKind

type DebugBoundaryKind = debugBoundaryKind

DebugBoundaryKind identifies one debuggable runtime-node family.

type DebugBoundaryPhase

type DebugBoundaryPhase = debugBoundaryPhase

DebugBoundaryPhase identifies whether the boundary is reached before or after node execution.

type DebugCheckpoint

type DebugCheckpoint struct {
	Name   string
	Values Values
}

DebugCheckpoint carries one action-authored mid-action debug snapshot.

type DebugCheckpointReporter

type DebugCheckpointReporter interface {
	DebugCheckpoint(DebugCheckpoint)
}

DebugCheckpointReporter is an optional action-facing reporter extension for cooperative mid-action checkpoints.

type DebugMode

type DebugMode string

DebugMode selects how a run should surface debug boundaries.

const (
	DebugModeOff         DebugMode = "off"
	DebugModeDump        DebugMode = "dump"
	DebugModeInteractive DebugMode = "interactive"
)

type DebugOptions

type DebugOptions struct {
	Mode        DebugMode
	StartPaused bool
	Breakpoints []string
	DumpPath    string
	Input       io.Reader
	Output      io.Writer
}

DebugOptions enables boundary-gated debugging on the standard run path.

type DebugPath

type DebugPath struct {
	Path       string             `json:"path"`
	Kind       DebugBoundaryKind  `json:"kind"`
	Phase      DebugBoundaryPhase `json:"phase"`
	RetryAware bool               `json:"retry_aware"`
}

DebugPath describes one debuggable runtime boundary that can be targeted by a breakpoint selector.

type DebugPathListing

type DebugPathListing struct {
	Diagnostics []Diagnostic
	Paths       []DebugPath
}

DebugPathListing returns either prepared debug paths or validation diagnostics for the supplied stage spec.

type DebugStateSnapshotter

type DebugStateSnapshotter interface {
	DebugStateSnapshot(context.Context) (Values, error)
}

DebugStateSnapshotter is an optional state-backend extension that can enrich pause-time state snapshots with backend-authored fields.

type DecodeKind

type DecodeKind = specmodel.DecodeKind

DecodeKind identifies an optional decode step before structural traversal.

type DecoratorContract

type DecoratorContract = specmodel.DecoratorContract

DecoratorContract describes the input, output, and configuration surface of a decorator.

type DecoratorDef

type DecoratorDef = specmodel.DecoratorDef

DecoratorDef registers a decorator contract and compile function.

type DecoratorFunc

type DecoratorFunc = specmodel.DecoratorFunc

DecoratorFunc transforms one value after decorator compilation.

type DecoratorRegistrar

type DecoratorRegistrar interface {
	RegisterDecorator(ref string, decorator DecoratorDef) error
}

DecoratorRegistrar registers decorators by stable reference.

type DecoratorResolver

type DecoratorResolver interface {
	ResolveDecorator(ref string) (DecoratorDef, error)
}

DecoratorResolver resolves decorators by registered ref.

type DecoratorSpec

type DecoratorSpec = specmodel.DecoratorSpec

DecoratorSpec selects a decorator and its static configuration.

type Diagnostic

type Diagnostic = reportmodel.Diagnostic

Diagnostic reports one compile or validate issue against a plan path.

type DiagnosticRecorder added in v0.4.0

type DiagnosticRecorder interface {
	RecordDiagnostic(NodeDiagnostic)
}

DiagnosticRecorder receives typed report-safe diagnostics from an action.

type DiagnosticSeverity

type DiagnosticSeverity = reportmodel.DiagnosticSeverity

DiagnosticSeverity classifies compile and validation diagnostics.

type Event

type Event = reportmodel.Event

Event is a low-level runtime event used to build reports and live mirrors.

type EventRecorder

type EventRecorder interface {
	Record(Event) error
}

EventRecorder receives emitted runtime events alongside final report projection.

type EventuallyReport

type EventuallyReport = reportmodel.EventuallyReport

EventuallyReport summarizes convergence behavior for an act with eventually.

type EventuallySpec

type EventuallySpec = specmodel.EventuallySpec

EventuallySpec configures whole-act convergence timing.

type ExpectationSpec

type ExpectationSpec = specmodel.ExpectationSpec

ExpectationSpec defines one assertion over a current-act value.

type ExportSpec

type ExportSpec = specmodel.ExportSpec

ExportSpec declares a named export. Act exports can select current action outputs with Field or available act-scope values with Ref. Scenario-call exports use Ref to select from the completed scenario scope.

type Failure

type Failure = reportmodel.Failure

Failure captures a user-facing failure summary and its optional underlying cause.

type FailureIndexEntry

type FailureIndexEntry = reportmodel.FailureIndexEntry

FailureIndexEntry points to one failed node inside Report.Failures.

type FailureKind

type FailureKind = reportmodel.FailureKind

FailureKind classifies the logical source of a failure.

type GenerationMetadata

type GenerationMetadata = reportmodel.GenerationMetadata

GenerationMetadata records the generator seed and base time captured for one run.

type GeneratorCapabilityDescriptor

type GeneratorCapabilityDescriptor struct {
	Args     []ArgSpec
	Produces ValueContract
}

GeneratorCapabilityDescriptor describes one generator contract.

type GeneratorContract

type GeneratorContract struct {
	Summary  string
	Args     []ArgSpec
	Produces ValueContract
}

GeneratorContract describes the declared args and produced value of a generator.

type GeneratorDef

type GeneratorDef struct {
	Contract GeneratorContract
	Validate func(args Values) error
	Generate func(request GeneratorRequest) (any, error)
}

GeneratorDef registers a generator contract together with its runtime logic.

type GeneratorRegistrar

type GeneratorRegistrar interface {
	RegisterGenerator(ref string, generator GeneratorDef) error
}

GeneratorRegistrar registers generators by stable name.

type GeneratorRequest

type GeneratorRequest struct {
	Args           Args
	Generation     GenerationMetadata
	BindingPath    string
	ScenarioCallID string
	ScenarioSeq    int
}

GeneratorRequest is the runtime request passed to a generator.

func (GeneratorRequest) DeriveRand

func (r GeneratorRequest) DeriveRand(purpose string) *randv2.Rand

DeriveRand returns a deterministic pseudo-random stream for this request and purpose.

func (GeneratorRequest) RunToken

func (r GeneratorRequest) RunToken(length int) string

RunToken returns a short deterministic token derived from the run seed.

func (GeneratorRequest) SequenceIndex

func (r GeneratorRequest) SequenceIndex() int64

SequenceIndex returns the stable per-scenario ordinal used by sequence-like generators.

type GeneratorResolver

type GeneratorResolver interface {
	ResolveGenerator(ref string) (GeneratorDef, error)
}

GeneratorResolver resolves generators by registered name.

type HTTPAPIKeyAuthSpec

type HTTPAPIKeyAuthSpec = specmodel.HTTPAPIKeyAuthSpec

HTTPAPIKeyAuthSpec attaches an API key to a header or query parameter.

type HTTPAPIKeyIn

type HTTPAPIKeyIn = specmodel.HTTPAPIKeyIn

HTTPAPIKeyIn identifies where an API key attachment is applied.

type HTTPAuthAttachmentSpec

type HTTPAuthAttachmentSpec = specmodel.HTTPAuthAttachmentSpec

HTTPAuthAttachmentSpec declares one typed request auth attachment.

type HTTPAuthBindingSpec added in v0.3.0

type HTTPAuthBindingSpec = specmodel.HTTPAuthBindingSpec

HTTPAuthBindingSpec initializes declared auth slots for one scenario execution from scenario-start bindings.

type HTTPAuthCaptureSpec

type HTTPAuthCaptureSpec = specmodel.HTTPAuthCaptureSpec

HTTPAuthCaptureSpec captures response material into named auth slots after a successful HTTP action.

type HTTPAuthSlotInitializer added in v0.3.0

type HTTPAuthSlotInitializer interface {
	InitializeHTTPAuthSlots(resources ResourceScope, bindings map[string]Values) error
}

HTTPAuthSlotInitializer receives scenario-start values for declared HTTP auth slots.

type HTTPAuthSpec

type HTTPAuthSpec = specmodel.HTTPAuthSpec

HTTPAuthSpec declares one reusable HTTP auth attachment set.

type HTTPBasicAuthSpec

type HTTPBasicAuthSpec = specmodel.HTTPBasicAuthSpec

HTTPBasicAuthSpec attaches HTTP Basic credentials.

type HTTPBearerAuthSpec

type HTTPBearerAuthSpec = specmodel.HTTPBearerAuthSpec

HTTPBearerAuthSpec attaches a bearer token to Authorization.

type HTTPCaptureSourceSpec

type HTTPCaptureSourceSpec = specmodel.HTTPCaptureSourceSpec

HTTPCaptureSourceSpec selects one response source for a captured auth slot.

type HTTPDiagnostic added in v0.4.0

type HTTPDiagnostic = reportmodel.HTTPDiagnostic

HTTPDiagnostic is the report-safe summary of one HTTP exchange.

type HTTPDiagnosticFailureKind added in v0.5.0

type HTTPDiagnosticFailureKind = reportmodel.HTTPDiagnosticFailureKind

HTTPDiagnosticFailureKind classifies the safe failure category for an HTTP diagnostic when the category is known.

type HTTPFormSlotAuthSpec

type HTTPFormSlotAuthSpec = specmodel.HTTPFormSlotAuthSpec

HTTPFormSlotAuthSpec attaches one captured auth slot to a form field.

type HTTPHeaderSlotAuthSpec

type HTTPHeaderSlotAuthSpec = specmodel.HTTPHeaderSlotAuthSpec

HTTPHeaderSlotAuthSpec attaches one captured auth slot to a request header.

type HTTPIdentitySpec

type HTTPIdentitySpec = specmodel.HTTPIdentitySpec

HTTPIdentitySpec bundles one optional session ref and one optional auth ref.

type HTTPQuerySlotAuthSpec

type HTTPQuerySlotAuthSpec = specmodel.HTTPQuerySlotAuthSpec

HTTPQuerySlotAuthSpec attaches one captured auth slot to a query parameter.

type HTTPRequestFingerprint added in v0.5.0

type HTTPRequestFingerprint = reportmodel.HTTPRequestFingerprint

HTTPRequestFingerprint is a report-safe identity for one attempted HTTP request. It records request shape, never query values or credentials.

type HTTPResponseMetadata added in v0.5.0

type HTTPResponseMetadata = reportmodel.HTTPResponseMetadata

HTTPResponseMetadata records report-safe response facts without exposing raw response bodies or non-allowlisted headers.

type HTTPSessionSpec

type HTTPSessionSpec = specmodel.HTTPSessionSpec

HTTPSessionSpec reserves a named managed cookie session.

type HTTPSpec

type HTTPSpec = specmodel.HTTPSpec

HTTPSpec declares shared stage-level HTTP sessions and auth configs.

type Inventory

type Inventory interface {
	Contract() InventoryContract
	Acquire(ctx context.Context, req InventoryRequest) (any, error)
}

Inventory resolves a value for property evaluation from explicit call-site args and runtime context.

type InventoryCall

type InventoryCall = specmodel.InventoryCall

InventoryCall configures one inventory use+with call-site.

type InventoryCapabilityDescriptor

type InventoryCapabilityDescriptor struct {
	Args     []ArgSpec
	Produces ValueContract
}

InventoryCapabilityDescriptor describes one inventory contract.

type InventoryContract

type InventoryContract = specmodel.InventoryContract

InventoryContract describes inventory args and the value contract it produces.

type InventoryRegistrar

type InventoryRegistrar interface {
	RegisterInventory(ref string, inventory Inventory) error
}

InventoryRegistrar registers inventories by stable reference.

type InventoryRequest

type InventoryRequest struct {
	Args      Args                `json:"args,omitempty"`
	HTTP      *HTTPSpec           `json:"http,omitempty"`
	State     *statemodel.Manager `json:"-"`
	Paths     PathContext         `json:"paths,omitempty"`
	Attempt   int                 `json:"attempt,omitempty"`
	Resources ResourceScope       `json:"-"`
}

InventoryRequest is the runtime request passed to an inventory acquisition.

type InventoryResolver

type InventoryResolver interface {
	ResolveInventory(ref string) (Inventory, error)
}

InventoryResolver resolves inventories by registered ref.

type JSONPointer

type JSONPointer = specmodel.JSONPointer

JSONPointer is an RFC 6901 pointer used for structural traversal after a ref or field root is selected.

func ParseJSONPointer

func ParseJSONPointer(raw string) (JSONPointer, error)

ParseJSONPointer validates raw and returns it as a JSONPointer.

type LogFormat

type LogFormat = specmodel.LogFormat

LogFormat identifies the preferred rendering format for one scenario-authored log record.

type LogRecord

type LogRecord = reportmodel.LogRecord

LogRecord is one scenario-authored log materialized in the run report.

type LogSpec

type LogSpec = specmodel.LogSpec

LogSpec declares one act-local scenario-authored log record.

type LogStatus

type LogStatus = reportmodel.LogStatus

LogStatus identifies how one scenario-authored log record was handled.

type LogSummary

type LogSummary = reportmodel.LogSummary

LogSummary reports the effective scenario-authored log limits and accounting.

type LogValueSpec

type LogValueSpec = specmodel.LogValueSpec

LogValueSpec selects or builds a report-only value for a scenario-authored log record.

type Matcher

type Matcher = specmodel.Matcher

Matcher checks one actual runtime value.

Ordinary non-match results may be classified separately from matcher-internal failures so wrapper matchers can invert only logical mismatches.

type MatcherArg

type MatcherArg = specmodel.MatcherArg

MatcherArg describes one named matcher argument.

type MatcherCapabilityDescriptor

type MatcherCapabilityDescriptor struct {
	Args   []MatcherArg
	Actual ValueContract
	Sugar  SugarSpec
}

MatcherCapabilityDescriptor describes one matcher contract.

type MatcherCatalog

type MatcherCatalog = specmodel.MatcherCatalog

MatcherCatalog stores matchers indexed by ref and YAML sugar key.

func NewMatcherCatalog

func NewMatcherCatalog(descriptors ...MatcherDescriptor) (*MatcherCatalog, error)

NewMatcherCatalog validates and indexes matcher descriptors.

type MatcherCompileContext

type MatcherCompileContext = specmodel.MatcherCompileContext

MatcherCompileContext lets matchers recursively compile nested canonical matcher specs when they own structured matcher-local payloads.

type MatcherDescriptor

type MatcherDescriptor = specmodel.MatcherDescriptor

MatcherDescriptor describes a registered matcher contract and compile hook.

type MatcherMismatch

type MatcherMismatch interface {
	TheaterMismatch() bool
}

MatcherMismatch marks an error as an ordinary matcher mismatch rather than a matcher-internal or terminal failure.

type MatcherPreflightArgIssue added in v0.5.0

type MatcherPreflightArgIssue = specmodel.MatcherPreflightArgIssue

MatcherPreflightArgIssue describes one descriptor-owned preflight arg validation failure.

type MatcherPreflightArgRule added in v0.5.0

type MatcherPreflightArgRule = specmodel.MatcherPreflightArgRule

MatcherPreflightArgRule declares preflight-only validation for one static matcher argument.

type MatcherPreflightPolicy added in v0.5.0

type MatcherPreflightPolicy = specmodel.MatcherPreflightPolicy

MatcherPreflightPolicy declares matcher-specific constraints for scenario preflight use. A nil policy means the matcher is not safe for preflight.

type MatcherResolver

type MatcherResolver interface {
	Resolve(ref string) (MatcherDescriptor, error)
}

MatcherResolver resolves matcher descriptors by registered ref.

type MatcherSugarResolver

type MatcherSugarResolver interface {
	ResolveSugarKey(key string) (MatcherDescriptor, error)
}

MatcherSugarResolver resolves matcher descriptors by YAML sugar key.

type NodeAddress

type NodeAddress = reportmodel.NodeAddress

NodeAddress identifies a logical runtime node within a scenario call.

type NodeDiagnostic added in v0.4.0

type NodeDiagnostic = reportmodel.NodeDiagnostic

NodeDiagnostic is one typed report-safe diagnostic attached to a report node.

type NodeDiagnosticKind added in v0.4.0

type NodeDiagnosticKind = reportmodel.NodeDiagnosticKind

NodeDiagnosticKind identifies the typed diagnostic attached to a report node.

type NodeKind

type NodeKind = reportmodel.NodeKind

NodeKind identifies the logical node represented in final reports.

type NodeReport

type NodeReport = reportmodel.NodeReport

NodeReport is the final terminal snapshot of one logical node.

type ObservedStream

type ObservedStream = reportmodel.ObservedStream

ObservedStream stores the report-safe observation of one streamed output.

type ObservedValue

type ObservedValue = reportmodel.ObservedValue

ObservedValue stores the report-safe observation of one action input or output.

type Outputs

type Outputs = specmodel.Outputs

Outputs is the named output bag produced by an action.

type ParamSpec

type ParamSpec = specmodel.ParamSpec

ParamSpec describes one decorator configuration parameter.

type PathContext

type PathContext = specmodel.PathContext

PathContext carries runtime paths that help adapters attribute work to the current stage, scenario, act, and property.

type PayloadMetadata

type PayloadMetadata = reportmodel.PayloadMetadata

PayloadMetadata describes how captured payload data was handled.

type Phase

type Phase = reportmodel.Phase

Phase identifies the compile, validate, or run phase.

type PickStepSpec

type PickStepSpec = specmodel.PickStepSpec

PickStepSpec selects exactly one list item by a compact at/equals predicate or by bounded relative where clauses.

type PickWhereClauseSpec

type PickWhereClauseSpec = specmodel.PickWhereClauseSpec

PickWhereClauseSpec describes one relative matcher clause inside a compound pick selector.

type PluginCatalog

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

PluginCatalog overlays runtime-loaded plugin capabilities on top of a base catalog.

func LoadPluginCatalog

func LoadPluginCatalog(base *Catalog, matchers *MatcherCatalog, configPath, lockPath string) (*PluginCatalog, error)

LoadPluginCatalog loads a plugin registry from files and overlays it on top of base.

func LoadPluginDescriptorCatalog

func LoadPluginDescriptorCatalog(base *Catalog, matchers *MatcherCatalog, configPath, lockPath string) (*PluginCatalog, error)

LoadPluginDescriptorCatalog loads plugin descriptors for static analysis without resolving or hashing plugin executables.

The returned catalog is intended for validation, completion, hover and other descriptor-only tooling. Runtime execution must use LoadPluginCatalog so the executable path and lock entry are checked before a plugin process can start. Validator calls against this catalog skip plugin validate hooks because no plugin subprocess is launched.

func NewPluginCatalog

func NewPluginCatalog(base *Catalog, matchers *MatcherCatalog, options PluginCatalogOptions) (*PluginCatalog, error)

NewPluginCatalog overlays a programmatically provided plugin registry on top of base.

Example
package main

import (
	"fmt"
	"path/filepath"

	"github.com/alex-poliushkin/theater"
	"github.com/alex-poliushkin/theater/builtin"

	builtinaction "github.com/alex-poliushkin/theater/builtin/action"

	builtinexpectation "github.com/alex-poliushkin/theater/builtin/expectation"

	pluginregistry "github.com/alex-poliushkin/theater/plugin/registry"
)

func main() {
	bundle, err := builtin.NewBundle()
	if err != nil {
		panic(err)
	}

	plugins, err := theater.NewPluginCatalog(bundle.Catalog, bundle.Matchers, theater.PluginCatalogOptions{
		RootDir: ".",
		Config: pluginregistry.ConfigFile{
			Schema: pluginregistry.ConfigSchemaVersion,
			Plugins: map[string]pluginregistry.PluginEntry{
				"smoke-plugin": {
					Manifest: filepath.Join("testdata", "plugins", "smoke", "manifest.json"),
					Exec: pluginregistry.ExecSpec{
						Command: []string{filepath.Join("testdata", "plugins", "smoke", "smoke.py")},
					},
					AllowCapabilities: []string{
						"action.smoke.echo",
						"matcher.smoke.equal",
					},
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	_, actionErr := plugins.ResolveAction("action.smoke.echo")
	_, matcherErr := plugins.Resolve("matcher.smoke.equal")
	_, baseActionErr := plugins.ResolveAction(builtinaction.GenerateRef)
	_, baseMatcherErr := plugins.Resolve(builtinexpectation.EqualRef)
	fmt.Println(actionErr == nil)
	fmt.Println(matcherErr == nil)
	fmt.Println(baseActionErr == nil)
	fmt.Println(baseMatcherErr == nil)

}
Output:
true
true
true
true

func (*PluginCatalog) Resolve

func (c *PluginCatalog) Resolve(ref string) (MatcherDescriptor, error)

func (*PluginCatalog) ResolveAction

func (c *PluginCatalog) ResolveAction(ref string) (Action, error)

func (*PluginCatalog) ResolveDecorator

func (c *PluginCatalog) ResolveDecorator(ref string) (DecoratorDef, error)

func (*PluginCatalog) ResolveGenerator

func (c *PluginCatalog) ResolveGenerator(ref string) (GeneratorDef, error)

func (*PluginCatalog) ResolveInventory

func (c *PluginCatalog) ResolveInventory(ref string) (Inventory, error)

func (*PluginCatalog) ResolveReportExporter

func (c *PluginCatalog) ResolveReportExporter(ref string) (ReportExporterDef, error)

func (*PluginCatalog) ResolveStateBackend

func (c *PluginCatalog) ResolveStateBackend(ref string) (StateBackendDef, error)

func (*PluginCatalog) ResolveSugarKey

func (c *PluginCatalog) ResolveSugarKey(key string) (MatcherDescriptor, error)

type PluginCatalogOptions

type PluginCatalogOptions struct {
	RootDir     string
	Config      pluginregistry.ConfigFile
	Lock        pluginregistry.LockFile
	RequireLock bool
}

PluginCatalogOptions configures programmatic plugin overlay construction.

type PreflightDiagnostic added in v0.5.0

type PreflightDiagnostic = reportmodel.PreflightDiagnostic

PreflightDiagnostic is the report-safe summary of one scenario preflight guard result that affected execution.

type PreflightSpec added in v0.5.0

type PreflightSpec = specmodel.PreflightSpec

PreflightSpec defines one scenario-level guard evaluated before scenario side effects begin.

type Preview

type Preview = reportmodel.Preview

Preview is a report-safe preview of a captured value or payload.

type ProjectedPayload

type ProjectedPayload struct {
	Preview  string
	Metadata PayloadMetadata
}

ProjectedPayload is a sanitized preview plus normalized payload metadata.

func SafeProjectText

func SafeProjectText(raw string, metadata PayloadMetadata, limit int) ProjectedPayload

SafeProjectText projects raw text into a report-safe preview using the given payload metadata and preview limit.

type Projector

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

Projector materializes final reports and run documents from runtime events.

func NewProjector

func NewProjector() *Projector

NewProjector constructs a Projector with the default report projection behavior.

func (*Projector) Document

func (p *Projector) Document(events []Event) (RunDocument, error)

Document materializes a RunDocument from runtime events.

func (*Projector) Project

func (p *Projector) Project(events []Event) (Report, error)

Project materializes a final Report from runtime events.

type PropertySpec

type PropertySpec = specmodel.PropertySpec

PropertySpec describes an act property resolved through either a value binding or an inventory call, then an optional decorator chain.

type RefSpec

type RefSpec = specmodel.RefSpec

RefSpec names a root value and optional decode/path traversal.

type RegexpStepSpec

type RegexpStepSpec = specmodel.RegexpStepSpec

RegexpStepSpec extracts a regexp match or capture group from text input.

type RelativeSubjectSpec

type RelativeSubjectSpec = specmodel.RelativeSubjectSpec

RelativeSubjectSpec selects a single value relative to a collection item.

type Report

type Report = reportmodel.Report

Report is the final materialized report for one stage run.

type ReportExportSpec

type ReportExportSpec struct {
	Ref  string `json:"ref"`
	With Values `json:"with,omitempty"`
}

ReportExportSpec identifies one report exporter invocation after a run.

type ReportExporterCapabilityDescriptor

type ReportExporterCapabilityDescriptor struct {
	Params []ParamSpec
}

ReportExporterCapabilityDescriptor describes one report exporter contract.

type ReportExporterDef

type ReportExporterDef struct {
	Params []ParamSpec
	Export func(ctx context.Context, config Values, document RunDocument) error
}

ReportExporterDef describes a host-owned report export capability.

type ReportExporterRegistrar

type ReportExporterRegistrar interface {
	RegisterReportExporter(ref string, exporter ReportExporterDef) error
}

ReportExporterRegistrar registers report exporters by stable ref.

type ReportExporterResolver

type ReportExporterResolver interface {
	ResolveReportExporter(ref string) (ReportExporterDef, error)
}

ReportExporterResolver resolves report exporters by registered ref.

type ResourceKey

type ResourceKey struct {
	Namespace string
	Name      string
}

ResourceKey identifies one scenario-scoped runtime resource.

func NewResourceKey

func NewResourceKey(namespace, name string) ResourceKey

NewResourceKey constructs a typed resource key from namespace and name.

type ResourceScope

type ResourceScope interface {
	GetOrCreate(key ResourceKey, create func() any) any
}

ResourceScope stores scenario-scoped reusable services keyed by ResourceKey.

func NewResourceScope

func NewResourceScope() ResourceScope

NewResourceScope creates an empty scenario-local resource scope.

type RunDocument

type RunDocument = reportmodel.RunDocument

RunDocument is the serializable top-level artifact for one stage run.

type RunOptions

type RunOptions struct {
	// RunID overrides the emitted run document identifier. When empty, Runner
	// generates an opaque identifier for the materialized document.
	RunID string

	Live            observe.Sink
	Events          EventRecorder
	ReportExporters []ReportExportSpec
	Debug           *DebugOptions
}

RunOptions configures run identity, live observation, and optional raw event recording. RunID is emitted as a document label for recorders and exporters; it is not proof of provenance.

Example
package main

import (
	"context"
	"fmt"
	"sync"

	"github.com/alex-poliushkin/theater"
	"github.com/alex-poliushkin/theater/builtin"

	builtinexpectation "github.com/alex-poliushkin/theater/builtin/expectation"
	"github.com/alex-poliushkin/theater/observe"
)

const (
	embeddingActionPath      = "stage.embedding/call.smoke/act.generate/action"
	embeddingExpectationPath = "stage.embedding/call.smoke/act.generate/expectation.message"
)

func main() {
	bundle, err := builtin.NewBundle()
	if err != nil {
		panic(err)
	}

	recorder := &embeddingEventRecorder{}
	live := &embeddingLiveSink{}
	result, err := theater.NewRunner(bundle.Catalog, bundle.Matchers).Run(
		context.Background(),
		embeddingStageSpec(),
		theater.RunOptions{
			Events: recorder,
			Live:   live,
		},
	)
	if err != nil {
		panic(err)
	}

	document, err := theater.NewProjector().Document(recorder.Events())
	if err != nil {
		panic(err)
	}

	events := recorder.Events()
	fmt.Println("result:", result.Report.Status)
	fmt.Println("action event:", embeddingHasEvent(events, theater.EventKindActionFinished, embeddingActionPath))
	fmt.Println("expectation event:", embeddingHasEvent(events, theater.EventKindExpectationFinished, embeddingExpectationPath))
	fmt.Println("live action:", live.HasTransition(theater.EventKindActionFinished, embeddingActionPath))
	fmt.Println("projected:", document.Report.Status)

}

type embeddingEventRecorder struct {
	mu     sync.Mutex
	events []theater.Event
}

type embeddingLiveSink struct {
	mu        sync.Mutex
	envelopes []observe.Envelope
}

func (r *embeddingEventRecorder) Record(event theater.Event) error {
	if err := event.Validate(); err != nil {
		return err
	}

	r.mu.Lock()
	defer r.mu.Unlock()
	r.events = append(r.events, event)
	return nil
}

func (r *embeddingEventRecorder) Events() []theater.Event {
	r.mu.Lock()
	defer r.mu.Unlock()

	events := make([]theater.Event, len(r.events))
	copy(events, r.events)
	return events
}

func (s *embeddingLiveSink) Publish(envelope observe.Envelope) uint64 {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.envelopes = append(s.envelopes, envelope)
	return uint64(len(s.envelopes))
}

func (s *embeddingLiveSink) HasTransition(kind, path string) bool {
	s.mu.Lock()
	defer s.mu.Unlock()

	for _, envelope := range s.envelopes {
		if envelope.Transition != nil &&
			envelope.Transition.EventKind == kind &&
			envelope.Node.Path == path &&
			envelope.DurableMirror {
			return true
		}
	}

	return false
}

func embeddingHasEvent(events []theater.Event, kind, path string) bool {
	for _, event := range events {
		if event.Kind == kind && event.Path == path {
			return true
		}
	}

	return false
}

func embeddingStageSpec() theater.StageSpec {
	return theater.StageSpec{
		ID: "embedding",
		Scenarios: []theater.ScenarioSpec{
			{
				ID: "smoke",
				Acts: []theater.ActSpec{
					{
						ID: "generate",
						Action: theater.ActionSpec{
							Use: "action.generate",
							With: map[string]theater.BindingSpec{
								"outputs": embeddingLiteral(map[string]any{"message": "hello"}),
							},
						},
						Expectations: []theater.ExpectationSpec{
							{
								ID:      "message",
								Subject: theater.SubjectSpec{Field: "values"},
								Assert: theater.AssertSpec{
									Ref: builtinexpectation.EqualRef,
									Args: map[string]theater.BindingSpec{
										"expected": embeddingLiteral(map[string]any{"message": "hello"}),
									},
								},
							},
						},
					},
				},
			},
		},
		ScenarioCalls: []theater.ScenarioCallSpec{
			{ID: "smoke", ScenarioID: "smoke"},
		},
	}
}

func embeddingLiteral(value any) theater.BindingSpec {
	return theater.BindingSpec{
		Kind:  theater.BindingKindLiteral,
		Value: value,
	}
}
Output:
result: passed
action event: true
expectation event: true
live action: true
projected: passed

type RunResult

type RunResult struct {
	RunID          string       `json:"run_id,omitempty"`
	TheaterVersion string       `json:"theater_version,omitempty"`
	Diagnostics    []Diagnostic `json:"diagnostics,omitempty"`
	Report         Report       `json:"report"`
}

RunResult is the public result returned by Runner.Run.

func (RunResult) Document

func (r RunResult) Document() RunDocument

Document returns the canonical run document form of r.

func (RunResult) MarshalJSON

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

MarshalJSON marshals r as its canonical RunDocument form.

type Runner

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

Runner compiles, validates, prepares, and executes stage specs.

func NewRunner

func NewRunner(catalog CatalogResolver, matchers MatcherResolver) *Runner

NewRunner constructs a Runner from a catalog resolver and matcher resolver.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, spec StageSpec, options RunOptions) (result RunResult, err error)

Run executes spec and returns either validation diagnostics or a final report.

type ScenarioCallSpec

type ScenarioCallSpec = specmodel.ScenarioCallSpec

ScenarioCallSpec invokes a scenario within a stage.

type ScenarioDependencySpec

type ScenarioDependencySpec = specmodel.ScenarioDependencySpec

ScenarioDependencySpec gates one scenario call on another.

type ScenarioScopeInitializer

type ScenarioScopeInitializer interface {
	InitializeScenarioScope(resources ResourceScope)
	Close()
}

ScenarioScopeInitializer populates and tears down scenario-local runtime resources.

type ScenarioScopeInitializerFactory

type ScenarioScopeInitializerFactory func() ScenarioScopeInitializer

ScenarioScopeInitializerFactory builds one initializer for a run.

type ScenarioScopeInitializerRegistrar

type ScenarioScopeInitializerRegistrar interface {
	RegisterScenarioScopeInitializer(ref string, factory ScenarioScopeInitializerFactory) error
}

ScenarioScopeInitializerRegistrar registers scenario-scope initializer factories.

type ScenarioSpec

type ScenarioSpec = specmodel.ScenarioSpec

ScenarioSpec defines a reusable scenario with inputs and ordered acts.

type Secret

type Secret = secretvalue.Value

Secret wraps a sensitive runtime value so reporting code can redact it.

func NewSecret

func NewSecret(value any) Secret

NewSecret marks value as sensitive for runtime transport and reporting.

type Sensitivity

type Sensitivity = reportmodel.Sensitivity

Sensitivity classifies how a value should be treated in diagnostics and report payloads.

type SkipReason

type SkipReason = reportmodel.SkipReason

SkipReason explains why a node or scenario finished as skipped.

type SourceRef

type SourceRef = reportmodel.SourceRef

SourceRef points to a source location in an authoring file when known.

type StageSpec

type StageSpec = specmodel.StageSpec

StageSpec is the top-level public stage definition.

type StateBackend

type StateBackend = statemodel.Backend

type StateBackendCapabilityDescriptor

type StateBackendCapabilityDescriptor struct {
	Descriptor StateDescriptor
	Params     []ParamSpec
}

StateBackendCapabilityDescriptor describes one persistent-state backend contract.

type StateBackendDef

type StateBackendDef struct {
	Params   []ParamSpec
	Describe func(config Values) (StateDescriptor, error)
	Open     func(config Values) (StateBackend, error)
}

type StateBackendRegistrar

type StateBackendRegistrar interface {
	RegisterStateBackend(ref string, backend StateBackendDef) error
}

type StateBackendResolver

type StateBackendResolver interface {
	ResolveStateBackend(ref string) (StateBackendDef, error)
}

type StateBackendSpec

type StateBackendSpec = specmodel.StateBackendSpec

StateBackendSpec declares one configured persistent state backend.

type StateClaimHandle

type StateClaimHandle = statemodel.ClaimHandle

type StateClaimResult

type StateClaimResult = statemodel.ClaimResult

type StateDescriptor

type StateDescriptor = statemodel.Descriptor

type StateExpiryPolicy

type StateExpiryPolicy = statemodel.ExpiryPolicy

type StateGuaranteeTier

type StateGuaranteeTier = statemodel.GuaranteeTier

type StateLeaseSpec

type StateLeaseSpec = statemodel.LeaseSpec

type StateManager

type StateManager = statemodel.Manager

type StatePoolHandle

type StatePoolHandle = statemodel.PoolHandle

type StateRecordHandle

type StateRecordHandle = statemodel.RecordHandle

type StateRecordSnapshot

type StateRecordSnapshot = statemodel.RecordSnapshot

type StateSelector

type StateSelector = statemodel.Selector

type StateSpec

type StateSpec = specmodel.StateSpec

StateSpec declares shared stage-level persistent state backends.

type Status

type Status = reportmodel.Status

Status describes the lifecycle state of a runtime node or stage.

type SubjectSourceKind

type SubjectSourceKind = specmodel.SubjectSourceKind

SubjectSourceKind identifies which current-act value family an expectation subject reads from.

type SubjectSpec

type SubjectSpec = specmodel.SubjectSpec

SubjectSpec selects either a current action output or a current-act property value before matcher evaluation.

type SugarForm

type SugarForm = specmodel.SugarForm

SugarForm identifies how YAML matcher sugar lowers into canonical assert args.

const (
	SugarFormNone       SugarForm = specmodel.SugarFormNone
	SugarFormUnary      SugarForm = specmodel.SugarFormUnary
	SugarFormFixedTuple SugarForm = specmodel.SugarFormFixedTuple
)

Supported YAML sugar forms for matcher lowering.

type SugarSpec

type SugarSpec = specmodel.SugarSpec

SugarSpec describes the shorthand keys and positional arg mapping supported by a matcher.

type Summary

type Summary = reportmodel.Summary

Summary counts terminal scenario outcomes for a run.

type TerminationReason

type TerminationReason = reportmodel.TerminationReason

TerminationReason explains why an eventually block stopped retrying.

type ThroughStepSpec

type ThroughStepSpec = specmodel.ThroughStepSpec

ThroughStepSpec declares one selector through step. Exactly one of Path, Pick, Regexp, or Transform should be set.

type TransformCapabilityDescriptor

type TransformCapabilityDescriptor struct {
	Accepts  ValueContract
	Params   []ParamSpec
	Produces ValueContract
}

TransformCapabilityDescriptor describes one value transform contract.

type TransitionOutcome

type TransitionOutcome = specmodel.TransitionOutcome

TransitionOutcome identifies which act outcome triggers a transition.

type TransitionSpec

type TransitionSpec = specmodel.TransitionSpec

TransitionSpec links an act outcome to the next act id.

type TriggerPredicate

type TriggerPredicate = specmodel.TriggerPredicate

TriggerPredicate identifies when a dependency is considered satisfied.

type Validator

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

Validator compiles, validates, and prepares stage specs without running them.

func NewValidator

func NewValidator(catalog CatalogResolver, matchers MatcherResolver) *Validator

NewValidator constructs a Validator from a catalog resolver and matcher resolver.

func (*Validator) ListDebugPaths

func (v *Validator) ListDebugPaths(spec StageSpec) (DebugPathListing, error)

ListDebugPaths compiles, validates, and prepares a stage spec, then returns the debuggable runtime paths available for breakpoint discovery.

Example
package main

import (
	"fmt"

	"github.com/alex-poliushkin/theater"
	"github.com/alex-poliushkin/theater/builtin"

	builtinexpectation "github.com/alex-poliushkin/theater/builtin/expectation"
)

func main() {
	bundle, err := builtin.NewBundle()
	if err != nil {
		panic(err)
	}

	listing, err := theater.NewValidator(bundle.Catalog, bundle.Matchers).ListDebugPaths(embeddingStageSpec())
	if err != nil {
		panic(err)
	}

	fmt.Println("diagnostics:", len(listing.Diagnostics))
	for _, path := range listing.Paths {
		if path.Kind == theater.DebugBoundaryKindAction && path.Phase == theater.DebugBoundaryPhaseBefore {
			fmt.Println("action:", path.Path)
			break
		}
	}

}

func embeddingStageSpec() theater.StageSpec {
	return theater.StageSpec{
		ID: "embedding",
		Scenarios: []theater.ScenarioSpec{
			{
				ID: "smoke",
				Acts: []theater.ActSpec{
					{
						ID: "generate",
						Action: theater.ActionSpec{
							Use: "action.generate",
							With: map[string]theater.BindingSpec{
								"outputs": embeddingLiteral(map[string]any{"message": "hello"}),
							},
						},
						Expectations: []theater.ExpectationSpec{
							{
								ID:      "message",
								Subject: theater.SubjectSpec{Field: "values"},
								Assert: theater.AssertSpec{
									Ref: builtinexpectation.EqualRef,
									Args: map[string]theater.BindingSpec{
										"expected": embeddingLiteral(map[string]any{"message": "hello"}),
									},
								},
							},
						},
					},
				},
			},
		},
		ScenarioCalls: []theater.ScenarioCallSpec{
			{ID: "smoke", ScenarioID: "smoke"},
		},
	}
}

func embeddingLiteral(value any) theater.BindingSpec {
	return theater.BindingSpec{
		Kind:  theater.BindingKindLiteral,
		Value: value,
	}
}
Output:
diagnostics: 0
action: stage.embedding/call.smoke/act.generate/action

func (*Validator) Validate

func (v *Validator) Validate(spec StageSpec) []Diagnostic

Validate compiles spec and returns structural or contract diagnostics. A nil receiver is invalid; construct validators with NewValidator.

type ValueContract

type ValueContract = specmodel.ValueContract

ValueContract describes accepted or produced runtime values, including optional structure and diagnostic visibility policy.

type ValueKind

type ValueKind = specmodel.ValueKind

ValueKind identifies the canonical runtime shape of a value.

Supported canonical runtime value kinds.

type ValueKindSet

type ValueKindSet = specmodel.ValueKindSet

ValueKindSet is a set of allowed runtime value kinds.

func NewValueKindSet

func NewValueKindSet(kinds ...ValueKind) ValueKindSet

NewValueKindSet builds a set containing the provided kinds.

type Values

type Values = specmodel.Values

Values is a generic named value bag used by decorators and matchers.

Directories

Path Synopsis
Package builtin bundles the shipped Theater built-ins for common host setups.
Package builtin bundles the shipped Theater built-ins for common host setups.
action
Package action registers the built-in theater actions.
Package action registers the built-in theater actions.
decorator
Package decorator registers the built-in theater decorators.
Package decorator registers the built-in theater decorators.
expectation
Package expectation exposes the built-in theater matcher descriptors.
Package expectation exposes the built-in theater matcher descriptors.
generator
Package generator exposes the built-in Theater generators together with the Register helper that installs them into a generator registrar.
Package generator exposes the built-in Theater generators together with the Register helper that installs them into a generator registrar.
internal/builtinhttp
Package builtinhttp provides private shared HTTP builtin semantics for built-in packages.
Package builtinhttp provides private shared HTTP builtin semantics for built-in packages.
inventory
Package inventory registers the built-in theater inventories.
Package inventory registers the built-in theater inventories.
statebackend
Package statebackend exposes the built-in Theater persistent-state backends together with the Register helper that installs them into a state-backend registrar.
Package statebackend exposes the built-in Theater persistent-state backends together with the Register helper that installs them into a state-backend registrar.
cmd
theater command
thtr-lsp command
docs
internal
authoring/thtr
Package thtr owns the `.thtr` authoring front-end implementation.
Package thtr owns the `.thtr` authoring front-end implementation.
docscheck
Package docscheck verifies repository documentation examples.
Package docscheck verifies repository documentation examples.
Package junit exports theater run documents as JUnit XML.
Package junit exports theater run documents as JUnit XML.
Package observe defines the live execution envelopes and sink interfaces used for streaming runtime progress outside the final stage report.
Package observe defines the live execution envelopes and sink interfaces used for streaming runtime progress outside the final stage report.
plugin
manifest
Package manifest owns the public Theater plugin manifest contract.
Package manifest owns the public Theater plugin manifest contract.
protocol
Package protocol owns the public Theater plugin transport envelopes and method payloads.
Package protocol owns the public Theater plugin transport envelopes and method payloads.
registry
Package registry owns the host-side Theater plugin registry config and lock file model.
Package registry owns the host-side Theater plugin registry config and lock file model.
sdk
Package sdk provides manifest and server helpers for implementing native Theater plugins in Go.
Package sdk provides manifest and server helpers for implementing native Theater plugins in Go.
Package report owns the canonical run-document and final-report data model.
Package report owns the canonical run-document and final-report data model.
Package spec owns the canonical authoring, contract, matcher, and reference data model used by theater stages.
Package spec owns the canonical authoring, contract, matcher, and reference data model used by theater stages.
Package state owns the canonical persistent-state data model and backend interface used by theater stages.
Package state owns the canonical persistent-state data model and backend interface used by theater stages.
Package thtr exposes public `.thtr` loading and editor-tooling APIs.
Package thtr exposes public `.thtr` loading and editor-tooling APIs.
Package yaml decodes YAML authoring files into the canonical theater.StageSpec model.
Package yaml decodes YAML authoring files into the canonical theater.StageSpec model.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL