From 494c03359fe37838dc333a2d7f716c2b57812dda Mon Sep 17 00:00:00 2001 From: crispinhu Date: Thu, 3 Dec 2026 02:18:09 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=B9=B6=E8=A1=8C?= =?UTF-8?q?=20DAG=20=E8=BF=94=E5=B7=A5=E5=92=8C=E8=BF=90=E8=A1=8C=E6=8B=93?= =?UTF-8?q?=E6=89=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/domain/run.go | 26 ++-- internal/domain/runner.go | 16 ++- internal/engine/artifacts.go | 81 +++++++------ internal/engine/artifacts_cases_test.go | 11 +- internal/engine/node_execute.go | 24 +++- internal/engine/node_outputs.go | 109 ++++++++++++++--- internal/engine/node_outputs_test.go | 64 +++++++++- internal/engine/parallel_branches_test.go | 92 ++++++++++++++ internal/engine/prompt.go | 2 +- internal/engine/prompt_context_test.go | 29 +++-- internal/engine/runner_dispatch.go | 3 + internal/engine/workflow_routing_test.go | 2 +- internal/engine/workspace_artifacts.go | 2 +- internal/httpapi/runner_outputs_test.go | 3 + internal/httpapi/runners.go | 8 +- internal/repo/run_lease_test.go | 30 +++++ internal/repo/runs.go | 15 +++ internal/runner/daemon.go | 17 ++- internal/runner/outputs.go | 44 ++++++- internal/runner/outputs_test.go | 32 +++++ internal/runner/reported_outputs_test.go | 60 +++++++++ internal/runtime/workspace_artifacts.go | 70 +++++++++++ web/app/runs.js | 141 ++++++++++++++++++---- web/observability.css | 24 ++-- webtest/tests/runs-detail.test.mjs | 63 +++++----- 25 files changed, 803 insertions(+), 165 deletions(-) diff --git a/internal/domain/run.go b/internal/domain/run.go index c7abce8af..19c0a0880 100644 --- a/internal/domain/run.go +++ b/internal/domain/run.go @@ -327,28 +327,26 @@ 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"` } +// 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 + } + return n.Status != "succeeded" || (n.Attempt != a.Attempt && !(a.Attempt == 0 && n.Attempt == 1)) +} + // 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 - } - } - if !conditional { - return - } 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]) } } diff --git a/internal/domain/runner.go b/internal/domain/runner.go index e69347f15..aa15b0ea5 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -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) } @@ -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"` @@ -868,6 +876,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"` diff --git a/internal/engine/artifacts.go b/internal/engine/artifacts.go index 3b0fb4e54..84f3a22e2 100644 --- a/internal/engine/artifacts.go +++ b/internal/engine/artifacts.go @@ -3,7 +3,6 @@ package engine import ( "agentflow/internal/domain" "agentflow/internal/runtime" - "context" "crypto/sha256" "errors" "fmt" @@ -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" { @@ -212,20 +207,13 @@ 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 + if reported, ok := outputs.(*reportedOutputs); ok { recovered = reported.takeRecovered() } else { recovered = recoverMisplacedArtifacts(workspace, current.Repository.LocalPath, node) @@ -237,9 +225,15 @@ func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode 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 { @@ -449,29 +443,46 @@ 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 !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" || !includeArtifact(direct, prior, artifact) || !run.ArtifactIsStale(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 diff --git a/internal/engine/artifacts_cases_test.go b/internal/engine/artifacts_cases_test.go index cc0c4e9a7..410d1cf76 100644 --- a/internal/engine/artifacts_cases_test.go +++ b/internal/engine/artifacts_cases_test.go @@ -131,7 +131,7 @@ 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) } @@ -139,7 +139,7 @@ func TestArtifactCollectionErrorsAndFreeze(t *testing.T) { 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) @@ -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") } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 546e51eb1..6b77177d1 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -13,6 +13,7 @@ import ( "errors" "fmt" "io" + "log" "os" "path/filepath" "strings" @@ -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) @@ -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 @@ -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 @@ -1419,7 +1435,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) diff --git a/internal/engine/node_outputs.go b/internal/engine/node_outputs.go index 0f5a7a790..96df6a3b8 100644 --- a/internal/engine/node_outputs.go +++ b/internal/engine/node_outputs.go @@ -12,6 +12,7 @@ import ( "sync" "agentflow/internal/domain" + "agentflow/internal/runtime" ) var ( @@ -70,7 +71,24 @@ func readWorkspaceOutput(file io.Reader) ([]byte, error) { type archivedWorkspaceOutputs struct { workspaceOutputs - save func(string, io.Reader) (domain.ArtifactBlob, error) + baseline runtime.ArtifactOutputBaseline + save func(string, io.Reader) (domain.ArtifactBlob, error) +} + +func (w archivedWorkspaceOutputs) openFile(rel string) (*os.File, int64, error) { + file, size, err := w.workspaceOutputs.openFile(rel) + if err != nil || w.baseline[rel] == nil { + return file, size, err + } + info, err := file.Stat() + if err == nil && w.baseline.Unchanged(rel, info) { + err = runtime.ErrStaleArtifactOutput + } + if err != nil { + file.Close() + return nil, 0, err + } + return file, size, nil } func (w archivedWorkspaceOutputs) archiveFile(rel, id string) ([]byte, domain.ArtifactBlob, error) { @@ -128,9 +146,12 @@ func (w workspaceOutputs) repositoryPatch(dir string) ([]byte, error) { // invocation of one node. It replaces the control-plane copy of the // workspace for artifact validation, registration, and the gate result. type reportedOutputs struct { - inputs []domain.RunnerInputFile - transfer bool - openBlob func(string) (io.ReadCloser, error) + inputs []domain.RunnerInputFile + staleInputs []string + previousOutputs map[string]map[string]bool + freshOutputs map[string]bool + transfer bool + openBlob func(string) (io.ReadCloser, error) mu sync.Mutex files map[string]string @@ -142,7 +163,7 @@ type reportedOutputs struct { } func newReportedOutputs(inputs []domain.RunnerInputFile) *reportedOutputs { - r := &reportedOutputs{inputs: inputs} + r := &reportedOutputs{inputs: inputs, freshOutputs: map[string]bool{}} r.reset() return r } @@ -168,13 +189,24 @@ func (r *reportedOutputs) absorb(outputs *domain.RunnerTaskOutputs) { } r.mu.Lock() defer r.mu.Unlock() + for _, rel := range outputs.FreshOutputFiles { + r.freshOutputs[rel] = true + } for rel, content := range outputs.Files { r.clearFile(rel) - r.files[rel] = content + if r.outputIsStale(rel, runtime.WorkspaceContentSHA(content)) { + r.errors[rel] = runtime.ErrStaleArtifactOutput.Error() + } else { + r.files[rel] = content + } } for rel, blob := range outputs.FileBlobs { r.clearFile(rel) - r.blobs[rel] = blob + if r.outputIsStale(rel, blob.SHA256) { + r.errors[rel] = runtime.ErrStaleArtifactOutput.Error() + } else { + r.blobs[rel] = blob + } } for rel, message := range outputs.FileErrors { r.clearFile(rel) @@ -190,6 +222,22 @@ func (r *reportedOutputs) absorb(outputs *domain.RunnerTaskOutputs) { r.recovered = append(r.recovered, outputs.Recovered...) } +// Older runners do not report file identity. An unchanged digest from a +// previous attempt is insufficient evidence that they produced a new output. +func (r *reportedOutputs) outputIsStale(rel, digest string) bool { + return r.previousOutputs[rel][digest] && !r.freshOutputs[rel] +} + +func (r *reportedOutputs) requireFreshOutputs(inv *domain.RunnerInvocation) { + r.mu.Lock() + defer r.mu.Unlock() + for _, rel := range inv.OutputFiles { + if _, tracked := r.previousOutputs[rel]; tracked && !r.freshOutputs[rel] { + inv.FreshOutputFiles = append(inv.FreshOutputFiles, rel) + } + } +} + func (r *reportedOutputs) clearFile(rel string) { delete(r.files, rel) delete(r.blobs, rel) @@ -284,21 +332,50 @@ func artifactOutputFiles(run domain.Run, node domain.WorkflowNode) []string { return out } +func trackReplayedOutputs(outputs nodeOutputs, run domain.Run, node domain.WorkflowNode) (nodeOutputs, error) { + nr := run.Nodes[node.ID] + if nr == nil || nr.Attempt < 2 || len(node.ArtifactOutputs) == 0 { + return outputs, nil + } + // A cancelled execution can leave an output on disk without archiving it. + paths := artifactOutputFiles(run, node) + switch out := outputs.(type) { + case archivedWorkspaceOutputs: + baseline, err := runtime.SnapshotArtifactOutputs(string(out.workspaceOutputs), paths) + out.baseline = baseline + return out, err + case *reportedOutputs: + out.previousOutputs = make(map[string]map[string]bool, len(paths)) + for _, path := range paths { + out.previousOutputs[path] = make(map[string]bool) + } + for _, artifact := range run.Artifacts { + if artifact.NodeID != node.ID || artifact.Attempt >= nr.Attempt || artifact.Name == "repository-patch" { + continue + } + rel, ok := artifactRelPath(artifact.RepositoryDir, artifact.Path) + if digests := out.previousOutputs[rel]; ok && digests != nil { + digest := artifact.SHA256 + if digest == "" { + digest = runtime.WorkspaceContentSHA(artifact.Content) + } + digests[digest] = true + } + } + } + return outputs, nil +} + // runnerArtifactInputs is materializeInputs for an execution machine: the // same selection and prompt manifest, returned as files for the runner to // write instead of being written into a control-plane workspace. Repository // patches are never applied; the runner's checkout is the source of truth. -func runnerArtifactInputs(wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run, stream ...bool) (string, []domain.RunnerInputFile) { +func runnerArtifactInputs(wf domain.WorkflowDefinition, node domain.WorkflowNode, run domain.Run, stream ...bool) (string, []domain.RunnerInputFile, []string) { transfer := len(stream) != 0 && stream[0] - 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) var manifest strings.Builder var files []domain.RunnerInputFile - for _, artifact := range latestInputArtifacts(activeRoutingArtifacts(run), sources, ancestors(wf, node.ID)) { + for _, artifact := range selected { if artifact.Name == "repository-patch" { if !sources[artifact.NodeID] { continue @@ -313,7 +390,7 @@ func runnerArtifactInputs(wf domain.WorkflowDefinition, node domain.WorkflowNode handoffManifest, handoffFiles := sopHandoffInputs(run, transfer) manifest.WriteString(handoffManifest) files = append(files, handoffFiles...) - return strings.TrimSpace(manifest.String()), files + return strings.TrimSpace(manifest.String()), files, stale } func runnerInputFile(artifact domain.Artifact, rel string, stream bool) domain.RunnerInputFile { diff --git a/internal/engine/node_outputs_test.go b/internal/engine/node_outputs_test.go index ba3d69454..953fbd874 100644 --- a/internal/engine/node_outputs_test.go +++ b/internal/engine/node_outputs_test.go @@ -2,10 +2,14 @@ package engine import ( "errors" + "io/fs" + "os" + "path/filepath" "strings" "testing" "agentflow/internal/domain" + "agentflow/internal/runtime" ) func TestReportedOutputsValidateRepositoryScopedContracts(t *testing.T) { @@ -74,7 +78,7 @@ func TestRunnerArtifactInputsMatchWorkspaceMount(t *testing.T) { {NodeID: "impl", Attempt: 1, Name: "notes", MediaType: "text/markdown", RepositoryDir: "svc-a", Content: "A"}, {NodeID: "impl", Attempt: 1, Name: "repository-patch", RepositoryDir: "svc-a", Content: "repository-patch summary\nM\tmain.go"}, }} - manifest, files := runnerArtifactInputs(wf, domain.WorkflowNode{ID: "review"}, run) + manifest, files, _ := runnerArtifactInputs(wf, domain.WorkflowNode{ID: "review"}, run) if len(files) != 1 || files[0].Path != ".agentflow/inputs/impl/svc-a/notes.md" || files[0].Content != "A" { t.Fatalf("files = %+v", files) } @@ -90,3 +94,61 @@ func TestRunnerArtifactInputsMatchWorkspaceMount(t *testing.T) { t.Fatalf("local manifest points elsewhere than the mounted file: %s", local) } } + +func TestArtifactHandoffRemovesAnOutputOmittedFromTheNewAttempt(t *testing.T) { + t.Parallel() + wf := domain.WorkflowDefinition{Edges: []domain.WorkflowEdge{edge("review", "next")}} + next := domain.WorkflowNode{ID: "next"} + run := domain.Run{WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{ + "review": {Status: "succeeded", Attempt: 1}, + }} + oldOptional := domain.Artifact{NodeID: "review", Attempt: 1, Name: "optional", Content: "old"} + run.Artifacts = []domain.Artifact{oldOptional} + workspace := t.TempDir() + if _, err := materializeInputs(workspace, wf, next, run); err != nil { + t.Fatal(err) + } + + run.Nodes["review"].Attempt = 2 + run.Artifacts = append(run.Artifacts, domain.Artifact{NodeID: "review", Attempt: 2, Name: "report", Content: "new"}) + manifest, files, stale := runnerArtifactInputs(wf, next, run) + oldPath := artifactInputRelPath(run, oldOptional) + if len(files) != 1 || files[0].Content != "new" || strings.Contains(manifest, "optional") || + len(stale) != 1 || stale[0] != oldPath { + t.Fatalf("runner handoff: files=%v stale=%v manifest=%q", files, stale, manifest) + } + if _, err := materializeInputs(workspace, wf, next, run); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(workspace, oldPath)); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("stale file still available: %v", err) + } + run.MarkStaleArtifacts() + if !run.Artifacts[0].Stale || run.Artifacts[1].Stale { + t.Fatalf("historical artifact flags: %+v", run.Artifacts) + } +} + +func TestReportedReplayArtifactsRequireFreshnessEvidence(t *testing.T) { + t.Parallel() + const path = "review.md" + outputs := newReportedOutputs(nil) + outputs.previousOutputs = map[string]map[string]bool{path: { + runtime.WorkspaceContentSHA("same report"): true, + runtime.WorkspaceContentSHA("later report"): true, + }} + report := &domain.RunnerTaskOutputs{Files: map[string]string{path: "same report"}} + outputs.absorb(report) + if _, err := outputs.readFile(path); err == nil { + t.Fatal("legacy runner accepted the previous attempt's unchanged report") + } + + report.FreshOutputFiles = []string{path} + outputs.absorb(report) + outputs.reset() + report.FreshOutputFiles = nil + outputs.absorb(report) + if got, err := outputs.readFile(path); err != nil || string(got) != "same report" { + t.Fatalf("rewritten identical report = %q, %v", got, err) + } +} diff --git a/internal/engine/parallel_branches_test.go b/internal/engine/parallel_branches_test.go index cc8cec6dc..c5b59914d 100644 --- a/internal/engine/parallel_branches_test.go +++ b/internal/engine/parallel_branches_test.go @@ -1,7 +1,9 @@ package engine import ( + "os" "path/filepath" + "strings" "testing" "time" @@ -357,3 +359,93 @@ func TestSchedulerSettlesRunWithCancelledNode(t *testing.T) { t.Fatalf("left=%s right=%s", got.Nodes["left"].Status, got.Nodes["right"].Status) } } + +func TestSharedDesignReworkRequiresNewReviewEvidence(t *testing.T) { + for _, tc := range []struct { + name string + interrupted bool + rewrite bool + }{ + {name: "old-file"}, + {name: "unarchived-file", interrupted: true}, + {name: "rewritten-file", rewrite: true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + backend := scriptNode("backend", `set -eu +if [ -f impl.txt ]; then + test "$(cat impl.txt)" = v1 + printf v2 > impl.txt +else + printf v1 > impl.txt +fi`) + review := scriptNode("review", `if [ "$(cat impl.txt)" = v1 ]; then printf report > review.md; fi`) + if tc.interrupted { + review.Script = `if [ "$(cat impl.txt)" = v1 ]; then printf report > review.md; exec sleep 30; fi` + } + if tc.rewrite { + review.Script = "printf report > review.md" + } + review.ArtifactOutputs = []domain.ArtifactContract{{Name: "review", Path: "review.md", Required: true}} + wf := domain.WorkflowDefinition{ + ID: "shared-design-evidence-" + tc.name, Name: tc.name, SandboxProfileID: "test-native", + Nodes: []domain.WorkflowNode{ + scriptNode("design", "true"), backend, review, + {ID: "frontend", Name: "frontend", Type: "approval", RejectTo: "design", MaxReworks: 1}, + scriptNode("summary", "test -f .agentflow/inputs/review/review.md"), + }, + Edges: []domain.WorkflowEdge{ + edge("design", "backend"), edge("backend", "review"), edge("design", "frontend"), + edge("review", "summary"), edge("frontend", "summary"), + }, + } + engine, store := parallelTestEngine(t, wf) + run, err := engine.Start(wf.ID, "") + if err != nil { + t.Fatal(err) + } + waitRun(t, store, run.ID, 15*time.Second, func(live domain.Run) bool { + if live.Nodes["frontend"].Status != "waiting_approval" { + return false + } + if tc.interrupted { + report, _ := os.ReadFile(filepath.Join(engine.RunWorkspace(run.ID), "review.md")) + return live.Nodes["review"].Status == "running" && string(report) == "report" + } + return live.Nodes["review"].Status == "succeeded" + }) + if err := engine.Reject(run.ID, domain.RejectRequest{NodeID: "frontend", TargetID: "design", Reason: "update common design"}); err != nil { + t.Fatal(err) + } + waitRun(t, store, run.ID, 30*time.Second, func(run domain.Run) bool { + return run.Nodes["design"].Attempt == 2 && run.Nodes["frontend"].Status == "waiting_approval" + }) + if err := engine.Approve(run.ID, "frontend", ""); err != nil { + t.Fatal(err) + } + status := "failed" + if tc.rewrite { + status = "succeeded" + } + waitFor(t, store, run.ID, status) + got, _ := store.Run(run.ID) + if got.Nodes["design"].ReworkCount != 1 || got.Nodes["backend"].Attempt != 2 || got.Nodes["review"].Attempt != 2 { + t.Fatalf("missing shared ancestor replay: %+v", got.Nodes) + } + if tc.rewrite { + if got.Nodes["summary"].Status != "succeeded" { + t.Fatal("fresh review output did not reach the join") + } + } else { + if !strings.Contains(got.Nodes["review"].Error, "重新生成") || got.Nodes["summary"].Attempt != 0 { + t.Fatalf("stale file passed review or let the join start: %+v", got.Nodes) + } + for _, artifact := range got.Artifacts { + if artifact.NodeID == "review" && artifact.Name == "review" && (tc.interrupted || artifact.Attempt != 1) { + t.Fatalf("the old file was archived again: %+v", artifact) + } + } + } + }) + } +} diff --git a/internal/engine/prompt.go b/internal/engine/prompt.go index 9c9f813b3..41a413adf 100644 --- a/internal/engine/prompt.go +++ b/internal/engine/prompt.go @@ -104,7 +104,7 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, node replacements = append(replacements, "{{node."+id+".output}}", nodeRun.Output) } } - for _, artifact := range activeRoutingArtifacts(run) { + for _, artifact := range currentNodeArtifacts(run) { placeholder := "{{artifact." + artifact.NodeID + "." + artifact.Name + "}}" if !strings.Contains(prompt, placeholder) { continue diff --git a/internal/engine/prompt_context_test.go b/internal/engine/prompt_context_test.go index 9b58c2ca4..5a6d4327d 100644 --- a/internal/engine/prompt_context_test.go +++ b/internal/engine/prompt_context_test.go @@ -47,17 +47,22 @@ func TestNodePromptAppendsOnlyToAgentTaskbook(t *testing.T) { func TestPromptArtifactPlaceholderIgnoresStaleArtifacts(t *testing.T) { t.Parallel() - wf := domain.WorkflowDefinition{Edges: []domain.WorkflowEdge{{Source: "source", Target: "report", Condition: &domain.WorkflowCondition{Type: "route", Values: []string{"small"}}}}} - node := domain.WorkflowNode{ID: "report"} - run := domain.Run{WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{ - "source": {Status: "succeeded", Attempt: 2}, - }, Artifacts: []domain.Artifact{ - {NodeID: "source", Attempt: 1, Name: "classification", Content: "stale"}, - {NodeID: "source", Attempt: 2, Name: "classification", Content: "active"}, - }} - role := &domain.AgentDefinition{Prompt: "{{artifact.source.classification}}"} - got := applyPromptPlaceholders(nil, wf, node, role, run) - if strings.Contains(got, "stale") || !strings.Contains(got, "active") { - t.Fatalf("prompt artifact selection = %q", got) + for _, edge := range []domain.WorkflowEdge{ + {Source: "source", Target: "report"}, + {Source: "source", Target: "report", Condition: &domain.WorkflowCondition{Type: "route", Values: []string{"small"}}}, + } { + wf := domain.WorkflowDefinition{Edges: []domain.WorkflowEdge{edge}} + node := domain.WorkflowNode{ID: "report"} + run := domain.Run{WorkflowSnapshot: wf, Nodes: map[string]*domain.NodeRun{ + "source": {Status: "succeeded", Attempt: 2}, + }, Artifacts: []domain.Artifact{ + {NodeID: "source", Attempt: 1, Name: "classification", Content: "old report"}, + {NodeID: "source", Attempt: 2, Name: "classification", Content: "new report"}, + }} + role := &domain.AgentDefinition{Prompt: "{{artifact.source.classification}}"} + got := applyPromptPlaceholders(nil, wf, node, role, run) + if strings.Contains(got, "old report") || !strings.Contains(got, "new report") { + t.Fatalf("conditional=%t prompt artifact selection = %q", edge.Condition != nil, got) + } } } diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.go index e32f6a6cd..21c1b9c2e 100644 --- a/internal/engine/runner_dispatch.go +++ b/internal/engine/runner_dispatch.go @@ -299,6 +299,7 @@ func (e *Engine) dispatchRunnerTask(ctx context.Context, runnerID string, run do if path := strings.TrimSpace(options.GateResultPath); path != "" { invocation.OutputFiles = append(invocation.OutputFiles, path) } + reported.requireFreshOutputs(invocation) invocation.RecoverOutputs = invocation.RepositoryPreview == nil && normalizeExecutionScope(node.ExecutionScope) != domain.ExecutionScopeRepositories } invocation.MCPCallServers = e.resolveRunScriptMCPAssets(run).MCPServers @@ -497,6 +498,7 @@ func (e *Engine) dispatchRunnerScript(ctx context.Context, runnerID string, run invocation.OutputFiles = append(invocation.OutputFiles, rel) } } + reported.requireFreshOutputs(invocation) invocation.RecoverOutputs = strings.TrimSpace(artifactDirectory) == "" } task := domain.RunnerTask{ @@ -568,6 +570,7 @@ func (e *Engine) setRunnerArtifactInputs(run domain.Run, nodeID string, inv *dom if reported != nil { inv.ArtifactTransfer = reported.transfer inv.Inputs = reported.inputs + inv.StaleInputs = reported.staleInputs } if inv.ArtifactTransfer { inv.Inputs = append(e.runnerArchivedInputs(run, nodeID), inv.Inputs...) diff --git a/internal/engine/workflow_routing_test.go b/internal/engine/workflow_routing_test.go index 6c65bdf32..028ce0da5 100644 --- a/internal/engine/workflow_routing_test.go +++ b/internal/engine/workflow_routing_test.go @@ -482,7 +482,7 @@ func TestConditionalRoutingAgentAndReplay(t *testing.T) { if second.Nodes["small"].Status != "skipped" || second.Nodes["large"].Status != "succeeded" || second.Nodes["delivery"].Status != "succeeded" { t.Fatalf("replay route: small=%+v large=%+v delivery=%+v", second.Nodes["small"], second.Nodes["large"], second.Nodes["delivery"]) } - for _, artifact := range activeRoutingArtifacts(second) { + for _, artifact := range currentNodeArtifacts(second) { if artifact.NodeID == "small" { t.Fatalf("stale artifact exposed: %+v", artifact) } diff --git a/internal/engine/workspace_artifacts.go b/internal/engine/workspace_artifacts.go index e68e08d55..6c201855a 100644 --- a/internal/engine/workspace_artifacts.go +++ b/internal/engine/workspace_artifacts.go @@ -38,7 +38,7 @@ func archivedWorkspaceArtifacts(run domain.Run, executingNode string) map[string } } latest := map[string]domain.Artifact{} - for _, a := range activeRoutingArtifacts(run) { + for _, a := range currentNodeArtifacts(run) { if a.Name == "repository-patch" || excluded[a.NodeID] || syntheticResults[a.NodeID] && a.Name == "result" && a.Path == "result.md" { continue } diff --git a/internal/httpapi/runner_outputs_test.go b/internal/httpapi/runner_outputs_test.go index 44483863d..b35c1ff25 100644 --- a/internal/httpapi/runner_outputs_test.go +++ b/internal/httpapi/runner_outputs_test.go @@ -19,6 +19,9 @@ func TestValidateRunnerTaskOutputsRejectsEscapingPaths(t *testing.T) { if msg := validateRunnerTaskOutputs(&domain.RunnerTaskOutputs{Files: map[string]string{bad: "x"}}); msg == "" { t.Fatalf("file path %q accepted", bad) } + if msg := validateRunnerTaskOutputs(&domain.RunnerTaskOutputs{FreshOutputFiles: []string{bad}}); msg == "" { + t.Fatalf("fresh output path %q accepted", bad) + } } if msg := validateRunnerTaskOutputs(&domain.RunnerTaskOutputs{Patches: map[string]string{"../svc": "x"}}); msg == "" { t.Fatal("patch dir escaping the workspace accepted") diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.go index c24205ba2..1ade14e28 100644 --- a/internal/httpapi/runners.go +++ b/internal/httpapi/runners.go @@ -1471,9 +1471,11 @@ func validateRunnerTaskOutputs(outputs *domain.RunnerTaskOutputs) string { return "无效的产物错误报告" } } - for _, path := range outputs.TooLarge { - if !domain.SafeWorkspaceRelPath(path) { - return fmt.Sprintf("产物路径 %q 不合法", path) + for _, paths := range [][]string{outputs.TooLarge, outputs.FreshOutputFiles} { + for _, path := range paths { + if !domain.SafeWorkspaceRelPath(path) { + return fmt.Sprintf("产物路径 %q 不合法", path) + } } } for dir, patch := range outputs.Patches { diff --git a/internal/repo/run_lease_test.go b/internal/repo/run_lease_test.go index 075a97a1e..c085beb0a 100644 --- a/internal/repo/run_lease_test.go +++ b/internal/repo/run_lease_test.go @@ -52,6 +52,36 @@ func TestRunLeaseMutualExclusionAndExpiryTakeover(t *testing.T) { } } +func TestParkRunForApprovalRejectsSnapshotBeforeRework(t *testing.T) { + s, err := OpenTest() + if err != nil { + t.Fatal(err) + } + defer s.Close() + run := putLeaseTestRun(t, s, "run-park-rework") + if err := s.TryAcquireRunLease(run.ID, "instance-a", run.Generation, time.Minute); err != nil { + t.Fatal(err) + } + waiting, _ := s.RunState(run.ID) + waiting.Nodes["node"].Status = "waiting_approval" + if err := s.PutRun(waiting); err != nil { + t.Fatal(err) + } + beforeRework, _ := s.RunState(run.ID) + reset, _ := s.RunState(run.ID) + reset.Nodes["node"].Status = "pending" + if err := s.PutRun(reset); err != nil { + t.Fatal(err) + } + if parked, err := s.ParkRunForApproval(beforeRework); err != nil || parked { + t.Fatalf("parking the pre-rework snapshot = %v, %v", parked, err) + } + current, _ := s.RunState(run.ID) + if current.Status != "running" || current.Nodes["node"].Status != "pending" { + t.Fatalf("rework was overwritten: run=%s node=%s", current.Status, current.Nodes["node"].Status) + } +} + func TestPutRunAllowsTerminalStatusAfterLeaseExpiry(t *testing.T) { s, err := OpenTest() if err != nil { diff --git a/internal/repo/runs.go b/internal/repo/runs.go index 72a29ab0a..c1910b51d 100644 --- a/internal/repo/runs.go +++ b/internal/repo/runs.go @@ -1468,6 +1468,21 @@ func (r *RunsRepo) ReleaseRunLease(runID, instanceID string, generation int) err return nil } +// ParkRunForApproval applies a scheduler's waiting decision only to the +// snapshot that still owns the lease and has not changed since the check. +func (r *RunsRepo) ParkRunForApproval(run domain.Run) (bool, error) { + now := time.Now().UTC() + res := r.DB.Model(&runRow{}). + Where("id = ? AND status = ? AND revision = ? AND execution_generation = ? AND owner_instance_id = ? AND lease_until > ?", + run.ID, "running", run.Revision, run.Generation, run.OwnerInstanceID, now). + Updates(map[string]any{ + "status": "waiting", + "revision": gorm.Expr("revision + 1"), + "updated_at": now, + }) + return res.RowsAffected == 1, res.Error +} + func (r *RunsRepo) BindRunWorkspace(runID, instanceID string, generation int, host, root string) (bool, error) { var bound bool err := r.DB.Transaction(func(tx *gorm.DB) error { diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index d5b5f585b..3196e6f3f 100644 --- a/internal/runner/daemon.go +++ b/internal/runner/daemon.go @@ -866,13 +866,20 @@ func (d *Daemon) executeTerminal(ctx context.Context, task domain.RunnerTask) ex } defer cleanup() } + var baseline runtime.ArtifactOutputBaseline + if task.Invocation != nil { + baseline, err = runtime.SnapshotArtifactOutputs(workspace, task.Invocation.FreshOutputFiles) + if err != nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("check prior outputs: %v", err)} + } + } var result execResult if sandbox != nil { result = d.executeSandboxProcess(ctx, task, sandbox, command) } else { result = d.executeProcess(ctx, task, command.Argv, runtime.CommandEnvironment(command)) } - result.outputs = collectTaskOutputs(workspace, task.Invocation) + result.outputs = collectTaskOutputs(workspace, task.Invocation, baseline) return result } @@ -932,6 +939,10 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask) return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil } } + baseline, err := runtime.SnapshotArtifactOutputs(workspace, inv.FreshOutputFiles) + if err != nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("check prior outputs: %v", err)}, nil + } finish := func(result execResult) (execResult, map[string]string) { // The engine can accept a gate and its artifacts after a provider stream // drops its final event. Publish the index in that case too. @@ -951,7 +962,7 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask) return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error(), exitCode: 1}, nil } } - result.outputs = collectTaskOutputs(workspace, inv) + result.outputs = collectTaskOutputs(workspace, inv, baseline) if result.status != domain.RunnerTaskSuccess { return result, nil } @@ -1563,7 +1574,7 @@ func (d *Daemon) defaultWorkspace(taskID string) string { } // runnerVersion is reported at registration; it matches the module build. -var runnerVersion = domain.RunnerVersionProjectSharedGitCredentials +var runnerVersion = domain.RunnerVersionReworkArtifacts // Version returns the runner build version reported at registration. func Version() string { return runnerVersion } diff --git a/internal/runner/outputs.go b/internal/runner/outputs.go index db62b36cb..2f7ab02c7 100644 --- a/internal/runner/outputs.go +++ b/internal/runner/outputs.go @@ -28,6 +28,9 @@ func prepareInvocationWorkspace(workspace string, inv *domain.RunnerInvocation, // input file; chmod/write/chmod must not interleave. unlock := lockInvocationWorkspace(workspace) defer unlock() + if err := runtime.RemoveArtifactInputs(workspace, inv.StaleInputs); err != nil { + return err + } if _, err := runtime.RestoreMissingWorkspaceArtifacts(workspace, inv.ArchivedFiles); err != nil { return fmt.Errorf("restore archived outputs: %w", err) } @@ -95,7 +98,7 @@ func lockInvocationWorkspace(workspace string) func() { // collectTaskOutputs reports the requested output files, the // repository-patch inventory of every checkout, and workspace facts. It runs // after success and failure alike so a failed node keeps its diagnostics. -func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation) *domain.RunnerTaskOutputs { +func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation, baselines ...runtime.ArtifactOutputBaseline) *domain.RunnerTaskOutputs { if inv == nil || !inv.ReportOutputs { return nil } @@ -116,25 +119,60 @@ func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation) *domain. } } out.Files, out.TooLarge = readOutputFiles(workspace, paths) + if len(baselines) != 0 && len(baselines[0]) != 0 { + markFreshTaskOutputs(workspace, out, baselines[0]) + } out.Patches = collectPatchInventories(workspace, patchInventoryDirs(inv)) frontend, evidence := domain.DetectFrontendProject(workspace) out.Facts = &domain.RunnerWorkspaceFacts{Frontend: frontend, FrontendEvidence: evidence} return out } +func markFreshTaskOutputs(workspace string, out *domain.RunnerTaskOutputs, baseline runtime.ArtifactOutputBaseline) { + out.FileErrors = map[string]string{} + root, err := os.OpenRoot(workspace) + if err == nil { + defer root.Close() + } + for rel := range baseline { + var info os.FileInfo + statErr := err + if statErr == nil { + info, statErr = root.Lstat(rel) + } + switch { + case errors.Is(statErr, fs.ErrNotExist): + delete(out.Files, rel) + continue + case statErr != nil: + out.FileErrors[rel] = statErr.Error() + case !info.Mode().IsRegular(): + out.FileErrors[rel] = "output is not a regular file" + case baseline.Unchanged(rel, info): + out.FileErrors[rel] = runtime.ErrStaleArtifactOutput.Error() + default: + out.FreshOutputFiles = append(out.FreshOutputFiles, rel) + continue + } + delete(out.Files, rel) + } +} + func (d *Daemon) uploadTaskOutputs(ctx context.Context, task domain.RunnerTask, out *domain.RunnerTaskOutputs) { inv := task.Invocation if inv == nil || !inv.ArtifactTransfer || out == nil { return } out.FileBlobs = make(map[string]domain.ArtifactBlob) - out.FileErrors = make(map[string]string) + if out.FileErrors == nil { + out.FileErrors = make(map[string]string) + } root, rootErr := os.OpenRoot(d.taskWorkspace(task)) if rootErr == nil { defer root.Close() } for _, rel := range inv.OutputFiles { - if rel == inv.GateResultPath || !domain.SafeWorkspaceRelPath(rel) { + if rel == inv.GateResultPath || !domain.SafeWorkspaceRelPath(rel) || out.FileErrors[rel] != "" { continue } err := rootErr diff --git a/internal/runner/outputs_test.go b/internal/runner/outputs_test.go index 52700f30d..f59404808 100644 --- a/internal/runner/outputs_test.go +++ b/internal/runner/outputs_test.go @@ -7,6 +7,7 @@ import ( "testing" "agentflow/internal/domain" + "agentflow/internal/runtime" ) func TestPrepareInvocationWorkspaceWritesInputsAndClearsGateResult(t *testing.T) { @@ -90,3 +91,34 @@ func TestCollectTaskOutputsReportsOnlyRegularFilesInsideWorkspace(t *testing.T) t.Fatal("outputs reported without ReportOutputs") } } + +func TestRunnerReplayOutputsReportOnlyFreshFiles(t *testing.T) { + t.Parallel() + workspace := t.TempDir() + for _, path := range []string{"old.md", "rewritten.md"} { + if err := os.WriteFile(filepath.Join(workspace, path), []byte("report"), 0600); err != nil { + t.Fatal(err) + } + } + inv := &domain.RunnerInvocation{ + ReportOutputs: true, OutputFiles: []string{"old.md", "rewritten.md"}, + FreshOutputFiles: []string{"old.md", "rewritten.md"}, + } + baseline, err := runtime.SnapshotArtifactOutputs(workspace, inv.FreshOutputFiles) + if err != nil { + t.Fatal(err) + } + replacement := filepath.Join(workspace, "new-report.md") + if err := os.WriteFile(replacement, []byte("report"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Rename(replacement, filepath.Join(workspace, "rewritten.md")); err != nil { + t.Fatal(err) + } + out := collectTaskOutputs(workspace, inv, baseline) + if out.FileErrors["old.md"] == "" || out.Files["old.md"] != "" || + out.Files["rewritten.md"] != "report" || len(out.FreshOutputFiles) != 1 || + out.FreshOutputFiles[0] != "rewritten.md" { + t.Fatalf("incorrect replay report: %+v", out) + } +} diff --git a/internal/runner/reported_outputs_test.go b/internal/runner/reported_outputs_test.go index 4538a0936..8d3098025 100644 --- a/internal/runner/reported_outputs_test.go +++ b/internal/runner/reported_outputs_test.go @@ -137,3 +137,63 @@ func TestRunnerReportedOutputsKeepFailedNodeArtifacts(t *testing.T) { t.Fatalf("failed node lost its artifact: %+v, %v", diagnosis, ok) } } + +func TestRunnerReworkRetiresOptionalArtifactHandoff(t *testing.T) { + server, store, e := newDaemonTestServer(t) + startReportingRunner(t, store, server.URL) + wf := domain.WorkflowDefinition{ + ID: "runner-rework-artifact", Name: "Runner rework artifact", SandboxProfileID: "test-native", + Nodes: []domain.WorkflowNode{ + {ID: "review", Name: "评审", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, + Script: "if [ ! -f review.md ]; then printf report > review.md; fi", + ArtifactOutputs: []domain.ArtifactContract{{Name: "review", Path: "review.md"}}}, + {ID: "check", Name: "测试", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, + Script: `set -eu +input=.agentflow/inputs/review/review.md +if [ -f checked ]; then + test ! -e "$input" +else + test "$(cat "$input")" = report + touch checked +fi`}, + {ID: "approve", Name: "确认", Type: "approval", RejectTo: "review", MaxReworks: 1}, + }, + Edges: []domain.WorkflowEdge{ + {ID: "review-check", Source: "review", Target: "check", When: "success"}, + {ID: "check-approve", Source: "check", Target: "approve", When: "success"}, + }, + } + if err := store.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + run, err := e.StartWithExecutionContext(wf.ID, "", domain.RepositoryContext{}, domain.TelemetryContext{ResponsibleUserID: 42}) + if err != nil { + t.Fatal(err) + } + waitFor(t, 15*time.Second, "first approval", func() bool { + current, ok := store.Run(run.ID) + return ok && current.Status == "waiting" + }) + if err := e.Reject(run.ID, domain.RejectRequest{NodeID: "approve", TargetID: "review", Reason: "redo review"}); err != nil { + t.Fatal(err) + } + waitFor(t, 15*time.Second, "second approval", func() bool { + current, ok := store.Run(run.ID) + return ok && current.Nodes["check"].Attempt == 2 && (current.Status == "waiting" || current.Status == "failed") + }) + final, _ := store.RunView(run.ID) + if final.Status != "waiting" || final.Nodes["check"].Status != "succeeded" { + t.Fatalf("second check failed to run without the retired input: %+v", final.Nodes["check"]) + } + review, ok := latestArtifact(final, "review", "review") + if !ok || review.Attempt != 1 || final.Nodes["review"].Attempt != 2 || !review.Stale { + t.Fatalf("optional artifact history = %+v (found %v)", review, ok) + } + if err := e.Approve(run.ID, "approve", ""); err != nil { + t.Fatal(err) + } + waitFor(t, 15*time.Second, "run completion", func() bool { + current, ok := store.Run(run.ID) + return ok && current.Status == "succeeded" + }) +} diff --git a/internal/runtime/workspace_artifacts.go b/internal/runtime/workspace_artifacts.go index f8224c3c7..c0f09ec0a 100644 --- a/internal/runtime/workspace_artifacts.go +++ b/internal/runtime/workspace_artifacts.go @@ -4,6 +4,7 @@ import ( "agentflow/internal/domain" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" "os" @@ -75,6 +76,75 @@ func RestoreMissingWorkspaceArtifact(root, path, digest string, source func() (i }) } +var ErrStaleArtifactOutput = errors.New("产物仍是上一次执行留下的文件,请为本次执行重新生成") + +// ArtifactOutputBaseline records the files that a rerun might inherit from +// an earlier attempt. Rewriting a file with the same bytes is valid. +type ArtifactOutputBaseline map[string]os.FileInfo + +func SnapshotArtifactOutputs(workspace string, paths []string) (ArtifactOutputBaseline, error) { + if len(paths) == 0 { + return nil, nil + } + root, err := os.OpenRoot(workspace) + if err != nil { + return nil, err + } + defer root.Close() + baseline := make(ArtifactOutputBaseline, len(paths)) + for _, rel := range paths { + if !domain.SafeWorkspaceRelPath(rel) { + return nil, fmt.Errorf("unsafe output path %q", rel) + } + info, err := root.Stat(rel) + if err != nil && !os.IsNotExist(err) { + return nil, err + } + baseline[rel] = info + } + return baseline, nil +} + +func (b ArtifactOutputBaseline) Unchanged(rel string, info os.FileInfo) bool { + before := b[rel] + return before != nil && os.SameFile(before, info) && before.Size() == info.Size() && before.ModTime().Equal(info.ModTime()) +} + +// RemoveArtifactInputs retires handoff files in the runtime-owned input directory. +func RemoveArtifactInputs(workspace string, paths []string) error { + if len(paths) == 0 { + return nil + } + base, err := os.OpenRoot(workspace) + if err != nil { + return err + } + defer base.Close() + for _, rel := range paths { + if !domain.SafeWorkspaceRelPath(rel) || !strings.HasPrefix(rel, ".agentflow/inputs/") { + return fmt.Errorf("unsafe input path %q", rel) + } + info, err := base.Lstat(rel) + if os.IsNotExist(err) { + continue + } + if err != nil { + return err + } + if !info.Mode().IsRegular() { + return fmt.Errorf("artifact input path is not a regular file: %s", rel) + } + segments := strings.Split(filepath.ToSlash(filepath.Dir(rel)), "/") + if _, err := EnsureControlDirectory(workspace, segments[1:]...); err != nil { + return err + } + if err := base.Remove(rel); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove stale input %s: %w", rel, err) + } + } + return nil +} + // WriteArtifactInput atomically materializes a read-only handoff file under // the runtime control directory. func WriteArtifactInput(workspace, rel, digest string, source io.Reader) error { diff --git a/web/app/runs.js b/web/app/runs.js index 9fa064092..ff65dc693 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -221,7 +221,6 @@ async function refreshRuns(background=false,runsView=false){ } function runProgress(r){const nodes=Object.values(r.nodes||{}).filter(Boolean),done=nodes.filter(n=>['succeeded','skipped','failed','cancelled'].includes(n.status)).length,total=Math.max(nodes.length,done);return {done:Math.min(done,total),total,pct:total?Math.round(Math.min(done,total)*100/total):0}} function workflowStages(workflow){const nodes=workflow?.nodes||[],edges=workflow?.edges||[],byId=new Map(nodes.map(n=>[n.id,n])),indegree=new Map(nodes.map(n=>[n.id,0]));for(const edge of edges)if(indegree.has(edge.target)&&byId.has(edge.source))indegree.set(edge.target,indegree.get(edge.target)+1);let ready=nodes.filter(n=>indegree.get(n.id)===0).map(n=>n.id),seen=new Set(),stages=[];while(ready.length){const ids=ready,stage=ids.map(id=>byId.get(id)).filter(Boolean);stages.push(stage);ready=[];for(const id of ids){seen.add(id);for(const edge of edges.filter(e=>e.source===id)){if(!indegree.has(edge.target))continue;indegree.set(edge.target,indegree.get(edge.target)-1);if(indegree.get(edge.target)===0)ready.push(edge.target)}}}const remaining=nodes.filter(n=>!seen.has(n.id));if(remaining.length)stages.push(remaining);return stages} -function stageHasConditionalEdges(stage,wf){const ids=new Set((stage||[]).map(n=>n.id));return (wf?.edges||[]).some(e=>ids.has(e.target)&&e.condition)||(wf?.edges||[]).some(e=>e.condition&&ids.has(e.target));} function routeEdgeKeyUI(edge,index,decision){return decision?.edgeKeyVersion?(edge.id?`id:${edge.id}`:`index:${index}`):String(index)} function edgeConditionLabel(edge){const c=edge?.condition;if(!c)return '';if(c.type==='route')return (c.values||[]).join(' / ')||'条件';if(c.type==='artifact')return `${c.artifact||'产物'}${c.pointer||''} = ${typeof c.equals==='string'?c.equals:JSON.stringify(c.equals)}`;return '条件'} function edgeRunLabel(edge,index,r,wf){const source=r?.nodes?.[edge.source],decision=source?.routeDecision;if(source?.status==='skipped')return '已跳过';if(!decision)return '待选路';const selected=!!decision.selectedEdges?.[routeEdgeKeyUI(edge,index,decision)];return selected?(source?.defaultTarget===edge.target?'已选中(默认)':'已选中'):(r?.nodes?.[edge.target]?.status==='skipped'?'已跳过':'未选中')} @@ -1436,6 +1435,8 @@ function patchRunLive(r){ const usageHost=host.querySelector('[data-run-usage]'); if(usageHost){const html=liveUsageHTML(r);if(usageHost.innerHTML!==html)usageHost.innerHTML=html} if(inspectorNeedsRefresh(host,r)){renderRunDetail(r);return} + const displayedWorkflow=runDetailWorkflow(r); + host.querySelectorAll('[data-run-edge-index]').forEach(path=>updateRunGraphEdge(path,r,displayedWorkflow)); const sandboxChip=host.querySelector('[data-run-sandbox]'); if(sandboxChip){ const sandbox=runSandboxDetails(r), label=sandboxChip.querySelector('code'); @@ -1449,7 +1450,13 @@ function patchRunLive(r){ const n=r.nodes?.[btn.dataset.runNode]||{},small=btn.querySelector('small'); const gv=graphNodeView(r,btn.dataset.runNode); btn.className=`graph-node ${gv.cls} ${state.selectedRunNode===btn.dataset.runNode?'selected':''}`; - if(small){const extra=(small.textContent.split(' · 上游')[1]);small.textContent=`${gv.text}${extra?` · 上游 ${extra}`:''}`} + if(small){ + const suffix=small.dataset.dependencyText||''; + small.textContent=gv.text+suffix; + btn.title=btn.querySelector('b').textContent+' · '+small.textContent; + } + const time=btn.querySelector('.graph-node-time'); + if(time){time.textContent=graphNodeTimeLabel(n);time.hidden=!time.textContent} const count=(r.artifacts||[]).filter(a=>a.nodeId===btn.dataset.runNode).length; let em=btn.querySelector('em'); if(count){if(!em){em=document.createElement('em');btn.appendChild(em)}em.textContent=`${count} 产物`}else if(em)em.remove(); @@ -2374,27 +2381,118 @@ function graphNodeView(r,nodeId){ } return view; } -// Stage window: when this stage's nodes started and finished, shown next to the stage label. -// Go zero time (0001-01-01T00:00:00Z) means "not set"; older payloads still carry it. +// Go zero time marks a node that has not started or finished. function runTimeMs(value){ if(!value)return null; const ms=new Date(value).getTime(); return Number.isFinite(ms)&&new Date(ms).getUTCFullYear()>1?ms:null; } -function stageTimeRange(r,stage){ - const entries=(stage||[]).map(node=>r?.nodes?.[node.id]).filter(item=>item&&runTimeMs(item.startedAt)!==null); - const starts=entries.map(item=>runTimeMs(item.startedAt)); - if(!starts.length)return null; - const running=entries.some(item=>runTimeMs(item.finishedAt)===null); - const ends=running?[]:entries.map(item=>runTimeMs(item.finishedAt)); - return {start:Math.min(...starts),end:ends.length?Math.max(...ends):null,running:running||!ends.length}; -} -function stageTimeLabel(r,stage){ - const range=stageTimeRange(r,stage); - if(!range)return ''; - const start=new Date(range.start).toLocaleTimeString(); - const end=range.running||range.end===null?'现在':new Date(range.end).toLocaleTimeString(); - return `${start} → ${end}`; + +function graphNodeTimeLabel(node){ + const start=runTimeMs(node?.startedAt); + if(start===null)return ''; + const end=runTimeMs(node.finishedAt); + return new Date(start).toLocaleTimeString()+' → '+(end===null?lfT('现在','Now'):new Date(end).toLocaleTimeString()); +} + +function runGraphPositions(workflow, parents){ + const columns=workflowStages(workflow), positions=new Map(); + for(const [column, nodes] of columns.entries()){ + const lanes=nodes.map((node,index)=>{ + const upstream=parents.get(node.id).map(edge=>positions.get(edge.source)).filter(Boolean); + const center=upstream.length?upstream.reduce((sum,pos)=>sum+pos.lane,0)/upstream.length:index-(nodes.length-1)/2; + return {node,center}; + }).sort((left,right)=>left.center-right.center); + // Pack each column around its preferred lanes. Single-parent chains stay + // aligned, and split/merge nodes remain centered on their connected lanes. + let previous=-Infinity,offset=0; + for(const lane of lanes){ + previous=Math.max(lane.center,previous+1); + lane.row=previous; + offset+=lane.row-lane.center; + } + for(const lane of lanes){ + positions.set(lane.node.id,{column,lane:lane.row-offset/lanes.length}); + } + } + return {columns:columns.length,positions}; +} + +function updateRunGraphEdge(path, r, workflow){ + const edge=(workflow.edges||[])[Number(path.dataset.runEdgeIndex)]; + if(!edge)return; + const source=r.nodes?.[edge.source]; + const conditional=edge.condition||workflow.nodes.find(node=>node.id===edge.source)?.defaultTarget===edge.target; + const skipped=source?.status==='skipped'||(conditional&&source?.routeDecision&&!source.routeDecision.selectedEdges?.[routeEdgeKeyUI(edge,Number(path.dataset.runEdgeIndex),source.routeDecision)]); + path.classList.toggle('is-skipped',!!skipped); +} + +function runDetailWorkflow(r){ + return r.workflowSnapshot?.id?r.workflowSnapshot:((state.data.workflows||[]).find(w=>w.id===r.workflowId)||state.workflow||{id:r.workflowId||'',name:r.workflowId||'流程',nodes:[],edges:[],version:1}); +} + +function renderRunTopology(graph,r,workflow,nodes){ + const buttons=new Map([...graph.querySelectorAll('[data-run-node]')].map(btn=>[btn.dataset.runNode,btn])); + if(!buttons.size)return; + const byId=new Map(nodes.map(node=>[node.id,node])); + const parents=new Map(nodes.map(node=>[node.id,[]])); + const edges=(workflow.edges||[]).map((edge,index)=>({...edge,index})).filter(edge=>byId.has(edge.source)&&byId.has(edge.target)); + for(const edge of edges)parents.get(edge.target).push(edge); + const {columns,positions}=runGraphPositions({nodes,edges},parents); + const width=192,height=76,columnGap=46,rowGap=16,pad=6; + const lanes=[...positions.values()].map(pos=>pos.lane); + const top=Math.min(...lanes),bottom=Math.max(...lanes); + const graphWidth=2*pad+columns*width+(columns-1)*columnGap; + const graphHeight=2*pad+height+(bottom-top)*(height+rowGap); + const surface=document.createElement('div'); + surface.className='run-graph-layout'; + surface.style.width=graphWidth+'px'; + surface.style.height=graphHeight+'px'; + const svgNS='http://www.w3.org/2000/svg'; + const wires=document.createElementNS(svgNS,'svg'); + wires.classList.add('run-graph-dependencies'); + wires.setAttribute('viewBox','0 0 '+graphWidth+' '+graphHeight); + wires.setAttribute('aria-hidden','true'); + surface.append(wires); + for(const [id,pos] of positions){ + const btn=buttons.get(id); + if(!btn)continue; + pos.left=pad+pos.column*(width+columnGap); + pos.top=pad+(pos.lane-top)*(height+rowGap); + Object.assign(btn.style,{left:pos.left+'px',top:pos.top+'px',width:width+'px',height:height+'px'}); + const incoming=parents.get(id); + const upstream=incoming.map(edge=>byId.get(edge.source).name).filter(Boolean); + const details=incoming.filter(edge=>edge.condition||byId.get(edge.source).defaultTarget===id).map(edge=>{ + const condition=edgeConditionLabel(edge)||(byId.get(edge.source).defaultTarget===id?lfT('默认分支','Default route'):lfT('条件','Condition')); + return condition+' · '+edgeRunLabel(edge,edge.index,r,workflow); + }); + const small=btn.querySelector('small'); + small.dataset.dependencyText=(upstream.length?' · '+lfT('上游','Upstream')+' '+upstream.join('、'):'')+ + (details.length?' · '+details.join(';'):''); + small.append(small.dataset.dependencyText); + btn.title=[byId.get(id).name,small.textContent].join(' · '); + const time=document.createElement('span'); + time.className='graph-node-time'; + time.textContent=graphNodeTimeLabel(r.nodes?.[id]); + time.hidden=!time.textContent; + small.after(time); + surface.append(btn); + } + for(const edge of edges){ + const source=positions.get(edge.source),target=positions.get(edge.target); + const x=source.left+width,y=source.top+height/2,endX=target.left,endY=target.top+height/2; + const bend=(x+endX)/2; + const path=document.createElementNS(svgNS,'path'); + path.classList.add('run-graph-edge'); + path.dataset.runEdgeIndex=edge.index; + path.dataset.runEdgeSource=edge.source; + path.dataset.runEdgeTarget=edge.target; + path.setAttribute('d','M '+x+' '+y+' C '+bend+' '+y+' '+bend+' '+endY+' '+endX+' '+endY+ + ' M '+(endX-5)+' '+(endY-4)+' L '+endX+' '+endY+' L '+(endX-5)+' '+(endY+4)); + updateRunGraphEdge(path,r,workflow); + wires.append(path); + } + graph.replaceChildren(surface); } function runNodeIcon(kind){ const types=typeof FLOW_NODE_TYPES==='object'&&FLOW_NODE_TYPES?FLOW_NODE_TYPES:{}; @@ -2613,7 +2711,7 @@ function renderRunDetail(r){ const existingPreviewFrame=host.querySelector('iframe[data-preview-frame]'); const previewFrameUrl=state.runPreview?.session?.url?(window.location.protocol==='https:'?previewCandidateHttpsURL(state.runPreview.session.url):state.runPreview.session.url):''; const keepPreview=!!(existingPreviewFrame&&host.dataset.runId===r.id&&existingPreviewFrame.getAttribute('data-run-id')===r.id&&previewFrameUrl&&(existingPreviewFrame.getAttribute('data-session-url')||existingPreviewFrame.getAttribute('src'))===previewFrameUrl); - const wf=r.workflowSnapshot?.id?r.workflowSnapshot:((state.data.workflows||[]).find(w=>w.id===r.workflowId)||state.workflow||{id:r.workflowId||'',name:r.workflowId||'流程',nodes:[],edges:[],version:1}),nodes=wf.nodes||[],graphNodes=runIsGroupMode(r)?runFrozenSopNodes(r,wf):nodes,progress=runProgress(r),ctx=runContext(r),usage=r.usage||{}; + const wf=runDetailWorkflow(r),nodes=wf.nodes||[],graphNodes=runIsGroupMode(r)?runFrozenSopNodes(r,wf):nodes,progress=runProgress(r),ctx=runContext(r),usage=r.usage||{}; const issueId=ctx.issue?.id||r.executionContext?.issueId||''; const pickNodes=runIsGroupMode(r)?(graphNodes.length?graphNodes:nodes):nodes;if(!state.selectedRunNode||!pickNodes.some(n=>n.id===state.selectedRunNode)){state.selectedRunNode=pickNodes.find(n=>['running','waiting_approval','failed','cancelled'].includes(r.nodes?.[n.id]?.status))?.id||pickNodes.find(n=>r.nodes?.[n.id]?.status==='succeeded')?.id||pickNodes[0]?.id}const pg=runPageTarget(r,state.selectedRunNode);const selected=pickNodes.find(n=>n.id===state.selectedRunNode)||nodes.find(n=>n.id===state.selectedRunNode),nr=r.nodes?.[selected?.id]||{},nodeArtifacts=(r.artifacts||[]).filter(a=>a.nodeId===selected?.id),logPage=state.runLogs?.runId===pg.runId&&state.runLogs.nodeId===pg.nodeId&&state.runLogs.loaded?state.runLogs:null,telAdapter=state.runTelemetryAdapter||'live',telPage=state.runTelemetry?.runId===pg.runId&&state.runTelemetry.nodeId===pg.nodeId&&state.runTelemetry.adapter===telAdapter&&state.runTelemetry.loaded?state.runTelemetry:null,telemetry=compactTelemetry(telPage?.items||[]); /** 首次渲染与实时更新使用同一节点活动判断。 */ @@ -2649,7 +2747,7 @@ function renderRunDetail(r){ if(child!==workspacePane)child.remove(); } workspacePane.hidden=runDetailTab!=='workspace'; - workspacePane.insertAdjacentHTML('beforebegin',`
${issueRef}›${escapeHTML(wf.name)}
${r.executionContext?.parentRunId?``:''}
${issueId?``:''}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}${['queued','running','waiting'].includes(r.status)&&runFailurePhase(r)!=='settling'?'':''}${runRecordDeletable(r)?'
更多操作
':''}

${escapeHTML(runTitle)}

${runHeaderDescription(runDescription,ctx.issue?.title,descriptionExpanded)}
${workspaceRestoreButtonHTML()}${runDisplayStatus(r)}${r.status==='failed'&&!runRecoveryKind(r.nodes?.[failedNodeId(r)])&&!gongfengIssueClosed(ctx.issue)?'':''}
Run ${escapeHTML(r.id.slice(-12))}${runModeChipHTML(r,wf)}${runExecutionChipHTML(r)}${clarificationEvidenceHTML(r,'run')}启动于 ${new Date(r.createdAt).toLocaleString()}执行 ${runElapsed(r)}${runWallNote(r)}
执行详情
${runProgressCellHTML(r,wf,progress,graphNodes)}
${liveUsageHTML(r)}
交付物${(r.artifacts||[]).length} 个不可变快照按节点和尝试次数保留版本
${alignPanelHTML}${runIsGroupMode(r)?`
已冷冻 LOOP 快照历史协作 · ${graphNodes.length} 个节点可展开审计
`:''}

节点执行拓扑

点击节点查看该节点的输出、产物和执行事件
完成运行中待确认未开始
${graphNodes.map((n,index)=>{const gv=graphNodeView(r,n.id),meta=nodeMeta(n),arts=(r.artifacts||[]).filter(a=>a.nodeId===n.id).length;return `${index?'→':''}`}).join('')}

${escapeHTML(selected?.name||'节点详情')}

当前活动:${escapeHTML(nr.activity||'')}${escapeHTML(nr.provider||'未分配')}${nr.model?` · ${escapeHTML(nr.model)}`:''}
${runStepStatusText(nr)}
执行次数${nr.attempt||0}
返工${nr.reworkCount||0}
Token${formatTokens(nr.usage?.totalTokens)}
工具调用${nr.toolCalls||0}
${childSOPPanelHTML(r,selected?.id)}${gateResultCardHTML(nr,selected?.type,wf,selected)}${runNodeFailureHTML(nr)}${runApprovalAuditHTML(r,selected?.id)}${nodeKBHTML}${canRerunFromHere(r,selected?.id)?`
保留上游结果,从本节点及下游重跑
`:''}${nr.output?`
节点输出
${nodeOutputHTML}
`:'
节点输出

节点完成后,结构化输出会显示在这里。

'}
Sandbox ${escapeHTML(nr.sandboxId||'—')}Session ${escapeHTML(nr.sessionId||'—')}

节点交付物

${nodeArtifacts.length} 个版本
${nodeArtifactsHTML(nodeArtifacts,nr)}
${runIsGroupMode(r)?'
':''}

${telemetrySectionTitle(telAdapter)}

${telPage?`${telemetry.length} 条已加载`:'加载最近 100 条'}
${telemetrySourceTabs(telAdapter,'data-tel-adapter')}${runDetailLevelButton(state.runTelemetryDetails,'data-tel-detail')}${telPage?.hasMore?``:''}

${lfT('这里显示执行环境与 CLI 已上报的事件。工具、消息与 Hook 的上报范围因 CLI 而异。','This trace shows events reported by the execution environment and CLI. Tool, message, and Hook coverage varies by CLI.')}

${telPage?telemetryFeedHTML(telemetry,telAdapter):'

正在加载轨迹…

'}

执行日志

${logPage?`${visibleWorkerLogs(logPage.items).length} 条调用`:(logBusy?'正在接收…':'实时加载最近调用')}
${runDetailLevelButton(state.runLogDetails,'data-log-detail')}${logPage?.hasMore?``:''}
${logPage?runWorkerLogsHTML(logPage.items):'

正在加载执行日志…

'}
`); + workspacePane.insertAdjacentHTML('beforebegin',`
${issueRef}›${escapeHTML(wf.name)}
${r.executionContext?.parentRunId?``:''}
${issueId?``:''}${!r.pauseRequested?refreshRunSOPButtonHTML(r):''}${['queued','running','waiting'].includes(r.status)&&runFailurePhase(r)!=='settling'?'':''}${runRecordDeletable(r)?'
更多操作
':''}

${escapeHTML(runTitle)}

${runHeaderDescription(runDescription,ctx.issue?.title,descriptionExpanded)}
${workspaceRestoreButtonHTML()}${runDisplayStatus(r)}${r.status==='failed'&&!runRecoveryKind(r.nodes?.[failedNodeId(r)])&&!gongfengIssueClosed(ctx.issue)?'':''}
Run ${escapeHTML(r.id.slice(-12))}${runModeChipHTML(r,wf)}${runExecutionChipHTML(r)}${clarificationEvidenceHTML(r,'run')}启动于 ${new Date(r.createdAt).toLocaleString()}执行 ${runElapsed(r)}${runWallNote(r)}
执行详情
${runProgressCellHTML(r,wf,progress,graphNodes)}
${liveUsageHTML(r)}
交付物${(r.artifacts||[]).length} 个不可变快照按节点和尝试次数保留版本
${alignPanelHTML}${runIsGroupMode(r)?`
已冷冻 LOOP 快照历史协作 · ${graphNodes.length} 个节点可展开审计
`:''}

节点执行拓扑

点击节点查看该节点的输出、产物和执行事件
完成运行中待确认未开始
${graphNodes.map(n=>{const gv=graphNodeView(r,n.id),meta=nodeMeta(n),arts=(r.artifacts||[]).filter(a=>a.nodeId===n.id).length;return ``}).join('')}

${escapeHTML(selected?.name||'节点详情')}

当前活动:${escapeHTML(nr.activity||'')}${escapeHTML(nr.provider||'未分配')}${nr.model?` · ${escapeHTML(nr.model)}`:''}
${runStepStatusText(nr)}
执行次数${nr.attempt||0}
返工${nr.reworkCount||0}
Token${formatTokens(nr.usage?.totalTokens)}
工具调用${nr.toolCalls||0}
${childSOPPanelHTML(r,selected?.id)}${gateResultCardHTML(nr,selected?.type,wf,selected)}${runNodeFailureHTML(nr)}${runApprovalAuditHTML(r,selected?.id)}${nodeKBHTML}${canRerunFromHere(r,selected?.id)?`
保留上游结果,从本节点及下游重跑
`:''}${nr.output?`
节点输出
${nodeOutputHTML}
`:'
节点输出

节点完成后,结构化输出会显示在这里。

'}
Sandbox ${escapeHTML(nr.sandboxId||'—')}Session ${escapeHTML(nr.sessionId||'—')}

节点交付物

${nodeArtifacts.length} 个版本
${nodeArtifactsHTML(nodeArtifacts,nr)}
${runIsGroupMode(r)?'
':''}

${telemetrySectionTitle(telAdapter)}

${telPage?`${telemetry.length} 条已加载`:'加载最近 100 条'}
${telemetrySourceTabs(telAdapter,'data-tel-adapter')}${runDetailLevelButton(state.runTelemetryDetails,'data-tel-detail')}${telPage?.hasMore?``:''}

${lfT('这里显示执行环境与 CLI 已上报的事件。工具、消息与 Hook 的上报范围因 CLI 而异。','This trace shows events reported by the execution environment and CLI. Tool, message, and Hook coverage varies by CLI.')}

${telPage?telemetryFeedHTML(telemetry,telAdapter):'

正在加载轨迹…

'}

执行日志

${logPage?`${visibleWorkerLogs(logPage.items).length} 条调用`:(logBusy?'正在接收…':'实时加载最近调用')}
${runDetailLevelButton(state.runLogDetails,'data-log-detail')}${logPage?.hasMore?``:''}
${logPage?runWorkerLogsHTML(logPage.items):'

正在加载执行日志…

'}
`); workspacePane.insertAdjacentHTML('afterend',`${previewEnabled?`
${previewPaneHTML(r)}
`:''}
${runEvalPaneHTML(r)}
`); if(keepPreview){const fresh=host.querySelector('iframe[data-preview-frame]');if(fresh)fresh.replaceWith(existingPreviewFrame);} const headerActions=host.querySelector('.run-header-actions');if(r.status==='running'&&runFailurePhase(r)!=='settling'&&headerActions)headerActions.querySelector('[data-cancel-run]')?.insertAdjacentHTML('beforebegin',''); @@ -2686,7 +2784,8 @@ function renderRunDetail(r){ const sandbox=runSandboxDetails(r); if(runMeta)runMeta.insertAdjacentHTML('beforeend',`${taskTriggerBadge(ctx.task)}Sandbox ${escapeHTML(sandbox.id)}`); const nodeSandbox=host.querySelector('.runtime-details span:first-child');if(nodeSandbox)nodeSandbox.remove(); - const graph=host.querySelector('.run-graph');if(graph){graph.querySelectorAll('.graph-arrow').forEach(arrow=>arrow.remove());const displayWf=runIsGroupMode(r)?{...wf,nodes:graphNodes}:wf,stages=workflowStages(displayWf);graph.classList.add('is-staged');stages.forEach((stage,index)=>{const conditional=stageHasConditionalEdges(stage,displayWf),column=document.createElement('div');column.className='graph-stage'+(stage.length>1&&!conditional?' is-parallel':'')+(conditional?' is-conditional':'');const caption=document.createElement('span');caption.className='graph-stage-label';const captionName=document.createElement('span');captionName.className='graph-stage-name';captionName.textContent=`阶段 ${index+1}${conditional?' · 条件分支':(stage.length>1?` · 并行 ${stage.length}`:'')}`;caption.append(captionName);const stageTime=stageTimeLabel(r,stage);if(stageTime){const stageTimeEl=document.createElement('em');stageTimeEl.className='graph-stage-time';stageTimeEl.textContent=stageTime;caption.append(stageTimeEl)}column.append(caption);for(const node of stage){const button=graph.querySelector(`[data-run-node="${CSS.escape(node.id)}"]`),parents=(displayWf.edges||[]).filter(edge=>edge.target===node.id).map(edge=>nodes.find(item=>item.id===edge.source)?.name).filter(Boolean);if(!button)continue;if(parents.length)button.querySelector('small').append(` · 上游 ${parents.join('、')}`);const incoming=(displayWf.edges||[]).map((edge,edgeIndex)=>({...edge,edgeIndex})).filter(edge=>edge.target===node.id&&(edge.condition||displayWf.nodes?.find(source=>source.id===edge.source)?.defaultTarget===edge.target));if(incoming.length){const details=incoming.map(edge=>{const source=displayWf.nodes?.find(item=>item.id===edge.source);const label=edgeConditionLabel(edge)||(source?.defaultTarget===edge.target?'默认分支':'条件');return `${label} · ${edgeRunLabel(edge,edge.edgeIndex,r,displayWf)}`}).join(';');button.title=details;button.querySelector('small').append(` · ${details}`)}column.append(button)}if(column.children.length>1)graph.append(column)})} + const graph=host.querySelector('.run-graph'); + if(graph)renderRunTopology(graph,r,wf,graphNodes); host.querySelector('[data-run-back]')?.addEventListener('click',()=>showRunList()); bindRunDetailTabs(r,host); bindRecoveryInspection(host); diff --git a/web/observability.css b/web/observability.css index 642bb773b..9e26b4175 100644 --- a/web/observability.css +++ b/web/observability.css @@ -74,11 +74,15 @@ .graph-legend i.succeeded{background:var(--green)} .graph-legend i.running{background:var(--blue)} .graph-legend i.waiting_approval{background:var(--amber)} -.run-graph{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));align-items:stretch;padding:6px 4px 8px;gap:24px 34px;overflow:visible} -.graph-arrow{display:none} +.run-graph{overflow-x:auto;overflow-y:hidden;padding:0 0 5px} +.run-graph-layout{position:relative} +.run-graph-dependencies{position:absolute;inset:0;width:100%;height:100%;pointer-events:none} +.run-graph-edge{fill:none;stroke:var(--muted-2);stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round} +.run-graph-edge.is-skipped{stroke-dasharray:4 3;opacity:.45} +.run-graph-layout>.graph-node{position:absolute} +.graph-node-time{display:block;margin-top:4px;color:var(--muted-2);font-size:9.5px;font-variant-numeric:tabular-nums;white-space:nowrap} +.graph-node-time[hidden]{display:none} .graph-node{position:relative;min-width:0;width:100%;box-sizing:border-box;display:grid;grid-template-columns:32px minmax(0,1fr);align-items:center;gap:9px;padding:12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--panel);color:var(--text);text-align:left;cursor:pointer;transition:all .14s ease} -.graph-node::after{content:"→";position:absolute;right:-27px;top:50%;transform:translateY(-50%);width:24px;text-align:center;color:var(--muted-2);font-size:15px;font-weight:700;pointer-events:none} -.graph-node:last-child::after{display:none} .graph-node:hover,.graph-node.selected{border-color:var(--blue);box-shadow:0 0 0 3px var(--blue-soft)} .graph-node.running{border-color:var(--blue)} .graph-node.succeeded{border-color:rgba(52,211,153,.5)} @@ -716,18 +720,6 @@ html[data-theme="dark"] #runsView .run-preview-site-select { .run-sop-snapshot>summary span{font-size:12px;color:var(--muted)} .run-sop-snapshot .run-graph-section{border-bottom:0} -/* Staged topology: one column per stage; parallel siblings share a column. */ -.run-graph.is-staged{display:flex;align-items:stretch;gap:0 40px;overflow-x:auto;padding:6px 4px 10px} -.graph-stage{position:relative;flex:0 0 220px;display:flex;flex-direction:column;gap:10px;padding:8px;border:1px dashed transparent;border-radius:12px;box-sizing:border-box} -.graph-stage.is-parallel{border-color:var(--line-strong);background:color-mix(in srgb,var(--blue) 3%,transparent)} -.graph-stage-label{display:flex;align-items:baseline;justify-content:space-between;gap:6px;font-size:10px;color:var(--muted-2);letter-spacing:.02em} -.graph-stage-name{white-space:nowrap} -.graph-stage-time{font-style:normal;font-size:9.5px;color:var(--muted-2);font-variant-numeric:tabular-nums;white-space:nowrap} -.graph-stage.is-parallel .graph-stage-label{color:var(--blue)} -.graph-stage>.graph-node:nth-child(2){margin-top:auto}.graph-stage>.graph-node:last-child{margin-bottom:auto} -.run-graph.is-staged .graph-node::after{display:none} -.graph-stage+.graph-stage::before{content:"→";position:absolute;left:-33px;top:calc(50% + 9px);transform:translateY(-50%);width:26px;text-align:center;color:var(--muted-2);font-size:15px;font-weight:700} - /* ================= 统计页(ECharts 改版):单一强调色、无渐变阴影、说明收进悬停 ================= */ :root{--c1:#5b8cff;--c2:#3d5fae;--c3:#2a3d66;--c4:#4b5568} [data-theme="light"]{--c1:#4f7cf0;--c2:#8fb0f7;--c3:#c8d7fb;--c4:#c4cad6} diff --git a/webtest/tests/runs-detail.test.mjs b/webtest/tests/runs-detail.test.mjs index f2c873dbf..994559277 100644 --- a/webtest/tests/runs-detail.test.mjs +++ b/webtest/tests/runs-detail.test.mjs @@ -418,42 +418,51 @@ test('a failed script override requires opening advanced recovery and confirming assert.deepEqual(call.body.expected,{status:'failed',attempt:3,reworkCount:1}); }); -test('run detail topology shows each stage time window beside its stage label', async (t) => { +test('run topology keeps independent branches on their own dependency paths', async (t) => { const app = await loadApp(); t.after(app.close); const workflow = app.evaluate('structuredClone(state.data.workflows[0])'); - const nodes = Object.fromEntries((workflow.nodes || []).map((node, i) => [node.id, { + workflow.nodes = ['design', 'api-dev', 'api-review', 'api-test', 'web-dev', 'web-review', 'web-test', 'integrate'] + .map(id => ({ id, name: id, type: 'agent' })); + const edges = [ + ['design', 'api-dev'], ['api-dev', 'api-review'], ['api-review', 'api-test'], + ['design', 'web-dev'], ['web-dev', 'web-review'], ['web-review', 'web-test'], + ['api-test', 'integrate'], ['web-test', 'integrate'], + ]; + workflow.edges = edges.map(([source, target]) => ({ source, target, when: 'success' })); + const nodes = Object.fromEntries(workflow.nodes.map((node, i) => [node.id, { status: 'succeeded', attempt: 1, - startedAt: `2026-10-21T10:0${i}:00Z`, finishedAt: `2026-10-21T10:0${i + 3}:00Z`, + startedAt: new Date(Date.UTC(2026, 9, 21, 10, i)).toISOString(), + finishedAt: new Date(Date.UTC(2026, 9, 21, 10, i + 5)).toISOString(), }])); const run = { ...app.evaluate('structuredClone(state.data.runs[0])'), status: 'succeeded', - finishedAt: '2026-10-21T10:09:00Z', workflowSnapshot: workflow, nodes, + workflowSnapshot: workflow, nodes, }; app.router.get('/api/runs/run-1', run); - app.evaluate(`state.data.runs=[${JSON.stringify(run)}];state.selectedRun='run-1';state.activeRun=state.data.runs[0]`); app.evaluate(`switchView('runs');showRunDetail('run-1')`); await settle(6); - const labels = [...app.document.querySelectorAll('#runsView .graph-stage-label')]; - const stageIds = app.evaluate(`workflowStages(${JSON.stringify(workflow)}).map(stage=>stage.map(node=>node.id))`); - assert.equal(labels.length, stageIds.length, 'every stage should keep its label'); - stageIds.forEach((ids, index) => { - const label = labels[index]; - assert.match(label.querySelector('.graph-stage-name').textContent, /^\u9636\u6bb5 \d/); - const starts = ids.map((id) => new Date(nodes[id].startedAt).getTime()); - const ends = ids.map((id) => new Date(nodes[id].finishedAt).getTime()); - const expected = `${new Date(Math.min(...starts)).toLocaleTimeString()} \u2192 ${new Date(Math.max(...ends)).toLocaleTimeString()}`; - assert.equal(label.querySelector('.graph-stage-time').textContent, expected, - 'stage label should show the stage start and finish time'); - }); - - const runtime = app.document.querySelector('#runsView .node-inspector .runtime-details'); - assert.ok(runtime, 'node inspector should keep the runtime details row'); - assert.doesNotMatch(runtime.textContent, /\u2192/, 'time window is no longer repeated under the node output'); + const graph = app.document.querySelector('#runDetail .run-graph'); + assert.deepEqual([...graph.querySelectorAll('[data-run-edge-source]')].map(path => + [path.dataset.runEdgeSource, path.dataset.runEdgeTarget]), edges); + const card = id => graph.querySelector('[data-run-node="' + id + '"]'); + const lane = id => Number.parseFloat(card(id).style.top); + assert.equal(lane('api-dev'), lane('api-review')); + assert.equal(lane('api-review'), lane('api-test')); + assert.equal(lane('web-dev'), lane('web-review')); + assert.equal(lane('web-review'), lane('web-test')); + assert.ok(lane('api-dev') < lane('design') && lane('design') < lane('web-dev')); + assert.equal(lane('design'), lane('integrate')); + assert.doesNotMatch(graph.textContent, /阶段|并行 2/); + const start = new Date(nodes['api-review'].startedAt).toLocaleTimeString(); + const end = new Date(nodes['api-review'].finishedAt).toLocaleTimeString(); + assert.equal(card('api-review').querySelector('.graph-node-time').textContent, start + ' → ' + end); + card('web-review').click(); + assert.equal(app.document.querySelector('#runDetail .node-inspector h3').textContent, 'web-review'); }); -test('a stage that has not started or finished hides the zero default time', async (t) => { +test('a graph node that has not started or finished hides the zero default time', async (t) => { const app = await loadApp(); t.after(app.close); const workflow = app.evaluate('structuredClone(state.data.workflows[0])'); @@ -470,11 +479,11 @@ test('a stage that has not started or finished hides the zero default time', asy app.evaluate(`state.data.runs=[${JSON.stringify(run)}];state.selectedRun='run-1';state.activeRun=state.data.runs[0]`); app.evaluate(`switchView('runs');showRunDetail('run-1')`); await settle(6); - const labels = [...app.document.querySelectorAll('#runsView .graph-stage-label')]; - const times = labels.map((label) => label.querySelector('.graph-stage-time')?.textContent || ''); - assert.ok(times.some((text) => text === ''), 'an unstarted stage has no duration'); - assert.ok(times.some((text) => text.includes('现在') && !text.includes('0001')), `an open stage shows now, not year 1: ${times.join(' | ')}`); - assert.ok(times.every((text) => !text.includes('0001')), times.join(' | ')); + const cards = [...app.document.querySelectorAll('#runDetail .graph-node')]; + const times = cards.map(card => card.querySelector('.graph-node-time').textContent); + assert.ok(times.some(text => text === ''), 'an unstarted node has no time window'); + assert.ok(times.some(text => text.includes('现在') && !text.includes('0001'))); + assert.ok(times.every(text => !text.includes('0001')), times.join(' | ')); }); /** 渲染正在执行的节点,保留真实详情页与实时更新入口。 */ From 79b38da4c82574c23a5837eb61c8e270bfca196a Mon Sep 17 00:00:00 2001 From: crispinhu Date: Thu, 3 Dec 2026 10:15:47 +0800 Subject: [PATCH 2/4] =?UTF-8?q?fix:=20=E9=9A=94=E7=A6=BB=E8=BF=94=E5=B7=A5?= =?UTF-8?q?=E6=97=A7=E8=BE=93=E5=85=A5=E5=92=8C=20bwrap=20Git=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/engine/artifacts.go | 8 ++- internal/engine/node_outputs_test.go | 54 ++++++++++++++++++ internal/engine/parallel_branches_test.go | 9 ++- internal/runner/reported_outputs_test.go | 20 ++++++- internal/runtime/artifact_stat_darwin.go | 10 ++++ internal/runtime/artifact_stat_linux.go | 10 ++++ internal/runtime/git_workspace_tools.go | 12 ++-- internal/runtime/sandbox_native_test.go | 67 +++++++++++++++++++++++ internal/runtime/sandbox_process.go | 40 +++++++++++++- internal/runtime/workspace_artifacts.go | 5 +- 10 files changed, 222 insertions(+), 13 deletions(-) create mode 100644 internal/runtime/artifact_stat_darwin.go create mode 100644 internal/runtime/artifact_stat_linux.go diff --git a/internal/engine/artifacts.go b/internal/engine/artifacts.go index 84f3a22e2..d9ebfaf21 100644 --- a/internal/engine/artifacts.go +++ b/internal/engine/artifacts.go @@ -470,7 +470,13 @@ func selectArtifactInputs(wf domain.WorkflowDefinition, node domain.WorkflowNode } var stale []string for _, artifact := range run.Artifacts { - if artifact.Name == "repository-patch" || !includeArtifact(direct, prior, artifact) || !run.ArtifactIsStale(artifact) { + 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) diff --git a/internal/engine/node_outputs_test.go b/internal/engine/node_outputs_test.go index 953fbd874..021df1ccd 100644 --- a/internal/engine/node_outputs_test.go +++ b/internal/engine/node_outputs_test.go @@ -129,6 +129,60 @@ func TestArtifactHandoffRemovesAnOutputOmittedFromTheNewAttempt(t *testing.T) { } } +func TestArtifactProducerRetiresMountedFilesBeforeReplay(t *testing.T) { + t.Parallel() + workflow := domain.WorkflowDefinition{Edges: []domain.WorkflowEdge{ + edge("worker", "check"), edge("independent", "other-check"), + }} + worker := domain.WorkflowNode{ID: "worker"} + check := domain.WorkflowNode{ID: "check"} + old := domain.Artifact{NodeID: worker.ID, Attempt: 1, Name: "data", MediaType: "text/plain", Content: "v1"} + retro := domain.Artifact{NodeID: worker.ID, Attempt: 1, Name: "loop-retro", MediaType: "text/markdown", Content: "old notes"} + sibling := domain.Artifact{NodeID: "independent", Attempt: 1, Name: "data", MediaType: "text/plain", Content: "current"} + run := domain.Run{ + WorkflowSnapshot: workflow, + Nodes: map[string]*domain.NodeRun{ + worker.ID: {Status: "succeeded", Attempt: 1}, + "independent": {Status: "succeeded", Attempt: 1}, + }, + Artifacts: []domain.Artifact{old, retro, sibling}, + } + workspace := t.TempDir() + for _, consumer := range []domain.WorkflowNode{check, {ID: "other-check"}} { + if _, err := materializeInputs(workspace, workflow, consumer, run); err != nil { + t.Fatal(err) + } + } + + run.Nodes[worker.ID] = &domain.NodeRun{Status: "running", Attempt: 2} + _, _, retired := runnerArtifactInputs(workflow, worker, run) + if len(retired) != 2 { + t.Fatalf("runner did not retire the producer's two old inputs: %v", retired) + } + if _, err := materializeInputs(workspace, workflow, worker, run); err != nil { + t.Fatal(err) + } + for _, artifact := range []domain.Artifact{old, retro} { + if _, err := os.Stat(filepath.Join(workspace, artifactInputRelPath(run, artifact))); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("old %s still readable when producer restarted: %v", artifact.Name, err) + } + } + if body, err := os.ReadFile(filepath.Join(workspace, artifactInputRelPath(run, sibling))); err != nil || string(body) != "current" { + t.Fatalf("independent branch input = %q, %v", body, err) + } + + run.Nodes[worker.ID].Status = "succeeded" + refreshed := old + refreshed.Attempt, refreshed.Content = 2, "v2" + run.Artifacts = append(run.Artifacts, refreshed) + if _, err := materializeInputs(workspace, workflow, check, run); err != nil { + t.Fatal(err) + } + if body, err := os.ReadFile(filepath.Join(workspace, artifactInputRelPath(run, old))); err != nil || string(body) != "v2" { + t.Fatalf("second round input = %q, %v", body, err) + } +} + func TestReportedReplayArtifactsRequireFreshnessEvidence(t *testing.T) { t.Parallel() const path = "review.md" diff --git a/internal/engine/parallel_branches_test.go b/internal/engine/parallel_branches_test.go index c5b59914d..24fcc4be1 100644 --- a/internal/engine/parallel_branches_test.go +++ b/internal/engine/parallel_branches_test.go @@ -384,7 +384,14 @@ fi`) review.Script = `if [ "$(cat impl.txt)" = v1 ]; then printf report > review.md; exec sleep 30; fi` } if tc.rewrite { - review.Script = "printf report > review.md" + review.Script = `set -eu +if [ -f review.md ]; then + touch -r review.md .review-mtime + printf report > review.md + touch -r .review-mtime review.md +else + printf report > review.md +fi` } review.ArtifactOutputs = []domain.ArtifactContract{{Name: "review", Path: "review.md", Required: true}} wf := domain.WorkflowDefinition{ diff --git a/internal/runner/reported_outputs_test.go b/internal/runner/reported_outputs_test.go index 8d3098025..657893930 100644 --- a/internal/runner/reported_outputs_test.go +++ b/internal/runner/reported_outputs_test.go @@ -145,11 +145,23 @@ func TestRunnerReworkRetiresOptionalArtifactHandoff(t *testing.T) { ID: "runner-rework-artifact", Name: "Runner rework artifact", SandboxProfileID: "test-native", Nodes: []domain.WorkflowNode{ {ID: "review", Name: "评审", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, - Script: "if [ ! -f review.md ]; then printf report > review.md; fi", - ArtifactOutputs: []domain.ArtifactContract{{Name: "review", Path: "review.md"}}}, + Script: `set -eu +if [ -f decision.md ]; then + touch -r decision.md .decision-mtime + printf report > decision.md + touch -r .decision-mtime decision.md +else + printf report > decision.md + printf report > review.md +fi`, + ArtifactOutputs: []domain.ArtifactContract{ + {Name: "review", Path: "review.md"}, + {Name: "decision", Path: "decision.md", Required: true}, + }}, {ID: "check", Name: "测试", Type: "script", ScriptLanguage: "shell", MaxAttempts: 1, Script: `set -eu input=.agentflow/inputs/review/review.md +test "$(cat .agentflow/inputs/review/decision.md)" = report if [ -f checked ]; then test ! -e "$input" else @@ -189,6 +201,10 @@ fi`}, if !ok || review.Attempt != 1 || final.Nodes["review"].Attempt != 2 || !review.Stale { t.Fatalf("optional artifact history = %+v (found %v)", review, ok) } + decision, ok := latestArtifact(final, "review", "decision") + if !ok || decision.Attempt != 2 || decision.Stale { + t.Fatalf("in-place rewritten artifact = %+v (found %v)", decision, ok) + } if err := e.Approve(run.ID, "approve", ""); err != nil { t.Fatal(err) } diff --git a/internal/runtime/artifact_stat_darwin.go b/internal/runtime/artifact_stat_darwin.go new file mode 100644 index 000000000..d3b15ba49 --- /dev/null +++ b/internal/runtime/artifact_stat_darwin.go @@ -0,0 +1,10 @@ +package runtime + +import ( + "os" + "syscall" +) + +func artifactChangeTime(info os.FileInfo) syscall.Timespec { + return info.Sys().(*syscall.Stat_t).Ctimespec +} diff --git a/internal/runtime/artifact_stat_linux.go b/internal/runtime/artifact_stat_linux.go new file mode 100644 index 000000000..1823ad4d1 --- /dev/null +++ b/internal/runtime/artifact_stat_linux.go @@ -0,0 +1,10 @@ +package runtime + +import ( + "os" + "syscall" +) + +func artifactChangeTime(info os.FileInfo) syscall.Timespec { + return info.Sys().(*syscall.Stat_t).Ctim +} diff --git a/internal/runtime/git_workspace_tools.go b/internal/runtime/git_workspace_tools.go index 8e5f91f6e..7bfbb6ac3 100644 --- a/internal/runtime/git_workspace_tools.go +++ b/internal/runtime/git_workspace_tools.go @@ -39,6 +39,13 @@ func nativeGitToolsRoot() (string, error) { return filepath.Join(cache, "LoopForge", "git-helpers"), nil } +func ensureNativeGitToolsRoot(root string) error { + if err := os.MkdirAll(filepath.Dir(root), 0o700); err != nil { + return err + } + return ensureRunnerGitDir(root) +} + func ensureRunnerGitDir(dir string) error { if err := os.Mkdir(dir, 0o755); err != nil && !os.IsExist(err) { return err @@ -90,10 +97,7 @@ func prepareWorkspaceGitTools(ctx context.Context, sandbox Sandbox, workspace st if err != nil { return "", "", err } - if err := os.MkdirAll(filepath.Dir(host), 0o700); err != nil { - return "", "", err - } - if err := ensureRunnerGitDir(host); err != nil { + if err := ensureNativeGitToolsRoot(host); err != nil { return "", "", err } self, err := os.Executable() diff --git a/internal/runtime/sandbox_native_test.go b/internal/runtime/sandbox_native_test.go index 718243a27..31244dbd3 100644 --- a/internal/runtime/sandbox_native_test.go +++ b/internal/runtime/sandbox_native_test.go @@ -55,6 +55,73 @@ func TestBwrapBunFSMountPoint(t *testing.T) { } } +func TestBwrapGitToolsExposeOnlyTheBoundInstallation(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_CACHE_HOME", filepath.Join(root, "cache")) + cache, err := nativeGitToolsRoot() + if err != nil { + t.Fatal(err) + } + args, err := bwrapGitTools([]string{"--"}, nil) + if err != nil || !strings.Contains(strings.Join(args, "\x00"), "--tmpfs\x00"+cache+"\x00") { + t.Fatalf("cold Git cache was not masked: %v, %v", args, err) + } + selected := filepath.Join(cache, "runner-selected", "credential") + unrelated := filepath.Join(cache, "runner-unrelated", "credential") + for _, tools := range []string{selected, unrelated} { + if err := os.MkdirAll(filepath.Join(tools, "bin"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(tools, "bin", "fixture"), []byte("fixture"), 0o600); err != nil { + t.Fatal(err) + } + } + environment := map[string]string{ + workspaceGitBinsEnv: filepath.Join(selected, "bin"), + SessionGatewayEnv: "http://127.0.0.1:1/fixture", + } + for _, tc := range []struct { + name string + env map[string]string + }{ + {name: "ordinary script"}, + {name: "explicit Git binding", env: environment}, + } { + t.Run(tc.name, func(t *testing.T) { + workspace := t.TempDir() + sb := &processSandbox{workspace: workspace, driver: "bwrap", binary: "bwrap"} + command := WithCommandEnvironment(CommandSpec{Argv: []string{"true"}}, tc.env) + cmd, err := sb.command(t.Context(), command, nil) + if err != nil { + t.Fatal(err) + } + args := strings.Join(cmd.Args, "\x00") + if !strings.Contains(args, "--tmpfs\x00"+cache+"\x00") || strings.Contains(args, unrelated) { + t.Fatalf("shared Git cache was not masked: %v", cmd.Args) + } + if bound := strings.Contains(args, "--ro-bind\x00"+selected+"\x00"+selected+"\x00"); bound != (tc.env != nil) { + t.Fatalf("unexpected Git helper mount: %v", cmd.Args) + } + t.Run("sandbox", func(t *testing.T) { + if !NativeSandboxAvailable("bwrap") { + t.Skip("bubblewrap user namespaces unavailable") + } + check := `test ! -e "$1"; test "$3" = "$(test -r "$2" && printf yes || printf no)"` + want := "no" + if tc.env != nil { + want = "yes" + } + command.Argv = []string{"sh", "-ec", check, "verify", unrelated, + filepath.Join(selected, "bin", "fixture"), want} + if out, err := sb.Exec(t.Context(), command, nil); err != nil { + t.Fatalf("Git helper visibility did not match the binding: %v (%s)", err, out) + } + }) + }) + } +} + func TestNativeSandboxResolvesPerOS(t *testing.T) { for _, tc := range []struct{ driver, goos, want string }{ {"native", "darwin", "seatbelt"}, diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go index db99686e9..d2144101c 100644 --- a/internal/runtime/sandbox_process.go +++ b/internal/runtime/sandbox_process.go @@ -236,6 +236,10 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, base return nil, err } args = bwrapPrivateBinds(args, command.privateBinds, command.managedCLIInstall) + args, err = bwrapGitTools(args, command.environment) + if err != nil { + return nil, err + } if command.runnerLogin != nil { // Hide host sources and the private journal after all other binds. // The managed CLI uses only its own private HOME and host callback. @@ -564,6 +568,39 @@ func bwrapPrivateBinds(args, binds []string, managedInstall string) []string { return append(out, "--") } +func bwrapGitTools(args []string, environment map[string]string) ([]string, error) { + cache, err := nativeGitToolsRoot() + if err != nil { + return args, nil + } + if _, err := os.Stat(cache); os.IsNotExist(err) { + // Reserve the empty mount point before Sandbox startup so a later + // Git-bound command cannot make a new cache visible via the host root. + if err := ensureNativeGitToolsRoot(cache); err != nil { + // The native Git binding cannot install helpers here either. + return args, nil + } + } else if err != nil { + return nil, err + } + // The host root is already visible read-only. Mask the Git cache even + // for commands without Git bindings, then expose only the selected tools. + out := append(args[:len(args)-1], "--tmpfs", cache) + bins := filepath.SplitList(environment[workspaceGitBinsEnv]) + if len(bins) > 0 && environment[SessionGatewayEnv] != "" { + tools := filepath.Dir(bins[len(bins)-1]) + rel, err := filepath.Rel(cache, tools) + runner, installation, inside := strings.Cut(rel, string(filepath.Separator)) + if err != nil || !inside || !strings.HasPrefix(runner, "runner-") || + (installation != "credential" && !strings.HasPrefix(installation, "git-")) || + strings.ContainsRune(installation, filepath.Separator) { + return nil, fmt.Errorf("invalid Git tools directory: %s", tools) + } + out = append(out, "--ro-bind", tools, tools) + } + return append(out, "--remount-ro", cache, "--"), nil +} + // bwrapChdir points the sandboxed process at dir instead of the workspace. func bwrapChdir(args []string, dir string) []string { out := append([]string{}, args...) @@ -626,9 +663,6 @@ func bwrapArgsCommand(workspace string, requirements SandboxRequirements) ([]str return nil, statErr } } - if gitTools, err := nativeGitToolsRoot(); err == nil { - args = append(args, "--ro-bind-try", gitTools, gitTools) - } return append(args, "--"), nil } diff --git a/internal/runtime/workspace_artifacts.go b/internal/runtime/workspace_artifacts.go index c0f09ec0a..fa17409c8 100644 --- a/internal/runtime/workspace_artifacts.go +++ b/internal/runtime/workspace_artifacts.go @@ -79,7 +79,7 @@ func RestoreMissingWorkspaceArtifact(root, path, digest string, source func() (i var ErrStaleArtifactOutput = errors.New("产物仍是上一次执行留下的文件,请为本次执行重新生成") // ArtifactOutputBaseline records the files that a rerun might inherit from -// an earlier attempt. Rewriting a file with the same bytes is valid. +// an earlier attempt. Change time also detects writes that preserve mtime. type ArtifactOutputBaseline map[string]os.FileInfo func SnapshotArtifactOutputs(workspace string, paths []string) (ArtifactOutputBaseline, error) { @@ -107,7 +107,8 @@ func SnapshotArtifactOutputs(workspace string, paths []string) (ArtifactOutputBa func (b ArtifactOutputBaseline) Unchanged(rel string, info os.FileInfo) bool { before := b[rel] - return before != nil && os.SameFile(before, info) && before.Size() == info.Size() && before.ModTime().Equal(info.ModTime()) + return before != nil && os.SameFile(before, info) && before.Size() == info.Size() && + before.ModTime().Equal(info.ModTime()) && artifactChangeTime(before) == artifactChangeTime(info) } // RemoveArtifactInputs retires handoff files in the runtime-owned input directory. From dd2463f7a3d2c32f81cd6195f8912f4bf7713bbe Mon Sep 17 00:00:00 2001 From: crispinhu Date: Thu, 3 Dec 2026 11:32:10 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E8=BF=94=E5=B7=A5?= =?UTF-8?q?=E4=BA=A7=E7=89=A9=E6=A0=A1=E9=AA=8C=E4=B8=8E=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E6=8B=93=E6=89=91=E7=BB=86=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/domain/run.go | 5 ++- internal/domain/runner.go | 3 ++ internal/engine/artifacts.go | 10 ++--- internal/engine/node_execute.go | 6 +-- internal/engine/node_outputs.go | 44 +++++++++++++++---- internal/engine/node_outputs_test.go | 57 +++++++++++++++++++++++++ internal/runner/outputs.go | 29 ++++++++++--- internal/runner/outputs_test.go | 21 +++++++-- internal/runtime/sandbox_native_test.go | 33 ++++++++++++++ internal/runtime/sandbox_process.go | 26 ++++++++--- web/app/runs.js | 31 +++++++++++--- web/observability.css | 3 +- webtest/tests/runs-detail.test.mjs | 10 +++-- 13 files changed, 233 insertions(+), 45 deletions(-) diff --git a/internal/domain/run.go b/internal/domain/run.go index 19c0a0880..1dbc974f0 100644 --- a/internal/domain/run.go +++ b/internal/domain/run.go @@ -341,7 +341,10 @@ func (r Run) ArtifactIsStale(a Artifact) bool { if n == nil { return false } - return n.Status != "succeeded" || (n.Attempt != a.Attempt && !(a.Attempt == 0 && n.Attempt == 1)) + 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. diff --git a/internal/domain/runner.go b/internal/domain/runner.go index aa15b0ea5..a4fd9b353 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -759,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 diff --git a/internal/engine/artifacts.go b/internal/engine/artifacts.go index d9ebfaf21..d274f6fe8 100644 --- a/internal/engine/artifacts.go +++ b/internal/engine/artifacts.go @@ -212,12 +212,7 @@ func (e *Engine) freezeAvailableArtifacts(runID string, node domain.WorkflowNode if !ok || !shouldCommitNodeOutcome(current, current.Nodes[node.ID], generation, attempt, false) { return nil } - recovered := []string(nil) - if reported, ok := outputs.(*reportedOutputs); ok { - 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, ";")}) } @@ -448,6 +443,9 @@ func latestInputArtifacts(artifacts []domain.Artifact, direct, prior map[string] func currentNodeArtifacts(run domain.Run) []domain.Artifact { var active []domain.Artifact for _, artifact := range run.Artifacts { + if node := run.Nodes[artifact.NodeID]; node != nil && node.Status != "succeeded" { + continue + } if !run.ArtifactIsStale(artifact) { active = append(active, artifact) } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 6b77177d1..6545e83ea 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -1329,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, ";")}) diff --git a/internal/engine/node_outputs.go b/internal/engine/node_outputs.go index 96df6a3b8..c694060ca 100644 --- a/internal/engine/node_outputs.go +++ b/internal/engine/node_outputs.go @@ -138,6 +138,20 @@ func collectOutputFile(outputs nodeOutputs, rel, id string) ([]byte, domain.Arti return content, domain.ArtifactBlob{}, err } +func recoverNodeOutputs(outputs nodeOutputs, workspace, hostLocalPath string, node domain.WorkflowNode) []string { + switch out := outputs.(type) { + case *reportedOutputs: + return out.takeRecovered() + case archivedWorkspaceOutputs: + if len(out.baseline) != 0 { + // A same-named file elsewhere in the shared workspace has no + // evidence that it was written for this replay. + return nil + } + } + return recoverMisplacedArtifacts(workspace, hostLocalPath, node) +} + func (w workspaceOutputs) repositoryPatch(dir string) ([]byte, error) { return collectRepositoryPatch(repositoryWorkspacePath(string(w), domain.RepositoryContext{WorkspaceDir: dir})) } @@ -149,7 +163,7 @@ type reportedOutputs struct { inputs []domain.RunnerInputFile staleInputs []string previousOutputs map[string]map[string]bool - freshOutputs map[string]bool + freshOutputs map[string]string transfer bool openBlob func(string) (io.ReadCloser, error) @@ -163,7 +177,7 @@ type reportedOutputs struct { } func newReportedOutputs(inputs []domain.RunnerInputFile) *reportedOutputs { - r := &reportedOutputs{inputs: inputs, freshOutputs: map[string]bool{}} + r := &reportedOutputs{inputs: inputs, freshOutputs: map[string]string{}} r.reset() return r } @@ -189,12 +203,13 @@ func (r *reportedOutputs) absorb(outputs *domain.RunnerTaskOutputs) { } r.mu.Lock() defer r.mu.Unlock() + fresh := make(map[string]bool, len(outputs.FreshOutputFiles)) for _, rel := range outputs.FreshOutputFiles { - r.freshOutputs[rel] = true + fresh[rel] = true } for rel, content := range outputs.Files { r.clearFile(rel) - if r.outputIsStale(rel, runtime.WorkspaceContentSHA(content)) { + if r.outputIsStale(rel, runtime.WorkspaceContentSHA(content), fresh[rel]) { r.errors[rel] = runtime.ErrStaleArtifactOutput.Error() } else { r.files[rel] = content @@ -202,7 +217,7 @@ func (r *reportedOutputs) absorb(outputs *domain.RunnerTaskOutputs) { } for rel, blob := range outputs.FileBlobs { r.clearFile(rel) - if r.outputIsStale(rel, blob.SHA256) { + if r.outputIsStale(rel, blob.SHA256, fresh[rel]) { r.errors[rel] = runtime.ErrStaleArtifactOutput.Error() } else { r.blobs[rel] = blob @@ -224,16 +239,27 @@ func (r *reportedOutputs) absorb(outputs *domain.RunnerTaskOutputs) { // Older runners do not report file identity. An unchanged digest from a // previous attempt is insufficient evidence that they produced a new output. -func (r *reportedOutputs) outputIsStale(rel, digest string) bool { - return r.previousOutputs[rel][digest] && !r.freshOutputs[rel] +func (r *reportedOutputs) outputIsStale(rel, digest string, fresh bool) bool { + if fresh { + r.freshOutputs[rel] = digest + return false + } + return r.previousOutputs[rel][digest] && r.freshOutputs[rel] != digest } func (r *reportedOutputs) requireFreshOutputs(inv *domain.RunnerInvocation) { r.mu.Lock() defer r.mu.Unlock() for _, rel := range inv.OutputFiles { - if _, tracked := r.previousOutputs[rel]; tracked && !r.freshOutputs[rel] { - inv.FreshOutputFiles = append(inv.FreshOutputFiles, rel) + if _, tracked := r.previousOutputs[rel]; !tracked { + continue + } + inv.FreshOutputFiles = append(inv.FreshOutputFiles, rel) + if digest := r.freshOutputs[rel]; digest != "" { + if inv.RetainedOutputSHA256 == nil { + inv.RetainedOutputSHA256 = map[string]string{} + } + inv.RetainedOutputSHA256[rel] = digest } } } diff --git a/internal/engine/node_outputs_test.go b/internal/engine/node_outputs_test.go index 021df1ccd..707acc1cc 100644 --- a/internal/engine/node_outputs_test.go +++ b/internal/engine/node_outputs_test.go @@ -205,4 +205,61 @@ func TestReportedReplayArtifactsRequireFreshnessEvidence(t *testing.T) { if got, err := outputs.readFile(path); err != nil || string(got) != "same report" { t.Fatalf("rewritten identical report = %q, %v", got, err) } + invocation := domain.RunnerInvocation{OutputFiles: []string{path}} + outputs.requireFreshOutputs(&invocation) + if len(invocation.FreshOutputFiles) != 1 || invocation.RetainedOutputSHA256[path] != runtime.WorkspaceContentSHA("same report") { + t.Fatalf("retained evidence was not scoped to exact report: %+v", invocation) + } + outputs.reset() + report.Files[path] = "later report" + outputs.absorb(report) + if _, err := outputs.readFile(path); err == nil { + t.Fatal("proof for one body authorized a different historical report") + } +} + +func TestWaitingApprovalArtifactIsCurrentButNotHandedOff(t *testing.T) { + t.Parallel() + run := domain.Run{ + Nodes: map[string]*domain.NodeRun{"review": {Status: "waiting_approval", Attempt: 2}}, + Artifacts: []domain.Artifact{ + {NodeID: "review", Attempt: 1, Name: "report"}, + {NodeID: "review", Attempt: 2, Name: "report"}, + }, + } + run.MarkStaleArtifacts() + if !run.Artifacts[0].Stale || run.Artifacts[1].Stale { + t.Fatalf("approval artifact history = %+v", run.Artifacts) + } + if got := currentNodeArtifacts(run); len(got) != 0 { + t.Fatalf("unapproved artifacts were handed off: %+v", got) + } + run.Nodes["review"].Status = "succeeded" + if got := currentNodeArtifacts(run); len(got) != 1 || got[0].Attempt != 2 { + t.Fatalf("approved artifacts = %+v", got) + } +} + +func TestReplayDoesNotRecoverAnUnverifiedWorkspaceCopy(t *testing.T) { + t.Parallel() + workspace := t.TempDir() + copyDir := filepath.Join(workspace, "old") + if err := os.Mkdir(copyDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(copyDir, "report.md"), []byte("old"), 0600); err != nil { + t.Fatal(err) + } + baseline, err := runtime.SnapshotArtifactOutputs(workspace, []string{"report.md"}) + if err != nil { + t.Fatal(err) + } + outputs := archivedWorkspaceOutputs{workspaceOutputs: workspaceOutputs(workspace), baseline: baseline} + node := domain.WorkflowNode{ArtifactOutputs: []domain.ArtifactContract{{Name: "report", Path: "report.md", Required: true}}} + if got := recoverNodeOutputs(outputs, workspace, "", node); len(got) != 0 { + t.Fatalf("old copy recovered during replay: %v", got) + } + if _, err := os.Stat(filepath.Join(workspace, "report.md")); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("failed replay materialized old report: %v", err) + } } diff --git a/internal/runner/outputs.go b/internal/runner/outputs.go index 2f7ab02c7..dfc4fb645 100644 --- a/internal/runner/outputs.go +++ b/internal/runner/outputs.go @@ -2,6 +2,7 @@ package runner import ( "context" + "crypto/sha256" "errors" "fmt" "io" @@ -9,6 +10,7 @@ import ( "os" "path" "path/filepath" + "slices" "strings" "sync" @@ -108,7 +110,7 @@ func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation, baseline if inv.ArtifactTransfer { limit = domain.MaxSOPArtifactBytes } - out.Recovered = recoverOutputFiles(workspace, inv.OutputFiles, limit) + out.Recovered = recoverOutputFiles(workspace, inv.OutputFiles, limit, inv.FreshOutputFiles) } paths := inv.OutputFiles if inv.ArtifactTransfer { @@ -120,7 +122,7 @@ func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation, baseline } out.Files, out.TooLarge = readOutputFiles(workspace, paths) if len(baselines) != 0 && len(baselines[0]) != 0 { - markFreshTaskOutputs(workspace, out, baselines[0]) + markFreshTaskOutputs(workspace, out, baselines[0], inv.RetainedOutputSHA256) } out.Patches = collectPatchInventories(workspace, patchInventoryDirs(inv)) frontend, evidence := domain.DetectFrontendProject(workspace) @@ -128,7 +130,7 @@ func collectTaskOutputs(workspace string, inv *domain.RunnerInvocation, baseline return out } -func markFreshTaskOutputs(workspace string, out *domain.RunnerTaskOutputs, baseline runtime.ArtifactOutputBaseline) { +func markFreshTaskOutputs(workspace string, out *domain.RunnerTaskOutputs, baseline runtime.ArtifactOutputBaseline, retained map[string]string) { out.FileErrors = map[string]string{} root, err := os.OpenRoot(workspace) if err == nil { @@ -149,6 +151,9 @@ func markFreshTaskOutputs(workspace string, out *domain.RunnerTaskOutputs, basel case !info.Mode().IsRegular(): out.FileErrors[rel] = "output is not a regular file" case baseline.Unchanged(rel, info): + if matchesRetainedOutput(root, rel, retained[rel]) { + continue + } out.FileErrors[rel] = runtime.ErrStaleArtifactOutput.Error() default: out.FreshOutputFiles = append(out.FreshOutputFiles, rel) @@ -158,6 +163,20 @@ func markFreshTaskOutputs(workspace string, out *domain.RunnerTaskOutputs, basel } } +func matchesRetainedOutput(root *os.Root, rel, digest string) bool { + if digest == "" { + return false + } + file, err := root.Open(rel) + if err != nil { + return false + } + defer file.Close() + hash := sha256.New() + n, err := io.Copy(hash, io.LimitReader(file, domain.MaxSOPArtifactBytes+1)) + return err == nil && n <= domain.MaxSOPArtifactBytes && fmt.Sprintf("%x", hash.Sum(nil)) == digest +} + func (d *Daemon) uploadTaskOutputs(ctx context.Context, task domain.RunnerTask, out *domain.RunnerTaskOutputs) { inv := task.Invocation if inv == nil || !inv.ArtifactTransfer || out == nil { @@ -289,10 +308,10 @@ func collectPatchInventories(workspace string, dirs []string) map[string]string // recoverOutputFiles moves a missing root-level output into place when the // Agent wrote a file with the same name elsewhere in the workspace. -func recoverOutputFiles(workspace string, outputs []string, limit int64) []string { +func recoverOutputFiles(workspace string, outputs []string, limit int64, replayOutputs []string) []string { var recovered []string for _, rel := range outputs { - if !domain.SafeWorkspaceRelPath(rel) { + if !domain.SafeWorkspaceRelPath(rel) || slices.Contains(replayOutputs, rel) { continue } dest := filepath.Join(workspace, filepath.FromSlash(rel)) diff --git a/internal/runner/outputs_test.go b/internal/runner/outputs_test.go index f59404808..21602206c 100644 --- a/internal/runner/outputs_test.go +++ b/internal/runner/outputs_test.go @@ -100,9 +100,15 @@ func TestRunnerReplayOutputsReportOnlyFreshFiles(t *testing.T) { t.Fatal(err) } } + if err := os.Mkdir(filepath.Join(workspace, "old"), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(workspace, "old", "missing.md"), []byte("old"), 0600); err != nil { + t.Fatal(err) + } inv := &domain.RunnerInvocation{ - ReportOutputs: true, OutputFiles: []string{"old.md", "rewritten.md"}, - FreshOutputFiles: []string{"old.md", "rewritten.md"}, + ReportOutputs: true, RecoverOutputs: true, OutputFiles: []string{"old.md", "rewritten.md", "missing.md"}, + FreshOutputFiles: []string{"old.md", "rewritten.md", "missing.md"}, } baseline, err := runtime.SnapshotArtifactOutputs(workspace, inv.FreshOutputFiles) if err != nil { @@ -118,7 +124,16 @@ func TestRunnerReplayOutputsReportOnlyFreshFiles(t *testing.T) { out := collectTaskOutputs(workspace, inv, baseline) if out.FileErrors["old.md"] == "" || out.Files["old.md"] != "" || out.Files["rewritten.md"] != "report" || len(out.FreshOutputFiles) != 1 || - out.FreshOutputFiles[0] != "rewritten.md" { + out.FreshOutputFiles[0] != "rewritten.md" || len(out.Recovered) != 0 || out.Files["missing.md"] != "" { t.Fatalf("incorrect replay report: %+v", out) } + nextBaseline, err := runtime.SnapshotArtifactOutputs(workspace, inv.FreshOutputFiles) + if err != nil { + t.Fatal(err) + } + inv.RetainedOutputSHA256 = map[string]string{"rewritten.md": runtime.WorkspaceContentSHA("report")} + out = collectTaskOutputs(workspace, inv, nextBaseline) + if out.Files["rewritten.md"] != "report" || out.FileErrors["rewritten.md"] != "" || len(out.FreshOutputFiles) != 0 { + t.Fatalf("same verified body was lost between invocations: %+v", out) + } } diff --git a/internal/runtime/sandbox_native_test.go b/internal/runtime/sandbox_native_test.go index 31244dbd3..1845bd229 100644 --- a/internal/runtime/sandbox_native_test.go +++ b/internal/runtime/sandbox_native_test.go @@ -122,6 +122,39 @@ func TestBwrapGitToolsExposeOnlyTheBoundInstallation(t *testing.T) { } } +func TestBwrapOrdinaryCommandsSurviveAnUnusableGitCache(t *testing.T) { + for _, parentBlocked := range []bool{false, true} { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_CACHE_HOME", filepath.Join(root, "cache")) + cache, err := nativeGitToolsRoot() + if err != nil { + t.Fatal(err) + } + blocked := cache + if parentBlocked { + blocked = filepath.Dir(cache) + } + if err := os.MkdirAll(filepath.Dir(blocked), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(blocked, nil, 0600); err != nil { + t.Fatal(err) + } + sb := &processSandbox{workspace: t.TempDir(), driver: "bwrap", binary: "bwrap"} + command := CommandSpec{Argv: []string{"true"}} + cmd, err := sb.command(t.Context(), command, nil) + if err != nil || strings.Contains(strings.Join(cmd.Args, "\x00"), cache) { + t.Fatalf("ordinary command required the unusable cache %q: %v", blocked, err) + } + if NativeSandboxAvailable("bwrap") { + if out, err := sb.Exec(t.Context(), command, nil); err != nil { + t.Fatalf("ordinary command did not start: %v (%s)", err, out) + } + } + } +} + func TestNativeSandboxResolvesPerOS(t *testing.T) { for _, tc := range []struct{ driver, goos, want string }{ {"native", "darwin", "seatbelt"}, diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go index d2144101c..3b81354fa 100644 --- a/internal/runtime/sandbox_process.go +++ b/internal/runtime/sandbox_process.go @@ -569,25 +569,37 @@ func bwrapPrivateBinds(args, binds []string, managedInstall string) []string { } func bwrapGitTools(args []string, environment map[string]string) ([]string, error) { + bins := filepath.SplitList(environment[workspaceGitBinsEnv]) + bound := len(bins) > 0 && environment[SessionGatewayEnv] != "" cache, err := nativeGitToolsRoot() if err != nil { + if bound { + return nil, err + } return args, nil } - if _, err := os.Stat(cache); os.IsNotExist(err) { + info, err := os.Stat(cache) + if os.IsNotExist(err) { // Reserve the empty mount point before Sandbox startup so a later // Git-bound command cannot make a new cache visible via the host root. - if err := ensureNativeGitToolsRoot(cache); err != nil { - // The native Git binding cannot install helpers here either. + _ = ensureNativeGitToolsRoot(cache) + info, err = os.Stat(cache) + } + if err != nil || !info.IsDir() { + // An inaccessible path or a file contains no helper directory to + // mount. Only a command that needs the Git binding depends on it. + if !bound { return args, nil } - } else if err != nil { - return nil, err + if err != nil { + return nil, fmt.Errorf("locate Git helper directory: %w", err) + } + return nil, fmt.Errorf("Git helper path is not a directory: %s", cache) } // The host root is already visible read-only. Mask the Git cache even // for commands without Git bindings, then expose only the selected tools. out := append(args[:len(args)-1], "--tmpfs", cache) - bins := filepath.SplitList(environment[workspaceGitBinsEnv]) - if len(bins) > 0 && environment[SessionGatewayEnv] != "" { + if bound { tools := filepath.Dir(bins[len(bins)-1]) rel, err := filepath.Rel(cache, tools) runner, installation, inside := strings.Cut(rel, string(filepath.Separator)) diff --git a/web/app/runs.js b/web/app/runs.js index ff65dc693..08c7c2b70 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1456,7 +1456,7 @@ function patchRunLive(r){ btn.title=btn.querySelector('b').textContent+' · '+small.textContent; } const time=btn.querySelector('.graph-node-time'); - if(time){time.textContent=graphNodeTimeLabel(n);time.hidden=!time.textContent} + if(time){time.textContent=graphNodeTimeLabel(n);time.title=time.textContent;time.hidden=!time.textContent} const count=(r.artifacts||[]).filter(a=>a.nodeId===btn.dataset.runNode).length; let em=btn.querySelector('em'); if(count){if(!em){em=document.createElement('em');btn.appendChild(em)}em.textContent=`${count} 产物`}else if(em)em.remove(); @@ -2388,11 +2388,13 @@ function runTimeMs(value){ return Number.isFinite(ms)&&new Date(ms).getUTCFullYear()>1?ms:null; } +const runGraphClock=new Intl.DateTimeFormat(undefined,{hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'}); + function graphNodeTimeLabel(node){ const start=runTimeMs(node?.startedAt); if(start===null)return ''; const end=runTimeMs(node.finishedAt); - return new Date(start).toLocaleTimeString()+' → '+(end===null?lfT('现在','Now'):new Date(end).toLocaleTimeString()); + return runGraphClock.format(start)+' → '+(end===null?lfT('现在','Now'):runGraphClock.format(end)); } function runGraphPositions(workflow, parents){ @@ -2439,11 +2441,23 @@ function renderRunTopology(graph,r,workflow,nodes){ const edges=(workflow.edges||[]).map((edge,index)=>({...edge,index})).filter(edge=>byId.has(edge.source)&&byId.has(edge.target)); for(const edge of edges)parents.get(edge.target).push(edge); const {columns,positions}=runGraphPositions({nodes,edges},parents); - const width=192,height=76,columnGap=46,rowGap=16,pad=6; + const width=192,height=76,columnGap=46,rowGap=16,pad=6,channelGap=12; + // A long edge goes around the cards in the intervening columns. + const channels=new Map(),occupiedUntil=[]; + const bySource=[...edges].sort((a,b)=>positions.get(a.source).column-positions.get(b.source).column); + for(const edge of bySource){ + const from=positions.get(edge.source).column,to=positions.get(edge.target).column; + if(to-from<=1)continue; + let channel=occupiedUntil.findIndex(end=>end<=from); + if(channel===-1)channel=occupiedUntil.length; + occupiedUntil[channel]=to; + channels.set(edge.index,channel); + } + const wireSpace=occupiedUntil.length*channelGap; const lanes=[...positions.values()].map(pos=>pos.lane); const top=Math.min(...lanes),bottom=Math.max(...lanes); const graphWidth=2*pad+columns*width+(columns-1)*columnGap; - const graphHeight=2*pad+height+(bottom-top)*(height+rowGap); + const graphHeight=2*pad+wireSpace+height+(bottom-top)*(height+rowGap); const surface=document.createElement('div'); surface.className='run-graph-layout'; surface.style.width=graphWidth+'px'; @@ -2458,7 +2472,7 @@ function renderRunTopology(graph,r,workflow,nodes){ const btn=buttons.get(id); if(!btn)continue; pos.left=pad+pos.column*(width+columnGap); - pos.top=pad+(pos.lane-top)*(height+rowGap); + pos.top=pad+wireSpace+(pos.lane-top)*(height+rowGap); Object.assign(btn.style,{left:pos.left+'px',top:pos.top+'px',width:width+'px',height:height+'px'}); const incoming=parents.get(id); const upstream=incoming.map(edge=>byId.get(edge.source).name).filter(Boolean); @@ -2474,6 +2488,7 @@ function renderRunTopology(graph,r,workflow,nodes){ const time=document.createElement('span'); time.className='graph-node-time'; time.textContent=graphNodeTimeLabel(r.nodes?.[id]); + time.title=time.textContent; time.hidden=!time.textContent; small.after(time); surface.append(btn); @@ -2482,12 +2497,16 @@ function renderRunTopology(graph,r,workflow,nodes){ const source=positions.get(edge.source),target=positions.get(edge.target); const x=source.left+width,y=source.top+height/2,endX=target.left,endY=target.top+height/2; const bend=(x+endX)/2; + const channel=channels.get(edge.index); + const line=channel===undefined + ? ' C '+bend+' '+y+' '+bend+' '+endY+' '+endX+' '+endY + : ' H '+(x+columnGap/2)+' V '+(pad+channel*channelGap)+' H '+(endX-columnGap/2)+' V '+endY+' H '+endX; const path=document.createElementNS(svgNS,'path'); path.classList.add('run-graph-edge'); path.dataset.runEdgeIndex=edge.index; path.dataset.runEdgeSource=edge.source; path.dataset.runEdgeTarget=edge.target; - path.setAttribute('d','M '+x+' '+y+' C '+bend+' '+y+' '+bend+' '+endY+' '+endX+' '+endY+ + path.setAttribute('d','M '+x+' '+y+line+ ' M '+(endX-5)+' '+(endY-4)+' L '+endX+' '+endY+' L '+(endX-5)+' '+(endY+4)); updateRunGraphEdge(path,r,workflow); wires.append(path); diff --git a/web/observability.css b/web/observability.css index 9e26b4175..ad8599f02 100644 --- a/web/observability.css +++ b/web/observability.css @@ -80,7 +80,7 @@ .run-graph-edge{fill:none;stroke:var(--muted-2);stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round} .run-graph-edge.is-skipped{stroke-dasharray:4 3;opacity:.45} .run-graph-layout>.graph-node{position:absolute} -.graph-node-time{display:block;margin-top:4px;color:var(--muted-2);font-size:9.5px;font-variant-numeric:tabular-nums;white-space:nowrap} +.graph-node-time{display:block;overflow:hidden;text-overflow:ellipsis;margin-top:4px;color:var(--muted-2);font-size:9.5px;font-variant-numeric:tabular-nums;white-space:nowrap} .graph-node-time[hidden]{display:none} .graph-node{position:relative;min-width:0;width:100%;box-sizing:border-box;display:grid;grid-template-columns:32px minmax(0,1fr);align-items:center;gap:9px;padding:12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--panel);color:var(--text);text-align:left;cursor:pointer;transition:all .14s ease} .graph-node:hover,.graph-node.selected{border-color:var(--blue);box-shadow:0 0 0 3px var(--blue-soft)} @@ -101,6 +101,7 @@ .graph-node b{font-size:11px} .graph-node small{margin-top:3px;color:var(--muted-2);font-size:9px} .graph-node em{position:absolute;right:7px;top:5px;padding:1px 5px;border-radius:5px;background:var(--panel-2);color:var(--muted-2);font-size:8px;font-style:normal} +.graph-node>.run-step-done{position:absolute;right:7px;bottom:5px} .node-workspace,.node-drilldown{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(260px,.75fr);gap:16px;border-bottom:1px solid var(--line)} .node-drilldown{border-top:16px solid var(--bg-soft);margin-top:0;background:var(--bg-soft)} diff --git a/webtest/tests/runs-detail.test.mjs b/webtest/tests/runs-detail.test.mjs index 994559277..7c1a512dc 100644 --- a/webtest/tests/runs-detail.test.mjs +++ b/webtest/tests/runs-detail.test.mjs @@ -427,7 +427,7 @@ test('run topology keeps independent branches on their own dependency paths', as const edges = [ ['design', 'api-dev'], ['api-dev', 'api-review'], ['api-review', 'api-test'], ['design', 'web-dev'], ['web-dev', 'web-review'], ['web-review', 'web-test'], - ['api-test', 'integrate'], ['web-test', 'integrate'], + ['api-test', 'integrate'], ['web-test', 'integrate'], ['design', 'integrate'], ]; workflow.edges = edges.map(([source, target]) => ({ source, target, when: 'success' })); const nodes = Object.fromEntries(workflow.nodes.map((node, i) => [node.id, { @@ -454,9 +454,13 @@ test('run topology keeps independent branches on their own dependency paths', as assert.equal(lane('web-review'), lane('web-test')); assert.ok(lane('api-dev') < lane('design') && lane('design') < lane('web-dev')); assert.equal(lane('design'), lane('integrate')); + const bridge=graph.querySelector('[data-run-edge-source="design"][data-run-edge-target="integrate"]'); + const bridgeY=Number(bridge.getAttribute('d').match(/ V ([0-9.]+) H /)?.[1]); + assert.ok(bridgeY < lane('api-review') && bridgeY < lane('web-review'), 'the edge clears both intermediate lanes'); assert.doesNotMatch(graph.textContent, /阶段|并行 2/); - const start = new Date(nodes['api-review'].startedAt).toLocaleTimeString(); - const end = new Date(nodes['api-review'].finishedAt).toLocaleTimeString(); + const clock=new Intl.DateTimeFormat(undefined,{hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23'}); + const start=clock.format(new Date(nodes['api-review'].startedAt)); + const end=clock.format(new Date(nodes['api-review'].finishedAt)); assert.equal(card('api-review').querySelector('.graph-node-time').textContent, start + ' → ' + end); card('web-review').click(); assert.equal(app.document.querySelector('#runDetail .node-inspector h3').textContent, 'web-review'); From 28a15967b2cdc8ed59bf2e798fd441b9224cd49b Mon Sep 17 00:00:00 2001 From: crispinhu Date: Thu, 3 Dec 2026 11:42:01 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(web):=20=E5=B9=B3=E6=BB=91=E8=BF=90?= =?UTF-8?q?=E8=A1=8C=E6=8B=93=E6=89=91=E7=9A=84=E8=B7=A8=E5=88=97=E8=BF=9E?= =?UTF-8?q?=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- web/app/runs.js | 79 ++++++++++++++++++++++-------- webtest/tests/runs-detail.test.mjs | 34 +++++++++++-- 2 files changed, 89 insertions(+), 24 deletions(-) diff --git a/web/app/runs.js b/web/app/runs.js index 08c7c2b70..20ccad95b 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -2420,6 +2420,46 @@ function runGraphPositions(workflow, parents){ return {columns:columns.length,positions}; } +function runGraphCurve(x,y,endX,endY,bow=0){ + const step=(endX-x)/3; + return ' C '+(x+step)+' '+(y+bow)+' '+(endX-step)+' '+(endY+bow)+' '+endX+' '+endY; +} + +function runGraphLongEdges(edges,positions,width,height){ + const routes=new Map(),taken=[]; + const clearance=5; + for(const edge of edges){ + const source=positions.get(edge.source),target=positions.get(edge.target); + if(target.column-source.column<=1)continue; + const cards=[...positions.values()].filter(pos=>pos.column>source.column&&pos.columny+(endY-y)*t*t*(3-2*t)+3*bow*t*(1-t); + // The horizontal control points are evenly spaced, so each card's + // horizontal bounds give the exact portion of the curve to check. + const bow=(y===endY?[-10,10,-4,4,0]:[0]).find(offset=>cards.every(card=>{ + const start=(card.left-x)/span,end=(card.left+width-x)/span; + const values=[curveY(start,offset),curveY(end,offset)]; + if(offset&&start<.5&&end>.5)values.push(curveY(.5,offset)); + return Math.max(...values)<=card.top-clearance||Math.min(...values)>=card.top+height+clearance; + })); + if(bow!==undefined){ + routes.set(edge.index,{bow}); + continue; + } + const blocked=cards.map(card=>[card.top-clearance,card.top+height+clearance]); + for(const lane of taken){ + if(lane.fromMath.abs(lane-y)+Math.abs(lane-endY); + candidates.sort((a,b)=>distance(a)-distance(b)||Math.abs(a-y)-Math.abs(b-y)); + const lane=candidates.find(value=>blocked.every(([above,below])=>value<=above||value>=below)); + taken.push({from:source.column,to:target.column,y:lane}); + routes.set(edge.index,{lane}); + } + return routes; +} + function updateRunGraphEdge(path, r, workflow){ const edge=(workflow.edges||[])[Number(path.dataset.runEdgeIndex)]; if(!edge)return; @@ -2441,23 +2481,20 @@ function renderRunTopology(graph,r,workflow,nodes){ const edges=(workflow.edges||[]).map((edge,index)=>({...edge,index})).filter(edge=>byId.has(edge.source)&&byId.has(edge.target)); for(const edge of edges)parents.get(edge.target).push(edge); const {columns,positions}=runGraphPositions({nodes,edges},parents); - const width=192,height=76,columnGap=46,rowGap=16,pad=6,channelGap=12; - // A long edge goes around the cards in the intervening columns. - const channels=new Map(),occupiedUntil=[]; - const bySource=[...edges].sort((a,b)=>positions.get(a.source).column-positions.get(b.source).column); - for(const edge of bySource){ - const from=positions.get(edge.source).column,to=positions.get(edge.target).column; - if(to-from<=1)continue; - let channel=occupiedUntil.findIndex(end=>end<=from); - if(channel===-1)channel=occupiedUntil.length; - occupiedUntil[channel]=to; - channels.set(edge.index,channel); - } - const wireSpace=occupiedUntil.length*channelGap; + const width=192,height=76,columnGap=46,rowGap=16,pad=6; const lanes=[...positions.values()].map(pos=>pos.lane); const top=Math.min(...lanes),bottom=Math.max(...lanes); + for(const pos of positions.values()){ + pos.left=pad+pos.column*(width+columnGap); + pos.top=(pos.lane-top)*(height+rowGap); + } + const edgeRoutes=runGraphLongEdges(edges,positions,width,height); + const detourLanes=[...edgeRoutes.values()].map(route=>route.lane).filter(lane=>lane!==undefined); + const graphTop=Math.min(0,...detourLanes); + const graphBottom=Math.max(height+(bottom-top)*(height+rowGap),...detourLanes); + const offset=pad-graphTop; const graphWidth=2*pad+columns*width+(columns-1)*columnGap; - const graphHeight=2*pad+wireSpace+height+(bottom-top)*(height+rowGap); + const graphHeight=2*pad+graphBottom-graphTop; const surface=document.createElement('div'); surface.className='run-graph-layout'; surface.style.width=graphWidth+'px'; @@ -2471,8 +2508,7 @@ function renderRunTopology(graph,r,workflow,nodes){ for(const [id,pos] of positions){ const btn=buttons.get(id); if(!btn)continue; - pos.left=pad+pos.column*(width+columnGap); - pos.top=pad+wireSpace+(pos.lane-top)*(height+rowGap); + pos.top+=offset; Object.assign(btn.style,{left:pos.left+'px',top:pos.top+'px',width:width+'px',height:height+'px'}); const incoming=parents.get(id); const upstream=incoming.map(edge=>byId.get(edge.source).name).filter(Boolean); @@ -2496,11 +2532,12 @@ function renderRunTopology(graph,r,workflow,nodes){ for(const edge of edges){ const source=positions.get(edge.source),target=positions.get(edge.target); const x=source.left+width,y=source.top+height/2,endX=target.left,endY=target.top+height/2; - const bend=(x+endX)/2; - const channel=channels.get(edge.index); - const line=channel===undefined - ? ' C '+bend+' '+y+' '+bend+' '+endY+' '+endX+' '+endY - : ' H '+(x+columnGap/2)+' V '+(pad+channel*channelGap)+' H '+(endX-columnGap/2)+' V '+endY+' H '+endX; + const route=edgeRoutes.get(edge.index); + let line=runGraphCurve(x,y,endX,endY,route?.bow); + if(route?.lane!==undefined){ + const lane=route.lane+offset,turn=columnGap*.8; + line=runGraphCurve(x,y,x+turn,lane)+runGraphCurve(x+turn,lane,endX-turn,lane)+runGraphCurve(endX-turn,lane,endX,endY); + } const path=document.createElementNS(svgNS,'path'); path.classList.add('run-graph-edge'); path.dataset.runEdgeIndex=edge.index; diff --git a/webtest/tests/runs-detail.test.mjs b/webtest/tests/runs-detail.test.mjs index 7c1a512dc..e7003e83f 100644 --- a/webtest/tests/runs-detail.test.mjs +++ b/webtest/tests/runs-detail.test.mjs @@ -454,9 +454,13 @@ test('run topology keeps independent branches on their own dependency paths', as assert.equal(lane('web-review'), lane('web-test')); assert.ok(lane('api-dev') < lane('design') && lane('design') < lane('web-dev')); assert.equal(lane('design'), lane('integrate')); - const bridge=graph.querySelector('[data-run-edge-source="design"][data-run-edge-target="integrate"]'); - const bridgeY=Number(bridge.getAttribute('d').match(/ V ([0-9.]+) H /)?.[1]); - assert.ok(bridgeY < lane('api-review') && bridgeY < lane('web-review'), 'the edge clears both intermediate lanes'); + const shortcut=graph.querySelector('[data-run-edge-source="design"][data-run-edge-target="integrate"]').getAttribute('d'); + const points=shortcut.split(' ').slice(0,10).filter(token=>token!=='M'&&token!=='C').map(Number); + const [,startY,,controlY1,,controlY2,,endY]=points; + const curveY=(startY+3*controlY1+3*controlY2+endY)/8; + assert.equal((shortcut.match(/ C /g)||[]).length,1,'the clear connection is a single curve'); + assert.ok(curveY>lane('api-review')+Number.parseFloat(card('api-review').style.height)&&curveY { + const app=await loadApp(); + t.after(app.close); + const result=app.evaluate(`(() => { + const positions=new Map([ + ['design',{column:0,left:0,top:46}], + ['backend',{column:1,left:238,top:0}], + ['frontend',{column:1,left:238,top:92}], + ['review',{column:2,left:476,top:0}], + ['test',{column:3,left:714,top:0}], + ['integrate',{column:4,left:952,top:46}], + ]); + const edges=[ + {index:0,source:'frontend',target:'integrate'}, + {index:1,source:'design',target:'integrate'}, + {index:2,source:'backend',target:'integrate'}, + ]; + return [...runGraphLongEdges(edges,positions,192,76).values()]; + })()`); + assert.equal(result[0].bow,0,'the short branch can curve directly to the merge'); + assert.notEqual(result[1].bow,0,'the shortcut has a shallow curve in the middle gap'); + assert.ok(result[2].lane>=81&&result[2].lane<=84,'the obstructed upper link turns into the nearest clear lane'); +}); + test('a graph node that has not started or finished hides the zero default time', async (t) => { const app = await loadApp(); t.after(app.close);