models

package
v0.38.4 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ResponderOutcomeStopped      = "stopped"
	ResponderOutcomeAbstained    = "abstained"
	ResponderOutcomeCapExhausted = "cap_exhausted"
	ResponderOutcomeError        = "error"
)

Responder outcome values recorded on RunResult.Responder.Outcome.

View Source
const (
	// UsageProviderCustom indicates request counters came from a BYOK/custom provider.
	UsageProviderCustom = "custom"

	// UsageProviderMixed indicates aggregate usage spans different provider routes.
	UsageProviderMixed = "mixed"
)
View Source
const (
	// CurrentSchemaVersion is the current MAJOR.MINOR schema version for public artifacts.
	//
	// 1.0 — initial public schema (PR #382 / issue #368).
	// 1.1 — additive: per-turn checkpoints (TestCase.Checkpoints / RunResult.Checkpoints, #358)
	//       and RunResult.tool_events[] for per-task tool metrics (#366). Purely additive
	//       over 1.0, so 1.0 artifacts continue to load without migration.
	// 1.2 — additive: RunResult.snapshot_path pointer to a self-contained
	//       snapshot.json artifact (#367), and EvalSpec.adversarial block
	//       declaring fault-injection packs to run (#365). Both fields are
	//       optional, so 1.0 and 1.1 artifacts continue to load without
	//       migration.
	CurrentSchemaVersion = "1.2"
)

Variables

This section is empty.

Functions

func AllGraderKinds

func AllGraderKinds() []string

func ComputeStdDev

func ComputeStdDev(values []float64) float64

ComputeStdDev returns the population standard deviation for a slice of float64 values.

func ProbeEvaluationOutcomeSchemaVersion added in v0.38.0

func ProbeEvaluationOutcomeSchemaVersion(data []byte) (version string, ok bool, err error)

ProbeEvaluationOutcomeSchemaVersion cheaply detects whether data has the top-level shape of a results.json artifact and returns its declared version.

func ValidateSchemaVersion added in v0.38.0

func ValidateSchemaVersion(artifact, source, version string) (string, error)

Types

type ActionSequenceGraderParameters

type ActionSequenceGraderParameters struct {
	MatchingMode    ActionSequenceMatchingMode `yaml:"matching_mode,omitempty" json:"matching_mode,omitempty"`
	ExpectedActions []string                   `yaml:"expected_actions,omitempty" json:"expected_actions,omitempty"`
}

type ActionSequenceMatchingMode

type ActionSequenceMatchingMode string

ActionSequenceMatchingMode controls how actual tool calls are compared to expected actions.

const (
	ActionSequenceMatchingModeExact    ActionSequenceMatchingMode = "exact_match"
	ActionSequenceMatchingModeInOrder  ActionSequenceMatchingMode = "in_order_match"
	ActionSequenceMatchingModeAnyOrder ActionSequenceMatchingMode = "any_order_match"
)

type AdversarialConfig added in v0.38.0

type AdversarialConfig struct {
	// Packs is the list of built-in pack identifiers to run (e.g.
	// "prompt-injection", "scope-bypass"). Unknown identifiers are rejected
	// by `waza adversarial`; the current schema does not support
	// out-of-tree custom packs. Required; must contain at least one entry.
	Packs []string `yaml:"packs" json:"packs"`
	// OnUnsafeOutcome controls whether unsafe outcomes fail the run
	// ("fail", default) or only warn ("warn"). When empty, "fail" is used.
	OnUnsafeOutcome AdversarialOnUnsafeOutcome `yaml:"on_unsafe_outcome,omitempty" json:"on_unsafe_outcome,omitempty"`
}

AdversarialConfig declares offline adversarial / fault-injection packs to run against the skill under test. Packs ship as deterministic, embedded YAML + fixture bundles so they execute identically in CI without any live payload generation. See `waza adversarial` for the runner.

func (*AdversarialConfig) EffectiveOnUnsafeOutcome added in v0.38.0

func (a *AdversarialConfig) EffectiveOnUnsafeOutcome() AdversarialOnUnsafeOutcome

EffectiveOnUnsafeOutcome returns the configured policy, defaulting to AdversarialOnUnsafeOutcomeFail when unset.

func (*AdversarialConfig) Validate added in v0.38.0

func (a *AdversarialConfig) Validate() error

Validate checks the adversarial config has at least one pack and that the on_unsafe_outcome policy is one of the supported values. Pack names are normalized in-place (whitespace trimmed) so downstream lookups see the canonical form regardless of YAML formatting.

type AdversarialOnUnsafeOutcome added in v0.38.0

type AdversarialOnUnsafeOutcome string

AdversarialOnUnsafeOutcome controls how unsafe outcomes from adversarial packs are reported to the caller. It is consumed by `waza adversarial` to decide whether an unsafe outcome should fail CI or only warn.

const (
	// AdversarialOnUnsafeOutcomeFail (default) makes any unsafe outcome a hard
	// failure: `waza adversarial` exits with code 2 (matching `waza gate`'s
	// golden-failure exit) so a single CI step can gate both signals.
	AdversarialOnUnsafeOutcomeFail AdversarialOnUnsafeOutcome = "fail"
	// AdversarialOnUnsafeOutcomeWarn keeps the exit code at zero and only
	// records the unsafe outcome in the results.json + stderr summary.
	AdversarialOnUnsafeOutcomeWarn AdversarialOnUnsafeOutcome = "warn"
)

type BehaviorGraderParameters

type BehaviorGraderParameters struct {
	MaxToolCalls   int      `yaml:"max_tool_calls,omitempty" json:"max_tool_calls,omitempty"`
	MaxTokens      int      `yaml:"max_tokens,omitempty" json:"max_tokens,omitempty"`
	RequiredTools  []string `yaml:"required_tools,omitempty" json:"required_tools,omitempty"`
	ForbiddenTools []string `yaml:"forbidden_tools,omitempty" json:"forbidden_tools,omitempty"`
	MaxDurationMS  int64    `yaml:"max_duration_ms,omitempty" json:"max_duration_ms,omitempty"`
}

type BehaviorRules

type BehaviorRules struct {
	MaxToolInvocations int      `yaml:"max_tool_calls,omitempty" json:"max_tool_invocations,omitempty"`
	MaxRounds          int      `yaml:"max_iterations,omitempty" json:"max_rounds,omitempty"`
	MaxTokens          int      `yaml:"max_tokens,omitempty" json:"max_tokens,omitempty"`
	MaxResponseTimeMs  int64    `yaml:"max_response_time_ms,omitempty" json:"max_response_time_ms,omitempty"`
	MustUseTool        []string `yaml:"required_tools,omitempty" json:"must_use_tool,omitempty"`
	ForbidTool         []string `yaml:"forbidden_tools,omitempty" json:"forbid_tool,omitempty"`
}

type BenchmarkSpec deprecated

type BenchmarkSpec = EvalSpec

Deprecated: Use EvalSpec instead.

type Checkpoint added in v0.38.0

type Checkpoint struct {
	// AfterTurn is the 1-based turn index at whose boundary the graders run.
	// Turn 1 is the initial prompt; turns 2..N are follow-ups or responder
	// replies. Must be >= 1.
	AfterTurn int `yaml:"after_turn" json:"after_turn"`
	// Graders is the slice of grader configurations to run at this turn
	// boundary. Required. Reuses the same ValidatorInline shape as task-level
	// `graders:` so any existing grader type is supported.
	Graders []ValidatorInline `yaml:"graders" json:"graders"`
	// OnFailure controls multi-turn behavior when any grader in this
	// checkpoint fails. "continue" (default) records the failure and keeps
	// going. "stop" short-circuits the multi-turn loop after the failure.
	OnFailure CheckpointOnFailure `yaml:"on_failure,omitempty" json:"on_failure,omitempty"`
}

