contract

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

Documentation

Overview

Package contract compiles a spec.SkillSpec into a behavioural contract of deterministic matchers. A later scoring stage checks an agent's normalized trajectory against the contract; this package never reads a trajectory or scores one, it only compiles the expectations.

The invariant every matcher in a compiled Contract must satisfy: it can be checked against a normalized trajectory.Event. Anything that cannot — a tone requirement, an unobservable step — is demoted to a judge-scored SemanticRule instead. A step matcher nothing can ever satisfy would score every run as a step failure, which reads as a badly-behaved skill rather than what it actually is: a compiler defect.

Index

Constants

View Source
const Version = 1

Version is the current Contract schema version.

Variables

View Source
var ErrBadCandidate = errors.New("contract: unusable candidate")

ErrBadCandidate wraps every error MatchPath returns because candidate is unusable — an absolute path, a backslash-separated one — while pattern itself is fine. This is a recording defect, not a compiler defect: a caller should count the check as unevaluable and keep scoring the rest of the trajectory.

View Source
var ErrBadPattern = errors.New("contract: malformed pattern")

ErrBadPattern wraps every error MatchPath returns because pattern itself is malformed — a compiler defect. A caller must stop scoring rather than continue around it: the compiled contract cannot be trusted for any candidate once one of its patterns is invalid.

Functions

func MatchPath

func MatchPath(pattern, candidate string) (bool, error)

MatchPath reports whether candidate satisfies pattern, under the small glob dialect every Matcher.PathGlob and Matcher.PathNotGlob value in this package is written in. Consumers evaluating a compiled Contract against a trajectory must call MatchPath rather than path/filepath.Match directly: Go's standard library treats "**" as two ordinary, non-recursive stars — neither crosses a "/" — so filepath.Match("out/**", "out/sub/file.csv") returns false. A forbid rule meaning "nothing outside out/" compiled to PathNotGlob "out/**" would then flag a legitimate nested write as a violation. MatchPath defines "/**" to mean "any path under here, at any depth" instead.

The full dialect, every behaviour it commits to, and the reasoning behind each — so that a caller can predict MatchPath's result for any input from this comment alone, without reading the implementation:

  • A trailing "/**" matches recursively, at any depth: "out/**" matches "out/tables.csv", "out/tables/q1.csv", and "out/a/b/c.csv" alike.
  • "out/**" does NOT match the bare directory "out" itself. "/**" names what is inside a directory, not the directory. A rule that must also forbid the bare directory has to say so with a second, explicit pattern — this keeps "**" meaning exactly one thing.
  • A single "*" keeps its ordinary, non-recursive meaning and never crosses a "/": "out/*" matches "out/tables.csv" but not "out/tables/q1.csv". Only a trailing "/**" is recursive; a bare "*" is not made recursive by this package.
  • "**" is only meaningful as a whole path segment, and only as the pattern's final segment, immediately after a "/". Any other use — "a/**/b", "**/a", "a**b", a bare "**" with no preceding segment — is a malformed pattern and returns an error. A malformed pattern must not silently return false: a forbid rule that silently never matches is the inert-rule problem in a new disguise.
  • pattern is matched segment-wise exactly as written: unlike candidate, it is never passed through path.Clean. A ".." segment in pattern is therefore rejected as malformed, with its own distinct error, rather than compared literally against a candidate that path.Clean will essentially never render as a literal "..": a pattern segment of ".." would otherwise never match anything, permanently and silently — the same inert-rule failure the candidate-side normalization exists to prevent, just relocated to the other argument. Patterns are produced by this package's own compiler, not by comparing untrusted text, so this is a defensive rejection of a compiler bug, not a security boundary the way the candidate-side checks are.
  • candidate is lexically normalized with path.Clean before matching, so "." and ".." segments are resolved rather than compared literally: a leading "./" is stripped ("./out/x.csv" behaves as "out/x.csv"), and "out/../etc/passwd" is recognised as "etc/passwd" — outside out/, not inside it. Without this, a MUST-NOT scoped to "out/" would let a traversal write escape undetected: the worse of the two directions this package can get wrong, since a missed violation looks like a clean run rather than a run worth investigating. A path that still escapes its own relative root after normalizing — "../x", "out/../../x" — can never satisfy a relative pattern, so MatchPath reports no match: a MUST-NOT scoped to a subdirectory correctly flags it, and a MUST/step matcher correctly refuses to count it as done.
  • The dialect is POSIX ("/"-separated) only. A pattern or candidate containing a literal backslash is a reported error, never a silent false: this repository cross-compiles for windows/amd64, and a Windows-recorded trajectory's "\"-separated paths would otherwise fail every path rule silently — every forbid rule inert, every path step unsatisfied, and the resulting score merely wrong rather than visibly broken. Whichever component records or replays a Windows trajectory is responsible for converting to "/" first.
  • An absolute pattern ("/out/**") is a reported error, for the same reason a ".." segment is: every pattern this package compiles is workspace-relative, so an absolute one can never match any candidate. Silently returning false would make the rule inert — every write allowed, or every step unsatisfied — and look like a badly-behaved skill rather than a compiler bug.
  • An absolute candidate ("/etc/passwd") is a reported error, not a quiet false. Every path this package's compiled patterns describe is workspace-relative, so an absolute candidate reaching MatchPath means something upstream already lost the workspace root; silently comparing it against a relative pattern would almost always report "no match" for the wrong reason — worth surfacing loudly rather than folding into the same "false" a legitimate out-of-scope path returns.
  • An empty pattern matches only a candidate that normalizes to the empty string — which none do, since path.Clean("") is "." and path.Clean never produces "" for any input. So in practice MatchPath("", candidate) is false for every candidate MatchPath accepts, including MatchPath("", ""). An empty candidate normalizes to "." (the current directory) and matches only a pattern that itself resolves to exactly ".".
  • Single-segment matching — the plain (non-"/**") case, and each fixed prefix segment of a recursive pattern — is filepath.Match underneath, unchanged. Its metacharacters ("*", "?", and a "[...]" character class) stay live in every segment. A pattern segment containing a literal "[" or "]" is parsed as a character class, not a literal bracket, so a real path segment containing the same literal bracket text will not match it unless the shapes coincide by accident (e.g. pattern segment "a.b[1]" matches path segment "a.b1", not "a.b[1]"). This is inherited from filepath.Match unchanged, not something this package attempts to fix.

