Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7488: fix(execenv): exclude committed local HEAD changes from resume replay (#8549)

Dante6d5cdcbed2a7
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdx
index 16b43d695f..06540af3d8 100644
--- a/apps/docs/content/docs/project-resources.mdx
+++ b/apps/docs/content/docs/project-resources.mdx
@@ -81,6 +81,7 @@ What the agent sees, and what you get back:
- **The agent starts from what you see, not from `HEAD`.** Your uncommitted edits and your untracked files are replayed into the worktree, so the agent is not reviewing code you no longer have. Your own working copy, index, and stash list are never touched. If that state cannot be reproduced faithfully — including when there is more untracked content than the replay covers (2000 files / 200 MiB) — the run fails instead of starting from a tree you would not recognise. The usual fix is to gitignore or clean up build output that is not already ignored.
- **The result is a branch in your repo**, one per issue rather than one per run: `agent/<agent>/<issue>` (a chat gets `agent/<agent>/chat-<session>`). The run's **Run details** panel shows the branch name (and lets you copy it); you can also find it with `git branch`. Review it with `git log` / `git diff`, and merge or cherry-pick it yourself. Multica never merges it for you. A run that failed partway still reports its branch, because it still committed whatever the agent had produced.
- **A follow-up continues where the last run stopped.** The next comment on the same issue checks that branch out again, so the agent is standing on the work it just delivered instead of starting from `HEAD` with its own changes stranded on another branch. Only what you changed in your own directory since the last run is replayed on top — the branch already carries the rest. Merge the branch and the next run starts from your `HEAD` again. If two runs on one issue overlap, the second one forks from the first's work onto `agent/<agent>/<issue>-<task>`, because git allows one worktree per branch.
+- **Committed updates to your local `HEAD` are kept separate from uncommitted edits.** A pull or local commit between turns is not replayed onto the issue branch; merge those commits into it explicitly when needed. If the previous run captured uncommitted work, comparing it on the new `HEAD` requires Git 2.40 or later. If those older edits conflict with the new committed baseline, the runtime logs a warning and uses the current `HEAD` only for the affected paths; other drafts keep their incremental comparison. Finishing and committing one draft therefore does not block future runs or re-propose your unchanged drafts against the agent's work. Any conflict between your current edits and the agent's work is still offered to the agent to resolve.
- **If your edits collide with the agent's, the agent resolves them.** When you rewrite the same lines the agent rewrote, git cannot decide which version wins, so the run starts on a conflicted worktree and is told to finish the merge before anything else — `git status` in that worktree lists the unmerged paths. A run that leaves any file unmerged delivers nothing: it fails, keeps the worktree, and the next run offers the same edits again, so your change is never quietly dropped.
- **Only branches Multica owns are continued.** Continuing a branch is decided by an ownership record, not by its name: the record names the conversation, and it names the commit the branch was left at. A branch you created yourself that happens to be called `agent/<agent>/<issue>` is never checked out, appended to, or read as a previous run — and neither is one that no longer contains the recorded commit, so deleting Multica's branch and making your own under that name, or force-moving it onto other history, is safe. In those cases the run takes `agent/<agent>/<issue>-<id>` instead. Committing on top of a delivered branch is the normal case and keeps it continuing — your commit is simply there in the next run. Every branch also starts with a baseline commit of its own, marking the tree the first run began from — that commit is what identifies the branch later, and `git diff <baseline>..<branch>` is exactly the agent's work. A run that could not record its branch — it failed before finishing, the record could not be written, or it reset its worktree past the commit that carried your edits into the branch — reports failure and keeps its worktree, and later runs start a new branch rather than continuing one they cannot prove is theirs.
- **Nothing is silently dropped.** Anything the agent leaves uncommitted is committed to that branch before the worktree is removed, including when the run fails partway. In the rare case that commit itself cannot be made — for example a repo with `commit.gpgSign` and no signing key available to the runtime — the worktree is deliberately kept instead of removed, the run is reported as failed, and `git worktree list` in your repo points at the directory holding the work.
diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.go
index 440bee6c4e..773a0265d6 100644
--- a/server/internal/daemon/execenv/local_worktree.go
+++ b/server/internal/daemon/execenv/local_worktree.go
@@ -1329,6 +1329,11 @@ type replayResult struct {
// itself, so the whole snapshot applies and cannot conflict. For a continued
// branch it is the snapshot that branch recorded, which is what makes this a
// replay of the user's LAST-TURN-TO-NOW edits rather than of their whole tree.
+// If the local HEAD changed, first transplant the previous uncommitted edits
+// onto the new HEAD. Comparing snapshots on that shared baseline excludes
+// committed updates without re-proposing edits the branch already carries.
+// If that transplant conflicts, use current HEAD for the affected paths while
+// retaining the successfully normalized edits in all other paths.
//
// Replaying the whole tree onto a continued branch is the tempting version and
// it is wrong: that merge takes the user's HEAD as its base, so it re-proposes
@@ -1346,7 +1351,11 @@ type replayResult struct {
func replayUserState(worktreePath string, plan taskBranchPlan, snapshot string, logger *slog.Logger) (replayResult, error) {
carried := plan.base
if plan.continues {
- carried = plan.priorState
+ var err error
+ carried, err = normalizeReplayBaseline(worktreePath, plan.priorState, snapshot, logger)
+ if err != nil {
+ return replayResult{}, err
+ }
}
if carried == "" {
return replayResult{}, fmt.Errorf("execenv: no baseline to replay the local directory against for branch %s", plan.name)
@@ -1404,6 +1413,161 @@ func replayUserState(worktreePath string, plan taskBranchPlan, snapshot string,
return replayResult{conflicts: conflicts}, nil
}
+// normalizeReplayBaseline puts the previously carried WIP on the current local
+// HEAD before calculating its incremental change. Writes are limited to Git
+// objects and disposable scratch files; neither live checkout/index nor the task
+// branch or its record is moved.
+func normalizeReplayBaseline(worktreePath, priorState, snapshot string, logger *slog.Logger) (string, error) {
+ // A record has two parents; its first is a snapshot or, after a conflict
+ // resolved without a commit, another record. Follow only that parent until
+ // the first one-parent commit: the actual snapshot, parented at local HEAD.
+ // Limit the result to that snapshot, not the repository's entire history.
+ previous, err := runGitTrimmed(worktreePath, "rev-list", "--first-parent", "--parents",
+ "--min-parents=1", "--max-parents=1", "--max-count=1", priorState)
+ if err != nil {
+ return "", fmt.Errorf("execenv: could not read the previous local snapshot: %w", err)
+ }
+ fields := strings.Fields(previous)
+ if len(fields) != 2 {
+ return "", errors.New("execenv: the previous local snapshot has no captured HEAD")
+ }
+ previousSnapshot, previousHead := fields[0], fields[1]
+ currentHead, err := runGitTrimmed(worktreePath, "rev-parse", "--verify", snapshot+"^1")
+ if err != nil {
+ return "", fmt.Errorf("execenv: could not read the current local snapshot's HEAD: %w", err)
+ }
+ if previousHead == currentHead {
+ return priorState, nil
+ }
+ // With no previous WIP, transplanting it is the identity operation. This
+ // also avoids requiring merge-tree when a clean local directory advances.
+ if _, err := runGit(worktreePath, "diff", "--quiet", previousHead, previousSnapshot); err == nil {
+ return currentHead, nil
+ }
+
+ // Use the captured HEAD as an explicit base. A record's second parent is
+ // the agent checkpoint, which may already contain newer mainline commits;
+ // using Git's inferred merge base could then subtract the wrong changes.
+ merged, err := runGitStdout(worktreePath, "merge-tree", "--write-tree", "--name-only", "--messages", "-z",
+ "--merge-base="+previousHead, currentHead, previousSnapshot)
+ tree, _, hasTree := strings.Cut(merged, "\x00")
+ if err != nil {
+ var exitErr *exec.ExitError
+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 1 {
+ paths, pathsErr := mergeTreeConflictPaths(merged)
+ if pathsErr != nil {
+ return "", fmt.Errorf("execenv: could not read the conflicted local snapshot: %w", pathsErr)
+ }
+ // A single conflicting draft must not re-propose every untouched
+ // draft against the agent's edits. Preserve the merged tree and
+ // replace only the conflicting paths with their current HEAD state.
+ if len(paths) == 0 {
+ // Git can report a tree-level conflict without affected paths.
+ // Retain the resumable current-WIP behavior in that case.
+ if logger != nil {
+ logger.Warn("execenv: local snapshot merge reported a conflict without paths; replaying current uncommitted edits",
+ "path", worktreePath, "previous_head", previousHead, "current_head", currentHead)
+ }
+ return currentHead, nil
+ }
+ tree, err = replaceConflictedSnapshotPaths(worktreePath, tree, currentHead, paths)
+ if err != nil {
+ return "", err
+ }
+ if logger != nil {
+ logger.Warn("execenv: previous local edits conflict with the committed HEAD update; replaying current edits only for the affected paths",
+ "path", worktreePath, "previous_head", previousHead, "current_head", currentHead, "files", quotedPaths(paths))
+ }
+ } else {
+ return "", fmt.Errorf("execenv: could not normalize previous uncommitted edits onto the current local HEAD "+
+ "(this operation requires Git 2.40 or later); the task branch and its previous snapshot are preserved: %w", err)
+ }
+ }
+ if !hasTree || tree == "" {
+ return "", errors.New("execenv: the normalized local snapshot has no tree")
+ }
+ // The replay commit needs a commit parent, not just a tree. This object is
+ // only a comparison baseline: its committed HEAD changes never enter the
+ // task branch, which cherry-picks only baseline-to-current-snapshot edits.
+ args := append(commitIdentityArgs(worktreePath), "commit-tree", tree, "-p", currentHead,
+ "-m", "multica: previous local edits on the current HEAD")
+ baseline, err := runGitTrimmed(worktreePath, args...)
+ if err != nil {
+ return "", fmt.Errorf("execenv: could not describe the normalized local snapshot: %w", err)
+ }
+ return baseline, nil
+}
+
+// mergeTreeConflictPaths reads merge-tree's NUL-delimited file and message
+// sections. Conflict messages also name paths for directory-rename conflicts
+// that have no unmerged file entries. Never parse the human-readable message.
+func mergeTreeConflictPaths(output string) ([]string, error) {
+ fields := strings.Split(output, "\x00")
+ if len(fields) < 3 || fields[0] == "" || fields[len(fields)-1] != "" {
+ return nil, errors.New("invalid merge-tree output")
+ }
+ var paths []string
+ seen := make(map[string]bool)
+ add := func(name string) {
+ if name != "" && !seen[name] {
+ paths = append(paths, name)
+ seen[name] = true
+ }
+ }
+ i := 1
+ for i < len(fields) && fields[i] != "" {
+ add(fields[i])
+ i++
+ }
+ i++ // End of the unmerged-file section.
+ for i < len(fields)-1 {
+ count, err := strconv.Atoi(fields[i])
+ i++
+ if err != nil || count < 0 || count > len(fields)-i-3 {
+ return nil, errors.New("invalid merge-tree conflict message")
+ }
+ if strings.HasPrefix(fields[i+count], "CONFLICT") {
+ for _, name := range fields[i : i+count] {
+ add(name)
+ }
+ }
+ i += count + 2 // Affected paths, conflict type, and message.
+ }
+ return paths, nil
+}
+
+// replaceConflictedSnapshotPaths edits only a private index beside the task
+// worktree. Resetting explicit literal paths handles additions, deletions,
+// renames and file/directory conflicts without touching either live index.
+func replaceConflictedSnapshotPaths(worktreePath, tree, currentHead string, paths []string) (string, error) {
+ if len(paths) == 0 {
+ return "", errors.New("execenv: no conflicted snapshot paths to replace")
+ }
+ dir, err := os.MkdirTemp(filepath.Dir(worktreePath), ".multica-normalize-")
+ if err != nil {
+ return "", fmt.Errorf("execenv: create private normalization index: %w", err)
+ }
+ defer os.RemoveAll(dir)
+ env := []string{"GIT_INDEX_FILE=" + filepath.Join(dir, "index"), "GIT_LITERAL_PATHSPECS=1"}
+ if out, err := runGitEnv(worktreePath, env, "read-tree", tree); err != nil {
+ return "", fmt.Errorf("execenv: seed private normalization index: %s: %w", strings.TrimSpace(out), err)
+ }
+ pathFile := filepath.Join(dir, "paths")
+ if err := os.WriteFile(pathFile, []byte(strings.Join(paths, "\x00")+"\x00"), 0o600); err != nil {
+ return "", fmt.Errorf("execenv: write conflicted snapshot paths: %w", err)
+ }
+ // The nonempty pathspec file selects reset's index-only form. Using a file
+ // avoids command-length limits and preserves whitespace in repository names.
+ if out, err := runGitEnv(worktreePath, env, "reset", currentHead, "--pathspec-from-file="+pathFile, "--pathspec-file-nul"); err != nil {
+ return "", fmt.Errorf("execenv: replace conflicted snapshot paths: %s: %w", strings.TrimSpace(out), err)
+ }
+ normalized, err := runGitTrimmedEnv(worktreePath, env, "write-tree")
+ if err != nil {
+ return "", fmt.Errorf("execenv: write normalized local snapshot: %w", err)
+ }
+ return normalized, nil
+}
+
// quotedPaths renders repository paths for a human-facing message. Quoted
// because a git path may contain newlines, quotes or control characters, and
// this string is read in logs and task errors where a raw one would look like
@@ -1704,7 +1868,8 @@ func runGitTrimmedEnv(dir string, extraEnv []string, args ...string) (string, er
// runGitStdout is runGitTrimmed without the trimming, for output where
// whitespace is significant — NUL-separated file listings, where a leading or
-// trailing space is part of a filename.
+// trailing space is part of a filename. Retain partial stdout on error for
+// plumbing like merge-tree, which emits a useful tree on a conflict.
func runGitStdout(dir string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
defer cancel()
@@ -1714,7 +1879,7 @@ func runGitStdout(dir string, args ...string) (string, error) {
cmd.WaitDelay = 5 * time.Second
out, err := cmd.Output()
if err != nil {
- return "", withGitStderr(err)
+ return string(out), withGitStderr(err)
}
return string(out), nil
}
diff --git a/server/internal/daemon/execenv/local_worktree_test.go b/server/internal/daemon/execenv/local_worktree_test.go
index 6543ddf1d3..8bf81b38c9 100644
--- a/server/internal/daemon/execenv/local_worktree_test.go
+++ b/server/internal/daemon/execenv/local_worktree_test.go
@@ -888,6 +888,412 @@ func TestPrepareLocalWorktreeContinuesTheConversationBranch(t *testing.T) {
}
}
+// A clean local HEAD advancing during a turn is committed work, not a new
+// user edit to replay onto the conversation branch (#8544).
+func TestPrepareLocalWorktreeDoesNotReplayCleanHEADAdvance(t *testing.T) {
+ for _, dirty := range []bool{false, true} {
+ t.Run(fmt.Sprintf("new_local_edit_%t", dirty), func(t *testing.T) {
+ repo := newTestRepo(t)
+ first := prepareTurn(t, repo, "MUL-6881", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "turn-one.txt"), "agent work\n")
+ writeFile(t, filepath.Join(repo, "upstream.txt"), "committed upstream work\n")
+ gitRun(t, repo, "add", "upstream.txt")
+ gitRun(t, repo, "commit", "-m", "advance local HEAD")
+ finalizeOK(t, first)
+ firstTip := gitRun(t, repo, "rev-parse", first.Branch)
+ if dirty {
+ writeFile(t, filepath.Join(repo, "local-edit.txt"), "new uncommitted work\n")
+ }
+
+ second := prepareTurn(t, repo, "MUL-6881", turnTwoTask)
+ if !second.Continued || second.Branch != first.Branch {
+ t.Fatalf("expected to continue %s, got %s (continued=%v)", first.Branch, second.Branch, second.Continued)
+ }
+ if _, err := os.Stat(filepath.Join(second.WorkDir, "upstream.txt")); !os.IsNotExist(err) {
+ t.Fatalf("committed local HEAD advance was replayed: %v", err)
+ }
+ if got := readFile(t, filepath.Join(second.WorkDir, "turn-one.txt")); got != "agent work\n" {
+ t.Fatalf("agent work changed: %q", got)
+ }
+ if dirty {
+ if got := readFile(t, filepath.Join(second.WorkDir, "local-edit.txt")); got != "new uncommitted work\n" {
+ t.Fatalf("new local edit missing: %q", got)
+ }
+ } else if second.BaseCommit != firstTip {
+ t.Fatalf("clean resume authored a commit: %s != %s", second.BaseCommit, firstTip)
+ }
+ finalizeOK(t, second)
+ secondTip := gitRun(t, repo, "rev-parse", second.Branch)
+ third := prepareTurn(t, repo, "MUL-6881", turnThreeTask)
+ if third.BaseCommit != secondTip {
+ t.Fatalf("unchanged third turn replayed local state again: %s != %s", third.BaseCommit, secondTip)
+ }
+ finalizeOK(t, third)
+ })
+ }
+}
+
+func TestPrepareLocalWorktreeExcludesHEADAdvanceWithExistingUserEdits(t *testing.T) {
+ for _, kind := range []string{"untracked", "tracked", "deleted"} {
+ for _, newEdits := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/new_edits_%t", kind, newEdits), func(t *testing.T) {
+ repo := newTestRepo(t)
+ switch kind {
+ case "untracked":
+ writeFile(t, filepath.Join(repo, "draft.txt"), "user draft\n")
+ case "tracked":
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user WIP\n")
+ case "deleted":
+ if err := os.Remove(filepath.Join(repo, "tracked.txt")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeFile(t, filepath.Join(repo, "notes.txt"), "old user notes\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "task.txt"), "agent work\n")
+ if kind == "untracked" {
+ writeFile(t, filepath.Join(first.WorkDir, "draft.txt"), "draft improved by the agent\n")
+ } else if kind == "tracked" {
+ writeFile(t, filepath.Join(first.WorkDir, "tracked.txt"), "WIP improved by the agent\n")
+ }
+ finalizeOK(t, first)
+ firstTip := gitRun(t, repo, "rev-parse", first.Branch)
+
+ // Advancing HEAD commits only upstream work, leaving all WIP alone.
+ writeFile(t, filepath.Join(repo, "upstream.txt"), "committed upstream work\n")
+ gitRun(t, repo, "add", "upstream.txt")
+ gitRun(t, repo, "commit", "-m", "advance local HEAD")
+ if newEdits {
+ writeFile(t, filepath.Join(repo, "keep.txt"), "new tracked user edit\n")
+ writeFile(t, filepath.Join(repo, "scratch.txt"), "new untracked user edit\n")
+ if err := os.Remove(filepath.Join(repo, "notes.txt")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ sourceStatus := gitRun(t, repo, "status", "--porcelain")
+ sourceIndex := gitRun(t, repo, "ls-files", "--stage")
+ second := prepareTurn(t, repo, "MUL-7488", turnTwoTask)
+ if !second.Continued || second.Branch != first.Branch || len(second.ReplayConflicts) != 0 {
+ t.Fatalf("unexpected continuation: %s, continued=%v, conflicts=%v", second.Branch, second.Continued, second.ReplayConflicts)
+ }
+ if _, err := os.Stat(filepath.Join(second.WorkDir, "upstream.txt")); !os.IsNotExist(err) {
+ t.Fatalf("committed HEAD advance was replayed: %v", err)
+ }
+ if kind == "untracked" {
+ if got := readFile(t, filepath.Join(second.WorkDir, "draft.txt")); got != "draft improved by the agent\n" {
+ t.Fatalf("agent's draft was overwritten: %q", got)
+ }
+ } else if kind == "tracked" {
+ if got := readFile(t, filepath.Join(second.WorkDir, "tracked.txt")); got != "WIP improved by the agent\n" {
+ t.Fatalf("agent's tracked edit was overwritten: %q", got)
+ }
+ } else if _, err := os.Stat(filepath.Join(second.WorkDir, "tracked.txt")); !os.IsNotExist(err) {
+ t.Fatalf("user's deletion was lost: %v", err)
+ }
+ if newEdits {
+ for name, want := range map[string]string{"keep.txt": "new tracked user edit\n", "scratch.txt": "new untracked user edit\n"} {
+ if got := readFile(t, filepath.Join(second.WorkDir, name)); got != want {
+ t.Fatalf("new user edit missing in %s: %q", name, got)
+ }
+ }
+ if _, err := os.Stat(filepath.Join(second.WorkDir, "notes.txt")); !os.IsNotExist(err) {
+ t.Fatalf("new untracked deletion was lost: %v", err)
+ }
+ } else if second.BaseCommit != firstTip {
+ t.Fatalf("unchanged WIP authored a replay commit: %s != %s", second.BaseCommit, firstTip)
+ }
+ if got := gitRun(t, repo, "status", "--porcelain"); got != sourceStatus {
+ t.Fatalf("source status changed: %q != %q", got, sourceStatus)
+ }
+ if got := gitRun(t, repo, "ls-files", "--stage"); got != sourceIndex {
+ t.Fatal("source index changed during prepare")
+ }
+ finalizeOK(t, second)
+ secondTip := gitRun(t, repo, "rev-parse", second.Branch)
+ third := prepareTurn(t, repo, "MUL-7488", turnThreeTask)
+ if third.BaseCommit != secondTip || len(third.ReplayConflicts) != 0 {
+ t.Fatalf("unchanged third turn replayed state again: %s, conflicts=%v", third.BaseCommit, third.ReplayConflicts)
+ }
+ finalizeOK(t, third)
+ })
+ }
+ }
+}
+
+func TestPrepareLocalWorktreeNormalizesEditsAcrossChangesInTheSameFile(t *testing.T) {
+ repo := newTestRepo(t)
+ base := "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n"
+ writeFile(t, filepath.Join(repo, "tracked.txt"), base)
+ gitRun(t, repo, "add", "tracked.txt")
+ gitRun(t, repo, "commit", "-m", "multi-line base")
+ writeFile(t, filepath.Join(repo, "tracked.txt"), strings.Replace(base, "one", "user one", 1))
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "tracked.txt"), strings.Replace(base, "one", "agent one", 1))
+ finalizeOK(t, first)
+ firstTip := gitRun(t, repo, "rev-parse", first.Branch)
+
+ // Pulling a change to another line and restoring the same user WIP is not
+ // a new uncommitted edit; neither line should be replayed into the task.
+ upstream := strings.Replace(base, "eight", "upstream eight", 1)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), upstream)
+ gitRun(t, repo, "add", "tracked.txt")
+ gitRun(t, repo, "commit", "-m", "upstream edit to another line")
+ writeFile(t, filepath.Join(repo, "tracked.txt"), strings.Replace(upstream, "one", "user one", 1))
+ second := prepareTurn(t, repo, "MUL-7488", turnTwoTask)
+ if second.BaseCommit != firstTip || len(second.ReplayConflicts) != 0 {
+ t.Fatalf("unchanged WIP caused replay: %s, conflicts=%v", second.BaseCommit, second.ReplayConflicts)
+ }
+ if got := readFile(t, filepath.Join(second.WorkDir, "tracked.txt")); got != strings.Replace(base, "one", "agent one", 1) {
+ t.Fatalf("committed source edit entered the task or agent edit was lost: %q", got)
+ }
+ finalizeOK(t, second)
+}
+
+func TestPrepareLocalWorktreeExcludesHEADAdvanceAfterUncommittedConflictResolution(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user A\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "tracked.txt"), "agent B\n")
+ finalizeOK(t, first)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user C\n")
+ for _, taskID := range []string{turnTwoTask, turnThreeTask} {
+ pending := prepareTurn(t, repo, "MUL-7488", taskID)
+ if len(pending.ReplayConflicts) != 1 {
+ t.Fatalf("expected a genuine user conflict, got %v", pending.ReplayConflicts)
+ }
+ gitRun(t, pending.Path, "reset", "--hard", pending.BaseCommit)
+ finalizeOK(t, pending)
+ }
+ record := gitRun(t, repo, "rev-parse", userStateRef(first.Branch))
+ if parents := strings.Fields(gitRun(t, repo, "rev-list", "--parents", "-n", "1", record+"^1")); len(parents) != 3 {
+ t.Fatalf("expected a nested two-parent record, got %v", parents)
+ }
+ writeFile(t, filepath.Join(repo, "upstream.txt"), "committed upstream work\n")
+ gitRun(t, repo, "add", "upstream.txt")
+ gitRun(t, repo, "commit", "-m", "advance local HEAD")
+ resumed := prepareTurn(t, repo, "MUL-7488", "11112222-3333-4444-5555-dddddddddddd")
+ if len(resumed.ReplayConflicts) != 1 || resumed.ReplayConflicts[0] != "tracked.txt" {
+ t.Fatalf("pending user conflict was lost: %v", resumed.ReplayConflicts)
+ }
+ if _, err := os.Stat(filepath.Join(resumed.WorkDir, "upstream.txt")); !os.IsNotExist(err) {
+ t.Fatalf("HEAD advance entered the task through a nested record: %v", err)
+ }
+ writeFile(t, filepath.Join(resumed.WorkDir, "tracked.txt"), "agent B and user C\n")
+ gitRun(t, resumed.Path, "add", "tracked.txt")
+ finalizeOK(t, resumed)
+ resolvedTip := gitRun(t, repo, "rev-parse", resumed.Branch)
+ next := prepareTurn(t, repo, "MUL-7488", "11112222-3333-4444-5555-eeeeeeeeeeee")
+ if next.BaseCommit != resolvedTip || len(next.ReplayConflicts) != 0 {
+ t.Fatalf("resolved user edit was replayed: %s, conflicts=%v", next.BaseCommit, next.ReplayConflicts)
+ }
+ finalizeOK(t, next)
+}
+
+func TestPrepareLocalWorktreeContinuesAfterUserCommitsConflictingDraft(t *testing.T) {
+ for _, kind := range []string{"untracked", "tracked"} {
+ for _, newEdits := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/new_edits_%t", kind, newEdits), func(t *testing.T) {
+ repo := newTestRepo(t)
+ name := "draft.txt"
+ if kind == "tracked" {
+ name = "tracked.txt"
+ }
+ writeFile(t, filepath.Join(repo, name), "previous user draft\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, name), "draft improved by the agent\n")
+ writeFile(t, filepath.Join(first.WorkDir, "task.txt"), "agent work\n")
+ finalizeOK(t, first)
+ record := gitRun(t, repo, "rev-parse", userStateRef(first.Branch))
+ tip := gitRun(t, repo, "rev-parse", first.Branch)
+
+ // The finished, committed draft conflicts with the old snapshot.
+ // Its committed changes must not enter the task or block resumes.
+ writeFile(t, filepath.Join(repo, name), "finished draft committed by the user\n")
+ gitRun(t, repo, "add", name)
+ gitRun(t, repo, "commit", "-m", "finish and commit the draft")
+ if newEdits {
+ writeFile(t, filepath.Join(repo, "scratch.txt"), "current uncommitted user edit\n")
+ }
+ sourceStatus := gitRun(t, repo, "status", "--porcelain")
+ sourceIndex := gitRun(t, repo, "ls-files", "--stage")
+ for _, taskID := range []string{turnTwoTask, turnThreeTask} {
+ resumed, err := prepareTurnAs(t, repo, "MUL-7488", taskID, testBranchOwner)
+ if err != nil {
+ t.Errorf("resume %s failed after the draft was committed: %v", taskID, err)
+ continue
+ }
+ if !resumed.Continued || resumed.Branch != first.Branch || len(resumed.ReplayConflicts) != 0 {
+ t.Fatalf("unexpected continuation: %s, continued=%v, conflicts=%v", resumed.Branch, resumed.Continued, resumed.ReplayConflicts)
+ }
+ if (!newEdits || taskID == turnThreeTask) && resumed.BaseCommit != tip {
+ t.Fatalf("unchanged user WIP authored a commit on resume %s", taskID)
+ }
+ if got := readFile(t, filepath.Join(resumed.WorkDir, name)); got != "draft improved by the agent\n" {
+ t.Fatalf("committed draft overwrote the agent's work: %q", got)
+ }
+ if got := readFile(t, filepath.Join(resumed.WorkDir, "task.txt")); got != "agent work\n" {
+ t.Fatalf("earlier agent work was lost: %q", got)
+ }
+ if newEdits {
+ if got := readFile(t, filepath.Join(resumed.WorkDir, "scratch.txt")); got != "current uncommitted user edit\n" {
+ t.Fatalf("current user edit was lost: %q", got)
+ }
+ }
+ finalizeOK(t, resumed)
+ tip = gitRun(t, repo, "rev-parse", first.Branch)
+ if got := gitRun(t, repo, "rev-parse", userStateRef(first.Branch)); got == record {
+ t.Fatal("successful resume did not advance the captured user state")
+ }
+ if got := gitRun(t, repo, "status", "--porcelain"); got != sourceStatus {
+ t.Fatalf("resume changed the user's checkout status: %q", got)
+ }
+ if got := gitRun(t, repo, "ls-files", "--stage"); got != sourceIndex {
+ t.Fatal("resume changed the user's index")
+ }
+ if got := readFile(t, filepath.Join(repo, name)); got != "finished draft committed by the user\n" {
+ t.Fatalf("resume changed the user's committed draft: %q", got)
+ }
+ }
+ })
+ }
+ }
+}
+
+func TestPrepareLocalWorktreeHandsCurrentEditsToAgentAfterHEADNormalizationConflict(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "previous user draft\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "tracked.txt"), "draft improved by the agent\n")
+ finalizeOK(t, first)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "finished draft committed by the user\n")
+ gitRun(t, repo, "add", "tracked.txt")
+ gitRun(t, repo, "commit", "-m", "finish and commit the draft")
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "current uncommitted user edit\n")
+
+ second := prepareTurn(t, repo, "MUL-7488", turnTwoTask)
+ if len(second.ReplayConflicts) != 1 || second.ReplayConflicts[0] != "tracked.txt" {
+ t.Fatalf("current user edit was not offered as a conflict: %v", second.ReplayConflicts)
+ }
+ conflict := readFile(t, filepath.Join(second.WorkDir, "tracked.txt"))
+ for _, want := range []string{"draft improved by the agent", "current uncommitted user edit", "<<<<<<<"} {
+ if !strings.Contains(conflict, want) {
+ t.Fatalf("conflicted file is missing %q: %s", want, conflict)
+ }
+ }
+ writeFile(t, filepath.Join(second.WorkDir, "tracked.txt"), "agent draft and current user edit\n")
+ gitRun(t, second.Path, "add", "tracked.txt")
+ finalizeOK(t, second)
+ resolvedTip := gitRun(t, repo, "rev-parse", second.Branch)
+ third := prepareTurn(t, repo, "MUL-7488", turnThreeTask)
+ if third.BaseCommit != resolvedTip || len(third.ReplayConflicts) != 0 {
+ t.Fatalf("resolved edit was replayed again: %s, conflicts=%v", third.BaseCommit, third.ReplayConflicts)
+ }
+ if got := readFile(t, filepath.Join(third.WorkDir, "tracked.txt")); got != "agent draft and current user edit\n" {
+ t.Fatalf("resolved draft was lost: %q", got)
+ }
+ finalizeOK(t, third)
+}
+
+func TestPrepareLocalWorktreePreservesOtherDraftsWhenNormalizationConflicts(t *testing.T) {
+ for _, committedChange := range []string{"finish", "delete", "directory"} {
+ for _, newEdit := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/new_edit_%t", committedChange, newEdit), func(t *testing.T) {
+ repo := newTestRepo(t)
+ // A tracked draft allows both content and modify/delete conflicts.
+ writeFile(t, filepath.Join(repo, "notes.txt"), "original notes\n")
+ gitRun(t, repo, "add", "notes.txt")
+ gitRun(t, repo, "commit", "-m", "initial notes")
+ writeFile(t, filepath.Join(repo, "notes.txt"), "old user notes\n")
+ writeFile(t, filepath.Join(repo, "scratch.txt"), "old user scratch\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, "scratch.txt"), "scratch improved by the agent\n")
+ finalizeOK(t, first)
+ tip := gitRun(t, repo, "rev-parse", first.Branch)
+
+ switch committedChange {
+ case "finish":
+ writeFile(t, filepath.Join(repo, "notes.txt"), "finished committed notes\n")
+ case "delete", "directory":
+ if err := os.Remove(filepath.Join(repo, "notes.txt")); err != nil {
+ t.Fatal(err)
+ }
+ if committedChange == "directory" {
+ writeFile(t, filepath.Join(repo, "notes.txt", "finished.txt"), "finished committed notes\n")
+ }
+ }
+ gitRun(t, repo, "add", "-A", "--", "notes.txt")
+ gitRun(t, repo, "commit", "-m", "commit the notes change")
+ if newEdit {
+ writeFile(t, filepath.Join(repo, "keep.txt"), "new tracked user edit\n")
+ }
+ sourceHead := gitRun(t, repo, "rev-parse", "HEAD")
+ sourceStatus := gitRun(t, repo, "status", "--porcelain")
+ sourceIndex := gitRun(t, repo, "ls-files", "--stage")
+ for _, taskID := range []string{turnTwoTask, turnThreeTask} {
+ resumed := prepareTurn(t, repo, "MUL-7488", taskID)
+ if len(resumed.ReplayConflicts) != 0 {
+ t.Fatalf("an unchanged draft was replayed as a conflict: %v", resumed.ReplayConflicts)
+ }
+ if (!newEdit || taskID == turnThreeTask) && resumed.BaseCommit != tip {
+ t.Fatal("unchanged drafts caused an extra replay commit")
+ }
+ if got := readFile(t, filepath.Join(resumed.WorkDir, "scratch.txt")); got != "scratch improved by the agent\n" {
+ t.Fatalf("unchanged user scratch overwrote the agent's work: %q", got)
+ }
+ if got := readFile(t, filepath.Join(resumed.WorkDir, "notes.txt")); got != "old user notes\n" {
+ t.Fatalf("committed notes change entered the task branch: %q", got)
+ }
+ if newEdit {
+ if got := readFile(t, filepath.Join(resumed.WorkDir, "keep.txt")); got != "new tracked user edit\n" {
+ t.Fatalf("new user edit was lost: %q", got)
+ }
+ }
+ finalizeOK(t, resumed)
+ tip = gitRun(t, repo, "rev-parse", first.Branch)
+ if got := gitRun(t, repo, "rev-parse", "HEAD"); got != sourceHead {
+ t.Fatal("normalization moved the user's HEAD")
+ }
+ if got := gitRun(t, repo, "status", "--porcelain"); got != sourceStatus {
+ t.Fatalf("normalization changed source status: %q", got)
+ }
+ if got := gitRun(t, repo, "ls-files", "--stage"); got != sourceIndex {
+ t.Fatal("normalization changed the user's index")
+ }
+ }
+ })
+ }
+ }
+}
+
+func TestPrepareLocalWorktreeNormalizesConflictPathsLiterally(t *testing.T) {
+ repo := newTestRepo(t)
+ // Brackets are valid filenames on every platform but are also Git glob
+ // syntax. Restoring the first path must not reset the second draft's WIP.
+ conflicting := "notes [1].txt"
+ unchanged := "notes 1.txt"
+ writeFile(t, filepath.Join(repo, conflicting), "old user notes\n")
+ writeFile(t, filepath.Join(repo, unchanged), "old user scratch\n")
+ first := prepareTurn(t, repo, "MUL-7488", turnOneTask)
+ writeFile(t, filepath.Join(first.WorkDir, unchanged), "scratch improved by the agent\n")
+ finalizeOK(t, first)
+ tip := gitRun(t, repo, "rev-parse", first.Branch)
+ writeFile(t, filepath.Join(repo, conflicting), "finished committed notes\n")
+ gitRun(t, repo, "add", "--", ":(literal)"+conflicting)
+ gitRun(t, repo, "commit", "-m", "finish notes with a literal name")
+
+ second := prepareTurn(t, repo, "MUL-7488", turnTwoTask)
+ if len(second.ReplayConflicts) != 0 || second.BaseCommit != tip {
+ t.Fatalf("unrelated matching filename was replayed: %v, base=%s", second.ReplayConflicts, second.BaseCommit)
+ }
+ if got := readFile(t, filepath.Join(second.WorkDir, unchanged)); got != "scratch improved by the agent\n" {
+ t.Fatalf("unrelated matching draft was overwritten: %q", got)
+ }
+ if got := readFile(t, filepath.Join(second.WorkDir, conflicting)); got != "old user notes\n" {
+ t.Fatalf("committed notes were replayed: %q", got)
+ }
+ finalizeOK(t, second)
+}
+
// The user's uncommitted work reaches the branch once, as turn one's baseline,
// and every later turn replays only what they changed since. Replaying their
// whole tree again would ask git to merge their copy of a file against the