Checkpoint runs a slice of graders against the conversation state at the end of a specific turn. See TestCase.Checkpoints for details.

func (*Checkpoint) EffectiveOnFailure added in v0.38.0

func (c *Checkpoint) EffectiveOnFailure() CheckpointOnFailure

EffectiveOnFailure returns the OnFailure value to use, defaulting to CheckpointContinue when unset.

func (*Checkpoint) Validate added in v0.38.0

func (c *Checkpoint) Validate() error

Validate checks the checkpoint has the required fields. Reuses ValidatorInline.Validate for inner grader validation.

type CheckpointOnFailure added in v0.38.0

type CheckpointOnFailure string

CheckpointOnFailure controls multi-turn behavior when a checkpoint fails.

const (
	// CheckpointContinue (default) records the failure and continues with the
	// remaining turns and the final grader pass.
	CheckpointContinue CheckpointOnFailure = "continue"
	// CheckpointStop records the failure, sets the run's error message, and
	// short-circuits the multi-turn loop so no further turns execute.
	CheckpointStop CheckpointOnFailure = "stop"
)

type CheckpointOutcome added in v0.38.0

type CheckpointOutcome struct {
	// AfterTurn echoes Checkpoint.AfterTurn so consumers can sort/group.
	AfterTurn int `json:"after_turn"`
	// Status is StatusPassed when every grader in this checkpoint passed,
	// StatusFailed when at least one grader failed.
	Status Status `json:"status"`
	// Validations maps grader identifier to result, identical to
	// RunResult.Validations.
	Validations map[string]GraderResults `json:"validations"`
	// Stopped is true when this checkpoint had `on_failure: stop` and at
	// least one grader failed, terminating the multi-turn loop after this
	// turn.
	Stopped bool `json:"stopped,omitempty"`
}

CheckpointOutcome captures the results of a single TestCase.Checkpoint that ran during a multi-turn run. It mirrors the shape of the final-grader validations map so dashboards can present per-turn pass/fail uniformly.

type Config

type Config struct {
	TrialsPerTask int `yaml:"trials_per_task" json:"runs_per_test"`
	TimeoutSec    int `yaml:"timeout_seconds" json:"timeout_sec"`
	// FirstEventTimeoutSec bounds how long to wait for the first session event
	// before treating a run as a session-start hang (the engine launched but
	// never started the agent's first turn). It is much shorter than
	// TimeoutSec, which must cover the slowest legitimate full turn. 0 (the
	// default) disables the check. Per-task overrides live on TestCase.
	FirstEventTimeoutSec int            `yaml:"first_event_timeout_seconds,omitempty" json:"first_event_timeout_sec,omitempty"`
	Concurrent           bool           `yaml:"parallel" json:"concurrent"`
	Workers              int            `yaml:"workers,omitempty" json:"workers,omitempty"`
	StopOnError          bool           `yaml:"fail_fast,omitempty" json:"stop_on_error,omitempty"`
	EngineType           string         `yaml:"executor" json:"engine_type"`
	ModelID              string         `yaml:"model" json:"model_id"`
	SkillPaths           []string       `yaml:"skill_directories,omitempty" json:"skill_paths,omitempty"`
	InstructionFiles     []string       `yaml:"instruction_files,omitempty" json:"instruction_files,omitempty"`
	InjectSkillBody      *bool          `yaml:"inject_skill_body,omitempty" json:"inject_skill_body,omitempty"`
	DisabledSkills       []string       `yaml:"disabled_skills,omitempty" json:"disabled_skills,omitempty"`
	RequiredSkills       []string       `yaml:"required_skills,omitempty" json:"required_skills,omitempty"`
	ServerConfigs        map[string]any `yaml:"mcp_servers,omitempty" json:"server_configs,omitempty"`
	MaxAttempts          int            `yaml:"max_attempts,omitempty" json:"max_attempts,omitempty"`
	GroupBy              string         `yaml:"group_by,omitempty" json:"group_by,omitempty"`
	JudgeModel           string         `yaml:"judge_model,omitempty" json:"judge_model,omitempty"`
}

Config controls execution behavior

func (*Config) AllSkillsDisabled added in v0.29.0

func (c *Config) AllSkillsDisabled() bool

AllSkillsDisabled returns true when skills should be completely disabled.

func (*Config) FilteredSkillPaths added in v0.29.0

func (c *Config) FilteredSkillPaths() []string

FilteredSkillPaths returns SkillPaths with any disabled skill directories removed.

func (*Config) ShouldInjectSkillBody added in v0.37.0

func (c *Config) ShouldInjectSkillBody() bool

ShouldInjectSkillBody returns true unless the eval explicitly opts out of injecting the target skill body into the system prompt.

type DiffExpectedFileParameters

type DiffExpectedFileParameters struct {
	// Path is the workspace-relative path to the file being checked.
	Path string `yaml:"path" json:"path"`

	// Snapshot is the path (relative to context/fixtures dir) of the expected file content.
	// When set, the workspace file must match this snapshot exactly.
	Snapshot string `yaml:"snapshot,omitempty" json:"snapshot,omitempty"`

	// Contains lists line fragments that must appear in the workspace file.
	// Prefixed with "+" means the line must be present; "-" means it must be absent.
	Contains []string `yaml:"contains,omitempty" json:"contains,omitempty"`
}

DiffExpectedFileParameters defines a single file expectation for the diff grader. Either Snapshot or Contains (or both) must be specified.

type DiffGraderParameters

type DiffGraderParameters struct {
	ExpectedFiles   []DiffExpectedFileParameters `yaml:"expected_files,omitempty" json:"expected_files,omitempty"`
	ContextDir      string                       `yaml:"context_dir,omitempty" json:"context_dir,omitempty"`
	UpdateSnapshots bool                         `yaml:"update_snapshots,omitempty" json:"update_snapshots,omitempty"`
}

type EvalSpec added in v0.31.0

type EvalSpec struct {
	SchemaVersion string `yaml:"schemaVersion,omitempty" json:"schemaVersion,omitempty"`
	SpecIdentity  `yaml:",inline"`
	SkillName     string             `yaml:"skill"`
	Version       string             `yaml:"version"`
	Config        Config             `yaml:"config"`
	Hooks         hooks.HooksConfig  `yaml:"hooks,omitempty"`
	MCPMocks      []MCPMockConfig    `yaml:"mcp_mocks,omitempty" json:"mcp_mocks,omitempty"`
	Adversarial   *AdversarialConfig `yaml:"adversarial,omitempty" json:"adversarial,omitempty"`
	Inputs        map[string]string  `yaml:"inputs,omitempty" json:"inputs,omitempty"`
	TasksFrom     string             `yaml:"tasks_from,omitempty" json:"tasks_from,omitempty"`
	Range         [2]int             `yaml:"range,omitempty" json:"range,omitempty"`
	Graders       []GraderConfig     `yaml:"graders"`
	Metrics       []MeasurementDef   `yaml:"metrics"`
	Tasks         []string           `yaml:"tasks"`
	Baseline      bool               `yaml:"baseline,omitempty" json:"baseline,omitempty"`
}

EvalSpec represents a complete evaluation specification.

Deprecated alias: BenchmarkSpec is provided for backward compatibility.

func LoadBenchmarkSpec deprecated

