Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): self-repair worktree deliveries moved off their branch (MUL-8139) (#9454)
Multica Evec0b46688f2ae
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 37d242d3b2..8c7f9afc3e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8462,6 +8462,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif env.LocalWorktree != nil && len(env.LocalWorktree.ReplayConflicts) > 0 {promptOptions = append(promptOptions, WithWorktreeReplayConflicts(env.LocalWorktree.ReplayConflicts))}+ // And it delivers only what ends on its own branch, still containing the+ // commit it started from. Say so up front: squashing or switching to a PR+ // branch is ordinary git hygiene the agent would otherwise reach for, and+ // the daemon cannot record either (#9404).+ if env.LocalWorktree != nil {+ promptOptions = append(promptOptions, WithWorktreeBranch(env.LocalWorktree.Branch, env.LocalWorktree.BaseCommit))+ }prompt := BuildPrompt(task, provider, promptOptions...)// Pass task-scoped auth credentials and context so the spawned agent CLI@@ -8855,6 +8862,17 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// than being relabeled resumable by a benign-looking second error.result, tools = reconcileFreshRetryResult(firstResult, firstUsage, firstTools, retryResult, retryTools, retryErr)}++ // Worktree mode: if the agent finished with its work somewhere Finalize+ // will refuse to record — squashed past its baseline, or committed off its+ // branch — give it one turn to put the work back before failing the task+ // (#9404). The delivery guard itself is untouched: the repaired state must+ // pass the very same check in Finalize.+ if env.LocalWorktree != nil && result.Status == "completed" {+ if problem := env.LocalWorktree.CheckDelivery(); problem != nil {+ result, tools = d.repairWorktreeDelivery(ctx, backend, execOpts, result, tools, problem, env, taskLog, task.ID, &msgSeq)+ }+ }phaseRecorder.Mark(taskPhaseTurnCompleted)elapsed := time.Since(taskStart).Round(time.Second)@@ -9247,6 +9265,62 @@ func shouldRetryWithFreshSession(result agent.Result, priorSessionID string, too// first result and only merge usage.//// Usage is merged across both attempts in every branch so billing is complete.+// worktreeRepairTimeout caps the delivery-repair turn. Putting work back on its+// branch is a handful of git commands; a turn that has not managed it in this+// long is not going to, and the task's own budget should not be spent twice.+const worktreeRepairTimeout = 10 * time.Minute++// repairWorktreeDelivery runs the one follow-up turn that asks the agent to put+// its work back where Finalize can record it (#9404), then reports what came of+// it. It never fails the task on its own: whatever state the worktree is in+// afterwards, Finalize makes the same decision it always made.+func (d *Daemon) repairWorktreeDelivery(ctx context.Context, backend agent.Backend, execOpts agent.ExecOptions, result agent.Result, tools int32, problem *execenv.DeliveryProblem, env *execenv.Environment, taskLog *slog.Logger, taskID string, msgSeq *atomic.Int32) (agent.Result, int32) {+ taskLog.Warn("local_directory: worktree delivery would be refused; asking the agent to repair it",+ "branch", problem.Branch, "base", problem.BaseCommit, "tip", problem.Tip, "reason", problem.Reason)++ opts := execOpts+ // Continue the conversation when there is one, so the agent knows what it+ // just did; the prompt is self-contained for the backends that cannot.+ opts.ResumeSessionID = result.SessionID+ opts.ResumeContinuityNotice = ""+ // No additional messages during housekeeping. The repair turn's reply is+ // discarded (mergeWorktreeRepairResult keeps the task's own), so a+ // message accepted here would be acknowledged as delivered and its answer+ // lost. Left unclaimed, the server settles it as turn_ended when the task+ // ends, so its receipt honestly reads "run ended before delivery" and the+ // author can resend it (MUL-8139 review).+ opts.EnableTaskSupplement = false+ if opts.Timeout <= 0 || opts.Timeout > worktreeRepairTimeout {+ opts.Timeout = worktreeRepairTimeout+ }+ repair, repairTools, repairErr := d.executeAndDrain(ctx, backend, BuildWorktreeDeliveryRepairPrompt(problem), opts, taskLog, taskID, env.CodexHome, msgSeq)+ if repairErr != nil {+ taskLog.Error("local_directory: worktree delivery repair turn failed to start", "error", repairErr)+ } else if remaining := env.LocalWorktree.CheckDelivery(); remaining != nil {+ taskLog.Error("local_directory: worktree delivery still cannot be recorded after the repair turn",+ "status", repair.Status, "reason", remaining.Reason)+ } else {+ taskLog.Info("local_directory: the agent repaired its worktree delivery", "branch", problem.Branch)+ }+ return mergeWorktreeRepairResult(result, tools, repair, repairTools, repairErr)+}++// mergeWorktreeRepairResult folds the repair turn into the task's result. The+// task's reply stays the original turn's: the repair turn is housekeeping, and+// its one-line answer is not what the user asked for. Usage and tool counts+// add up, and a session the repair turn completed in becomes the resume+// pointer, since that is now where the conversation ends.+func mergeWorktreeRepairResult(original agent.Result, originalTools int32, repair agent.Result, repairTools int32, repairErr error) (agent.Result, int32) {+ if repairErr != nil {+ return original, originalTools+ }+ original.Usage = mergeUsage(original.Usage, repair.Usage)+ if repair.Status == "completed" && repair.SessionID != "" {+ original.SessionID = repair.SessionID+ }+ return original, originalTools + repairTools+}+func reconcileFreshRetryResult(first agent.Result, firstUsage map[string]agent.TokenUsage, firstTools int32, retry agent.Result, retryTools int32, retryErr error) (agent.Result, int32) {switch {case retryErr != nil:diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.goindex aace124836..096ecd7bf5 100644--- a/server/internal/daemon/execenv/local_worktree.go+++ b/server/internal/daemon/execenv/local_worktree.go@@ -1643,6 +1643,295 @@ func (w *LocalWorktree) verifyDeliveryPoint(tip string) error {return nil}+// DeliveryProblem is a refusal Finalize is about to make that the agent can+// still repair from inside its own worktree: the run left its work somewhere+// verifyDeliveryPoint will not record, but the work itself is intact and the+// fix is ordinary git (#9404).+type DeliveryProblem struct {+ // Branch is the task branch the delivery has to end on.+ Branch string+ // BaseCommit is the commit the delivery has to contain — this turn's+ // baseline, or the branch tip it continued.+ BaseCommit string+ // Tip is the commit the worktree's HEAD points at now.+ Tip string+ // Reason is verifyDeliveryPoint's own explanation, as Finalize would+ // report it.+ Reason string+}++// RepairCommitMessage is the commit message RepairSteps uses for the one+// commit it makes.+const RepairCommitMessage = "chore(agent): put this turn's work back on its task branch"++// RepairSteps is one git sequence that resolves any DeliveryProblem while+// keeping the worktree's files exactly as they are: stage everything, point+// HEAD back at the task branch without touching files or index, move the+// branch to BaseCommit, and commit the staged tree on top of it. The result is+// a single commit whose parent is BaseCommit and whose tree is what the agent+// left — so it passes verifyDeliveryPoint by construction, and the guard+// itself is unchanged.+//+// Each step is a git argv (without the leading "git"). Rendered into the+// repair prompt and executed verbatim by the tests, so the instruction the+// agent gets is the one that is proven to work.+func (p *DeliveryProblem) RepairSteps() [][]string {+ return [][]string{+ {"add", "-A"},+ {"symbolic-ref", "HEAD", "refs/heads/" + p.Branch},+ {"reset", "--soft", p.BaseCommit},+ {"commit", "-m", RepairCommitMessage},+ }+}++// CheckDelivery reports, without changing anything, whether Finalize would+// refuse to record this turn's delivery because of where the run left its+// history — and returns nil whenever it would not, or when it would refuse for+// a reason a repair turn should not be asked to undo.+//+// It predicts the same verifyDeliveryPoint call Finalize makes, including the+// auto-commit Finalize adds first: uncommitted leftovers are committed onto+// whatever HEAD points at, so they only reach the task branch when HEAD is+// attached to it.+//+// A tip that is an ancestor of BaseCommit is deliberately NOT offered for+// repair. That is the run resetting back to where the turn started or earlier+// — the MUL-6881 case, where the user's replayed edits were thrown away — and+// the guard exists to stop exactly that being recorded. Asking the agent to+// re-commit such a tree on top of the baseline would turn a refused discard+// into a delivered revert of the user's edits. Repair is only for a tip that+// carries something the baseline line does not: a squash or rebase that+// dropped the baseline, or work committed onto another branch.+func (w *LocalWorktree) CheckDelivery() *DeliveryProblem {+ if w == nil || w.aborted != nil || !w.tracksState || w.BaseCommit == "" {+ return nil+ }+ // An unresolved merge fails Finalize before the delivery point is ever+ // checked, and the prompt already told the agent to resolve it.+ if unmerged, err := unmergedPaths(w.Path); err != nil || len(unmerged) > 0 {+ return nil+ }+ tip, err := runGitTrimmed(w.Path, "rev-parse", "--verify", "HEAD")+ if err != nil || tip == "" {+ return nil+ }+ dirty, err := worktreeIsDirty(w.Path)+ if err != nil {+ dirty = true // Finalize commits defensively on the same uncertainty.+ }+ if !dirty && tip == w.BaseCommit {+ // Nothing produced: Finalize drops a branch it created and records a+ // continued one as-is. Neither is refused.+ return nil+ }+ if tip != w.BaseCommit {+ if _, err := runGit(w.GitRoot, "merge-base", "--is-ancestor", tip, w.BaseCommit); err == nil {+ // Reset back past the baseline (see the doc comment): Finalize+ // refuses it, and that refusal is not ours to talk the agent around.+ return nil+ }+ }+ if dirty && !headAttachedTo(w.Path, w.Branch) {+ if w.repairWouldRevertBase(tip) {+ return nil+ }+ return &DeliveryProblem{+ Branch: w.Branch,+ BaseCommit: w.BaseCommit,+ Tip: tip,+ Reason: fmt.Sprintf("the worktree has uncommitted changes while HEAD is not on branch %s, so they would not be delivered onto it",+ w.Branch),+ }+ }+ if verifyErr := w.verifyDeliveryPoint(tip); verifyErr != nil {+ if w.repairWouldRevertBase(tip) {+ return nil+ }+ return &DeliveryProblem{Branch: w.Branch, BaseCommit: w.BaseCommit, Tip: tip, Reason: verifyErr.Error()}+ }+ return nil+}++// repairWouldRevertBase reports whether re-committing the worktree's current+// files on top of BaseCommit could lose something BaseCommit carries — the+// user's replayed edits, or an earlier turn's work — that the agent's files do+// not.+//+// RepairSteps keeps the agent's files exactly as they are. That is right for a+// squash (the files still carry everything; only the ancestry dropped the+// baseline) and wrong for work done on a line that never saw the baseline's+// content: a detached checkout of the user's HEAD, say, when the baseline holds+// their uncommitted edits. Delivered on top of the baseline, those files are a+// silent revert of the edits — the loss MUL-6881 guards against.+//+// So the repair is offered only when the agent's files provably already contain+// every change BaseCommit made relative to its common ancestor with tip+// (mergeBase). Per path BaseCommit changed:+//+// - the agent's file mode must equal BaseCommit's: a user's chmod +x is a+// change the content comparison alone cannot see;+// - the agent's file equals BaseCommit's: kept as-is;+// - otherwise a three-way merge (base = mergeBase, ours = the agent's file,+// theirs = BaseCommit's) must be clean AND leave the agent's file+// unchanged — i.e. BaseCommit's change is already in it, and the agent+// only added to it. A merge that would change the agent's file means the+// change is missing; repairing would deliver its revert (MUL-8139 review).+//+// The agent's side is read from the tree `git add -A` would stage, i.e. what+// RepairSteps actually commits. Anything else — a deletion on either side, a+// symlink or submodule, a binary+// file, a conflict, git failing to answer — refuses the repair. That includes+// an agent edit on a line touching one the baseline changed, which merge-file+// reports as a conflict even when the agent did build on the baseline.+// Conservative by design: Finalize then makes its usual refusal and nothing is+// lost.+func (w *LocalWorktree) repairWouldRevertBase(tip string) bool {+ mergeBase, err := runGitTrimmed(w.GitRoot, "merge-base", tip, w.BaseCommit)+ if err != nil || mergeBase == "" {+ return true // Unrelated histories: nothing to prove against.+ }+ if mergeBase == w.BaseCommit {+ return false // tip already descends from the baseline: nothing to lose.+ }+ out, err := runGitStdout(w.GitRoot, "diff", "--name-only", "--no-renames", "-z", mergeBase, w.BaseCommit)+ if err != nil {+ return true+ }+ // Judge the agent's side as the repair will commit it: RepairSteps starts+ // with `git add -A`, so the tree that stages — content after filters, and+ // the file mode git records (core.filemode decides whether the worktree's+ // executable bit or the index's mode wins) — is what reaches the branch.+ agentTree, err := stagedWorktreeTree(w.Path)+ if err != nil {+ return true+ }+ scratch := ""+ defer func() {+ if scratch != "" {+ _ = os.RemoveAll(scratch)+ }+ }()+ for _, path := range strings.Split(out, "\x00") {+ if path == "" {+ continue+ }+ baseBlob, ok := regularBlob(w.GitRoot, w.BaseCommit, path)+ if !ok {+ return true // Deleted, or not a plain file, on the baseline side.+ }+ baseMode := treeEntryMode(w.GitRoot, w.BaseCommit, path)+ if baseMode != treeEntryMode(w.GitRoot, agentTree, path) {+ return true // A mode change (chmod +x, say) the agent's files lack.+ }+ ours, ok := regularBlob(w.GitRoot, agentTree, path)+ if !ok {+ return true // The agent's side dropped it, or it is not a plain file.+ }+ if ours == baseBlob {+ continue+ }+ ancestor := ""+ if blob, ok := regularBlob(w.GitRoot, mergeBase, path); ok {+ ancestor = blob+ } else if exists, _ := pathInCommit(w.GitRoot, mergeBase, path); exists {+ return true // Present but not a plain file in the ancestor.+ }+ if scratch == "" {+ if scratch, err = os.MkdirTemp("", "multica-repair-check-"); err != nil {+ scratch = ""+ return true+ }+ }+ merged, clean := mergeFileContents(scratch, ours, ancestor, baseBlob)+ if !clean || merged != ours {+ return true+ }+ }+ return false+}++// regularBlob returns the content of path in commit when it is a regular+// (non-symlink, non-submodule) text file there. ok is false otherwise,+// including when the path does not exist or holds binary content.+func regularBlob(gitRoot, commit, path string) (string, bool) {+ entry, err := runGitStdout(gitRoot, "ls-tree", "-z", commit, "--", path)+ if err != nil || entry == "" {+ return "", false+ }+ mode, _, _ := strings.Cut(entry, " ")+ if mode != "100644" && mode != "100755" {+ return "", false+ }+ content, err := runGitStdout(gitRoot, "cat-file", "blob", commit+":"+path)+ if err != nil || strings.ContainsRune(content, 0) {+ return "", false+ }+ return content, true+}++// treeEntryMode returns the git file mode of path in a commit or tree+// ("100644", "100755", "120000", ...), or "" when it is absent or git fails.+func treeEntryMode(gitRoot, treeish, path string) string {+ entry, err := runGitStdout(gitRoot, "ls-tree", "-z", treeish, "--", path)+ if err != nil {+ return ""+ }+ mode, _, _ := strings.Cut(entry, " ")+ return mode+}++// stagedWorktreeTree returns the tree `git add -A` would stage in dir, built in+// a private copy of dir's index so neither the agent's index nor its files+// change. Errors — including a missing index to seed from, without which the+// recorded modes cannot be predicted — fail the caller closed.+func stagedWorktreeTree(dir string) (string, error) {+ tmp, err := os.MkdirTemp("", "multica-repair-index-")+ if err != nil {+ return "", err+ }+ defer os.RemoveAll(tmp)+ index := filepath.Join(tmp, "index")+ if !seedSnapshotIndex(dir, index) {+ return "", errors.New("execenv: cannot copy the worktree index")+ }+ env := []string{"GIT_INDEX_FILE=" + index}+ if out, err := runGitEnv(dir, env, "add", "-A"); err != nil {+ return "", fmt.Errorf("execenv: stage worktree in private index: %s: %w", strings.TrimSpace(out), err)+ }+ return runGitTrimmedEnv(dir, env, "write-tree")+}++func pathInCommit(gitRoot, commit, path string) (bool, error) {+ entry, err := runGitStdout(gitRoot, "ls-tree", "-z", commit, "--", path)+ return entry != "", err+}++// mergeFileContents runs `git merge-file -p ours base theirs` on scratch copies+// and reports the merged content and whether it merged without conflicts.+// merge-file works on plain files, so it needs no repository and is available+// in every git the daemon supports.+func mergeFileContents(scratch, ours, base, theirs string) (string, bool) {+ paths := make([]string, 3)+ for i, content := range []string{ours, base, theirs} {+ paths[i] = filepath.Join(scratch, strconv.Itoa(i))+ if err := os.WriteFile(paths[i], []byte(content), 0o600); err != nil {+ return "", false+ }+ }+ merged, err := runGitStdout(scratch, "merge-file", "-p", paths[0], paths[1], paths[2])+ if err != nil {+ return "", false // Non-zero exit: conflicts, or merge-file failed.+ }+ return merged, true+}++// headAttachedTo reports whether the worktree's HEAD is the symbolic ref of+// branch, i.e. a commit made now would advance that branch.+func headAttachedTo(worktreePath, branch string) bool {+ ref, err := runGitTrimmed(worktreePath, "symbolic-ref", "--quiet", "HEAD")+ return err == nil && ref == "refs/heads/"+branch+}+// unmergedPaths lists the files git considers unresolved in a worktree.func unmergedPaths(worktreePath string) ([]string, error) {out, err := runGitStdout(worktreePath, "diff", "--name-only", "--diff-filter=U", "-z")diff --git a/server/internal/daemon/execenv/local_worktree_delivery_repair_test.go b/server/internal/daemon/execenv/local_worktree_delivery_repair_test.gonew file mode 100644index 0000000000..4dbff7c8ba--- /dev/null+++ b/server/internal/daemon/execenv/local_worktree_delivery_repair_test.go@@ -0,0 +1,371 @@+package execenv++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++// applyRepairSteps runs exactly the git sequence the repair prompt hands the+// agent, so these tests prove the instruction itself, not a paraphrase of it.+func applyRepairSteps(t *testing.T, wt *LocalWorktree, problem *DeliveryProblem) {+ t.Helper()+ for _, step := range problem.RepairSteps() {+ gitRun(t, wt.Path, step...)+ }+}++// requireRepairable asserts CheckDelivery predicts the refusal Finalize would+// make, then repairs it and checks Finalize records the delivery with the+// agent's files intact.+func requireRepairable(t *testing.T, repo string, wt *LocalWorktree, wantReason string, wantFiles map[string]string) {+ t.Helper()+ problem := wt.CheckDelivery()+ if problem == nil {+ t.Fatal("CheckDelivery found nothing to repair, but Finalize would refuse this delivery")+ }+ if !strings.Contains(problem.Reason, wantReason) {+ t.Errorf("Reason = %q, want it to contain %q", problem.Reason, wantReason)+ }+ if problem.Branch != wt.Branch || problem.BaseCommit != wt.BaseCommit {+ t.Errorf("problem names branch %q base %q, want %q %q", problem.Branch, problem.BaseCommit, wt.Branch, wt.BaseCommit)+ }++ applyRepairSteps(t, wt, problem)+ if again := wt.CheckDelivery(); again != nil {+ t.Fatalf("the repair steps did not fix the delivery: %s", again.Reason)+ }++ outcome := finalizeOK(t, wt)+ if outcome.Branch != wt.Branch {+ t.Fatalf("outcome.Branch = %q, want %q", outcome.Branch, wt.Branch)+ }+ if _, err := gitTry(t, repo, "merge-base", "--is-ancestor", wt.BaseCommit, wt.Branch); err != nil {+ t.Error("the delivered branch does not contain the commit this turn started from")+ }+ for name, want := range wantFiles {+ if got := gitRun(t, repo, "show", wt.Branch+":"+name); got != strings.TrimSpace(want) {+ t.Errorf("%s on the branch = %q, want %q", name, got, strings.TrimSpace(want))+ }+ }+}++// #9404 shape one: the agent squashes its commits and drops the empty baseline+// along with them. Every change is still there; only the ancestry is wrong.+func TestCheckDeliveryRepairsASquashThatDroppedTheBaseline(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "turn one\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ // `git reset --soft <baseline>^ && git commit`, as in the report.+ gitRun(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitRun(t, wt.Path, "commit", "-m", "squashed")++ requireRepairable(t, repo, wt, "no longer contains", map[string]string{"agent.txt": "turn one"})+}++// #9404 shape two: the work landed on a sibling line while the task branch+// still sits on its baseline.+func TestCheckDeliveryRepairsWorkCommittedOffTheBranch(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ head := gitRun(t, repo, "rev-parse", "HEAD")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ gitRun(t, wt.Path, "checkout", "--quiet", "--detach", head)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "on a sibling\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work on the main line")++ requireRepairable(t, repo, wt, "did not deliver onto its own branch", map[string]string{"agent.txt": "on a sibling"})+}++// The common #8541 shape: the agent checked out a feature branch for its PR.+// Its own commits there extend the task branch; only HEAD is elsewhere.+func TestCheckDeliveryRepairsWorkOnAFeatureBranch(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ gitRun(t, wt.Path, "checkout", "--quiet", "-b", "feature/x")+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "feature\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "feature work")+ // And some leftovers it never committed.+ writeFile(t, filepath.Join(wt.WorkDir, "tracked.txt"), "edited\n")++ requireRepairable(t, repo, wt, "HEAD is not on branch", map[string]string{+ "agent.txt": "feature",+ "tracked.txt": "edited",+ })+}++// Uncommitted changes on a detached HEAD would be auto-committed onto the+// detached line, not the branch — the same refusal, predicted before it happens.+func TestCheckDeliveryRepairsUncommittedWorkOnADetachedHead(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ gitRun(t, wt.Path, "checkout", "--quiet", "--detach")+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "detached\n")++ requireRepairable(t, repo, wt, "HEAD is not on branch", map[string]string{"agent.txt": "detached"})+}++// A follow-up turn that squashes the whole branch — earlier turns included —+// back onto the user's HEAD. The repair keeps the follow-up's own starting+// point, so the earlier turns stay in the branch's history.+func TestCheckDeliveryRepairsAFollowUpThatSquashedTheWholeBranch(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ head := gitRun(t, repo, "rev-parse", "HEAD")++ first := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ writeFile(t, filepath.Join(first.WorkDir, "one.txt"), "turn one\n")+ finalizeOK(t, first)++ second := prepareTurn(t, repo, "MUL-9404", turnTwoTask)+ if !second.Continued {+ t.Fatal("second turn did not continue the branch")+ }+ writeFile(t, filepath.Join(second.WorkDir, "two.txt"), "turn two\n")+ gitRun(t, second.Path, "add", "-A")+ gitRun(t, second.Path, "commit", "-m", "turn two")+ gitRun(t, second.Path, "reset", "--soft", head)+ gitRun(t, second.Path, "commit", "-m", "everything in one")++ requireRepairable(t, repo, second, "no longer contains", map[string]string{+ "one.txt": "turn one",+ "two.txt": "turn two",+ })+}++// Work done on a line that never saw the baseline's content is not repaired+// either: here the baseline carries the user's uncommitted edit, the agent+// worked on a detached checkout of their HEAD, and re-committing that tree on+// the baseline would silently revert the user's edit.+func TestCheckDeliveryDoesNotOfferARepairThatRevertsTheUsersEdits(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user work in progress\n")+ head := gitRun(t, repo, "rev-parse", "HEAD")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ gitRun(t, wt.Path, "checkout", "--quiet", "--force", "--detach", head)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "off the baseline\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work without the user's edit")++ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("CheckDelivery offered a repair that would revert tracked.txt: %s", problem.Reason)+ }+ if _, err := wt.Finalize(worktreeTestLogger()); err == nil {+ t.Fatal("Finalize must still refuse this delivery")+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// A squash that keeps the user's replayed edit is still repairable.+func TestCheckDeliveryRepairsASquashThatKeptTheUsersEdits(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user work in progress\n")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "turn one\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ gitRun(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitRun(t, wt.Path, "commit", "-m", "squashed")++ requireRepairable(t, repo, wt, "no longer contains", map[string]string{+ "agent.txt": "turn one",+ "tracked.txt": "user work in progress",+ })+}++// MUL-8139 review: the same file carries both sides. The user's uncommitted+// edit changed one line; the agent, working on a checkout without it, changed+// another. Path-level checks see "both touched it" — only the content shows the+// user's line would be reverted, so no repair may be offered.+func TestCheckDeliveryDoesNotOfferARepairThatRevertsAUserEditInTheSameFile(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user=old\nagent=old\n")+ gitRun(t, repo, "add", "-A")+ gitRun(t, repo, "commit", "-m", "two independent settings")+ head := gitRun(t, repo, "rev-parse", "HEAD")+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user=NEW\nagent=old\n")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ gitRun(t, wt.Path, "checkout", "--quiet", "--force", "--detach", head)+ writeFile(t, filepath.Join(wt.Path, "tracked.txt"), "user=old\nagent=NEW\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "agent edit without the user's edit")++ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("CheckDelivery offered a repair that would revert user=NEW: %s", problem.Reason)+ }+ if _, err := wt.Finalize(worktreeTestLogger()); err == nil {+ t.Fatal("Finalize must still refuse this delivery")+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// The legitimate same-file case stays repairable: the agent built on the+// user's edit, changed another line of the same file, then squashed the+// baseline away. Its file already contains the user's change. (Edits on+// touching lines conflict in the three-way check and are refused instead —+// the safe direction, covered by the same-file revert test above.)+func TestCheckDeliveryRepairsASquashThatAlsoEditedTheUsersFile(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user=old\nctx1\nctx2\nctx3\nagent=old\n")+ gitRun(t, repo, "add", "-A")+ gitRun(t, repo, "commit", "-m", "two independent settings")+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user=NEW\nctx1\nctx2\nctx3\nagent=old\n")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ writeFile(t, filepath.Join(wt.Path, "tracked.txt"), "user=NEW\nctx1\nctx2\nctx3\nagent=NEW\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ gitRun(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitRun(t, wt.Path, "commit", "-m", "squashed")++ requireRepairable(t, repo, wt, "no longer contains", map[string]string{"tracked.txt": "user=NEW\nctx1\nctx2\nctx3\nagent=NEW"})+}++// userChmodBaseline commits run.sh without the executable bit, then makes it+// executable as the user's uncommitted change, which the turn's baseline+// records as mode 100755. It returns the repo, the pre-chmod HEAD and the turn.+func userChmodBaseline(t *testing.T) (string, string, *LocalWorktree) {+ t.Helper()+ if runtime.GOOS == "windows" {+ t.Skip("requires Unix executable bits")+ }+ repo := newTestRepo(t)+ gitRun(t, repo, "config", "core.filemode", "true")+ writeFile(t, filepath.Join(repo, "run.sh"), "#!/bin/sh\nexit 0\n")+ gitRun(t, repo, "add", "-A")+ gitRun(t, repo, "commit", "-m", "script before the user's chmod")+ head := gitRun(t, repo, "rev-parse", "HEAD")+ if err := os.Chmod(filepath.Join(repo, "run.sh"), 0o755); err != nil {+ t.Fatal(err)+ }+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ if entry := gitRun(t, repo, "ls-tree", wt.BaseCommit, "--", "run.sh"); !strings.HasPrefix(entry, "100755 ") {+ t.Fatalf("baseline did not record the user's chmod: %s", entry)+ }+ return repo, head, wt+}++// MUL-8139 review: a mode-only change carries no content difference, so a+// content check alone would offer a repair that delivers run.sh as 100644 —+// a silent revert of the user's chmod +x.+func TestCheckDeliveryDoesNotOfferARepairThatRevertsAUsersChmod(t *testing.T) {+ t.Parallel()+ repo, head, wt := userChmodBaseline(t)+ gitRun(t, wt.Path, "checkout", "--quiet", "--force", "--detach", head)+ writeFile(t, filepath.Join(wt.Path, "agent.txt"), "agent's separate change\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "agent work without the user's chmod")++ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("CheckDelivery offered a repair that would revert run.sh to 100644: %s", problem.Reason)+ }+ if _, err := wt.Finalize(worktreeTestLogger()); err == nil {+ t.Fatal("Finalize must still refuse this delivery")+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// A squash keeps the executable bit in the agent's files, so it stays+// repairable, and the delivered script is still 100755.+func TestCheckDeliveryRepairsASquashThatKeptTheUsersChmod(t *testing.T) {+ t.Parallel()+ repo, _, wt := userChmodBaseline(t)+ writeFile(t, filepath.Join(wt.Path, "agent.txt"), "work\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ gitRun(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitRun(t, wt.Path, "commit", "-m", "squashed")++ requireRepairable(t, repo, wt, "no longer contains", map[string]string{"agent.txt": "work"})+ if entry := gitRun(t, repo, "ls-tree", wt.Branch, "--", "run.sh"); !strings.HasPrefix(entry, "100755 ") {+ t.Fatalf("delivered run.sh lost the user's executable bit: %s", entry)+ }+}++// The MUL-6881 case stays a plain refusal: a run that reset back to the user's+// own HEAD discarded what the baseline carried, and re-committing that tree on+// top of the baseline would deliver a revert of the user's edits.+func TestCheckDeliveryDoesNotOfferToRepairAResetPastTheBaseline(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user work in progress\n")+ head := gitRun(t, repo, "rev-parse", "HEAD")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)++ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "turn one\n")+ gitRun(t, wt.Path, "reset", "--hard", head)++ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("CheckDelivery offered to repair a reset past the baseline: %s", problem.Reason)+ }+ if _, err := wt.Finalize(worktreeTestLogger()); err == nil || !strings.Contains(err.Error(), "no longer contains") {+ t.Fatalf("Finalize must still refuse this delivery, got %v", err)+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// Ordinary turns are never sent to repair.+func TestCheckDeliveryAcceptsOrdinaryTurns(t *testing.T) {+ t.Parallel()++ t.Run("committed on the branch", func(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "x\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("unexpected problem: %s", problem.Reason)+ }+ finalizeOK(t, wt)+ })++ t.Run("left uncommitted on the branch", func(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "x\n")+ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("unexpected problem: %s", problem.Reason)+ }+ finalizeOK(t, wt)+ })++ t.Run("read-only", func(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("unexpected problem: %s", problem.Reason)+ }+ finalizeOK(t, wt)+ })++ t.Run("nil worktree", func(t *testing.T) {+ var wt *LocalWorktree+ if wt.CheckDelivery() != nil {+ t.Fatal("nil worktree reported a problem")+ }+ })+}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 7acaecda78..403fece180 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -64,6 +64,7 @@ func perTurnContextBlocks(task Task, opts promptOpts) string {var b strings.Builderb.WriteString(buildSharedLocalDirectoryBlock(opts.sharedLocalDirectory))b.WriteString(buildWorktreeReplayConflictBlock(opts.worktreeReplayConflicts))+ b.WriteString(buildWorktreeBranchBlock(opts.worktreeBranch, opts.worktreeBase))if task.PriorSessionResumeUnavailable {b.WriteString(sessionContinuityNoticeFor(task))}@@ -104,6 +105,8 @@ func buildJoinedWakeupsBlock(notes string) string {type promptOpts struct {sharedLocalDirectory boolworktreeReplayConflicts []string+ worktreeBranch string+ worktreeBase string}// PromptOption tunes per-turn prompt copy with run-scoped context.@@ -129,6 +132,60 @@ func WithWorktreeReplayConflicts(files []string) PromptOption {return func(o *promptOpts) { o.worktreeReplayConflicts = files }}+// WithWorktreeBranch names the task branch a worktree-mode turn delivers on and+// the commit it started from. The daemon refuses to record a delivery that is+// not on that branch or no longer contains that commit (MUL-6881), and nothing+// inside the worktree tells the agent so — squashing or switching branches is+// ordinary git hygiene it would otherwise reach for (#9404).+func WithWorktreeBranch(branch, base string) PromptOption {+ return func(o *promptOpts) {+ o.worktreeBranch = branch+ o.worktreeBase = base+ }+}++// buildWorktreeBranchBlock states the delivery contract of a worktree turn.+// Branch names come from the daemon's own sanitised naming and the base is a+// hex object id, so both are safe to render in code spans.+func buildWorktreeBranchBlock(branch, base string) string {+ if branch == "" || base == "" {+ return ""+ }+ var b strings.Builder+ b.WriteString("## Your task branch\n\n")+ fmt.Fprintf(&b, "This run works in a private git worktree on branch `%s`, starting from commit `%s`. What that branch holds when you finish is what gets delivered, and the next turn continues from it.\n\n", branch, base)+ fmt.Fprintf(&b, "- Keep HEAD on `%s` and only add commits on top of `%s`. Do not squash, amend, rebase or reset past `%s`, and do not check out another branch or a detached HEAD to do the work.\n", branch, base, base)+ b.WriteString("- To publish the work under another name (for a pull request), push it without switching: `git push origin HEAD:<name>`.\n")+ b.WriteString("- A delivery that is not on this branch, or no longer contains its starting commit, cannot be recorded: the task fails even though the work is done.\n\n")+ return b.String()+}++// BuildWorktreeDeliveryRepairPrompt is the follow-up turn the daemon runs when+// the agent finished with its work somewhere Finalize would refuse to record.+// It is self-contained — the backend may not be able to resume the session, so+// nothing here may depend on the agent remembering the turn it just ran.+func BuildWorktreeDeliveryRepairPrompt(problem *execenv.DeliveryProblem) string {+ var b strings.Builder+ b.WriteString("Your previous turn in this git worktree finished, but its work cannot be delivered yet.\n\n")+ fmt.Fprintf(&b, "Problem: %s.\n\n", problem.Reason)+ fmt.Fprintf(&b, "The work has to end on branch `%s`, in commits on top of `%s` (the commit this turn started from), with HEAD on that branch. Your files are intact; only where they are committed is wrong.\n\n", problem.Branch, problem.BaseCommit)+ b.WriteString("Fix it in this worktree. This sequence keeps every file exactly as it is now and puts it on the branch as one commit:\n\n```sh\n")+ for _, step := range problem.RepairSteps() {+ b.WriteString("git")+ for _, arg := range step {+ if strings.ContainsAny(arg, " '\"") {+ arg = "'" + strings.ReplaceAll(arg, "'", `'\''`) + "'"+ }+ b.WriteString(" " + arg)+ }+ b.WriteString("\n")+ }+ b.WriteString("```\n\n")+ fmt.Fprintf(&b, "Before the final commit, check `git diff --cached %s`: it should show only the changes you meant to make. If it undoes something `%s` contains that you did not intend to remove, restore it first. You may keep separate commits instead (for example by rebasing them onto `%s`), as long as the end state is the same.\n\n", problem.BaseCommit, problem.BaseCommit, problem.BaseCommit)+ b.WriteString("Do only this — no other changes, no new comments or status updates. Reply with one line saying what you did.\n")+ return b.String()+}+// buildSharedLocalDirectoryBlock warns an unlocked turn that its working// directory is shared live. Deliberately guidance and not a prohibition: the// mutex never covered the user's own editor either, so refusing writes herediff --git a/server/internal/daemon/worktree_delivery_repair_supplement_test.go b/server/internal/daemon/worktree_delivery_repair_supplement_test.gonew file mode 100644index 0000000000..5c2d23d5d4--- /dev/null+++ b/server/internal/daemon/worktree_delivery_repair_supplement_test.go@@ -0,0 +1,94 @@+package daemon++import (+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/pkg/agent"+)++type supplementRepairBackend struct {+ repairingBackend+ ack <-chan struct{}+}++func (b *supplementRepairBackend) Execute(ctx context.Context, prompt string, opts agent.ExecOptions) (*agent.Session, error) {+ if _, err := b.repairingBackend.Execute(ctx, prompt, opts); err != nil {+ return nil, err+ }+ messages := make(chan agent.Message)+ results := make(chan agent.Result, 1)+ go func() {+ if opts.EnableTaskSupplement {+ select {+ case <-b.ack:+ case <-ctx.Done():+ }+ }+ close(messages)+ results <- agent.Result{Status: "completed", Output: "repair done; the requested additional answer is 42"}+ }()+ return &agent.Session{+ Messages: messages, Result: results,+ SupplementReady: func() bool { return true },+ Supplement: func(context.Context, string) error { return nil },+ }, nil+}++// MUL-8139 review: the repair turn's reply is discarded, so it must not claim+// an additional message — that would ack it as delivered and lose the answer.+// Left unclaimed, the server settles it as turn_ended, which the receipt shows.+func TestRepairWorktreeDeliveryDoesNotConsumeAdditionalMessages(t *testing.T) {+ _, wt := squashedWorktree(t)+ ack := make(chan struct{})+ var delivered atomic.Bool+ var claims atomic.Int32+ d := taskSupplementTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/supplements/claim"):+ if claims.Add(1) == 1 {+ _ = json.NewEncoder(w).Encode(map[string]string{"comment_id": "review-comment", "author_name": "User", "content": "Also answer my additional question"})+ } else {+ w.WriteHeader(http.StatusPreconditionFailed)+ }+ case strings.HasSuffix(r.URL.Path, "/supplements/review-comment/ack"):+ var body struct {+ Delivered bool `json:"delivered"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ }+ delivered.Store(body.Delivered)+ close(ack)+ default:+ w.WriteHeader(http.StatusOK)+ }+ })+ problem := wt.CheckDelivery()+ backend := &supplementRepairBackend{repairingBackend: repairingBackend{worktree: wt, problem: problem, comply: true}, ack: ack}+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)+ defer cancel()+ result, _ := d.repairWorktreeDelivery(ctx, backend, agent.ExecOptions{EnableTaskSupplement: true}, agent.Result{Status: "completed", Output: "original reply"}, 0, problem, &execenv.Environment{LocalWorktree: wt}, slog.Default(), "review-task", new(atomic.Int32))+ if backend.runErr != nil {+ t.Fatal(backend.runErr)+ }+ if _, err := wt.Finalize(slog.Default()); err != nil {+ t.Fatal(err)+ }+ if backend.gotOpts.EnableTaskSupplement {+ t.Error("the repair turn was started with additional-message intake enabled")+ }+ if n := claims.Load(); n != 0 {+ t.Errorf("the repair turn claimed %d additional message(s)", n)+ }+ if delivered.Load() && !strings.Contains(result.Output, "42") {+ t.Fatalf("additional guidance acknowledged delivered during housekeeping, but its answer was discarded: output=%q", result.Output)+ }+}diff --git a/server/internal/daemon/worktree_delivery_repair_test.go b/server/internal/daemon/worktree_delivery_repair_test.gonew file mode 100644index 0000000000..4eda82e039--- /dev/null+++ b/server/internal/daemon/worktree_delivery_repair_test.go@@ -0,0 +1,272 @@+package daemon++import (+ "context"+ "fmt"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/pkg/agent"+)++// #9404: a worktree turn is told up front where its delivery has to end, so+// the squash / feature-branch habits that the daemon cannot record are avoided+// rather than repaired.+func TestWorktreeBranchBlock(t *testing.T) {+ task := Task{IssueID: "issue-1"}++ if out := BuildPrompt(task, "claude"); strings.Contains(out, "Your task branch") {+ t.Fatal("a non-worktree turn got the task-branch block")+ }++ out := BuildPrompt(task, "claude", WithWorktreeBranch("agent/j/mul-9404", "abc123def"))+ for _, want := range []string{+ "## Your task branch",+ "`agent/j/mul-9404`",+ "`abc123def`",+ "Do not squash, amend, rebase or reset past `abc123def`",+ "git push origin HEAD:<name>",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("prompt missing %q:\n%s", want, out)+ }+ }+}++// The repair prompt renders exactly execenv's RepairSteps (which the execenv+// tests run against real repositories), and quotes them so a shell receives the+// same argv — the commit message carries an apostrophe.+func TestBuildWorktreeDeliveryRepairPrompt(t *testing.T) {+ problem := &execenv.DeliveryProblem{+ Branch: "agent/j/mul-9404",+ BaseCommit: "abc123def",+ Tip: "fff000",+ Reason: "the delivered commit fff000 no longer contains abc123de, the commit this turn started from",+ }+ out := BuildWorktreeDeliveryRepairPrompt(problem)+ for _, want := range []string{problem.Reason, "`agent/j/mul-9404`", "git diff --cached abc123def", "no new comments or status updates"} {+ if !strings.Contains(out, want) {+ t.Errorf("repair prompt missing %q:\n%s", want, out)+ }+ }++ start := strings.Index(out, "```sh\n")+ end := strings.Index(out[start+6:], "```")+ if start < 0 || end < 0 {+ t.Fatalf("repair prompt has no sh block:\n%s", out)+ }+ lines := strings.Split(strings.TrimSpace(out[start+6:start+6+end]), "\n")+ steps := problem.RepairSteps()+ if len(lines) != len(steps) {+ t.Fatalf("rendered %d commands, want %d:\n%s", len(lines), len(steps), out)+ }+ if _, err := exec.LookPath("sh"); err != nil {+ t.Skip("sh not available to check quoting")+ }+ for i, line := range lines {+ if !strings.HasPrefix(line, "git ") {+ t.Fatalf("line %d is not a git command: %q", i, line)+ }+ // Let the shell parse the arguments and echo them back one per line.+ got, err := exec.Command("sh", "-c", `printf '%s\n' `+strings.TrimPrefix(line, "git ")).Output()+ if err != nil {+ t.Fatalf("sh could not parse %q: %v", line, err)+ }+ if want := strings.Join(steps[i], "\n"); strings.TrimSuffix(string(got), "\n") != want {+ t.Errorf("line %d parses to %q, want %q", i, got, want)+ }+ }+}++func TestMergeWorktreeRepairResult(t *testing.T) {+ original := agent.Result{+ Status: "completed",+ Output: "the real reply",+ SessionID: "s1",+ Usage: map[string]agent.TokenUsage{"m": {InputTokens: 10}},+ }++ t.Run("repair completed", func(t *testing.T) {+ repair := agent.Result{Status: "completed", Output: "fixed the branch", SessionID: "s2",+ Usage: map[string]agent.TokenUsage{"m": {InputTokens: 5}}}+ got, tools := mergeWorktreeRepairResult(original, 3, repair, 2, nil)+ if got.Output != "the real reply" || got.Status != "completed" {+ t.Errorf("the task reply was replaced: %+v", got)+ }+ if got.SessionID != "s2" {+ t.Errorf("SessionID = %q, want the repair turn's s2", got.SessionID)+ }+ if got.Usage["m"].InputTokens != 15 || tools != 5 {+ t.Errorf("usage/tools not added up: %+v, %d", got.Usage, tools)+ }+ })++ t.Run("repair failed", func(t *testing.T) {+ repair := agent.Result{Status: "failed", SessionID: "s3", Usage: map[string]agent.TokenUsage{"m": {InputTokens: 1}}}+ got, _ := mergeWorktreeRepairResult(original, 3, repair, 0, nil)+ if got.SessionID != "s1" || got.Status != "completed" {+ t.Errorf("a failed repair changed the outcome: %+v", got)+ }+ if got.Usage["m"].InputTokens != 11 {+ t.Errorf("the failed repair's usage was dropped: %+v", got.Usage)+ }+ })++ t.Run("repair never started", func(t *testing.T) {+ got, tools := mergeWorktreeRepairResult(original, 3, agent.Result{}, 0, exec.ErrNotFound)+ if got.SessionID != "s1" || tools != 3 || got.Output != "the real reply" {+ t.Errorf("a repair that never started changed the result: %+v", got)+ }+ })+}++// repairingBackend plays an agent that follows the repair prompt: it records+// what it was asked and runs the prompt's git commands in the worktree.+type repairingBackend struct {+ worktree *execenv.LocalWorktree+ problem *execenv.DeliveryProblem+ comply bool++ gotPrompt string+ gotOpts agent.ExecOptions+ runErr error+}++func (b *repairingBackend) Execute(_ context.Context, prompt string, opts agent.ExecOptions) (*agent.Session, error) {+ b.gotPrompt, b.gotOpts = prompt, opts+ if b.comply {+ for _, step := range b.problem.RepairSteps() {+ if out, err := exec.Command("git", append([]string{"-C", b.worktree.Path}, step...)...).CombinedOutput(); err != nil {+ b.runErr = fmt.Errorf("git %v: %s: %w", step, out, err)+ break+ }+ }+ }+ msgCh := make(chan agent.Message)+ resCh := make(chan agent.Result, 1)+ close(msgCh)+ resCh <- agent.Result{Status: "completed", Output: "moved the work back onto the branch", SessionID: "sess-repair",+ Usage: map[string]agent.TokenUsage{"m": {InputTokens: 7}}}+ return &agent.Session{Messages: msgCh, Result: resCh}, nil+}++func gitOK(t *testing.T, dir string, args ...string) string {+ t.Helper()+ out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %s: %v", args, out, err)+ }+ return strings.TrimSpace(string(out))+}++// squashedWorktree builds the #9404 shape-one state: a worktree turn whose+// agent committed, then squashed its baseline away.+func squashedWorktree(t *testing.T) (string, *execenv.LocalWorktree) {+ t.Helper()+ if _, err := exec.LookPath("git"); err != nil {+ t.Skip("git not available")+ }+ repo := t.TempDir()+ if resolved, err := filepath.EvalSymlinks(repo); err == nil {+ repo = resolved+ }+ gitOK(t, repo, "init", "-q", "-b", "main")+ gitOK(t, repo, "config", "user.name", "Test")+ gitOK(t, repo, "config", "user.email", "[email protected]")+ gitOK(t, repo, "config", "gc.auto", "0")+ if err := os.WriteFile(filepath.Join(repo, "a.txt"), []byte("a\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ gitOK(t, repo, "add", "-A")+ gitOK(t, repo, "commit", "-q", "-m", "initial")++ wt, err := execenv.PrepareLocalWorktree(execenv.LocalWorktreeParams{+ LocalPath: repo,+ EnvRoot: t.TempDir(),+ AgentName: "j",+ TaskID: "11112222-3333-4444-5555-aaaaaaaaaaaa",+ ConversationKey: "MUL-9404",+ WorkspaceID: "ws",+ AgentID: "agent",+ ConversationID: "issue",+ }, slog.Default())+ if err != nil {+ t.Fatalf("PrepareLocalWorktree: %v", err)+ }+ if err := os.WriteFile(filepath.Join(wt.WorkDir, "agent.txt"), []byte("work\n"), 0o644); err != nil {+ t.Fatal(err)+ }+ gitOK(t, wt.Path, "add", "-A")+ gitOK(t, wt.Path, "commit", "-q", "-m", "work")+ gitOK(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitOK(t, wt.Path, "commit", "-q", "-m", "squashed")+ return repo, wt+}++// End to end through the daemon's repair turn: the agent is resumed in its own+// session with the repair prompt, follows it, and Finalize then records the+// delivery it would have refused.+func TestRepairWorktreeDeliveryLetsTheAgentFixItsBranch(t *testing.T) {+ t.Parallel()+ repo, wt := squashedWorktree(t)+ problem := wt.CheckDelivery()+ if problem == nil {+ t.Fatal("expected a delivery problem after the squash")+ }++ d, _ := newPinRecorder(t)+ backend := &repairingBackend{worktree: wt, problem: problem, comply: true}+ original := agent.Result{Status: "completed", Output: "the real reply", SessionID: "sess-1"}+ env := &execenv.Environment{LocalWorktree: wt}++ got, _ := d.repairWorktreeDelivery(context.Background(), backend, agent.ExecOptions{Timeout: time.Hour}, original, 1, problem, env, slog.Default(), "task-repair", new(atomic.Int32))+ if backend.runErr != nil {+ t.Fatalf("the repair prompt's commands failed: %v", backend.runErr)+ }+ if backend.gotOpts.ResumeSessionID != "sess-1" {+ t.Errorf("repair turn resumed %q, want the turn's own session sess-1", backend.gotOpts.ResumeSessionID)+ }+ if backend.gotOpts.Timeout != worktreeRepairTimeout {+ t.Errorf("repair turn timeout = %s, want %s", backend.gotOpts.Timeout, worktreeRepairTimeout)+ }+ if !strings.Contains(backend.gotPrompt, problem.Reason) {+ t.Errorf("repair prompt does not name the problem:\n%s", backend.gotPrompt)+ }+ if got.Output != "the real reply" || got.SessionID != "sess-repair" {+ t.Errorf("merged result = %+v", got)+ }++ if _, err := wt.Finalize(slog.Default()); err != nil {+ t.Fatalf("Finalize still refused after the repair: %v", err)+ }+ if content := gitOK(t, repo, "show", wt.Branch+":agent.txt"); content != "work" {+ t.Errorf("agent.txt on the branch = %q", content)+ }+}++// An agent that ignores the repair prompt changes nothing: Finalize refuses+// exactly as it did before this feature.+func TestRepairWorktreeDeliveryLeavesTheRefusalWhenTheAgentDoesNotFixIt(t *testing.T) {+ t.Parallel()+ _, wt := squashedWorktree(t)+ problem := wt.CheckDelivery()+ if problem == nil {+ t.Fatal("expected a delivery problem after the squash")+ }++ d, _ := newPinRecorder(t)+ backend := &repairingBackend{worktree: wt, problem: problem, comply: false}+ env := &execenv.Environment{LocalWorktree: wt}+ d.repairWorktreeDelivery(context.Background(), backend, agent.ExecOptions{}, agent.Result{Status: "completed"}, 0, problem, env, slog.Default(), "task-norepair", new(atomic.Int32))++ if _, err := wt.Finalize(slog.Default()); err == nil || !strings.Contains(err.Error(), "no longer contains") {+ t.Fatalf("Finalize = %v, want the original refusal", err)+ }+}