cmd/teststamp/main.go
// Command teststamp lets the justfile skip a self-contained AgentHub test
// target whose inputs match the committed stamp from its last passing run.
//
// A stamp replaces only `go test` of one package whose test binary is built
// entirely from AgentHub code plus a short allowlist, or one corpus checker
// script. It never stands in for cross-package, non-hub or Python tests.
//
// teststamp go-test -stamps FILE -hub REGEX [-timeout D] [-refresh] [-plan] PACKAGE...
// teststamp go-bypass -stamps FILE -packages LIST [GO-TEST-FLAG...]
// teststamp ruby -stamps FILE -ruby PATH -tree DIR [-refresh] SCRIPT
// teststamp hash -hub REGEX [-stamps FILE] PACKAGE...
//
// go-test runs every named package that is stale, unstamped or ineligible in
// one `go test` invocation, then records the packages that passed. -refresh,
// or a non-empty EZ_AGENT_HUB_DEEP, runs everything and records the passes.
// An eligible package whose own Go files read an environment variable that
// is set, other than EZ_AGENT_HUB_DEEP, runs without recording.
package main
import (
"bufio"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
)
func main() {
if len(os.Args) < 2 {
usage(os.Stderr)
os.Exit(2)
}
var code int
switch os.Args[1] {
case "go-test":
code = cmdGoTest(os.Args[2:], os.Stdout, os.Stderr)
case "go-bypass":
code = cmdGoBypass(os.Args[2:], os.Stdout, os.Stderr)
case "ruby":
code = cmdRuby(os.Args[2:], os.Stdout, os.Stderr)
case "hash":
code = cmdHash(os.Args[2:], os.Stdout, os.Stderr)
default:
usage(os.Stderr)
code = 2
}
os.Exit(code)
}
func usage(w io.Writer) {
fmt.Fprintln(w, "usage: teststamp go-test|go-bypass|ruby|hash [flags] ARGS...")
}
func fail(stderr io.Writer, err error) int {
fmt.Fprintf(stderr, "teststamp: %v\n", err)
return 1
}
func cmdGoTest(args []string, stdout, stderr io.Writer) int {
flags := flag.NewFlagSet("go-test", flag.ContinueOnError)
flags.SetOutput(stderr)
stampPath := flags.String("stamps", "", "stamp file")
hub := flags.String("hub", "", "regexp selecting AgentHub import paths")
timeout := flags.String("timeout", "30m", "go test -timeout")
refreshFlag := flags.Bool("refresh", false, "run every package and record passes")
planOnly := flags.Bool("plan", false, "print which packages would run, be skipped and be recorded, then stop")
if err := flags.Parse(args); err != nil {
return 2
}
refresh, refreshWhy := refreshMode(*refreshFlag, os.Getenv("EZ_AGENT_HUB_DEEP"))
if *stampPath == "" || flags.NArg() == 0 {
fmt.Fprintln(stderr, "teststamp go-test: -stamps and at least one package are required")
return 2
}
pol, err := defaultPolicy(*hub)
if err != nil {
return fail(stderr, err)
}
ws, err := openWorkspace(".")
if err != nil {
return fail(stderr, err)
}
targets, err := ws.analyze(pol, flags.Args())
if err != nil {
return fail(stderr, err)
}
stamps, err := readStampFile(*stampPath)
if err != nil {
return fail(stderr, err)
}
var skipped, stale, ineligible, profiled []target
var run []string
others := 0
for _, t := range targets {
switch {
case !t.Hub:
others++
case !t.Eligible:
ineligible = append(ineligible, t)
case len(profileEnv(t, os.Getenv)) > 0:
profiled = append(profiled, t)
case !refresh && stamps.stamps["go "+t.Rel].Closure == t.Closure:
skipped = append(skipped, t)
continue
default:
stale = append(stale, t)
}
run = append(run, t.ImportPath)
}
fmt.Fprintf(stdout, "== Test stamps (%s) ==\n", *stampPath)
if refresh {
fmt.Fprintf(stdout, "refresh (%s): stamps ignored; every package runs and passes are recorded\n", refreshWhy)
}
if stamps.invalid != "" {
fmt.Fprintf(stdout, "stamp file discarded (%s): it holds no stamps, every target runs, and this run rewrites it\n", stamps.invalid)
}
fmt.Fprintf(stdout, "NOT RUN in this run, skipped by stamp (last passed at these exact inputs): %d package(s)\n", len(skipped))
for _, t := range skipped {
fmt.Fprintf(stdout, " skipped by stamp: %s\n", t.Rel)
}
if len(ineligible) > 0 {
fmt.Fprintf(stdout, "always run, not stamp-eligible: %d AgentHub package(s)\n", len(ineligible))
for _, t := range ineligible {
fmt.Fprintf(stdout, " %s (%s)\n", t.Rel, t.Reason)
}
}
if len(profiled) > 0 {
fmt.Fprintf(stdout, "run without stamps, their tests read a set environment variable (a pass is not recorded; a FAIL marks the stamp failed): %d package(s)\n", len(profiled))
for _, t := range profiled {
fmt.Fprintf(stdout, " %s (%s)\n", t.Rel, strings.Join(profileEnv(t, os.Getenv), ", "))
}
}
reason := "without a matching stamp"
if refresh {
reason = "refreshing"
}
fmt.Fprintf(stdout, "running %d package(s): %d stamp-eligible %s, %d ineligible AgentHub, %d without stamps by environment, %d other\n",
len(run), len(stale), reason, len(ineligible), len(profiled), others)
if *planOnly {
recordable := strings.Join(rels(stale), " ")
if recordable == "" {
recordable = "(none)"
}
fmt.Fprintf(stdout, "plan only (-plan): go test was not started and %s was not changed; it would record passes of: %s\n",
*stampPath, recordable)
return 0
}
if len(run) == 0 {
fmt.Fprintln(stdout, "no packages to run; nothing was tested in this run")
return 0
}
// Invalidate stamps that still match before running, so a refresh that
// fails, is interrupted or yields no result leaves nothing to match.
pending := map[string]*stamp{}
for _, t := range stale {
if old, ok := stamps.stamps["go "+t.Rel]; ok && old.Closure == t.Closure {
old.Closure = failedMark
pending[old.key()] = &old
}
}
if len(pending) > 0 {
if err := applyUpdates(*stampPath, pending); err != nil {
return fail(stderr, err)
}
}
results, code, err := runGoTest(ws.root, append([]string{"test", "-timeout=" + *timeout}, run...), stdout, stderr)
if err != nil {
return fail(stderr, err)
}
updates, trials, passed, failed := recordResults(stale, stamps.stamps, results)
// Ineligible packages and removed package directories keep no stamp.
for _, t := range ineligible {
updates["go "+t.Rel] = nil
}
for key, s := range stamps.stamps {
if s.Kind == "go" {
if _, err := os.Stat(filepath.Join(ws.root, filepath.FromSlash(s.Path))); errors.Is(err, os.ErrNotExist) {
updates[key] = nil
}
}
}
if err := applyUpdates(*stampPath, updates); err != nil {
return fail(stderr, err)
}
// Packages run because of the environment are treated as a bypass: only
// a reported FAIL changes their stamp.
profiledResults := map[string]bool{}
for _, t := range profiled {
if ok, has := results[t.ImportPath]; has {
profiledResults[t.ImportPath] = ok
}
}
if err := markFailed(*stampPath, ws, profiledResults, stderr); err != nil {
return fail(stderr, err)
}
fmt.Fprintf(stdout, "== Test stamps: recorded %d passed package(s); %d failed package(s) left stale; %d package(s) run without stamps by environment were not recorded; %d package(s) skipped by stamp were NOT run ==\n",
passed, failed, len(profiled), len(skipped))
for _, line := range trials {
fmt.Fprintln(stdout, line)
}
return code
}
// profileEnv returns the variables t's own Go files read that are set to a
// non-empty value. Such a variable can enable tests that the recorded stamp
// did not cover, so the package runs and its pass is not recorded.
// EZ_AGENT_HUB_DEEP is excluded: it selects refresh, whose passes record.
func profileEnv(t target, getenv func(string) string) []string {
var set []string
for _, name := range t.Env {
if name != "EZ_AGENT_HUB_DEEP" && getenv(name) != "" {
set = append(set, name)
}
}
return set
}
func rels(targets []target) []string {
out := make([]string, 0, len(targets))
for _, t := range targets {
out = append(out, t.Rel)
}
return out
}
// refreshMode reports whether every eligible package runs and records its
// pass. EZ_AGENT_HUB_DEEP un-skips tests a default-profile stamp never ran;
// the deep profile is a superset of the default one, so its passes may be
// recorded.
func refreshMode(flag bool, deep string) (bool, string) {
switch {
case flag:
return true, "-refresh"
case deep != "":
return true, "EZ_AGENT_HUB_DEEP is set"
}
return false, ""
}
// recordResults computes the stamp updates for the eligible packages that
// ran. A pass records the current digests. A failure, or a package without a
// result, leaves no matching stamp: an existing line keeps its trial
// counters but its closure becomes failedMark, and a missing line stays
// missing. A wrap trial is a run whose closure changed from the last passing
// one while its own files did not; a run after a failure is not a trial.
func recordResults(ran []target, old map[string]stamp, results map[string]bool) (updates map[string]*stamp, trials []string, passed, failed int) {
updates = map[string]*stamp{}
for _, t := range ran {
key := "go " + t.Rel
prev, had := old[key]
ok := results[t.ImportPath]
next := stamp{Kind: "go", Path: t.Rel, Closure: t.Closure, Own: t.Own, Trials: prev.Trials, Failures: prev.Failures}
if ok {
passed++
} else {
failed++
if !had {
continue
}
next.Closure, next.Own = failedMark, prev.Own
}
if had && prev.Closure != failedMark && prev.Closure != t.Closure && prev.Own == t.Own {
next.Trials++
outcome := "passed"
if !ok {
next.Failures++
outcome = "FAILED"
}
trials = append(trials, fmt.Sprintf("wrap trial: %s %s with its own files unchanged (cumulative trials=%d failures=%d)",
t.Rel, outcome, next.Trials, next.Failures))
}
updates[key] = &next
}
return updates, trials, passed, failed
}
// applyUpdates re-reads the stamp file so writers of other lines between our
// read and this write are kept, then sets or (for nil) removes the given keys.
// It does not lock. Two writers in one checkout can still lose an update in
// the short window between this re-read and the rename. Losing a newly
// recorded pass only makes that target run again. Losing a failure mark from
// a concurrent refresh could restore an older matching line, so run at most
// one stamped recipe per checkout at a time.
func applyUpdates(path string, updates map[string]*stamp) error {
f, err := readStampFile(path)
if err != nil {
return err
}
for key, s := range updates {
if s == nil {
delete(f.stamps, key)
} else {
f.stamps[key] = *s
}
}
return f.write()
}
var statusLine = regexp.MustCompile(`^(ok|FAIL|\?)\s+(\S+)`)
// parseStatus reads a go test package summary line, in text or -json form.
func parseStatus(line string) (pkg string, passed, matched bool) {
if strings.HasPrefix(line, "{") {
var event struct{ Action, Package, Test string }
if json.Unmarshal([]byte(line), &event) != nil || event.Test != "" || event.Package == "" {
return "", false, false
}
switch event.Action {
case "pass", "skip":
return event.Package, true, true
case "fail":
return event.Package, false, true
}
return "", false, false
}
m := statusLine.FindStringSubmatch(line)
if m == nil {
return "", false, false
}
return m[2], m[1] != "FAIL", true
}
// runGoTest streams go test output and returns which packages passed. A
// package without a passing summary line counts as failed.
func runGoTest(dir string, args []string, stdout, stderr io.Writer) (map[string]bool, int, error) {
cmd := exec.Command("go", args...)
cmd.Dir = dir
cmd.Stderr = stderr
pipe, err := cmd.StdoutPipe()
if err != nil {
return nil, 0, err
}
if err := cmd.Start(); err != nil {
return nil, 0, err
}
results := map[string]bool{}
failedSeen := map[string]bool{}
reader := bufio.NewReader(pipe)
for {
line, readErr := reader.ReadString('\n')
if line != "" {
io.WriteString(stdout, line)
if pkg, ok, matched := parseStatus(strings.TrimRight(line, "\n")); matched {
if !ok {
failedSeen[pkg] = true
}
results[pkg] = ok && !failedSeen[pkg]
}
}
if readErr != nil {
break
}
}
return results, exitCode(cmd.Wait()), nil
}
// cmdGoBypass runs `go test` with caller-chosen flags, such as -run, -race or
// -count, whose results say nothing about the default profile a stamp
// records. Output and exit status are go test's own. It never records a pass.
// It marks failed only the stamped packages that reported FAIL. A package
// with no result keeps its stamp: the run may have been interrupted, or a
// flag such as -run or -failfast may have kept it from running, and that is
// no evidence against the stamp. Invalidating every stamp up front instead
// would make each spot test cost a full re-run afterwards.
func cmdGoBypass(args []string, stdout, stderr io.Writer) int {
flags := flag.NewFlagSet("go-bypass", flag.ContinueOnError)
flags.SetOutput(stderr)
stampPath := flags.String("stamps", "", "stamp file")
packages := flags.String("packages", "", "whitespace-separated packages, appended after the go test flags")
if err := flags.Parse(args); err != nil {
return 2
}
if *stampPath == "" || strings.TrimSpace(*packages) == "" {
fmt.Fprintln(stderr, "teststamp go-bypass: -stamps and -packages are required")
return 2
}
ws, err := openWorkspace(".")
if err != nil {
return fail(stderr, err)
}
goArgs := append(append([]string{"test"}, flags.Args()...), strings.Fields(*packages)...)
results, code, err := runGoTest(ws.root, goArgs, stdout, stderr)
if err != nil {
return fail(stderr, err)
}
if code != 0 {
if err := markFailed(*stampPath, ws, results, stderr); err != nil {
fmt.Fprintf(stderr, "teststamp: marking failed stamps: %v\n", err)
}
}
return code
}
// markFailed sets closure=failed, keeping the trial counters, on each stamped
// package whose result is a failure, and reports them on stderr.
func markFailed(path string, ws *workspace, results map[string]bool, stderr io.Writer) error {
stamps, err := readStampFile(path)
if err != nil {
return err
}
updates := map[string]*stamp{}
var marked []string
for importPath, passed := range results {
rel := ws.relImport(importPath)
if old, ok := stamps.stamps["go "+rel]; ok && !passed && old.Closure != failedMark {
old.Closure = failedMark
updates[old.key()] = &old
marked = append(marked, rel)
}
}
if len(updates) == 0 {
return nil
}
if err := applyUpdates(path, updates); err != nil {
return err
}
sort.Strings(marked)
fmt.Fprintf(stderr, "teststamp: marked failed in %s, so they run next time: %s\n", path, strings.Join(marked, " "))
return nil
}
func exitCode(err error) int {
var exit *exec.ExitError
switch {
case err == nil:
return 0
case errors.As(err, &exit) && exit.ExitCode() > 0:
return exit.ExitCode()
default:
return 1
}
}
func cmdRuby(args []string, stdout, stderr io.Writer) int {
flags := flag.NewFlagSet("ruby", flag.ContinueOnError)
flags.SetOutput(stderr)
stampPath := flags.String("stamps", "", "stamp file")
ruby := flags.String("ruby", "", "fallback Ruby interpreter when the checkout has no build/ez-agent-ruby")
tree := flags.String("tree", "", "directory holding the script and every file it reads")
refresh := flags.Bool("refresh", false, "run and record a pass regardless of the stamp")
if err := flags.Parse(args); err != nil {
return 2
}
if *stampPath == "" || *ruby == "" || *tree == "" || flags.NArg() != 1 {
fmt.Fprintln(stderr, "teststamp ruby: -stamps, -ruby, -tree and one script are required")
return 2
}
script := flags.Arg(0)
ws, err := openWorkspace(".")
if err != nil {
return fail(stderr, err)
}
scriptRel, ok := ws.rel(absPath(script))
if !ok {
return fail(stderr, errors.New("script must be inside the repository"))
}
key := "ruby " + scriptRel
run := func(interpreter string) int {
cmd := exec.Command(interpreter, script)
cmd.Stdout, cmd.Stderr = stdout, stderr
return exitCode(cmd.Run())
}
stamps, err := readStampFile(*stampPath)
if err != nil {
return fail(stderr, err)
}
if stamps.invalid != "" {
fmt.Fprintf(stdout, "stamp file discarded (%s): it holds no stamps and the next write rewrites it\n", stamps.invalid)
}
old, had := stamps.stamps[key]
// markFailed leaves an existing line unable to match.
markFailed := func() error {
if !had || old.Inputs == failedMark {
return nil
}
return applyUpdates(*stampPath, map[string]*stamp{key: {Kind: "ruby", Path: scriptRel, Inputs: failedMark}})
}
own, built := ws.checkoutRuby()
if !built {
fmt.Fprintf(stdout, "%s: this checkout has no build/ez-agent-ruby; running with %s without stamps: a pass is not recorded, a failure is\n", scriptRel, *ruby)
code := run(*ruby)
if code != 0 {
if err := markFailed(); err != nil {
fmt.Fprintf(stderr, "teststamp: marking %s failed: %v\n", scriptRel, err)
}
}
return code
}
if !sameFile(own, *ruby) {
fmt.Fprintf(stdout, "%s: stamped checker uses this checkout's build/ez-agent-ruby, not %s\n", scriptRel, *ruby)
}
inputs, err := rubyInputs(ws, own, *tree, scriptRel)
if err != nil {
return fail(stderr, err)
}
if !*refresh && had && old.Inputs == inputs {
fmt.Fprintf(stdout, "NOT RUN in this run, skipped by stamp (last passed at these exact inputs): %s\n", scriptRel)
return 0
}
// Mark the line failed first, so a failed or interrupted run leaves
// nothing to match.
if err := markFailed(); err != nil {
return fail(stderr, err)
}
if code := run(own); code != 0 {
fmt.Fprintf(stdout, "%s failed; its stamp is marked failed\n", scriptRel)
return code
}
if err := applyUpdates(*stampPath, map[string]*stamp{key: {Kind: "ruby", Path: scriptRel, Inputs: inputs}}); err != nil {
return fail(stderr, err)
}
fmt.Fprintf(stdout, "%s passed; stamp recorded\n", scriptRel)
return 0
}
// checkoutRuby returns this checkout's build/ez-agent-ruby when it is an
// executable file. It is the only interpreter whose runtime rubyRuntimeInputs
// describe, so the stamped checker always uses it when present.
func (ws *workspace) checkoutRuby() (string, bool) {
path := filepath.Join(ws.root, "build", "ez-agent-ruby")
info, err := os.Stat(path)
return path, err == nil && info.Mode().IsRegular() && info.Mode()&0o111 != 0
}
func sameFile(a, b string) bool {
ai, aerr := os.Stat(a)
bi, berr := os.Stat(b)
return aerr == nil && berr == nil && os.SameFile(ai, bi)
}
// rubyRuntimeInputs are the tracked files that determine the runtime embedded
// in build/ez-agent-ruby, following ez-agent-ruby/runtime/build.sh: the source
// lock and runtime build scripts (CRuby, its stdlib, zlib, libyaml and the
// toolchain), the first-party libraries installed into vendor_ruby, the
// payload packager and manifest, and the wrapper and launcher that embed,
// extract and run the payload. The binary itself is not hashed because its
// build is not reproducible; the stamp assumes it was built from these files.
var rubyRuntimeInputs = []string{
"ez-agent-ruby/LICENSE", "ez-agent-ruby/go.mod", "ez-agent-ruby/go.sum",
"ez-agent-ruby/runtime", "ez-agent-ruby/lib",
"ez-agent-ruby/cmd/ez-agent-ruby", "ez-agent-ruby/cmd/package-runtime",
"ez-agent-ruby/internal/launcher", "ez-agent-ruby/internal/runtimepayload",
}
// rubyRuntimeOutput reports generated or test-only files inside
// rubyRuntimeInputs.
func rubyRuntimeOutput(rel string) bool {
return rel == "ez-agent-ruby/cmd/ez-agent-ruby/payload.zip" || strings.HasSuffix(rel, "_test.go")
}
// rubyInputs hashes the checker's tree, the runtime's tracked inputs, the
// interpreter's RUBY_DESCRIPTION and the Go toolchain.
func rubyInputs(ws *workspace, ruby, tree, scriptRel string) (string, error) {
treeRel, ok := ws.rel(absPath(tree))
if !ok {
return "", errors.New("tree must be inside the repository")
}
if !strings.HasPrefix(scriptRel, treeRel+"/") {
return "", fmt.Errorf("%s is not inside %s", scriptRel, treeRel)
}
description, err := exec.Command(ruby, "-e", "print RUBY_DESCRIPTION").Output()
if err != nil {
return "", fmt.Errorf("%s: %w", ruby, err)
}
set := map[string]bool{}
if err := ws.addTree(set, treeRel); err != nil {
return "", err
}
for _, input := range rubyRuntimeInputs {
files, err := ws.tree(input)
if err != nil {
return "", err
}
for _, file := range files {
if !rubyRuntimeOutput(file) {
set[file] = true
}
}
}
extra := append([]string{"ruby " + string(description), "tree " + treeRel}, ws.toolchain...)
return ws.digest("ruby", scriptRel, extra, set)
}
func absPath(path string) string {
abs, err := filepath.Abs(path)
if err != nil {
return path
}
return abs
}
func cmdHash(args []string, stdout, stderr io.Writer) int {
flags := flag.NewFlagSet("hash", flag.ContinueOnError)
flags.SetOutput(stderr)
stampPath := flags.String("stamps", "", "optional stamp file to compare")
hub := flags.String("hub", "", "regexp selecting AgentHub import paths")
if err := flags.Parse(args); err != nil {
return 2
}
pol, err := defaultPolicy(*hub)
if err != nil {
return fail(stderr, err)
}
ws, err := openWorkspace(".")
if err != nil {
return fail(stderr, err)
}
targets, err := ws.analyze(pol, flags.Args())
if err != nil {
return fail(stderr, err)
}
stamps := &stampFile{stamps: map[string]stamp{}}
if *stampPath != "" {
if stamps, err = readStampFile(*stampPath); err != nil {
return fail(stderr, err)
}
}
hubCount, eligible := 0, 0
for _, t := range targets {
if !t.Hub {
continue
}
hubCount++
if !t.Eligible {
fmt.Fprintf(stdout, "%s ineligible: %s\n", t.Rel, t.Reason)
continue
}
eligible++
state := ""
if *stampPath != "" {
switch s, ok := stamps.stamps["go "+t.Rel]; {
case !ok:
state = " stamp=missing"
case s.Closure == t.Closure:
state = " stamp=match"
case s.Closure == failedMark:
state = " stamp=failed"
case s.Own == t.Own:
state = " stamp=stale(own-match)"
default:
state = " stamp=stale"
}
}
fmt.Fprintf(stdout, "%s eligible closure=%s own=%s%s\n", t.Rel, t.Closure, t.Own, state)
if len(t.Env) > 0 {
fmt.Fprintf(stdout, " reads environment: %s\n", strings.Join(t.Env, " "))
}
if set := profileEnv(t, os.Getenv); len(set) > 0 {
fmt.Fprintf(stdout, " runs without stamps in this environment: %s set\n", strings.Join(set, ", "))
}
for _, read := range t.EnvUnclassified {
fmt.Fprintf(stdout, " unclassified environment read: %s\n", read)
}
}
fmt.Fprintf(stdout, "%d of %d AgentHub package(s) stamp-eligible\n", eligible, hubCount)
return 0
}