func LoadBenchmarkSpec(path string) (*EvalSpec, error)

Deprecated: Use LoadEvalSpec instead.

func LoadEvalSpec added in v0.31.0

func LoadEvalSpec(path string) (*EvalSpec, error)

LoadEvalSpec loads a spec from a YAML file with strict validation.

Normally the schema validation will catch errors in the eval.yaml, but this also does strict YAML parsing to catch errors like unknown fields or type errors that the schema validation might miss.

func (*EvalSpec) ResolveTestFiles added in v0.31.0

func (s *EvalSpec) ResolveTestFiles(basePath string) ([]string, error)

ResolveTestFiles expands glob patterns to actual test files

func (*EvalSpec) Validate added in v0.31.0

func (s *EvalSpec) Validate() error

Validate checks that the spec is valid

type EvaluationOutcome

type EvaluationOutcome struct {
	SchemaVersion   string                   `json:"schemaVersion"`
	RunID           string                   `json:"eval_id"`
	SkillTested     string                   `json:"skill"`
	BenchName       string                   `json:"eval_name"`
	Timestamp       time.Time                `json:"timestamp"`
	Setup           OutcomeSetup             `json:"config"`
	Digest          OutcomeDigest            `json:"summary"`
	Measures        map[string]MeasureResult `json:"metrics"`
	TestOutcomes    []TestOutcome            `json:"tasks"`
	TriggerMetrics  *TriggerMetrics          `json:"trigger_metrics,omitempty"`
	TriggerResults  []TriggerResult          `json:"trigger_results,omitempty"`
	Metadata        map[string]any           `json:"metadata,omitempty"`
	IsBaseline      bool                     `json:"is_baseline,omitempty"`
	BaselineOutcome *EvaluationOutcome       `json:"baseline_outcome,omitempty"`
}

EvaluationOutcome represents the complete result of an evaluation run

func LoadEvaluationOutcome added in v0.38.0

func LoadEvaluationOutcome(path string) (*EvaluationOutcome, error)

LoadEvaluationOutcome loads a results.json file with schema-version compatibility checks.

func ParseEvaluationOutcome added in v0.38.0

func ParseEvaluationOutcome(data []byte, source string) (*EvaluationOutcome, error)

ParseEvaluationOutcome decodes an EvaluationOutcome and defaults missing schemaVersion to the current version.

func (EvaluationOutcome) MarshalJSON added in v0.38.0

func (o EvaluationOutcome) MarshalJSON() ([]byte, error)

type FailureArtifacts added in v0.37.0

type FailureArtifacts struct {
	StdErr        string            `json:"stderr,omitempty"`
	StdOut        string            `json:"stdout,omitempty"`
	ExitCode      int               `json:"exit_code,omitempty"`
	FailedGraders []string          `json:"failed_graders,omitempty"`
	ErrorPatterns []string          `json:"error_patterns,omitempty"`
	TriageSummary string            `json:"triage_summary,omitempty"`
	CapturedAt    time.Time         `json:"captured_at"`
	Context       map[string]string `json:"context,omitempty"`
}

FailureArtifacts captures diagnostic information when a run fails

type FileContentPatternParameters

type FileContentPatternParameters struct {
	Path         string   `yaml:"path" json:"path"`
	MustMatch    []string `yaml:"must_match,omitempty" json:"must_match,omitempty"`
	MustNotMatch []string `yaml:"must_not_match,omitempty" json:"must_not_match,omitempty"`
}

type FileGraderParameters

type FileGraderParameters struct {
	MustExist       []string                       `yaml:"must_exist,omitempty" json:"must_exist,omitempty"`
	MustNotExist    []string                       `yaml:"must_not_exist,omitempty" json:"must_not_exist,omitempty"`
	ContentPatterns []FileContentPatternParameters `yaml:"content_patterns,omitempty" json:"content_patterns,omitempty"`
}

type GenericGraderParameters

type GenericGraderParameters map[string]any

GenericGraderParameters is used for unknown kinds to preserve raw config values.

type GitResource added in v0.37.0

type GitResource struct {
	// Type selects the materialization strategy. Required. Only "worktree"
	// is currently supported.
	Type GitResourceType `yaml:"type" json:"type"`
	// Source is the local path to a git repository. Required for the
	// "worktree" strategy.
	Source string `yaml:"source" json:"source"`
	// Commit is an optional commit SHA, branch, or tag to check out.
	// Defaults to the source repo's HEAD when empty.
	Commit string `yaml:"commit,omitempty" json:"commit,omitempty"`
	// Dest is an optional subdirectory under the workspace to materialize
	// the repo into. When empty, the repo is materialized at the workspace
	// root. Must be a relative path that does not escape the workspace.
	Dest string `yaml:"dest,omitempty" json:"dest,omitempty"`
}

GitResource describes a git repository to materialize into the per-task workspace before the agent runs. Currently only the `worktree` strategy is supported; additional strategies (e.g. HTTPS clone) can be added later without breaking the YAML surface.

func (*GitResource) Validate added in v0.37.0

func (g *GitResource) Validate() error

Validate verifies that the git resource has the required fields and that its destination path is safe (relative, no traversal segments).

type GitResourceType added in v0.37.0

type GitResourceType string

GitResourceType identifies how a git resource is materialized.

const (
	// GitResourceTypeWorktree materializes the resource via `git worktree add`
	// against a local source repository. It is cheap and requires no network.
	GitResourceTypeWorktree GitResourceType = "worktree"
)

type GradeOutcome added in v0.22.0

type GradeOutcome struct {
	OverallScore   float64                 `json:"overall_score"`
	Passed         bool                    `json:"passed"`
	Tasks          map[string]GradeOutcome `json:"tasks,omitempty"`
	GraderAverages map[string]float64      `json:"grader_averages,omitempty"`
}

type GraderConfig

type GraderConfig struct {
	Kind       GraderKind       `yaml:"type" json:"kind"`
	Identifier string           `yaml:"name" json:"identifier"`
	ScriptPath string           `yaml:"script,omitempty" json:"script_path,omitempty"`
	Rubric     string           `yaml:"rubric,omitempty" json:"rubric,omitempty"`
	ModelID    string           `yaml:"model,omitempty" json:"model_id,omitempty"`
	Weight     float64          `yaml:"weight,omitempty" json:"weight,omitempty"`
	Parameters GraderParameters `yaml:"config,omitempty" json:"parameters,omitempty"`
}

GraderConfig defines a validator/grader

func (*GraderConfig) EffectiveWeight

func (g *GraderConfig) EffectiveWeight() float64

EffectiveWeight returns the grader weight, defaulting to 1.0 if unset.

func (*GraderConfig) UnmarshalYAML

func (g *GraderConfig) UnmarshalYAML(node *yaml.Node) error

func (*GraderConfig) Validate added in v0.26.0

func (g *GraderConfig) Validate() error

Validate checks that the grader config has required fields for its type.

type GraderKind

type GraderKind string

GraderKind identifies the type of grader (e.g. regex, file, code).

const (
	GraderKindInlineScript    GraderKind = "code"
	GraderKindPrompt          GraderKind = "prompt"
	GraderKindText            GraderKind = "text"
	GraderKindFile            GraderKind = "file"
	GraderKindJSONSchema      GraderKind = "json_schema"
	GraderKindProgram         GraderKind = "program"
	GraderKindBehavior        GraderKind = "behavior"
	GraderKindActionSequence  GraderKind = "action_sequence"
	GraderKindSkillInvocation GraderKind = "skill_invocation"
	GraderKindTrigger         GraderKind = "trigger"
	GraderKindDiff            GraderKind = "diff"
	GraderKindToolConstraint  GraderKind = "tool_constraint"
	GraderKindToolCalls       GraderKind = "tool_calls"
)

