Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ versioning follows [SemVer](https://semver.org/).

## [Unreleased]

### Fixed

- The v0.2.3 "unchanged code" downgrade never fired in practice: it compared HEAD to the snapshot's commit, but the snapshot keeps its commit byte-stable and normal use commits the baseline, so the commits never matched. It now compares a fingerprint of the working tree (tracked and untracked files by content, excluding `.regressguard/` and `.gitignore`) with the fingerprint of the last tree whose tests passed, stored in `.regressguard/state.json`. A test that fails on code that passed before is a WARNING; any code change, new file, no git, or no prior green run stays CRITICAL. Route findings are never downgraded.

## [0.2.3] - 2026-10-03

### Fixed
Expand Down
45 changes: 13 additions & 32 deletions internal/checkrun/checkrun.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,14 @@ func Run(opts Options) (Result, error) {
}
}

treeFP := state.TreeFingerprint(opts.ProjectRoot)
st := state.Load(opts.ProjectRoot)
prevGreenTree := st.GreenTree
if testResult.Failed == 0 && treeFP != "" && st.GreenTree != treeFP {
st.GreenTree = treeFP
_ = state.Save(opts.ProjectRoot, st)
}

var routeSpinner *ui.Spinner
var routeProgress *ui.RouteProgress
if showSpinner && ui.AnimationsEnabled() && len(routes) >= 4 {
Expand Down Expand Up @@ -388,7 +396,10 @@ func Run(opts Options) (Result, error) {
diff.HasCritical = true
}

if hasTestFailure(diff) && treeMatchesSnapshot(opts.ProjectRoot, snap.GitCommit) {
// Tests failing on the exact tree that passed before is environmental
// (flaky, load, port race), not something an agent changed. Unknown
// fingerprint or no green history keeps the failure critical.
if hasTestFailure(diff) && treeFP != "" && treeFP == prevGreenTree {
diff = downgradeTestFailures(diff)
}

Expand Down Expand Up @@ -542,36 +553,6 @@ func hasTestFailure(diff engine.DiffResult) bool {
return false
}

// treeMatchesSnapshot reports whether the working tree is exactly the code the
// baseline was recorded on: HEAD is the snapshot commit and nothing but
// RegressGuard's own files (.regressguard/, init's .gitignore edit) differs,
// untracked files included. Any doubt (no git, unknown commit) returns false,
// so the caller keeps failing closed.
func treeMatchesSnapshot(root, commit string) bool {
if commit == "" || commit == "unknown" {
return false
}
head, err := exec.Command("git", "-C", root, "rev-parse", "HEAD").Output()
if err != nil || !strings.HasPrefix(strings.TrimSpace(string(head)), commit) {
return false
}
out, err := exec.Command("git", "-C", root, "status", "--porcelain", "--untracked-files=all").Output()
if err != nil {
return false
}
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if len(line) < 4 {
continue
}
path := strings.TrimSpace(line[3:])
if path == ".gitignore" || strings.HasPrefix(path, ".regressguard/") {
continue
}
return false
}
return true
}

// downgradeTestFailures turns critical test findings into warnings. Callers
// must only use it when the code is unchanged since the baseline: a test that
// newly fails on identical code is environmental (flaky, port race, load),
Expand All @@ -585,7 +566,7 @@ func downgradeTestFailures(diff engine.DiffResult) engine.DiffResult {
continue
}
diff.Results[i].Severity = engine.SeverityWarning
diff.Results[i].Message += " (no source files changed since the baseline, so this is likely a flaky or environment-dependent test)"
diff.Results[i].Message += " (this exact code passed the tests before, so this is likely a flaky or environment-dependent test)"
diff.CriticalCount--
diff.WarningCount++
diff.HasWarning = true
Expand Down
139 changes: 92 additions & 47 deletions internal/checkrun/checkrun_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1163,52 +1163,6 @@ func TestRun_base_noSnapshotAtRef(t *testing.T) {

// --- tests failing on an unchanged tree are environmental, not regressions ---

func treeFixture(t *testing.T) (dir, commit string) {
t.Helper()
dir = t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "app.ts"), []byte("v1"), 0o644)
gitIn(t, dir, "init", "-q")
gitIn(t, dir, "add", "-A")
gitIn(t, dir, "commit", "-qm", "base")
commit = snapshot.GitCommit(dir)
return dir, commit
}