Types

type Contract

type Contract struct {
	Version     int            `yaml:"version" json:"version"`
	Steps       []StepMatch    `yaml:"steps,omitempty" json:"steps,omitempty"`
	Forbid      []ForbidMatch  `yaml:"forbid,omitempty" json:"forbid,omitempty"`
	Checkpoints []string       `yaml:"checkpoints,omitempty" json:"checkpoints,omitempty"`
	Semantic    []SemanticRule `yaml:"semantic,omitempty" json:"semantic,omitempty"`
}

Contract is the compiled behavioural contract for one skill.

func Compile

func Compile(s *spec.SkillSpec) (*Contract, error)

Compile builds a Contract from a spec.SkillSpec.

Every emitted StepMatch and ForbidMatch is checkable against a normalized trajectory.Event. A step or constraint that has no deterministic check is demoted to a SemanticRule rather than emitted as a matcher: a matcher nothing can ever satisfy would score every run as a step failure.

A MUST-NOT constraint may become a ForbidMatch; a MUST constraint may become a StepMatch when its text names an observable action, reusing the same classification as a step (a positive obligation is otherwise just as deterministically checkable as a step's action) — both share the ID space of an emitted matcher. Every ID Compile emits (across Steps, Forbid, and Semantic together) must therefore be unique in the whole compiled Contract: a spec whose constraint ID collides with a step ID (or with another constraint's ID) is a compile error rather than a silent merge or overwrite, since a later report keyed by ID could otherwise attribute a violation to the wrong rule.

func Load

func Load(r io.Reader) (*Contract, error)

Load parses a Contract from YAML. Unknown fields are an error: a contract with a misspelled key would otherwise silently lose whatever that key described.

func (*Contract) Save

func (c *Contract) Save(w io.Writer) error

Save writes the contract as block-style YAML with two-space indentation.

type ForbidMatch

type ForbidMatch struct {
	ID       string        `yaml:"id" json:"id"`
	Desc     string        `yaml:"desc,omitempty" json:"desc,omitempty"`
	Match    Matcher       `yaml:"match" json:"match"`
	Severity spec.Severity `yaml:"severity" json:"severity"`
}

ForbidMatch is a deterministic check for one spec.Rule of kind spec.RuleMustNot. Its presence in the trajectory is a violation.

type Matcher

type Matcher struct {
	Type        trajectory.EventType `yaml:"type" json:"type"`
	Pattern     string               `yaml:"pattern,omitempty" json:"pattern,omitempty"`
	PathGlob    string               `yaml:"path_glob,omitempty" json:"path_glob,omitempty"`
	PathNotGlob string               `yaml:"path_not_glob,omitempty" json:"path_not_glob,omitempty"`
}

Matcher describes one observable event a trajectory must (or must not) contain. Type is always one trajectory.EventType that the scorer can check against a normalized event; Pattern is a regular expression matched against the event's command or name, and PathGlob/PathNotGlob constrain the event's paths.

PathGlob and PathNotGlob are written in this package's own glob dialect — notably, a trailing "/**" means "at any depth", unlike path/filepath's standard-library "**". A consumer must test a path against them with MatchPath, not filepath.Match; see MatchPath's doc comment for the exact semantics.

type Order

type Order struct {
	Mode  string   `yaml:"mode" json:"mode"`
	After []string `yaml:"after,omitempty" json:"after,omitempty"`
}

Order constrains where in the trajectory a step's matching event may fall. Mode is one of "any" (no constraint), "after" (must occur after the listed step IDs, in any relative order among themselves), or "strict" (must occur immediately after them, in that order).

type SemanticRule

type SemanticRule struct {
	ID   string `yaml:"id" json:"id"`
	Text string `yaml:"text" json:"text"`
}

SemanticRule is a requirement with no deterministic check — a step or constraint that cannot be verified against a normalized event. It is scored by an LLM judge rather than the deterministic matcher path.

type StepMatch

type StepMatch struct {
	ID       string  `yaml:"id" json:"id"`
	Desc     string  `yaml:"desc,omitempty" json:"desc,omitempty"`
	Match    Matcher `yaml:"match" json:"match"`
	Order    Order   `yaml:"order" json:"order"`
	Required bool    `yaml:"required,omitempty" json:"required,omitempty"`
}

StepMatch is a deterministic check for one spec.Step.

Jump to

Keyboard shortcuts

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