type GraderParameters

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

GraderParameters is a polymorphic grader config payload decoded from YAML based on GraderKind.

type GraderResults

type GraderResults struct {
	Name       string         `json:"identifier"`
	Type       GraderKind     `json:"type"`
	Score      float64        `json:"score"`
	Weight     float64        `json:"weight"`
	Passed     bool           `json:"passed"`
	Feedback   string         `json:"feedback"`
	Details    map[string]any `json:"details,omitempty"`
	DurationMs int64          `json:"duration_ms"`
}

type GroupStats

type GroupStats struct {
	Name     string  `json:"name"`
	Passed   int     `json:"passed"`
	Total    int     `json:"total"`
	AvgScore float64 `json:"avg_score"`
}

GroupStats holds aggregate statistics for a group of test outcomes.

type InlineScriptGraderParameters

type InlineScriptGraderParameters struct {
	Assertions []string `yaml:"assertions,omitempty" json:"assertions,omitempty"`

	// Language indicates which language the Assertions are written for. Defaults to [LanguagePython]
	Language Language `yaml:"language,omitempty" json:"language,omitempty"`
}

type JSONSchemaGraderParameters

type JSONSchemaGraderParameters struct {
	// Schema is an inline JSON schema object used for validation.
	Schema map[string]any `yaml:"schema,omitempty" json:"schema,omitempty"`

	// SchemaFile is a path to a JSON schema file. Used when Schema is not provided.
	SchemaFile string `yaml:"schema_file,omitempty" json:"schema_file,omitempty"`

	// ExtractJSON allows the grader to validate a single JSON document embedded
	// in prose or a Markdown JSON code block. The default requires pure JSON.
	ExtractJSON bool `yaml:"extract_json,omitempty" json:"extract_json,omitempty"`
}

JSONSchemaGraderParameters holds the arguments for creating a JSON schema grader.

type Language

type Language string
const (
	LanguagePython     Language = "python"
	LanguageJavascript Language = "javascript"
)

type MCPMockConfig added in v0.38.0

type MCPMockConfig struct {
	Name     string                 `yaml:"name" json:"name"`
	Fixtures string                 `yaml:"fixtures,omitempty" json:"fixtures,omitempty"`
	Tools    map[string]MCPMockTool `yaml:"tools,omitempty" json:"tools,omitempty"`
}

MCPMockConfig defines a deterministic MCP server mock launched for an eval.

type MCPMockResponse added in v0.38.0

type MCPMockResponse struct {
	Match       map[string]any    `yaml:"match,omitempty" json:"match,omitempty"`
	MatchSchema map[string]any    `yaml:"match_schema,omitempty" json:"match_schema,omitempty"`
	MatchRegex  map[string]string `yaml:"match_regex,omitempty" json:"match_regex,omitempty"`
	Return      any               `yaml:"return,omitempty" json:"return,omitempty"`
	Error       string            `yaml:"error,omitempty" json:"error,omitempty"`
}

MCPMockResponse defines one deterministic response for a mocked tool call.

type MCPMockTool added in v0.38.0

type MCPMockTool struct {
	Description string            `yaml:"description,omitempty" json:"description,omitempty"`
	InputSchema map[string]any    `yaml:"input_schema,omitempty" json:"input_schema,omitempty"`
	Responses   []MCPMockResponse `yaml:"responses,omitempty" json:"responses,omitempty"`
}

MCPMockTool defines a mocked MCP tool and its response fixtures.

type MeasureResult

type MeasureResult struct {
	Identifier string         `json:"identifier"`
	Value      float64        `json:"value"`
	Threshold  float64        `json:"threshold"`
	Passed     bool           `json:"passed"`
	Weight     float64        `json:"weight"`
	Details    map[string]any `json:"details,omitempty"`
}

type MeasurementDef

type MeasurementDef struct {
	Identifier string  `yaml:"name" json:"identifier"`
	Weight     float64 `yaml:"weight" json:"weight"`
	Threshold  float64 `yaml:"threshold" json:"threshold"`
	Enabled    bool    `yaml:"enabled,omitempty" json:"enabled,omitempty"`
	Desc       string  `yaml:"description,omitempty" json:"desc,omitempty"`
}

MeasurementDef defines a metric

type ModelScore

type ModelScore struct {
	ModelID        string             `json:"model_id"`
	HeuristicScore float64            `json:"heuristic_score"`
	Rank           int                `json:"rank"`
	Scores         map[string]float64 `json:"component_scores,omitempty"`
}

ModelScore holds the heuristic score and rank for a single model.

type ModelUsage

type ModelUsage struct {
	InputTokens      int     `json:"input_tokens"`
	OutputTokens     int     `json:"output_tokens"`
	CacheReadTokens  int     `json:"cache_read_tokens"`
	CacheWriteTokens int     `json:"cache_write_tokens"`
	RequestCount     float64 `json:"request_count"`
	RequestCost      float64 `json:"request_cost"`
}

ModelUsage holds per-model token and request usage.

type MultiSkillSummary

type MultiSkillSummary struct {
	Timestamp time.Time      `json:"timestamp"`
	Skills    []SkillSummary `json:"skills"`
	Overall   OverallSummary `json:"overall"`
}

MultiSkillSummary aggregates results across multiple skill evaluations.

type OutcomeDigest

type OutcomeDigest struct {
	TotalTests     int          `json:"total_tests"`
	Succeeded      int          `json:"succeeded"`
	Failed         int          `json:"failed"`
	Errors         int          `json:"errors"`
	Skipped        int          `json:"skipped"`
	SuccessRate    float64      `json:"success_rate"`
	AggregateScore float64      `json:"aggregate_score"`
	WeightedScore  float64      `json:"weighted_score"`
	MinScore       float64      `json:"min_score"`
	MaxScore       float64      `json:"max_score"`
	StdDev         float64      `json:"std_dev"`
	DurationMs     int64        `json:"duration_ms"`
	Groups         []GroupStats `json:"groups,omitempty"`
	Usage          *UsageStats  `json:"usage,omitempty"`

	// Statistical summary populated when trials_per_task > 1
	Statistics *StatisticalSummary `json:"statistics,omitempty"`
}

type OutcomeSetup

type OutcomeSetup struct {
	RunsPerTest int    `json:"runs_per_test"`
	ModelID     string `json:"model_id"`
	EngineType  string `json:"engine_type"`
	TimeoutSec  int    `json:"timeout_sec"`
	JudgeModel  string `json:"judge_model,omitempty"`
}

type OutcomeSpec

type OutcomeSpec struct {
	Category  string `yaml:"type" json:"category"`
	Value     any    `yaml:"value,omitempty" json:"value,omitempty"`
	Predicate string `yaml:"condition,omitempty" json:"predicate,omitempty"`
}

type OverallSummary

type OverallSummary struct {
	TotalSkills       int     `json:"total_skills"`
	TotalModels       int     `json:"total_models"`
	AvgPassRate       float64 `json:"avg_pass_rate"`
	AvgAggregateScore float64 `json:"avg_aggregate_score"`
}

OverallSummary contains cross-skill aggregated metrics.

type PairwiseResult

type PairwiseResult struct {
	Winner             string `json:"winner"`    // "baseline", "skill", or "tie"
	Magnitude          string `json:"magnitude"` // "much-better", "slightly-better", "equal", etc.
	Reasoning          string `json:"reasoning"`
	PositionConsistent bool   `json:"position_consistent"` // true if result held after position swap
}

