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:
+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))
|
||||
|
||||
Reference in New Issue
Block a user