func TestTreeMatchesSnapshot(t *testing.T) {
dir, commit := treeFixture(t)
if !treeMatchesSnapshot(dir, commit) {
t.Fatal("clean tree at snapshot commit should match")
}
// RegressGuard's own files and init's .gitignore edit do not count.
_ = os.MkdirAll(filepath.Join(dir, ".regressguard"), 0o755)
_ = os.WriteFile(filepath.Join(dir, ".regressguard", "snapshot.json"), []byte("{}"), 0o644)
_ = os.WriteFile(filepath.Join(dir, ".gitignore"), []byte(".regressguard/*\n"), 0o644)
if !treeMatchesSnapshot(dir, commit) {
t.Fatal("regressguard-owned files must be ignored")
}
// An edited tracked file, or a new untracked source file, is a real change.
_ = os.WriteFile(filepath.Join(dir, "app.ts"), []byte("v2"), 0o644)
if treeMatchesSnapshot(dir, commit) {
t.Fatal("edited file must not match")
}
gitIn(t, dir, "checkout", "--", "app.ts")
_ = os.WriteFile(filepath.Join(dir, "new.ts"), []byte("x"), 0o644)
if treeMatchesSnapshot(dir, commit) {
t.Fatal("untracked source file must not match")
}
_ = os.Remove(filepath.Join(dir, "new.ts"))
gitIn(t, dir, "commit", "-q", "--allow-empty", "-m", "later")
if treeMatchesSnapshot(dir, commit) {
t.Fatal("moved HEAD must not match")
}
}

func TestTreeMatchesSnapshot_failsClosed(t *testing.T) {
if treeMatchesSnapshot(t.TempDir(), "unknown") || treeMatchesSnapshot(t.TempDir(), "") {
t.Fatal("no git / unknown commit must never match")
}
}

