stage turns: replace JSON results with file-based markdown turns
Each model visit now gets <run>/stages/<seq>-<stage>/ with input.md, memory.md, output.md, private/ and a shared run-level public/. The model reads the two input files, follows the stage's instructions verbatim and returns complete markdown; only the # outcome section is parsed. - add internal/turn layout, render and output parsing - write input.md/memory.md before a visit and output.md from the final message; inventory all turn files as stage artifacts - accumulate completed turns and system-written public file additions in memory, including across retries and resume - remove the JSON envelope, strict field validation, line format and the repair ladder for model stages - republish pipeline authoring prompts and docs in the new style Checks: go build ./..., go vet ./..., go test -count=1 ./..., gofmt -l .
This commit is contained in:
@@ -25,7 +25,8 @@ go test ./... # ~1 min for everything; `gofmt -l .` must print
|
||||
session registry.
|
||||
- `internal/stage/` — one client per harness and stage type: `opencode.go` (native sessions),
|
||||
`pi.go` (RPC), `model.go`, `agent.go`, `human.go` (decision stages), `ntfy.go` (notifications),
|
||||
`result_repair.go` (the strict-envelope repair ladder), `budget.go` (usage accounting).
|
||||
`model_prompt.go` (file-based turn prompt), `budget.go` (usage accounting). Model stages return
|
||||
markdown for `output.md`; only its `# outcome` section is parsed (`internal/turn`).
|
||||
- `internal/pipeline/` — the store: definitions and immutable versions, runs and steps, the
|
||||
operator-session registry, retention, search.
|
||||
- `internal/protocol/` — every wire shape. A new command means a message field here, documentation in
|
||||
|
||||
+103
-54
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
@@ -30,9 +31,12 @@ const (
|
||||
|
||||
// scanArtifacts returns a bounded inventory of one step's artifacts directory.
|
||||
// The directory path is supplied by the caller because it was created next to
|
||||
// the step; runID and sequence name the served URL. A missing, unreadable,
|
||||
// symlinked or oversized directory yields no entries and a zero count.
|
||||
func (r *runner) scanArtifacts(runID int64, sequence int, directory string) ([]protocol.StageArtifact, int, int) {
|
||||
// the step; runID and sequence name the served URL. Optional public
|
||||
// directories are inventoried with a "public/" name prefix so the shared
|
||||
// artifacts are visible from the visit that produced them. A missing,
|
||||
// unreadable, symlinked or oversized directory yields no entries and a zero
|
||||
// count.
|
||||
func (r *runner) scanArtifacts(runID int64, sequence int, directory string, publicDirs ...string) ([]protocol.StageArtifact, int, int) {
|
||||
if directory == "" || r.artifactsRoot == "" {
|
||||
return nil, 0, 0
|
||||
}
|
||||
@@ -42,64 +46,77 @@ func (r *runner) scanArtifacts(runID int64, sequence int, directory string) ([]p
|
||||
return nil, 0, 0
|
||||
}
|
||||
defer root.Close()
|
||||
rel := path.Join(strconv.FormatInt(runID, 10), strconv.Itoa(sequence))
|
||||
rel, err := artifactRel(root.Name(), directory)
|
||||
if err != nil {
|
||||
return nil, 0, 0
|
||||
}
|
||||
if !containedDirectory(root, rel) {
|
||||
return nil, 0, 0
|
||||
}
|
||||
files := []protocol.StageArtifact{}
|
||||
skipped, truncated := 0, 0
|
||||
used := int64(0)
|
||||
walkErr := fs.WalkDir(root.FS(), rel, func(name string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
// A single unreadable entry must not abort the whole inventory.
|
||||
return nil
|
||||
}
|
||||
if name == rel || entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if entry.Type()&fs.ModeSymlink != 0 || !entry.Type().IsRegular() {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
info, infoErr := entry.Info()
|
||||
if infoErr != nil || !info.Mode().IsRegular() {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
if len(files) >= maxArtifactFiles {
|
||||
skipped++
|
||||
return fs.SkipAll
|
||||
}
|
||||
if info.Size() > maxArtifactFileBytes {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
if used+info.Size() > maxArtifactTotalBytes {
|
||||
truncated++
|
||||
return fs.SkipAll
|
||||
}
|
||||
artifactName := strings.TrimPrefix(name, rel+"/")
|
||||
full := path.Join(rel, artifactName)
|
||||
contentType := mime.TypeByExtension(filepath.Ext(artifactName))
|
||||
if contentType == "" {
|
||||
contentType = sniffArtifact(root, full)
|
||||
if contentType == "" {
|
||||
scan := func(relative, prefix string) {
|
||||
_ = fs.WalkDir(root.FS(), relative, func(name string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
// A single unreadable entry must not abort the whole inventory.
|
||||
return nil
|
||||
}
|
||||
if name == relative || entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if entry.Type()&fs.ModeSymlink != 0 || !entry.Type().IsRegular() {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
}
|
||||
used += info.Size()
|
||||
files = append(files, protocol.StageArtifact{
|
||||
Name: artifactName,
|
||||
SizeBytes: info.Size(),
|
||||
ContentType: contentType,
|
||||
URL: artifactURL(runID, sequence, artifactName),
|
||||
info, infoErr := entry.Info()
|
||||
if infoErr != nil || !info.Mode().IsRegular() {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
if len(files) >= maxArtifactFiles {
|
||||
skipped++
|
||||
return fs.SkipAll
|
||||
}
|
||||
if info.Size() > maxArtifactFileBytes {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
if used+info.Size() > maxArtifactTotalBytes {
|
||||
truncated++
|
||||
return fs.SkipAll
|
||||
}
|
||||
artifactName := strings.TrimPrefix(name, relative+"/")
|
||||
artifactName = prefix + artifactName
|
||||
full := path.Join(relative, strings.TrimPrefix(artifactName, prefix))
|
||||
contentType := mime.TypeByExtension(filepath.Ext(artifactName))
|
||||
if contentType == "" {
|
||||
contentType = sniffArtifact(root, full)
|
||||
if contentType == "" {
|
||||
skipped++
|
||||
return nil
|
||||
}
|
||||
}
|
||||
used += info.Size()
|
||||
files = append(files, protocol.StageArtifact{
|
||||
Name: artifactName,
|
||||
SizeBytes: info.Size(),
|
||||
ContentType: contentType,
|
||||
URL: artifactURL(runID, sequence, artifactName),
|
||||
})
|
||||
return nil
|
||||
})
|
||||
return nil
|
||||
})
|
||||
if walkErr != nil {
|
||||
log.Printf("stage artifacts inventory run=%d step=%d: %v", runID, sequence, walkErr)
|
||||
return nil, 0, 0
|
||||
}
|
||||
scan(rel, "")
|
||||
for _, public := range publicDirs {
|
||||
if public == "" {
|
||||
continue
|
||||
}
|
||||
publicRel, relErr := artifactRel(root.Name(), public)
|
||||
if relErr != nil || !containedDirectory(root, publicRel) {
|
||||
continue
|
||||
}
|
||||
scan(publicRel, "public/")
|
||||
}
|
||||
if len(files) == 0 {
|
||||
files = nil
|
||||
@@ -107,6 +124,16 @@ func (r *runner) scanArtifacts(runID int64, sequence int, directory string) ([]p
|
||||
return files, skipped, truncated
|
||||
}
|
||||
|
||||
// artifactRel returns the slash path of directory below the artifacts root. A
|
||||
// directory outside the root is refused.
|
||||
func artifactRel(root, directory string) (string, error) {
|
||||
relative, err := filepath.Rel(root, directory)
|
||||
if err != nil || relative == "." || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) || relative == ".." || filepath.IsAbs(relative) {
|
||||
return "", fmt.Errorf("artifact directory is outside the artifacts root")
|
||||
}
|
||||
return filepath.ToSlash(relative), nil
|
||||
}
|
||||
|
||||
// containedDirectory reports whether rel names a real directory below root with
|
||||
// no symlink in any component.
|
||||
func containedDirectory(root *os.Root, rel string) bool {
|
||||
@@ -191,12 +218,34 @@ func (r *runner) serveArtifact(w http.ResponseWriter, req *http.Request) {
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
rel := path.Join(strconv.FormatInt(runID, 10), strconv.Itoa(sequence))
|
||||
if !containedDirectory(root, rel) {
|
||||
runRoot := strconv.FormatInt(runID, 10)
|
||||
// The public directory is shared by every stage; a name carrying the
|
||||
// "public/" prefix maps there. Everything else maps to the turn directory
|
||||
// for this visit, with the pre-turn <run>/<step> layout still readable for
|
||||
// runs recorded before the file-based protocol landed.
|
||||
var rel string
|
||||
if strings.HasPrefix(name, "public/") {
|
||||
rel = path.Join(runRoot, "public", strings.TrimPrefix(name, "public/"))
|
||||
} else {
|
||||
stageKey := ""
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence == sequence {
|
||||
stageKey = step.Stage
|
||||
break
|
||||
}
|
||||
}
|
||||
turnDir := path.Join(runRoot, "stages", fmt.Sprintf("%02d-%s", sequence, stageKey))
|
||||
if stageKey != "" && containedDirectory(root, turnDir) {
|
||||
rel = path.Join(turnDir, name)
|
||||
} else {
|
||||
rel = path.Join(runRoot, strconv.Itoa(sequence), name)
|
||||
}
|
||||
}
|
||||
if !containedDirectory(root, path.Dir(rel)) {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
full := path.Join(rel, name)
|
||||
full := rel
|
||||
parts := strings.Split(full, "/")
|
||||
for i := range parts {
|
||||
info, lerr := root.Lstat(strings.Join(parts[:i+1], "/"))
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -108,54 +109,59 @@ func TestArtifactsScanMissingDirectoryIsEmpty(t *testing.T) {
|
||||
func TestArtifactAccessUsesOnlyCurrentAndEarlierVisits(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
r := &runner{artifactsRoot: root}
|
||||
for _, directory := range []string{"7/1", "7/2", "7/3", "8/1"} {
|
||||
for _, directory := range []string{"7/stages/01-a", "7/stages/02-b/private", "7/stages/03-c", "7/public", "8/stages/01-a"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, directory), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
access := r.artifactAccess(7, 2, []string{"1", "3", "../8/1"}, filepath.Join(root, "7", "2"))
|
||||
current, _ := filepath.EvalSymlinks(filepath.Join(root, "7", "2"))
|
||||
prior, _ := filepath.EvalSymlinks(filepath.Join(root, "7", "1"))
|
||||
if access.Write != current || len(access.Read) != 2 || access.Read[0] != access.Write || access.Read[1] != prior {
|
||||
access := r.artifactAccess(7, 2, []string{"1", "3", "../8/1"}, filepath.Join(root, "7", "stages", "02-b"))
|
||||
current, _ := filepath.EvalSymlinks(filepath.Join(root, "7", "stages", "02-b"))
|
||||
private, _ := filepath.EvalSymlinks(filepath.Join(root, "7", "stages", "02-b", "private"))
|
||||
public, _ := filepath.EvalSymlinks(filepath.Join(root, "7", "public"))
|
||||
if access.Write != private || access.WriteShared != public || len(access.Read) != 2 || access.Read[0] != current || access.Read[1] != public {
|
||||
t.Fatalf("artifact scope = %#v", access)
|
||||
}
|
||||
if got := r.artifactAccess(7, 2, nil, filepath.Join(root, "8", "1")); got.Write != "" || len(got.Read) != 0 {
|
||||
if access.Read[1] == filepath.Join(root, "7", "stages", "01-a") {
|
||||
t.Fatal("a prior turn's private directory was opened to this visit")
|
||||
}
|
||||
if got := r.artifactAccess(7, 2, nil, filepath.Join(root, "8", "stages", "01-a")); got.Write != "" || len(got.Read) != 0 {
|
||||
t.Fatalf("other-run current scope accepted: %#v", got)
|
||||
}
|
||||
if got := r.artifactAccess(7, 2, nil, filepath.Join(root, "7", "3")); got.Write != "" || len(got.Read) != 0 {
|
||||
if got := r.artifactAccess(7, 2, nil, filepath.Join(root, "7", "stages", "03-c")); got.Write != "" || len(got.Read) != 0 {
|
||||
t.Fatalf("sibling current scope accepted: %#v", got)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "7", "4"), []byte("not a directory"), 0600); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(root, "7", "stages", "04-d"), []byte("not a directory"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := r.artifactAccess(7, 4, nil, filepath.Join(root, "7", "4")); got.Write != "" || len(got.Read) != 0 {
|
||||
if got := r.artifactAccess(7, 4, nil, filepath.Join(root, "7", "stages", "04-d")); got.Write != "" || len(got.Read) != 0 {
|
||||
t.Fatalf("file current scope accepted: %#v", got)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(root, "7", "2"), filepath.Join(root, "7", "5")); err != nil {
|
||||
if err := os.Symlink(filepath.Join(root, "7", "stages", "02-b"), filepath.Join(root, "7", "stages", "05-e")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := r.artifactAccess(7, 5, nil, filepath.Join(root, "7", "5")); got.Write != "" || len(got.Read) != 0 {
|
||||
if got := r.artifactAccess(7, 5, nil, filepath.Join(root, "7", "stages", "05-e")); got.Write != "" || len(got.Read) != 0 {
|
||||
t.Fatalf("symlinked current scope accepted: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerPassesDerivedArtifactAccessToAgentClient(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, directory := range []string{"7/1", "7/2"} {
|
||||
for _, directory := range []string{"7/stages/01-a/private", "7/stages/02-b/private", "7/public"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, directory), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r := &runner{artifactsRoot: root}
|
||||
client := r.agentClient(7, 2, []string{"1", "3"}, t.TempDir(), filepath.Join(root, "7", "2"), &stage.OperationLog{}, nil, []string{"read", "edit"})
|
||||
if client.ArtifactAccess.Write == "" || len(client.ArtifactAccess.Read) != 2 {
|
||||
current := filepath.Join(root, "7", "stages", "02-b")
|
||||
client := r.agentClient(7, 2, []string{"1", "3"}, t.TempDir(), current, &stage.OperationLog{}, nil, []string{"read", "edit"})
|
||||
if client.ArtifactAccess.Write == "" || client.ArtifactAccess.WriteShared == "" || len(client.ArtifactAccess.Read) != 2 {
|
||||
t.Fatalf("runner did not pass scoped artifact access: %#v", client.ArtifactAccess)
|
||||
}
|
||||
if client.ArtifactAccess.Read[1] == filepath.Join(root, "7", "3") {
|
||||
t.Fatal("runner passed a future visit to the client")
|
||||
if client.ArtifactAccess.Read[1] == filepath.Join(root, "7", "stages", "01-a") {
|
||||
t.Fatal("runner passed a prior turn's private directory to the client")
|
||||
}
|
||||
piClient := r.piClient(7, 2, []string{"1", "3"}, "pi", t.TempDir(), filepath.Join(root, "7", "2"), nil, []string{"read", "edit"})
|
||||
if piClient.ArtifactAccess.Write != client.ArtifactAccess.Write || len(piClient.ArtifactAccess.Read) != len(client.ArtifactAccess.Read) || piClient.ArtifactAccess.Read[1] != client.ArtifactAccess.Read[1] {
|
||||
piClient := r.piClient(7, 2, []string{"1", "3"}, "pi", t.TempDir(), current, nil, []string{"read", "edit"})
|
||||
if !reflect.DeepEqual(piClient.ArtifactAccess, client.ArtifactAccess) {
|
||||
t.Fatalf("runner passed different artifact scope to Pi client: %#v", piClient.ArtifactAccess)
|
||||
}
|
||||
}
|
||||
@@ -183,11 +189,14 @@ func runWithArtifact(t *testing.T) (*runHandler, protocol.RunStep) {
|
||||
t.Cleanup(func() { cancel(); WaitRuns(handler) })
|
||||
handler.runner.artifactsRoot = t.TempDir()
|
||||
handler.runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
if def.ArtifactsDir == "" {
|
||||
t.Error("runner did not provide an artifacts directory")
|
||||
if def.Turn.Private == "" || def.Turn.Public == "" {
|
||||
t.Error("runner did not provide the turn artifact scopes")
|
||||
return stage.Result{Outcome: "success"}, nil
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(def.ArtifactsDir, "report.txt"), []byte("artifact bytes"), 0600); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Private, "report.txt"), []byte("artifact bytes"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Public, "shared.txt"), []byte("shared bytes"), 0600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
|
||||
@@ -206,14 +215,27 @@ func runWithArtifact(t *testing.T) (*runHandler, protocol.RunStep) {
|
||||
t.Fatalf("unexpected run: %+v", detail)
|
||||
}
|
||||
step := detail.Steps[0]
|
||||
if len(step.Artifacts) != 1 {
|
||||
for _, name := range []string{"input.md", "memory.md", "output.md"} {
|
||||
if _, ok := artifactNamed(step.Artifacts, name); !ok {
|
||||
t.Fatalf("turn file %s not listed as an artifact: %+v", name, step.Artifacts)
|
||||
}
|
||||
}
|
||||
artifact, ok := artifactNamed(step.Artifacts, "private/report.txt")
|
||||
if !ok {
|
||||
t.Fatalf("artifact not retained: %+v", step.Artifacts)
|
||||
}
|
||||
artifact := step.Artifacts[0]
|
||||
if artifact.Name != "report.txt" || artifact.SizeBytes != int64(len("artifact bytes")) ||
|
||||
shared, ok := artifactNamed(step.Artifacts, "public/shared.txt")
|
||||
if !ok {
|
||||
t.Fatalf("shared artifact not retained: %+v", step.Artifacts)
|
||||
}
|
||||
step.Artifacts = []protocol.StageArtifact{artifact, shared}
|
||||
if artifact.SizeBytes != int64(len("artifact bytes")) ||
|
||||
!strings.HasPrefix(artifact.ContentType, "text/plain") || artifact.URL == "" {
|
||||
t.Fatalf("recorded artifact wrong: %+v", artifact)
|
||||
}
|
||||
if shared.SizeBytes != int64(len("shared bytes")) || shared.URL == "" {
|
||||
t.Fatalf("recorded shared artifact wrong: %+v", shared)
|
||||
}
|
||||
return handler, step
|
||||
}
|
||||
|
||||
@@ -292,6 +314,30 @@ func TestArtifactHTTPGetHeadRangeAndRefusals(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactHTTPGetPublicSharedFile(t *testing.T) {
|
||||
handler, step := runWithArtifact(t)
|
||||
var shared protocol.StageArtifact
|
||||
for _, artifact := range step.Artifacts {
|
||||
if artifact.Name == "public/shared.txt" {
|
||||
shared = artifact
|
||||
}
|
||||
}
|
||||
if shared.URL == "" {
|
||||
t.Fatalf("public artifact missing: %+v", step.Artifacts)
|
||||
}
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
resp, err := http.Get(srv.URL + shared.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || string(body) != "shared bytes" {
|
||||
t.Fatalf("public artifact GET = %d %q", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
func runIDFromURL(url string) int64 {
|
||||
var id int64
|
||||
fmt.Sscanf(url, "/artifacts/%d/", &id)
|
||||
@@ -304,7 +350,7 @@ func TestArtifactHTTPRefusesEscapes(t *testing.T) {
|
||||
root := handler.runner.artifactsRoot
|
||||
|
||||
// A symlink inside the step directory must never be followed.
|
||||
stepDir := filepath.Join(root, fmt.Sprint(runID), "1")
|
||||
stepDir := filepath.Join(root, fmt.Sprint(runID), "stages", "01-one")
|
||||
secret := filepath.Join(t.TempDir(), "secret.txt")
|
||||
if err := os.WriteFile(secret, []byte("secret"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -1,112 +1,16 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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"
|
||||
)
|
||||
|
||||
// committerCaptureSource builds an implementer -> committer pipeline whose
|
||||
// committer selects both the implementer's declared changed_files and the
|
||||
// runner-published input.server_changed_files.
|
||||
func committerCaptureSource() string {
|
||||
source := pipeline.Template([]string{"implementer", "committer"}, true)
|
||||
return strings.Replace(source, "# stage committer", "# stage committer\n\n```memory\n{\"changed_files\":\"implementer.changed_files\",\"server_changed_files\":\"input.server_changed_files\"}\n```", 1)
|
||||
}
|
||||
|
||||
// runCommitterCapture runs committerCaptureSource once. seed writes the workspace
|
||||
// and returns the implementer's declared output; the returned map is exactly the
|
||||
// input the committer stage received.
|
||||
func runCommitterCapture(t *testing.T, key string, seed func(dir string) stage.Values) stage.Values {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "changed-paths.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "commit", committerCaptureSource()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("submit/list: %+v %v", items, err)
|
||||
}
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
var committerInput stage.Values
|
||||
r.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
if def.Key == "implementer" {
|
||||
return stage.Result{Outcome: "success", Output: seed(dir)}, nil
|
||||
}
|
||||
committerInput = input
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "committed"}}, nil
|
||||
}
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: key, Workspace: dir, 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)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 2 {
|
||||
t.Fatalf("run = %q steps=%d, want succeeded/2: %+v", detail.Status, len(detail.Steps), detail.RunSummary)
|
||||
}
|
||||
if committerInput == nil {
|
||||
t.Fatal("committer stage did not run")
|
||||
}
|
||||
return committerInput
|
||||
}
|
||||
|
||||
// TestCommitterReceivesServerCapturedChangedPaths proves the runner publishes the
|
||||
// server-captured changed-path set as input.server_changed_files, distinct from
|
||||
// and additive to the implementer's self-declared changed_files: a file the
|
||||
// implementer changed but did not declare is still handed to the committer.
|
||||
func TestCommitterReceivesServerCapturedChangedPaths(t *testing.T) {
|
||||
committerInput := runCommitterCapture(t, "captured", func(dir string) stage.Values {
|
||||
for name := range map[string]bool{"declared.txt": true, "undeclared.txt": true} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(name+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return stage.Values{"changed_files": []any{"declared.txt"}}
|
||||
})
|
||||
|
||||
declared, ok := committerInput["changed_files"].([]any)
|
||||
if !ok || len(declared) != 1 || declared[0] != "declared.txt" {
|
||||
t.Fatalf("committer changed_files = %v, want the declared list", committerInput["changed_files"])
|
||||
}
|
||||
captured, ok := committerInput["server_changed_files"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("committer did not receive server_changed_files: %v", committerInput)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, path := range captured {
|
||||
seen[path.(string)] = true
|
||||
}
|
||||
// Additivity/distinctness: the captured set carries the path the declared
|
||||
// list omitted, plus the declared one, and nothing else.
|
||||
if !seen["undeclared.txt"] || !seen["declared.txt"] || len(seen) != 2 {
|
||||
t.Fatalf("server_changed_files = %v, want the two captured paths", captured)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResumedRunStatePublishesPersistedCapturedPaths proves the field is rebuilt
|
||||
// from every persisted completed step's captured paths (rebuildRunState →
|
||||
// recordChanges), deduplicated and first-seen-ordered, so a resumed run hands the
|
||||
// committer the same evidence as a live one.
|
||||
// recordChanges), deduplicated and first-seen-ordered, so a resumed run keeps the
|
||||
// same server evidence available to any stage that still asks for it.
|
||||
func TestResumedRunStatePublishesPersistedCapturedPaths(t *testing.T) {
|
||||
detail := &protocol.RunDetail{Input: map[string]any{"prompt": "task"}}
|
||||
detail.Steps = []protocol.RunStep{
|
||||
@@ -129,19 +33,3 @@ func TestResumedRunStatePublishesPersistedCapturedPaths(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommitterServerChangedFilesEmptyWhenNothingCaptured proves the field is
|
||||
// present as an empty list when no changes were captured, so an unconditional
|
||||
// input.server_changed_files binding still resolves.
|
||||
func TestCommitterServerChangedFilesEmptyWhenNothingCaptured(t *testing.T) {
|
||||
committerInput := runCommitterCapture(t, "empty", func(string) stage.Values {
|
||||
return stage.Values{"changed_files": []any{}}
|
||||
})
|
||||
captured, ok := committerInput["server_changed_files"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("server_changed_files not present: %v", committerInput)
|
||||
}
|
||||
if len(captured) != 0 {
|
||||
t.Fatalf("server_changed_files = %v, want an empty list", captured)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,11 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func TestRuntimeLimitAndSelectedMemory(t *testing.T) {
|
||||
// TestRuntimeLimitAndReviewLoop exercises the runner-owned visit limit on a
|
||||
// worker -> review loop. Model stages now read turn files rather than selected
|
||||
// memory fields, so the fake stage hands its result forward through the previous
|
||||
// output map and the loop is bounded by limits alone.
|
||||
func TestRuntimeLimitAndReviewLoop(t *testing.T) {
|
||||
for _, approveLast := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "exhaustion", true: "last review approves"}[approveLast], func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
@@ -21,8 +25,7 @@ func TestRuntimeLimitAndSelectedMemory(t *testing.T) {
|
||||
}
|
||||
defer store.Close()
|
||||
source := pipeline.Template([]string{"planner", "worker", "review"}, true)
|
||||
source = strings.Replace(source, "# stage worker", "# stage worker\n\n```memory\n{\"task\":\"input.prompt\",\"plan\":\"planner.plan\",\"findings\":\"review.findings?\"}\n```", 1)
|
||||
source = strings.Replace(source, "# stage review", "# stage review\n\n```limits\n{\"max_visits\":3,\"on\":[\"rejected\"]}\n```\n\n```memory\n{\"task\":\"input.prompt\",\"checks\":\"planner.checks\"}\n```", 1)
|
||||
source = strings.Replace(source, "# stage review", "# stage review\n\n```limits\n{\"max_visits\":3,\"on\":[\"rejected\"]}\n```", 1)
|
||||
source = strings.Replace(source, "success -> #success", "success -> #success\nrejected -> worker", 1)
|
||||
if _, err := store.Submit(ctx, "bounded", source); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -33,7 +36,7 @@ func TestRuntimeLimitAndSelectedMemory(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := map[string]int{}
|
||||
runner.execute = func(_ context.Context, def stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
calls[def.Key]++
|
||||
if _, ok := def.Blocks["limits"]; ok {
|
||||
t.Fatal("policy exposed to model")
|
||||
@@ -42,17 +45,8 @@ func TestRuntimeLimitAndSelectedMemory(t *testing.T) {
|
||||
case "planner":
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"plan": "do task", "checks": "inspect actual files"}}, nil
|
||||
case "worker":
|
||||
if input["task"] != "task" || input["plan"] != "do task" {
|
||||
t.Error("lost shared task context", input)
|
||||
}
|
||||
if calls["worker"] > 1 && input["findings"] != "fix layout" {
|
||||
t.Error("missing revision feedback", input)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"ui_revision": 0, "previous_verdict": "rejected"}}, nil
|
||||
default:
|
||||
if len(input) != 2 || input["checks"] != "inspect actual files" {
|
||||
t.Error("review context contaminated", input)
|
||||
}
|
||||
if approveLast && calls["review"] == 3 {
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "approved"}}, nil
|
||||
}
|
||||
@@ -68,8 +62,8 @@ func TestRuntimeLimitAndSelectedMemory(t *testing.T) {
|
||||
t.Fatal("model evaded runtime limit", calls, len(retained.Steps))
|
||||
}
|
||||
last := retained.Steps[6]
|
||||
if last.Control == nil || last.Control.Visit != 3 || last.Control.Memory["checks"].Sequence != 1 {
|
||||
t.Fatal("missing retained control evidence", last)
|
||||
if last.Control == nil || last.Control.Visit != 3 {
|
||||
t.Fatalf("missing retained control evidence: %+v", last)
|
||||
}
|
||||
if approveLast {
|
||||
if retained.Status != "succeeded" || last.Control.LimitReached {
|
||||
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
|
||||
func TestRetryInputOverrideRejectsReservedAndOversizedValues(t *testing.T) {
|
||||
base := map[string]any{"handoff": "retained"}
|
||||
if _, err := retryInputOverride(base, map[string]any{"workspace": "/escape"}); err == nil {
|
||||
t.Fatal("reserved retry input was accepted")
|
||||
for _, reserved := range []string{"workspace", "server_changed_files"} {
|
||||
if _, err := retryInputOverride(base, map[string]any{reserved: "/escape"}); err == nil {
|
||||
t.Fatalf("reserved retry input %s was accepted", reserved)
|
||||
}
|
||||
}
|
||||
if _, err := retryInputOverride(base, map[string]any{"large": strings.Repeat("x", maxRetryInputBytes)}); err == nil {
|
||||
t.Fatal("oversized retry input was accepted")
|
||||
@@ -69,7 +71,7 @@ case "$3" in
|
||||
/api/session/ses_fresh_1/interrupt) echo '{}' ;;
|
||||
/api/session/ses_fresh_1) echo '{"data":{"id":"ses_fresh_1"}}' ;;
|
||||
/api/session/ses_fresh_1/message*) echo '{"data":[{"error":{"message":"provider rejected generation","token":"private-token"}}]}' ;;
|
||||
/api/session/ses_fresh_2/generate) echo '{"data":{"text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}}' ;;
|
||||
/api/session/ses_fresh_2/generate) printf '%%s\n' '{"data":{"text":"# outcome\nsuccess\n"}}' ;;
|
||||
*) exit 99 ;;
|
||||
esac
|
||||
`, log, count, count, count)
|
||||
@@ -288,8 +290,7 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := "# stage a\n\n```output\nA\n```\n\n```prompt\nA\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n\n# stage b\n\n```output\nB\n```\n\n```prompt\nB\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n\n# stage c\n\n```output\nC\n```\n\n```prompt\nC\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=test\nmodel=test\n```\n"
|
||||
source = strings.Replace(source, "# stage b\n\n```output", "# stage b\n\n```memory\n{\"task\":\"input.prompt\",\"handoff\":\"a.handoff\"}\n```\n\n```output", 1)
|
||||
source := "# stage a\n\n```prompt\nDo A.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```prompt\nDo B.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```prompt\nDo C.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
|
||||
if _, err := store.Submit(ctx, "resume", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -307,7 +308,7 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if input["prompt"] != "task" {
|
||||
t.Errorf("entry received altered input: %#v", input)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"handoff": "from-a"}}, nil
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"task": "task", "handoff": "from-a"}}, nil
|
||||
case "b":
|
||||
bCalls++
|
||||
if input["handoff"] != "from-a" {
|
||||
@@ -329,6 +330,21 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if bCalls == 3 && input["correction"] != "use-new-plan-again" {
|
||||
t.Errorf("transitive selected retry lost input override: %#v", input)
|
||||
}
|
||||
if bCalls >= 2 {
|
||||
// The model reads input.md, not the persisted step input. A retry
|
||||
// correction that lives only in the step row is invisible.
|
||||
data, err := os.ReadFile(def.Turn.Input)
|
||||
if err != nil {
|
||||
t.Fatalf("read retry input.md: %v", err)
|
||||
}
|
||||
want := "use-new-plan"
|
||||
if bCalls == 3 {
|
||||
want = "use-new-plan-again"
|
||||
}
|
||||
if !strings.Contains(string(data), want) {
|
||||
t.Errorf("retry input.md missing override %q:\n%s", want, data)
|
||||
}
|
||||
}
|
||||
if bCalls <= 2 {
|
||||
return stage.Result{}, fmt.Errorf("deliberate failure")
|
||||
}
|
||||
@@ -380,9 +396,6 @@ func TestRetryResumeReusesPrefixHandoffAndReplaysRequestAfterReopen(t *testing.T
|
||||
if transitive.Steps[0].Input["task"] != "corrected-again" || transitive.Steps[0].Input["correction"] != "use-new-plan-again" {
|
||||
t.Fatalf("retry persisted the wrong selected input: %#v", transitive.Steps[0].Input)
|
||||
}
|
||||
if transitive.Steps[0].Control == nil || transitive.Steps[0].Control.Memory["handoff"].Sequence != 1 {
|
||||
t.Fatalf("transitive retry lost prefix memory provenance: %#v", transitive.Steps[0].Control)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -418,10 +431,10 @@ case "$3" in
|
||||
*/wait) echo '{}' ;;
|
||||
*/message*)
|
||||
case "$3" in
|
||||
*/ses_native_2/*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"invalid\\",\\"output\\":{\\"wrong\\":\\"format\\"}}"}]}]}' ;;
|
||||
*/ses_native_2/*) printf '%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\ninvalid\n"}]}]}' ;;
|
||||
*/ses_native_3/*) echo '{}' ;;
|
||||
*/ses_native_3/*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"success\\",\\"output\\":{\\"handoff\\":\\"from-b\\"}}"}]}]}' ;;
|
||||
*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\\"outcome\\":\\"success\\",\\"output\\":{\\"handoff\\":\\"from-a\\",\\"summary\\":\\"done\\"}}"}]}]}' ;;
|
||||
*/ses_native_3/*) printf '%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n\n# Handoff\n\nfrom-b\n"}]}]}' ;;
|
||||
*) printf '%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n\n# Handoff\n\nfrom-a\n"}]}]}' ;;
|
||||
esac ;;
|
||||
*) echo '{}' ;;
|
||||
esac
|
||||
@@ -436,7 +449,6 @@ esac
|
||||
}
|
||||
defer store.Close()
|
||||
source := "# stage a\n\n```output\n{ handoff, summary }\n```\n\n```prompt\nDo A.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> b\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage b\n\n```output\n{ handoff }\n```\n\n```prompt\nDo B.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> c\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n\n# stage c\n\n```output\n{ handoff, summary }\n```\n\n```prompt\nDo C.\n```\n\n```tools\nread\nglob\ngrep\nshell\n```\n\n```edges\nsuccess -> #success\nerror -> #failure\n```\n\n```configs\ntype=model\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n```\n"
|
||||
source = strings.Replace(source, "# stage b\n\n```output", "# stage b\n\n```memory\n{\"task\":\"input.prompt\",\"handoff\":\"a.handoff\"}\n```\n\n```output", 1)
|
||||
if _, err := store.Submit(ctx, "native-resume", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -489,9 +501,6 @@ esac
|
||||
if transitive.RunDetail.Steps[0].Input["task"] != "corrected-second" || transitive.RunDetail.Steps[0].Input["correction"] != "second" {
|
||||
t.Fatalf("transitive native resume persisted wrong selected input: %#v", transitive.RunDetail.Steps[0].Input)
|
||||
}
|
||||
if transitive.RunDetail.Steps[0].Control == nil || transitive.RunDetail.Steps[0].Control.Memory["handoff"].Sequence != 1 {
|
||||
t.Fatalf("transitive native resume lost prefix provenance: %#v", transitive.RunDetail.Steps[0].Control)
|
||||
}
|
||||
sessions, err := os.ReadFile(filepath.Join(dir, "sessions"))
|
||||
if err != nil || strings.TrimSpace(string(sessions)) != "5" {
|
||||
t.Fatalf("native stage execution count = %q, want 5 (A once, B three times, C once): %v", sessions, err)
|
||||
@@ -536,7 +545,7 @@ case "$3" in
|
||||
if [ "$r" = "1" ]; then
|
||||
echo '{"data":[{"finish":"stop","content":'
|
||||
else
|
||||
echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}]}]}'
|
||||
printf '%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n"}]}]}'
|
||||
fi ;;
|
||||
*/interrupt) echo '{}' ;;
|
||||
*) exit 99 ;;
|
||||
|
||||
+159
-42
@@ -20,6 +20,7 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||||
)
|
||||
|
||||
// activeRun records one in-flight run's cancellation seam and the resolved
|
||||
@@ -421,8 +422,10 @@ type retryCheckpoint struct {
|
||||
}
|
||||
|
||||
type retryPrefixRecord struct {
|
||||
stage string
|
||||
sequence int
|
||||
stage string
|
||||
sequence int
|
||||
public []string
|
||||
publicKnown bool
|
||||
}
|
||||
|
||||
const maxRetryInputBytes = 64 * 1024
|
||||
@@ -435,7 +438,7 @@ func retryInputOverride(base map[string]any, override map[string]any) (map[strin
|
||||
if err != nil || len(encoded) > maxRetryInputBytes {
|
||||
return nil, fmt.Errorf("retry input must be a JSON object no larger than %d bytes", maxRetryInputBytes)
|
||||
}
|
||||
reserved := map[string]bool{"pwd": true, "workspace": true, "write_paths": true, "allow_tools": true, "pipeline_id": true, "pipeline_version": true, "request_key": true, "retry_mode": true, "retry_source": true, "retry_stage": true, "retry_visit": true}
|
||||
reserved := map[string]bool{"pwd": true, "workspace": true, "write_paths": true, "allow_tools": true, "pipeline_id": true, "pipeline_version": true, "request_key": true, "retry_mode": true, "retry_source": true, "retry_stage": true, "retry_visit": true, serverChangedFilesField: true}
|
||||
merged := map[string]any{}
|
||||
for key, value := range base {
|
||||
merged[key] = value
|
||||
@@ -538,7 +541,13 @@ func (r *runner) retrySourceCheckpointSelected(sourceID int64, pinned *protocol.
|
||||
handoff["prefix"] = prefix
|
||||
serializedPrefix := make([]map[string]any, 0, len(prefixRecords))
|
||||
for _, record := range prefixRecords {
|
||||
serializedPrefix = append(serializedPrefix, map[string]any{"stage": record.stage, "sequence": record.sequence})
|
||||
entry := map[string]any{"stage": record.stage, "sequence": record.sequence}
|
||||
if record.publicKnown {
|
||||
// Persist the exact additions so a later retry can rebuild memory
|
||||
// and carry public/ without reading this attempt's rows.
|
||||
entry["public"] = record.public
|
||||
}
|
||||
serializedPrefix = append(serializedPrefix, entry)
|
||||
}
|
||||
handoff["prefix_provenance"] = serializedPrefix
|
||||
// A newer explicitly selected version may continue only when every recorded
|
||||
@@ -787,6 +796,13 @@ func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail,
|
||||
if override, ok := storedHandoff["override"].(map[string]any); ok {
|
||||
state.retryOverride = stage.Values(override)
|
||||
}
|
||||
// The retry is a new run with a new artifact root. Carry the completed
|
||||
// prefix's recorded public files before the first visit, so memory does
|
||||
// not name files this attempt cannot read.
|
||||
if err := r.carryRetryPublic(id, request.RetrySource, checkpoint.failed.Sequence, storedHandoff, source); err != nil {
|
||||
r.finishRunState(id, d.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil)
|
||||
return
|
||||
}
|
||||
r.runLoop(ctx, id, d.Graph, d.Name, workspace, request, state)
|
||||
return
|
||||
}
|
||||
@@ -865,30 +881,44 @@ type runState struct {
|
||||
// running total without re-reading the store.
|
||||
completed int
|
||||
artifactDirs []string
|
||||
// prompt is the original run prompt; lastOutput is the previous visit's
|
||||
// markdown and turns is every completed turn in order. Together they render
|
||||
// the next model visit's input.md and memory.md.
|
||||
prompt string
|
||||
lastOutput string
|
||||
turns []turn.MemoryEntry
|
||||
// retryOverride is applied once, after the selected stage's memory bindings
|
||||
// have been resolved. It is intentionally not part of run input or memory.
|
||||
retryOverride stage.Values
|
||||
}
|
||||
|
||||
func newRunState(key string, input stage.Values) *runState {
|
||||
return &runState{key: key, nextSequence: 1, visits: map[string]int{}, memory: map[string]memoryValue{}, input: input}
|
||||
prompt, _ := input["prompt"].(string)
|
||||
return &runState{key: key, nextSequence: 1, visits: map[string]int{}, memory: map[string]memoryValue{}, input: input, prompt: prompt}
|
||||
}
|
||||
|
||||
func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runState {
|
||||
state := newRunState(decided.Target, stage.Values(decided.Output))
|
||||
if prompt, ok := detail.Input["prompt"].(string); ok {
|
||||
state.prompt = prompt
|
||||
}
|
||||
if original, err := copyValues(stage.Values(detail.Input)); err == nil {
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
}
|
||||
publicSeen := map[string]bool{}
|
||||
for _, step := range detail.Steps {
|
||||
state.visits[step.Stage]++
|
||||
if step.Sequence >= state.nextSequence {
|
||||
state.nextSequence = step.Sequence + 1
|
||||
}
|
||||
added := publicArtifacts(step.Artifacts, publicSeen)
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
state.completed++
|
||||
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Output: turnOutput(step.Output), PublicFiles: added})
|
||||
state.lastOutput = turnOutput(step.Output)
|
||||
}
|
||||
// Seed the UI-surface accumulator from the persisted evidence so a
|
||||
// resumed run reaches the same skip decision with no extra query.
|
||||
@@ -907,10 +937,17 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
|
||||
// attempt, so retries cannot duplicate execution or usage aggregates.
|
||||
func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, handoff map[string]any) *runState {
|
||||
state := newRunState(failed.Stage, stage.Values(failed.Input))
|
||||
// Resume at the failed sequence. The retry is a new run with a new run ID
|
||||
// and artifact root, so this sequence's turn directory does not overlap the
|
||||
// source attempt's files.
|
||||
state.nextSequence = failed.Sequence
|
||||
if prompt, ok := detail.Input["prompt"].(string); ok {
|
||||
state.prompt = prompt
|
||||
}
|
||||
if original, err := copyValues(stage.Values(detail.Input)); err == nil {
|
||||
state.memory["input"] = memoryValue{output: original}
|
||||
}
|
||||
publicSeen := map[string]bool{}
|
||||
_, hasCheckpointPrefix := handoff["prefix"]
|
||||
if !hasCheckpointPrefix {
|
||||
for _, step := range detail.Steps {
|
||||
@@ -918,11 +955,14 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
|
||||
break
|
||||
}
|
||||
state.visits[step.Stage]++
|
||||
added := publicArtifacts(step.Artifacts, publicSeen)
|
||||
if step.Status == "completed" {
|
||||
if values, err := copyValues(stage.Values(step.Output)); err == nil {
|
||||
state.memory[step.Stage] = memoryValue{output: values, sequence: step.Sequence}
|
||||
}
|
||||
state.completed++
|
||||
state.turns = append(state.turns, turn.MemoryEntry{Stage: step.Stage, Visit: state.visits[step.Stage], Output: turnOutput(step.Output), PublicFiles: added})
|
||||
state.lastOutput = turnOutput(step.Output)
|
||||
}
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
if step.Status == "completed" {
|
||||
@@ -947,6 +987,8 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
|
||||
state.memory[record.stage] = memoryValue{output: values, sequence: record.sequence}
|
||||
state.visits[record.stage]++
|
||||
state.completed++
|
||||
state.turns = append(state.turns, turn.MemoryEntry{Stage: record.stage, Visit: state.visits[record.stage], Output: turnOutput(values), PublicFiles: recordPublicFiles(record, detail, publicSeen)})
|
||||
state.lastOutput = turnOutput(values)
|
||||
state.artifactDirs = append(state.artifactDirs, filepath.Join("", strconv.Itoa(record.sequence)))
|
||||
}
|
||||
}
|
||||
@@ -960,6 +1002,7 @@ func rebuildRetryState(detail *protocol.RunDetail, failed protocol.RunStep, hand
|
||||
func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedSequence int) (map[string]any, []retryPrefixRecord, error) {
|
||||
prefix := map[string]any{}
|
||||
records := []retryPrefixRecord{}
|
||||
inheritedPublic := map[string]bool{}
|
||||
if source.RetryMode == "resume" && source.RetrySource > 0 {
|
||||
checkpointSource, mode, _, inherited, err := r.store.RetryCheckpoint(r.ctx, sourceID)
|
||||
if err != nil {
|
||||
@@ -975,14 +1018,26 @@ func (r *runner) retryPrefix(sourceID int64, source *protocol.RunDetail, failedS
|
||||
}
|
||||
for _, record := range retryPrefixRecords(inherited["prefix_provenance"]) {
|
||||
records = append(records, record)
|
||||
for _, name := range record.public {
|
||||
inheritedPublic[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
publicBySequence := retryPublicBySequence(source, failedSequence)
|
||||
for _, step := range source.Steps {
|
||||
if step.Sequence >= failedSequence || step.Status != "completed" {
|
||||
continue
|
||||
}
|
||||
prefix[step.Stage] = step.Output
|
||||
records = append(records, retryPrefixRecord{stage: step.Stage, sequence: step.Sequence})
|
||||
added := make([]string, 0, len(publicBySequence[step.Sequence]))
|
||||
for _, name := range publicBySequence[step.Sequence] {
|
||||
// Carried prefix files reappear in this attempt's inventory but were
|
||||
// added by an earlier turn, not this one.
|
||||
if !inheritedPublic[name] {
|
||||
added = append(added, name)
|
||||
}
|
||||
}
|
||||
records = append(records, retryPrefixRecord{stage: step.Stage, sequence: step.Sequence, public: added, publicKnown: true})
|
||||
}
|
||||
return prefix, records, nil
|
||||
}
|
||||
@@ -1006,11 +1061,35 @@ func retryPrefixRecords(raw any) []retryPrefixRecord {
|
||||
if !ok || sequence < 1 {
|
||||
continue
|
||||
}
|
||||
result = append(result, retryPrefixRecord{stage: stageName, sequence: int(sequence)})
|
||||
record := retryPrefixRecord{stage: stageName, sequence: int(sequence)}
|
||||
if raw, ok := entry["public"]; ok {
|
||||
record.public = stringValues(raw)
|
||||
record.publicKnown = true
|
||||
}
|
||||
result = append(result, record)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// stringValues accepts the JSON-decoded forms of a string list in a retry
|
||||
// checkpoint and returns a copy; unknown element types are ignored.
|
||||
func stringValues(raw any) []string {
|
||||
switch values := raw.(type) {
|
||||
case []string:
|
||||
return append([]string(nil), values...)
|
||||
case []any:
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if text, ok := value.(string); ok {
|
||||
result = append(result, text)
|
||||
}
|
||||
}
|
||||
return result
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func retryPrefixStep(detail *protocol.RunDetail, record retryPrefixRecord) (protocol.RunStep, bool) {
|
||||
for _, step := range detail.Steps {
|
||||
if step.Stage == record.stage && step.Sequence == record.sequence {
|
||||
@@ -1023,21 +1102,24 @@ func retryPrefixStep(detail *protocol.RunDetail, record retryPrefixRecord) (prot
|
||||
return protocol.RunStep{Stage: record.stage, Sequence: record.sequence}, true
|
||||
}
|
||||
|
||||
// artifactAccess derives exact visit directories; it never consumes a path from
|
||||
// a definition or model result. An unreadable or symlinked root fails closed.
|
||||
// artifactAccess derives exact turn directories; it never consumes a path from
|
||||
// a definition or model result. The current visit may read and write its own
|
||||
// turn and the shared public directory. Earlier visits are not readable: their
|
||||
// public files are already shared and their private/ files are never handed to
|
||||
// a later stage. An unreadable or symlinked root fails closed.
|
||||
func (r *runner) artifactAccess(runID int64, sequence int, prior []string, current string) stage.ArtifactAccess {
|
||||
_ = prior // prior private directories remain deliberately inaccessible
|
||||
root, err := filepath.EvalSymlinks(r.artifactsRoot)
|
||||
if err != nil {
|
||||
return stage.ArtifactAccess{}
|
||||
}
|
||||
runRoot := filepath.Join(root, strconv.FormatInt(runID, 10))
|
||||
visitDirectory := func(visit int) (string, bool) {
|
||||
if visit <= 0 {
|
||||
directory := func(path string) (string, bool) {
|
||||
if path == "" {
|
||||
return "", false
|
||||
}
|
||||
directory := filepath.Join(runRoot, strconv.Itoa(visit))
|
||||
resolved, err := filepath.EvalSymlinks(directory)
|
||||
if err != nil || resolved != directory {
|
||||
resolved, err := filepath.EvalSymlinks(path)
|
||||
if err != nil || !strings.HasPrefix(resolved, runRoot+string(os.PathSeparator)) {
|
||||
return "", false
|
||||
}
|
||||
info, err := os.Stat(resolved)
|
||||
@@ -1047,22 +1129,26 @@ func (r *runner) artifactAccess(runID int64, sequence int, prior []string, curre
|
||||
return resolved, true
|
||||
}
|
||||
access := stage.ArtifactAccess{}
|
||||
if directory, ok := visitDirectory(sequence); ok {
|
||||
resolved, err := filepath.EvalSymlinks(current)
|
||||
if err != nil || resolved != directory {
|
||||
return access
|
||||
}
|
||||
access.Write = directory
|
||||
access.Read = append(access.Read, directory)
|
||||
currentDir, ok := directory(current)
|
||||
if !ok {
|
||||
return access
|
||||
}
|
||||
for _, priorSequence := range prior {
|
||||
visit, err := strconv.Atoi(priorSequence)
|
||||
if err != nil || visit <= 0 || visit >= sequence {
|
||||
continue
|
||||
}
|
||||
if directory, ok := visitDirectory(visit); ok {
|
||||
access.Read = append(access.Read, directory)
|
||||
}
|
||||
// The current directory must be this visit's turn, not another stage's turn
|
||||
// in the same run.
|
||||
expectedPrefix := fmt.Sprintf("%02d-", sequence)
|
||||
if filepath.Dir(currentDir) != filepath.Join(runRoot, "stages") || !strings.HasPrefix(filepath.Base(currentDir), expectedPrefix) {
|
||||
return access
|
||||
}
|
||||
if private, ok := directory(filepath.Join(currentDir, "private")); ok {
|
||||
// The model may write its own private/ files, never the server-owned
|
||||
// input.md, memory.md or output.md. A missing private/ grants no write
|
||||
// scope; falling back to the turn directory would widen the permission.
|
||||
access.Write = private
|
||||
}
|
||||
access.Read = append(access.Read, currentDir)
|
||||
if public, ok := directory(filepath.Join(runRoot, "public")); ok {
|
||||
access.WriteShared = public
|
||||
access.Read = append(access.Read, public)
|
||||
}
|
||||
return access
|
||||
}
|
||||
@@ -1378,19 +1464,37 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// was captured). Only a selecting stage copies it into its input.
|
||||
state.publishServerChangedFiles()
|
||||
var reads map[string]protocol.MemoryRead
|
||||
input, reads, copyErr := memoryInput(state.input, selected.Memory, state.memory)
|
||||
bindings := selected.Memory
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
// A model stage reads the turn's memory.md and input.md files; the
|
||||
// retired per-field memory block no longer selects its input.
|
||||
bindings = nil
|
||||
}
|
||||
input, reads, copyErr := memoryInput(state.input, bindings, state.memory)
|
||||
if copyErr != nil {
|
||||
finish("failed", "error", copyErr.Error())
|
||||
return
|
||||
}
|
||||
if changed := state.capturedList(); stage.EffectiveType(def.Type) == stage.ModelType && len(changed) > 0 {
|
||||
// The turn files, not a memory binding, carry the stage context. The
|
||||
// prompt reads this reserved value so a committer still sees the
|
||||
// server-captured paths that distinguish this run from pre-existing
|
||||
// dirty work. An empty list adds nothing and leaves the entry input
|
||||
// unchanged.
|
||||
input[serverChangedFilesField] = changed
|
||||
}
|
||||
var retryInput stage.Values
|
||||
if state.retryOverride != nil {
|
||||
input, copyErr = retryInputOverride(input, state.retryOverride)
|
||||
if copyErr != nil {
|
||||
finish("failed", "error", copyErr.Error())
|
||||
return
|
||||
}
|
||||
// A selected-stage override belongs only to this invocation, not to
|
||||
// a later visit reached through the stage graph.
|
||||
// Keep the merged values for this visit's input.md: the model reads
|
||||
// files, not the persisted step row, so the override must be visible
|
||||
// there. A selected-stage override belongs only to this invocation,
|
||||
// not to a later visit reached through the stage graph.
|
||||
retryInput = input
|
||||
state.retryOverride = nil
|
||||
}
|
||||
if err := r.store.BeginStep(ctx, id, sequence, key, input); err != nil {
|
||||
@@ -1477,18 +1581,23 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
return
|
||||
}
|
||||
useAgent := stage.EffectiveType(def.Type) == stage.ModelType && (len(tools) > 0 || !explicitTools)
|
||||
// Every agent visit gets a per-run/step directory for the files it
|
||||
// produces. Creation is best-effort: an unusable directory must never
|
||||
// fail the run, and it is only attempted for model stages.
|
||||
// Every model visit gets a file-based turn: input.md and memory.md are
|
||||
// written before execution, output.md after it. Creation is part of the
|
||||
// protocol, so an unusable turn directory fails the run instead of
|
||||
// silently degrading to the retired JSON envelope.
|
||||
artifactsDir := ""
|
||||
var visitTurn turn.Paths
|
||||
var publicBefore map[string]bool
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
candidate := filepath.Join(r.artifactsRoot, strconv.FormatInt(id, 10), strconv.Itoa(sequence))
|
||||
if mkErr := os.MkdirAll(candidate, 0700); mkErr != nil {
|
||||
log.Printf("stage artifacts directory run=%d step=%d: %v", id, sequence, mkErr)
|
||||
} else {
|
||||
artifactsDir = candidate
|
||||
def.ArtifactsDir = candidate
|
||||
visitTurn = r.turnPaths(id, sequence, key)
|
||||
if turnErr := r.prepareTurn(visitTurn, state, retryInput); turnErr != nil {
|
||||
finish("failed", "error", turnErr.Error())
|
||||
return
|
||||
}
|
||||
artifactsDir = visitTurn.TurnDir
|
||||
def.ArtifactsDir = artifactsDir
|
||||
def.Turn = stageTurnPaths(visitTurn)
|
||||
publicBefore = publicFileSet(visitTurn.RunDir)
|
||||
}
|
||||
operations := &stage.OperationLog{}
|
||||
var landing stage.LandingAccess
|
||||
@@ -1600,6 +1709,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
result, err = stage.DefaultRegistry().Run(stageCtx, def, input)
|
||||
}
|
||||
}()
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType && err == nil {
|
||||
ensureTurnOutput(visitTurn, result)
|
||||
}
|
||||
if held != nil {
|
||||
resourceQuiet = r.resourceQuiescent(id, err, panicked)
|
||||
if confirmed, reported := result.Output[protocol.ResourceCleanupConfirmedKey]; reported && confirmed != true {
|
||||
@@ -1626,7 +1738,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
sessionExport = r.exportStageSession(ctx, owner, artifactsDir, id, sequence, key, modelConfig)
|
||||
}
|
||||
}
|
||||
artifacts, artifactsSkipped, artifactsTruncated := r.scanArtifacts(id, sequence, artifactsDir)
|
||||
artifacts, artifactsSkipped, artifactsTruncated := r.scanArtifacts(id, sequence, artifactsDir, visitTurn.PublicDir)
|
||||
step := protocol.RunStep{Sequence: sequence, Stage: key, Status: "completed", Outcome: result.Outcome, Output: result.Output, Transcript: operations.Transcript(client.Transcript), SessionID: stageSession, FileChanges: changes, SessionExport: sessionExport, Artifacts: artifacts, ArtifactsSkipped: artifactsSkipped, ArtifactsTruncated: artifactsTruncated}
|
||||
// Stamp the effective provider/model this visit actually ran with for every
|
||||
// model stage, including failures, so the app/TUI evidence reflects any
|
||||
@@ -1734,6 +1846,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// persisted, so the skip guard agrees with what the store holds.
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
if step.Status == "completed" {
|
||||
added := []string(nil)
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
added = addedPublicFiles(publicBefore, publicFileSet(visitTurn.RunDir))
|
||||
}
|
||||
state.recordTurn(step, added)
|
||||
state.completed++
|
||||
if artifactsDir != "" {
|
||||
state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence))
|
||||
|
||||
@@ -36,7 +36,7 @@ case "$3" in
|
||||
touch %q/"$id"
|
||||
echo '{}' ;;
|
||||
/api/session/active) echo '{"data":{}}' ;;
|
||||
*/message*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}]}]}' ;;
|
||||
*/message*) printf '%%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n\n# Summary\n\ndone\n"}]}]}' ;;
|
||||
*/interrupt) echo '{}' ;;
|
||||
/api/session/ses_budget_*)
|
||||
id=${3#/api/session/}; cost=0; tokens=0
|
||||
@@ -75,7 +75,7 @@ esac
|
||||
t.Fatal(err, out.String())
|
||||
}
|
||||
detail := response.RunDetail
|
||||
if detail == nil || detail.ResultPreview != "done" || detail.CompletedSteps != 1 {
|
||||
if detail == nil || !strings.Contains(detail.ResultPreview, "done") || detail.CompletedSteps != 1 {
|
||||
t.Fatal("partial results missing from run summary", out.String())
|
||||
}
|
||||
if detail == nil || detail.Status != "failed" || len(detail.Steps) != 2 || detail.Steps[0].SessionID == detail.Steps[1].SessionID || detail.Steps[1].AgentActive || !strings.Contains(detail.Steps[1].Diagnostic, "stage budget exceeded") {
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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"
|
||||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||||
)
|
||||
|
||||
// TestTurnsAccumulateMemoryAndListFilesAsArtifacts runs two real visits and
|
||||
// proves the file contract end to end: input.md carries the run prompt and then
|
||||
// the previous turn's output, memory.md accumulates completed turns plus the
|
||||
// system-written public file list, and all three turn files are inventoried.
|
||||
func TestTurnsAccumulateMemoryAndListFilesAsArtifacts(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "turns.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "turns", pipeline.Template([]string{"first", "second"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("submit/list: %+v %v", items, err)
|
||||
}
|
||||
runner, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var secondInput, secondMemory string
|
||||
runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
if def.Turn.Input == "" || def.Turn.Memory == "" || def.Turn.Output == "" || def.Turn.Private == "" || def.Turn.Public == "" {
|
||||
t.Fatalf("runner did not provide the turn paths: %+v", def.Turn)
|
||||
}
|
||||
switch def.Key {
|
||||
case "first":
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Public, "shared.txt"), []byte("shared"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Private, "secret.txt"), []byte("turn one only"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "first body\n"}}, nil
|
||||
case "second":
|
||||
data, err := os.ReadFile(def.Turn.Input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondInput = string(data)
|
||||
data, err = os.ReadFile(def.Turn.Memory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondMemory = string(data)
|
||||
if _, err := os.Stat(filepath.Join(def.Turn.Private, "secret.txt")); !os.IsNotExist(err) {
|
||||
t.Fatalf("a later turn received an earlier private file: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(def.Turn.Public, "shared.txt")); err != nil {
|
||||
t.Fatalf("shared public artifact was not visible to the later turn: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Public, "second.txt"), []byte("second"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "second body\n"}}, nil
|
||||
}
|
||||
t.Fatalf("unexpected stage %q", def.Key)
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
run, err := runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "turns", Workspace: t.TempDir(), Input: map[string]any{"prompt": "original task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner.wg.Wait()
|
||||
detail, err := store.GetRun(ctx, run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detail.Status != "succeeded" || len(detail.Steps) != 2 {
|
||||
t.Fatalf("run = %q steps=%d: %+v", detail.Status, len(detail.Steps), detail.RunSummary)
|
||||
}
|
||||
if secondInput != "# Previous turn output\n\nfirst body\n" {
|
||||
t.Fatalf("second input.md = %q, want the previous turn's output", secondInput)
|
||||
}
|
||||
for _, want := range []string{"## first · visit 1", "first body", "Files added to public/:\n- public/shared.txt"} {
|
||||
if !strings.Contains(secondMemory, want) {
|
||||
t.Fatalf("second memory.md missing %q:\n%s", want, secondMemory)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"input.md", "memory.md", "output.md"} {
|
||||
if _, ok := artifactNamed(detail.Steps[1].Artifacts, name); !ok {
|
||||
t.Fatalf("second visit did not list %s: %+v", name, detail.Steps[1].Artifacts)
|
||||
}
|
||||
}
|
||||
if _, ok := artifactNamed(detail.Steps[0].Artifacts, "private/secret.txt"); !ok {
|
||||
t.Fatalf("first visit did not list its private artifact: %+v", detail.Steps[0].Artifacts)
|
||||
}
|
||||
if _, ok := artifactNamed(detail.Steps[0].Artifacts, "public/shared.txt"); !ok {
|
||||
t.Fatalf("first visit did not list the shared public artifact: %+v", detail.Steps[0].Artifacts)
|
||||
}
|
||||
if _, ok := artifactNamed(detail.Steps[1].Artifacts, "private/secret.txt"); ok {
|
||||
t.Fatalf("second visit inherited the first turn's private artifact: %+v", detail.Steps[1].Artifacts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildRunStateRestoresPublicFileLists proves a durable resume rebuilds
|
||||
// each turn's system-written public list from persisted step artifacts instead
|
||||
// of rendering the "none" placeholder for every prior turn.
|
||||
func TestRebuildRunStateRestoresPublicFileLists(t *testing.T) {
|
||||
detail := &protocol.RunDetail{
|
||||
Input: map[string]any{"prompt": "task"},
|
||||
Steps: []protocol.RunStep{
|
||||
{Sequence: 1, Stage: "first", Status: "completed", Outcome: "success", Output: map[string]any{"markdown": "first body\n"}, Artifacts: []protocol.StageArtifact{{Name: "input.md"}, {Name: "public/a.png"}}},
|
||||
{Sequence: 2, Stage: "second", Status: "completed", Outcome: "success", Output: map[string]any{"markdown": "second body\n"}, Artifacts: []protocol.StageArtifact{{Name: "public/a.png"}, {Name: "public/b.txt"}}},
|
||||
},
|
||||
}
|
||||
state := rebuildRunState(detail, protocol.RunStep{Sequence: 2, Stage: "second", Output: map[string]any{"markdown": "second body\n"}})
|
||||
memory := turn.RenderMemory(state.turns)
|
||||
for _, want := range []string{
|
||||
"## first · visit 1",
|
||||
"Files added to public/:\n- public/a.png",
|
||||
"## second · visit 1",
|
||||
"Files added to public/:\n- public/b.txt",
|
||||
} {
|
||||
if !strings.Contains(memory, want) {
|
||||
t.Fatalf("resumed memory missing %q:\n%s", want, memory)
|
||||
}
|
||||
}
|
||||
if strings.Count(memory, "public/a.png") != 1 {
|
||||
t.Fatalf("public file was repeated on a later turn:\n%s", memory)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRebuildRetryStateRestoresPublicFileLists proves an inherited retry
|
||||
// prefix still lists the files that turn added, using the source step's
|
||||
// persisted artifact inventory.
|
||||
func TestRebuildRetryStateRestoresPublicFileLists(t *testing.T) {
|
||||
detail := &protocol.RunDetail{
|
||||
Input: map[string]any{"prompt": "task"},
|
||||
Steps: []protocol.RunStep{
|
||||
{Sequence: 1, Stage: "first", Status: "completed", Outcome: "success", Output: map[string]any{"markdown": "first body\n"}, Artifacts: []protocol.StageArtifact{{Name: "public/report.pdf"}}},
|
||||
{Sequence: 2, Stage: "second", Status: "failed", Output: map[string]any{"error": "boom"}},
|
||||
},
|
||||
}
|
||||
handoff := map[string]any{
|
||||
"prefix": map[string]any{"first": map[string]any{"markdown": "first body\n"}},
|
||||
"prefix_provenance": []any{map[string]any{"stage": "first", "sequence": float64(1)}},
|
||||
}
|
||||
state := rebuildRetryState(detail, detail.Steps[1], handoff)
|
||||
memory := turn.RenderMemory(state.turns)
|
||||
if !strings.Contains(memory, "Files added to public/:\n- public/report.pdf") {
|
||||
t.Fatalf("retry memory lost the inherited public file list:\n%s", memory)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRetryCarriesPublicFilesAcrossAttempts proves a selected retry starts a
|
||||
// new artifact root but still reads the completed prefix's public files and
|
||||
// lists them in memory, including a retry of a retry.
|
||||
func TestRetryCarriesPublicFilesAcrossAttempts(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "retry-turns.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "retry-turns", pipeline.Template([]string{"a", "b"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err := store.List(ctx)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("submit/list: %+v %v", items, err)
|
||||
}
|
||||
runner, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
attempts := 0
|
||||
runner.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
switch def.Key {
|
||||
case "a":
|
||||
if err := os.WriteFile(filepath.Join(def.Turn.Public, "shared.txt"), []byte("shared"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "a body\n"}}, nil
|
||||
case "b":
|
||||
attempts++
|
||||
if _, err := os.Stat(filepath.Join(def.Turn.Public, "shared.txt")); err != nil {
|
||||
t.Fatalf("attempt %d cannot read the carried public file: %v", attempts, err)
|
||||
}
|
||||
memory, err := os.ReadFile(def.Turn.Memory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(memory), "public/shared.txt") {
|
||||
t.Fatalf("attempt %d memory did not list the carried public file:\n%s", attempts, memory)
|
||||
}
|
||||
if attempts < 3 {
|
||||
return stage.Result{}, fmt.Errorf("deliberate failure %d", attempts)
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "b body\n"}}, nil
|
||||
}
|
||||
t.Fatalf("unexpected stage %q", def.Key)
|
||||
return stage.Result{}, nil
|
||||
}
|
||||
original, err := runner.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "retry-turns", Workspace: t.TempDir(), Input: map[string]any{"prompt": "original task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner.wg.Wait()
|
||||
original, err = store.GetRun(ctx, original.ID)
|
||||
if err != nil || original.Status != "failed" || len(original.Steps) != 2 {
|
||||
t.Fatalf("initial run did not stop at b: %+v %v", original, err)
|
||||
}
|
||||
first, err := runner.retry(protocol.Message{RunID: original.ID, RequestKey: "retry-one", RetryStage: "b"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner.wg.Wait()
|
||||
first, err = store.GetRun(ctx, first.ID)
|
||||
if err != nil || first.Status != "failed" {
|
||||
t.Fatalf("first retry did not fail at b: %+v %v", first, err)
|
||||
}
|
||||
second, err := runner.retry(protocol.Message{RunID: first.ID, RequestKey: "retry-two", RetryStage: "b"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner.wg.Wait()
|
||||
second, err = store.GetRun(ctx, second.ID)
|
||||
if err != nil || second.Status != "succeeded" {
|
||||
t.Fatalf("transitive retry did not succeed: %+v %v", second, err)
|
||||
}
|
||||
if attempts != 3 {
|
||||
t.Fatalf("b ran %d times, want original plus two retries", attempts)
|
||||
}
|
||||
carried := filepath.Join(runner.artifactsRoot, strconv.FormatInt(second.ID, 10), "public", "shared.txt")
|
||||
if data, err := os.ReadFile(carried); err != nil || string(data) != "shared" {
|
||||
t.Fatalf("transitive retry did not carry the public file: %q %v", data, err)
|
||||
}
|
||||
paths := runner.turnPaths(second.ID, 2, "b")
|
||||
memory, err := os.ReadFile(paths.MemoryPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{"## a · visit 1", "public/shared.txt"} {
|
||||
if !strings.Contains(string(memory), want) {
|
||||
t.Fatalf("transitive retry memory missing %q:\n%s", want, memory)
|
||||
}
|
||||
}
|
||||
if _, ok := artifactNamed(second.Steps[0].Artifacts, "public/shared.txt"); !ok {
|
||||
t.Fatalf("transitive retry did not list the carried public file: %+v", second.Steps[0].Artifacts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnLayoutMatchesRunnerDirectories pins the runner's artifact layout to
|
||||
// internal/turn.Layout so the server and the protocol cannot drift.
|
||||
func TestTurnLayoutMatchesRunnerDirectories(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
r := &runner{artifactsRoot: root}
|
||||
paths := r.turnPaths(7, 2, "implementer")
|
||||
want := turn.Layout(filepath.Join(root, "7"), 2, "implementer")
|
||||
if paths != want {
|
||||
t.Fatalf("runner layout = %#v, want %#v", paths, want)
|
||||
}
|
||||
if paths.InputPath != filepath.Join(root, "7", "stages", "02-implementer", "input.md") || paths.PublicDir != filepath.Join(root, "7", "public") {
|
||||
t.Fatalf("unexpected turn paths: %#v", paths)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnPrivateAndPublicSeparation proves a visit may read and write its own
|
||||
// private directory and the shared public directory, while an earlier visit's
|
||||
// private directory is never opened to it.
|
||||
func TestTurnPrivateAndPublicSeparation(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
r := &runner{artifactsRoot: root}
|
||||
first := r.turnPaths(3, 1, "one")
|
||||
second := r.turnPaths(3, 2, "two")
|
||||
for _, paths := range []turn.Paths{first, second} {
|
||||
if err := paths.Ensure(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(first.PrivateDir, "secret.txt"), []byte("first only"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(first.PublicDir, "shared.txt"), []byte("shared"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access := r.artifactAccess(3, 2, []string{"1"}, second.TurnDir)
|
||||
private, _ := filepath.EvalSymlinks(second.PrivateDir)
|
||||
public, _ := filepath.EvalSymlinks(second.PublicDir)
|
||||
firstPrivate, _ := filepath.EvalSymlinks(first.PrivateDir)
|
||||
firstTurn, _ := filepath.EvalSymlinks(first.TurnDir)
|
||||
if access.Write != private {
|
||||
t.Fatalf("write scope = %q, want the second turn's private directory", access.Write)
|
||||
}
|
||||
if access.WriteShared != public {
|
||||
t.Fatalf("shared write scope = %q, want public", access.WriteShared)
|
||||
}
|
||||
for _, directory := range access.Read {
|
||||
if directory == firstPrivate || directory == firstTurn {
|
||||
t.Fatalf("second visit can read the first visit's private turn: %#v", access.Read)
|
||||
}
|
||||
}
|
||||
foundPublic := false
|
||||
for _, directory := range access.Read {
|
||||
if directory == public {
|
||||
foundPublic = true
|
||||
}
|
||||
}
|
||||
if !foundPublic {
|
||||
t.Fatalf("second visit cannot read public: %#v", access.Read)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTurnMissingPrivateGrantsNoWrite proves a broken visit layout fails closed
|
||||
// instead of widening write access to the server-owned turn files.
|
||||
func TestTurnMissingPrivateGrantsNoWrite(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
r := &runner{artifactsRoot: root}
|
||||
paths := r.turnPaths(4, 1, "one")
|
||||
if err := paths.Ensure(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.RemoveAll(paths.PrivateDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access := r.artifactAccess(4, 1, nil, paths.TurnDir)
|
||||
if access.Write != "" {
|
||||
t.Fatalf("missing private/ granted write scope %q", access.Write)
|
||||
}
|
||||
if access.WriteShared == "" {
|
||||
t.Fatal("shared public scope was lost with private/")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||||
)
|
||||
|
||||
// turnRoot is the run-level artifact directory shared by every stage turn. The
|
||||
// per-visit directories live under <run>/stages/ and public/ is run-level.
|
||||
func (r *runner) turnRoot(runID int64) string {
|
||||
return filepath.Join(r.artifactsRoot, strconv.FormatInt(runID, 10))
|
||||
}
|
||||
|
||||
// turnPaths returns the deterministic layout for one visit. The zero-padded
|
||||
// sequence is part of the directory name, and a retry is admitted as a new run
|
||||
// with its own artifact root, so a later visit never reuses an earlier turn's
|
||||
// files.
|
||||
func (r *runner) turnPaths(runID int64, sequence int, stageKey string) turn.Paths {
|
||||
return turn.Layout(r.turnRoot(runID), sequence, stageKey)
|
||||
}
|
||||
|
||||
// stageTurnPaths projects the turn layout onto the runtime-only paths a model
|
||||
// stage receives.
|
||||
func stageTurnPaths(paths turn.Paths) stage.TurnPaths {
|
||||
return stage.TurnPaths{
|
||||
Dir: paths.TurnDir,
|
||||
Input: paths.InputPath,
|
||||
Memory: paths.MemoryPath,
|
||||
Output: paths.OutputPath,
|
||||
Private: paths.PrivateDir,
|
||||
Public: paths.PublicDir,
|
||||
}
|
||||
}
|
||||
|
||||
// prepareTurn creates the visit layout and writes the model's input.md and
|
||||
// memory.md before the visit starts. A failure here is a run failure: the file
|
||||
// protocol is the stage contract, not best-effort evidence.
|
||||
//
|
||||
// retryInput is the complete merged input for a selected-stage retry and nil for
|
||||
// an ordinary visit. A retry override is persisted on the step, but the model
|
||||
// reads input.md rather than the step row, so the same values must be written
|
||||
// into the file or the operator's correction is invisible to the model.
|
||||
func (r *runner) prepareTurn(paths turn.Paths, state *runState, retryInput stage.Values) error {
|
||||
if err := paths.Ensure(); err != nil {
|
||||
return err
|
||||
}
|
||||
input := turnInputWithRetry(state.turnInput(), retryInput)
|
||||
memory := turn.RenderMemory(state.turns)
|
||||
if err := os.WriteFile(paths.InputPath, []byte(input), 0o600); err != nil {
|
||||
return fmt.Errorf("write %s: %w", paths.InputPath, err)
|
||||
}
|
||||
if err := os.WriteFile(paths.MemoryPath, []byte(memory), 0o600); err != nil {
|
||||
return fmt.Errorf("write %s: %w", paths.MemoryPath, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// turnInputWithRetry appends the merged retry input to the ordinary turn input.
|
||||
// It is rendered as a fenced JSON object because the values are operator data,
|
||||
// not prose; encoding/json sorts map keys so the file is deterministic.
|
||||
func turnInputWithRetry(base string, retryInput stage.Values) string {
|
||||
if len(retryInput) == 0 {
|
||||
return base
|
||||
}
|
||||
encoded, err := json.MarshalIndent(retryInput, "", " ")
|
||||
if err != nil {
|
||||
// A retry input that cannot be rendered is still shown as a visible
|
||||
// section; the stage can choose its error outcome rather than silently
|
||||
// receiving a correction it cannot see.
|
||||
return base + "\n\n# Retry input\n\nThe retry input could not be rendered.\n"
|
||||
}
|
||||
if !strings.HasSuffix(base, "\n") {
|
||||
base += "\n"
|
||||
}
|
||||
return base + "\n# Retry input\n\nThis retry was given this complete input:\n\n```json\n" + string(encoded) + "\n```\n"
|
||||
}
|
||||
|
||||
// turnInput is the run prompt on the first visit and the previous visit's
|
||||
// output afterwards.
|
||||
func (s *runState) turnInput() string {
|
||||
if len(s.turns) == 0 && strings.TrimSpace(s.lastOutput) == "" {
|
||||
return s.prompt
|
||||
}
|
||||
if strings.TrimSpace(s.lastOutput) == "" {
|
||||
return "# Previous turn output\n\n_(no output)_\n"
|
||||
}
|
||||
return turn.RenderInput("", s.lastOutput)
|
||||
}
|
||||
|
||||
// turnOutput renders a completed step for later memory. Model stages store their
|
||||
// body under the single markdown key; human and other stages keep a small
|
||||
// fenced rendering of their recorded evidence.
|
||||
func turnOutput(output stage.Values) string {
|
||||
if markdown, ok := output["markdown"].(string); ok {
|
||||
return markdown
|
||||
}
|
||||
if len(output) == 0 {
|
||||
return ""
|
||||
}
|
||||
data, err := json.MarshalIndent(output, "", " ")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return "```json\n" + string(data) + "\n```\n"
|
||||
}
|
||||
|
||||
// recordTurn appends one completed visit to the run's accumulated memory. The
|
||||
// public file list is a system-written addition computed from the filesystem,
|
||||
// never a model claim.
|
||||
func (s *runState) recordTurn(step protocol.RunStep, publicFiles []string) {
|
||||
output := turnOutput(step.Output)
|
||||
s.turns = append(s.turns, turn.MemoryEntry{
|
||||
Stage: step.Stage,
|
||||
Visit: s.visits[step.Stage],
|
||||
Output: output,
|
||||
PublicFiles: publicFiles,
|
||||
})
|
||||
s.lastOutput = output
|
||||
}
|
||||
|
||||
// publicFileSet lists regular files below the run's public directory as paths
|
||||
// relative to the run directory, retaining the "public/" prefix.
|
||||
func publicFileSet(runRoot string) map[string]bool {
|
||||
files := map[string]bool{}
|
||||
public := filepath.Join(runRoot, "public")
|
||||
_ = filepath.WalkDir(public, func(name string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if entry.IsDir() || entry.Type()&fs.ModeSymlink != 0 || !entry.Type().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
relative, err := filepath.Rel(runRoot, name)
|
||||
if err != nil || strings.HasPrefix(relative, ".."+string(os.PathSeparator)) {
|
||||
return nil
|
||||
}
|
||||
files[filepath.ToSlash(relative)] = true
|
||||
return nil
|
||||
})
|
||||
return files
|
||||
}
|
||||
|
||||
// addedPublicFiles returns the deterministic sorted difference between two
|
||||
// public file snapshots.
|
||||
func addedPublicFiles(before, after map[string]bool) []string {
|
||||
added := make([]string, 0, len(after))
|
||||
for name := range after {
|
||||
if !before[name] {
|
||||
added = append(added, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(added)
|
||||
return added
|
||||
}
|
||||
|
||||
// publicArtifacts returns the public/ entries in a persisted step inventory that
|
||||
// have not been seen in an earlier turn. scanArtifacts records the run-level
|
||||
// public directory for every model visit, so the persisted artifacts are enough
|
||||
// to rebuild each turn's system-written file list after a restart or retry
|
||||
// without reading the filesystem.
|
||||
func publicArtifacts(artifacts []protocol.StageArtifact, seen map[string]bool) []string {
|
||||
added := []string{}
|
||||
for _, artifact := range artifacts {
|
||||
if !strings.HasPrefix(artifact.Name, "public/") || seen[artifact.Name] {
|
||||
continue
|
||||
}
|
||||
seen[artifact.Name] = true
|
||||
added = append(added, artifact.Name)
|
||||
}
|
||||
sort.Strings(added)
|
||||
return added
|
||||
}
|
||||
|
||||
// markPublicFiles filters names already attributed to an earlier turn. A prefix
|
||||
// record carries the exact additions of its turn, so retries do not have to
|
||||
// guess from a source inventory that may already include carried files.
|
||||
func markPublicFiles(names []string, seen map[string]bool) []string {
|
||||
added := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
if !strings.HasPrefix(name, "public/") || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
added = append(added, name)
|
||||
}
|
||||
sort.Strings(added)
|
||||
return added
|
||||
}
|
||||
|
||||
// retryPublicBySequence attributes public files to completed steps of the
|
||||
// source attempt by first appearance. A failed step still advances the seen set
|
||||
// so files it wrote are not later attributed to an unrelated completed turn,
|
||||
// matching the live before/after snapshot.
|
||||
func retryPublicBySequence(detail *protocol.RunDetail, failedSequence int) map[int][]string {
|
||||
result := map[int][]string{}
|
||||
if detail == nil {
|
||||
return result
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence >= failedSequence {
|
||||
break
|
||||
}
|
||||
added := publicArtifacts(step.Artifacts, seen)
|
||||
if step.Status == "completed" {
|
||||
result[step.Sequence] = added
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// recordPublicFiles returns the public files a retried prefix turn added. New
|
||||
// checkpoints carry the list directly; legacy checkpoints fall back to the
|
||||
// source step's persisted inventory.
|
||||
func recordPublicFiles(record retryPrefixRecord, detail *protocol.RunDetail, seen map[string]bool) []string {
|
||||
if record.publicKnown {
|
||||
return markPublicFiles(record.public, seen)
|
||||
}
|
||||
return publicArtifacts(stepArtifacts(detail, record.sequence), seen)
|
||||
}
|
||||
|
||||
// carryRetryPublic copies the completed prefix's recorded public files into the
|
||||
// retried run's artifact root. A retry is a new run with a new root, so without
|
||||
// this the memory lists files the new visit cannot read. The copy is limited to
|
||||
// files attributed to completed prefix turns; files written by a failed visit
|
||||
// are not carried. The source is opened through os.Root and each name is
|
||||
// re-checked so a symlink cannot escape either artifact root.
|
||||
func (r *runner) carryRetryPublic(targetID, sourceID int64, failedSequence int, handoff map[string]any, source *protocol.RunDetail) error {
|
||||
files := retryPublicCarryFiles(source, failedSequence, handoff)
|
||||
if len(files) == 0 {
|
||||
return nil
|
||||
}
|
||||
sourceRootPath := filepath.Join(r.artifactsRoot, strconv.FormatInt(sourceID, 10))
|
||||
targetRootPath := filepath.Join(r.artifactsRoot, strconv.FormatInt(targetID, 10))
|
||||
if err := os.MkdirAll(targetRootPath, 0o700); err != nil {
|
||||
return fmt.Errorf("carry retry public: create %s: %w", targetRootPath, err)
|
||||
}
|
||||
sourceRoot, err := os.OpenRoot(sourceRootPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("carry retry public: open %s: %w", sourceRootPath, err)
|
||||
}
|
||||
defer sourceRoot.Close()
|
||||
targetRoot, err := os.OpenRoot(targetRootPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("carry retry public: open %s: %w", targetRootPath, err)
|
||||
}
|
||||
defer targetRoot.Close()
|
||||
for _, name := range files {
|
||||
if path.Clean(name) != name || path.IsAbs(name) || !strings.HasPrefix(name, "public/") {
|
||||
return fmt.Errorf("carry retry public: invalid recorded name %q", name)
|
||||
}
|
||||
info, statErr := sourceRoot.Lstat(name)
|
||||
if statErr != nil {
|
||||
if errors.Is(statErr, fs.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("carry retry public: read %s: %w", name, statErr)
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
src, openErr := sourceRoot.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
|
||||
if openErr != nil {
|
||||
return fmt.Errorf("carry retry public: open %s: %w", name, openErr)
|
||||
}
|
||||
if err := targetRoot.MkdirAll(path.Dir(name), 0o700); err != nil {
|
||||
src.Close()
|
||||
return fmt.Errorf("carry retry public: create %s: %w", path.Dir(name), err)
|
||||
}
|
||||
dst, createErr := targetRoot.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
|
||||
if createErr != nil {
|
||||
src.Close()
|
||||
return fmt.Errorf("carry retry public: create %s: %w", name, createErr)
|
||||
}
|
||||
_, copyErr := io.Copy(dst, src)
|
||||
closeErr := dst.Close()
|
||||
src.Close()
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("carry retry public: copy %s: %w", name, copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("carry retry public: write %s: %w", name, closeErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// retryPublicCarryFiles is the union of the public files recorded for the
|
||||
// retried prefix. Inherited records already carry their exact additions; an
|
||||
// immediate record without one falls back to first-appearance attribution from
|
||||
// the source attempt.
|
||||
func retryPublicCarryFiles(detail *protocol.RunDetail, failedSequence int, handoff map[string]any) []string {
|
||||
records := retryPrefixRecords(handoff["prefix_provenance"])
|
||||
bySequence := retryPublicBySequence(detail, failedSequence)
|
||||
files := map[string]bool{}
|
||||
inherited := map[string]bool{}
|
||||
for _, record := range records {
|
||||
if !record.publicKnown {
|
||||
continue
|
||||
}
|
||||
for _, name := range record.public {
|
||||
if strings.HasPrefix(name, "public/") {
|
||||
files[name] = true
|
||||
inherited[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(records) == 0 {
|
||||
for _, names := range bySequence {
|
||||
for _, name := range names {
|
||||
files[name] = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, record := range records {
|
||||
if record.publicKnown {
|
||||
continue
|
||||
}
|
||||
for _, name := range bySequence[record.sequence] {
|
||||
if !inherited[name] {
|
||||
files[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result := make([]string, 0, len(files))
|
||||
for name := range files {
|
||||
result = append(result, name)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// stepArtifacts finds one persisted visit's artifact inventory by sequence.
|
||||
func stepArtifacts(detail *protocol.RunDetail, sequence int) []protocol.StageArtifact {
|
||||
if detail == nil {
|
||||
return nil
|
||||
}
|
||||
for _, step := range detail.Steps {
|
||||
if step.Sequence == sequence {
|
||||
return step.Artifacts
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ensureTurnOutput writes a best-effort output.md for a completed model visit
|
||||
// that did not go through the model prompt path (for example the runner's
|
||||
// execute fixture). The real model path writes output.md from the final
|
||||
// message before the step is recorded.
|
||||
func ensureTurnOutput(paths turn.Paths, result stage.Result) {
|
||||
if paths.OutputPath == "" {
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(paths.OutputPath); err == nil {
|
||||
return
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("# outcome\n")
|
||||
b.WriteString(result.Outcome)
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(turnOutput(result.Output))
|
||||
_ = os.WriteFile(paths.OutputPath, []byte(b.String()), 0o600)
|
||||
}
|
||||
@@ -72,7 +72,7 @@ case "$3" in
|
||||
touch %q/"$id"
|
||||
echo '{}' ;;
|
||||
/api/session/active) echo '{"data":{}}' ;;
|
||||
*/message*) echo '{"data":[{"finish":"stop","content":[{"type":"text","text":"{\"outcome\":\"success\",\"output\":{\"summary\":\"done\"}}"}]}]}' ;;
|
||||
*/message*) printf '%%s\n' '{"data":[{"finish":"stop","content":[{"type":"text","text":"# outcome\nsuccess\n"}]}]}' ;;
|
||||
*/interrupt) echo '{}' ;;
|
||||
/api/session/ses_usage_*)
|
||||
id=${3#/api/session/}; tokens=0; cost=0
|
||||
|
||||
Reference in New Issue
Block a user