Skip to content

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

15.9 KB
Raw Blame
package scenario

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

// Validate exists to catch authoring mistakes *before* a sandbox is paid for, so its reject
// cases matter more than the accept case: a scenario that silently asserts nothing produces a
// green run that means nothing.

func valid() Scenario {
	return Scenario{
		ID:     "t-valid",
		Prompt: "run echo {{canary}}",
		Expect: []Expect{{Action: "command.executed", Fields: []string{"command.command"}}},
	}
}

func TestValidScenarioPasses(t *testing.T) {
	if err := valid().Validate(); err != nil {
		t.Fatalf("expected valid, got %v", err)
	}
}

func TestValidateRejectsAuthoringMistakes(t *testing.T) {
	cases := map[string]func(*Scenario){
		"missing id":        func(s *Scenario) { s.ID = "" },
		"whitespace id":     func(s *Scenario) { s.ID = "   " },
		"missing prompt":    func(s *Scenario) { s.Prompt = "" },
		"whitespace prompt": func(s *Scenario) { s.Prompt = "\t\n" },
		"no expectations":   func(s *Scenario) { s.Expect = nil },
		// `expect: []` in YAML decodes to an empty, non-nil slice: a scenario that asserts nothing.
		"empty expectations":    func(s *Scenario) { s.Expect = []Expect{} },
		"expectation no action": func(s *Scenario) { s.Expect = []Expect{{Fields: []string{"a"}}} },
	}
	for name, mutate := range cases {
		s := valid()
		mutate(&s)
		if err := s.Validate(); err == nil {
			t.Errorf("%s: expected a validation error, got nil", name)
		}
	}
}

// A dotted path with an empty segment never resolves, so a typo would make an expectation
// quietly unsatisfiable rather than failing loudly at load time.
func TestValidateRejectsMalformedFieldPaths(t *testing.T) {
	for _, bad := range []string{"", "  ", "command..command", ".command", "command."} {
		s := valid()
		s.Expect[0].Fields = []string{bad}
		err := s.Validate()
		if err == nil {
			t.Errorf("field path %q should be rejected", bad)
			continue
		}
		if !strings.Contains(err.Error(), "malformed field path") {
			t.Errorf("field path %q: error should name the problem, got %v", bad, err)
		}
	}
	// A legitimately nested path must still be accepted.
	s := valid()
	s.Expect[0].Fields = []string{"gen_ai.usage.input_tokens"}
	if err := s.Validate(); err != nil {
		t.Errorf("nested path should be valid, got %v", err)
	}
}

func TestDefaultsAreSane(t *testing.T) {
	var s Scenario
	if got := s.Timeout(); got != 10*time.Minute {
		t.Errorf("default timeout = %v, want 10m", got)
	}
	if got := s.Budget(); got != 1.0 {
		t.Errorf("default budget = %v, want 1.0", got)
	}
	s.TimeoutSeconds = 90
	s.BudgetUSD = 0.25
	if got := s.Timeout(); got != 90*time.Second {
		t.Errorf("explicit timeout = %v, want 90s", got)
	}
	if got := s.Budget(); got != 0.25 {
		t.Errorf("explicit budget = %v, want 0.25", got)
	}
	// A non-positive value must fall back rather than producing a zero budget that would make
	// every session fail instantly.
	s.TimeoutSeconds = -5
	s.BudgetUSD = -1
	if s.Timeout() != 10*time.Minute || s.Budget() != 1.0 {
		t.Errorf("negative values should fall back to defaults, got %v / %v", s.Timeout(), s.Budget())
	}
}

func TestExpandSubstitutesEveryPlaceholder(t *testing.T) {
	got := Expand("marker={{canary}} file={{sentinel}} dir={{workdir}}", "CANARY1", "/tmp/s", "/work")
	want := "marker=CANARY1 file=/tmp/s dir=/work"
	if got != want {
		t.Errorf("Expand = %q, want %q", got, want)
	}
	// Repeated placeholders must all be replaced, since prompts often mention the canary twice.
	if got := Expand("{{canary}} and {{canary}}", "X", "", ""); got != "X and X" {
		t.Errorf("repeated placeholder = %q", got)
	}
	// Unknown placeholders are left alone rather than silently blanked.
	if got := Expand("{{unknown}}", "X", "", ""); got != "{{unknown}}" {
		t.Errorf("unknown placeholder should pass through, got %q", got)
	}
}

func writeScenario(t *testing.T, dir, name, body string) {
	t.Helper()
	if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
		t.Fatal(err)
	}
}

