Merge branch 'worktree-agent-add3194df2bcbd3c5'

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:21:07 +00:00
48 changed files with 2684 additions and 131 deletions
+6 -1
View File
@@ -64,7 +64,12 @@ Start from `pipelines templates` and `pipelines new NAME --template KEY`
(`research`, `task`); these fill in
the server's provider/model. Read `references/format.md` and
`references/practices.md` before writing prompts. Stage names: `plan` ·
`implement` · `review` · `ui-review` · `decide` (human) · `land`.
`implement` · `verify` (check) · `review` · `ui-review` · `decide` (human) ·
`land`. A `type=check` stage runs listed shell commands on the server, no
model, and routes on `pass`/`fail`: put one before review and use one with
`delivery=true` as the landing gate rather than having a model run the suite.
Stages with `shell` but no `edit` must not change the workspace (the server fails the
visit); give reviewers a `permissions.shell` allow-list.
Keep prompts short and objective: what the stage should produce and any real
constraints. The runner enforces turns, tools and limits and explains the output
+3 -3
View File
@@ -9,9 +9,9 @@ request does not authorize publication, execution or deployment.
Inspect actual source and diffs, run relevant tests and record exact results.
A model summary, committed branch or successful merge is not proof of runtime
behavior. Missing or partial diff capture must be reported as incomplete.
With delivery=true, the stage returns a clean candidate and the server checks and
lands it, first merging a moved main and re-checking the merged tree; only a real
conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
With delivery=true (a model land stage on any harness, or a check stage), the
server checks and lands the candidate, first merging a moved main and
re-checking the merged tree; only a real conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
Keep artifacts under the supplied run/stage artifact directory. Mark unverified
builds as WIP. Verify any download URL serves the real bytes before reporting it.
+79 -8
View File
@@ -2,8 +2,8 @@
A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
`checks`, `limits` (`references/control.md`), `permissions` and `notify`
(`references/notifications.md`). There are no memory, links, input or output
`checks`, `limits` (`references/control.md`), `permissions`, `notify`
(`references/notifications.md`) and, on check stages, `commands`. There are no memory, links, input or output
blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
Schedules are saved run configurations, never definition blocks
(`references/schedules.md`).
@@ -102,8 +102,9 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
(`pipelines new NAME --template KEY`) fill them in; copy those IDs into a
hand-written draft. Availability needs `pipelines provider-check`.
- `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`).
`claude` needs `provider=anthropic` and a Claude model ID, and accepts no
`permissions` block, `delivery=true` or run write paths.
`claude` needs `provider=anthropic` and a Claude model ID; its `permissions`
block may hold only a `shell` allow-list (no `edit` patterns or run write
paths).
- `retries` 0–100, default 2 (three attempts). Retries cover transport failures
and timeouts; a stage with `edit`/`shell` (or no tools block) never replays
admitted work.
@@ -114,7 +115,10 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
- `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across
attempts and visits of this stage; totals include cache reads and writes. Set
only when the user asks or a measured visit exists (`references/practices.md`).
- `delivery=true`: the landing stage's gate (below). OpenCode harness only.
- `delivery=true`: the landing stage's gate (below), on any harness, or on a
check stage.
- `allow_workspace_changes=true`: lets a stage with `shell` but no `edit` leave file changes
in the run directory (below).
- `auto_skip=false`: disable the server skip fallback for a stage that declares a
`skipped` edge (`references/operations.md`, Server skip fallback).
@@ -134,6 +138,20 @@ patterns) and `shell` (exact commands) arrays. It narrows declared tools; it nev
enables a missing one. Empty arrays deny; wildcards, chaining, redirects and
traversal are rejected. With restricted edits and shell enabled, list shell too:
`{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`.
On `harness=claude` only `shell` is accepted; each entry becomes a Claude Code
rule (`go test ./...` -> `Bash(go test ./...)`) and an entry ending in ` *` is a
prefix (`git diff *` -> `Bash(git diff:*)`, any arguments; claude only). Claude
Code checks each part of a chained command, and every other command is
refused. A read-only reviewer: `{"shell":["git diff *","git log *","go test ./..."]}`.
A stage whose `tools` block has `shell` but not `edit` must leave the run directory as it
found it: the server compares the workspace before and after the visit and
fails the visit (`permission denied: ... changed the workspace (added x, ...)`,
following the `error` edge) when any file changed, outside the run's artifact
directories and a harness state directory inside the workspace. Committing is
not a change; merging or generating files is. Set
`allow_workspace_changes=true` on a stage that legitimately writes (for
example a land stage that merges main itself).
Named MCP entries are an explicit allowlist for unattended Claude stages:
`mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues`
@@ -190,6 +208,56 @@ A check must fail when it cannot run: validation rejects `|| true`, `|| :`,
`|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no
failing else, and `set +e`. Cover every language the run can change.
## Check stages
`type=check` runs shell commands on the server, without a model, and routes on
`pass` or `fail`. Use it before review, so a reviewer never sees a red tree, and
as the landing gate instead of a model stage that runs the suite itself.
````markdown
# stage verify
```configs
type=check
command_timeout=15m
```
```commands
uv run ruff check .
uv run ty check
uv run pytest -q
```
```edges
pass -> review
fail -> implement
```
```limits
{"max_visits":3}
```
````
- `commands` (required): 1-20 lines, one `sh -c` command each, run in order
from the run directory with its workspace environment; blank and `#` lines are
ignored. The first failure stops the rest (`not_run`) unless `keep_going=true`.
Lint rejects silent guards (`|| true`) as for `checks`.
- Configs: `command_timeout` (per command, default `30m`), `timeout` (the whole
stage, default `1h`), `keep_going=true|false`, `delivery=true`. No prompt,
tools, model or skills.
- Edges: `pass` and `fail` are required and are the only outcomes besides
`error` (an infrastructure failure). A `fail` loop back needs `limits`.
- Output: the step records each command's status (`passed`, `failed`,
`timed_out`, `not_run`), exit code, duration and output (64 KB per failing
command, head and tail kept), plus a one-line summary as its verdict. Its
`# handoff` names the failing commands with the tail of their output, and the
full outputs follow, so the next stage sees exactly what failed.
- `delivery=true` makes it the landing gate: the server commits what the run
left uncommitted (run worktrees), merges a moved `main`, runs the commands in
a fresh worktree of the commit and fast-forwards `main` on `pass`. A failing
command is `fail` with `main` untouched; a gate problem (dirty checkout,
conflict, refused fast-forward) is `error`.
## Human stages
`type=human` pauses the run until a person picks one of its non-`error` edges
@@ -201,14 +269,17 @@ wait survives restarts and is never killed by a stage timeout or `max_visits`.
## Land stage and delivery gate
A workflow that commits its change ends in `land`: a model stage with
`read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. Its prompt states:
A workflow that commits its change ends in `land`: either a check stage with
`delivery=true` (above; no model, the server commits and lands), or a model
stage with `read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. A model
land stage's prompt states:
1. Commit only this run's changes (server list + git status).
2. Check the staged diff for unrelated work and secrets.
3. No empty commit, push, amend or rebase. Report the hash.
With `delivery=true` and `checks` commands, after `land` succeeds the server:
With `delivery=true` and `checks` commands (any harness), after `land` succeeds
the server:
commits whatever the run left uncommitted when the item is the run's own
worktree (see "Run worktrees" below); requires the item checkout to be clean,
untracked files included (the main checkout need not be: the final
+19
View File
@@ -119,6 +119,25 @@ func TestInspectStepAndTranscriptsAndJSON(t *testing.T) {
}
}
func TestInspectStepListsCheckCommandsAndRepairs(t *testing.T) {
d := &protocol.RunDetail{ID: 7, Steps: []protocol.RunStep{{Sequence: 1, Stage: "verify", Status: "completed", Outcome: "fail",
Control: &protocol.ControlEvidence{OutcomeRepairs: 1},
Output: map[string]any{"markdown": "# outcome\n\nfail\n", "checks": []any{
map[string]any{"command": "go vet ./...", "status": "passed", "exit_code": float64(0), "duration_ms": float64(1200)},
map[string]any{"command": "go test ./...", "status": "failed", "exit_code": float64(1), "duration_ms": float64(51000)},
}}}}}
var out bytes.Buffer
if err := (App{Out: &out}).inspect(d, &options{step: 1}); err != nil {
t.Fatal(err)
}
text := out.String()
for _, want := range []string{"outcome repair follow-ups: 1", "passed exit 0 1.2s go vet ./...", "failed exit 1 51.0s go test ./..."} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q:\n%s", want, text)
}
}
}
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
line := waitLine(sampleRun())
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
+14
View File
@@ -93,9 +93,23 @@ func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string,
if step.SessionID != "" {
b.WriteString("session: " + step.SessionID + "\n")
}
if step.Control != nil && step.Control.OutcomeRepairs > 0 {
fmt.Fprintf(&b, "outcome repair follow-ups: %d\n", step.Control.OutcomeRepairs)
}
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
}
if checks, ok := step.Output["checks"].([]any); ok && len(checks) > 0 {
b.WriteString("\nchecks:\n")
for _, entry := range checks {
check, _ := entry.(map[string]any)
command, _ := check["command"].(string)
status, _ := check["status"].(string)
exit, _ := check["exit_code"].(float64)
duration, _ := check["duration_ms"].(float64)
fmt.Fprintf(&b, " %-9s exit %-3d %6.1fs %s\n", status, int(exit), duration/1000, command)
}
}
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
} else if len(step.Output) > 0 {
+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)
}
}
+89
View File
@@ -0,0 +1,89 @@
package pipeline
import (
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func checkStageSource(key, commands, configs, edges string) string {
return "# stage " + key + "\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n"
}
// A check stage sits between implement and review: a red tree goes back to
// the implementer with the failing output, never to the reviewer.
func TestParseCheckStageBeforeReview(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change.", "read\nedit\nshell", "success -> verify\nerror -> #failure", "```checks\nnone: the verify stage runs the suite\n```"),
checkStageSource("verify", "go vet ./...\ngo test ./...", "command_timeout=15m", "pass -> review\nfail -> implement"),
modelStage("review", "Review the diff.", "read\nglob\ngrep", "success -> #success\nerror -> #failure", ""),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
verify := g.Stages[1]
if verify.Type != stage.CheckType || verify.Blocks["commands"] != "go vet ./...\ngo test ./..." || verify.Configs["command_timeout"] != "15m" {
t.Fatalf("parsed %+v", verify)
}
if verify.Edges["error"] != "#failure" || !verify.FallbackError {
t.Fatal("check stage error edge", verify.Edges)
}
def := StageDefinition(verify)
if _, err := stage.CheckStageSpec(def); err != nil {
t.Fatal("stored definition no longer validates:", err)
}
errs, _ := Lint(g)
var rules []string
for _, finding := range errs {
rules = append(rules, finding.String())
}
// fail -> implement loops back: the existing loop rule asks for a limit.
if len(errs) != 1 || errs[0].Rule != "limits" {
t.Fatalf("lint %v", rules)
}
limited := strings.Replace(source, "```configs\ntype=check", "```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check", 1)
if g, err = ParseDefinition(limited); err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
}
func TestCheckStageRejectsModelBlocksAndSilentGuards(t *testing.T) {
if _, err := ParseDefinition(checkStageSource("verify", "go test ./...", "model=x", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("model config accepted on a check stage")
}
if _, err := ParseDefinition(checkStageSource("verify", "", "", "pass -> #success\nfail -> #failure")); err == nil {
t.Fatal("empty commands accepted")
}
g, err := ParseDefinition(checkStageSource("verify", "ruff check . || true", "", "pass -> #success\nfail -> #failure"))
if err != nil {
t.Fatal(err)
}
errs, _ := Lint(g)
if len(errs) != 1 || errs[0].Rule != "commands" {
t.Fatal(errs)
}
}
// A delivery check stage is the landing gate: its commands are the checks the
// server runs on the committed candidate before fast-forwarding main.
func TestCheckStageAsLandingGateSatisfiesDeliveryLint(t *testing.T) {
source := lintSource(
modelStage("implement", "Make the change; the delivery gate lands it.", "read\nedit\nshell", "success -> land\nerror -> #failure", "```checks\nnone: the land gate runs the suite\n```"),
checkStageSource("land", "go test ./...", "delivery=true", "pass -> #success\nfail -> #failure"),
)
g, err := ParseDefinition(source)
if err != nil {
t.Fatal(err)
}
if errs, _ := Lint(g); len(errs) != 0 {
t.Fatal(errs)
}
if enabled, err := stage.DeliveryEnabled(StageDefinition(g.Stages[1])); err != nil || !enabled {
t.Fatal(enabled, err)
}
}
+7
View File
@@ -90,6 +90,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
}
}
}
if stage.EffectiveType(s.Type) == stage.CheckType {
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
if guard := silentGuard(line); guard != "" {
add(&errs, s, "commands", "command %q can pass without running anything (%s); a missing tool must fail the check, so remove the guard", strings.TrimSpace(line), guard)
}
}
}
if stage.EffectiveType(s.Type) == stage.HumanType {
continue // a person bounds a human stage's loop
}
+9 -2
View File
@@ -458,6 +458,9 @@ type ControlEvidence struct {
LimitReached bool `json:"limit_reached,omitempty"`
ModelTarget string `json:"model_target,omitempty"`
Memory map[string]MemoryRead `json:"memory,omitempty"`
// OutcomeRepairs counts the "missing # outcome" repair follow-ups the
// server sent during this visit (0 when the first answer was valid).
OutcomeRepairs int `json:"outcome_repairs,omitempty"`
}
// StageFileChanges is observed workspace evidence, not a model's claim of authorship.
@@ -483,9 +486,13 @@ type FileChange struct {
NoPatch bool `json:"no_patch,omitempty"`
// NoPatchReason says why a content change has no (complete) patch:
// "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget),
// "lines" (over 5,000 combined lines), "evidence_size" (per-visit retained
// "lines" (over 20,000 combined lines), "evidence_size" (per-visit retained
// evidence limit), "git_status" (seen only in Git status) or "baseline"
// (stage-start content unrecoverable). Empty when a patch was recorded.
// (stage-start content unrecoverable). Policy reasons, which list the
// change completely and leave Truncated unset: "symlink" (target
// compared), "large" (over the hash bound; size/mtime/mode compared) and
// "generated" (lockfile, minified bundle, source map, cache file).
// Empty when a patch was recorded.
NoPatchReason string `json:"no_patch_reason,omitempty"`
BeforeMode string `json:"before_mode,omitempty"`
AfterMode string `json:"after_mode,omitempty"`
+1 -1
View File
@@ -126,7 +126,7 @@ func TestChatTurnDiffMarksBoundedPatchesTruncated(t *testing.T) {
dir := gitRepo(t, map[string]string{"a.txt": "x\n"})
h := turnDiffHub(t, dir)
h.startRoomTurnDiff("ses_1")
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 6000))
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 21000))
endDiffTurn(h, "ses_1")
turns := recordedTurns(t, h, "ses_1")
if len(turns) != 1 || !turns[0].Truncated || turns[0].Files != 1 || turns[0].Status != "partial" {
+146
View File
@@ -0,0 +1,146 @@
package server
import (
"context"
"errors"
"fmt"
"os"
"strings"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// errDeliveryChecksFailed marks a delivery check stage whose commands ran and
// failed on the candidate: that is the stage's fail outcome, not an error.
var errDeliveryChecksFailed = errors.New("delivery checks failed")
// runCheckStage executes a check stage. Without delivery its commands run in
// place in the run workspace. With delivery=true it is the landing gate: the
// server commits the run's leftovers, merges a moved main, runs the commands
// in a fresh candidate worktree of the commit and fast-forwards main only when
// every command passes. A failing command is the fail outcome (main is not
// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is
// an error.
func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) {
spec, err := stage.CheckStageSpec(def)
if err != nil {
return stage.Result{}, err
}
if !delivery {
def.Workspace = workspace
return stage.CheckStage{}.Run(ctx, def, nil)
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
var report stage.CheckReport
note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error {
report = stage.RunCheckCommands(ctx, candidate, spec)
if report.Failed() {
return errDeliveryChecksFailed
}
return nil
})
if err != nil && !errors.Is(err, errDeliveryChecksFailed) {
return stage.Result{}, err
}
result := stage.CheckResult(def.Key, spec, report)
markdown, _ := result.Output["markdown"].(string)
gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed."
if err == nil {
gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it."
}
if note != "" {
gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "."
}
result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1)
return result, nil
}
// checkVerdict is the check stage's one-line verdict: its own summary, never
// a model's paraphrase of the command output.
func checkVerdict(output stage.Values) *protocol.StageVerdict {
summary, _ := output["summary"].(string)
if strings.TrimSpace(summary) == "" {
return nil
}
return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback}
}
// readOnlyViolation reports the files a stage with shell but without edit
// left changed in the run directory: its shell is for reading, testing and
// committing, not for writing. A stage without shell cannot write at all (a
// change during it is not its own), and a stage with edit may write. Paths
// under the stage's artifacts directory, the run's shared public directory and
// a harness state directory that lives inside the workspace (for example
// CLAUDE_CONFIG_DIR) are the harness's or the run's own and are not counted.
// It returns "" when the stage may change files or none changed.
func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string {
if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil {
return ""
}
shell := false
for _, tool := range tools {
if tool == "edit" {
return ""
}
shell = shell || tool == "shell"
}
if !shell {
return ""
}
var prefixes []string
for _, dir := range ignored {
if rel, ok := workspaceRelative(workspace, dir); ok {
prefixes = append(prefixes, rel+"/")
}
}
var changed []string
for _, file := range changes.Files {
skip := false
for _, prefix := range prefixes {
if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) {
skip = true
break
}
}
if !skip {
changed = append(changed, file.Kind+" "+file.Path)
}
}
if len(changed) == 0 && changes.Omitted == 0 {
return ""
}
listed := changed
if len(listed) > 20 {
listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20))
}
if changes.Omitted > 0 {
listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted))
}
return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", "))
}
// workspaceEnv is the environment a command in workspace runs with: the run's
// directory environment when one applies, else the server's.
func workspaceEnv(ctx context.Context, workspace string) []string {
if env := workenv.CommandEnv(ctx, workspace); env != nil {
return env
}
return os.Environ()
}
// workspaceRelative returns dir relative to workspace when dir is inside it.
func workspaceRelative(workspace, dir string) (string, bool) {
workspace = strings.TrimSuffix(workspace, "/")
dir = strings.TrimSuffix(dir, "/")
if workspace == "" || dir == "" {
return "", false
}
if dir == workspace {
return ".", true
}
rel, ok := strings.CutPrefix(dir, workspace+"/")
return rel, ok && rel != ""
}
+206
View File
@@ -0,0 +1,206 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
func checkModelStage(key, tools, edges, configs string) string {
return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n"
}
func checkTypeStage(key, commands, edges, configs string) string {
return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n"
}
func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) {
t.Helper()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { store.Close() })
if _, err := store.Submit(ctx, "check", source); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = execute
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
return detail, store
}
// A failing check sends the run back to the implementer with the failing
// output in its input; the reviewer only runs once the tree is green.
func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) {
ctx := context.Background()
workspace := t.TempDir()
source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") +
checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") +
checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "")
var visits atomic.Int32
var secondInput string
detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "implement" {
if visits.Add(1) == 2 {
data, _ := os.ReadFile(def.Turn.Input)
secondInput = string(data)
if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil {
return stage.Result{}, err
}
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil
})
if detail.Status != "succeeded" {
t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
var stages []string
for _, step := range detail.Steps {
stages = append(stages, step.Stage+":"+step.Outcome)
}
if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" {
t.Fatal(got)
}
for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} {
if !strings.Contains(secondInput, want) {
t.Fatalf("implementer input lacks %q:\n%s", want, secondInput)
}
}
failed := detail.Steps[1]
if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") {
t.Fatalf("verdict %+v", failed.Verdict)
}
checks, _ := failed.Output["checks"].([]any)
if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" {
t.Fatalf("check step %+v", failed)
}
}
// A delivery check stage is the landing gate: the run's uncommitted work is
// committed, the commands run on a fresh candidate and main fast-forwards;
// a failing command is the fail outcome and leaves main alone.
func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) {
for _, test := range []struct {
name, command, status string
landed bool
}{
{"pass", "test -f work", "succeeded", true},
{"fail", "test -f absent", "failed", false},
} {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
main := filepath.Join(root, "main")
runGit(t, root, "init", "-b", "main", main)
runGit(t, main, "config", "user.email", "test@example.invalid")
runGit(t, main, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, main, "add", "README")
runGit(t, main, "commit", "-m", "base")
item := filepath.Join(root, "item")
runGit(t, main, "worktree", "add", "-b", "item", item)
if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil {
t.Fatal(err)
}
runGit(t, item, "add", "work")
runGit(t, item, "commit", "-m", "work")
before := runGitOutput(t, main, "rev-parse", "HEAD")
source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true")
detail, _ := startSource(t, ctx, source, item, nil)
if detail.Status != test.status || len(detail.Steps) != 1 {
t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps)
}
step := detail.Steps[0]
markdown, _ := step.Output["markdown"].(string)
if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true {
t.Fatalf("gate evidence missing: %q", markdown)
}
landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD")
if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) {
t.Fatalf("landed = %v, want %v", landed, test.landed)
}
})
}
}
// A stage without edit that changes the workspace fails its visit and names
// the files; allow_workspace_changes=true opts a stage out.
func TestReadOnlyStageThatChangesFilesFails(t *testing.T) {
ctx := context.Background()
for _, test := range []struct {
name, configs, status string
}{
{"enforced", "", "failed"},
{"allowed", "allow_workspace_changes=true", "succeeded"},
} {
t.Run(test.name, func(t *testing.T) {
workspace := t.TempDir()
if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil {
t.Fatal(err)
}
source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs)
detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil
})
if detail.Status != test.status {
t.Fatalf("run %s %q", detail.Status, detail.Diagnostic)
}
if test.status == "failed" {
diagnostic := detail.Steps[0].Diagnostic
if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") {
t.Fatal(diagnostic)
}
}
})
}
}
func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) {
def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}}
changes := &protocol.StageFileChanges{Files: []protocol.FileChange{
{Path: ".claude-profile/.claude.json", Kind: "modified"},
{Path: "artifacts/x/out.md", Kind: "added"},
}}
ignored := []string{"/w/.claude-profile", "/w/artifacts/x"}
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" {
t.Fatal(v)
}
changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"})
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") {
t.Fatal(v)
}
for name, ok := range map[string]bool{
"edit tool": readOnlyViolation(def, []string{"edit", "shell"}, true, changes, "/w", nil) == "",
"no shell (cannot write)": readOnlyViolation(def, []string{"read"}, true, changes, "/w", nil) == "",
"no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "",
} {
if !ok {
t.Fatal(name, "was enforced")
}
}
}
+17 -8
View File
@@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second
// own `merge --ff-only`, which refuses without touching anything when a local
// change or untracked file would be overwritten.
func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) {
return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error {
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
})
}
// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as
// a function of the fresh candidate worktree: a check stage records each
// command's result there instead of stopping at the first error.
func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) {
lock, err := acquireDeliveryLock(ctx, access.LockPath)
if err != nil {
return "", err
@@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA
note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged))
itemHead = merged
}
if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil {
if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil {
if note != "" {
return note, fmt.Errorf("%s; %w", note, err)
}
@@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) {
}
}
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error {
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error {
candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-")
if err != nil {
return fmt.Errorf("create delivery candidate: %w", err)
@@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check
return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output)))
}
defer cleanupDeliveryCandidate(workspace, candidate)
for _, check := range checks {
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
return err
}
}
return nil
return check(ctx, candidate)
}
// cleanupDeliveryCandidate always uses its own bounded context: the stage context
+32 -4
View File
@@ -2250,6 +2250,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
budgetBefore = budgets[key].Snapshot()
stageCtx = stage.WithBudget(stageCtx, budgets[key])
}
repairs := &stage.RepairCounter{}
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
before := filediff.Capture(snapshotCtx, workspace)
snapshotCancel()
@@ -2266,7 +2268,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
err = ctx.Err()
return
}
if r.execute != nil {
if stage.EffectiveType(def.Type) == stage.CheckType {
// The server runs a check stage's commands itself, in the run
// workspace or, for delivery, in a fresh candidate worktree.
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
} else if r.execute != nil {
timeout, _ := stage.StageTimeout(def)
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
defer cancel()
@@ -2444,7 +2450,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
}
}
if err == nil && delivery && result.Outcome == "success" {
if err == nil {
// A stage without edit must leave the run directory as it found it;
// a shell is not a licence to write (allow_workspace_changes opts out).
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
err = errors.New(violation)
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
step.Status = "failed"
step.Diagnostic = violation
step.Outcome = "error"
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
if len(result.Output) > 0 {
step.Output["salvage"] = result.Output
}
}
}
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
step.Verdict = checkVerdict(result.Output)
}
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
checks, checksErr := stage.DeliveryChecks(def)
if checksErr != nil {
err = checksErr
@@ -2488,7 +2513,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
return
}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
if step.Control.OutcomeRepairs > 0 {
log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs)
}
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
for _, outcome := range selected.Limits.On {
if outcome == step.Outcome {
@@ -2535,7 +2563,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
// markdown body, which the field-map summariser reads as untrusted data and
// answers with an invented rationale; those steps get the honest read-time
// fallback instead.
if r.verdict != nil && !turnOutputOnly(step.Output) {
if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
+6 -3
View File
@@ -190,12 +190,15 @@ func TestUISkipRunsModelOnAnyRecordedChange(t *testing.T) {
}
}
// TestUISkipPartialCaptureNeverSkips proves a visit whose capture was partial
// (here a protected .env file forces skipped>0) blocks the fallback even when
// (here a protected secrets/ directory, which is never walked, forces skipped>0;
// an untouched .env no longer does) blocks the fallback even when
// it recorded no file changes, and that inspect carries a run-level warning.
func TestUISkipPartialCaptureNeverSkips(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("A=1\n"), 0o600); err != nil {
if err := os.MkdirAll(filepath.Join(dir, "secrets"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "secrets", "token"), []byte("A=1\n"), 0o600); err != nil {
t.Fatal(err)
}
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), nil, dir)
+413
View File
@@ -0,0 +1,413 @@
package stage
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// CheckType is a stage the server runs itself: a list of shell commands in the
// run's workspace, no model. Its outcome is pass or fail, so a red tree can be
// routed back to the implementer (with the failing output as the handoff)
// before a reviewer or a landing stage ever sees it.
const CheckType = "check"
// Check outcomes. error stays the infrastructure-failure route, as for every
// stage type.
const (
CheckPass = "pass"
CheckFail = "fail"
)
// Per-command check statuses recorded on the step output.
const (
CheckStatusPassed = "passed"
CheckStatusFailed = "failed"
CheckStatusTimedOut = "timed_out"
CheckStatusNotRun = "not_run"
)
const (
maxCheckCommands = 20
maxCheckCommandBytes = 4096
defaultCommandTimeout = 30 * time.Minute
maxCheckOutputBytes = 64 << 10 // retained per failed command (head and tail)
maxPassedOutputBytes = 2 << 10 // retained per passing command (tail)
checkHandoffTailBytes = 1500 // per failed command in the handoff
checkOutputHeadBytes = 16 << 10
checkProcessWaitDelay = 5 * time.Second
checkFailureHandoffMax = 3
)
// CheckSpec is a validated check stage.
type CheckSpec struct {
Commands []string
CommandTimeout time.Duration
Timeout time.Duration
KeepGoing bool
Delivery bool
}
// CheckCommandResult is one command's recorded result (step output "checks").
type CheckCommandResult struct {
Command string `json:"command"`
Status string `json:"status"`
ExitCode int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
Output string `json:"output,omitempty"`
Truncated bool `json:"truncated,omitempty"`
}
// CheckReport is the result of running a check stage's commands once.
type CheckReport struct {
Commands []CheckCommandResult
}
// Failed reports whether any command did not pass.
func (r CheckReport) Failed() bool {
for _, c := range r.Commands {
if c.Status != CheckStatusPassed {
return true
}
}
return false
}
type CheckStage struct{}
var _ Stage = CheckStage{}
func (CheckStage) Validate(def Definition) error {
_, err := CheckStageSpec(def)
return err
}
// CheckStageSpec validates a check stage definition and returns its settings.
func CheckStageSpec(def Definition) (CheckSpec, error) {
if EffectiveType(def.Type) != CheckType {
return CheckSpec{}, fmt.Errorf("expected check stage")
}
for name := range def.Blocks {
switch name {
case "configs", "edges", "output", "commands":
case "skills":
return CheckSpec{}, errSkillsModelOnly("check")
case "prompt", "tools", "permissions", "checks":
return CheckSpec{}, fmt.Errorf("check stages run their commands block on the server, without a model; remove the %s block", name)
default:
return CheckSpec{}, fmt.Errorf("unexpected block %q for check stage", name)
}
}
commands, err := CheckCommands(def.Blocks["commands"])
if err != nil {
return CheckSpec{}, err
}
spec := CheckSpec{Commands: commands, CommandTimeout: defaultCommandTimeout}
for key, value := range def.Configs {
switch key {
case "timeout":
case "command_timeout":
duration, err := time.ParseDuration(value)
if err != nil || duration <= 0 {
return CheckSpec{}, fmt.Errorf("command_timeout must be a positive duration, such as 10m")
}
spec.CommandTimeout = duration
case "keep_going":
if value != "true" && value != "false" {
return CheckSpec{}, fmt.Errorf("keep_going must be true or false")
}
spec.KeepGoing = value == "true"
case "delivery":
if value != "true" {
return CheckSpec{}, fmt.Errorf("delivery must be true when set")
}
spec.Delivery = true
default:
return CheckSpec{}, fmt.Errorf("unknown check config %q (use timeout, command_timeout, keep_going or delivery)", key)
}
}
if spec.Timeout, err = StageTimeout(def); err != nil {
return CheckSpec{}, err
}
for _, outcome := range []string{CheckPass, CheckFail} {
if def.Edges[outcome] == "" {
return CheckSpec{}, fmt.Errorf("check stage requires %s and %s edges", CheckPass, CheckFail)
}
}
for outcome := range def.Edges {
if outcome != CheckPass && outcome != CheckFail && outcome != "error" {
return CheckSpec{}, fmt.Errorf("check stage outcomes are %s, %s and error; remove the %s edge", CheckPass, CheckFail, outcome)
}
}
return spec, nil
}
// CheckCommands parses a commands block: one shell command per line; blank
// lines and lines starting with # are ignored.
func CheckCommands(text string) ([]string, error) {
var commands []string
for _, line := range strings.Split(text, "\n") {
command := strings.TrimSpace(line)
if command == "" || strings.HasPrefix(command, "#") {
continue
}
if len(command) > maxCheckCommandBytes {
return nil, fmt.Errorf("check command exceeds %d bytes", maxCheckCommandBytes)
}
if !utf8.ValidString(command) || strings.ContainsRune(command, 0) {
return nil, fmt.Errorf("check commands must be UTF-8 text")
}
commands = append(commands, command)
}
if len(commands) == 0 || len(commands) > maxCheckCommands {
return nil, fmt.Errorf("check stage requires a commands block with 1 to %d commands, one per line", maxCheckCommands)
}
return commands, nil
}
// Run executes the commands in place in def.Workspace. The runner calls
// RunCheckCommands directly for a delivery check (in a fresh candidate
// worktree); this is the in-place path.
func (CheckStage) Run(ctx context.Context, def Definition, _ Values) (Result, error) {
spec, err := CheckStageSpec(def)
if err != nil {
return Result{}, err
}
if strings.TrimSpace(def.Workspace) == "" {
return Result{}, fmt.Errorf("check stage has no workspace")
}
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
defer cancel()
report := RunCheckCommands(ctx, def.Workspace, spec)
if err := ctx.Err(); err != nil && !report.Failed() {
return Result{}, err
}
return CheckResult(def.Key, spec, report), nil
}
// RunCheckCommands runs every command with `sh -c` from directory, in order,
// with the directory's workspace environment. It stops at the first failure
// unless KeepGoing; later commands are recorded as not_run.
func RunCheckCommands(ctx context.Context, directory string, spec CheckSpec) CheckReport {
report := CheckReport{}
stop := false
for _, command := range spec.Commands {
if stop || ctx.Err() != nil {
report.Commands = append(report.Commands, CheckCommandResult{Command: command, Status: CheckStatusNotRun, ExitCode: -1})
continue
}
result := runCheckCommand(ctx, directory, command, spec.CommandTimeout)
report.Commands = append(report.Commands, result)
if result.Status != CheckStatusPassed && !spec.KeepGoing {
stop = true
}
}
return report
}
func runCheckCommand(ctx context.Context, directory, command string, timeout time.Duration) CheckCommandResult {
commandCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(commandCtx, "sh", "-c", command)
cmd.Dir = directory
cmd.Env = workenv.CommandEnv(ctx, directory)
// A test suite starts children; a timeout kills the whole process group,
// and WaitDelay bounds a child that keeps the output pipes open.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return nil
}
cmd.WaitDelay = checkProcessWaitDelay
output := &headTailBuffer{head: checkOutputHeadBytes, limit: maxCheckOutputBytes}
cmd.Stdout = output
cmd.Stderr = output
started := time.Now()
err := cmd.Run()
result := CheckCommandResult{Command: command, DurationMS: time.Since(started).Milliseconds()}
result.Output, result.Truncated = output.String()
var exit *exec.ExitError
switch {
case err == nil:
result.Status = CheckStatusPassed
case commandCtx.Err() != nil:
result.Status = CheckStatusTimedOut
result.ExitCode = -1
if ctx.Err() != nil {
result.Output = strings.TrimRight(result.Output+"\n[stopped: the stage timeout or cancellation ended the command]", "\n")
} else {
result.Output = strings.TrimRight(result.Output+"\n[stopped: command_timeout "+timeout.String()+" reached]", "\n")
}
case errors.As(err, &exit):
result.Status = CheckStatusFailed
result.ExitCode = exit.ExitCode()
default:
result.Status = CheckStatusFailed
result.ExitCode = -1
result.Output = strings.TrimSpace(result.Output + "\n" + err.Error())
}
if result.Status == CheckStatusPassed && len(result.Output) > maxPassedOutputBytes {
cut := len(result.Output) - maxPassedOutputBytes
for cut < len(result.Output) && !utf8.RuneStart(result.Output[cut]) {
cut++
}
result.Output = "[... earlier output omitted ...]\n" + result.Output[cut:]
result.Truncated = true
}
return result
}
// CheckResult renders a report as the stage result: outcome pass or fail, the
// output.md-style markdown later stages read (handoff first, then every
// command's output), a one-line summary and the structured per-command list.
func CheckResult(key string, spec CheckSpec, report CheckReport) Result {
outcome := CheckPass
if report.Failed() {
outcome = CheckFail
}
summary := CheckSummary(report)
var b strings.Builder
b.WriteString("# outcome\n\n" + outcome + "\n\n# handoff\n\n" + summary + "\n")
failures := 0
for _, c := range report.Commands {
if c.Status != CheckStatusFailed && c.Status != CheckStatusTimedOut {
continue
}
failures++
if failures > checkFailureHandoffMax {
b.WriteString("\nMore failures are listed below.\n")
break
}
fmt.Fprintf(&b, "\n`%s` %s:\n\n~~~\n%s\n~~~\n", c.Command, checkStatusPhrase(c), tailText(c.Output, checkHandoffTailBytes))
}
if outcome == CheckFail {
b.WriteString("\nFix the cause; the server reruns these checks.\n")
}
b.WriteString("\n## Commands\n")
for _, c := range report.Commands {
fmt.Fprintf(&b, "\n### `%s`: %s\n", c.Command, checkStatusPhrase(c))
if c.Status == CheckStatusNotRun {
continue
}
if strings.TrimSpace(c.Output) == "" {
b.WriteString("\n(no output)\n")
continue
}
fmt.Fprintf(&b, "\n~~~\n%s\n~~~\n", c.Output)
}
checks := make([]any, 0, len(report.Commands))
for _, c := range report.Commands {
checks = append(checks, map[string]any{
"command": c.Command, "status": c.Status, "exit_code": c.ExitCode,
"duration_ms": c.DurationMS, "output": c.Output, "truncated": c.Truncated,
})
}
output := Values{"markdown": b.String(), "summary": summary, "checks": checks}
if spec.Delivery {
output["delivery"] = true
}
return Result{Outcome: outcome, Output: output}
}
// CheckSummary is the one-line verdict for a report.
func CheckSummary(report CheckReport) string {
total := len(report.Commands)
var failed []string
for _, c := range report.Commands {
if c.Status == CheckStatusFailed || c.Status == CheckStatusTimedOut {
failed = append(failed, c.Command)
}
}
if len(failed) == 0 {
if total == 1 {
return "1 check passed."
}
return strconv.Itoa(total) + " checks passed."
}
line := fmt.Sprintf("%d of %d checks failed: %s", len(failed), total, strings.Join(failed, "; "))
if len(line) > 180 {
line = strings.ToValidUTF8(line[:180], "") + "…"
}
return line
}
func checkStatusPhrase(c CheckCommandResult) string {
duration := (time.Duration(c.DurationMS) * time.Millisecond).Round(100 * time.Millisecond)
switch c.Status {
case CheckStatusPassed:
return "passed (" + duration.String() + ")"
case CheckStatusTimedOut:
return "timed out (" + duration.String() + ")"
case CheckStatusNotRun:
return "not run (an earlier check failed)"
default:
return fmt.Sprintf("failed with exit code %d (%s)", c.ExitCode, duration)
}
}
func tailText(text string, limit int) string {
text = strings.TrimSpace(text)
if len(text) <= limit {
if text == "" {
return "(no output)"
}
return text
}
cut := len(text) - limit
for cut < len(text) && !utf8.RuneStart(text[cut]) {
cut++
}
return "[...]\n" + text[cut:]
}
// headTailBuffer keeps the first head bytes and the last limit-head bytes of a
// stream: compiler errors come first, test summaries last.
type headTailBuffer struct {
head, limit int
first bytes.Buffer
tail []byte
dropped int64
}
func (b *headTailBuffer) Write(p []byte) (int, error) {
n := len(p)
if room := b.head - b.first.Len(); room > 0 {
take := min(room, len(p))
b.first.Write(p[:take])
p = p[take:]
}
if len(p) == 0 {
return n, nil
}
keep := b.limit - b.head
b.tail = append(b.tail, p...)
if over := len(b.tail) - keep; over > 0 {
b.dropped += int64(over)
b.tail = append(b.tail[:0], b.tail[over:]...)
}
return n, nil
}
// String returns the retained text and whether anything was dropped.
func (b *headTailBuffer) String() (string, bool) {
if b.dropped == 0 {
return strings.ToValidUTF8(strings.TrimRight(b.first.String()+string(b.tail), "\n"), "\uFFFD"), false
}
tail := b.tail
for len(tail) > 0 && !utf8.RuneStart(tail[0]) {
tail = tail[1:]
}
text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail)
return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true
}
+159
View File
@@ -0,0 +1,159 @@
package stage
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func checkDefinition(t *testing.T, commands string, configs map[string]string) Definition {
t.Helper()
if configs == nil {
configs = map[string]string{}
}
return Definition{Key: "verify", Type: CheckType, Workspace: t.TempDir(),
Blocks: map[string]string{"commands": commands, "configs": "type=check", "edges": "x"},
Configs: configs,
Edges: map[string]string{"pass": "review", "fail": "implement", "error": "#failure"}}
}
func TestCheckStageValidation(t *testing.T) {
def := checkDefinition(t, "# lint first\ngo vet ./...\n\ngo test ./...", map[string]string{"command_timeout": "5m", "keep_going": "true", "timeout": "20m", "delivery": "true"})
spec, err := CheckStageSpec(def)
if err != nil {
t.Fatal(err)
}
if len(spec.Commands) != 2 || spec.CommandTimeout != 5*time.Minute || spec.Timeout != 20*time.Minute || !spec.KeepGoing || !spec.Delivery {
t.Fatalf("spec %+v", spec)
}
if err := DefaultRegistry().Validate(def); err != nil {
t.Fatal("registry:", err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatal("delivery check", enabled, err)
}
for name, change := range map[string]func(*Definition){
"no commands": func(d *Definition) { d.Blocks["commands"] = "# only a comment\n" },
"too many": func(d *Definition) { d.Blocks["commands"] = strings.Repeat("true\n", 21) },
"prompt block": func(d *Definition) { d.Blocks["prompt"] = "Run the tests." },
"tools block": func(d *Definition) { d.Blocks["tools"] = "shell" },
"skills block": func(d *Definition) { d.Blocks["skills"] = "x" },
"unknown config": func(d *Definition) { d.Configs["model"] = "x" },
"bad timeout": func(d *Definition) { d.Configs["command_timeout"] = "soon" },
"bad keep_going": func(d *Definition) { d.Configs["keep_going"] = "yes" },
"bad delivery": func(d *Definition) { d.Configs["delivery"] = "false" },
"missing fail": func(d *Definition) { delete(d.Edges, "fail") },
"missing pass": func(d *Definition) { delete(d.Edges, "pass") },
"success outcome": func(d *Definition) { d.Edges["success"] = "#success" },
} {
t.Run(name, func(t *testing.T) {
copy := def
copy.Blocks, copy.Configs, copy.Edges = map[string]string{}, map[string]string{}, map[string]string{}
for k, v := range def.Blocks {
copy.Blocks[k] = v
}
for k, v := range def.Configs {
copy.Configs[k] = v
}
for k, v := range def.Edges {
copy.Edges[k] = v
}
change(&copy)
if err := (CheckStage{}).Validate(copy); err == nil {
t.Fatal("accepted")
}
})
}
}
func TestCheckStageRunsCommandsInTheWorkspace(t *testing.T) {
def := checkDefinition(t, "pwd > where.txt\necho all good", nil)
result, err := DefaultRegistry().Run(context.Background(), def, Values{})
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckPass {
t.Fatalf("outcome %q: %v", result.Outcome, result.Output)
}
where, _ := os.ReadFile(filepath.Join(def.Workspace, "where.txt"))
real, _ := filepath.EvalSymlinks(def.Workspace)
if got := strings.TrimSpace(string(where)); got != def.Workspace && got != real {
t.Fatalf("ran in %q, want %q", got, def.Workspace)
}
if result.Output["summary"] != "2 checks passed." {
t.Fatal("summary", result.Output["summary"])
}
checks := result.Output["checks"].([]any)
if len(checks) != 2 || checks[1].(map[string]any)["output"] != "all good" {
t.Fatalf("checks %v", checks)
}
}
func TestCheckStageFailureIsTheHandoff(t *testing.T) {
def := checkDefinition(t, "echo compiling\necho 'FAIL: TestParse expected 2' >&2; exit 3\necho never", nil)
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if result.Outcome != CheckFail {
t.Fatalf("outcome %q", result.Outcome)
}
markdown := result.Output["markdown"].(string)
handoff := markdown[strings.Index(markdown, "# handoff"):strings.Index(markdown, "## Commands")]
for _, want := range []string{"1 of 3 checks failed", "exit code 3", "FAIL: TestParse expected 2"} {
if !strings.Contains(handoff, want) {
t.Fatalf("handoff lacks %q:\n%s", want, handoff)
}
}
if !strings.HasPrefix(markdown, "# outcome\n\nfail\n") {
t.Fatalf("markdown does not start with the outcome:\n%s", markdown)
}
checks := result.Output["checks"].([]any)
if checks[2].(map[string]any)["status"] != CheckStatusNotRun {
t.Fatal("a later check ran after a failure", checks[2])
}
// keep_going runs every command and reports each failure.
def.Configs["keep_going"] = "true"
def.Blocks["commands"] = "exit 1\nexit 2\ntrue"
result, _ = (CheckStage{}).Run(context.Background(), def, nil)
if result.Output["summary"] != "2 of 3 checks failed: exit 1; exit 2" {
t.Fatal(result.Output["summary"])
}
}
func TestCheckStageCommandTimeoutKillsTheProcessGroup(t *testing.T) {
def := checkDefinition(t, "sleep 30 & echo started; wait", map[string]string{"command_timeout": "300ms"})
started := time.Now()
result, err := (CheckStage{}).Run(context.Background(), def, nil)
if err != nil {
t.Fatal(err)
}
if time.Since(started) > 10*time.Second {
t.Fatal("timeout did not stop the command", time.Since(started))
}
check := result.Output["checks"].([]any)[0].(map[string]any)
if result.Outcome != CheckFail || check["status"] != CheckStatusTimedOut || !strings.Contains(check["output"].(string), "command_timeout") {
t.Fatalf("result %v", check)
}
}
func TestCheckOutputIsBoundedHeadAndTail(t *testing.T) {
buffer := &headTailBuffer{head: 10, limit: 30}
for i := 0; i < 100; i++ {
_, _ = buffer.Write([]byte("0123456789"))
}
_, _ = buffer.Write([]byte("THE-END"))
text, truncated := buffer.String()
if !truncated || !strings.HasPrefix(text, "0123456789") || !strings.HasSuffix(text, "THE-END") || len(text) > 80 {
t.Fatalf("%v %q", truncated, text)
}
def := checkDefinition(t, "head -c 300000 /dev/zero | tr '\\0' x; echo; echo TAIL; exit 1", nil)
result, _ := (CheckStage{}).Run(context.Background(), def, nil)
check := result.Output["checks"].([]any)[0].(map[string]any)
if output := check["output"].(string); len(output) > maxCheckOutputBytes+200 || !strings.HasSuffix(output, "TAIL") || check["truncated"] != true {
t.Fatalf("output %d bytes, truncated %v", len(output), check["truncated"])
}
}
+31 -5
View File
@@ -135,7 +135,10 @@ func claudeMCPAllowRules(tools []string) ([]string, error) {
// approved only below the run directory and the stage's artifacts directory;
// everything else a declared tool does not need approval for stays denied by
// dontAsk.
func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
//
// A non-nil shell allow-list replaces the bare Bash rule with one Bash(...)
// rule per permitted command, so any other command is refused.
func claudeAllowRules(tools []string, directory, artifactsDir string, shell []string) []string {
rules := []string{}
edit := false
for _, tool := range tools {
@@ -143,6 +146,12 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string {
case "Edit":
edit = true
case "Write":
case "Bash":
if shell != nil {
rules = append(rules, claudeShellRules(shell)...)
} else {
rules = append(rules, tool)
}
default:
rules = append(rules, tool)
}
@@ -164,7 +173,7 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
// skills block) may be loaded. A skill only adds instructions; the declared
// tools and their rules still bound what the session can do.
tools = append(append([]string(nil), tools...), "Skill")
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir)
rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir, c.Policy.Shell)
args := []string{"-p", "--output-format", "stream-json", "--verbose",
"--model", config.Model,
"--permission-mode", "dontAsk",
@@ -220,10 +229,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
if effort == "none" || effort == "minimal" {
return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
}
if len(c.WritePaths) > 0 || c.Policy.Edit != nil || c.Policy.Shell != nil {
if len(c.WritePaths) > 0 || c.Policy.Edit != nil {
// The other harnesses enforce these narrower scopes themselves. Claude
// Code's rule syntax is not audited for them, so refuse, never widen.
return "", fmt.Errorf("the claude harness cannot enforce a permissions block or a narrowed write scope; use the opencode harness for this stage")
// Code's edit-path rules are not audited for them, so refuse, never
// widen. A shell allow-list is enforced with Bash(...) rules.
return "", fmt.Errorf("the claude harness cannot enforce permissions.edit or a narrowed write scope; use the opencode harness for this stage")
}
tools, err := claudeTools(c.Tools)
if err != nil {
@@ -300,6 +310,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
}
owned = true
}
if c.Policy.Shell != nil {
// The allow-list is enforced by Bash(...) rules; say it up front so the
// session does not spend turns on refused commands.
prompt += "\nPermitted shell commands (a trailing * allows any arguments; anything else is refused): " + strings.Join(c.Policy.Shell, "; ")
}
if adopted != nil {
// The prompt was admitted by the previous process. The evidence stream
// is rebuilt from the CLI's own output, so nothing is listed twice.
@@ -363,6 +378,17 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string {
// claudeConfigDir is the Claude Code configuration directory the stage's CLI
// will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude.
// HarnessStateDirs are directories a harness itself writes during a visit
// (Claude Code's config directory: session state, caches) for the given
// environment. When one lives inside the run directory its changes are the
// harness's, not the stage's.
func HarnessStateDirs(env []string) []string {
if dir := claudeConfigDir(env); dir != "" {
return []string{filepath.Clean(dir)}
}
return nil
}
func claudeConfigDir(env []string) string {
lookup := func(name string) string {
for i := len(env) - 1; i >= 0; i-- {
+78 -8
View File
@@ -246,6 +246,74 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) {
}
}
// A shell allow-list replaces the bare Bash rule: only the listed commands
// (exact, or a prefix with any arguments) are approved under dontAsk.
func TestClaudeStageShellAllowListMapsToBashRules(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "shell"}
client.Policy.Shell = []string{"go test ./...", "git diff *"}
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
calls := fakeClaudeArgs(t, root)
if len(calls) != 1 {
t.Fatal(calls)
}
args := calls[0]
for _, want := range []string{"Read,Bash,Skill", "Bash(go test ./...)", "Bash(git diff:*)"} {
if !slices.Contains(args, want) {
t.Fatalf("missing %q in args %q", want, args)
}
}
if slices.Contains(args, "Bash") {
t.Fatalf("a bare Bash rule approves every command: %q", args)
}
prompt, _ := os.ReadFile(filepath.Join(root, "prompt"))
if !strings.Contains(string(prompt), "Permitted shell commands") || !strings.Contains(string(prompt), "git diff *") {
t.Fatalf("prompt does not name the allow-list: %q", prompt)
}
// An empty list approves no command at all.
client2, root2, _ := fakeClaudeClient(t, "success")
client2.Tools = []string{"shell"}
client2.Policy.Shell = []string{}
if _, err := client2.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
t.Fatal(err)
}
for _, arg := range fakeClaudeArgs(t, root2)[0] {
if strings.HasPrefix(arg, "Bash") && arg != "Bash,Skill" {
t.Fatalf("empty allow-list approved %q", arg)
}
}
}
func TestClaudeStagePermissionsValidation(t *testing.T) {
def := func(permissions string) Definition {
return Definition{Key: "review", Type: ModelType,
Blocks: map[string]string{"prompt": "Review.", "configs": "x", "tools": "read\nshell", "permissions": permissions},
Configs: map[string]string{"harness": "claude", "provider": "anthropic", "model": "claude-haiku-5-5"},
Edges: map[string]string{"success": "#success"}}
}
if _, err := (ModelStage{}).Spec(def(`{"shell":["git diff *","go test ./..."]}`)); err != nil {
t.Fatal("shell allow-list rejected:", err)
}
for name, permissions := range map[string]string{
"edit": `{"edit":["a.go"],"shell":[]}`,
"chaining": `{"shell":["go test && rm x"]}`,
"mid star": `{"shell":["git * diff"]}`,
"parentheses": `{"shell":["echo (x)"]}`,
} {
if _, err := (ModelStage{}).Spec(def(permissions)); err == nil {
t.Fatal(name, "accepted")
}
}
// Prefix entries are claude-only: other harnesses enforce exact commands.
opencode := def(`{"shell":["git diff *"]}`)
opencode.Configs = map[string]string{"provider": "opencode-go", "model": "deepseek-v4.1-flash"}
if _, err := (ModelStage{}).Spec(opencode); err == nil || !strings.Contains(err.Error(), "claude harness") {
t.Fatal("opencode prefix permission:", err)
}
}
func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "success")
client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"}
@@ -272,12 +340,11 @@ func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) {
func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) {
for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"shell permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Shell = []string{"go test"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
"write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} },
"edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} },
"unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} },
"other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" },
"no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" },
} {
t.Run(name, func(t *testing.T) {
client, root, active := fakeClaudeClient(t, "success")
@@ -344,7 +411,8 @@ func TestClaudeStageBudgetAccounting(t *testing.T) {
func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
client, root, _ := fakeClaudeClient(t, "repair")
budget := NewBudget(0, 1000)
ctx := withOutputRepair(context.Background(), []string{"error", "success"})
counter := &RepairCounter{}
ctx := withOutputRepair(WithRepairCounter(context.Background(), counter), []string{"error", "success"})
text, err := client.Generate(ctx, claudeConfig(budget), "task")
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
t.Fatalf("%q %v", text, err)
@@ -357,6 +425,9 @@ func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) {
if budget.Snapshot().UsedTokens != 34 {
t.Fatalf("usage %+v", budget.Snapshot())
}
if counter.Count() != 1 {
t.Fatalf("repair follow-ups counted %d, want 1", counter.Count())
}
}
func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) {
@@ -413,7 +484,6 @@ func TestClaudeHarnessValidation(t *testing.T) {
"unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil),
"other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil),
"delivery": definition(claude(map[string]string{"delivery": "true"}), nil),
"permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}),
"no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil),
} {
+7 -5
View File
@@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
}
for key := range def.Configs {
switch key {
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip":
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes":
default:
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
}
@@ -111,8 +111,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("auto_skip must be true or false")
}
if def.Configs["delivery"] == "true" && backend != "opencode" {
return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness")
// allow_workspace_changes=true lets a stage with shell but no edit leave file changes
// in the run directory; by default the runner fails such a visit.
if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" {
return ModelSpec{}, fmt.Errorf("allow_workspace_changes must be true or false")
}
if err := ValidateChecksBlock(def); err != nil {
return ModelSpec{}, err
@@ -143,8 +145,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
if _, err := claudeTools(tools); err != nil {
return ModelSpec{}, err
}
if _, present := def.Blocks["permissions"]; present {
return ModelSpec{}, fmt.Errorf("the claude harness cannot enforce a permissions block; use the opencode harness for this stage")
if err := claudePermissionsSupported(def); err != nil {
return ModelSpec{}, err
}
if effort == "none" || effort == "minimal" {
return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max")
+30 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"strings"
"sync/atomic"
"git.a-wan.net/alan/pipelines/internal/turn"
)
@@ -13,14 +14,38 @@ import (
// message in the same session asking only for the outcome, instead of failing
// a stage whose admitted work a full retry would repeat. The outcome is always
// stated by the model; the server never infers one from prose.
type outputRepair struct{ outcomes []string }
type outputRepair struct {
outcomes []string
counter *RepairCounter
}
type outputRepairKey struct{}
type repairCounterKey struct{}
// RepairCounter counts the outcome repair follow-ups sent during one visit
// (across its attempts). The runner records the count on the step.
type RepairCounter struct{ n atomic.Int32 }
// Count is the number of follow-ups sent so far.
func (c *RepairCounter) Count() int {
if c == nil {
return 0
}
return int(c.n.Load())
}
// WithRepairCounter makes every outcome repair follow-up under ctx increment
// counter.
func WithRepairCounter(ctx context.Context, counter *RepairCounter) context.Context {
return context.WithValue(ctx, repairCounterKey{}, counter)
}
// withOutputRepair lets a model client repair a missing or invalid outcome
// for the given declared outcomes while its session is still open.
func withOutputRepair(ctx context.Context, outcomes []string) context.Context {
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes})
counter, _ := ctx.Value(repairCounterKey{}).(*RepairCounter)
return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes, counter: counter})
}
// outputRepairFrom returns the attempt's repair, or nil when none applies.
@@ -40,6 +65,9 @@ func (r *outputRepair) followUp(text string) (string, bool) {
if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) {
return "", false
}
if r.counter != nil {
r.counter.n.Add(1)
}
allowed := strings.Join(r.outcomes, ", ")
return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " +
outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n<one of: " + allowed + ">\n", true
+52 -2
View File
@@ -77,9 +77,17 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
seen[pattern] = true
}
seen = map[string]bool{}
claude := def.Configs["harness"] == ClaudeBackend
for _, command := range policy.Shell {
if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion")
exact, prefix := ShellPermissionPrefix(command)
if prefix && !claude {
return ToolPolicy{}, fmt.Errorf("shell prefix permissions (%q) are supported only by the claude harness; list exact commands", command)
}
if exact == "" || strings.TrimSpace(exact) != exact || strings.ContainsAny(exact, "*?;|&<>`$\r\n\\") {
return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands (or, on the claude harness, a command prefix ending in \" *\") without other wildcards, chaining, redirects, or expansion")
}
if claude && strings.ContainsAny(exact, "()") {
return ToolPolicy{}, fmt.Errorf("claude shell permissions cannot contain parentheses")
}
if seen[command] {
return ToolPolicy{}, fmt.Errorf("duplicate shell permission")
@@ -92,3 +100,45 @@ func StagePermissions(def Definition) (ToolPolicy, error) {
}
return *policy, nil
}
// ShellPermissionPrefix splits a permissions.shell entry. "go test *" is a
// prefix entry (the command with any arguments; claude harness only) and
// returns ("go test", true); any other entry is an exact command.
func ShellPermissionPrefix(entry string) (string, bool) {
if base, ok := strings.CutSuffix(entry, " *"); ok {
return base, true
}
return entry, false
}
// claudePermissionsSupported limits a claude stage's permissions block to a
// shell allow-list (mapped to Bash(...) rules). Claude Code's edit-path rules
// are not audited, so restricted edits stay with the other harnesses.
func claudePermissionsSupported(def Definition) error {
if _, present := def.Blocks["permissions"]; !present {
return nil
}
policy, err := StagePermissions(def)
if err != nil {
return err
}
if policy.Edit != nil {
return fmt.Errorf("the claude harness enforces only permissions.shell; remove permissions.edit or use the opencode harness for this stage")
}
return nil
}
// claudeShellRules maps a shell allow-list to Claude Code permission rules:
// an exact command to Bash(command) and a prefix entry to Bash(prefix:*).
// Claude Code checks each part of a chained command against the rules.
func claudeShellRules(shell []string) []string {
rules := make([]string, 0, len(shell))
for _, entry := range shell {
if base, prefix := ShellPermissionPrefix(entry); prefix {
rules = append(rules, "Bash("+base+":*)")
} else {
rules = append(rules, "Bash("+base+")")
}
}
return rules
}
+5 -2
View File
@@ -33,7 +33,10 @@ type Definition struct {
// ArtifactsDir is the per-run/step directory the runtime created for this
// visit; empty when the runner did not provide one (for example in tests).
ArtifactsDir string
Turn TurnPaths
// Workspace is the run directory (runtime-provided); a check stage runs
// its commands there.
Workspace string
Turn TurnPaths
// Skills is the visit's materialised skills block (runtime-provided, like
// ArtifactsDir); nil when the stage configures none or in tests.
Skills *SkillSet
@@ -72,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry {
}
func DefaultRegistry() *Registry {
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}})
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}})
}
func EffectiveType(name string) string {
+10 -3
View File
@@ -40,8 +40,9 @@ func (a LandingAccess) valid() bool {
}
// DeliveryEnabled is the narrow, declarative capability check used before the
// runner supplies any landing paths. Only a validated model definition can ask
// for it; runtime paths are still derived by the server.
// runner supplies any landing paths. Only a validated model or check
// definition can ask for it, whatever its harness; runtime paths are still
// derived by the server.
func DeliveryEnabled(def Definition) (bool, error) {
delivery := def.Configs["delivery"]
if delivery == "" {
@@ -50,8 +51,14 @@ func DeliveryEnabled(def Definition) (bool, error) {
if delivery != "true" {
return false, fmt.Errorf("delivery must be true when set")
}
if EffectiveType(def.Type) == CheckType {
if _, err := CheckStageSpec(def); err != nil {
return false, fmt.Errorf("invalid delivery check stage: %w", err)
}
return true, nil
}
if EffectiveType(def.Type) != ModelType {
return false, fmt.Errorf("delivery is supported only by model stages")
return false, fmt.Errorf("delivery is supported only by model and check stages")
}
if _, err := (ModelStage{}).Spec(def); err != nil {
return false, fmt.Errorf("invalid delivery model stage: %w", err)
+19 -10
View File
@@ -246,18 +246,27 @@ func TestDeliveryEnabledRequiresValidatedModelStage(t *testing.T) {
}
}
func TestDeliveryRejectsPiBeforeAgentExecution(t *testing.T) {
func TestDeliveryIsHarnessAgnostic(t *testing.T) {
for _, harness := range []string{"opencode", "pi"} {
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = harness
def.Blocks["checks"] = "go test ./..."
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatalf("%s delivery was rejected: %v", harness, err)
}
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("%s delivery = %v, %v", harness, enabled, err)
}
}
def := modelDefinition()
def.Configs["delivery"] = "true"
def.Configs["harness"] = "pi"
def.Blocks["checks"] = "true"
if err := (ModelStage{}).Validate(def); err == nil || !strings.Contains(err.Error(), "opencode harness") {
t.Fatal("Pi delivery was accepted", err)
}
delete(def.Configs, "delivery")
delete(def.Blocks, "checks")
if err := (ModelStage{}).Validate(def); err != nil {
t.Fatal("Pi non-delivery was changed", err)
def.Configs["harness"] = ClaudeBackend
def.Configs["provider"] = ClaudeProvider
def.Configs["model"] = "claude-sonnet-4-5"
def.Blocks["checks"] = "go test ./..."
if enabled, err := DeliveryEnabled(def); err != nil || !enabled {
t.Fatalf("claude delivery = %v, %v", enabled, err)
}
}