func TestDowngradeTestFailures(t *testing.T) {
diff := engine.DiffResult{
Results: []engine.CheckResult{
Expand All @@ -1218,7 +1172,7 @@ func TestDowngradeTestFailures(t *testing.T) {
HasCritical: true, CriticalCount: 2,
}
got := downgradeTestFailures(diff)
if got.Results[0].Severity != engine.SeverityWarning || !strings.Contains(got.Results[0].Message, "no source files changed") {
if got.Results[0].Severity != engine.SeverityWarning || !strings.Contains(got.Results[0].Message, "passed the tests before") {
t.Errorf("test finding should become a warning with explanation: %+v", got.Results[0])
}
if got.Results[1].Severity != engine.SeverityCritical {
Expand Down Expand Up @@ -1251,3 +1205,94 @@ func TestGitChangedFiles_ignoresRegressguardOwnedFiles(t *testing.T) {
t.Errorf("want only app.ts, got %v", got)
}
}

// toggleScript is a test command that fails while <toggleDir>/FAIL exists. It
// lives outside the project so flipping it never changes the project tree.
func toggleScript(t *testing.T) (cmd, toggleDir string) {
t.Helper()
toggleDir = t.TempDir()
script := filepath.Join(toggleDir, "t.sh")
body := "if [ -f " + filepath.Join(toggleDir, "FAIL") + " ]; then echo 'Tests: 1 failed, 1 passed, 2 total'; exit 1; fi\necho 'Tests: 2 passed, 2 total'\n"
if err := os.WriteFile(script, []byte(body), 0o755); err != nil {
t.Fatal(err)
}
return "sh " + script, toggleDir
}

func greenTreeProject(t *testing.T) (dir, toggleDir string) {
t.Helper()
dir = t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "app.ts"), []byte("v1"), 0o644)
gitIn(t, dir, "init", "-q")
gitIn(t, dir, "add", "-A")
gitIn(t, dir, "commit", "-qm", "base")
cmd, toggleDir := toggleScript(t)
writeCfg(t, dir, config.Config{Version: 1, TestCommand: cmd, ServerURL: "http://127.0.0.1:1"})
writeSnap(t, dir, snapshot.Snapshot{
Version: 1, CreatedAt: time.Now(),
Tests: snapshot.TestSummary{Passed: 2},
Routes: map[string]snapshot.RouteRecord{},
})
return dir, toggleDir
}

func runCheck(t *testing.T, dir string) Result {
t.Helper()
var out, errb bytes.Buffer
res, err := Run(Options{ProjectRoot: dir, Stdout: &out, Stderr: &errb})
if err != nil {
t.Fatalf("check: %v", err)
}
return res
}

func TestRun_testFailureOnPreviouslyGreenTreeIsWarning(t *testing.T) {
dir, toggle := greenTreeProject(t)
if res := runCheck(t, dir); res.Status == "critical" {
t.Fatalf("baseline run should not be critical: %+v", res)
}
_ = os.WriteFile(filepath.Join(toggle, "FAIL"), nil, 0o644)
res := runCheck(t, dir)
if res.Status != "warning" {
t.Fatalf("same tree that passed before now fails tests: want warning, got %q: %+v", res.Status, res.Results)
}
}

func TestRun_testFailureAfterCodeChangeStaysCritical(t *testing.T) {
dir, toggle := greenTreeProject(t)
runCheck(t, dir)
_ = os.WriteFile(filepath.Join(dir, "app.ts"), []byte("v2"), 0o644)
_ = os.WriteFile(filepath.Join(toggle, "FAIL"), nil, 0o644)
if res := runCheck(t, dir); res.Status != "critical" {
t.Fatalf("edited code + failing tests must be critical, got %q", res.Status)
}
// A new untracked source file is a change too.
dir2, toggle2 := greenTreeProject(t)
runCheck(t, dir2)
_ = os.WriteFile(filepath.Join(dir2, "new.ts"), []byte("x"), 0o644)
_ = os.WriteFile(filepath.Join(toggle2, "FAIL"), nil, 0o644)
if res := runCheck(t, dir2); res.Status != "critical" {
t.Fatalf("new file + failing tests must be critical, got %q", res.Status)
}
}

func TestRun_testFailureWithNoGreenHistoryStaysCritical(t *testing.T) {
dir, toggle := greenTreeProject(t)
_ = os.WriteFile(filepath.Join(toggle, "FAIL"), nil, 0o644)
if res := runCheck(t, dir); res.Status != "critical" {
t.Fatalf("no prior green run: must fail closed, got %q", res.Status)
}
}

func TestRun_greenTreeSurvivesCommitOfBaseline(t *testing.T) {
dir, toggle := greenTreeProject(t)
runCheck(t, dir)
// Normal workflow: init edits .gitignore, the baseline gets committed.
_ = os.WriteFile(filepath.Join(dir, ".gitignore"), []byte(".regressguard/*\n!.regressguard/snapshot.json\n"), 0o644)
gitIn(t, dir, "add", "-A")
gitIn(t, dir, "commit", "-qm", "add baseline")
_ = os.WriteFile(filepath.Join(toggle, "FAIL"), nil, 0o644)
if res := runCheck(t, dir); res.Status != "warning" {
t.Fatalf("committing the baseline must not defeat the green-tree match, got %q", res.Status)
}
}
7 changes: 7 additions & 0 deletions internal/snapshotrun/snapshotrun.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ func Run(opts Options) (Result, error) {
MoreContext: "regressguard snapshot --help",
}
}
if testResult.Failed == 0 {
if fp := state.TreeFingerprint(opts.ProjectRoot); fp != "" {
st := state.Load(opts.ProjectRoot)
st.GreenTree = fp
_ = state.Save(opts.ProjectRoot, st)
}
}
snap.Tests = snapshot.TestSummary{
Passed: testResult.Passed,
Failed: testResult.Failed,
Expand Down
53 changes: 53 additions & 0 deletions internal/state/fingerprint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package state

import (
"crypto/sha256"
"encoding/hex"
"os"
"os/exec"
"strconv"
"strings"
)

const (
maxFingerprintFiles = 50000
maxFingerprintBytes = 20 << 20
)

// TreeFingerprint hashes the project's working tree: every tracked and
// untracked-but-not-ignored file, by path and content, except RegressGuard's
// own files (.regressguard/, the root .gitignore that init edits). Two equal
// fingerprints mean identical code. It returns "" when it cannot be sure
// (not a git repo, git failure, unreadable or oversized tree), so callers
// must treat "" as "unknown" and fail closed.
func TreeFingerprint(root string) string {
out, err := exec.Command("git", "-C", root, "ls-files", "-z", "--cached", "--others", "--exclude-standard").Output()
if err != nil {
return ""
}
paths := strings.Split(strings.TrimRight(string(out), "\x00"), "\x00")
if len(paths) > maxFingerprintFiles {
return ""
}
h := sha256.New()
for _, p := range paths {
if p == "" || p == ".gitignore" || strings.HasPrefix(p, ".regressguard/") {
continue
}
h.Write([]byte(p))
h.Write([]byte{0})
data, err := os.ReadFile(root + string(os.PathSeparator) + p)
switch {
case os.IsNotExist(err):
h.Write([]byte("<deleted>"))
case err != nil || len(data) > maxFingerprintBytes:
return ""
default:
h.Write([]byte(strconv.Itoa(len(data))))
h.Write([]byte{0})
h.Write(data)
}
h.Write([]byte{0})
}
return hex.EncodeToString(h.Sum(nil))
}
52 changes: 52 additions & 0 deletions internal/state/fingerprint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package state

import (
"os"
"os/exec"
"path/filepath"
"testing"
)

func gitRepo(t *testing.T) string {
t.Helper()
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, "a.ts"), []byte("v1"), 0o644)
for _, args := range [][]string{{"init", "-q"}, {"add", "-A"}, {"-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "base"}} {
if out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput(); err != nil {
t.Fatalf("git %v: %v\n%s", args, err, out)
}
}
return dir
}

func TestTreeFingerprint(t *testing.T) {
dir := gitRepo(t)
base := TreeFingerprint(dir)
if base == "" {
t.Fatal("git repo should fingerprint")
}
if TreeFingerprint(dir) != base {
t.Fatal("fingerprint must be stable")
}
_ = os.WriteFile(filepath.Join(dir, ".gitignore"), []byte(".regressguard/*\n"), 0o644)
_ = os.MkdirAll(filepath.Join(dir, ".regressguard"), 0o755)
_ = os.WriteFile(filepath.Join(dir, ".regressguard", "snapshot.json"), []byte("{}"), 0o644)
if TreeFingerprint(dir) != base {
t.Fatal(".gitignore and .regressguard/ must not affect the fingerprint")
}
_ = os.WriteFile(filepath.Join(dir, "a.ts"), []byte("v2"), 0o644)
edited := TreeFingerprint(dir)
if edited == base {
t.Fatal("edit must change the fingerprint")
}
_ = os.WriteFile(filepath.Join(dir, "b.ts"), []byte("x"), 0o644)
if TreeFingerprint(dir) == edited {
t.Fatal("new untracked file must change the fingerprint")
}
}

func TestTreeFingerprint_noGitIsUnknown(t *testing.T) {
if TreeFingerprint(t.TempDir()) != "" {
t.Fatal("outside git the fingerprint must be empty (fail closed)")
}
}
2 changes: 2 additions & 0 deletions internal/state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ type State struct {
HookNudgeShown bool `json:"hookNudgeShown,omitempty"`
CheckStreak int `json:"checkStreak,omitempty"`
FirstPassShown bool `json:"firstPassShown,omitempty"`
// GreenTree is the TreeFingerprint of the last tree whose test suite passed.
GreenTree string `json:"greenTree,omitempty"`
}

// Path returns the absolute path to state.json given a project root.
Expand Down
Loading