Merge main into the engine loop improvements
Keep both intents: check stages, allow_workspace_changes, outcome repair counts and Claude stage re-adoption from main beside the findings gate, resume_session, applyLimitOn and exhaustion decisions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -42,14 +42,10 @@ preserved branch. `failed` and `interrupted` (server stopped mid-run) runs can b
|
||||
retried: resume reruns the failed or interrupted stage, or starts the next stage
|
||||
after the last completed one. `canceled` runs need a new run or direct work on
|
||||
their branch. A retried stage's `input.md` carries a `# Previous attempt` section
|
||||
(why the last attempt failed, plus the failed visit's partial `output.md` and
|
||||
`private/` files copied under `previous-attempt/`) and, with `--input-file`, a
|
||||
`# Operator correction` section holding only the overridden keys. A run that
|
||||
failed because a loop exhausted its visits continues with `--extra-visits N
|
||||
[--stage KEY]`; a run waiting on an exhausted loop (`on_exhausted: decide`) is
|
||||
answered with `pipelines decide <id> --option accept|continue|abort`.
|
||||
`inspect` shows the run's findings ledger (stable `F1`, `F2` IDs; stages report
|
||||
them in a `# findings` section, `references/format.md`).
|
||||
(why it failed; partial work under `previous-attempt/`) and, with
|
||||
`--input-file`, a `# Operator correction`. An exhausted loop continues with
|
||||
`--extra-visits N [--stage KEY]` (`references/control.md`); `inspect` shows the
|
||||
findings ledger (`references/format.md`).
|
||||
|
||||
## Use an existing pipeline
|
||||
|
||||
@@ -70,7 +66,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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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`).
|
||||
@@ -160,8 +160,9 @@ edges are allowed.
|
||||
(`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.
|
||||
@@ -172,7 +173,10 @@ edges are allowed.
|
||||
- `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).
|
||||
- `resume_session=true`: on a loop visit, resume this stage's previous harness
|
||||
session instead of starting a cold one (Claude harness only; others start
|
||||
fresh; a session Claude Code no longer has starts fresh). Use it for
|
||||
@@ -196,6 +200,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`
|
||||
@@ -252,6 +270,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
|
||||
@@ -263,14 +331,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
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -107,9 +107,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 {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -107,6 +107,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
|
||||
add(&warnings, s, "resume_session", "resume_session on a read-only stage carries its earlier verdicts into later visits; keep reviewers on fresh sessions and resume only implementers")
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// RunWritePaths returns the write paths a run declared (relative to its
|
||||
// workspace; empty when it declared none). The workspace reservation check
|
||||
// reads it only when two runs' workspaces nest outside any repository.
|
||||
func (s *Store) RunWritePaths(ctx context.Context, id int64) ([]string, error) {
|
||||
var encoded string
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT write_paths FROM pipeline_runs WHERE id=?", id).Scan(&encoded); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var paths []string
|
||||
if encoded == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err := json.Unmarshal([]byte(encoded), &paths); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
@@ -99,7 +99,7 @@ func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail,
|
||||
// Acquire the SQLite writer lock while checking the original saved
|
||||
// revision and occurrence. Edits/deletes between claim and admission
|
||||
// invalidate admission, including while a title was being generated.
|
||||
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status='claimed' AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
|
||||
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status IN ('claimed','delayed') AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
@@ -409,6 +409,15 @@ func (s *Store) FinishSavedSchedule(ctx context.Context, id int64, due time.Time
|
||||
return err
|
||||
}
|
||||
|
||||
// SavedScheduleOccurrence reads one occurrence's history entry: its status
|
||||
// (claimed, delayed, admitted, started, skipped, skipped_missed, skipped_day),
|
||||
// diagnostic and admitted run (0 when none).
|
||||
func (s *Store) SavedScheduleOccurrence(ctx context.Context, id int64, due time.Time) (status, diagnostic string, runID int64, err error) {
|
||||
var run sql.NullInt64
|
||||
err = s.db.QueryRowContext(ctx, `SELECT status,diagnostic,run_id FROM saved_schedule_events WHERE schedule_id=? AND due=?`, id, due.UTC().Format(time.RFC3339Nano)).Scan(&status, &diagnostic, &run)
|
||||
return status, diagnostic, run.Int64, err
|
||||
}
|
||||
|
||||
// ScheduleAdmission is an internal capability, never decoded from public messages.
|
||||
type ScheduleAdmission struct {
|
||||
ID, Revision int64
|
||||
|
||||
@@ -53,6 +53,9 @@ const (
|
||||
// NotificationChatNotify is an agent's own notify tool call. Its priority
|
||||
// is the tool's: low 2, default 3, high 4.
|
||||
NotificationChatNotify = "chat_notify"
|
||||
// NotificationSchedule says a scheduled run was delayed (its workspace was
|
||||
// busy) or skipped. It is low priority (2).
|
||||
NotificationSchedule = "schedule"
|
||||
)
|
||||
|
||||
// DefaultNotificationPriority is ntfy's default priority, which every ntfy
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -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" {
|
||||
|
||||
@@ -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 != ""
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
|
||||
|
||||
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
|
||||
_, r, pipelineID := concurrentStore(t)
|
||||
// One repository: its folder and a folder inside it are one shared tree.
|
||||
workspace := t.TempDir()
|
||||
child := filepath.Join(workspace, "child")
|
||||
if err := os.Mkdir(child, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
|
||||
if err := os.Mkdir(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
alias := filepath.Join(t.TempDir(), "alias")
|
||||
if err := os.Symlink(child, alias); err != nil {
|
||||
@@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Two folders outside any repository (the operator's ~/caplens and a sibling
|
||||
// project folder under it) are not one tree merely because neither is in a
|
||||
// repository: nested, they overlap only where the outer run's declared write
|
||||
// paths reach the inner folder. The same folder always overlaps.
|
||||
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
|
||||
hub := t.TempDir()
|
||||
brief := filepath.Join(hub, "brief")
|
||||
notes := filepath.Join(hub, "notes", "deep")
|
||||
for _, dir := range []string{brief, notes} {
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
paths := func(p ...string) func() []string { return func() []string { return p } }
|
||||
for _, test := range []struct {
|
||||
a, b string
|
||||
aPaths, bPaths func() []string
|
||||
want bool
|
||||
}{
|
||||
{hub, hub, nil, nil, true},
|
||||
{brief, brief, nil, nil, true},
|
||||
{hub, brief, nil, nil, false},
|
||||
{brief, hub, nil, nil, false},
|
||||
{brief, notes, nil, nil, false},
|
||||
{hub, brief, paths("notes"), nil, false},
|
||||
{hub, brief, paths("brief"), nil, true},
|
||||
{hub, notes, paths("notes"), nil, true},
|
||||
{hub, notes, paths("notes/deep/file.md"), nil, true},
|
||||
{notes, hub, nil, paths("notes"), true},
|
||||
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
|
||||
{hub, brief, paths("."), nil, true},
|
||||
} {
|
||||
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
|
||||
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
|
||||
}
|
||||
}
|
||||
// Nested repository rules stay: a repository inside a plain folder is its
|
||||
// own tree whatever the folder's write paths.
|
||||
repo := filepath.Join(hub, "repo")
|
||||
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
|
||||
t.Fatal("a repository inside a plain folder overlaps it")
|
||||
}
|
||||
|
||||
// End to end: a scheduled brief in the hub is admitted while a run works in
|
||||
// a sibling folder below it, and refused only when it declares a write
|
||||
// path reaching that folder.
|
||||
_, r, pipelineID := concurrentStore(t)
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return stage.Result{Outcome: "success"}, nil
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
|
||||
t.Fatal("a hub run writing into the active folder was admitted:", err)
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal("a hub run was refused for a sibling folder's run:", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,12 +23,19 @@ import (
|
||||
// re-enters that visit, attaches to the session, waits for it to settle (or
|
||||
// reads the result it reached while the server was down) and continues the
|
||||
// graph as if it had watched it;
|
||||
// - a running Claude Code visit is re-adopted the same way: its CLI runs in
|
||||
// its own session writing stream-json to a file (see
|
||||
// stage.ClaudeStageClient), so the next process keeps reading that file
|
||||
// where the CLI is, waits for it to exit, or reads the result it left
|
||||
// while the server was down (an interrupted outcome repair follow-up is
|
||||
// asked again);
|
||||
// - a visit begun but never handed to a harness is marked interrupted and the
|
||||
// same stage starts again (nothing was admitted, so nothing replays);
|
||||
// - a run between visits continues with its next stage;
|
||||
// - a session whose harness process is gone, or that belongs to a harness the
|
||||
// server owned as a child (Pi, OpenCode V1), falls back to the previous
|
||||
// behaviour: the run is interrupted, with the reason in its diagnostic.
|
||||
// - a session whose harness process is gone (a Claude Code CLI that ended
|
||||
// without a result), or that belongs to a harness the server owned as a
|
||||
// child (Pi, OpenCode V1), falls back to the previous behaviour: the run
|
||||
// is interrupted, with the reason in its diagnostic.
|
||||
//
|
||||
// Only an operator cancel (cancel_run) stops a stage session.
|
||||
|
||||
@@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e
|
||||
return opencode.ReferenceAlive(ctx, owner.Reference)
|
||||
}
|
||||
|
||||
// claudeStageReattachable reports why a retained Claude Code stage session
|
||||
// cannot be re-adopted (nil when it can). It is a seam for tests.
|
||||
var claudeStageReattachable = stage.ClaudeStageReattachable
|
||||
|
||||
// interruptRecoveredSession stops a previously active session that start-up
|
||||
// recovery does not re-adopt. It is a seam for tests.
|
||||
var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error {
|
||||
@@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
owner.RunID = row.ID
|
||||
if owner.Backend == stage.ClaudeBackend {
|
||||
// Claude Code stage CLIs run detached from the server: re-adopt
|
||||
// one still running, or one that left its result while the
|
||||
// server was down.
|
||||
if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil {
|
||||
reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason)
|
||||
continue
|
||||
}
|
||||
plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner})
|
||||
continue
|
||||
}
|
||||
if owner.Backend != "v2" {
|
||||
name := "OpenCode V1"
|
||||
if owner.Backend == "pi" {
|
||||
name = "Pi"
|
||||
}
|
||||
if owner.Backend == stage.ClaudeBackend {
|
||||
name = "Claude Code"
|
||||
}
|
||||
reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) {
|
||||
t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final)
|
||||
}
|
||||
}
|
||||
|
||||
// ownedClaudeStage is a first-process stage one whose Claude Code CLI
|
||||
// (session claude-live) is still running, detached, at shutdown.
|
||||
func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
|
||||
if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
<-ctx.Done()
|
||||
if stage.Detached(ctx) {
|
||||
return stage.Result{}, stage.ErrDetached
|
||||
}
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
|
||||
func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value {
|
||||
t.Helper()
|
||||
asked := &atomic.Value{}
|
||||
previous := claudeStageReattachable
|
||||
claudeStageReattachable = func(reference, session string) error {
|
||||
asked.Store(reference + " " + session)
|
||||
return reason
|
||||
}
|
||||
t.Cleanup(func() { claudeStageReattachable = previous })
|
||||
return asked
|
||||
}
|
||||
|
||||
// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a
|
||||
// restart is re-adopted from its retained session (never re-prompted, never
|
||||
// interrupted) and the run continues to the next stage.
|
||||
func TestClaudeStageRunContinuesAfterRestart(t *testing.T) {
|
||||
interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude"))
|
||||
asked := seamClaudeReattachable(t, nil)
|
||||
f := stopMidStage(t, ownedClaudeStage)
|
||||
var resumed atomic.Value
|
||||
r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) {
|
||||
if def.Key == "one" {
|
||||
resumed.Store(stage.TakeResumeSession(ctx))
|
||||
if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil
|
||||
})
|
||||
if interrupts.Load() != 0 {
|
||||
t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart")
|
||||
}
|
||||
if got, _ := asked.Load().(string); got != "ref-claude claude-live" {
|
||||
t.Fatalf("reattachability asked about %q", got)
|
||||
}
|
||||
r.reattachRuns()
|
||||
r.wg.Wait()
|
||||
d, err := s.GetRun(context.Background(), f.runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := resumed.Load().(string); got != "claude-live" {
|
||||
t.Fatalf("stage one was not re-adopted from its Claude session: %q", got)
|
||||
}
|
||||
if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" {
|
||||
t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI
|
||||
// that ended without a result while the server was down is not replayed; the
|
||||
// run is interrupted, saying why.
|
||||
func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) {
|
||||
interrupts := seamRestartRecovery(t, nil)
|
||||
seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result"))
|
||||
f := stopMidStage(t, ownedClaudeStage)
|
||||
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
|
||||
t.Error("a Claude stage without a result executed again")
|
||||
return stage.Result{}, nil
|
||||
})
|
||||
r.reattachRuns()
|
||||
r.wg.Wait()
|
||||
d, err := s.GetRun(context.Background(), f.runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") {
|
||||
t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
|
||||
}
|
||||
if interrupts.Load() != 1 {
|
||||
t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load())
|
||||
}
|
||||
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
|
||||
t.Fatalf("the lost session still blocks recovery: %+v", owners)
|
||||
}
|
||||
}
|
||||
|
||||
+115
-27
@@ -320,7 +320,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
return nil, err
|
||||
}
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -344,7 +344,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
// Another run may have reserved this workspace while the title was
|
||||
// generated, so re-check before reserving it; a race on the request key is
|
||||
// handled by the store's idempotent insert.
|
||||
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
|
||||
if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -381,7 +381,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
request.Input["pwd"] = workspace
|
||||
recheck := r.ctx.Err()
|
||||
if recheck == nil {
|
||||
recheck = r.checkAdmissionWorkspace(workspace, existing)
|
||||
recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...)
|
||||
}
|
||||
if recheck != nil {
|
||||
r.mu.Unlock()
|
||||
@@ -544,9 +544,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru
|
||||
// storage maintenance may have removed a clean inactive tree while an
|
||||
// admission was generating its title, so it is checked under the same lock
|
||||
// removal takes. Callers must hold r.mu.
|
||||
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
|
||||
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error {
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -558,14 +558,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error
|
||||
|
||||
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
|
||||
// reserves an overlapping resolved workspace. Callers must hold r.mu.
|
||||
func (r *runner) checkWorkspaceFree(workspace string) error {
|
||||
return r.checkWorkspaceFreeExcept(workspace, 0)
|
||||
// writePaths are the new run's declared write paths (they decide an overlap
|
||||
// only between nested folders outside any repository).
|
||||
func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error {
|
||||
return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...)
|
||||
}
|
||||
|
||||
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
|
||||
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error {
|
||||
own := func() []string { return writePaths }
|
||||
// pathsOf reads a reserving run's declared write paths only when needed.
|
||||
pathsOf := func(id int64) func() []string {
|
||||
return func() []string {
|
||||
read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
paths, err := r.store.RunWritePaths(read, id)
|
||||
if err != nil {
|
||||
// Unknown scope: keep the whole folder reserved (fail closed).
|
||||
return []string{"."}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
}
|
||||
for id, entry := range r.active {
|
||||
if workspacesOverlap(entry.workspace, workspace) {
|
||||
return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)
|
||||
if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) {
|
||||
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)}
|
||||
}
|
||||
}
|
||||
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
|
||||
@@ -575,35 +591,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error
|
||||
return fmt.Errorf("read pending export workspace reservations: %w", err)
|
||||
}
|
||||
for id, reserved := range reservations {
|
||||
if id != ownGate && workspacesOverlap(reserved, workspace) {
|
||||
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
|
||||
if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) {
|
||||
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// workspaceBusyError refuses an admission because another run (runID)
|
||||
// reserves an overlapping workspace; waiting can clear it.
|
||||
type workspaceBusyError struct {
|
||||
runID int64
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *workspaceBusyError) Error() string { return e.message }
|
||||
|
||||
// workspacesOverlap reports whether two resolved workspaces are the same
|
||||
// tree or nested in one another within the same repository. A folder that
|
||||
// merely holds separate repositories (a hub such as ~/project with clones
|
||||
// under repos/) does not overlap a run inside one of those repositories, and
|
||||
// neither do two different repositories nested in one another: each run
|
||||
// works in its own repository.
|
||||
// works in its own repository. Two folders outside any repository are not one
|
||||
// shared tree either: nested, they overlap only where the outer run declared
|
||||
// write paths reaching the inner folder (see workspaceScopesOverlap).
|
||||
func workspacesOverlap(a, b string) bool {
|
||||
within := func(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
|
||||
}
|
||||
return workspaceScopesOverlap(a, b, nil, nil)
|
||||
}
|
||||
|
||||
// workspaceScopesOverlap is workspacesOverlap with each workspace's declared
|
||||
// write paths (relative to it). They matter only for two nested folders
|
||||
// outside any repository; a nil lookup means "declared none".
|
||||
func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool {
|
||||
switch {
|
||||
case filepath.Clean(a) == filepath.Clean(b):
|
||||
return true
|
||||
case within(a, b):
|
||||
return repositoryRoot(b) == repositoryRoot(a)
|
||||
case within(b, a):
|
||||
return repositoryRoot(a) == repositoryRoot(b)
|
||||
case pathAtOrBelow(a, b):
|
||||
return nestedWorkspacesOverlap(a, b, aPaths)
|
||||
case pathAtOrBelow(b, a):
|
||||
return nestedWorkspacesOverlap(b, a, bPaths)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// nestedWorkspacesOverlap decides for an inner workspace below outer.
|
||||
func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool {
|
||||
root := repositoryRoot(outer)
|
||||
if repositoryRoot(inner) != root {
|
||||
return false // Different repositories: each run works in its own.
|
||||
}
|
||||
if root != "" {
|
||||
return true // The same repository is one shared tree.
|
||||
}
|
||||
if outerPaths == nil {
|
||||
return false
|
||||
}
|
||||
for _, path := range outerPaths() {
|
||||
target := filepath.Join(outer, path)
|
||||
if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pathAtOrBelow reports whether child is parent or below it.
|
||||
func pathAtOrBelow(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
// repositoryRoot is the nearest directory at or above dir holding a .git
|
||||
// entry (a repository or a linked worktree), or "" outside any repository.
|
||||
func repositoryRoot(dir string) string {
|
||||
@@ -1080,7 +1137,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID)
|
||||
}
|
||||
if detail.Status == protocol.RunStatusWaiting {
|
||||
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -2308,6 +2365,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()
|
||||
@@ -2324,7 +2383,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()
|
||||
@@ -2352,7 +2415,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
client.Transcript = piClient.Transcript
|
||||
} else if modelConfig.Harness == stage.ClaudeBackend {
|
||||
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills}
|
||||
if def.Configs["resume_session"] == "true" && adopted == nil && state.visits[key] > 1 {
|
||||
if adopted != nil {
|
||||
// Follow the CLI the previous process left (see run_reattach.go).
|
||||
claudeClient.Reference = adopted.owner.Reference
|
||||
} else if def.Configs["resume_session"] == "true" && state.visits[key] > 1 {
|
||||
// A loop visit continues the stage's previous session.
|
||||
claudeClient.ResumeSessionID = state.sessions[key]
|
||||
}
|
||||
@@ -2502,7 +2568,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
|
||||
@@ -2546,7 +2631,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)
|
||||
}
|
||||
parkExhausted := false
|
||||
if err == nil {
|
||||
parkExhausted = applyLimitOn(&step, selected, state.visits[key], maxVisits)
|
||||
@@ -2588,7 +2676,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}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"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 (r *runner) scheduleLoop() {
|
||||
@@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if claimed && status == "skipped_missed" {
|
||||
name := scheduleLabel(item)
|
||||
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
|
||||
}
|
||||
if !claimed || status != "claimed" {
|
||||
return nil
|
||||
}
|
||||
@@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
|
||||
return nil
|
||||
}
|
||||
|
||||
// admitScheduled starts one claimed schedule's run and records the outcome.
|
||||
// scheduleBusyRetry is how often, and for how long after its due time, a
|
||||
// scheduled admission whose workspace another run holds is tried again
|
||||
// (the limit counts from the first attempt).
|
||||
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
|
||||
// (Go durations; FOR=0 disables waiting) override the defaults.
|
||||
var scheduleBusyRetry = func() (every, limit time.Duration) {
|
||||
every, limit = 5*time.Minute, 2*time.Hour
|
||||
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
|
||||
every = value
|
||||
}
|
||||
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
|
||||
limit = value
|
||||
}
|
||||
return every, limit
|
||||
}
|
||||
|
||||
// scheduleNoticePriority is ntfy's "low" priority.
|
||||
const scheduleNoticePriority = 2
|
||||
|
||||
// admitScheduled starts one claimed schedule's run and records the outcome in
|
||||
// the schedule's history. A workspace another run holds delays the admission
|
||||
// instead of skipping it: it is tried again every few minutes for a bounded
|
||||
// time, recorded as "delayed" meanwhile. The operator is told, at low
|
||||
// priority, when a scheduled run is delayed and when one is skipped.
|
||||
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
|
||||
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
every, limit := scheduleBusyRetry()
|
||||
started := time.Now()
|
||||
deadline := started.Add(limit)
|
||||
name := scheduleLabel(item)
|
||||
diagnostic := ""
|
||||
status := "started"
|
||||
var runID int64
|
||||
if err != nil {
|
||||
status = "skipped"
|
||||
diagnostic = err.Error()
|
||||
} else if run != nil {
|
||||
runID = run.ID
|
||||
for attempt := 1; ; attempt++ {
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
if err == nil {
|
||||
status, diagnostic = "started", ""
|
||||
if run != nil {
|
||||
runID = run.ID
|
||||
}
|
||||
if attempt > 1 {
|
||||
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
|
||||
}
|
||||
break
|
||||
}
|
||||
status, diagnostic = "skipped", err.Error()
|
||||
var busy *workspaceBusyError
|
||||
if !errors.As(err, &busy) {
|
||||
break
|
||||
}
|
||||
if time.Now().Add(every).After(deadline) {
|
||||
if attempt > 1 {
|
||||
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
|
||||
}
|
||||
break
|
||||
}
|
||||
if attempt == 1 {
|
||||
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
|
||||
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
|
||||
}
|
||||
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
|
||||
log.Printf("schedule id=%d record delay: %v", item.ID, err)
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
|
||||
timer := time.NewTimer(every)
|
||||
select {
|
||||
case <-timer.C:
|
||||
continue
|
||||
case <-r.ctx.Done():
|
||||
timer.Stop()
|
||||
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
|
||||
}
|
||||
break
|
||||
}
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
|
||||
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
|
||||
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
|
||||
log.Printf("schedule id=%d record admission: %v", item.ID, err)
|
||||
}
|
||||
cancel()
|
||||
if status == "skipped" {
|
||||
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
|
||||
}
|
||||
|
||||
// scheduleLabel names a schedule in a notice.
|
||||
func scheduleLabel(item protocol.SavedSchedule) string {
|
||||
if name := singleLine(item.Name); name != "" {
|
||||
return truncateUTF8(name, 120)
|
||||
}
|
||||
return fmt.Sprintf("Schedule %d", item.ID)
|
||||
}
|
||||
|
||||
// scheduleNotice tells the operator, at low priority, through the app
|
||||
// notification stream and (when enabled) ntfy, that a scheduled run was
|
||||
// delayed or skipped.
|
||||
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
|
||||
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
|
||||
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
|
||||
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
|
||||
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
|
||||
return
|
||||
}
|
||||
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
|
||||
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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 scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification {
|
||||
t.Helper()
|
||||
active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var notices []protocol.AppNotification
|
||||
for _, n := range active {
|
||||
if n.Kind == protocol.NotificationSchedule {
|
||||
notices = append(notices, n)
|
||||
}
|
||||
}
|
||||
return notices
|
||||
}
|
||||
|
||||
func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due)
|
||||
if err == nil && status == want {
|
||||
return diagnostic, run
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A scheduled run whose workspace another run holds is delayed, not skipped:
|
||||
// it is recorded as delayed, the operator is told at low priority, and it
|
||||
// starts once the workspace is free.
|
||||
func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
r.notes = newAppNotifier(s)
|
||||
workspace := t.TempDir()
|
||||
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
|
||||
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
|
||||
release := make(chan struct{})
|
||||
entered := make(chan struct{}, 2)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
if prompt, _ := input["prompt"].(string); prompt == "busy" {
|
||||
<-release
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
due := dueOf(t, brief)
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed")
|
||||
if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") {
|
||||
t.Fatalf("delay diagnostic %q", diagnostic)
|
||||
}
|
||||
notices := scheduleNotices(t, s)
|
||||
if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") {
|
||||
t.Fatalf("delay notices %+v", notices)
|
||||
}
|
||||
close(release)
|
||||
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started")
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
if run == 0 || !strings.Contains(diagnostic, "started after waiting") {
|
||||
t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic)
|
||||
}
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 2 {
|
||||
t.Fatalf("runs %+v %v", runs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Waiting is bounded: past the limit the occurrence is skipped, saying why,
|
||||
// and the operator is told.
|
||||
func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
r.notes = newAppNotifier(s)
|
||||
workspace := t.TempDir()
|
||||
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
|
||||
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
entered := make(chan struct{}, 2)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
due := dueOf(t, brief)
|
||||
if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed {
|
||||
t.Fatal(claimed, err)
|
||||
}
|
||||
r.admitScheduled(*brief, due)
|
||||
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped")
|
||||
if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") {
|
||||
t.Fatalf("skip diagnostic %q run=%d", diagnostic, run)
|
||||
}
|
||||
notices := scheduleNotices(t, s)
|
||||
var titles []string
|
||||
for _, n := range notices {
|
||||
titles = append(titles, n.Title)
|
||||
if n.Priority != 2 {
|
||||
t.Fatalf("schedule notice is not low priority: %+v", n)
|
||||
}
|
||||
}
|
||||
if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") {
|
||||
t.Fatalf("notices %v", titles)
|
||||
}
|
||||
}
|
||||
@@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// seamScheduleBusyRetry sets how a scheduled admission waits for a busy
|
||||
// workspace (limit 0: it is skipped at once, as before delays existed).
|
||||
func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) {
|
||||
t.Helper()
|
||||
previous := scheduleBusyRetry
|
||||
scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit }
|
||||
t.Cleanup(func() { scheduleBusyRetry = previous })
|
||||
}
|
||||
|
||||
func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, time.Minute, 0)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now())
|
||||
due := dueOf(t, item)
|
||||
|
||||
@@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error {
|
||||
r.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil {
|
||||
if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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(©)
|
||||
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"])
|
||||
}
|
||||
}
|
||||
+446
-137
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -36,6 +37,9 @@ var (
|
||||
errClaudeMissing = errors.New("Claude Code is not installed on the execution server; run pipelines harness setup claude there")
|
||||
errClaudeSignedOut = errors.New("Claude Code is not signed in on the execution server; run pipelines harness setup claude there")
|
||||
errClaudeNoResult = errors.New("Claude Code ended without a final result")
|
||||
// errClaudeStoppedUnwatched: the CLI ended while no server was watching
|
||||
// it (the server was restarting) and left no final result.
|
||||
errClaudeStoppedUnwatched = errors.New("Claude Code stopped while the server was restarting, before it reported a final result")
|
||||
)
|
||||
|
||||
// ClaudeStageClient runs one stage visit with the Claude Code CLI in print
|
||||
@@ -134,7 +138,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 {
|
||||
@@ -142,6 +149,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)
|
||||
}
|
||||
@@ -163,7 +176,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",
|
||||
@@ -199,6 +212,10 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri
|
||||
}
|
||||
|
||||
func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, prompt string) (text string, err error) {
|
||||
// A re-adopted visit was admitted by a previous server process (see
|
||||
// WithResumeSession): follow its CLI or read what it left, never prompt
|
||||
// again.
|
||||
resume := TakeResumeSession(ctx)
|
||||
c.WorkStarted = false
|
||||
c.usd, c.input, c.output, c.reasoning, c.cacheRead, c.cacheW = 0, 0, 0, 0, 0, 0
|
||||
c.budget = config.Budget
|
||||
@@ -215,10 +232,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 {
|
||||
@@ -233,40 +251,60 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
|
||||
if _, statErr := os.Stat(c.Executable); statErr != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
}
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
root := filepath.Join(cache, "pipelines", claudeStageSessions)
|
||||
if err = os.MkdirAll(root, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.SessionID, err = newClaudeSessionID(); err != nil {
|
||||
return "", err
|
||||
var adopted *claudeStageOwner
|
||||
if resume != "" {
|
||||
owner, ownerErr := claudeStageOwnerAt(c.Reference)
|
||||
if ownerErr != nil || owner.SessionID != resume || owner.Output == "" {
|
||||
return "", fmt.Errorf("retained Claude Code stage session %.64s cannot be re-adopted: invalid retained evidence", RedactEvidence(resume))
|
||||
}
|
||||
adopted = &owner
|
||||
c.SessionID = resume
|
||||
} else {
|
||||
cache, cacheErr := os.UserCacheDir()
|
||||
if cacheErr != nil {
|
||||
return "", cacheErr
|
||||
}
|
||||
root := filepath.Join(cache, "pipelines", claudeStageSessions)
|
||||
if err = os.MkdirAll(root, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.Reference, err = os.MkdirTemp(root, "stage-*"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if c.SessionID, err = newClaudeSessionID(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
env := claudeStageEnvironment(c.environment(ctx), c.ArtifactsDir)
|
||||
// resume_session: continue the stage's previous session when Claude Code
|
||||
// still has it; otherwise this visit starts fresh.
|
||||
resumeFirst := false
|
||||
if c.ResumeSessionID != "" && claudeSessionExists(claudeConfigDir(env), c.ResumeSessionID) {
|
||||
if adopted == nil && c.ResumeSessionID != "" && claudeSessionExists(claudeConfigDir(env), c.ResumeSessionID) {
|
||||
c.SessionID, resumeFirst = c.ResumeSessionID, true
|
||||
}
|
||||
// User settings are not loaded, so the operator's skills are offered as
|
||||
// skills-only plugins generated for this visit, never their plugins.
|
||||
if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil {
|
||||
// skills-only plugins generated for this visit, never their plugins. A
|
||||
// re-adopted visit keeps the ones its first process generated.
|
||||
if adopted != nil {
|
||||
c.operatorPlugins = existingOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"))
|
||||
} else if c.operatorPlugins, err = writeOperatorSkillPlugins(filepath.Join(c.Reference, "operator-skills"), OperatorSkills(claudeConfigDir(env))); err != nil {
|
||||
return "", err
|
||||
}
|
||||
owned := false
|
||||
defer func() {
|
||||
// Quiescence is proven per invocation (see run); only then is the
|
||||
if errors.Is(err, ErrDetached) {
|
||||
// The server is stopping: the CLI keeps running and its
|
||||
// ownership stays recorded for the next process to re-adopt.
|
||||
text = ""
|
||||
return
|
||||
}
|
||||
// Quiescence is proven per invocation (see settle); only then is the
|
||||
// evidence marked settled and ownership released.
|
||||
if errors.Is(err, ErrStageCleanup) {
|
||||
text = ""
|
||||
return
|
||||
}
|
||||
c.removeRawOutput()
|
||||
_ = os.WriteFile(filepath.Join(c.Reference, "quiescent"), []byte("quiescent"), 0600)
|
||||
if owned {
|
||||
if saveErr := c.OnOwnership(c.SessionID, c.Reference, false); saveErr != nil {
|
||||
@@ -281,13 +319,26 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr
|
||||
}
|
||||
owned = true
|
||||
}
|
||||
if text, err = c.run(ctx, env, c.args(config, tools, effort, resumeFirst), config.Model, prompt); err != nil {
|
||||
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.
|
||||
c.WorkStarted = true
|
||||
if err = os.WriteFile(filepath.Join(c.Reference, "stream.jsonl"), nil, 0600); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if text, err = c.invoke(ctx, env, c.args(config, tools, effort, resumeFirst), 0, config.Model, prompt, adopted); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// One outcome repair follow-up in the same session.
|
||||
repair := outputRepairFrom(ctx)
|
||||
if message, ok := repair.followUp(text); ok {
|
||||
reply, err := c.run(ctx, env, c.args(config, tools, effort, true), config.Model, message)
|
||||
reply, err := c.invoke(ctx, env, c.args(config, tools, effort, true), 1, config.Model, message, adopted)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -336,6 +387,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-- {
|
||||
@@ -404,145 +466,330 @@ type claudeStreamRecord struct {
|
||||
} `json:"message"`
|
||||
}
|
||||
|
||||
func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model, prompt string) (text string, err error) {
|
||||
// claudeInvocation is what one CLI invocation's stream-json output reported.
|
||||
type claudeInvocation struct {
|
||||
final *claudeStreamRecord
|
||||
refusal, limited bool
|
||||
resetsAt int64
|
||||
authFailed, sessionMismatch, modelMismatch bool
|
||||
}
|
||||
|
||||
func (inv *claudeInvocation) observe(record claudeStreamRecord, session, model string) {
|
||||
switch record.Type {
|
||||
case "system":
|
||||
if record.Subtype == "init" {
|
||||
inv.sessionMismatch = record.SessionID != session
|
||||
inv.modelMismatch = record.Model != model
|
||||
}
|
||||
case "rate_limit_event":
|
||||
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
|
||||
inv.limited = true
|
||||
inv.resetsAt = record.RateLimit.ResetsAt
|
||||
}
|
||||
case "assistant":
|
||||
if record.Message != nil {
|
||||
switch record.Message.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
inv.refusal = true
|
||||
case "authentication_failed":
|
||||
inv.authFailed = true
|
||||
}
|
||||
}
|
||||
switch record.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
inv.refusal = true
|
||||
case "authentication_failed":
|
||||
inv.authFailed = true
|
||||
}
|
||||
case "result":
|
||||
copied := record
|
||||
inv.final = &copied
|
||||
}
|
||||
}
|
||||
|
||||
// claudeProcess is one invocation's CLI: a child this process started, or one
|
||||
// a previous server process left (adopted: it cannot be waited on and its exit
|
||||
// status is unknown).
|
||||
type claudeProcess struct {
|
||||
pid int
|
||||
adopted bool
|
||||
done chan struct{} // closed once the CLI has exited
|
||||
waitErr error // the child's exit error, read after done
|
||||
stop chan struct{} // ends an adopted process's liveness poll
|
||||
}
|
||||
|
||||
// exitedClaudeProcess is an invocation whose CLI already exited: its output
|
||||
// is read to the end, nothing is waited for.
|
||||
func exitedClaudeProcess(pid int) *claudeProcess {
|
||||
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
close(p.done)
|
||||
return p
|
||||
}
|
||||
|
||||
// adoptClaudeProcess follows a CLI left running by a previous server process.
|
||||
func adoptClaudeProcess(pid int, session string) *claudeProcess {
|
||||
p := &claudeProcess{pid: pid, adopted: true, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
go func() {
|
||||
ticker := time.NewTicker(claudeAdoptPoll)
|
||||
defer ticker.Stop()
|
||||
for claudeProcessAlive(pid, session) {
|
||||
select {
|
||||
case <-p.stop:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
close(p.done)
|
||||
}()
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *claudeProcess) release() {
|
||||
select {
|
||||
case <-p.stop:
|
||||
default:
|
||||
close(p.stop)
|
||||
}
|
||||
}
|
||||
|
||||
// claudeAdoptPoll is how often an adopted CLI's liveness is checked, and how
|
||||
// often its output file is read again when no new line has arrived.
|
||||
var claudeAdoptPoll = 100 * time.Millisecond
|
||||
|
||||
// claudeOutputName is the raw stdout file of invocation n in the evidence
|
||||
// directory. The CLI writes it directly, so it keeps writing whether or not a
|
||||
// server is reading; it is removed once the visit settles.
|
||||
func claudeOutputName(n int) string { return fmt.Sprintf("cli-%d.out", n) }
|
||||
|
||||
func claudePromptName(n int) string { return fmt.Sprintf("cli-%d.prompt", n) }
|
||||
|
||||
// removeRawOutput drops the unredacted CLI output and prompt files of a settled
|
||||
// visit; the redacted stream.jsonl stays as its evidence.
|
||||
func (c *ClaudeStageClient) removeRawOutput() {
|
||||
for n := 0; n < 2; n++ {
|
||||
_ = os.Remove(filepath.Join(c.Reference, claudeOutputName(n)))
|
||||
_ = os.Remove(filepath.Join(c.Reference, claudePromptName(n)))
|
||||
}
|
||||
}
|
||||
|
||||
// invoke runs invocation n (0 is the prompt, 1 the outcome repair follow-up).
|
||||
// For a re-adopted visit (adopted != nil), an invocation the previous process
|
||||
// already started is followed instead: its CLI if it still runs, else the
|
||||
// output it left. A prompt that ended without a result while no server was
|
||||
// watching is never sent again; a lost repair follow-up is.
|
||||
func (c *ClaudeStageClient) invoke(ctx context.Context, env, args []string, n int, model, prompt string, adopted *claudeStageOwner) (string, error) {
|
||||
if adopted != nil && n <= adopted.Invocation {
|
||||
var proc *claudeProcess
|
||||
switch {
|
||||
case n < adopted.Invocation:
|
||||
// An earlier invocation settled before the next one started;
|
||||
// the owner record names only the latest process.
|
||||
proc = exitedClaudeProcess(0)
|
||||
case claudeProcessAlive(adopted.PID, c.SessionID):
|
||||
proc = adoptClaudeProcess(adopted.PID, c.SessionID)
|
||||
default:
|
||||
proc = exitedClaudeProcess(adopted.PID)
|
||||
}
|
||||
inv, waitErr, err := c.follow(ctx, proc, n, model)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if inv.final != nil || n == 0 || n < adopted.Invocation {
|
||||
return c.settle(ctx, proc, inv, waitErr)
|
||||
}
|
||||
// The repair follow-up's CLI ended without a reply while the server
|
||||
// was down; the follow-up only asks for the outcome, so ask again.
|
||||
}
|
||||
proc, err := c.start(env, args, n, prompt)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
inv, waitErr, err := c.follow(ctx, proc, n, model)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.settle(ctx, proc, inv, waitErr)
|
||||
}
|
||||
|
||||
// start launches one CLI invocation detached from the server process: in its
|
||||
// own session, with the prompt read from a file and stdout written straight to
|
||||
// a file, so a server restart neither signals it nor cuts its output. The owner
|
||||
// record names the process and its output for a later server to re-adopt.
|
||||
func (c *ClaudeStageClient) start(env, args []string, n int, prompt string) (*claudeProcess, error) {
|
||||
promptPath := filepath.Join(c.Reference, claudePromptName(n))
|
||||
if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stdin, err := os.Open(promptPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stdin.Close()
|
||||
stdout, err := os.OpenFile(filepath.Join(c.Reference, claudeOutputName(n)), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stdout.Close()
|
||||
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer stderr.Close()
|
||||
cmd := exec.Command(c.Executable, args...)
|
||||
cmd.Dir = c.Directory
|
||||
cmd.Env = env
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Stdin = strings.NewReader(prompt)
|
||||
stderr, err := os.OpenFile(filepath.Join(c.Reference, "stderr.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer stderr.Close()
|
||||
cmd.Stderr = stderr
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer stream.Close()
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
|
||||
if err = cmd.Start(); err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
return nil, fmt.Errorf("%w: %w", ErrHarnessUnreachable, errClaudeMissing)
|
||||
}
|
||||
owner, _ := json.Marshal(map[string]any{"pid": cmd.Process.Pid, "session_id": c.SessionID})
|
||||
if err = os.WriteFile(filepath.Join(c.Reference, "owner.json"), owner, 0600); err != nil {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
_ = cmd.Wait()
|
||||
return "", err
|
||||
proc := &claudeProcess{pid: cmd.Process.Pid, done: make(chan struct{}), stop: make(chan struct{})}
|
||||
go func() {
|
||||
// Reaps the child, also after this server detached from it.
|
||||
proc.waitErr = cmd.Wait()
|
||||
close(proc.done)
|
||||
}()
|
||||
owner := claudeStageOwner{PID: proc.pid, PGID: proc.pid, SessionID: c.SessionID, Invocation: n, Output: claudeOutputName(n)}
|
||||
if err = writeClaudeStageOwner(c.Reference, owner); err != nil {
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGKILL)
|
||||
<-proc.done
|
||||
return nil, err
|
||||
}
|
||||
// The prompt is admitted once the process has it: tool work may follow.
|
||||
c.WorkStarted = true
|
||||
var final *claudeStreamRecord
|
||||
var refusal, limited bool
|
||||
var resetsAt int64
|
||||
var authFailed, sessionMismatch, modelMismatch bool
|
||||
scanned := make(chan error, 1)
|
||||
go func() {
|
||||
scanner := bufio.NewScanner(out)
|
||||
scanner.Buffer(make([]byte, 64<<10), 16<<20)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Bytes()
|
||||
var record claudeStreamRecord
|
||||
if json.Unmarshal(line, &record) != nil {
|
||||
continue
|
||||
}
|
||||
// One valid JSON record per line: the export parses this stream.
|
||||
redacted := RedactEvidenceJSON(line)
|
||||
_, _ = stream.WriteString(redacted + "\n")
|
||||
if len(c.Transcript) < 32<<10 {
|
||||
c.Transcript += redacted + "\n"
|
||||
}
|
||||
switch record.Type {
|
||||
case "system":
|
||||
if record.Subtype == "init" {
|
||||
sessionMismatch = record.SessionID != c.SessionID
|
||||
modelMismatch = record.Model != model
|
||||
}
|
||||
case "rate_limit_event":
|
||||
if record.RateLimit != nil && record.RateLimit.Status == "rejected" {
|
||||
limited = true
|
||||
resetsAt = record.RateLimit.ResetsAt
|
||||
}
|
||||
case "assistant":
|
||||
if record.Message != nil {
|
||||
switch record.Message.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
refusal = true
|
||||
case "authentication_failed":
|
||||
authFailed = true
|
||||
}
|
||||
}
|
||||
switch record.Error {
|
||||
case "billing_error", "rate_limit":
|
||||
refusal = true
|
||||
case "authentication_failed":
|
||||
authFailed = true
|
||||
}
|
||||
case "result":
|
||||
copied := record
|
||||
final = &copied
|
||||
}
|
||||
}
|
||||
scanned <- scanner.Err()
|
||||
}()
|
||||
waited := make(chan error, 1)
|
||||
go func() {
|
||||
scanErr := <-scanned
|
||||
waitErr := cmd.Wait()
|
||||
if scanErr != nil && waitErr == nil {
|
||||
waitErr = scanErr
|
||||
}
|
||||
waited <- waitErr
|
||||
}()
|
||||
var waitErr error
|
||||
select {
|
||||
case waitErr = <-waited:
|
||||
case <-ctx.Done():
|
||||
// Timeout or cancellation: stop the whole process group, then prove it.
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
|
||||
select {
|
||||
case <-waited:
|
||||
case <-time.After(5 * time.Second):
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
<-waited
|
||||
}
|
||||
waitErr = ctx.Err()
|
||||
return proc, nil
|
||||
}
|
||||
|
||||
// follow reads invocation n's output file from its start until the CLI has
|
||||
// exited and every line it wrote is read, keeping the redacted evidence
|
||||
// stream. A server shutdown leaves the CLI running (ErrDetached); any other
|
||||
// cancellation stops its process group first.
|
||||
func (c *ClaudeStageClient) follow(ctx context.Context, proc *claudeProcess, n int, model string) (inv claudeInvocation, waitErr error, err error) {
|
||||
defer proc.release()
|
||||
out, err := os.Open(filepath.Join(c.Reference, claudeOutputName(n)))
|
||||
if err != nil {
|
||||
return inv, nil, err
|
||||
}
|
||||
defer out.Close()
|
||||
stream, err := os.OpenFile(filepath.Join(c.Reference, "stream.jsonl"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
return inv, nil, err
|
||||
}
|
||||
defer stream.Close()
|
||||
consume := func(line []byte) {
|
||||
var record claudeStreamRecord
|
||||
if json.Unmarshal(line, &record) != nil {
|
||||
return
|
||||
}
|
||||
// One valid JSON record per line: the export parses this stream.
|
||||
redacted := RedactEvidenceJSON(line)
|
||||
_, _ = stream.WriteString(redacted + "\n")
|
||||
if len(c.Transcript) < 32<<10 {
|
||||
c.Transcript += redacted + "\n"
|
||||
}
|
||||
inv.observe(record, c.SessionID, model)
|
||||
}
|
||||
reader := bufio.NewReaderSize(out, 64<<10)
|
||||
var partial []byte
|
||||
exited := false
|
||||
ticker := time.NewTicker(claudeAdoptPoll)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
chunk, readErr := reader.ReadBytes('\n')
|
||||
partial = append(partial, chunk...)
|
||||
if readErr == nil {
|
||||
consume(partial)
|
||||
partial = partial[:0]
|
||||
continue
|
||||
}
|
||||
if readErr != io.EOF {
|
||||
return inv, nil, readErr
|
||||
}
|
||||
if exited {
|
||||
if len(bytes.TrimSpace(partial)) > 0 {
|
||||
consume(partial)
|
||||
}
|
||||
if !proc.adopted {
|
||||
waitErr = proc.waitErr
|
||||
}
|
||||
return inv, waitErr, nil
|
||||
}
|
||||
select {
|
||||
case <-proc.done:
|
||||
exited = true // Read what it wrote before exiting.
|
||||
case <-ticker.C:
|
||||
case <-ctx.Done():
|
||||
if Detached(ctx) {
|
||||
return inv, nil, fmt.Errorf("%w: Claude Code stage session %s left running", ErrDetached, c.SessionID)
|
||||
}
|
||||
// Timeout or cancellation: stop the whole process group, then prove it.
|
||||
if proc.pid > 1 {
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGTERM)
|
||||
}
|
||||
select {
|
||||
case <-proc.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
_ = syscall.Kill(-proc.pid, syscall.SIGKILL) // done never stays open for pid 0.
|
||||
select {
|
||||
case <-proc.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
}
|
||||
}
|
||||
if !claudeGroupStopped(proc.pid) {
|
||||
return inv, nil, errors.Join(ctx.Err(), ErrStageCleanup)
|
||||
}
|
||||
return inv, nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// claudeGroupStopped kills what is left of an exited CLI's process group and
|
||||
// reports whether the group is proven gone.
|
||||
func claudeGroupStopped(pid int) bool {
|
||||
if pid <= 1 {
|
||||
return true // No process of this server's to prove (see exitedClaudeProcess).
|
||||
}
|
||||
if claudeGroupGone(pid) {
|
||||
return true
|
||||
}
|
||||
_ = syscall.Kill(-pid, syscall.SIGKILL)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(pid) && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
return claudeGroupGone(pid)
|
||||
}
|
||||
|
||||
// settle proves the invocation's process group is gone and turns what its
|
||||
// output reported into the invocation's result.
|
||||
func (c *ClaudeStageClient) settle(ctx context.Context, proc *claudeProcess, inv claudeInvocation, waitErr error) (string, error) {
|
||||
// The CLI's exit alone does not prove its shell descendants exited.
|
||||
if !claudeGroupGone(cmd.Process.Pid) {
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(cmd.Process.Pid) && time.Now().Before(deadline) {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if !claudeGroupGone(cmd.Process.Pid) {
|
||||
return "", errors.Join(waitErr, ErrStageCleanup)
|
||||
}
|
||||
if !claudeGroupStopped(proc.pid) {
|
||||
return "", errors.Join(waitErr, ErrStageCleanup)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
final := inv.final
|
||||
if final != nil {
|
||||
if usageErr := c.observe(final); usageErr != nil {
|
||||
return "", usageErr
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case authFailed:
|
||||
case inv.authFailed:
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeSignedOut)
|
||||
case refusal || (limited && (final == nil || final.IsError)):
|
||||
if resetsAt > 0 {
|
||||
case inv.refusal || (inv.limited && (final == nil || final.IsError)):
|
||||
if inv.resetsAt > 0 {
|
||||
// A usage window, not an empty account: say when it reopens (a
|
||||
// time only; no provider text is copied).
|
||||
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(resetsAt, 0).Format("15:04 on 2 Jan"))
|
||||
return "", fmt.Errorf("%w: %w; the Claude usage limit resets at %s", ErrHarnessTransport, opencode.ErrProviderQuota, time.Unix(inv.resetsAt, 0).Format("15:04 on 2 Jan"))
|
||||
}
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, opencode.ErrProviderQuota)
|
||||
case sessionMismatch || modelMismatch:
|
||||
case inv.sessionMismatch || inv.modelMismatch:
|
||||
return "", fmt.Errorf("%w: Claude Code did not start the requested session and model", ErrHarnessTransport)
|
||||
case final == nil && proc.adopted:
|
||||
return "", fmt.Errorf("%w: %w", ErrHarnessTransport, errClaudeStoppedUnwatched)
|
||||
case final == nil:
|
||||
if waitErr != nil {
|
||||
return "", fmt.Errorf("%w: Claude Code exited with an error before a result (see the retained stderr log)", ErrHarnessTransport)
|
||||
@@ -556,6 +803,68 @@ func (c *ClaudeStageClient) run(ctx context.Context, env, args []string, model,
|
||||
return final.Result, nil
|
||||
}
|
||||
|
||||
// claudeProcessAlive reports whether pid is a live (not zombie) process whose
|
||||
// command line names the session, so a recorded pid the system reused is never
|
||||
// mistaken for the stage's CLI.
|
||||
func claudeProcessAlive(pid int, session string) bool {
|
||||
if pid <= 1 || session == "" {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat("/proc/self/stat"); err != nil {
|
||||
return syscall.Kill(pid, 0) == nil // No procfs: liveness only.
|
||||
}
|
||||
stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if i := bytes.LastIndexByte(stat, ')'); i < 0 || i+2 >= len(stat) || stat[i+2] == 'Z' || stat[i+2] == 'X' {
|
||||
return false
|
||||
}
|
||||
cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
|
||||
return err == nil && bytes.Contains(cmdline, []byte(session))
|
||||
}
|
||||
|
||||
// ClaudeStageReattachable reports whether a Claude Code stage session a
|
||||
// stopped server left owned can be re-adopted: its CLI still runs, or it ended
|
||||
// with a final result while no server was watching (or it was in the outcome
|
||||
// repair follow-up, which follows a complete result). Otherwise the error says
|
||||
// why.
|
||||
func ClaudeStageReattachable(reference, sessionID string) error {
|
||||
owner, err := claudeStageOwnerAt(reference)
|
||||
if err != nil || owner.SessionID != sessionID {
|
||||
return errors.New("its retained evidence is missing or invalid")
|
||||
}
|
||||
if owner.Output == "" {
|
||||
return errors.New("it was started by a server version that ran Claude Code as its own child")
|
||||
}
|
||||
if claudeProcessAlive(owner.PID, sessionID) || owner.Invocation > 0 {
|
||||
return nil
|
||||
}
|
||||
root, err := claudeStageRoot(reference)
|
||||
if err != nil {
|
||||
return errors.New("its retained evidence is missing or invalid")
|
||||
}
|
||||
defer root.Close()
|
||||
f, err := piOpenEvidence(root, owner.Output)
|
||||
if err != nil {
|
||||
return errors.New("its Claude Code output is missing")
|
||||
}
|
||||
defer f.Close()
|
||||
reader := bufio.NewReaderSize(f, 64<<10)
|
||||
for {
|
||||
line, readErr := reader.ReadBytes('\n')
|
||||
var record struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if json.Unmarshal(line, &record) == nil && record.Type == "result" {
|
||||
return nil
|
||||
}
|
||||
if readErr != nil {
|
||||
return errClaudeStoppedUnwatched
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func claudeGroupGone(pid int) bool {
|
||||
return errors.Is(syscall.Kill(-pid, 0), syscall.ESRCH)
|
||||
}
|
||||
|
||||
@@ -76,9 +76,47 @@ func claudeStageRead(root *os.Root, name string, limit int64) ([]byte, bool, err
|
||||
return data, false, err
|
||||
}
|
||||
|
||||
// claudeStageOwner is the retained owner record of a Claude stage visit's
|
||||
// current CLI invocation. Output names the file the detached CLI writes its
|
||||
// stream-json to; it is empty for a visit an older server ran as its own child
|
||||
// (with piped output), which a restart cannot re-adopt.
|
||||
type claudeStageOwner struct {
|
||||
PID int `json:"pid"`
|
||||
SessionID string `json:"session_id"`
|
||||
PID int `json:"pid"`
|
||||
PGID int `json:"pgid,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
Invocation int `json:"invocation,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
// writeClaudeStageOwner replaces the owner record atomically, so a server
|
||||
// stopped mid-write never leaves a torn record behind.
|
||||
func writeClaudeStageOwner(reference string, owner claudeStageOwner) error {
|
||||
data, err := json.Marshal(owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
temp := filepath.Join(reference, "owner.json.tmp")
|
||||
if err := os.WriteFile(temp, data, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temp, filepath.Join(reference, "owner.json"))
|
||||
}
|
||||
|
||||
// claudeStageOwnerAt reads the owner record of a validated evidence directory.
|
||||
func claudeStageOwnerAt(reference string) (claudeStageOwner, error) {
|
||||
root, err := claudeStageRoot(reference)
|
||||
if err != nil {
|
||||
return claudeStageOwner{}, err
|
||||
}
|
||||
defer root.Close()
|
||||
owner, err := claudeStageOwnerOf(root)
|
||||
if err != nil {
|
||||
return owner, err
|
||||
}
|
||||
if owner.Output != "" && owner.Output != claudeOutputName(owner.Invocation) {
|
||||
return owner, fmt.Errorf("invalid retained Claude stage owner")
|
||||
}
|
||||
return owner, nil
|
||||
}
|
||||
|
||||
func claudeStageOwnerOf(root *os.Root) (claudeStageOwner, error) {
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// detachClaudeMidInvocation runs Generate until invocation n's CLI has started
|
||||
// working, then stops the "server" (a shutdown-caused cancel). The CLI must be
|
||||
// left running and owned.
|
||||
func detachClaudeMidInvocation(t *testing.T, client *ClaudeStageClient, ctx context.Context, config ModelConfig, n int) claudeStageOwner {
|
||||
t.Helper()
|
||||
run, stop := context.WithCancelCause(ctx)
|
||||
defer stop(nil)
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Generate(run, config, "the task")
|
||||
done <- err
|
||||
}()
|
||||
waitForClaudeOutput(t, n, `"init"`)
|
||||
stop(ErrServerShutdown)
|
||||
if err := <-done; !errors.Is(err, ErrDetached) {
|
||||
t.Fatalf("a server shutdown did not detach the stage: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(client.Reference, "quiescent")); err == nil {
|
||||
t.Fatal("a detached stage was marked quiescent")
|
||||
}
|
||||
owner, err := claudeStageOwnerAt(client.Reference)
|
||||
if err != nil || owner.Invocation != n || owner.SessionID != client.SessionID {
|
||||
t.Fatalf("owner %+v %v", owner, err)
|
||||
}
|
||||
if !claudeProcessAlive(owner.PID, client.SessionID) {
|
||||
t.Fatal("the server shutdown stopped the Claude Code CLI")
|
||||
}
|
||||
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err != nil {
|
||||
t.Fatalf("a running stage is not reattachable: %v", err)
|
||||
}
|
||||
return owner
|
||||
}
|
||||
|
||||
// waitForClaudeOutput waits until the (only) stage evidence directory's
|
||||
// invocation n output contains needle and returns that directory. It reads the
|
||||
// file system, never the client a running Generate is writing.
|
||||
func waitForClaudeOutput(t *testing.T, n int, needle string) string {
|
||||
t.Helper()
|
||||
cache, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
dirs, _ := filepath.Glob(filepath.Join(cache, "pipelines", claudeStageSessions, "stage-*"))
|
||||
for _, dir := range dirs {
|
||||
if data, err := os.ReadFile(filepath.Join(dir, claudeOutputName(n))); err == nil && strings.Contains(string(data), needle) {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("invocation %d never started", n)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// restartedClaudeClient is the next server process's client for the same visit.
|
||||
func restartedClaudeClient(first *ClaudeStageClient) (*ClaudeStageClient, *[]bool) {
|
||||
active := &[]bool{}
|
||||
return &ClaudeStageClient{Executable: first.Executable, Directory: first.Directory, Tools: first.Tools, Reference: first.Reference, OnOwnership: func(_, _ string, value bool) error {
|
||||
*active = append(*active, value)
|
||||
return nil
|
||||
}}, active
|
||||
}
|
||||
|
||||
func release(t *testing.T, root string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(root, "release"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func waitGone(t *testing.T, pid int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for !claudeGroupGone(pid) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the CLI did not exit")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageSurvivesServerRestart: a server restart mid-stage leaves the
|
||||
// CLI running; the next process re-adopts it, keeps reading its output, waits
|
||||
// for its result and settles the visit, without prompting again.
|
||||
func TestClaudeStageSurvivesServerRestart(t *testing.T) {
|
||||
first, root, firstActive := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
if !slices.Equal(*firstActive, []bool{true}) {
|
||||
t.Fatal("the detaching process released ownership", *firstActive)
|
||||
}
|
||||
second, active := restartedClaudeClient(first)
|
||||
budget := NewBudget(10, 1000)
|
||||
ctx, cancel := context.WithTimeout(WithResumeSession(context.Background(), first.SessionID), 10*time.Second)
|
||||
defer cancel()
|
||||
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
|
||||
text, err := second.Generate(ctx, claudeConfig(budget), "never sent")
|
||||
if err != nil || text != "done" {
|
||||
t.Fatal(text, err)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("the restarted server prompted again: %v", calls)
|
||||
}
|
||||
if prompt, _ := os.ReadFile(filepath.Join(root, "prompt")); string(prompt) != "the task" {
|
||||
t.Fatalf("prompt %q", prompt)
|
||||
}
|
||||
if !slices.Equal(*active, []bool{true, false}) || !second.WorkStarted || second.SessionID != first.SessionID {
|
||||
t.Fatal("ownership", *active, second.WorkStarted)
|
||||
}
|
||||
if used := budget.Snapshot(); used.UsedUSD != 0.25 || used.UsedTokens != 17 {
|
||||
t.Fatalf("usage %+v", used)
|
||||
}
|
||||
if !claudeGroupGone(owner.PID) {
|
||||
t.Fatal("the adopted CLI's group is still running")
|
||||
}
|
||||
// The evidence lists each record once and the export reads it.
|
||||
data, err := ClaudeStageEvidence(first.Reference)
|
||||
if err != nil || strings.Count(data, `"working"`) != 1 || strings.Count(data, `"type":"result"`) != 1 {
|
||||
t.Fatalf("evidence %q %v", data, err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(first.Reference, claudeOutputName(0))); !os.IsNotExist(err) {
|
||||
t.Fatal("the raw CLI output outlived the settled visit")
|
||||
}
|
||||
session, err := exportClaudeStageSession(ctx, SessionExportRequest{Backend: ClaudeBackend, SessionID: first.SessionID, Reference: first.Reference})
|
||||
if err != nil || len(session.Messages) == 0 {
|
||||
t.Fatalf("export %+v %v", session, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageFinishedWhileServerWasDown: the CLI completed while no server
|
||||
// ran; the next process reads the result it left.
|
||||
func TestClaudeStageFinishedWhileServerWasDown(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
release(t, root)
|
||||
waitGone(t, owner.PID)
|
||||
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
|
||||
t.Fatalf("a completed stage is not reattachable: %v", err)
|
||||
}
|
||||
second, active := restartedClaudeClient(first)
|
||||
text, err := second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
|
||||
if err != nil || text != "done" || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal(text, err, *active)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("the restarted server prompted again: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageDiedWithoutResultWhileServerWasDown: a CLI that ended
|
||||
// without a result while no server watched is never prompted again; recovery
|
||||
// says why.
|
||||
func TestClaudeStageDiedWithoutResultWhileServerWasDown(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slow")
|
||||
owner := detachClaudeMidInvocation(t, first, context.Background(), claudeConfig(nil), 0)
|
||||
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
|
||||
waitGone(t, owner.PID)
|
||||
err := ClaudeStageReattachable(first.Reference, first.SessionID)
|
||||
if !errors.Is(err, errClaudeStoppedUnwatched) {
|
||||
t.Fatalf("a dead stage without a result was reattachable: %v", err)
|
||||
}
|
||||
// Adopting anyway (a death between the plan and the adoption) fails
|
||||
// closed with the same diagnostic and settles ownership.
|
||||
second, active := restartedClaudeClient(first)
|
||||
_, err = second.Generate(WithResumeSession(context.Background(), first.SessionID), claudeConfig(nil), "never sent")
|
||||
if !errors.Is(err, ErrHarnessTransport) || !errors.Is(err, errClaudeStoppedUnwatched) || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal(err, *active)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 1 {
|
||||
t.Fatalf("a lost prompt was sent again: %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageRestartDuringOutcomeRepair: a restart during the outcome
|
||||
// repair follow-up re-adopts that follow-up; the prompt's report is read back
|
||||
// from its retained output and merged with the reply, and both invocations'
|
||||
// usage counts.
|
||||
func TestClaudeStageRestartDuringOutcomeRepair(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slowrepair")
|
||||
repair := withOutputRepair(context.Background(), []string{"error", "success"})
|
||||
detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
|
||||
second, active := restartedClaudeClient(first)
|
||||
budget := NewBudget(0, 1000)
|
||||
go func() { time.Sleep(200 * time.Millisecond); release(t, root) }()
|
||||
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(budget), "never sent")
|
||||
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") {
|
||||
t.Fatalf("%q %v", text, err)
|
||||
}
|
||||
if calls := fakeClaudeArgs(t, root); len(calls) != 2 {
|
||||
t.Fatalf("invocations %v", calls)
|
||||
}
|
||||
if budget.Snapshot().UsedTokens != 34 || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatalf("usage %+v ownership %v", budget.Snapshot(), *active)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageLostRepairFollowUpIsSentAgain: the follow-up's CLI died
|
||||
// without a reply while the server was down; it only asks for the outcome,
|
||||
// so the next process asks again instead of failing the visit.
|
||||
func TestClaudeStageLostRepairFollowUpIsSentAgain(t *testing.T) {
|
||||
first, root, _ := fakeClaudeClient(t, "slowrepair")
|
||||
repair := withOutputRepair(context.Background(), []string{"error", "success"})
|
||||
owner := detachClaudeMidInvocation(t, first, repair, claudeConfig(nil), 1)
|
||||
_ = syscall.Kill(-owner.PID, syscall.SIGKILL)
|
||||
waitGone(t, owner.PID)
|
||||
if err := ClaudeStageReattachable(first.Reference, first.SessionID); err != nil {
|
||||
t.Fatalf("a visit with a complete prompt result is not reattachable: %v", err)
|
||||
}
|
||||
release(t, root)
|
||||
second, _ := restartedClaudeClient(first)
|
||||
text, err := second.Generate(WithResumeSession(repair, first.SessionID), claudeConfig(nil), "never sent")
|
||||
if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") {
|
||||
t.Fatalf("%q %v", text, err)
|
||||
}
|
||||
calls := fakeClaudeArgs(t, root)
|
||||
if len(calls) != 3 || !slices.Contains(calls[2], "--resume") {
|
||||
t.Fatalf("invocations %v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageOperatorCancelStillStopsTheCLI: only a server shutdown
|
||||
// detaches; an ordinary cancel stops the detached process group.
|
||||
func TestClaudeStageOperatorCancelStillStopsTheCLI(t *testing.T) {
|
||||
client, _, active := fakeClaudeClient(t, "slow")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := client.Generate(ctx, claudeConfig(nil), "task")
|
||||
done <- err
|
||||
}()
|
||||
owner, _ := claudeStageOwnerAt(waitForClaudeOutput(t, 0, "working"))
|
||||
cancel()
|
||||
if err := <-done; !errors.Is(err, context.Canceled) || errors.Is(err, ErrDetached) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !claudeGroupGone(owner.PID) || !slices.Equal(*active, []bool{true, false}) {
|
||||
t.Fatal("cancel left the CLI running", *active)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeStageLegacyOwnerIsNotReattachable(t *testing.T) {
|
||||
client, _, _ := fakeClaudeClient(t, "success")
|
||||
if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(client.Reference, "owner.json"), []byte(`{"pid":99999999,"session_id":"`+client.SessionID+`"}`), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ClaudeStageReattachable(client.Reference, client.SessionID); err == nil || !strings.Contains(err.Error(), "server version") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,24 @@ case "$FAKE_CLAUDE_CASE" in
|
||||
if [ "$resumed" = 1 ]; then text='# outcome\nsuccess\n'; else text='Report kept.'; fi
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
slow)
|
||||
# Works until the test releases it (a server restart happens meanwhile).
|
||||
init "$session" "$model"
|
||||
echo '{"type":"assistant","session_id":"'"$session"'","message":{"role":"assistant","content":[{"type":"text","text":"working"}]}}'
|
||||
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
slowrepair)
|
||||
# The prompt's report lacks an outcome; the follow-up waits for release.
|
||||
init "$session" "$model"
|
||||
if [ "$resumed" = 1 ]; then
|
||||
while [ ! -e "$FAKE_CLAUDE_OUT/release" ]; do sleep 0.02; done
|
||||
text='# outcome\nsuccess\n'
|
||||
else
|
||||
text='Report kept.'
|
||||
fi
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"result":"'"$text"'","session_id":"'"$session"'",'"$usage"'}'
|
||||
;;
|
||||
nousage)
|
||||
init "$session" "$model"
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"'"$session"'"}'
|
||||
@@ -228,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"}
|
||||
@@ -254,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")
|
||||
@@ -326,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)
|
||||
@@ -339,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) {
|
||||
@@ -395,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),
|
||||
} {
|
||||
|
||||
@@ -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", "resume_session":
|
||||
case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes", "resume_session":
|
||||
default:
|
||||
return ModelSpec{}, fmt.Errorf("unknown config %q", key)
|
||||
}
|
||||
@@ -116,8 +116,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) {
|
||||
if value := def.Configs["resume_session"]; value != "" && value != "true" && value != "false" {
|
||||
return ModelSpec{}, fmt.Errorf("resume_session 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
|
||||
@@ -148,8 +150,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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -249,3 +249,20 @@ func writeOperatorSkillPlugins(dir string, groups []OperatorSkillGroup) ([]strin
|
||||
}
|
||||
return roots, nil
|
||||
}
|
||||
|
||||
// existingOperatorSkillPlugins lists the skills-only plugin roots an earlier
|
||||
// process generated in dir (see writeOperatorSkillPlugins), for a re-adopted
|
||||
// visit whose follow-up must offer the same skills.
|
||||
func existingOperatorSkillPlugins(dir string) []string {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var roots []string
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
roots = append(roots, filepath.Join(dir, entry.Name()))
|
||||
}
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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{}, FindingsType: FindingsStage{}})
|
||||
return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}, FindingsType: FindingsStage{}})
|
||||
}
|
||||
|
||||
func EffectiveType(name string) string {
|
||||
|
||||
+10
-3
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user