func TestLoadValidatesOnRead(t *testing.T) {
	dir := t.TempDir()
	// Syntactically fine YAML, but asserts nothing.
	writeScenario(t, dir, "bad.yaml", "id: bad\nprompt: hello\n")
	if _, err := Load(filepath.Join(dir, "bad.yaml")); err == nil {
		t.Fatal("Load must validate, not just parse")
	}
	writeScenario(t, dir, "malformed.yaml", "id: [unclosed\n")
	if _, err := Load(filepath.Join(dir, "malformed.yaml")); err == nil {
		t.Fatal("malformed YAML must error")
	}
	if _, err := Load(filepath.Join(dir, "absent.yaml")); err == nil {
		t.Fatal("a missing file must error")
	}
}

func TestLoadRejectsUnknownFields(t *testing.T) {
	const body = `id: strict
prompt: run echo {{canary}}
install:
  mode: user
  verify_uninstall: true
expect:
  - action: command.executed
    fields: [command.command]
    min_count: 2
`
	for _, tc := range []struct {
		name, old, replacement, key string
		line                        int
	}{
		{"scenario", "id: strict\n", "id: strict\npromtp: ignored\n", "promtp", 2},
		{"expectation fields", "fields:", "feilds:", "feilds", 8},
	} {
		t.Run(tc.name, func(t *testing.T) {
			dir := t.TempDir()
			const name = "misspelled.yaml"
			writeScenario(t, dir, name, strings.Replace(body, tc.old, tc.replacement, 1))
			_, err := Load(filepath.Join(dir, name))
			if err == nil {
				t.Fatalf("Load accepted unknown key %q; the intended check may be omitted", tc.key)
			}
			for _, detail := range []string{name, tc.key, fmt.Sprintf("line %d", tc.line)} {
				if !strings.Contains(err.Error(), detail) {
					t.Errorf("Load error %q must identify %q", err, detail)
				}
			}
		})
	}
}

func TestLoadSuiteIsDeterministicallyOrdered(t *testing.T) {
	dir := t.TempDir()
	body := "id: %s\nprompt: p {{canary}}\nexpect:\n  - action: prompt.submitted\n"
	// Written out of order on purpose; suite order must not depend on filesystem order.
	for _, id := range []string{"s03", "s01", "s02"} {
		writeScenario(t, dir, id+".yaml", strings.Replace(body, "%s", id, 1))
	}
	suite, err := LoadSuite(dir)
	if err != nil {
		t.Fatal(err)
	}
	var ids []string
	for _, s := range suite.Scenarios {
		ids = append(ids, s.ID)
	}
	if strings.Join(ids, ",") != "s01,s02,s03" {
		t.Errorf("suite order = %v, want sorted by filename", ids)
	}
}

// An empty directory must error rather than reporting a vacuous pass over zero scenarios.
func TestLoadSuiteRejectsEmptyDirectory(t *testing.T) {
	if _, err := LoadSuite(t.TempDir()); err == nil {
		t.Fatal("an empty suite must error, not silently assert nothing")
	}
}

func TestLoadSuitePropagatesAnInvalidScenario(t *testing.T) {
	dir := t.TempDir()
	writeScenario(t, dir, "ok.yaml", "id: ok\nprompt: p\nexpect:\n  - action: prompt.submitted\n")
	writeScenario(t, dir, "broken.yaml", "id: broken\nprompt: p\n")
	if _, err := LoadSuite(dir); err == nil {
		t.Fatal("one invalid scenario must fail the whole suite load")
	}
}

// Setup is still allowed to build fixtures the agent will act on -- only the sentinel is off
// limits, or every read-style scenario would become unwritable.
func TestSetupMayStillCreateFixtures(t *testing.T) {
	sc := Scenario{
		ID:       "ok",
		Prompt:   "read the fixture and write the answer to {{sentinel}}",
		Sentinel: "/home/agent/work/answer.txt",
		Setup:    "printf 'line {{canary}}\\n' > /home/agent/work/fixture/notes.txt",
		Expect:   []Expect{{Action: "file.read", Why: "the point of the scenario"}},
	}
	if err := sc.Validate(); err != nil {
		t.Errorf("a fixture-building setup must remain valid: %v", err)
	}
}