PairwiseResult captures the outcome of a pairwise LLM judge comparison.

type ProgramGraderParameters

type ProgramGraderParameters struct {
	Command string   `yaml:"command,omitempty" json:"command,omitempty"`
	Args    []string `yaml:"args,omitempty" json:"args,omitempty"`
	Timeout int      `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}

type PromptGraderMode

type PromptGraderMode string
const (
	PromptGraderModeIndependent PromptGraderMode = "independent"
	PromptGraderModePairwise    PromptGraderMode = "pairwise"
)

type PromptGraderParameters

type PromptGraderParameters struct {
	Prompt          string           `yaml:"prompt,omitempty" json:"prompt,omitempty"`
	Model           string           `yaml:"model,omitempty" json:"model,omitempty"`
	ContinueSession bool             `yaml:"continue_session,omitempty" json:"continue_session,omitempty"`
	Mode            PromptGraderMode `yaml:"mode,omitempty" json:"mode,omitempty"`
	// Rubric is an optional reference to a reusable rubric. It can be either
	// the name of a built-in rubric ("groundedness") or a path to a local
	// rubric markdown file ("./rubrics/my-custom.md"). When set, the rubric's
	// body becomes the judge prompt unless an inline Prompt is also supplied.
	Rubric string `yaml:"rubric,omitempty" json:"rubric,omitempty"`
}

type Recommendation

type Recommendation struct {
	RecommendedModel string                `json:"recommended_model"`
	HeuristicScore   float64               `json:"heuristic_score"`
	Reason           string                `json:"reason"`
	WinnerMarginPct  float64               `json:"winner_margin_pct"`
	Weights          RecommendationWeights `json:"weights"`
	ModelScores      []ModelScore          `json:"all_models"`
}

Recommendation represents a heuristic recommendation for the best model across a multi-model evaluation run.

type RecommendationWeights

type RecommendationWeights struct {
	AggregateScore float64 `json:"aggregate_score"`
	PassRate       float64 `json:"pass_rate"`
	Consistency    float64 `json:"consistency"`
	Speed          float64 `json:"speed"`
}

RecommendationWeights defines the weighting scheme for heuristic scoring.

type ResourceRef

type ResourceRef struct {
	Location string `yaml:"path,omitempty" json:"location,omitempty"`
	Body     string `yaml:"content,omitempty" json:"body,omitempty"`
}

ResourceRef points to a file or inline content

type ResponderConfig added in v0.37.0

type ResponderConfig struct {
	// Model is the model used for the responder LLM. Optional; when empty the
	// eval-level config.model is used.
	Model string `yaml:"model,omitempty" json:"model,omitempty"`
	// Instructions describe the target configuration the responder represents
	// and the rule for abstaining. Required.
	Instructions string `yaml:"instructions" json:"instructions"`
	// MaxFollowups caps how many times the responder may reply before the loop
	// stops. Required; must be >= 1.
	MaxFollowups int `yaml:"max_followups" json:"max_followups"`
}

ResponderConfig configures an LLM-backed surrogate user that answers a skill's follow-up questions during a multi-turn run. It is mutually exclusive with TaskStimulus.FollowUps.

type ResponderInfo added in v0.37.0

type ResponderInfo struct {
	// FollowupsSent is the number of responder answers sent to the agent.
	FollowupsSent int `json:"followups_sent"`
	// Outcome is one of: stopped, abstained, cap_exhausted, error.
	Outcome string `json:"outcome"`
	// Reason holds the responder's reason when Outcome == "abstained" or an
	// error message when Outcome == "error".
	Reason string `json:"reason,omitempty"`
}

ResponderInfo records the outcome of a responder-driven multi-turn run.

type RunResult

type RunResult struct {
	RunNumber int `json:"run_number"`
	Attempts  int `json:"attempts"`
	// Status contains the overall status of the run.
	// NOTE: if Status == [StatusError], then [ErrorMsg] will be set to the
	// message from the error.
	Status           Status                   `json:"status"`
	DurationMs       int64                    `json:"duration_ms"`
	Validations      map[string]GraderResults `json:"validations"`
	SessionDigest    SessionDigest            `json:"session_digest"`
	Transcript       []TranscriptEvent        `json:"transcript,omitempty"`
	FinalOutput      string                   `json:"final_output"`
	ErrorMsg         string                   `json:"error_msg,omitempty"`
	SkillInvocations []SkillInvocation        `json:"skill_invocations,omitempty"`
	Usage            *UsageStats              `json:"usage,omitempty"`
	WorkspaceDir     string                   `json:"workspace_dir,omitempty"`
	FailureArtifacts *FailureArtifacts        `json:"failure_artifacts,omitempty"`
	Responder        *ResponderInfo           `json:"responder,omitempty"`
	// Checkpoints captures per-turn checkpoint grader results, one entry per
	// configured TestCase.Checkpoint that actually ran (i.e., turn index was
	// reached). Empty / omitted when the task defines no checkpoints.
	Checkpoints []CheckpointOutcome `json:"checkpoints,omitempty"`

	// ToolEvents is a normalized, replay-friendly record of every tool call
	// made during the run. Added in schema version 1.1 as an additive field
	// (see issue #366). The legacy SessionDigest.ToolCalls is preserved for
	// backward compatibility; new consumers should prefer ToolEvents.
	ToolEvents []ToolEvent `json:"tool_events,omitempty"`

	// SnapshotPath is the on-disk path of the self-contained snapshot.json
	// artifact for this run, as returned by snapshot.Writer.Write. It is
	// rooted at the --snapshot directory the user passed to `waza run` (so
	// it may be absolute, or relative to the working directory at run time,
	// depending on what the user supplied). Consumers that need a
	// results.json-relative path should compute it themselves with
	// filepath.Rel against the results.json directory. Empty when
	// `waza run --snapshot` was not used. Added in schema version 1.2 as
	// an additive field (see issue #367).
	SnapshotPath string `json:"snapshot_path,omitempty"`
}

RunResult is the result of a single run/trial

func (*RunResult) AllValidationsPassed

func (r *RunResult) AllValidationsPassed() bool

AllValidationsPassed checks if all validations passed

func (*RunResult) ComputeRunScore

func (r *RunResult) ComputeRunScore() float64

ComputeRunScore calculates the average score across all validations (unweighted, for backward compat)

func (*RunResult) ComputeWeightedRunScore

func (r *RunResult) ComputeWeightedRunScore() float64

ComputeWeightedRunScore calculates the weighted composite score (0.0–1.0) using each grader's Weight field. If all weights are zero, falls back to simple average.

type SessionDigest

type SessionDigest struct {
	ToolCallCount int         `json:"tool_call_count"`
	ToolsUsed     []string    `json:"tools_used"`
	ToolCalls     []ToolCall  `json:"tool_calls,omitempty"`
	Errors        []string    `json:"errors"`
	Usage         *UsageStats `json:"usage,omitempty"`
	SessionID     string      `json:"session_id,omitempty"`
}

type SkillImpactMetric

type SkillImpactMetric struct {
	PassRateWithSkills float64         `json:"pass_rate_with_skills"`
	PassRateBaseline   float64         `json:"pass_rate_baseline"`
	Delta              float64         `json:"delta"`
	PercentChange      float64         `json:"percent_change"`
	Pairwise           *PairwiseResult `json:"pairwise,omitempty"`
}

SkillImpactMetric represents A/B comparison for a single task

type SkillInvocation added in v0.22.0

type SkillInvocation struct {
	Name string `json:"name"`
	Path string `json:"path,omitempty"`
}

SkillInvocation records a skill invoked during an agent session.

type SkillInvocationGraderParameters

type SkillInvocationGraderParameters struct {
	RequiredSkills  []string                    `yaml:"required_skills,omitempty" json:"required_skills,omitempty"`
	ForbiddenSkills []string                    `yaml:"forbidden_skills,omitempty" json:"forbidden_skills,omitempty"`
	Mode            SkillInvocationMatchingMode `yaml:"mode,omitempty" json:"mode,omitempty"`
	AllowExtra      *bool                       `yaml:"allow_extra,omitempty" json:"allow_extra,omitempty"`
}

type SkillInvocationMatchingMode

type SkillInvocationMatchingMode string

SkillInvocationMatchingMode controls how actual skill invocations are compared to expected skills.

const (
	SkillMatchingModeExact    SkillInvocationMatchingMode = "exact_match"
	SkillMatchingModeInOrder  SkillInvocationMatchingMode = "in_order"
	SkillMatchingModeAnyOrder SkillInvocationMatchingMode = "any_order"
)

type SkillSummary

type SkillSummary struct {
	SkillName      string   `json:"skill_name"`
	Models         []string `json:"models"`
	PassRate       float64  `json:"pass_rate"`
	AggregateScore float64  `json:"aggregate_score"`
	OutputFiles    []string `json:"output_files"`
}

SkillSummary contains aggregated metrics for a single skill evaluation.

type SpecIdentity

type SpecIdentity struct {
	Name        string `yaml:"name" json:"name"`
	Description string `yaml:"description,omitempty" json:"description,omitempty"`
}

type StatisticalSummary

type StatisticalSummary struct {
	BootstrapCI    statistics.ConfidenceInterval `json:"bootstrap_ci"`
	IsSignificant  bool                          `json:"is_significant"`
	NormalizedGain *float64                      `json:"normalized_gain,omitempty"`
}

StatisticalSummary holds aggregate statistical data for the digest when trials > 1.

type Status

type Status string

Status represents the outcome status of a test or run.

const (
	StatusPassed  Status = "passed"
	StatusFailed  Status = "failed"
	StatusError   Status = "error"
	StatusSkipped Status = "skipped"
	// StatusNA is used in comparison reports when a task is not found in a result file.
	StatusNA Status = "n/a"
)

type TaskExpectation added in v0.31.0

type TaskExpectation struct {
	OutcomeSpecs    []OutcomeSpec  `yaml:"outcomes,omitempty" json:"outcome_specs,omitempty"`
	ToolPatterns    map[string]any `yaml:"tool_calls,omitempty" json:"tool_patterns,omitempty"`
	BehaviorRules   BehaviorRules  `yaml:"behavior,omitempty" json:"behavior_rules,omitempty"`
	MustInclude     []string       `yaml:"output_contains,omitempty" json:"must_include,omitempty"`
	MustExclude     []string       `yaml:"output_not_contains,omitempty" json:"must_exclude,omitempty"`
	MayInclude      []string       `yaml:"output_contains_any,omitempty" json:"may_include,omitempty"`
	ExpectedTrigger *bool          `yaml:"should_trigger,omitempty" json:"expected_trigger,omitempty"`
}

TaskExpectation defines expected outcomes.

Deprecated alias: TestExpectation is provided for backward compatibility.

type TaskStimulus added in v0.31.0

type TaskStimulus struct {
	Message     string            `yaml:"prompt" json:"message"`
	MessageFile string            `yaml:"prompt_file,omitempty" json:"message_file,omitempty"`
	Metadata    map[string]any    `yaml:"context,omitempty" json:"metadata,omitempty"`
	Resources   []ResourceRef     `yaml:"files,omitempty" json:"resources,omitempty"`
	Repos       []GitResource     `yaml:"repos,omitempty" json:"repos,omitempty"`
	WorkDir     string            `yaml:"workdir,omitempty" json:"workdir,omitempty"`
	Environment map[string]string `yaml:"environment,omitempty" json:"environment,omitempty"`
	FollowUps   []string          `yaml:"follow_up_prompts,omitempty" json:"follow_ups,omitempty"`
	Responder   *ResponderConfig  `yaml:"responder,omitempty" json:"responder,omitempty"`
}

TaskStimulus defines the input for a task.

Deprecated alias: TestStimulus is provided for backward compatibility.

type TaskTranscript

type TaskTranscript struct {
	TaskID      string                   `json:"task_id"`
	TaskName    string                   `json:"task_name"`
	Status      Status                   `json:"status"`
	StartedAt   time.Time                `json:"started_at"`
	CompletedAt time.Time                `json:"completed_at"`
	DurationMs  int64                    `json:"duration_ms"`
	Prompt      string                   `json:"prompt"`
	FinalOutput string                   `json:"final_output"`
	Transcript  []TranscriptEvent        `json:"transcript"`
	Validations map[string]GraderResults `json:"validations,omitempty"`
	Session     SessionDigest            `json:"session"`
	ErrorMsg    string                   `json:"error_msg,omitempty"`
}

TaskTranscript is the per-task JSON file written to the transcript directory.

type TestCase

type TestCase struct {
	Active           *bool           `yaml:"enabled,omitempty" json:"active,omitempty"`
	ContextRoot      string          `yaml:"context_dir,omitempty" json:"context_root,omitempty"`
	DisplayName      string          `yaml:"name" json:"display_name"`
	Expectation      TaskExpectation `yaml:"expected,omitempty" json:"expectation,omitempty"`
	InstructionFiles []string        `yaml:"instruction_files,omitempty" json:"instruction_files,omitempty"`
	SkillPaths       []string        `yaml:"skill_directories,omitempty" json:"skill_paths,omitempty"`
	Stimulus         TaskStimulus    `yaml:"inputs" json:"stimulus"`
	Summary          string          `yaml:"description,omitempty" json:"summary,omitempty"`
	Tags             []string        `yaml:"tags,omitempty" json:"labels,omitempty"`
	TestID           string          `yaml:"id" json:"test_id"`
	// Golden marks a task as a "must always pass" regression gate. When set
	// to true, `waza gate` treats any non-pass status as a hard failure
	// (exit code 2) regardless of the aggregate pass-rate threshold.
	Golden     bool `yaml:"golden,omitempty" json:"golden,omitempty"`
	TimeoutSec *int `yaml:"timeout_seconds,omitempty" json:"timeout_sec,omitempty"`
	// FirstEventTimeoutSec overrides Config.FirstEventTimeoutSec for this task.
	// nil inherits the eval-level value; 0 disables the check for this task.
	FirstEventTimeoutSec *int              `yaml:"first_event_timeout_seconds,omitempty" json:"first_event_timeout_sec,omitempty"`
	Validators           []ValidatorInline `yaml:"graders,omitempty" json:"validators,omitempty"`
	// Checkpoints attach graders to intermediate turn boundaries in a
	// multi-turn run. Each checkpoint specifies `after_turn: N` (1-based,
	// where turn 1 is the initial prompt) and a list of graders that run
	// against the cumulative conversation state at the end of that turn.
	// Checkpoints are additive — task-level `graders:` still run against
	// the final state after all turns complete.
	Checkpoints []Checkpoint `yaml:"checkpoints,omitempty" json:"checkpoints,omitempty"`
}

TestCase represents a single evaluation test

func LoadTestCase

func LoadTestCase(path string) (*TestCase, error)

LoadTestCase loads a test case from YAML

func (*TestCase) Validate added in v0.37.0

func (tc *TestCase) Validate() error

Validate checks task-level timeout constraints.

type TestExpectation deprecated

type TestExpectation = TaskExpectation

Deprecated: Use TaskExpectation instead.

type TestOutcome

type TestOutcome struct {
	TestID      string `json:"test_id"`
	DisplayName string `json:"display_name"`
	Group       string `json:"group,omitempty"`
	// Golden mirrors TestCase.Golden so `waza gate` can identify
	// must-pass tasks directly from results.json without re-reading YAML.
	Golden      bool               `json:"golden,omitempty"`
	Status      Status             `json:"status"`
	Runs        []RunResult        `json:"runs"`
	Stats       *TestStats         `json:"stats,omitempty"`
	SkillImpact *SkillImpactMetric `json:"skill_impact,omitempty"`
}

TestOutcome represents the result of one test case

type TestStats

type TestStats struct {
	PassRate         float64 `json:"pass_rate"`
	FlakinessPercent float64 `json:"flakiness_percent"`
	PassedRuns       int     `json:"passed_runs"`
	FailedRuns       int     `json:"failed_runs"`
	ErrorRuns        int     `json:"error_runs"`
	TotalRuns        int     `json:"total_runs"`
	AvgScore         float64 `json:"avg_score"`
	AvgWeightedScore float64 `json:"avg_weighted_score"`
	MinScore         float64 `json:"min_score"`
	MaxScore         float64 `json:"max_score"`
	StdDevScore      float64 `json:"std_dev_score"`
	ScoreVariance    float64 `json:"score_variance"`
	CI95Lo           float64 `json:"ci95_lo"`
	CI95Hi           float64 `json:"ci95_hi"`
	Flaky            bool    `json:"flaky"`
	AvgDurationMs    int64   `json:"avg_duration_ms"`

	// Bootstrap confidence interval over weighted scores (populated when trials > 1)
	BootstrapCI   *statistics.ConfidenceInterval `json:"bootstrap_ci,omitempty"`
	IsSignificant *bool                          `json:"is_significant,omitempty"`
}

type TestStimulus deprecated

type TestStimulus = TaskStimulus

Deprecated: Use TaskStimulus instead.

type TextGraderParameters

type TextGraderParameters struct {
	// Contains lists substrings that must appear in the output (case-insensitive).
	Contains []string `yaml:"contains,omitempty" json:"contains,omitempty"`

	// NotContains lists substrings that must NOT appear in the output (case-insensitive).
	NotContains []string `yaml:"not_contains,omitempty" json:"not_contains,omitempty"`

	// ContainsCS lists substrings that must appear in the output (case-sensitive).
	ContainsCS []string `yaml:"contains_cs,omitempty" json:"contains_cs,omitempty"`

	// NotContainsCS lists substrings that must NOT appear in the output (case-sensitive).
	NotContainsCS []string `yaml:"not_contains_cs,omitempty" json:"not_contains_cs,omitempty"`

	// RegexMatch lists regex patterns that must match somewhere in the output.
	RegexMatch []string `yaml:"regex_match,omitempty" json:"regex_match,omitempty"`

	// RegexNotMatch lists regex patterns that must NOT match anywhere in the output.
	RegexNotMatch []string `yaml:"regex_not_match,omitempty" json:"regex_not_match,omitempty"`
}

TextGraderParameters holds the arguments for creating a text grader.

type ToolCall

type ToolCall struct {
	// ID is the engine-assigned identifier for this call (e.g. the
	// Copilot SDK's ToolCallID). Used to correlate tool invocations in
	// observability backends.
	ID        string                               `json:"id,omitempty"`
	Name      string                               `json:"name"`
	Arguments ToolCallArgs                         `json:"arguments,omitempty"`
	Result    *copilot.ToolExecutionCompleteResult `json:"result,omitempty"`
	Success   bool                                 `json:"success"`
}

ToolCall represents a tool invocation

func FilterToolCalls

func FilterToolCalls(sessionEvents []copilot.SessionEvent) []ToolCall

FilterToolCalls goes through the list of session events and correlates tool starts with Success.

type ToolCallArgs

type ToolCallArgs struct {
	// these are filled out for file-based tools (view/edit)
	Path     string `json:"path"      mapstructure:"path"`
	FileText string `json:"file_text" mapstructure:"file_text"`

	// filled out for tools like bash or powershell
	Command     string `json:"command"     mapstructure:"command"`
	Description string `json:"description" mapstructure:"description"`

	// filled out for skill invocations
	Skill string `json:"skill" mapstructure:"skill"`

	// Extra captures any tool-specific argument keys that aren't part of
	// the fixed fields above (e.g. `query`/`limit` for search tools,
	// MCP-specific payloads). Populated automatically by mapstructure's
	// ",remain" support so argument matchers in tool_calls /
	// tool_constraint graders can see the full argument bag.
	//
	// Excluded from JSON marshaling: callers consuming arguments as a
	// generic map should use graders.normalizeToolCallArgs, which merges
	// Extra into the known fields. Persisting the raw bag in results.json
	// happens through RunResult.ToolEvents instead, which preserves the
	// engine's original argument value verbatim.
	Extra map[string]any `json:"-" mapstructure:",remain"`
}

type ToolCallsGraderParameters added in v0.27.0

type ToolCallsGraderParameters struct {
	RequiredTools  []string `yaml:"required_tools,omitempty" json:"required_tools,omitempty"`
	ForbiddenTools []string `yaml:"forbidden_tools,omitempty" json:"forbidden_tools,omitempty"`
	MinCalls       *int     `yaml:"min_calls,omitempty" json:"min_calls,omitempty"`
	MaxCalls       *int     `yaml:"max_calls,omitempty" json:"max_calls,omitempty"`

	// Expect is an ordered list of tool-call expectations. Each entry names
	// the expected tool and (optionally) structured matchers for argument
	// fields. An expectation passes when there is at least one actual tool
	// call whose name matches and whose arguments satisfy every matcher.
	//
	// Unlike RequiredTools (which only checks names), Expect lets a grader
	// assert input correctness — e.g. "list_dir was called with
	// path matching ^src/".
	Expect []ToolExpectation `yaml:"expect,omitempty" json:"expect,omitempty"`
}

ToolCallsGraderParameters validates which tools were called during a session.

type ToolConstraintGraderParameters

type ToolConstraintGraderParameters struct {
	ExpectTools []ToolSpecParameters `yaml:"expect_tools,omitempty" json:"expect_tools,omitempty"`
	RejectTools []ToolSpecParameters `yaml:"reject_tools,omitempty" json:"reject_tools,omitempty"`
}

type ToolEvent added in v0.38.0

type ToolEvent struct {
	// Turn is the 1-based ordinal of the assistant turn that produced this
	// call. Multiple tool calls may share the same turn. 0 means unknown
	// (engines that do not surface turn boundaries).
	Turn int `json:"turn"`

	// Sequence is the 1-based ordinal of this call within the run, in the
	// order the engine emitted them. Stable across replays.
	Sequence int `json:"sequence"`

	// ToolCallID is the engine's unique identifier for this call. May be
	// empty for engines that do not assign IDs.
	ToolCallID string `json:"tool_call_id,omitempty"`

	// ToolName is the canonical name of the tool that was invoked.
	ToolName string `json:"tool_name"`

	// Args is the call's argument payload normalised to a JSON-compatible
	// value (object, array, scalar, or null). The exact shape depends on
	// the tool; argmatcher matchers in tool_calls / tool_constraint graders
	// run against this field.
	Args any `json:"args,omitempty"`

	// Result is the tool's response payload normalised to a JSON-compatible
	// value, or nil when the engine did not surface a result.
	Result any `json:"result,omitempty"`

	// Success reports whether the engine considered the call to have
	// completed without error.
	Success bool `json:"success"`

	// Error is the engine's failure message when Success is false. Empty
	// for successful calls.
	Error string `json:"error,omitempty"`

	// DurationMs is the wall-clock time between the tool-start and
	// tool-complete events when available. 0 when timing is unavailable.
	DurationMs int64 `json:"duration_ms,omitempty"`
}

ToolEvent is the normalized, engine-agnostic record of a single tool call emitted during an agent session. It is the canonical per-task tool record surfaced in `results.json` under `runs[].tool_events` (schema version 1.1+).

Fields are intentionally aligned with the GenAI OpenTelemetry semantic conventions (see internal/telemetry) so the same record can be exported as a span attribute set without translation:

tool_call_id   <-> gen_ai.tool.call.id
tool_name      <-> gen_ai.tool.name
args           <-> gen_ai.tool.arguments (JSON value)
result         <-> gen_ai.tool.result    (JSON value)
success        <-> waza.tool.success

Wave 3 (#367) snapshot/replay consumes tool_events directly, so the wire format must remain stable: additions are MINOR (1.x), renames/removals are MAJOR (2.0).

type ToolExpectation added in v0.38.0

type ToolExpectation struct {
	// Tool is the expected tool name (matched as a Go regexp against the
	// recorded tool name). A plain string is a substring match anchored by
	// the regexp engine, so use `^foo$` for exact match.
	Tool string `yaml:"tool" json:"tool"`

	// Args holds matcher specs for tool-call argument fields. All matchers
	// must pass for the expectation to be considered satisfied.
	Args map[string]argmatcher.Matcher `yaml:"args,omitempty" json:"args,omitempty"`
}

ToolExpectation defines one entry in ToolCallsGraderParameters.Expect.

type ToolSpecParameters

type ToolSpecParameters struct {
	Tool           string `yaml:"tool" json:"tool"`
	CommandPattern string `yaml:"command_pattern,omitempty" json:"command_pattern,omitempty"`
	SkillPattern   string `yaml:"skill_pattern,omitempty" json:"skill_pattern,omitempty"`
	PathPattern    string `yaml:"path_pattern,omitempty" json:"path_pattern,omitempty"`

	// Args constrains specific argument fields on the tool call using
	// structured matchers (equals / regex / contains / range / json_schema).
	// Keys are argument names as they appear on ToolCall.Arguments after JSON
	// normalisation; values are matcher specs. All matchers must pass for the
	// call to satisfy the spec.
	Args map[string]argmatcher.Matcher `yaml:"args,omitempty" json:"args,omitempty"`
}

type TranscriptEvent

type TranscriptEvent struct {
	copilot.SessionEvent `json:"-"`
}

func (TranscriptEvent) MarshalJSON

func (te TranscriptEvent) MarshalJSON() ([]byte, error)

func (*TranscriptEvent) UnmarshalJSON

func (te *TranscriptEvent) UnmarshalJSON(data []byte) error

type TriggerHeuristicGraderParameters

type TriggerHeuristicGraderParameters struct {
	SkillPath string   `yaml:"skill_path" json:"skill_path"`
	Mode      string   `yaml:"mode" json:"mode"`
	Threshold *float64 `yaml:"threshold,omitempty" json:"threshold,omitempty"`
}

TriggerHeuristicGraderParameters holds the arguments for creating a trigger heuristic grader.

type TriggerMetrics

type TriggerMetrics struct {
	TP        int     `json:"true_positives"`
	FP        int     `json:"false_positives"`
	TN        int     `json:"true_negatives"`
	FN        int     `json:"false_negatives"`
	Errors    int     `json:"errors,omitempty"`
	Precision float64 `json:"precision"`
	Recall    float64 `json:"recall"`
	F1        float64 `json:"f1"`
	Accuracy  float64 `json:"accuracy"`
}

TriggerMetrics holds classification metrics for trigger accuracy.

func ComputeTriggerMetrics

func ComputeTriggerMetrics(results []TriggerResult) *TriggerMetrics

ComputeTriggerMetrics calculates precision, recall, F1, and accuracy from a set of trigger classification results. Results are weighted by confidence: "high" (or empty) counts as 1.0, "medium" as 0.5. Returns nil when results is empty.

type TriggerResult

type TriggerResult struct {
	Prompt        string            `json:"prompt"`
	Confidence    string            `json:"confidence,omitempty"`
	ShouldTrigger bool              `json:"should_trigger"`
	DidTrigger    bool              `json:"did_trigger"`
	ErrorMsg      string            `json:"error_msg,omitempty"`
	FinalOutput   string            `json:"final_output,omitempty"`
	Transcript    []TranscriptEvent `json:"transcript,omitempty"`
	ToolCalls     []ToolCall        `json:"tool_calls,omitempty"`
	SessionID     string            `json:"session_id,omitempty"`
}

TriggerResult pairs an expected trigger label with the actual outcome.

type UsageStats

type UsageStats struct {
	Turns            int                   `json:"turns"`
	InputTokens      int                   `json:"input_tokens"`
	OutputTokens     int                   `json:"output_tokens"`
	CacheReadTokens  int                   `json:"cache_read_tokens"`
	CacheWriteTokens int                   `json:"cache_write_tokens"`
	PremiumRequests  float64               `json:"premium_requests"`
	Provider         string                `json:"provider,omitempty"`
	ProviderHost     string                `json:"provider_host,omitempty"`
	ModelMetrics     map[string]ModelUsage `json:"model_metrics,omitempty"`
}

UsageStats holds token and premium request usage data from a Copilot SDK session.

Provider is empty for the default Copilot MaaS path. When it is "custom", PremiumRequests should be read as custom-provider request count rather than GitHub Copilot premium billing. ProviderHost may contain a sanitized host from the custom provider base URL; it intentionally omits scheme, path, query, and credentials.

func AggregateUsageStats

func AggregateUsageStats(stats []*UsageStats) *UsageStats

AggregateUsageStats sums usage across multiple UsageStats (e.g. across runs). Provider metadata is preserved when all aggregated stats share the same route. If usage spans multiple provider routes, Provider is set to "mixed" so consumers avoid labeling the aggregate as purely Copilot premium or BYOK.

func (*UsageStats) IsZero

func (u *UsageStats) IsZero() bool

IsZero returns true if no usage data has been recorded.

type ValidatorInline

type ValidatorInline struct {
	Identifier string           `yaml:"name" json:"identifier"`
	Kind       GraderKind       `yaml:"type,omitempty" json:"kind,omitempty"`
	Checks     []string         `yaml:"assertions,omitempty" json:"checks,omitempty"`
	Rubric     string           `yaml:"rubric,omitempty" json:"rubric,omitempty"`
	Weight     float64          `yaml:"weight,omitempty" json:"weight,omitempty"`
	Parameters GraderParameters `yaml:"config,omitempty" json:"parameters,omitempty"`
}

ValidatorInline is a validator embedded in a test case

func (*ValidatorInline) EffectiveWeight added in v0.22.0

func (v *ValidatorInline) EffectiveWeight() float64

func (*ValidatorInline) UnmarshalYAML

func (v *ValidatorInline) UnmarshalYAML(node *yaml.Node) error

func (*ValidatorInline) Validate added in v0.26.0

func (v *ValidatorInline) Validate() error

Validate checks that the validator config has required fields for its type.

Jump to

Keyboard shortcuts

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