diff --git a/docs/data/generated/dev-docs.json b/docs/data/generated/dev-docs.json index edd687905..b65f073c8 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## 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`).\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 d6ab1f52d..f4ca5d50e 100644 --- a/docs/development/workflows.md +++ b/docs/development/workflows.md @@ -28,6 +28,17 @@ vocabulary it registers, so both must see the same step types. 6. Add a parse test (settings accepted and refused) and a run test with fake `Trees` and agent runner. +## Retiring a step type + +A step word cannot simply be deleted. A stored or pinned definition is +validated as a whole collection, so one unknown word fails EVERY workflow's +definition to decode and the workflow-definitions resource becomes unreadable. +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`). + ## Changing the definition format - The fields a caller needs without the engine (inputs, repository, profile) diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index cfdf3026c..0f65996c3 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -107,22 +107,6 @@ func (h *hybridTrees) Snapshot(ctx context.Context, dir, destDir string) error { return h.local.Snapshot(ctx, dir, destDir) } -// Resume is a no-op here for the same reason Prepare is: resuming a PR -// branch needs the daemon's forge credential to fetch, so archied must run -// it against the bind-mounted worktree before the container starts, the -// same way it runs Prepare today. The container's worktree is already -// resumed by the time a remediate run reaches this stage. -func (h *hybridTrees) Resume(ctx context.Context, dir, branch string) error { - return nil -} - -// Dir returns the bind-mounted worktree path archied already prepared, -// ignoring its arguments -- the sandbox has no way to independently derive -// or verify the path, same as Prepare above. -func (h *hybridTrees) Dir(owner, repo string, issue int) string { - return h.localDir -} - func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, error) { return h.local.ChangedLines(ctx, dir, base) } diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 88ce1c0dc..2bb6de88f 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -302,7 +302,7 @@ type remoteManager struct { } 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) + dir, branch, err := r.manager.Prepare(ctx, owner, repo, base, issue, title, body, labels, worktree.Fresh) if err == nil { r.dir = dir r.branch = branch @@ -634,7 +634,7 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) { BotEmail: "archie-bot@example.com", BaseURL: "file://" + host, } - hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "rpc-widget", "main", 2, task.Title, "", "bootstrap") + hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "rpc-widget", "main", 2, task.Title, "", "bootstrap", worktree.Fresh) if err != nil { t.Fatal(err) } @@ -726,7 +726,7 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) { BotEmail: "archie-bot@example.com", BaseURL: "file://" + host, } - hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "events-widget", "main", 3, task.Title, "", "bootstrap") + hostDir, branch, err := daemonTrees.Prepare(ctx, "acme", "events-widget", "main", 3, task.Title, "", "bootstrap", worktree.Fresh) if err != nil { t.Fatal(err) } @@ -919,7 +919,7 @@ func TestHybridTreesForwardsChangedFileStatsToItsLocalManager(t *testing.T) { WorkDir: t.TempDir(), Token: "unused", BotUser: "archie-bot", BotEmail: "archie-bot@example.com", BaseURL: "file://" + host, } - dir, branch, err := manager.Prepare(ctx, "acme", "diffstat", "main", 4, "feat: widget", "", "") + dir, branch, err := manager.Prepare(ctx, "acme", "diffstat", "main", 4, "feat: widget", "", "", worktree.Fresh) if err != nil { t.Fatalf("prepare: %v", err) } diff --git a/internal/daemon/architecture_test.go b/internal/daemon/architecture_test.go index b0f57e072..f5c70f2a9 100644 --- a/internal/daemon/architecture_test.go +++ b/internal/daemon/architecture_test.go @@ -136,7 +136,9 @@ func TestDaemonPreparesWorktreesFromTheMappedBaseBranch(t *testing.T) { } ast.Inspect(file, func(node ast.Node) bool { call, ok := node.(*ast.CallExpr) - if !ok || len(call.Args) != 8 { + // Prepare carries owner, repo, base, issue, title, body, labels and + // the daemon's prepare target: nine arguments. + if !ok || len(call.Args) != 9 { return true } selector, ok := call.Fun.(*ast.SelectorExpr) diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index bc6fcc2f8..6929d2d34 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1485,25 +1485,42 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree } return dir, true } - // A task that continues an already-open PR branch -- the remediate - // workflow -- resumes that branch's remote tip instead of resetting onto - // base. Preparing one the ordinary way discarded the commits the implement - // run had already pushed, so the agent remediated a PR from a tree that no - // longer contained it. This runs before Acquire, because the daemon holds - // the forge credential that fetches the branch and the container must find - // the PR's work already in place. + // The retry path selects the worktree mode from the task row. A task that + // continues an already-open PR branch -- the remediate workflow -- resumes + // that branch's remote tip instead of resetting onto base: preparing one + // the ordinary way discarded the commits the implement run had already + // pushed, so the agent remediated a PR from a tree that no longer contained + // it. Every other task starts fresh on base. This runs before Acquire, + // because the daemon holds the forge credential that fetches the branch and + // the container must find the PR's work already in place. It also runs on a + // retry whose local worktree is gone: Prepare clones a missing worktree for + // either target, which is how a resume reaches a task whose clone the + // terminal cleanup removed. + target := worktree.Fresh if continuesOpenPRBranch(task) { - return d.resumePRBranchWorkspace(ctx, task, trees) + if task.Branch == "" { + // A remediation task is queued against the branch its implement + // run pushed, so an empty branch is a dispatch bug upstream and no + // retry can fix it. + d.Log.Error("remediate task has no persisted branch", "task", task.ID) + d.parkRunningTask(ctx, task.ID, "worktree resume failed: remediate task has no branch to resume", taskstate.ParkNeedsHuman) + return "", false + } + target = worktree.Target(task.Branch) } // Every task gets an independent full clone. The former // PreparePersistent path shared objects with a per-repo bare cache; // go-git has no --dissociate, so a shared cache would stay a live // dependency of each worktree and expiring one would corrupt running // tasks. repo.PersistentStorage still governs the container volume. - dir, branch, err := trees.Prepare(ctx, task.Owner, task.Repo, repo.BaseBranch(), task.IssueNumber, task.Title, task.Body, task.Labels) + dir, branch, err := trees.Prepare(ctx, task.Owner, task.Repo, repo.BaseBranch(), task.IssueNumber, task.Title, task.Body, task.Labels, target) if err != nil { - d.Log.Error("worktree prepare failed", "err", err) - d.parkRunningTask(ctx, task.ID, "worktree prepare failed: "+err.Error(), taskstate.ParkTransient) + reason := "worktree prepare failed: " + err.Error() + if target != worktree.Fresh { + reason = "worktree resume failed: " + err.Error() + } + d.Log.Error("worktree prepare failed", "task", task.ID, "err", err) + d.parkRunningTask(ctx, task.ID, reason, taskstate.ParkTransient) return "", false } task.Branch = branch @@ -1524,30 +1541,6 @@ func continuesOpenPRBranch(task *workflow.Task) bool { return task.Workflow == "remediate" } -// resumePRBranchWorkspace prepares a task's worktree on the branch its row -// names, never on a branch recomputed from the title or labels: the PR was -// opened from the persisted branch, and a retitled issue or relabelled task -// would otherwise name a branch that does not exist. It fails closed -- there -// is deliberately no fallback to preparing base, because that fallback is the -// defect this route removes. -func (d *Daemon) resumePRBranchWorkspace(ctx context.Context, task *workflow.Task, trees *worktree.Manager) (string, bool) { - if task.Branch == "" { - // A remediation task is queued against the branch its implement run - // pushed, so an empty branch is a dispatch bug upstream and no retry - // can fix it. - d.Log.Error("remediate task has no persisted branch", "task", task.ID) - d.parkRunningTask(ctx, task.ID, "worktree resume failed: remediate task has no branch to resume", taskstate.ParkNeedsHuman) - return "", false - } - dir := trees.Dir(task.Owner, task.Repo, task.IssueNumber) - if err := trees.Resume(ctx, dir, task.Branch); err != nil { - d.Log.Error("worktree resume failed", "task", task.ID, "branch", task.Branch, "err", err) - d.parkRunningTask(ctx, task.ID, "worktree resume failed: "+err.Error(), taskstate.ParkTransient) - return "", false - } - return dir, true -} - // cleanupTerminalTaskWorktree removes a task's worktree once its forge side is // settled, unless the worktree still holds work no commit captured. // diff --git a/internal/daemon/prepare_workspace_test.go b/internal/daemon/prepare_workspace_test.go index 897b0f619..f9129c122 100644 --- a/internal/daemon/prepare_workspace_test.go +++ b/internal/daemon/prepare_workspace_test.go @@ -23,7 +23,7 @@ import ( func pushedImplementRun(t *testing.T, trees *worktree.Manager, title string) (dir, branch string, tip plumbing.Hash) { t.Helper() ctx := context.Background() - dir, branch, err := trees.Prepare(ctx, "acme", "widget", "main", 7, title, "", "bug") + dir, branch, err := trees.Prepare(ctx, "acme", "widget", "main", 7, title, "", "bug", worktree.Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -116,6 +116,42 @@ func TestPrepareWorkspaceResumesThePersistedBranchForARemediation(t *testing.T) } } +// TestPrepareWorkspaceResumesAPRBranchAfterTheWorktreeWasRemoved pins the +// retry failure archie-core-866m reports. Manager.Resume opens an +// already-prepared worktree, so a remediation whose local clone is gone -- a +// first run on this host, an expired volume, a worktree the terminal cleanup +// removed before a retry -- can never be resumed, and the retry path offers +// only fresh-from-base or that unrunnable resume. Preparing a resume must +// clone when the worktree is missing, exactly as a fresh prepare does, and +// land on the PR branch tip rather than base. +func TestPrepareWorkspaceResumesAPRBranchAfterTheWorktreeWasRemoved(t *testing.T) { + ctx := context.Background() + trees := newTestTrees(t, newLocalRemote(t, "acme", "widget")) + dir, branch, tip := pushedImplementRun(t, trees, "fix: original issue") + + // The clone is gone before the retry reaches prepareWorkspace. + if err := os.RemoveAll(dir); err != nil { + t.Fatalf("remove worktree: %v", err) + } + + d, st, _ := testDaemon(t, 3, 0) + task := claimedTask(t, st, "fix: original issue", "remediate", branch) + + gotDir, ok := d.prepareWorkspace(ctx, task, trees, config.Repo{Owner: "acme", Name: "widget", Base: "main"}) + if !ok { + t.Fatal("prepareWorkspace() = false, want the remediation prepared on its PR branch after the worktree was removed") + } + if gotDir != dir { + t.Errorf("prepareWorkspace() dir = %q, want the task's worktree %q", gotDir, dir) + } + if _, err := os.Stat(filepath.Join(gotDir, "widget.go")); err != nil { + t.Fatalf("widget.go missing after prepare: %v (the PR branch's work was not restored)", err) + } + if got := headOf(t, gotDir); got != tip { + t.Errorf("worktree HEAD = %s, want the PR branch tip %s", got, tip) + } +} + // TestPrepareWorkspaceFailsClosedWhenTheRemediationBranchIsGone pins the other // half of the same routing: a remediation whose branch is not on the remote // must park, not quietly fall back to preparing base -- the fallback is exactly diff --git a/internal/daemon/task_cancellation_test.go b/internal/daemon/task_cancellation_test.go index 8537536d0..ee4e202f9 100644 --- a/internal/daemon/task_cancellation_test.go +++ b/internal/daemon/task_cancellation_test.go @@ -276,7 +276,7 @@ func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) { // A prepared clone: the cancelled context is the thing under test, // so the worktree itself is readied with a live one. if _, _, err := trees.Prepare(context.Background(), task.Owner, task.Repo, "main", - task.IssueNumber, task.Title, task.Body, task.Labels); err != nil { + task.IssueNumber, task.Title, task.Body, task.Labels, worktree.Fresh); err != nil { t.Fatalf("prepare worktree: %v", err) } diff --git a/internal/daemon/terminal_cleanup_test.go b/internal/daemon/terminal_cleanup_test.go index d1f78c4bb..03d8856a4 100644 --- a/internal/daemon/terminal_cleanup_test.go +++ b/internal/daemon/terminal_cleanup_test.go @@ -248,7 +248,7 @@ func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) { workDir := targetTrees.Dir(claimed.Owner, claimed.Repo, claimed.IssueNumber) // A prepared clone, the only shape the daemon ever cleans up. if _, _, err := targetTrees.Prepare(ctx, claimed.Owner, claimed.Repo, "main", - claimed.IssueNumber, claimed.Title, claimed.Body, claimed.Labels); err != nil { + claimed.IssueNumber, claimed.Title, claimed.Body, claimed.Labels, worktree.Fresh); err != nil { t.Fatalf("prepare worktree: %v", err) } if tt.uncommitted { diff --git a/internal/domain/workflow/definition.go b/internal/domain/workflow/definition.go index 402329efb..f280904a1 100644 --- a/internal/domain/workflow/definition.go +++ b/internal/domain/workflow/definition.go @@ -188,6 +188,20 @@ func noSettingsFactory(stage Stage) StepFactory { } } +// retiredSteps are step types no shipped workflow names any more but that must +// keep resolving. A stored workflow definition is validated as a whole +// collection, so a word dropped from the vocabulary does not merely fail its +// own step -- it fails every workflow's definition to decode, taking the whole +// workflow-definitions resource down with it. Each entry is inert by +// construction: the behaviour its stage used to perform has another owner now, +// and it exists only so a definition pinned or stored before that move still +// parses and compiles. +var retiredSteps = map[string]Stage{ + // The remediate workflow's in-container resume stage moved to daemon + // preparation (archie-core-866m); see retiredResumeStep. + "remediate.resume": retiredResumeStep(), +} + // BuiltinStepRegistry exposes every shipped stage as a typed, non-interpreted step. func BuiltinStepRegistry() StepRegistry { registry := StepRegistry{} @@ -196,6 +210,9 @@ func BuiltinStepRegistry() StepRegistry { registry[id+"."+stage.Name] = noSettingsFactory(stage) } } + for name, stage := range retiredSteps { + registry[name] = noSettingsFactory(stage) + } return registry } diff --git a/internal/domain/workflow/definition_test.go b/internal/domain/workflow/definition_test.go index f70377f55..b111d217b 100644 --- a/internal/domain/workflow/definition_test.go +++ b/internal/domain/workflow/definition_test.go @@ -134,3 +134,28 @@ func TestShippedDefinitionsPreserveStageOrder(t *testing.T) { } } } + +// TestRetiredStepTypeStillCompiles pins the compatibility contract for a step +// word retired from a shipped workflow (archie-core-866m). A stored definition +// is validated as a whole collection, so one unknown step type fails EVERY +// workflow's definition to decode, taking the workflow-definitions resource +// down with it. A definition pinned or stored before the retire must therefore +// keep parsing, compiling, and running -- and the retired stage itself must be +// inert, because the behaviour it used to perform now happens before the +// container starts. +func TestRetiredStepTypeStillCompiles(t *testing.T) { + src := "id: remediate\nsteps:\n - type: remediate.check-review-payload\n - type: remediate.resume\n" + wf, err := ParseAndCompile(src, BuiltinStepRegistry()) + if err != nil { + t.Fatalf("ParseAndCompile(a stored definition naming a retired step): %v", err) + } + if len(wf.Stages) != 2 { + t.Fatalf("stages = %d, want 2", len(wf.Stages)) + } + if wf.Stages[1].Name != "resume" { + t.Fatalf("stage 2 = %q, want the retired resume stage", wf.Stages[1].Name) + } + if err := wf.Stages[1].Run(t.Context(), &TaskContext{Task: &Task{}}); err != nil { + t.Fatalf("the retired resume stage is not inert: %v", err) + } +} diff --git a/internal/domain/workflow/diff_rules_test.go b/internal/domain/workflow/diff_rules_test.go index 6f419644a..18d4fd545 100644 --- a/internal/domain/workflow/diff_rules_test.go +++ b/internal/domain/workflow/diff_rules_test.go @@ -514,7 +514,7 @@ func TestDiffRulesStepReadsARealDiff(t *testing.T) { } var log bytes.Buffer tc := diffRulesTestTaskContext(t, dir, &log) - tc.Trees = &worktree.Manager{WorkDir: t.TempDir()} + tc.Trees = &realTrees{Manager: &worktree.Manager{WorkDir: t.TempDir()}} if err := stage.Run(context.Background(), tc); err != nil { t.Fatalf("stage.Run(): %v", err) diff --git a/internal/domain/workflow/implement_test.go b/internal/domain/workflow/implement_test.go index a4ee7f10a..5747291af 100644 --- a/internal/domain/workflow/implement_test.go +++ b/internal/domain/workflow/implement_test.go @@ -36,7 +36,7 @@ func TestStageBaselineGateAccountsForRepairAgentUsage(t *testing.T) { tc := &TaskContext{ Task: task, Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, - Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}, + Agent: runner, Trees: &realTrees{Manager: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}}, Dir: dir, Log: slog.New(slog.DiscardHandler), } if err := StageBaselineGate().Run(t.Context(), tc); err != nil { @@ -154,7 +154,7 @@ func TestStageBaselineGateMissionOmitsPassingPackageOutput(t *testing.T) { Task: &Task{ID: 1, Owner: "o", Repo: "r"}, Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, - Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}, + Agent: runner, Trees: &realTrees{Manager: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}}, Dir: dir, Log: slog.New(slog.DiscardHandler), } if err := StageBaselineGate().Run(t.Context(), tc); err != nil { @@ -193,7 +193,7 @@ func TestStageBaselineGateSetsBaselineFixedWhenItCommits(t *testing.T) { tc := &TaskContext{ Task: task, Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, - Agent: runner, Trees: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}, + Agent: runner, Trees: &realTrees{Manager: &worktree.Manager{BotUser: "archie", BotEmail: "archie@example.com"}}, Dir: dir, Log: slog.New(slog.DiscardHandler), } if err := StageBaselineGate().Run(t.Context(), tc); err != nil { @@ -475,11 +475,6 @@ type fakeTrees struct { // change" from "not committed yet". The zero value is a clean worktree. uncommitted bool uncommittedErr error - - resumed bool - resumeDir string - resumeBranch string - resumeErr error } func (f *fakeTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) { @@ -513,13 +508,6 @@ func (f *fakeTrees) ChangedLines(context.Context, string, string) (int, error) { func (f *fakeTrees) Snapshot(context.Context, string, string) error { return nil } -func (f *fakeTrees) Resume(_ context.Context, dir, branch string) error { - f.resumed, f.resumeDir, f.resumeBranch = true, dir, branch - return f.resumeErr -} - -func (f *fakeTrees) Dir(string, string, int) string { return f.dir } - // TestStageCommitPushPushesBaselineFixEvenWithNothingNewToCommit is the // regression case for archie-core-95dj: StageBaselineGate already // committed a real, gate-verified fix for a pre-existing failure, and the diff --git a/internal/domain/workflow/real_trees_test.go b/internal/domain/workflow/real_trees_test.go new file mode 100644 index 000000000..c10cbe01a --- /dev/null +++ b/internal/domain/workflow/real_trees_test.go @@ -0,0 +1,20 @@ +package workflow + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/worktree" +) + +// 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). +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) +} diff --git a/internal/domain/workflow/remediate.go b/internal/domain/workflow/remediate.go index 8c15b8183..522e61105 100644 --- a/internal/domain/workflow/remediate.go +++ b/internal/domain/workflow/remediate.go @@ -115,42 +115,18 @@ func orUnknown(s string) string { // other clipped park reasons in this package. const remediationRoundCapBytes = 2000 -// resumableTrees is the optional capability a Trees implementation offers -// for continuing work on an already-open PR branch instead of starting a -// fresh worktree. It stays separate because Trees is already at the interface -// size cap and most workflow stages do not need branch resumption. -// -// *worktree.Manager (real git access) and the container-mode hybrid -// implementation both already satisfy this structurally; a Trees -// implementation that doesn't (a narrower test fake, say) simply cannot run -// the remediate workflow, which StageResumeWorktree reports plainly. -type resumableTrees interface { - Dir(owner, repo string, issue int) string - Resume(ctx context.Context, dir, branch string) error -} - -// StageResumeWorktree re-syncs the task's already-prepared worktree onto -// its PR branch's remote tip, so the remediate workflow continues on the -// branch the implement run pushed instead of resetting to base the way -// StagePrepareWorktree's refresh would (docs/prds/pr-review-remediation.md -// decision 4). A remediate task always has a branch: it only ever runs -// against a PR archie itself opened. -func StageResumeWorktree() Stage { - return Stage{Name: "resume", Run: func(ctx context.Context, tc *TaskContext) error { - if tc.Task.Branch == "" { - return fmt.Errorf("remediate: task has no branch to resume") - } - rt, ok := tc.Trees.(resumableTrees) - if !ok { - return fmt.Errorf("remediate: this worktree implementation cannot resume a PR branch") - } - dir := rt.Dir(tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber) - if err := rt.Resume(ctx, dir, tc.Task.Branch); err != nil { - return fmt.Errorf("resume worktree onto %s: %w", tc.Task.Branch, err) - } - tc.Dir, tc.Branch = dir, tc.Task.Branch - return nil - }} +// retiredResumeStep is the remediate workflow's old in-container resume stage, +// kept as an inert word in the step vocabulary. The resume it used to perform +// now happens in daemon.prepareWorkspace before the container starts +// (archie-core-866m): the daemon holds the forge credential that fetches the +// branch and positions the worktree onto origin/, so by the time a +// container-side stage could run there is nothing left to do. It is +// deliberately not a stage of Remediate() any more -- a new definition never +// names it -- but a definition pinned or stored before that move still does, +// and a step word removed from the vocabulary fails every workflow's +// definition to decode, not just its own. +func retiredResumeStep() Stage { + return Stage{Name: "resume", Run: func(context.Context, *TaskContext) error { return nil }} } // StageRemediationRoundCap enforces the hard stop on an unbounded @@ -294,14 +270,15 @@ 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. +// 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. func Remediate() Workflow { return Workflow{ Name: "remediate", Stages: []Stage{ StageCheckReviewPayload(), StageRemediationRoundCap(), - StageResumeWorktree(), remediateBuildStage(), StageRemediationCommitPush(), StageRemediationReply(), diff --git a/internal/domain/workflow/remediate_test.go b/internal/domain/workflow/remediate_test.go index f148975cc..65aed77d4 100644 --- a/internal/domain/workflow/remediate_test.go +++ b/internal/domain/workflow/remediate_test.go @@ -42,31 +42,6 @@ func TestStageCheckReviewPayloadFailsOnEmptyPayload(t *testing.T) { } } -func TestStageResumeWorktreeRequiresABranch(t *testing.T) { - tc := &TaskContext{Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5}, Trees: &fakeTrees{}} - if err := StageResumeWorktree().Run(t.Context(), tc); err == nil { - t.Fatal("StageResumeWorktree with no branch = nil error, want an error") - } -} - -func TestStageResumeWorktreeResumesOntoTheTaskBranch(t *testing.T) { - trees := &fakeTrees{dir: "/worktrees/o-r-5"} - tc := &TaskContext{ - Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 5, Branch: "archie/issue-5"}, - Trees: trees, - } - if err := StageResumeWorktree().Run(t.Context(), tc); err != nil { - t.Fatalf("StageResumeWorktree: %v", err) - } - if !trees.resumed || trees.resumeDir != "/worktrees/o-r-5" || trees.resumeBranch != "archie/issue-5" { - t.Fatalf("Resume call = resumed=%v dir=%q branch=%q, want true /worktrees/o-r-5 archie/issue-5", - trees.resumed, trees.resumeDir, trees.resumeBranch) - } - 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) - } -} - func TestStageRemediationRoundCapCountsARoundUnderTheCap(t *testing.T) { forge := &fakeForge{} tc := &TaskContext{ @@ -231,9 +206,6 @@ func TestRemediateEndToEndAddressesCommentsAndReplies(t *testing.T) { } } - if !trees.resumed { - t.Fatal("worktree was never resumed") - } if !trees.pushed { t.Fatal("remediation commit was never pushed") } diff --git a/internal/domain/workflow/steps_test.go b/internal/domain/workflow/steps_test.go index 7a3a37959..11213809e 100644 --- a/internal/domain/workflow/steps_test.go +++ b/internal/domain/workflow/steps_test.go @@ -71,7 +71,7 @@ func newYaegiGateTaskContext(t *testing.T, dir string) *TaskContext { return &TaskContext{ Task: &Task{ID: 1, Owner: "acme", Repo: "todo", IssueNumber: 42}, Repo: config.Repo{Owner: "acme", Name: "todo", Base: "main"}, - Trees: &worktree.Manager{WorkDir: t.TempDir()}, + Trees: &realTrees{Manager: &worktree.Manager{WorkDir: t.TempDir()}}, Dir: dir, Log: slog.New(slog.DiscardHandler), } diff --git a/internal/worktree/resume_test.go b/internal/worktree/resume_test.go index 526d50b94..15eab0172 100644 --- a/internal/worktree/resume_test.go +++ b/internal/worktree/resume_test.go @@ -7,23 +7,34 @@ import ( "testing" "github.com/go-git/go-git/v6" + "github.com/go-git/go-git/v6/plumbing" ) -// TestResumeResetsToBranchTipNotBase pins the remediate workflow's worktree -// semantics: Resume must land the worktree on the PR branch's remote tip (the -// committed work), not reset to base the way refresh does for a fresh run. -func TestResumeResetsToBranchTipNotBase(t *testing.T) { - ctx := context.Background() - host := newLocalRemote(t, "acme", "todo") - m := newManager(t, host) +// headHash reads a worktree's HEAD commit, so a test can assert which commit a +// prepare landed on. +func headHash(t *testing.T, dir string) plumbing.Hash { + t.Helper() + r, err := git.PlainOpen(dir) + if err != nil { + t.Fatalf("PlainOpen(%s): %v", dir, err) + } + ref, err := r.Head() + if err != nil { + t.Fatalf("Head(%s): %v", dir, err) + } + return ref.Hash() +} - dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: add widget", "", "feature") +// prepareResume models what a task retry starts from: a fresh prepare, a commit +// pushed onto the task branch, and the pushed tip. It returns the worktree +// directory, branch and tip. +func prepareResume(t *testing.T, m *Manager, issue int, title string) (dir, branch string, tip plumbing.Hash) { + t.Helper() + ctx := context.Background() + dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, issue, title, "", "bug", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } - - // Commit + push work on the branch, so origin/ has widget.go - // while base (main) has only README. r, err := git.PlainOpen(dir) if err != nil { t.Fatalf("PlainOpen: %v", err) @@ -32,51 +43,98 @@ func TestResumeResetsToBranchTipNotBase(t *testing.T) { if err := m.Push(ctx, dir, branch); err != nil { t.Fatalf("Push() error = %v", err) } + return dir, branch, headHash(t, dir) +} - if err := m.Resume(ctx, dir, branch); err != nil { - t.Fatalf("Resume() error = %v", err) +// TestPrepareResumeLandsOnTheBranchTipNotBase pins the resume target's +// semantics: it must land the worktree on the PR branch's remote tip (the +// committed work), not reset to base the way a fresh prepare does. +func TestPrepareResumeLandsOnTheBranchTipNotBase(t *testing.T) { + ctx := context.Background() + m := newManager(t, newLocalRemote(t, "acme", "todo")) + dir, branch, tip := prepareResume(t, m, 7, "feat: add widget") + + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: add widget", "", "bug", Target(branch)); err != nil { + t.Fatalf("Prepare(resume) error = %v", err) } content, err := os.ReadFile(filepath.Join(dir, "widget.go")) if err != nil { - t.Fatalf("widget.go missing after Resume: %v (resume reset to base and discarded the branch work)", err) + t.Fatalf("widget.go missing after resume: %v (resume reset to base and discarded the branch work)", err) } if string(content) != "package widget\n" { t.Fatalf("widget.go = %q, want %q", content, "package widget\n") } + if got := headHash(t, dir); got != tip { + t.Fatalf("HEAD = %s, want the branch tip %s", got, tip) + } } -// TestResumeCleansAbandonedFiles ensures Resume clears untracked residue the -// way refresh does, so a prior interrupted remediation cannot leak files into -// the next run. -func TestResumeCleansAbandonedFiles(t *testing.T) { +// TestPrepareResumeClonesAMissingWorktree is the root-cause test for +// archie-core-866m: a resume must create the clone when it is missing, so a +// retry reaches a task whose worktree the terminal cleanup removed, an expired +// volume dropped, or a different host never had. +func TestPrepareResumeClonesAMissingWorktree(t *testing.T) { ctx := context.Background() - host := newLocalRemote(t, "acme", "todo") - m := newManager(t, host) + m := newManager(t, newLocalRemote(t, "acme", "todo")) + dir, branch, tip := prepareResume(t, m, 8, "fix: thing") - dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "fix: thing", "", "bug") + if err := os.RemoveAll(dir); err != nil { + t.Fatalf("remove worktree: %v", err) + } + if _, err := os.Stat(filepath.Join(dir, preparedSentinel)); !os.IsNotExist(err) { + t.Fatalf("worktree not removed: sentinel stat err = %v", err) + } + + gotDir, gotBranch, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "fix: thing", "", "bug", Target(branch)) if err != nil { - t.Fatalf("Prepare() error = %v", err) + t.Fatalf("Prepare(resume) on a missing worktree error = %v, want it cloned", err) } - - // The branch must be pushed for Resume to resolve origin/. - r, err := git.PlainOpen(dir) + if gotDir != dir || gotBranch != branch { + t.Fatalf("Prepare(resume) = (%q, %q), want (%q, %q)", gotDir, gotBranch, dir, branch) + } + content, err := os.ReadFile(filepath.Join(gotDir, "widget.go")) if err != nil { - t.Fatalf("PlainOpen: %v", err) + t.Fatalf("widget.go missing after resume cloned: %v", err) } - writeSeedCommit(t, r, dir, "change.go", "package change\n", "a change") - if err := m.Push(ctx, dir, branch); err != nil { - t.Fatalf("Push() error = %v", err) + if string(content) != "package widget\n" { + t.Fatalf("widget.go = %q, want %q", content, "package widget\n") } + if got := headHash(t, gotDir); got != tip { + t.Fatalf("HEAD = %s, want the branch tip %s", got, tip) + } +} + +// TestPrepareResumeFailsClosedWhenTheBranchIsNotPushed pins that a resume +// never falls back to base: a branch that is not on the remote is a dispatch +// defect, and a base checkout would silently remediate the wrong tree. +func TestPrepareResumeFailsClosedWhenTheBranchIsNotPushed(t *testing.T) { + ctx := context.Background() + m := newManager(t, newLocalRemote(t, "acme", "todo")) + dir, _, tip := prepareResume(t, m, 9, "fix: thing") + + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "fix: thing", "", "bug", Target("fix/9-never-pushed")); err == nil { + t.Fatal("Prepare(resume) with an unpushed branch = nil error, want a fail-closed error") + } + if got := headHash(t, dir); got != tip { + t.Fatalf("HEAD = %s, want the worktree left on the branch tip %s", got, tip) + } +} + +// TestPrepareResumeCleansAbandonedFiles ensures a resume clears untracked +// residue the way a fresh prepare does, so a prior interrupted run cannot leak +// files into the next commit. +func TestPrepareResumeCleansAbandonedFiles(t *testing.T) { + ctx := context.Background() + m := newManager(t, newLocalRemote(t, "acme", "todo")) + dir, branch, _ := prepareResume(t, m, 10, "fix: thing") - // Untracked residue that a clean run must remove. if err := os.WriteFile(filepath.Join(dir, "scratch.txt"), []byte("junk\n"), 0o600); err != nil { t.Fatal(err) } - - if err := m.Resume(ctx, dir, branch); err != nil { - t.Fatalf("Resume() error = %v", err) + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 10, "fix: thing", "", "bug", Target(branch)); err != nil { + t.Fatalf("Prepare(resume) error = %v", err) } if _, err := os.Stat(filepath.Join(dir, "scratch.txt")); !os.IsNotExist(err) { - t.Errorf("scratch.txt still exists after Resume; untracked residue was not cleaned") + t.Errorf("scratch.txt still exists after resume; untracked residue was not cleaned") } } diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index 6395c9ffe..a75b69f01 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -120,70 +120,103 @@ func (m *Manager) signature() *object.Signature { return &object.Signature{Name: m.BotUser, Email: m.BotEmail, When: time.Now()} } -// Prepare creates a fresh clone for the task and checks out its branch. -// Any leftover worktree from a prior attempt is removed first. If the -// worktree is already prepared, it is refreshed and reused. +// Target selects the commit a prepared worktree is positioned at. +// +// The zero value is Fresh: a run that starts new work is reset onto +// origin/. A non-empty Target is a resume: the worktree is reset onto +// origin/, continuing the work an earlier attempt already pushed. +// +// The branch travels with the choice rather than being recomputed from the +// title, because a resume must land on the branch the open pull request lives +// on: a retitled issue would otherwise name a branch that does not exist. +// +// It is a string rather than a bool or an enum precisely so the branch to +// resume onto is carried by the choice; a bool would force a second parameter +// and let a caller select a resume without naming what it resumes onto. +type Target string + +// Fresh is the fresh-run target: reset onto origin/. +const Fresh Target = "" + +// Prepare creates (or reuses) the task's clone and positions it on target, +// returning the worktree directory and the branch it is on. +// +// A missing clone is created for either target. That is what lets a resume +// recover a worktree the terminal cleanup, an expired volume or a different +// host removed before a retry. Fresh lands it on origin/; a resume lands +// it on origin/ and fails closed when that branch is not on the remote +// rather than falling back to base. func (m *Manager) Prepare( ctx context.Context, owner, repo, base string, issue int, title, body, labels string, + target Target, ) (dir, branch string, err error) { if !ValidCoordinates(owner, repo, issue) { return "", "", fmt.Errorf("invalid worktree coordinates") } dir = m.Dir(owner, repo, issue) branch = archieBranch(issue, title, labels) + if target != Fresh { + branch = string(target) + } + prepared := false if _, statErr := os.Stat(filepath.Join(dir, preparedSentinel)); statErr == nil { - if err := m.refresh(ctx, dir, base, branch); err != nil { - return "", "", err + prepared = true + } else { + migrated, migrateErr := m.migrateLegacy(owner, repo, issue, dir) + if migrateErr != nil { + return "", "", migrateErr } - return dir, branch, nil - } - if migrated, migrateErr := m.migrateLegacy(owner, repo, issue, dir); migrateErr != nil { - return "", "", migrateErr - } else if migrated { - if err := m.refresh(ctx, dir, base, branch); err != nil { - return "", "", err - } - return dir, branch, nil + prepared = migrated } + if !prepared { + if err := m.createClone(ctx, owner, repo, base, dir); err != nil { + return "", "", err + } + } + + if err := m.sync(ctx, dir, base, branch, target); err != nil { + return "", "", err + } + return dir, branch, nil +} + +// createClone removes whatever sits at dir, clones the task's repository there, +// records the bot identity and marks the worktree prepared. Prepare calls it +// only for a worktree it could not reuse. +func (m *Manager) createClone(ctx context.Context, owner, repo, base, dir string) error { if err := os.RemoveAll(dir); err != nil { - return "", "", fmt.Errorf("clear stale worktree: %w", err) + return fmt.Errorf("clear stale worktree: %w", err) } if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil { - return "", "", fmt.Errorf("create worktree parent: %w", err) + return fmt.Errorf("create worktree parent: %w", err) } - r, err := git.PlainCloneContext(ctx, dir, &git.CloneOptions{ URL: m.cloneURL(owner, repo), ClientOptions: m.auth(), ReferenceName: plumbing.NewBranchReferenceName(base), }) if err != nil { - return "", "", fmt.Errorf("clone %s/%s: %w", owner, repo, err) + return fmt.Errorf("clone %s/%s: %w", owner, repo, err) } if err := m.setIdentity(r); err != nil { - return "", "", err + return err } + return writeSentinel(dir) +} - wt, err := r.Worktree() - if err != nil { - return "", "", fmt.Errorf("open worktree: %w", err) +// sync positions an already-prepared worktree: Fresh resets it onto +// origin/; a resume resets it onto origin/. Both fetch first and +// clear the worktree against the target tree before committing to it. +func (m *Manager) sync(ctx context.Context, dir, base, branch string, target Target) error { + if target == Fresh { + return m.refresh(ctx, dir, base, branch) } - if err := wt.Checkout(&git.CheckoutOptions{ - Branch: plumbing.NewBranchReferenceName(branch), - Create: true, - }); err != nil { - return "", "", fmt.Errorf("create branch %s: %w", branch, err) - } - - if err := writeSentinel(dir); err != nil { - return "", "", err - } - return dir, branch, nil + return m.resume(ctx, dir, branch) } func (m *Manager) legacyDir(owner, repo string, issue int) string { @@ -256,12 +289,13 @@ func (m *Manager) refresh(ctx context.Context, dir, base, branch string) error { return resetOnto(r, dir, branch, baseHash, remoteBase(base)) } -// Resume re-syncs an already-prepared worktree onto its branch's remote tip -// without resetting to base, so the remediate workflow can continue work on -// the PR branch the implement run already pushed. It is refresh's complement: -// refresh resets to origin/ for a fresh run; Resume resets to -// origin/ so the committed PR work survives. -func (m *Manager) Resume(ctx context.Context, dir, branch string) error { +// resume re-syncs an already-prepared worktree onto its branch's remote tip +// without resetting to base, so a remediation can continue work on the PR +// branch an earlier attempt already pushed. It is refresh's complement: refresh +// resets to origin/ for a fresh run; resume resets to origin/ so +// the committed PR work survives. It is reached through Prepare's Target, and +// the worktree it opens is one Prepare has already cloned when it was missing. +func (m *Manager) resume(ctx context.Context, dir, branch string) error { r, err := git.PlainOpen(dir) if err != nil { return fmt.Errorf("open prepared worktree: %w", err) diff --git a/internal/worktree/worktree_repair_test.go b/internal/worktree/worktree_repair_test.go index 3378833dd..0f5ece7f0 100644 --- a/internal/worktree/worktree_repair_test.go +++ b/internal/worktree/worktree_repair_test.go @@ -88,7 +88,7 @@ func TestPushSucceedsWhenPostPublicationMetadataFails(t *testing.T) { m.Log = slog.New(logs) } - dir, branch, err := m.Prepare(ctx, "acme", "push-test", testBase, tc.issue, tc.title, "", tc.labels) + dir, branch, err := m.Prepare(ctx, "acme", "push-test", testBase, tc.issue, tc.title, "", tc.labels, Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -178,7 +178,7 @@ func TestRecordUpstreamErrorPaths(t *testing.T) { host := newLocalRemote(t, "acme", "record-upstream") m := newManager(t, host) - dir, branch, err := m.Prepare(ctx, "acme", "record-upstream", testBase, 105, "feat: record upstream", "", "feature") + dir, branch, err := m.Prepare(ctx, "acme", "record-upstream", testBase, 105, "feat: record upstream", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -229,7 +229,7 @@ func TestCommitAllHonoursCancellation(t *testing.T) { host := newLocalRemote(t, "acme", "cancel-test") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "cancel-test", testBase, 201, "feat: cancel test", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "cancel-test", testBase, 201, "feat: cancel test", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } diff --git a/internal/worktree/worktree_test.go b/internal/worktree/worktree_test.go index ec267dfc9..13df521d3 100644 --- a/internal/worktree/worktree_test.go +++ b/internal/worktree/worktree_test.go @@ -120,7 +120,7 @@ func TestPrepareCommitPushRoundTrip(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: add widget", "", "feature") + dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: add widget", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -194,7 +194,7 @@ func TestPrepareIsIdempotent(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir1, branch1, err := m.Prepare(ctx, "acme", "todo", testBase, 3, "fix: thing", "", "bug") + dir1, branch1, err := m.Prepare(ctx, "acme", "todo", testBase, 3, "fix: thing", "", "bug", Fresh) if err != nil { t.Fatalf("first Prepare() error = %v", err) } @@ -205,7 +205,7 @@ func TestPrepareIsIdempotent(t *testing.T) { t.Fatal(err) } - dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 3, "fix: thing", "", "bug") + dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 3, "fix: thing", "", "bug", Fresh) if err != nil { t.Fatalf("second Prepare() error = %v", err) } @@ -260,7 +260,7 @@ func TestPrepareRecoversFromADirtyWorktreeOnRetry(t *testing.T) { } m := newManager(t, host) - dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "fix: retry robustness", "", "bug") + dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "fix: retry robustness", "", "bug", Fresh) if err != nil { t.Fatalf("first Prepare() error = %v", err) } @@ -280,7 +280,7 @@ func TestPrepareRecoversFromADirtyWorktreeOnRetry(t *testing.T) { t.Fatal(err) } - dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "fix: retry robustness", "", "bug") + dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "fix: retry robustness", "", "bug", Fresh) if err != nil { t.Fatalf("retry Prepare() on a dirty worktree error = %v, want recovery", err) } @@ -384,13 +384,13 @@ func TestPrepareRecoversFromAPathTypeConflictOnRetry(t *testing.T) { seedTrackedPath(t, host, "pkg/a.txt", "a\n") m := newManager(t, host) - dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "fix: path type conflict", "", "bug") + dir, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "fix: path type conflict", "", "bug", Fresh) if err != nil { t.Fatalf("first Prepare() error = %v", err) } c.wreck(t, dir) - dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "fix: path type conflict", "", "bug") + dir2, branch2, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "fix: path type conflict", "", "bug", Fresh) if err != nil { t.Fatalf("retry Prepare() over a path type conflict error = %v, want recovery", err) } @@ -439,7 +439,7 @@ func TestPrepareCreatesTheBranchWhenItIsGenuinelyMissing(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "fix: first title", "", "bug") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "fix: first title", "", "bug", Fresh) if err != nil { t.Fatalf("first Prepare() error = %v", err) } @@ -452,7 +452,7 @@ func TestPrepareCreatesTheBranchWhenItIsGenuinelyMissing(t *testing.T) { t.Fatalf("remove branch %s: %v", first, err) } - _, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "fix: renamed title", "", "bug") + _, branch, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "fix: renamed title", "", "bug", Fresh) if err != nil { t.Fatalf("Prepare() after the branch was removed error = %v, want it created", err) } @@ -506,7 +506,7 @@ func TestCleanUntrackedHandlesGitdirFile(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 12, "fix: gitdir file", "", "bug") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 12, "fix: gitdir file", "", "bug", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -591,7 +591,7 @@ func TestPrepareDiscardsDirectoryWithoutSentinel(t *testing.T) { t.Fatal(err) } - if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 11, "chore: retry", "", "chore"); err != nil { + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 11, "chore: retry", "", "chore", Fresh); err != nil { t.Fatalf("Prepare() error = %v", err) } if _, err := os.Stat(junk); !os.IsNotExist(err) { @@ -619,7 +619,7 @@ func TestPrepareErrors(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { m := newManager(t, tc.host) - _, _, err := m.Prepare(context.Background(), tc.owner, tc.repo, tc.base, 1, "t", "", "") + _, _, err := m.Prepare(context.Background(), tc.owner, tc.repo, tc.base, 1, "t", "", "", Fresh) if err == nil { t.Fatal("Prepare() error = nil, want a failure") } @@ -631,10 +631,10 @@ func TestPrepareRefreshRejectsUnknownBase(t *testing.T) { ctx := context.Background() host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 12, "fix: base", "", "bug"); err != nil { + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 12, "fix: base", "", "bug", Fresh); err != nil { t.Fatal(err) } - if _, _, err := m.Prepare(ctx, "acme", "todo", "missing-base", 12, "fix: base", "", "bug"); err == nil { + if _, _, err := m.Prepare(ctx, "acme", "todo", "missing-base", 12, "fix: base", "", "bug", Fresh); err == nil { t.Fatal("prepared worktree accepted an unknown base") } } @@ -682,7 +682,7 @@ func TestSnapshotExportsTrackedFilesWithoutGit(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "feat: snapshot me", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 9, "feat: snapshot me", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -718,7 +718,7 @@ func TestDiffUsesMergeBaseNotRemoteTip(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 5, "feat: mine", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 5, "feat: mine", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -771,7 +771,7 @@ func TestDiffOperationsRejectUnrelatedBaseHistory(t *testing.T) { ctx := context.Background() host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 6, "feat: task", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 6, "feat: task", "", "feature", Fresh) if err != nil { t.Fatal(err) } @@ -886,7 +886,7 @@ func TestPushWithoutTokenOverHTTPFailsWithClearMessage(t *testing.T) { ctx := context.Background() host := newLocalRemote(t, "acme", "todo") seeder := newManager(t, host) - dir, branch, err := seeder.Prepare(ctx, "acme", "todo", testBase, 1, "t", "", "") + dir, branch, err := seeder.Prepare(ctx, "acme", "todo", testBase, 1, "t", "", "", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -973,7 +973,7 @@ func TestPrepareMigratesMatchingLegacyWorktree(t *testing.T) { t.Fatal(err) } - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 44, "feat: migrate", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 44, "feat: migrate", "", "feature", Fresh) if err != nil { t.Fatal(err) } @@ -1008,7 +1008,7 @@ func TestPreparePreservesMismatchedLegacyWorktree(t *testing.T) { t.Fatal(err) } - if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 45, "feat: safe migration", "", "feature"); err != nil { + if _, _, err := m.Prepare(ctx, "acme", "todo", testBase, 45, "feat: safe migration", "", "feature", Fresh); err != nil { t.Fatal(err) } if _, err := os.Stat(marker); err != nil { @@ -1059,7 +1059,7 @@ func TestSentinelIsNeverCommitted(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "feat: thing", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 21, "feat: thing", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -1097,7 +1097,7 @@ func TestTaskBriefIsNeverCommitted(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "feat: brief", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 22, "feat: brief", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -1397,7 +1397,7 @@ func TestChangedFileStatsRecordsTheDiffedBaseNotTheAdvancedTip(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "feat: mine", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "feat: mine", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } @@ -1473,7 +1473,7 @@ func TestHasUncommittedChangesReportsWorkNoCommitHasCaptured(t *testing.T) { host := newLocalRemote(t, "acme", "todo") m := newManager(t, host) - dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: mine", "", "feature") + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 7, "feat: mine", "", "feature", Fresh) if err != nil { t.Fatalf("Prepare() error = %v", err) } diff --git a/internal/worktreerpc/worktreerpc_test.go b/internal/worktreerpc/worktreerpc_test.go index 472a71cef..a4c75c084 100644 --- a/internal/worktreerpc/worktreerpc_test.go +++ b/internal/worktreerpc/worktreerpc_test.go @@ -124,7 +124,7 @@ func TestManagerPrepareCannotDeleteOutsideWorkDir(t *testing.T) { } m := &worktree.Manager{WorkDir: workDir, BaseURL: t.TempDir()} - _, _, _ = m.Prepare(ctx, "../escape", "widget", "main", 7, "feat: test", "", "") + _, _, _ = m.Prepare(ctx, "../escape", "widget", "main", 7, "feat: test", "", "", worktree.Fresh) if _, err := os.Stat(marker); err != nil { t.Fatalf("Prepare removed a path outside WorkDir: %v", err) } @@ -140,7 +140,7 @@ func TestClientPushRejectsTaskMismatchedCoordinates(t *testing.T) { BotEmail: "archie-bot@example.com", BaseURL: host, } - dir, branch, err := m.Prepare(ctx, "other", "widget", "main", 9, "feat: other", "", "") + dir, branch, err := m.Prepare(ctx, "other", "widget", "main", 9, "feat: other", "", "", worktree.Fresh) if err != nil { t.Fatal(err) } @@ -181,7 +181,7 @@ func TestClientPushPublishesViaServer(t *testing.T) { BaseURL: host, } - dir, branch, err := m.Prepare(ctx, "acme", "widget", "main", 1, "feat: test", "", "") + dir, branch, err := m.Prepare(ctx, "acme", "widget", "main", 1, "feat: test", "", "", worktree.Fresh) if err != nil { t.Fatalf("prepare: %v", err) }