// The guard must catch every spelling of "setup creates the sentinel", not just the placeholder.
// A first version matched only the literal "{{sentinel}}" string, so a setup writing the real
// path or assembling it from {{workdir}} walked straight past — leaving the same unfalsifiable
// gate the guard exists to prevent. Cursor Bugbot flagged the gap.
func TestSentinelGuardCatchesEverySpelling(t *testing.T) {
	cases := map[string]string{
		"placeholder":      "cp fixture.txt {{sentinel}}",
		"literal path":     "cp fixture.txt /home/agent/work/planted.txt",
		"workdir-relative": "cp fixture.txt {{workdir}}/planted.txt",
		"redirect":         "printf hi > /home/agent/work/planted.txt",
		"touch":            "touch /home/agent/work/planted.txt",
	}
	for name, setup := range cases {
		sc := Scenario{
			ID:       "bad-" + name,
			Prompt:   "do a thing",
			Sentinel: "/home/agent/work/planted.txt",
			Setup:    setup,
			Expect:   []Expect{{Action: "prompt.submitted", Why: "baseline"}},
		}
		err := sc.Validate()
		if err == nil {
			t.Errorf("%s: setup %q plants the sentinel and must be rejected", name, setup)
			continue
		}
		if !strings.Contains(err.Error(), "regardless of what the agent does") {
			t.Errorf("%s: error should explain the unfalsifiability, got: %v", name, err)
		}
	}
}

// The basename check has to respect path boundaries. A bare substring test rejected valid setups:
// a sentinel named out.txt matched a fixture called timeout.txt, so a legitimate scenario could
// not be written at all. Cursor Bugbot caught the false positive.
func TestSentinelBasenameMatchRespectsPathBoundaries(t *testing.T) {
	valid := map[string]string{
		"longer name":       "printf hi > /home/agent/work/timeout.txt",
		"different prefix":  "printf hi > /home/agent/work/layout.txt",
		"suffixed":          "printf hi > /home/agent/work/out.txt.bak",
		"embedded in a dir": "mkdir -p /home/agent/work/out.txt.d",
	}
	for name, setup := range valid {
		sc := Scenario{
			ID: "ok-" + name, Prompt: "write to {{sentinel}}",
			Sentinel: "/home/agent/work/out.txt", Setup: setup,
			Expect: []Expect{{Action: "file.modified", Why: "the point"}},
		}
		if err := sc.Validate(); err != nil {
			t.Errorf("%s: setup %q does not plant out.txt and must be allowed: %v", name, setup, err)
		}
	}

	// The real thing must still be caught, by any spelling.
	planting := map[string]string{
		"exact basename": "printf hi > /home/agent/work/out.txt",
		"workdir form":   "printf hi > {{workdir}}/out.txt",
		"quoted":         "cp fixture 'out.txt'",
	}
	for name, setup := range planting {
		sc := Scenario{
			ID: "bad-" + name, Prompt: "write to {{sentinel}}",
			Sentinel: "/home/agent/work/out.txt", Setup: setup,
			Expect: []Expect{{Action: "file.modified", Why: "the point"}},
		}
		if err := sc.Validate(); err == nil {
			t.Errorf("%s: setup %q plants the sentinel and must be rejected", name, setup)
		}
	}
}

// An install scenario reaches the guest as CLI flags, so a typo would fail mid-run after a
// sandbox has already been paid for. Validate catches it while it is still free.
func TestInstallModeAndServiceAreValidated(t *testing.T) {
	base := func(in *Install) Scenario {
		return Scenario{ID: "i", Prompt: "do a thing", Install: in,
			Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}}}
	}
	for _, in := range []*Install{
		{Mode: "systemwide"},
		{Mode: "root"},
		{Service: "launchd2"},
		{Service: "upstart"},
	} {
		if err := base(in).Validate(); err == nil {
			t.Errorf("install %+v must be rejected", in)
		}
	}
	// Every documented spelling must be accepted, including the empty auto-detect default.
	for _, in := range []*Install{
		{},
		{Mode: "user"},
		{Mode: "system", Service: "systemd"},
		{Service: "none"},
		{Service: "auto"},
		{Mode: "user", Service: "launchd", ExpectStatusRunning: true},
	} {
		if err := base(in).Validate(); err != nil {
			t.Errorf("install %+v must be accepted: %v", in, err)
		}
	}
}

