From 2d9eb0b2cddccda3f2267f01d0ec793e4d133b4c Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Fri, 2 Oct 2026 12:28:49 +1000 Subject: [PATCH] fix(workflow): bind the remediate worktree before the builder runs Commit 6ff239ee moved the remediate resume into daemon worktree preparation and deleted StageResumeWorktree together with the Dir/Resume pair it called, but nothing in the workflow replaced the binding it did: TaskContext.Dir and Branch stayed empty for a whole run, so remediate-build ran the builder with no workspace and remediate-commit-push called CommitAll/Push with an empty dir and branch. Extend the workflow-side Trees seam with the prepare target, mirroring the daemon's mode-aware worktree.Manager.Prepare: PrepareFresh lands on base, a non-empty target is the branch a resume continues. Remediate now stages StagePrepareWorktreeOnBranch before any agent stage, binding the same directory the daemon prepared and the task's PR branch, and failing closed when the task has no branch rather than preparing base. The container adapter returns the requested resume target verbatim. Refs archie-core-h4tk --- docs/data/generated/dev-docs.json | 2 +- docs/development/workflows.md | 4 +- internal/app/agentworker/task_execution.go | 10 +- .../app/agentworker/task_execution_test.go | 31 ++++- .../task_execution_workflow_call_test.go | 2 +- internal/domain/workflow/agent_run.go | 2 +- internal/domain/workflow/implement_test.go | 16 ++- internal/domain/workflow/real_trees_test.go | 15 ++- internal/domain/workflow/remediate.go | 10 +- internal/domain/workflow/remediate_test.go | 108 ++++++++++++++++++ internal/domain/workflow/steps.go | 43 ++++++- internal/domain/workflow/workflow.go | 23 +++- 12 files changed, 235 insertions(+), 31 deletions(-) diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index 0c491a3ee..7c267e43b 100644 --- a/docs/data/generated/dev-docs.json +++ b/docs/data/generated/dev-docs.json @@ -154,7 +154,7 @@ "url": "/dev/development/workflows/", "title": "Workflows", "section": "Development", - "body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Retiring a step type\n\nA step word cannot simply be deleted. A stored or pinned definition is\nvalidated as a whole collection, so one unknown word fails EVERY workflow's\ndefinition to decode and the workflow-definitions resource becomes unreadable.\nRetire a stage by removing it from its workflow's `Stages` and adding it to\n`retiredSteps` in `definition.go`, which keeps the word resolving as an inert\nstage. The retired stage must do nothing: the behaviour it used to perform now\nbelongs to whatever layer took it over (the remediate workflow's in-container\nresume moved to daemon worktree preparation, `archie-core-866m`).\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- A declared `outputs:` entry is written through a capture tool, so it forces\n the captures need: `task.WorkflowInterface.Needs` resolves that from the\n declaration rather than the author also writing `needs.captures`. A Kit\n profile whose harness serves no capture tools is refused before dispatch.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n" + "body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Retiring a step type\n\nA step word cannot simply be deleted. A stored or pinned definition is\nvalidated as a whole collection, so one unknown word fails EVERY workflow's\ndefinition to decode and the workflow-definitions resource becomes unreadable.\nRetire a stage by removing it from its workflow's `Stages` and adding it to\n`retiredSteps` in `definition.go`, which keeps the word resolving as an inert\nstage. The retired stage must do nothing: the behaviour it used to perform now\nbelongs to whatever layer took it over (the remediate workflow's in-container\nresume moved to daemon worktree preparation, `archie-core-866m`; the workflow\nstill binds the daemon-prepared directory and the PR branch in a `prepare`\nstage before any agent work).\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- A declared `outputs:` entry is written through a capture tool, so it forces\n the captures need: `task.WorkflowInterface.Needs` resolves that from the\n declaration rather than the author also writing `needs.captures`. A Kit\n profile whose harness serves no capture tools is refused before dispatch.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n" }, { "url": "/dev/prds/01-project-management/", diff --git a/docs/development/workflows.md b/docs/development/workflows.md index f4ca5d50e..e8cb2368f 100644 --- a/docs/development/workflows.md +++ b/docs/development/workflows.md @@ -37,7 +37,9 @@ Retire a stage by removing it from its workflow's `Stages` and adding it to `retiredSteps` in `definition.go`, which keeps the word resolving as an inert stage. The retired stage must do nothing: the behaviour it used to perform now belongs to whatever layer took it over (the remediate workflow's in-container -resume moved to daemon worktree preparation, `archie-core-866m`). +resume moved to daemon worktree preparation, `archie-core-866m`; the workflow +still binds the daemon-prepared directory and the PR branch in a `prepare` +stage before any agent work). ## Changing the definition format diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index f32c9191d..837c9b531 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -50,7 +50,15 @@ type hybridTrees struct { worktreeUID, worktreeGID int } -func (h *hybridTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) { +// Prepare binds the task's already-prepared, bind-mounted worktree. The +// daemon positioned it before the container started, so this resolves the +// directory and branch rather than doing network work. A resume target (the +// PR branch a remediation continues) is returned verbatim; a fresh target uses +// the branch the daemon computed and persisted on the task row. +func (h *hybridTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string, target workflow.PrepareTarget) (dir, branch string, err error) { + if target != workflow.PrepareFresh { + return h.localDir, string(target), nil + } return h.localDir, h.branch, nil } diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 2bb6de88f..f6293e846 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -170,6 +170,31 @@ func TestHybridTreesPushSkipsReconciliationWhenNotConfigured(t *testing.T) { } } +// TestHybridTreesPrepareResolvesTheTargetBranch pins the container half of the +// workflow prepare seam: the daemon has already positioned the bind-mounted +// worktree, so the adapter resolves its directory and returns the requested +// resume target verbatim -- the branch a remediation continues -- while a fresh +// prepare returns the branch the daemon persisted on the task row. +func TestHybridTreesPrepareResolvesTheTargetBranch(t *testing.T) { + trees := &hybridTrees{localDir: "/work/issue-1", branch: "archie/fresh"} + + dir, branch, err := trees.Prepare(t.Context(), "o", "r", "main", 1, "title", "", "", workflow.PrepareTarget("archie/pr-branch")) + if err != nil { + t.Fatalf("Prepare(resume): %v", err) + } + if dir != "/work/issue-1" || branch != "archie/pr-branch" { + t.Fatalf("Prepare(resume) = %q/%q, want /work/issue-1/archie/pr-branch", dir, branch) + } + + dir, branch, err = trees.Prepare(t.Context(), "o", "r", "main", 1, "title", "", "", workflow.PrepareFresh) + if err != nil { + t.Fatalf("Prepare(fresh): %v", err) + } + if dir != "/work/issue-1" || branch != "archie/fresh" { + t.Fatalf("Prepare(fresh) = %q/%q, want /work/issue-1/archie/fresh", dir, branch) + } +} + func TestHybridTreesCommitReconcilesOwnershipEvenWhenCommitFails(t *testing.T) { missing := filepath.Join(t.TempDir(), "does-not-exist") trees := &hybridTrees{ @@ -301,8 +326,8 @@ type remoteManager struct { branch string } -func (r *remoteManager) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (string, string, error) { - dir, branch, err := r.manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Fresh) +func (r *remoteManager) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string, target workflow.PrepareTarget) (string, string, error) { + dir, branch, err := r.manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Target(target)) if err == nil { r.dir = dir r.branch = branch @@ -428,7 +453,7 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { fg := &prCapturingForge{} manager := &worktree.Manager{WorkDir: t.TempDir(), Token: "unused", BotUser: "archie-bot", BotEmail: "archie-bot@example.com", BaseURL: "file://" + host} remote := &remoteManager{manager: manager} - hostDir, _, err := remote.Prepare(ctx, "acme", "widget", "main", 1, task.Title, "", "bootstrap") + hostDir, _, err := remote.Prepare(ctx, "acme", "widget", "main", 1, task.Title, "", "bootstrap", workflow.PrepareFresh) if err != nil { t.Fatalf("prepare: %v", err) } diff --git a/internal/app/agentworker/task_execution_workflow_call_test.go b/internal/app/agentworker/task_execution_workflow_call_test.go index f6b830f52..f4e2af7a4 100644 --- a/internal/app/agentworker/task_execution_workflow_call_test.go +++ b/internal/app/agentworker/task_execution_workflow_call_test.go @@ -34,7 +34,7 @@ type fakeScratchTrees struct { dir string } -func (f *fakeScratchTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) { +func (f *fakeScratchTrees) Prepare(context.Context, string, string, string, int, string, string, string, workflow.PrepareTarget) (string, string, error) { return f.dir, "", nil } diff --git a/internal/domain/workflow/agent_run.go b/internal/domain/workflow/agent_run.go index 69c3f2319..bd9310cd3 100644 --- a/internal/domain/workflow/agent_run.go +++ b/internal/domain/workflow/agent_run.go @@ -59,7 +59,7 @@ func newAgentRunStage(settings yaml.Node) (Stage, error) { }.Stage() return Stage{Name: AgentRunStepName, Run: func(ctx context.Context, tc *TaskContext) error { if tc.Dir == "" { - dir, branch, err := tc.Trees.Prepare(ctx, tc.Task.Owner, tc.Task.Repo, tc.Repo.BaseBranch(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Labels) + dir, branch, err := tc.Trees.Prepare(ctx, tc.Task.Owner, tc.Task.Repo, tc.Repo.BaseBranch(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Labels, PrepareFresh) if err != nil { return fmt.Errorf("%s: workspace: %w", AgentRunStepName, err) } diff --git a/internal/domain/workflow/implement_test.go b/internal/domain/workflow/implement_test.go index 5747291af..f13a794ee 100644 --- a/internal/domain/workflow/implement_test.go +++ b/internal/domain/workflow/implement_test.go @@ -464,6 +464,12 @@ type fakeTrees struct { pushErr error dir string + // prepareBranch is the branch a prepare returns, so a test can model the + // daemon's resume landing the worktree on the task's PR branch. + prepareBranch string + // prepareTarget records the target a prepare was asked for, so a test can + // prove a resume workflow selected the PR branch rather than base. + prepareTarget PrepareTarget // changedLines is what ChangedLines reports, for StageDiffCap. changedLines int // diff is what Diff reports, for the stages that read the committed @@ -477,8 +483,14 @@ type fakeTrees struct { uncommittedErr error } -func (f *fakeTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) { - return f.dir, "", nil +func (f *fakeTrees) Prepare(_ context.Context, _, _, _ string, _ int, _, _, _ string, target PrepareTarget) (string, string, error) { + f.prepareTarget = target + // A resume target is the branch to land on, mirroring hybridTrees; a fresh + // prepare returns the branch this fake was configured with. + if target != PrepareFresh { + return f.dir, string(target), nil + } + return f.dir, f.prepareBranch, nil } func (f *fakeTrees) CommitAll(context.Context, string, string) (bool, error) { diff --git a/internal/domain/workflow/real_trees_test.go b/internal/domain/workflow/real_trees_test.go index c10cbe01a..96c51dea2 100644 --- a/internal/domain/workflow/real_trees_test.go +++ b/internal/domain/workflow/real_trees_test.go @@ -7,14 +7,13 @@ import ( ) // realTrees adapts a real worktree.Manager to the workflow's Trees contract for -// the tests that drive a stage against a real clone. Manager.Prepare carries -// the daemon's prepare target -- worktree.Fresh for a run that starts new work -// -- which the workflow's Trees contract deliberately does not expose, so the -// manager no longer satisfies Trees directly. Embedding keeps every other -// method; these tests never call Prepare, they only need the manager's git -// reads (Diff, ChangedFiles, ChangedFileStats). +// the tests that drive a stage against a real clone. The workflow's PrepareTarget +// and the manager's worktree.Target are the same choice spelled in two packages +// (workflow cannot import infrastructure), so the adapter maps one onto the +// other. Embedding keeps every other method; these tests never call Prepare, +// they only need the manager's git reads (Diff, ChangedFiles, ChangedFileStats). type realTrees struct{ *worktree.Manager } -func (t realTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (string, string, error) { - return t.Manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Fresh) +func (t realTrees) Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string, target PrepareTarget) (string, string, error) { + return t.Manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Target(target)) } diff --git a/internal/domain/workflow/remediate.go b/internal/domain/workflow/remediate.go index 522e61105..4d5d9c3e6 100644 --- a/internal/domain/workflow/remediate.go +++ b/internal/domain/workflow/remediate.go @@ -270,15 +270,19 @@ func StageRemediationReply() Stage { // Remediate runs one remediation round against an archie-owned, still-open // pull request in response to a forge review reaction // (docs/prds/pr-review-remediation.md decision 4). It reuses the task's -// existing worktree and branch rather than opening a new PR: the worktree is -// positioned onto the PR branch by daemon.prepareWorkspace before the container -// starts, so there is no in-container resume stage. +// existing worktree and branch rather than opening a new PR. The daemon +// positions the worktree onto the PR branch before the container starts +// (prepareWorkspace), and StagePrepareWorktreeOnBranch then binds that +// directory and branch onto the task context before any agent work -- without +// it remediate-build ran with an empty tc.Dir and remediate-commit-push pushed +// an empty branch. func Remediate() Workflow { return Workflow{ Name: "remediate", Stages: []Stage{ StageCheckReviewPayload(), StageRemediationRoundCap(), + StagePrepareWorktreeOnBranch(), remediateBuildStage(), StageRemediationCommitPush(), StageRemediationReply(), diff --git a/internal/domain/workflow/remediate_test.go b/internal/domain/workflow/remediate_test.go index 65aed77d4..0b022d7b8 100644 --- a/internal/domain/workflow/remediate_test.go +++ b/internal/domain/workflow/remediate_test.go @@ -170,6 +170,114 @@ func TestStageRemediationReplyFallsBackToAPlainCommentForABareReview(t *testing. } } +func TestStagePrepareWorktreeOnBranchRequiresABranch(t *testing.T) { + tc := &TaskContext{Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5}, Trees: &fakeTrees{}} + if err := StagePrepareWorktreeOnBranch().Run(t.Context(), tc); err == nil { + t.Fatal("StagePrepareWorktreeOnBranch with no branch = nil error, want a fail-closed error") + } +} + +func TestStagePrepareWorktreeOnBranchBindsThePRBranch(t *testing.T) { + trees := &fakeTrees{dir: "/worktrees/o-r-5", prepareBranch: "unused/fresh"} + tc := &TaskContext{ + Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5, Branch: "archie/issue-5"}, + Trees: trees, + } + if err := StagePrepareWorktreeOnBranch().Run(t.Context(), tc); err != nil { + t.Fatalf("StagePrepareWorktreeOnBranch: %v", err) + } + if trees.prepareTarget != "archie/issue-5" { + t.Fatalf("prepare target = %q, want the task branch archie/issue-5", trees.prepareTarget) + } + if tc.Dir != "/worktrees/o-r-5" || tc.Branch != "archie/issue-5" { + t.Fatalf("tc.Dir/Branch = %q/%q, want /worktrees/o-r-5/archie/issue-5", tc.Dir, tc.Branch) + } + if tc.Task.Branch != "archie/issue-5" { + t.Fatalf("tc.Task.Branch = %q, want archie/issue-5", tc.Task.Branch) + } +} + +func TestStagePrepareWorktreePreparesFresh(t *testing.T) { + trees := &fakeTrees{dir: "/worktrees/o-r-5", prepareBranch: "archie/issue-5"} + tc := &TaskContext{Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5}, Trees: trees} + if err := StagePrepareWorktree().Run(t.Context(), tc); err != nil { + t.Fatalf("StagePrepareWorktree: %v", err) + } + if trees.prepareTarget != PrepareFresh { + t.Fatalf("prepare target = %q, want the fresh target", trees.prepareTarget) + } + if tc.Dir != "/worktrees/o-r-5" || tc.Branch != "archie/issue-5" { + t.Fatalf("tc.Dir/Branch = %q/%q, want /worktrees/o-r-5/archie/issue-5", tc.Dir, tc.Branch) + } +} + +// TestRemediateBindsItsWorktreeBeforeTheBuilderRuns is the release-blocker +// regression for a remediate run that never bound its worktree. The +// in-container resume stage was retired in favour of daemon-side preparation, +// but nothing in the workflow resolved the directory the daemon prepared and +// the branch its pull request lives on. The builder therefore ran with an empty +// Dir and the final stage pushed an empty branch. +func TestRemediateBindsItsWorktreeBeforeTheBuilderRuns(t *testing.T) { + const ( + prBranch = "archie/issue-1" + worktree = "/worktrees/o-r-1" + ) + trees := &fakeTrees{dir: worktree, prepareBranch: prBranch, commitAllChanged: true} + forge := &fakeForge{} + payload, err := EncodeReviewUnit(ReviewUnit{ + ReviewID: 1, State: "requested_changes", + Comments: []ReviewUnitComment{{CommentID: 10, Path: "a.go", Line: 4, Body: "nil check missing"}}, + }) + if err != nil { + t.Fatalf("EncodeReviewUnit: %v", err) + } + task := &Task{ + ID: 1, Owner: "o", Repo: "r", IssueNumber: 1, PRNumber: 9, + Branch: prBranch, ReviewPayload: payload, + } + var builderDir string + runner := agentRunnerFunc(func(_ context.Context, dir string, req agentexec.Request, _ agentexec.ToolCallReporter) (agentexec.Result, error) { + builderDir = dir + return agentexec.Result{ + Version: agentexec.ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, Stage: req.Stage, + Status: agentexec.StatusPassed, Summary: "added the nil check", Changes: []string{"a.go"}, + }, nil + }) + tc := &TaskContext{ + Task: task, Repo: config.Repo{Owner: "o", Name: "r", MaxRetries: 3}, + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + Agent: runner, Trees: trees, Forge: forge, Log: slog.New(slog.DiscardHandler), + } + + for _, stage := range Remediate().Stages { + if err := stage.Run(t.Context(), tc); err != nil { + t.Fatalf("stage %s: %v", stage.Name, err) + } + if tc.Outcome.Status != "" { + break + } + } + + if tc.Dir == "" { + t.Fatal("remediate left tc.Dir empty: no stage bound the task's worktree") + } + if tc.Dir != worktree { + t.Fatalf("tc.Dir = %q, want the prepared worktree %q", tc.Dir, worktree) + } + if tc.Branch != prBranch { + t.Fatalf("tc.Branch = %q, want the task's PR branch %q", tc.Branch, prBranch) + } + if builderDir != worktree { + t.Fatalf("builder ran with dir %q, want the bound worktree %q", builderDir, worktree) + } + if trees.pushBranch != prBranch { + t.Fatalf("pushed branch = %q, want the task's PR branch %q", trees.pushBranch, prBranch) + } + if trees.prepareTarget != PrepareTarget(prBranch) { + t.Fatalf("prepare target = %q, want the task's PR branch %q (a fresh prepare would have reset onto base)", trees.prepareTarget, prBranch) + } +} + func TestRemediateEndToEndAddressesCommentsAndReplies(t *testing.T) { trees := &fakeTrees{dir: "/worktrees/o-r-1", commitAllChanged: true} forge := &fakeForge{} diff --git a/internal/domain/workflow/steps.go b/internal/domain/workflow/steps.go index d58055aba..1f717475f 100644 --- a/internal/domain/workflow/steps.go +++ b/internal/domain/workflow/steps.go @@ -104,12 +104,45 @@ func changeCaptureData(tc *TaskContext, after string, stats task.ChangeStats) ma } } -// StagePrepareWorktree clones the repo fresh and checks out the task -// branch. Skips if the daemon already prepared the worktree (Docker -// containers require the tree before acquire). +// StagePrepareWorktree binds the task's worktree for a fresh run: it positions +// it onto the repository's base branch. Skips if the daemon already prepared +// the worktree (Docker containers require the tree before acquire); in a +// container the adapter resolves the directory the daemon prepared. func StagePrepareWorktree() Stage { - return Stage{Name: "prepare", Run: func(ctx context.Context, tc *TaskContext) error { - dir, branch, err := tc.Trees.Prepare(ctx, tc.Task.Owner, tc.Task.Repo, tc.Repo.BaseBranch(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Labels) + return prepareWorktreeStage("prepare", func(*TaskContext) (PrepareTarget, error) { + return PrepareFresh, nil + }) +} + +// StagePrepareWorktreeOnBranch binds the task's worktree on the branch its +// already-open pull request lives on -- the resume target -- for a workflow +// that continues pushed work rather than starting fresh +// (docs/prds/pr-review-remediation.md decision 4). The branch is the task's +// persisted branch, never recomputed from the title: the PR was opened from +// that branch, and a retitled issue would otherwise name one that does not +// exist. It resolves the same directory the daemon's mode-aware prepare +// resolved and positions it on the same branch, because the daemon has already +// done the fetch before the container starts; this stage only binds +// tc.Dir/tc.Branch. An empty branch fails closed rather than silently +// preparing base. +func StagePrepareWorktreeOnBranch() Stage { + return prepareWorktreeStage("prepare", func(tc *TaskContext) (PrepareTarget, error) { + if tc.Task.Branch == "" { + return "", fmt.Errorf("prepare: remediate task has no branch to resume") + } + return PrepareTarget(tc.Task.Branch), nil + }) +} + +// prepareWorktreeStage builds a stage that prepares the task's worktree at the +// target its workflow selects and binds the result onto the task context. +func prepareWorktreeStage(name string, target func(*TaskContext) (PrepareTarget, error)) Stage { + return Stage{Name: name, Run: func(ctx context.Context, tc *TaskContext) error { + t, err := target(tc) + if err != nil { + return err + } + dir, branch, err := tc.Trees.Prepare(ctx, tc.Task.Owner, tc.Task.Repo, tc.Repo.BaseBranch(), tc.Task.IssueNumber, tc.Task.Title, tc.Task.Body, tc.Task.Labels, t) if err != nil { return err } diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 8ee0ccd10..4762eb95b 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -65,12 +65,25 @@ type ReviewComment struct { Body string } -// Trees is the subset of *worktree.Manager that workflow stages call -// mid-run. *worktree.Manager (the daemon's real manager, holding the push -// token) and a hybrid RPC-backed implementation (archie-agent proxies -// Prepare/Push, runs the rest locally) both satisfy it. +// PrepareTarget selects where a prepare stage positions the task's worktree, +// mirroring the daemon's worktree.Target: the zero value prepares fresh onto +// the base branch, and a non-empty target is the branch a resume lands on -- +// the branch an open pull request lives on. It travels through the seam rather +// than being recomputed from the title, because a retitled issue would +// otherwise name a branch that does not exist. +type PrepareTarget string + +// PrepareFresh is the fresh-run target: position the worktree onto the base +// branch. +const PrepareFresh PrepareTarget = "" + +// Trees is the subset of the daemon's worktree.Manager that workflow stages +// call mid-run. The production implementation is archie-agent's hybrid adapter +// (hybridTrees): the daemon prepares the worktree before the container starts, +// so the adapter's Prepare resolves the directory the daemon prepared and its +// branch. type Trees interface { - Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string) (dir, branch string, err error) + Prepare(ctx context.Context, owner, repo, base string, issue int, title, body, labels string, target PrepareTarget) (dir, branch string, err error) CommitAll(ctx context.Context, dir, message string) (bool, error) Push(ctx context.Context, dir, branch string) error Diff(ctx context.Context, dir, base string) (string, error)