Engine: check stages, harness-agnostic delivery, read-only enforcement, complete captures

- New `type=check` stage: the server runs a `commands` block (sh -c, per
  command_timeout, workspace env) and routes on pass/fail; per-command status,
  exit code, duration and bounded output are recorded and the failing output is
  the handoff. With delivery=true it is the landing gate (commit leftovers,
  merge moved main, checks in a fresh candidate worktree, fast-forward main).
  Parser/registry, lint (silent guards), format docs, CLI inspect, app graph and
  run detail rendering.
- delivery=true is accepted on every harness (and on check stages).
- permissions.shell on claude stages maps to Bash(cmd) / Bash(prefix:*) rules
  instead of a bare Bash allow; stages without edit that change the workspace
  fail the visit with the changed files listed (allow_workspace_changes=true
  opts out; artifacts, public and harness state dirs are ignored).
- File-change capture: symlinks compared by target, untouched protected files no
  longer make captures partial, untracked caches/dependency/build output left
  out, lockfiles listed without patch, huge files compared by metadata, raised
  patch/line limits. Outcome repair follow-ups are logged and counted on the
  step (control.outcome_repairs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:52:16 +00:00
parent c4de1de27b
commit 87016ef5dc
47 changed files with 2674 additions and 129 deletions
+117
View File
@@ -0,0 +1,117 @@
package filediff
import (
"crypto/sha256"
"fmt"
"io/fs"
"path"
"strings"
)
// Policy no-patch reasons: the change is listed, completely, without a patch
// by design rather than because a capture limit ran out, so it never makes a
// capture partial.
const (
reasonSymlink = "symlink" // a symbolic link; its target is compared
reasonLarge = "large" // over the hash bound; compared by size, mtime and mode
reasonGenerated = "generated" // a lockfile, minified bundle or source map
)
// cacheDirs are tool caches, virtual environments and dependency trees. Their
// untracked files are left out of the inventory entirely (never "skipped"):
// they are regenerated by tools, not authored by a stage. Tracked files below
// them are still compared, without a patch.
var cacheDirs = map[string]bool{
"node_modules": true, "bower_components": true, ".git": true,
"__pycache__": true, ".venv": true, "venv": true, ".tox": true, ".nox": true,
".mypy_cache": true, ".pytest_cache": true, ".ruff_cache": true, ".hypothesis": true, ".eggs": true,
".next": true, ".nuxt": true, ".svelte-kit": true, ".turbo": true, ".parcel-cache": true, ".pnpm-store": true,
".dart_tool": true, ".gradle": true, ".terraform": true,
}
// buildDirs are conventional build output directories. Untracked files below
// one are left out only when Git tracks nothing there, so a new source file
// in a real `build/` source directory is still captured.
var buildDirs = map[string]bool{"build": true, "dist": true, "out": true, "target": true, "coverage": true}
// generatedNames are lockfiles: tool output whose diff is noise.
var generatedNames = map[string]bool{
"package-lock.json": true, "npm-shrinkwrap.json": true, "yarn.lock": true, "pnpm-lock.yaml": true,
"bun.lockb": true, "cargo.lock": true, "go.sum": true, "poetry.lock": true, "uv.lock": true,
"pipfile.lock": true, "gemfile.lock": true, "composer.lock": true, "pubspec.lock": true,
"flake.lock": true, "mix.lock": true, "podfile.lock": true, "packages.lock.json": true,
}
// inCacheDir reports whether any directory component of name is a cache dir.
func inCacheDir(name string) bool {
parts := strings.Split(name, "/")
for _, part := range parts[:len(parts)-1] {
if cacheDirs[part] {
return true
}
}
return false
}
// generatedFile reports a file whose diff is tool output: a lockfile, a
// minified bundle, a source map, compiled Python, or anything below a cache
// directory.
func generatedFile(name string) bool {
base := strings.ToLower(path.Base(name))
if generatedNames[base] || strings.HasSuffix(base, ".min.js") || strings.HasSuffix(base, ".min.css") ||
strings.HasSuffix(base, ".map") || strings.HasSuffix(base, ".pyc") {
return true
}
return inCacheDir(name)
}
// excludedUntracked reports an untracked path that is tool output rather than
// stage work: below a cache directory, compiled Python, or below a build
// directory where Git tracks nothing (trackedDirs holds every directory that
// contains a tracked file).
func excludedUntracked(name string, trackedDirs map[string]bool) bool {
if inCacheDir(name) || strings.HasSuffix(name, ".pyc") {
return true
}
parts := strings.Split(name, "/")
for i, part := range parts[:len(parts)-1] {
if buildDirs[part] && !trackedDirs[strings.Join(parts[:i+1], "/")] {
return true
}
}
return false
}
// trackedDirectories returns every ancestor directory of the tracked names.
func trackedDirectories(names []string) map[string]bool {
dirs := map[string]bool{}
for _, name := range names {
for dir := path.Dir(name); dir != "." && dir != "/" && !dirs[dir]; dir = path.Dir(dir) {
dirs[dir] = true
}
}
return dirs
}
// policyReason is the policy no-patch reason of a changed path, preferring
// the stage-end side (a file that became a symlink is a symlink change).
func policyReason(a file, aOK bool, b file, bOK bool) string {
if bOK && b.reason != "" {
return b.reason
}
if aOK && a.reason != "" {
return a.reason
}
return ""
}
// metaHash fingerprints a file by its metadata alone, without reading it: a
// protected (secret) file is never opened, and a huge file is not hashed.
func metaHash(info fs.FileInfo) [32]byte {
return sha256.Sum256(fmt.Appendf(nil, "meta\x00%d\x00%d\x00%o", info.Size(), info.ModTime().UnixNano(), info.Mode()))
}
// linkHash fingerprints a symbolic link by its target.
func linkHash(target string) [32]byte {
return sha256.Sum256([]byte("symlink\x00" + target))
}
+73
View File
@@ -0,0 +1,73 @@
package filediff
import (
"context"
"os"
"path/filepath"
"testing"
)
// A committed symlink no longer makes every capture partial, and a symlink a
// stage creates (a read-only reviewer's stray link) is listed.
func TestSymlinksAreComparedByTarget(t *testing.T) {
dir, git := gitRepo(t)
put(t, dir, "real.md", "skill\n")
if err := os.Symlink("real.md", filepath.Join(dir, "linked")); err != nil {
t.Fatal(err)
}
git("add", "real.md", "linked")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 || len(quiet.Files) != 0 {
t.Fatalf("an untouched symlink: %+v", quiet)
}
if err := os.Symlink("/etc", filepath.Join(dir, "stray")); err != nil {
t.Fatal(err)
}
changes := Compare(before, Capture(ctx, dir, before))
if changes.Status != "complete" || len(changes.Files) != 1 {
t.Fatalf("%+v", changes)
}
if f := changes.Files[0]; f.Path != "stray" || f.Kind != "added" || f.NoPatchReason != reasonSymlink || f.Truncated {
t.Fatalf("%+v", f)
}
}
func TestToolOutputIsExcludedOrListedWithoutPatch(t *testing.T) {
dir, git := gitRepo(t)
for _, name := range []string{"build/keep.sh", "go.sum", "src/a.go"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "v1\n")
}
git("add", ".")
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
for _, name := range []string{"node_modules/x/index.js", "dist/app.js", "src/__pycache__/a.pyc", "build/new.sh"} {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
t.Fatal(err)
}
put(t, dir, name, "generated\n")
}
put(t, dir, "go.sum", "v2\n")
put(t, dir, "src/a.go", "v2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
got[f.Path] = f.NoPatchReason
}
// Untracked caches and an untracked build directory are left out; a new
// file in a tracked build directory is stage work; a lockfile has no patch.
want := map[string]string{"build/new.sh": "", "go.sum": reasonGenerated, "src/a.go": ""}
if len(got) != len(want) || changes.Status != "complete" {
t.Fatalf("got %v (%+v)", got, changes)
}
for name, reason := range want {
if r, ok := got[name]; !ok || r != reason {
t.Fatalf("%s: got %q (%v)", name, r, got)
}
}
}
+121 -21
View File
@@ -26,12 +26,12 @@ import (
)
const (
maxFiles = 10000
maxFiles = 20000
maxFileBytes = 1 << 20
maxSnapshotBytes = 32 << 20
maxPatchBytes = 128 << 10
maxFilePatchBytes = 64 << 10
maxLines = 5000
maxPatchBytes = 512 << 10
maxFilePatchBytes = 128 << 10
maxLines = 20000
binarySniffBytes = 8 << 10
)
@@ -82,6 +82,12 @@ type file struct {
// already holds it, and a later capture recovers it only if the file
// changed. This keeps the text budget for files Git has no baseline for.
blob string
// reason is a policy no-patch reason (symlink, large, generated): the
// change is listed completely, without a patch, and no content is kept.
reason string
// secret marks a protected file fingerprinted by metadata only. It is
// never read or listed; a change to it makes the capture partial.
secret bool
}
// baseline is stage-start content recovered from Git for a changed file whose
@@ -108,6 +114,9 @@ type Snapshot struct {
// the previous snapshot; missing records why one could not be recovered.
baselines map[string]baseline
missing map[string]string
// excluded holds untracked tool output left out of the inventory, so
// the Git-status pass does not list it either.
excluded map[string]bool
}
// gitCommand runs git for directory with the run's directory environment
@@ -245,7 +254,7 @@ func protected(name string) bool {
if template(part) {
continue
}
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" || part == "node_modules" {
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" {
return true
}
if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" {
@@ -278,16 +287,43 @@ func (b *boundedOutput) Write(p []byte) (int, error) {
// inventory lists the files to snapshot. Git is only read, never altered;
// the baseline is still stage-start content (see Capture and recoverBaselines).
func inventory(ctx context.Context, directory string, root *os.Root) ([]string, bool, error) {
func inventory(ctx context.Context, directory string, root *os.Root, excluded map[string]bool) ([]string, bool, error) {
probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree")
if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" {
cmd := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate", "-z", "--", ".")
out := &boundedOutput{limit: 2 << 20}
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return nil, true, fmt.Errorf("Git file inventory unavailable")
list := func(args ...string) ([]string, error) {
cmd := gitCommand(ctx, directory, append([]string{"-c", "core.fsmonitor=false", "-C", directory, "ls-files"}, append(args, "-z", "--", ".")...)...)
out := &boundedOutput{limit: 2 << 20}
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("Git file inventory unavailable")
}
text := strings.TrimSuffix(out.String(), "\x00")
if text == "" {
return nil, nil
}
return strings.Split(text, "\x00"), nil
}
return strings.Split(strings.TrimSuffix(out.String(), "\x00"), "\x00"), true, nil
tracked, err := list("--cached", "--deduplicate")
if err != nil {
return nil, true, err
}
untracked, err := list("--others", "--exclude-standard")
if err != nil {
return nil, true, err
}
// Untracked tool output (caches, dependency trees, untracked build
// directories) is not stage work: leave it out instead of letting it
// crowd the inventory and the budgets.
trackedDirs := trackedDirectories(tracked)
names := tracked
for _, name := range untracked {
if excludedUntracked(name, trackedDirs) {
excluded[name] = true
} else {
names = append(names, name)
}
}
return names, true, nil
}
if ctx.Err() != nil {
return nil, false, ctx.Err()
@@ -300,6 +336,9 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
if err != nil {
return err
}
if name != "." && entry.IsDir() && cacheDirs[entry.Name()] {
return fs.SkipDir // tool output, not stage work
}
if name != "." && protected(name) {
names = append(names, name)
if entry.IsDir() {
@@ -319,7 +358,7 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
}
func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot {
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}}
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}, excluded: map[string]bool{}}
root, err := os.OpenRoot(directory)
if err != nil {
s.diagnostic = "Workspace snapshot unavailable."
@@ -327,7 +366,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
}
defer root.Close()
s.available = true
names, git, err := inventory(ctx, directory, root)
names, git, err := inventory(ctx, directory, root, s.excluded)
s.scope = "Workspace regular files"
if git {
s.scope = "Git tracked and nonignored files in the run directory"
@@ -379,12 +418,13 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.diagnostic = "Workspace capture reached its time/file limit."
break
}
if !fs.ValidPath(name) || protected(name) {
if !fs.ValidPath(name) {
s.skipped[name] = true
continue
}
// Reject symlinks in every component, including aliases to sensitive paths.
valid := true
// Never follow a symlink: a path through a symlinked directory is
// skipped, and a symlink itself is compared by its target only.
valid, link := true, false
parts := strings.Split(name, "/")
for j := range parts {
info, err := root.Lstat(strings.Join(parts[:j+1], "/"))
@@ -392,6 +432,10 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
valid = false
break
} // tracked deletion
if err == nil && info.Mode()&os.ModeSymlink != 0 && j == len(parts)-1 {
link = true
break
}
if err != nil || info.Mode()&os.ModeSymlink != 0 {
s.skipped[name] = true
valid = false
@@ -402,10 +446,38 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
continue
}
info, err := root.Lstat(name)
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes {
if err != nil {
s.skipped[name] = true
continue
}
if protected(name) {
// A secret is never opened: its metadata shows whether it changed,
// so an untouched .env no longer makes every capture partial.
if info.IsDir() {
s.skipped[name] = true
} else {
s.files[name] = file{hash: metaHash(info), secret: true}
}
continue
}
if link {
target, err := root.Readlink(name)
if err != nil {
s.skipped[name] = true
continue
}
s.files[name] = file{hash: linkHash(target), size: int64(len(target)), mode: info.Mode().Perm(), reason: reasonSymlink}
continue
}
if !info.Mode().IsRegular() {
s.skipped[name] = true
continue
}
if info.Size() > maxHashBytes {
s.files[name] = file{hash: metaHash(info), size: info.Size(), mode: info.Mode().Perm(), reason: reasonLarge}
continue
}
generated := generatedFile(name)
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
if err != nil {
s.skipped[name] = true
@@ -440,6 +512,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
// listed (without a patch) instead of being skipped unseen.
switch {
case binary:
case generated:
// Tool output: compared by hash, listed without a patch.
entry.reason = reasonGenerated
case seen && p.hash == entry.hash && !p.binary:
// Unchanged since the previous snapshot: share its representation
// without spending this snapshot's budget on it again.
@@ -463,7 +538,11 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
s.skipped[name] = true
continue
}
s.files[name] = file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
entry := file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
if generated && !binary {
entry.hashOnly, entry.limit, entry.reason = false, "", reasonGenerated
}
s.files[name] = entry
}
if prev != nil {
s.recoverBaselines(ctx, directory, prev, used)
@@ -584,6 +663,14 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
result.Files = append(result.Files, change)
}
listed := 0
secretChanges := 0
defer func() {
if secretChanges > 0 {
result.Skipped += secretChanges
result.Status = "partial"
result.Diagnostic = "A protected file (secrets, credentials, databases) changed; it is never read or listed, so this is not a complete workspace diff."
}
}()
// decided records every path the content comparison settled (changed or
// not), so the Git-status pass below only speaks for the rest.
decided := map[string]bool{}
@@ -598,7 +685,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
continue
}
decided[name] = true
if aOK && bOK && a.hash == b.hash && a.mode == b.mode {
if aOK && bOK && a.hash == b.hash && a.mode == b.mode && a.secret == b.secret {
continue
}
if a.secret || b.secret {
// A protected file changed: never listed, so the capture is honest
// about being incomplete.
secretChanges++
continue
}
kind := "modified"
@@ -615,6 +708,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
if bOK {
change.AfterMode = fmt.Sprintf("%04o", b.mode)
}
if reason := policyReason(a, aOK, b, bOK); reason != "" {
// Listed completely by design (a symlink, a huge or generated
// file), without a patch; not a capture limit.
change.NoPatchReason = reason
add(change)
continue
}
// A clean-at-start file kept only its Git blob id; its start content
// comes from the after snapshot's verified Git recovery.
aData, unavailable := a.data, ""
@@ -690,7 +790,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
}
ordered := make([]string, 0, len(gitNames))
for name := range gitNames {
if !decided[name] && fs.ValidPath(name) && !protected(name) {
if !decided[name] && fs.ValidPath(name) && !protected(name) && !before.excluded[name] && !after.excluded[name] {
ordered = append(ordered, name)
}
}
+20 -11
View File
@@ -248,10 +248,10 @@ func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
}
}
// TestGitStatusListsUncomparableChanges proves a file the content snapshot
// skips (here: above the hash bound) is still listed when its Git status
// changes during the visit, while a protected path never is.
func TestGitStatusListsUncomparableChanges(t *testing.T) {
// TestHugeFilesAreListedByMetadata proves a file above the hash bound is
// listed completely (by size, mtime and mode, without a patch), while a
// protected path is never listed and its change marks the capture partial.
func TestHugeFilesAreListedByMetadata(t *testing.T) {
previous := maxHashBytes
maxHashBytes = 16
defer func() { maxHashBytes = previous }()
@@ -263,21 +263,30 @@ func TestGitStatusListsUncomparableChanges(t *testing.T) {
git("commit", "-qm", "init")
ctx := context.Background()
before := Capture(ctx, dir)
put(t, dir, "big.bin", strings.Repeat("y", 64))
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 {
t.Fatalf("an untouched secret and huge file made the capture %+v", quiet)
}
put(t, dir, "big.bin", strings.Repeat("y", 65))
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
put(t, dir, ".env", "A=2\n")
changes := Compare(before, Capture(ctx, dir, before))
got := map[string]string{}
for _, f := range changes.Files {
if !f.NoPatch {
t.Fatalf("git-listed change carries a patch: %+v", f)
if f.Patch != "" || f.NoPatchReason != reasonLarge || f.Truncated {
t.Fatalf("huge-file change: %+v", f)
}
got[f.Path] = f.Kind
}
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" {
t.Fatalf("git status listing = %v (%+v)", got, changes)
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" || changes.Status != "complete" {
t.Fatalf("listing = %v (%+v)", got, changes)
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") {
put(t, dir, ".env", "A=2\n")
changes = Compare(before, Capture(ctx, dir, before))
for _, f := range changes.Files {
if f.Path == ".env" {
t.Fatal("a protected path was listed")
}
}
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "protected") {
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
}
}