Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

1.8 KB
Raw Blame
package threatrules

import "fmt"

// FixtureResult is the outcome of running one fixture through an evaluator.
type FixtureResult struct {
	RuleID   string
	Fixture  string
	Expected Verdict
	Actual   Verdict
	Err      error
}

// OK reports whether the fixture produced its declared verdict without error.
func (r FixtureResult) OK() bool {
	return r.Err == nil && r.Actual == r.Expected
}

func (r FixtureResult) String() string {
	if r.Err != nil {
		return fmt.Sprintf("%s/%s: error: %v", r.RuleID, r.Fixture, r.Err)
	}
	return fmt.Sprintf("%s/%s: expected %s, got %s", r.RuleID, r.Fixture, r.Expected, r.Actual)
}

// CheckRule validates a rule, enforces its maturity gate, compiles it, and runs every
// embedded fixture. It returns one FixtureResult per fixture (in declaration order). A
// non-nil error is a rule-level failure (invalid rule, maturity-gate violation, or
// compile error) that prevents fixtures from running; in that case the results slice is
// nil.
//
// This is the engine-agnostic core of the conformance harness: a test wrapper turns each
// FixtureResult into a subtest assertion, but the logic here has no test dependency so it
// can also back a CLI lint command later.
func CheckRule(rule *Rule) (results []FixtureResult, err error) {
	if err := rule.Validate(); err != nil {
		return nil, fmt.Errorf("rule %q: %w", rule.ID, err)
	}
	if err := CheckMaturity(rule); err != nil {
		return nil, err
	}
	compiled, err := Compile(rule)
	if err != nil {
		return nil, fmt.Errorf("rule %q: compile: %w", rule.ID, err)
	}
	for _, f := range rule.Tests {
		res := FixtureResult{RuleID: rule.ID, Fixture: f.Name, Expected: f.Verdict}
		actual, evalErr := compiled.Evaluate(f.EventList())
		if evalErr != nil {
			res.Err = evalErr
		} else {
			res.Actual = actual
		}
		results = append(results, res)
	}
	return results, nil
}