// A POSIX sentinel in a Windows scenario is the mistake hardest to notice at runtime: the agent
// writes somewhere, the probe looks somewhere else, and the run reports the agent idle rather
// than the scenario being wrong. So it is rejected at authoring time, before a runner is spent.
func TestWindowsScenariosRejectPosixSentinelsAndSystemd(t *testing.T) {
	base := func(mutate func(*Scenario)) Scenario {
		s := Scenario{ID: "w", Platform: PlatformWindows, Prompt: "do a thing",
			Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}}}
		mutate(&s)
		return s
	}
	if err := base(func(s *Scenario) { s.Sentinel = "/home/agent/work/out.txt" }).Validate(); err == nil {
		t.Error("a POSIX absolute sentinel must be rejected in a windows scenario")
	}
	if err := base(func(s *Scenario) {
		s.Install = &Install{Mode: "system", NeedsRealSystemd: true}
	}).Validate(); err == nil {
		t.Error("needs_real_systemd must be rejected in a windows scenario")
	}
	// The spellings a Windows scenario legitimately uses.
	for _, sentinel := range []string{`{{workdir}}\out.txt`, `C:\work\out.txt`} {
		if err := base(func(s *Scenario) { s.Sentinel = sentinel }).Validate(); err != nil {
			t.Errorf("sentinel %q must be accepted: %v", sentinel, err)
		}
	}
	// An unknown platform is a typo, and a typo that defaulted to linux would run a Windows
	// scenario's PowerShell prompt against bash.
	if err := (Scenario{ID: "w", Platform: "win32", Prompt: "x",
		Expect: []Expect{{Action: "a", Why: "b"}}}).Validate(); err == nil {
		t.Error("an unrecognized platform must be rejected rather than defaulting")
	}
}

// The suite loader must report what it set aside. `run` with no --scenario is the "everything"
// command, so returning a subset of it silently would read as full coverage.
func TestSuiteForReportsWhatItSkipped(t *testing.T) {
	suite := Suite{Scenarios: []Scenario{
		{ID: "s01"},
		{ID: "w00", Platform: PlatformWindows},
		{ID: "s02", Platform: PlatformLinux},
	}}

	linux, skipped := suite.For(PlatformLinux)
	if len(linux.Scenarios) != 2 || skipped != 1 {
		t.Errorf("linux: got %d scenarios and %d skipped, want 2 and 1", len(linux.Scenarios), skipped)
	}
	win, skipped := suite.For(PlatformWindows)
	if len(win.Scenarios) != 1 || skipped != 2 {
		t.Errorf("windows: got %d scenarios and %d skipped, want 1 and 2", len(win.Scenarios), skipped)
	}
	if win.Scenarios[0].ID != "w00" {
		t.Errorf("wrong scenario selected: %q", win.Scenarios[0].ID)
	}
}

// A systemd requirement combined with the supervised backend, or without system mode, would
// silently exercise something other than what the scenario claims — and the run would pass,
// reporting coverage it does not have.
func TestNeedsRealSystemdRejectsContradictions(t *testing.T) {
	base := func(in *Install) Scenario {
		return Scenario{ID: "i", Prompt: "do a thing", Install: in,
			Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}}}
	}
	contradictory := []*Install{
		{NeedsRealSystemd: true, Mode: "system", Service: "none"},
		{NeedsRealSystemd: true, Mode: "user", Service: "systemd"},
		{NeedsRealSystemd: true}, // mode defaults to user
	}
	for _, in := range contradictory {
		if err := base(in).Validate(); err == nil {
			t.Errorf("%+v is contradictory and must be rejected", in)
		}
	}
	// The coherent combination must be accepted.
	if err := base(&Install{NeedsRealSystemd: true, Mode: "system", Service: "systemd"}).Validate(); err != nil {
		t.Errorf("system+systemd is the intended combination: %v", err)
	}
}

// The forwarding probe runs Vector by hand as the agent user against the user-mode log and secrets
// file, so it only means something in that arrangement.
func TestVerifyVectorForwardingRejectsArrangementsTheProbeCannotRun(t *testing.T) {
	base := func(in *Install) Scenario {
		return Scenario{ID: "i", Prompt: "do a thing", Install: in,
			Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}}}
	}
	for _, in := range []*Install{
		{VerifyVectorForwarding: true, Mode: "system", Service: "none"},
		{VerifyVectorForwarding: true, NeedsRealSystemd: true, Mode: "system", Service: "systemd"},
	} {
		if err := base(in).Validate(); err == nil {
			t.Errorf("%+v cannot run the forwarding probe and must be rejected", in)
		}
	}
	win := base(&Install{VerifyVectorForwarding: true, Mode: "user", Service: "none"})
	win.Platform = PlatformWindows
	if err := win.Validate(); err == nil {
		t.Error("a Windows scenario has no bundled Vector and must be rejected")
	}
	ok := base(&Install{VerifyVectorForwarding: true, Mode: "user", Service: "none"})
	if err := ok.Validate(); err != nil {
		t.Errorf("user mode with no service manager is the intended arrangement: %v", err)
	}
	if !ok.VerifiesVectorForwarding() {
		t.Error("VerifiesVectorForwarding should report the request")
	}
}