Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions internal/domain/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,28 +327,29 @@ type Artifact struct {
SHA256 string `json:"sha256"`
Content string `json:"content"`
BlobID string `json:"-"`
Stale bool `json:"stale,omitempty"` // derived from the current routing attempt
Stale bool `json:"stale,omitempty"` // derived from the current node attempt
// RepositoryDir records which run repository workspace the artifact was
// collected from (empty = run workspace root, where LOOP deliverables live).
RepositoryDir string `json:"repositoryDir,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}

// MarkStaleArtifacts retains history while identifying outputs from inactive attempts.
func (r *Run) MarkStaleArtifacts() {
conditional := false
for _, edge := range r.WorkflowSnapshot.Edges {
if edge.Condition != nil {
conditional = true
break
}
// ArtifactIsStale identifies outputs from an inactive execution attempt.
func (r Run) ArtifactIsStale(a Artifact) bool {
n := r.Nodes[a.NodeID]
// Run-level handoffs and legacy records without node state are unversioned.
if n == nil {
return false
}
if !conditional {
return
if n.Status != "succeeded" && n.Status != "waiting_approval" {
return true
}
return n.Attempt != a.Attempt && !(a.Attempt == 0 && n.Attempt == 1)
}

// MarkStaleArtifacts retains history while identifying outputs from inactive attempts.
func (r *Run) MarkStaleArtifacts() {
for i := range r.Artifacts {
a := &r.Artifacts[i]
n := r.Nodes[a.NodeID]
a.Stale = n == nil || n.Status != "succeeded" || n.Attempt != a.Attempt
r.Artifacts[i].Stale = r.ArtifactIsStale(r.Artifacts[i])
}
}
19 changes: 16 additions & 3 deletions internal/domain/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,10 @@ func (r Runner) SupportsDockerSandboxLimits() bool {
// hand every relayed token to any sandbox process.
const RunnerVersionProjectSharedGitCredentials = "0.13.4"

// RunnerVersionReworkArtifacts adds cleanup of retired inputs and verification
// that a replay produced its own outputs.
const RunnerVersionReworkArtifacts = "0.13.5"

func (r Runner) SupportsProjectSharedGitCredentials() bool {
return versionAtLeast(r.RunnerVersion, RunnerVersionProjectSharedGitCredentials)
}
Expand Down Expand Up @@ -725,15 +729,19 @@ type RunnerInvocation struct {
// Inputs are upstream artifacts the runner writes read-only into the
// task workspace before the invocation (paths under .agentflow/inputs).
Inputs []RunnerInputFile `json:"inputs,omitempty"`
// StaleInputs are previously mounted handoffs with no current output.
StaleInputs []string `json:"staleInputs,omitempty"`
// ReportOutputs asks the runner to return RunnerTask.Outputs: the
// OutputFiles that exist, the repository-patch inventory of every
// checkout, and workspace facts. OutputFiles are workspace-relative
// paths resolved by the control plane. RecoverOutputs lets the runner
// move a missing output file found elsewhere in the workspace into
// place, as the control plane does for its own sandboxes.
ReportOutputs bool `json:"reportOutputs,omitempty"`
ArtifactTransfer bool `json:"artifactTransfer,omitempty"`
OutputFiles []string `json:"outputFiles,omitempty"`
ReportOutputs bool `json:"reportOutputs,omitempty"`
ArtifactTransfer bool `json:"artifactTransfer,omitempty"`
OutputFiles []string `json:"outputFiles,omitempty"`
// FreshOutputFiles are contract outputs that a replay must produce afresh.
FreshOutputFiles []string `json:"freshOutputFiles,omitempty"`
RecoverOutputs bool `json:"recoverOutputs,omitempty"`
HumanContext string `json:"humanContext,omitempty"`
CredentialSource string `json:"credentialSource,omitempty"`
Expand All @@ -751,6 +759,9 @@ type RunnerInvocation struct {
// AgentCLIModels is the responsible user's saved catalog for the agent
// CLI; Cursor resolves the model's effort to an ID from it.
AgentCLIModels []CLIModel `json:"agentCliModels,omitempty"`
// RetainedOutputSHA256 identifies exact bodies verified in an earlier
// invocation of the same node attempt.
RetainedOutputSHA256 map[string]string `json:"retainedOutputSha256,omitempty"`
// MCPCallServers is the project/personal HTTP MCP set for `agentflow mcp call`
// in scripts, verification gates, and Agent hooks. It is unbound; personal
// credentials are applied in memory on the runner. Agent Assets stay
Expand Down Expand Up @@ -868,6 +879,8 @@ type RunnerTaskOutputs struct {
TooLarge []string `json:"tooLarge,omitempty"`
FileBlobs map[string]ArtifactBlob `json:"fileBlobs,omitempty"`
FileErrors map[string]string `json:"fileErrors,omitempty"`
// FreshOutputFiles lists files verified as rewritten during this attempt.
FreshOutputFiles []string `json:"freshOutputFiles,omitempty"`
// Patches maps a repository checkout dir ("" is the workspace root) to
// its repository-patch inventory. Unchanged checkouts are absent.
Patches map[string]string `json:"patches,omitempty"`
Expand Down
95 changes: 55 additions & 40 deletions internal/engine/artifacts.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package engine
import (
"agentflow/internal/domain"
"agentflow/internal/runtime"
"context"
"crypto/sha256"
"errors"
"fmt"
Expand All @@ -25,14 +24,10 @@ const maxArtifactBytes = 1 << 20
var artifactSeq atomic.Uint64

func materializeInputs(workspace string, wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run, open ...func(string) (io.ReadCloser, error)) (string, error) {
sources := map[string]bool{}
for _, edge := range wf.Edges {
if edge.Target == node.ID {
sources[edge.Source] = true
}
sources, selected, stale := selectArtifactInputs(wf, node, run)
if err := runtime.RemoveArtifactInputs(workspace, stale); err != nil {
return "", err
}
prior := ancestors(wf, node.ID)
selected := latestInputArtifacts(activeRoutingArtifacts(run), sources, prior)
var manifest strings.Builder
for _, artifact := range selected {
if artifact.Name == "repository-patch" {
Expand Down Expand Up @@ -212,34 +207,28 @@ func removeUntrackedHostLeak(host, path string) {
}
}

func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode, workspace string, reported *reportedOutputs, output string) []domain.Artifact {
func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode, attempt, generation int, workspace string, outputs nodeOutputs, output string) []domain.Artifact {
current, ok := e.repo.RunProgress(runID)
if !ok {
if !ok || !shouldCommitNodeOutcome(current, current.Nodes[node.ID], generation, attempt, false) {
return nil
}
var outputs nodeOutputs = archivedWorkspaceOutputs{
workspaceOutputs: workspaceOutputs(workspace),
save: func(id string, body io.Reader) (domain.ArtifactBlob, error) {
return e.repo.SaveArtifactBlob(context.Background(), runID, id, body)
},
}
recovered := []string(nil)
if reported != nil {
outputs = reported
recovered = reported.takeRecovered()
} else {
recovered = recoverMisplacedArtifacts(workspace, current.Repository.LocalPath, node)
}
recovered := recoverNodeOutputs(outputs, workspace, current.Repository.LocalPath, node)
if len(recovered) > 0 {
e.observe(runID, node.ID, domain.TelemetryEvent{Category: "artifact", Name: "artifact.recovered", Phase: "progress", Message: "失败路径收回交付物:" + strings.Join(recovered, ";")})
}
artifacts, err := collectArtifactsMode(outputs, current, node, output, true)
if err != nil || len(artifacts) == 0 {
return nil
}
if !e.updateRunAt(runID, false, func(r *domain.Run) {
saved := false
updated := e.updateRunAt(runID, false, func(r *domain.Run) {
if !shouldCommitNodeOutcome(*r, r.Nodes[node.ID], generation, attempt, false) {
return
}
r.Artifacts = append(r.Artifacts, artifacts...)
}) {
saved = true
})
if !updated || !saved {
return nil
}
for _, artifact := range artifacts {
Expand Down Expand Up @@ -449,29 +438,55 @@ func latestInputArtifacts(artifacts []domain.Artifact, direct, prior map[string]
return out
}

// Old attempts remain auditable, but an inactive or rerun node's artifacts
// must not be handed to the newly selected branch.
func activeRoutingArtifacts(run domain.Run) []domain.Artifact {
conditional := false
for _, edge := range run.WorkflowSnapshot.Edges {
if edge.Condition != nil {
conditional = true
break
}
}
if !conditional {
return run.Artifacts
}
// Historical outputs remain auditable. Only the current successful attempt can
// supply artifacts to downstream nodes.
func currentNodeArtifacts(run domain.Run) []domain.Artifact {
var active []domain.Artifact
for _, artifact := range run.Artifacts {
n := run.Nodes[artifact.NodeID]
if n != nil && n.Status == "succeeded" && n.Attempt == artifact.Attempt {
if node := run.Nodes[artifact.NodeID]; node != nil && node.Status != "succeeded" {
continue
}
if !run.ArtifactIsStale(artifact) {
active = append(active, artifact)
}
}
return active
}

func selectArtifactInputs(wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run) (map[string]bool, []domain.Artifact, []string) {
direct := map[string]bool{}
for _, edge := range wf.Edges {
if edge.Target == node.ID {
direct[edge.Source] = true
}
}
prior := ancestors(wf, node.ID)
selected := latestInputArtifacts(currentNodeArtifacts(run), direct, prior)
paths := map[string]bool{}
for _, artifact := range selected {
paths[artifactInputRelPath(run, artifact)] = true
}
var stale []string
for _, artifact := range run.Artifacts {
if artifact.Name == "repository-patch" || !run.ArtifactIsStale(artifact) {
continue
}
// Retire a producer's previous inputs when that producer restarts.
// Its old aliases can still be in the shared checkout even though
// the producer is not an ancestor of itself.
if artifact.NodeID != node.ID && !includeArtifact(direct, prior, artifact) {
continue
}
rel := artifactInputRelPath(run, artifact)
if !paths[rel] {
stale = append(stale, rel)
paths[rel] = true
}
}
sort.Strings(stale)
return direct, selected, stale
}

func includeArtifact(direct, prior map[string]bool, artifact domain.Artifact) bool {
if direct[artifact.NodeID] {
return true
Expand Down
11 changes: 7 additions & 4 deletions internal/engine/artifacts_cases_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,15 @@ func TestArtifactCollectionErrorsAndFreeze(t *testing.T) {
}

e, st := cvEEngine(t)
stored := domain.Run{ID: "freeze-run", Nodes: map[string]*domain.NodeRun{"node": {Attempt: 1}}}
stored := domain.Run{ID: "freeze-run", Nodes: map[string]*domain.NodeRun{"node": {Attempt: 1, Status: "running"}}}
if err := st.PutRun(stored); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(workspace, "freeze.md"), []byte("frozen"), 0o644); err != nil {
t.Fatal(err)
}
freezeNode := domain.WorkflowNode{ID: "node", ArtifactOutputs: []domain.ArtifactContract{{Name: "freeze", Path: "freeze.md", Required: true}}}
e.freezeAvailableArtifacts(stored.ID, freezeNode, workspace, nil, "result body")
e.freezeAvailableArtifacts(stored.ID, freezeNode, 1, stored.Generation, workspace, workspaceOutputs(workspace), "result body")
updated, ok := st.RunState(stored.ID)
if !ok || len(updated.Artifacts) == 0 || updated.Artifacts[0].Name != "freeze" {
t.Fatalf("frozen artifacts=%v", updated.Artifacts)
Expand All @@ -150,10 +150,13 @@ func TestArtifactCollectionErrorsAndFreeze(t *testing.T) {
Recovered: []string{"reported.md"},
})
reportedNode := domain.WorkflowNode{ID: "node", ArtifactOutputs: []domain.ArtifactContract{{Name: "reported", Path: "reported.md", Required: true}}}
e.freezeAvailableArtifacts(stored.ID, reportedNode, workspace, reported, "reported body")
e.freezeAvailableArtifacts(stored.ID, reportedNode, 1, stored.Generation, workspace, reported, "reported body")
updated, _ = st.RunState(stored.ID)
if len(updated.Artifacts) < 2 {
t.Fatalf("reported artifacts=%v", updated.Artifacts)
}
e.freezeAvailableArtifacts("missing-run", freezeNode, workspace, nil, "ignored")
if frozen := e.freezeAvailableArtifacts(stored.ID, freezeNode, 0, stored.Generation, workspace, workspaceOutputs(workspace), "stale attempt"); len(frozen) != 0 {
t.Fatalf("frozen artifacts from an earlier attempt: %v", frozen)
}
e.freezeAvailableArtifacts("missing-run", freezeNode, 1, stored.Generation, workspace, workspaceOutputs(workspace), "ignored")
}
30 changes: 22 additions & 8 deletions internal/engine/node_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -251,8 +252,18 @@ func (e *Engine) execute(ctx context.Context, runID string) {
})
continue
}
e.updateRun(runID, func(current *domain.Run) { current.Status = "waiting" })
return
e.stateMu.Lock()
parked, err := e.repo.ParkRunForApproval(r)
e.stateMu.Unlock()
if err != nil {
log.Printf("park run %s for approval: %v", runID, err)
time.Sleep(80 * time.Millisecond)
}
if parked {
e.publish(runID)
return
}
continue
}
if hasFailed(wf, r) {
e.finishAtReason(runID, generation, "failed", pipelineFailedMessage, finishFailedNode)
Expand Down Expand Up @@ -779,9 +790,11 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
artifactContext := ""
if runnerFound && runner.SupportsReportedOutputs() {
var inputs []domain.RunnerInputFile
artifactContext, inputs = runnerArtifactInputs(wf, node, current, runner.SupportsArtifactTransfer())
var staleInputs []string
artifactContext, inputs, staleInputs = runnerArtifactInputs(wf, node, current, runner.SupportsArtifactTransfer())
reported = sb.beginReportedOutputs(node.ID, inputs)
reported.transfer = runner.SupportsArtifactTransfer()
reported.staleInputs = staleInputs
reported.openBlob = func(id string) (io.ReadCloser, error) {
_, body, err := e.repo.OpenArtifactBlob(ctx, runID, id)
return body, err
Expand Down Expand Up @@ -1186,6 +1199,9 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
return result, runErr
}
}
if err == nil {
outputs, err = trackReplayedOutputs(outputs, current, effectiveNode)
}
if err != nil {
failNode(err, nodeRejects(node))
return
Expand Down Expand Up @@ -1313,10 +1329,8 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
if err == nil {
live, _ := e.repo.RunProgress(runID)
var recovered []string
if reported != nil {
recovered = reported.takeRecovered()
} else if repositoryPreview == nil {
recovered = recoverMisplacedArtifacts(sb.Workspace(), live.Repository.LocalPath, effectiveNode)
if reported != nil || repositoryPreview == nil {
recovered = recoverNodeOutputs(outputs, sb.Workspace(), live.Repository.LocalPath, effectiveNode)
}
if len(recovered) > 0 {
e.observe(runID, node.ID, domain.TelemetryEvent{Category: "artifact", Name: "artifact.recovered", Phase: "progress", Message: "从错误写入位置收回交付物:" + strings.Join(recovered, ";")})
Expand Down Expand Up @@ -1419,7 +1433,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl
}
e.attachLoopRetro(runID, node.ID, retroWorkspace, lastIteration, err, failedAction)
if err != nil {
frozen := e.freezeAvailableArtifacts(runID, effectiveNode, sb.Workspace(), reported, output)
frozen := e.freezeAvailableArtifacts(runID, effectiveNode, executionAttempt, executionGeneration, sb.Workspace(), outputs, output)
if ctx.Err() != nil || runtime.IsSandboxInterrupt(err) {
if ctx.Err() == nil {
e.requeueInterruptedNode(runID, node.ID, executionAttempt, executionGeneration)
Expand Down
Loading
Loading