Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8463: fix(daemon): keep a worktree turn's leftovers off its branch once the agent commits (#9870)
Bohan Jiangbcdf970c76c2
diff --git a/apps/docs/content/docs/project-resources.fr.mdx b/apps/docs/content/docs/project-resources.fr.mdxindex cfe1b9ed64..9ec0d7cbdd 100644--- a/apps/docs/content/docs/project-resources.fr.mdx+++ b/apps/docs/content/docs/project-resources.fr.mdx@@ -121,7 +121,7 @@ Une branche par tâche plutôt qu'une par exécution : `agent/<agent>/<issue>` (`<agent>` vient du nom de l'agent : mis en minuscules, tout ce qui n'est pas a–z ou 0–9 (lettres accentuées comprises) devient `-`, sur 30 caractères au plus. Un nom sans lettre latine ni chiffre devient `agent`. Ainsi, Assistant ops qui traite OPS-21 obtient `agent/assistant-ops/ops-21`, et un agent nommé 运营助手 obtient `agent/agent/ops-21`. `<issue>` est l'identifiant de la tâche en minuscules.-Une exécution qui a échoué en cours de route indique tout de même sa branche, car elle y a déjà commité ce que l'agent avait produit.+Une exécution qui a échoué en cours de route indique tout de même sa branche : les commits de l'agent s'y trouvent, et ce qu'il a laissé non commité est conservé comme décrit dans [Rien n'est perdu en silence](#nothing-is-silently-lost).</Accordion><Accordion title="Une suite reprend là où la dernière exécution s'est arrêtée" id="follow-ups-continue-the-branch">@@ -156,9 +156,16 @@ Une exécution qui n'a pas pu enregistrer sa branche, par exemple parce qu'elle</Accordion><Accordion title="Rien n'est perdu en silence" id="nothing-is-silently-lost">-Tout ce que l'agent laisse non commité est commité sur cette branche avant la suppression du worktree, y compris lorsque l'exécution échoue en cours de route.+Rien de ce que l'agent laisse non commité n'est supprimé avec le worktree, y compris lorsque l'exécution échoue en cours de route. Sa destination dépend de ce que l'agent a fait pendant l'exécution :-Dans le rare cas où ce commit lui-même est impossible, par exemple un dépôt avec `commit.gpgSign` et aucune clé de signature disponible pour le runtime, le worktree est délibérément conservé, l'exécution est signalée comme échouée, et `git worktree list` dans votre dépôt indique le répertoire qui contient le travail.+- **L'agent n'a fait aucun commit :** tout ce qu'il a laissé et qui n'est pas ignoré par git est commité sur la branche. Les hooks de commit de votre dépôt ne s'exécutent pas pour ce commit.+- **L'agent a fait ses propres commits :** seuls ces commits sont livrés. Ce qu'il a laissé non commité (fichiers générés, fichiers temporaires, modifications non commitées) est enregistré sous une ref cachée, `refs/multica/leftovers/<branch>/<task>`, et n'atteint pas la branche. Cette règle est indiquée à l'agent au début de chaque exécution : un agent qui commite décide donc de ce qui est livré.++Exception : une exécution qui commence par terminer une fusion avec vos modifications locales (voir [les conflits](#conflicts-are-resolved-by-the-agent)) commite tout ce qu'elle laisse, car ces modifications non commitées contiennent les vôtres.++Pour voir ce qu'une exécution a enregistré, listez les refs avec `git for-each-ref refs/multica/leftovers` et inspectez-en une avec `git show --stat <ref>`. `git restore --source=<ref> -- <path>` remet un fichier dans votre copie de travail.++Dans le rare cas où ce commit ou cet enregistrement lui-même est impossible, par exemple un dépôt avec `commit.gpgSign` et aucune clé de signature disponible pour le runtime, le worktree est délibérément conservé, l'exécution est signalée comme échouée, et `git worktree list` dans votre dépôt indique le répertoire qui contient le travail.</Accordion><Accordion title="Une exécution qui ne change rien ne laisse aucune trace" id="no-changes-leave-nothing">@@ -168,7 +175,7 @@ Sa branche est supprimée plutôt que laissée comme entrée vide dans `git bran</Accordion><Accordion title="Les branches et refs cachées qui restent dans votre dépôt" id="what-stays-in-your-repo">-Le worktree se trouve dans le répertoire de travail du runtime et il est récupéré selon [le calendrier de nettoyage habituel](/daemon-runtimes#cleanup). Deux éléments persistent dans votre dépôt : la branche, et une ref cachée par branche sous `refs/multica/local-state/`, qui enregistre à qui elle appartient et l'état de votre répertoire lors de sa dernière reprise.+Le worktree se trouve dans le répertoire de travail du runtime et il est récupéré selon [le calendrier de nettoyage habituel](/daemon-runtimes#cleanup). Ce qui persiste dans votre dépôt : la branche ; une ref cachée par branche sous `refs/multica/local-state/`, qui enregistre à qui elle appartient et l'état de votre répertoire lors de sa dernière reprise ; et une ref cachée sous `refs/multica/leftovers/` pour chaque exécution qui a laissé des modifications non commitées après avoir fait ses propres commits.Les refs cachées n'apparaissent jamais dans `git branch` ; listez-les avec `git for-each-ref refs/multica`. Multica supprime chacune d'elles avec sa branche, et élimine celles dont vous avez vous-même supprimé la branche la prochaine fois qu'une exécution démarre sur ce dépôt. Vous pouvez aussi toutes les supprimer d'un coup avec `git for-each-ref --format='%(refname)' refs/multica | xargs -n1 git update-ref -d`.diff --git a/apps/docs/content/docs/project-resources.ja.mdx b/apps/docs/content/docs/project-resources.ja.mdxindex 36a38674c5..5bd76aa111 100644--- a/apps/docs/content/docs/project-resources.ja.mdx+++ b/apps/docs/content/docs/project-resources.ja.mdx@@ -123,7 +123,7 @@ git 管理外の通常のディレクトリはこのモードしか使えませ`<agent>` はエージェント名から作られます。小文字にしたうえで英字と数字だけを残し、それ以外の文字は `-` に置き換え、最大 30 文字です。英字も数字も含まない名前は `agent` になります。そのため「運用アシスタント」が OPS-21 を処理すると、ブランチは `agent/agent/ops-21` です。`<issue>` は小文字にしたタスク番号です。-途中で失敗した実行もブランチを報告します。エージェントが作った分はすでにコミットされているからです。+途中で失敗した実行もブランチを報告します。エージェントのコミットはそこにあり、コミットされなかった分は[黙って失われるものはない](#nothing-is-silently-lost)のとおりに保持されます。</Accordion><Accordion title="続きのコメントは前回の続きから始まる" id="follow-ups-continue-the-branch">@@ -158,9 +158,16 @@ git 管理外の通常のディレクトリはこのモードしか使えませ</Accordion><Accordion title="黙って失われるものはない" id="nothing-is-silently-lost">-エージェントが未コミットのまま残した変更は、ワークツリーが削除される前にそのブランチへコミットされます。実行が途中で失敗した場合も同様です。+エージェントが未コミットのまま残した変更は、ワークツリーと一緒に削除されることはありません。実行が途中で失敗した場合も同様です。行き先は、エージェントがその実行中に自分でコミットしたかどうかで決まります。-ごくまれに、そのコミット自体ができないことがあります。たとえば `commit.gpgSign` が有効で、ランタイムが署名鍵を利用できないリポジトリです。その場合ワークツリーは削除されずに意図的に保持され、実行は失敗として報告されます。あなたのリポジトリで `git worktree list` を実行すると、その変更を保持しているディレクトリが表示されます。+- **エージェントがコミットしなかった場合:** gitignore されていないファイルはすべてブランチにコミットされます。このコミットではリポジトリのコミットフックは実行されません。+- **エージェントが自分でコミットした場合:** 納品されるのはそのコミットだけです。コミットされなかった分(生成物、一時ファイル、コミットしなかった編集)は隠し ref `refs/multica/leftovers/<branch>/<task>` に保存され、ブランチには入りません。このルールは毎回の実行開始時にエージェントへ伝えられるので、自分でコミットするエージェントが何を納品するかを決めます。++例外として、最初にあなたのローカル変更とのマージを完了させる実行([衝突の解決](#conflicts-are-resolved-by-the-agent)を参照)は、残したものをすべてコミットします。その未コミットの変更にはあなたの編集が含まれるからです。++ある実行が何を保存したかは、`git for-each-ref refs/multica/leftovers` で ref を一覧し、`git show --stat <ref>` で確認できます。`git restore --source=<ref> -- <path>` でファイルを作業ディレクトリに戻せます。++ごくまれに、そのコミットや保存自体ができないことがあります。たとえば `commit.gpgSign` が有効で、ランタイムが署名鍵を利用できないリポジトリです。その場合ワークツリーは削除されずに意図的に保持され、実行は失敗として報告されます。あなたのリポジトリで `git worktree list` を実行すると、その変更を保持しているディレクトリが表示されます。</Accordion><Accordion title="何も変更しなかった実行は、何も残さない" id="no-changes-leave-nothing">@@ -170,7 +177,7 @@ git 管理外の通常のディレクトリはこのモードしか使えませ</Accordion><Accordion title="リポジトリに残るブランチと隠し ref" id="what-stays-in-your-repo">-ワークツリーはランタイムのワークスペースディレクトリ内にあるため、[通常のクリーンアップ周期](/daemon-runtimes#cleanup)で回収されます。あなたのリポジトリに残るのは 2 つ、ブランチと、ブランチごとの隠し ref(`refs/multica/local-state/` 配下)です。後者はそのブランチの所有者と、最後に引き継いだ時点のあなたのディレクトリの内容を記録します。+ワークツリーはランタイムのワークスペースディレクトリ内にあるため、[通常のクリーンアップ周期](/daemon-runtimes#cleanup)で回収されます。あなたのリポジトリに残るのは、ブランチと、ブランチごとの隠し ref(`refs/multica/local-state/` 配下)、そしてエージェントが自分でコミットしたあとに未コミットの変更を残した実行ごとの隠し ref(`refs/multica/leftovers/` 配下)です。`refs/multica/local-state/` の ref はそのブランチの所有者と、最後に引き継いだ時点のあなたのディレクトリの内容を記録します。隠し ref は `git branch` には現れず、`git for-each-ref refs/multica` で一覧できます。Multica はブランチと一緒に削除し、あなたが自分で消したブランチの ref は、そのリポジトリで次の実行が始まるときに片付けます。`git for-each-ref --format='%(refname)' refs/multica | xargs -n1 git update-ref -d` で一括削除もできます。diff --git a/apps/docs/content/docs/project-resources.ko.mdx b/apps/docs/content/docs/project-resources.ko.mdxindex bb5aeba5da..38d49acc55 100644--- a/apps/docs/content/docs/project-resources.ko.mdx+++ b/apps/docs/content/docs/project-resources.ko.mdx@@ -121,7 +121,7 @@ git으로 관리되지 않는 일반 디렉터리는 이 모드만 사용할 수`<agent>`는 에이전트 이름에서 만들어집니다. 소문자로 바꾼 뒤 영문자와 숫자만 남기고 나머지 문자는 `-`로 바꾸며, 최대 30자입니다. 영문자나 숫자가 없는 이름은 `agent`가 됩니다. 그래서 "운영 도우미"가 OPS-21을 처리하면 브랜치는 `agent/agent/ops-21`입니다. `<issue>`는 소문자로 바꾼 태스크 번호입니다.-도중에 실패한 실행도 브랜치를 보고합니다. 에이전트가 만든 부분은 이미 커밋되어 있기 때문입니다.+도중에 실패한 실행도 브랜치를 보고합니다. 에이전트의 커밋은 브랜치에 있고, 커밋하지 않은 부분은 [조용히 사라지는 것은 없습니다](#nothing-is-silently-lost)에 설명한 대로 보존됩니다.</Accordion><Accordion title="후속 실행은 지난 실행이 멈춘 지점에서 이어집니다" id="follow-ups-continue-the-branch">@@ -156,9 +156,16 @@ git으로 관리되지 않는 일반 디렉터리는 이 모드만 사용할 수</Accordion><Accordion title="조용히 사라지는 것은 없습니다" id="nothing-is-silently-lost">-에이전트가 커밋하지 않고 남긴 변경 사항은 워크트리가 제거되기 전에 해당 브랜치로 커밋되며, 실행이 도중에 실패한 경우에도 마찬가지입니다.+에이전트가 커밋하지 않고 남긴 변경 사항은 워크트리와 함께 삭제되지 않으며, 실행이 도중에 실패한 경우에도 마찬가지입니다. 어디로 가는지는 에이전트가 그 실행 중에 직접 커밋했는지에 따라 달라집니다.-드물게 그 커밋 자체를 할 수 없는 경우도 있습니다. 예를 들어 `commit.gpgSign`이 켜져 있는데 런타임이 서명 키를 사용할 수 없는 저장소입니다. 이때 워크트리는 의도적으로 유지되고 실행은 실패로 보고되며, 저장소에서 `git worktree list`를 실행하면 해당 변경 사항이 있는 디렉터리를 확인할 수 있습니다.+- **에이전트가 커밋하지 않은 경우:** gitignore되지 않은 파일은 모두 브랜치에 커밋됩니다. 이 커밋에서는 저장소의 커밋 훅이 실행되지 않습니다.+- **에이전트가 직접 커밋한 경우:** 그 커밋만 전달됩니다. 커밋하지 않은 부분(생성된 결과물, 임시 파일, 커밋하지 않은 수정)은 숨은 ref `refs/multica/leftovers/<branch>/<task>`에 저장되고 브랜치에는 들어가지 않습니다. 이 규칙은 매 실행이 시작될 때 에이전트에게 알려지므로, 직접 커밋하는 에이전트가 무엇을 전달할지 결정합니다.++예외로, 먼저 사용자의 로컬 변경과 병합을 마쳐야 하는 실행([충돌 해결](#conflicts-are-resolved-by-the-agent) 참고)은 남긴 것을 모두 커밋합니다. 그 커밋되지 않은 변경에 사용자의 수정이 포함되어 있기 때문입니다.++어떤 실행이 무엇을 저장했는지는 `git for-each-ref refs/multica/leftovers`로 ref를 나열하고 `git show --stat <ref>`로 확인할 수 있습니다. `git restore --source=<ref> -- <path>`로 파일을 작업 디렉터리에 되돌릴 수 있습니다.++드물게 그 커밋이나 저장 자체를 할 수 없는 경우도 있습니다. 예를 들어 `commit.gpgSign`이 켜져 있는데 런타임이 서명 키를 사용할 수 없는 저장소입니다. 이때 워크트리는 의도적으로 유지되고 실행은 실패로 보고되며, 저장소에서 `git worktree list`를 실행하면 해당 변경 사항이 있는 디렉터리를 확인할 수 있습니다.</Accordion><Accordion title="아무것도 변경하지 않은 실행은 아무것도 남기지 않습니다" id="no-changes-leave-nothing">@@ -168,7 +175,7 @@ git으로 관리되지 않는 일반 디렉터리는 이 모드만 사용할 수</Accordion><Accordion title="저장소에 남는 브랜치와 숨은 ref" id="what-stays-in-your-repo">-워크트리는 런타임의 작업 공간 디렉터리 안에 있으므로 [일반적인 정리 주기](/daemon-runtimes#cleanup)에 따라 회수됩니다. 저장소에는 두 가지가 남습니다. 브랜치, 그리고 브랜치마다 하나씩 있는 숨은 ref(`refs/multica/local-state/` 아래)입니다. 숨은 ref는 그 브랜치의 소유자와 마지막으로 이어받을 때 사용자 디렉터리의 내용을 기록합니다.+워크트리는 런타임의 작업 공간 디렉터리 안에 있으므로 [일반적인 정리 주기](/daemon-runtimes#cleanup)에 따라 회수됩니다. 저장소에 남는 것은 브랜치, 브랜치마다 하나씩 있는 숨은 ref(`refs/multica/local-state/` 아래), 그리고 에이전트가 직접 커밋한 뒤 커밋하지 않은 변경을 남긴 실행마다 하나씩 있는 숨은 ref(`refs/multica/leftovers/` 아래)입니다. `refs/multica/local-state/`의 ref는 그 브랜치의 소유자와 마지막으로 이어받을 때 사용자 디렉터리의 내용을 기록합니다.숨은 ref는 `git branch`에 나타나지 않으며 `git for-each-ref refs/multica`로 확인할 수 있습니다. Multica는 브랜치를 지울 때 함께 지우고, 사용자가 직접 지운 브랜치의 ref는 그 저장소에서 다음 실행이 시작될 때 정리합니다. `git for-each-ref --format='%(refname)' refs/multica | xargs -n1 git update-ref -d`로 한 번에 지울 수도 있습니다.diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdxindex 174102d824..26458ec331 100644--- a/apps/docs/content/docs/project-resources.mdx+++ b/apps/docs/content/docs/project-resources.mdx@@ -121,7 +121,7 @@ There is one branch per issue rather than one per run: `agent/<agent>/<issue>` (`<agent>` comes from the agent's name: lowercased, with everything other than a–z and 0–9 turned into `-`, up to 30 characters. A name with no Latin letters or digits becomes `agent`. So Ops helper working on OPS-21 gets `agent/ops-helper/ops-21`, while an agent named 运营助手 gets `agent/agent/ops-21`. `<issue>` is the issue identifier in lowercase.-A run that failed partway still reports its branch, because it still committed whatever the agent had produced.+A run that failed partway still reports its branch: the agent's commits are on it, and what it left uncommitted is kept as described in [Nothing is silently dropped](#nothing-is-silently-lost).</Accordion><Accordion title="A follow-up continues where the last run stopped" id="follow-ups-continue-the-branch">@@ -156,9 +156,16 @@ A run that could not record its branch — it failed before finishing, the recor</Accordion><Accordion title="Nothing is silently dropped" id="nothing-is-silently-lost">-Anything the agent leaves uncommitted is committed to that branch before the worktree is removed, including when the run fails partway.+Nothing the agent leaves uncommitted is deleted with the worktree, including when the run fails partway. Where it goes depends on whether the agent committed during the run:-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, the run is reported as failed, and `git worktree list` in your repo points at the directory holding the work.+- **The agent made no commit:** everything it left that is not gitignored is committed to the branch. Your repository's commit hooks do not run for this commit.+- **The agent made commits of its own:** only those commits are delivered. Whatever it left uncommitted (generated output, scratch files, edits it did not commit) is saved under a hidden ref, `refs/multica/leftovers/<branch>/<task>`, and does not reach the branch. The agent is told this rule at the start of every run, so an agent that commits decides what is delivered.++One exception: a run that starts by finishing a merge with your local edits (see [conflicts](#conflicts-are-resolved-by-the-agent)) commits everything it leaves, because those uncommitted changes include your edits.++To see what a run saved, list the refs with `git for-each-ref refs/multica/leftovers` and inspect one with `git show --stat <ref>`. `git restore --source=<ref> -- <path>` brings a file back into your checkout.++In the rare case that the commit or the save itself cannot be made — for example a repo with `commit.gpgSign` and no signing key available to the runtime — the worktree is deliberately kept, the run is reported as failed, and `git worktree list` in your repo points at the directory holding the work.</Accordion><Accordion title="A run that changes nothing leaves nothing behind" id="no-changes-leave-nothing">@@ -166,9 +173,9 @@ In the rare case that commit itself cannot be made — for example a repo with `Its branch is deleted rather than left as an empty entry in `git branch`, unless it is the issue's branch carrying earlier runs' work, which always survives.</Accordion>-<Accordion title="The branch and hidden ref left in your repo" id="what-stays-in-your-repo">+<Accordion title="The branch and hidden refs left in your repo" id="what-stays-in-your-repo">-The worktree lives in the runtime's workspace directory and is reclaimed on [the normal cleanup schedule](/daemon-runtimes#cleanup). Two things persist in your repo: the branch, and one hidden ref per branch under `refs/multica/local-state/` recording who owns it and what your directory looked like when it was last continued.+The worktree lives in the runtime's workspace directory and is reclaimed on [the normal cleanup schedule](/daemon-runtimes#cleanup). What persists in your repo is the branch; one hidden ref per branch under `refs/multica/local-state/`, recording who owns it and what your directory looked like when it was last continued; and one hidden ref under `refs/multica/leftovers/` for each run that left uncommitted changes after making commits of its own.The hidden refs never appear in `git branch`; list them with `git for-each-ref refs/multica`. Multica deletes each one with its branch, and drops any whose branch you deleted yourself the next time a run starts on that repo. You can also remove them at once with `git for-each-ref --format='%(refname)' refs/multica | xargs -n1 git update-ref -d`.diff --git a/apps/docs/content/docs/project-resources.zh.mdx b/apps/docs/content/docs/project-resources.zh.mdxindex e1e6a759e1..4bce8be294 100644--- a/apps/docs/content/docs/project-resources.zh.mdx+++ b/apps/docs/content/docs/project-resources.zh.mdx@@ -122,7 +122,7 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";`<agent>` 由智能体名字得来:转成小写后只保留英文字母和数字,其余字符换成 `-`,最长 30 个字符;名字里没有英文字母和数字时写作 `agent`。所以"运营助手"处理 OPS-21 时,分支是 `agent/agent/ops-21`。`<issue>` 是小写的任务编号。-中途失败的运行同样会报告它的分支,因为它已经把智能体做出来的部分提交进去了。+中途失败的运行同样会报告它的分支:智能体的提交都在上面,没提交的部分按[不会静默丢东西](#nothing-is-silently-lost)里的方式保留。</Accordion><Accordion title="后续对话接着上一轮继续" id="follow-ups-continue-the-branch">@@ -157,9 +157,16 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";</Accordion><Accordion title="不会静默丢东西" id="nothing-is-silently-lost">-智能体留下的未提交改动,会在 worktree 被移除前提交到那个分支上,运行中途失败时同样如此。+智能体留下的未提交改动不会随 worktree 一起删除,运行中途失败时同样如此。它们去哪里,取决于智能体这次运行有没有自己提交:-极少数情况下连这次提交都做不了,例如仓库开了 `commit.gpgSign` 而运行时拿不到签名密钥。这时 worktree 会被刻意保留,运行标记为失败,在你仓库里执行 `git worktree list` 就能看到存放这些改动的目录。+- **智能体没有提交过:** 所有没被 gitignore 的文件都会提交到分支上。这次提交不会运行仓库的提交钩子。+- **智能体自己提交过:** 只交付它的提交。没提交的部分(生成的产物、临时文件、没提交的修改)存到隐藏 ref `refs/multica/leftovers/<branch>/<task>` 下,不进分支。每次运行开始时都会把这条规则告诉智能体,所以自己提交的智能体决定交付哪些内容。++例外:一开始要先和你的本地改动完成 merge 的运行(见[冲突处理](#conflicts-are-resolved-by-the-agent))会提交它留下的全部内容,因为这些未提交的改动里有你的修改。++想看某次运行存下了什么,用 `git for-each-ref refs/multica/leftovers` 列出这些 ref,再用 `git show --stat <ref>` 查看。`git restore --source=<ref> -- <path>` 可以把某个文件取回到你的工作目录。++极少数情况下连这次提交或保存都做不了,例如仓库开了 `commit.gpgSign` 而运行时拿不到签名密钥。这时 worktree 会被刻意保留,运行标记为失败,在你仓库里执行 `git worktree list` 就能看到存放这些改动的目录。</Accordion><Accordion title="没有产生改动的运行不留下任何东西" id="no-changes-leave-nothing">@@ -169,7 +176,7 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";</Accordion><Accordion title="留在你仓库里的分支和隐藏 ref" id="what-stays-in-your-repo">-worktree 位于运行时的工作区目录内,会按[正常的清理周期](/daemon-runtimes#cleanup)回收。留在你仓库里的有两样东西:分支,以及每条分支对应的一个隐藏 ref(在 `refs/multica/local-state/` 下),记录这条分支归谁所有、以及上次续接时你目录里的内容。+worktree 位于运行时的工作区目录内,会按[正常的清理周期](/daemon-runtimes#cleanup)回收。留在你仓库里的有:分支;每条分支对应的一个隐藏 ref(在 `refs/multica/local-state/` 下),记录这条分支归谁所有、以及上次续接时你目录里的内容;以及智能体自己提交后又留下未提交改动的每次运行,各对应一个隐藏 ref(在 `refs/multica/leftovers/` 下)。隐藏 ref 不会出现在 `git branch` 里,可以用 `git for-each-ref refs/multica` 查看。Multica 删除分支时会一并删掉它;你自己删掉的分支所对应的 ref,会在下一次该仓库上有运行开始时被清理。也可以用 `git for-each-ref --format='%(refname)' refs/multica | xargs -n1 git update-ref -d` 一次性清掉。diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex be02339f23..8cda0157bd 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8685,6 +8685,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// the daemon cannot record either (#9404).if env.LocalWorktree != nil {promptOptions = append(promptOptions, WithWorktreeBranch(env.LocalWorktree.Branch, env.LocalWorktree.BaseCommit))+ // The branch block's rule for uncommitted files has one exception,+ // decided by the same predicate Finalize uses (#9788 review).+ if env.LocalWorktree.CommitsAllLeftovers() {+ promptOptions = append(promptOptions, WithWorktreeCommitsAllLeftovers())+ }}prompt := BuildPrompt(task, provider, promptOptions...)diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.goindex 5634f8459c..03ac609083 100644--- a/server/internal/daemon/execenv/local_worktree.go+++ b/server/internal/daemon/execenv/local_worktree.go@@ -32,11 +32,13 @@ import (// 2. The user's directory is never written to. Everything — including the// sidecar context files Prepare writes — lands inside the worktree, which// is disposable. What lasts in the user's repo is the branch, plus one-// hidden ref per branch recording who owns it and what it carries.-// 3. Nothing is silently discarded. Whatever the agent leaves uncommitted is-// committed to the branch before the worktree goes away, and an edit of the-// user's that could not be merged is offered again next turn rather than-// recorded as delivered.+// hidden ref per branch recording who owns it and what it carries, and one+// per turn that left uncommitted changes after committing its own work.+// 3. Nothing is silently discarded. Whatever the agent leaves uncommitted+// outlives the worktree — committed to the branch when the agent made no+// commit of its own, saved under a hidden ref when it did (#9788) — and an+// edit of the user's that could not be merged is offered again next turn+// rather than recorded as delivered.const (// localWorktreeDirName is the env-root-relative directory holding the@@ -71,6 +73,18 @@ const (// `git branch`, and a ref rather than a loose object so `git gc` in their// repo cannot reclaim a snapshot between two turns.localStateRefPrefix = "refs/multica/local-state/"++ // leftoverRefPrefix namespaces what a turn left uncommitted after making+ // commits of its own: refs/multica/leftovers/<branch>/<task>. Hidden for+ // the same reasons as the local-state record, and kept in its own namespace+ // because a branch's record is a single ref while a branch collects one of+ // these per turn.+ leftoverRefPrefix = "refs/multica/leftovers/"++ // maxLeftoverPathsInMessage caps the file list written into a leftover+ // commit's message. The commit itself always carries every file; the list+ // is only there so `git log` on the ref is readable.+ maxLeftoverPathsInMessage = 200)// LocalWorktreeParams describes the worktree Prepare should build for a@@ -202,6 +216,9 @@ type LocalWorktree struct {// worktree: the branch does not carry userState yet, and only a commit made// after the agent resolves can put it there.snapshotPending bool+ // taskID names the hidden ref this turn's leftovers are saved under, so the+ // user can tell which run they came from.+ taskID string// aborted, when set, makes Finalize refuse to commit or remove anything.// Set by the daemon when a pre-commit step failed in a way that would make// the committed branch wrong (see AbortWithReason).@@ -232,6 +249,7 @@ func (w *LocalWorktree) MarshalJSON() ([]byte, error) {Owner branchOwner `json:"owner"`TracksState bool `json:"tracks_state"`SnapshotPending bool `json:"snapshot_pending"`+ TaskID string `json:"task_id"`}{wire: (*wire)(w),CreatedBranch: w.createdBranch,@@ -240,6 +258,7 @@ func (w *LocalWorktree) MarshalJSON() ([]byte, error) {Owner: w.owner,TracksState: w.tracksState,SnapshotPending: w.snapshotPending,+ TaskID: w.taskID,})}@@ -253,6 +272,7 @@ func (w *LocalWorktree) UnmarshalJSON(data []byte) error {Owner branchOwner `json:"owner"`TracksState bool `json:"tracks_state"`SnapshotPending bool `json:"snapshot_pending"`+ TaskID string `json:"task_id"`}{wire: (*wire)(w)}if err := json.Unmarshal(data, &aux); err != nil {return err@@ -263,6 +283,7 @@ func (w *LocalWorktree) UnmarshalJSON(data []byte) error {w.owner = aux.Ownerw.tracksState = aux.TracksStatew.snapshotPending = aux.SnapshotPending+ w.taskID = aux.TaskIDreturn nil}@@ -275,6 +296,11 @@ type LocalWorktreeOutcome struct {// AutoCommitted is true when the agent left uncommitted changes that// Finalize committed so they would survive the worktree's removal.AutoCommitted bool+ // LeftoverRef names the hidden ref holding what the agent left uncommitted+ // after making commits of its own, which Finalize kept off the branch+ // (#9788). Empty when nothing was left over, or when the leftovers were+ // auto-committed because the agent made no commit.+ LeftoverRef string// PreservedPath is set only when Finalize could NOT commit the agent's// changes. The worktree at this path was intentionally left on disk because// it is the only remaining copy of that work.@@ -396,6 +422,7 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*LocuserState: userState,priorState: plan.priorState,owner: plan.owner,+ taskID: params.TaskID,// A branch a sibling task forked because the conversation's own branch// was busy is delivered once and never continued, so it records nothing.tracksState: plan.tracksState && actualBranch == plan.name,@@ -515,13 +542,24 @@ func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*Loc// have no way to get them back. Committing first turns "the agent edited files"// into "the branch has a commit", which is the delivery contract for this mode.//-// If that commit cannot be made — a repo with commit.gpgSign and no signing key-// available to the daemon, a full disk, a ref lock we lost — Finalize returns an-// error and DELIBERATELY LEAVES THE WORKTREE IN PLACE. Removing it would be the-// one operation in this file that destroys work with no way back, and a warning-// in the daemon log is not an acceptable substitute for the user's changes. The-// surviving worktree stays registered in the user's repo, so `git worktree list`-// points straight at it.+// That holds for an agent that never commits — its uncommitted files ARE its+// work. An agent that made commits of its own this turn has already chosen+// what to deliver, and what it left out is usually left out on purpose:+// generated output, scratch files, a one-off helper. Committing those onto the+// branch, past the repository's commit hooks, is how they used to reach the+// user's main line on the next merge (#9788). So after the agent's own commits+// the leftovers are saved under a hidden ref instead (saveLeftovers): still+// recoverable, never delivered. The prompt states this rule to the agent+// (buildWorktreeBranchBlock), so which side of it a turn lands on is the+// agent's decision, not a guess made here.+//+// If that commit — or that save — cannot be made — a repo with commit.gpgSign+// and no signing key available to the daemon, a full disk, a ref lock we lost —+// Finalize returns an error and DELIBERATELY LEAVES THE WORKTREE IN PLACE.+// Removing it would be the one operation in this file that destroys work with+// no way back, and a warning in the daemon log is not an acceptable substitute+// for the user's changes. The surviving worktree stays registered in the+// user's repo, so `git worktree list` points straight at it.func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, error) {if w == nil {return LocalWorktreeOutcome{}, nil@@ -595,7 +633,8 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, err}dirty = true}- if dirty {+ keepOff := dirty && w.leftoversStayOffBranch()+ if dirty && !keepOff {committed, err := w.commitAll(logger)if err != nil {outcome.PreservedPath = w.Path@@ -667,6 +706,25 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, err"recover the work from there, and let the run keep the commit the worktree started from instead of resetting past it",w.Branch, verifyErr, w.Path, w.GitRoot)}+ // Saved only once the delivery is known to be recordable: a refused one+ // keeps the whole worktree anyway, leftovers included, and a ref saved+ // for it would only be a second copy. Saved BEFORE the record, so a save+ // that fails leaves nothing recorded — the same position, and the same+ // recovery, as an auto-commit that fails.+ if keepOff {+ ref, saveErr := w.saveLeftovers(tip, logger)+ if saveErr != nil {+ outcome.PreservedPath = w.Path+ if logger != nil {+ logger.Error("execenv: could not save the changes the agent left uncommitted; keeping the worktree so they are recoverable",+ "path", w.Path, "branch", w.Branch, "git_root", w.GitRoot, "error", saveErr)+ }+ return outcome, fmt.Errorf(+ "could not save the changes the agent left uncommitted on branch %s: %w; the work is preserved in the worktree at %s (listed by `git worktree list` in %s) — recover it before that directory is reclaimed",+ w.Branch, saveErr, w.Path, w.GitRoot)+ }+ outcome.LeftoverRef = ref+ }if recErr := w.recordState(tip, logger); recErr != nil {outcome.PreservedPath = w.Pathif logger != nil {@@ -698,6 +756,7 @@ func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, err"git_root", w.GitRoot,"branch", outcome.Branch,"auto_committed", outcome.AutoCommitted,+ "leftover_ref", outcome.LeftoverRef,"produced_work", producedWork,"continued", w.Continued,)@@ -789,6 +848,160 @@ func (w *LocalWorktree) commitAll(logger *slog.Logger) (bool, error) {return commitEverything(w.Path, "chore(agent): uncommitted changes from task", false)}+// agentCommitted reports whether head carries commits the agent made this+// turn, which decides where its uncommitted changes go (see Finalize). "This+// turn" is measured from BaseCommit, which already includes the baseline the+// daemon committed in Prepare, so that commit never counts as the agent's.+//+// A head that is BaseCommit itself or one of its ancestors carries no commit+// of the agent's: that is a run that reset backwards, not one that committed,+// and it keeps the old rule. (On a branch that records its delivery,+// verifyDeliveryPoint then refuses it anyway; on one that does not, its+// uncommitted work is committed as before.)+//+// A turn that started on an unresolved merge never counts. Its BaseCommit is+// the branch tip the user's edits are being merged into, and those edits sit+// uncommitted in the worktree until something commits them. An agent that+// committed only part of the resolution would otherwise have the user's edits+// saved aside while the branch is recorded as carrying them; committing+// everything, as before, is the side that cannot lose them.+func (w *LocalWorktree) agentCommitted(head string) bool {+ if w.CommitsAllLeftovers() || w.BaseCommit == "" || head == "" || head == w.BaseCommit {+ return false+ }+ // --is-ancestor exits 1 for "no" and something else when git cannot+ // answer; either way the agent is not shown to have committed.+ _, err := runGit(w.Path, "merge-base", "--is-ancestor", head, w.BaseCommit)+ var exitErr *exec.ExitError+ return errors.As(err, &exitErr) && exitErr.ExitCode() == 1+}++// CommitsAllLeftovers reports that this turn is the exception to the #9788+// rule: Finalize will commit everything it leaves uncommitted onto the branch+// even after the agent's own commits, because the turn started on an+// unresolved merge of the user's edits (see agentCommitted). Exported so the+// prompt can tell the agent; a turn that is not told would leave generated+// output behind expecting it to stay off the branch.+func (w *LocalWorktree) CommitsAllLeftovers() bool {+ return w != nil && w.snapshotPending+}++// leftoversStayOffBranch reports whether Finalize should save what the agent+// left uncommitted under a hidden ref instead of committing it onto the branch.+// HEAD that cannot be resolved counts as "no commits": the auto-commit is the+// side that keeps the work.+func (w *LocalWorktree) leftoversStayOffBranch() bool {+ head, err := runGitTrimmed(w.Path, "rev-parse", "--verify", "HEAD")+ return err == nil && w.agentCommitted(head)+}++// saveLeftovers records everything the worktree holds beyond tip — every change+// `git add -A` would stage, tracked or untracked — as one commit whose parent is+// tip, under a hidden ref, and returns the ref. The worktree, its index and the+// branch are left as they are: the tree is built in a private index.+//+// With tip as the parent, `git show <ref>` is exactly the leftovers, and+// `git restore --source=<ref> -- <path>` brings one back. The ref is created,+// never moved: a task re-dispatched under the same id saves under a second name+// rather than overwriting what the first attempt left.+//+// Returns "" and no error when `git add -A` would stage nothing beyond tip.+func (w *LocalWorktree) saveLeftovers(tip string, logger *slog.Logger) (string, error) {+ tree, err := stagedWorktreeTree(w.Path)+ if err != nil {+ return "", err+ }+ tipTree, err := runGitTrimmed(w.Path, "rev-parse", "--verify", tip+"^{tree}")+ if err != nil {+ return "", fmt.Errorf("resolve the tree of %s: %w", shortID(tip), err)+ }+ if tree == tipTree {+ return "", nil+ }+ changed, err := runGitTrimmed(w.Path, "diff", "--name-status", "--no-renames", tipTree, tree)+ if err != nil {+ return "", fmt.Errorf("list the uncommitted changes: %w", err)+ }+ files := strings.Split(changed, "\n")+ args := append(commitIdentityArgs(w.Path), "commit-tree", tree, "-p", tip, "-m", leftoverCommitMessage(w.Branch, files))+ commit, err := runGitTrimmed(w.Path, args...)+ if err != nil {+ return "", fmt.Errorf("git commit-tree: %w", err)+ }+ if commit == "" {+ return "", errors.New("git commit-tree returned no commit")+ }+ short := commit[:min(12, len(commit))]+ key := taskKey(w.taskID)+ if key == "" {+ key = short+ }+ ref := leftoverRef(w.Branch, key)+ // The empty old value makes update-ref refuse a ref that already exists.+ if _, err := runGit(w.GitRoot, "update-ref", ref, commit, ""); err != nil {+ ref = leftoverRef(w.Branch, key+"-"+short)+ if out, err := runGit(w.GitRoot, "update-ref", ref, commit, ""); err != nil {+ return "", fmt.Errorf("git update-ref %s: %s: %w", ref, strings.TrimSpace(out), err)+ }+ }+ if logger != nil {+ logger.Info("execenv: the agent committed its own work; kept what it left uncommitted off the branch",+ "branch", w.Branch, "leftover_ref", ref, "files", len(files))+ }+ return ref, nil+}++// leftoverCommitMessage explains a leftover commit to whoever finds it with+// `git log`. The list is capped; the commit itself always carries every file.+func leftoverCommitMessage(branch string, files []string) string {+ var b strings.Builder+ b.WriteString("multica: changes the agent left uncommitted\n\n")+ fmt.Fprintf(&b, "The agent made commits of its own on %s in this run, so these changes\n", branch)+ b.WriteString("were kept off the branch instead of being committed onto it. This\n")+ b.WriteString("commit's parent is what the run delivered: `git show --stat <this commit>`\n")+ b.WriteString("lists the changes, and `git restore --source=<this commit> -- <path>`\n")+ b.WriteString("brings one back.\n\n")+ for i, file := range files {+ if i == maxLeftoverPathsInMessage {+ fmt.Fprintf(&b, "…and %d more\n", len(files)-i)+ break+ }+ b.WriteString(file + "\n")+ }+ return b.String()+}++// leftoverRef is where one turn's leftovers on branch are kept.+func leftoverRef(branch, key string) string {+ return leftoverRefPrefix + branch + "/" + key+}++// deleteLeftoverRefs drops every leftover ref saved for branch. Only refs one+// level below the branch's prefix are its own: a deeper one would belong to a+// branch named <branch>/<something>, which git cannot hold alongside this one,+// but a stale ref of that shape is still not this branch's to delete.+func deleteLeftoverRefs(gitRoot, branch string, logger *slog.Logger) {+ prefix := leftoverRefPrefix + branch + "/"+ out, err := runGitTrimmed(gitRoot, "for-each-ref", "--format=%(refname)", prefix)+ if err != nil {+ if logger != nil {+ logger.Debug("execenv: could not list the leftover refs of a task branch", "branch", branch, "error", err)+ }+ return+ }+ for _, ref := range strings.Split(out, "\n") {+ ref = strings.TrimSpace(ref)+ key, ok := strings.CutPrefix(ref, prefix)+ if !ok || key == "" || strings.Contains(key, "/") {+ continue+ }+ if out, delErr := runGit(gitRoot, "update-ref", "-d", ref); delErr != nil && logger != nil {+ logger.Warn("execenv: could not drop a leftover ref of a deleted task branch (non-fatal)",+ "ref", ref, "output", strings.TrimSpace(out), "error", delErr)+ }+ }+}+// commitEverything returns (false, nil) for the benign "there was nothing to// commit" case and (false, err) for a real failure — the distinction callers// need to decide whether the tree is safe to discard.@@ -1685,24 +1898,58 @@ type DeliveryProblem struct {// Reason is verifyDeliveryPoint's own explanation, as Finalize would// report it.Reason string+ // CommittedOnly is set when the agent made commits of its own this turn.+ // Finalize keeps what such a turn leaves uncommitted off the branch+ // (#9788), so the repair must not fold it in either: RepairSteps then puts+ // Tip's tree on the branch and leaves the uncommitted changes where they+ // are, for Finalize to save aside like any other turn's leftovers.+ CommittedOnly bool+ // LeftoverTree is the tree `git add -A` would stage in the worktree,+ // captured when CommittedOnly is set: exactly what Finalize would save+ // aside if this turn needed no repair. The repair has to load Tip's tree+ // into the index to commit it, which discards the agent's index; the last+ // step loads this tree in its place, so Finalize's own `git add -A` still+ // finds every leftover. Restoring the agent's index as such is not enough:+ // a tree cannot hold an intent-to-add entry (`git add -N`), and one for a+ // file the repository ignores would turn back into an ignored untracked+ // file that `git add -A` skips (#9870 review).+ LeftoverTree 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.+// RepairSteps is one git sequence that resolves any DeliveryProblem without+// touching the worktree's files: stage the tree to deliver, 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 — so it passes verifyDeliveryPoint by+// construction, and the guard itself is unchanged.+//+// The tree to deliver follows the rule Finalize applies to the same turn. An+// agent that made no commit delivers everything it left, so the sequence+// stages it all (`add -A`). One that did delivers its commits, so the sequence+// loads Tip's tree into the index (`read-tree`, which leaves the files alone),+// commits it, and then loads LeftoverTree, so everything the agent left+// uncommitted ends up staged — untouched on disk, still off the branch — for+// Finalize to save aside exactly as it would have without the repair.+// --allow-empty there covers a turn whose commits add up to nothing: the+// sequence must still end on the branch rather than fail halfway through.//// 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 {+ if p.CommittedOnly {+ return [][]string{+ {"read-tree", p.Tip},+ {"symbolic-ref", "HEAD", "refs/heads/" + p.Branch},+ {"reset", "--soft", p.BaseCommit},+ {"commit", "--allow-empty", "-m", RepairCommitMessage},+ {"read-tree", p.LeftoverTree},+ }+ }return [][]string{{"add", "-A"},{"symbolic-ref", "HEAD", "refs/heads/" + p.Branch},@@ -1711,15 +1958,17 @@ func (p *DeliveryProblem) RepairSteps() [][]string {}}-// 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.+// CheckDelivery reports, without changing the worktree, its index or any ref,+// 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+// does write tree objects: the ones its checks compare.)//-// 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.+// It predicts the same verifyDeliveryPoint call Finalize makes, including what+// Finalize does with uncommitted changes first. When the agent made no commit+// they are auto-committed onto whatever HEAD points at, so they only reach the+// task branch when HEAD is attached to it. When it did, they are never+// committed, and only where its commits are matters.//// 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@@ -1758,8 +2007,9 @@ func (w *LocalWorktree) CheckDelivery() *DeliveryProblem {return nil}}- if dirty && !headAttachedTo(w.Path, w.Branch) {- if w.repairWouldRevertBase(tip) {+ committedOnly := w.agentCommitted(tip)+ if dirty && !committedOnly && !headAttachedTo(w.Path, w.Branch) {+ if w.repairWouldRevertBase(tip, false) {return nil}return &DeliveryProblem{@@ -1771,10 +2021,20 @@ func (w *LocalWorktree) CheckDelivery() *DeliveryProblem {}}if verifyErr := w.verifyDeliveryPoint(tip); verifyErr != nil {- if w.repairWouldRevertBase(tip) {+ if w.repairWouldRevertBase(tip, committedOnly) {return nil}- return &DeliveryProblem{Branch: w.Branch, BaseCommit: w.BaseCommit, Tip: tip, Reason: verifyErr.Error()}+ problem := &DeliveryProblem{Branch: w.Branch, BaseCommit: w.BaseCommit, Tip: tip, Reason: verifyErr.Error(), CommittedOnly: committedOnly}+ if committedOnly {+ // Nothing to hand to Finalize means no repair that keeps the+ // leftovers: offer none, and Finalize keeps the whole worktree.+ leftoverTree, err := stagedWorktreeTree(w.Path)+ if err != nil {+ return nil+ }+ problem.LeftoverTree = leftoverTree+ }+ return problem}return nil}@@ -1804,15 +2064,15 @@ func (w *LocalWorktree) CheckDelivery() *DeliveryProblem {// 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+// The agent's side is read from the tree RepairSteps actually commits: Tip's+// own tree when committedOnly, otherwise the tree `git add -A` would stage.+// 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 {+func (w *LocalWorktree) repairWouldRevertBase(tip string, committedOnly bool) bool {mergeBase, err := runGitTrimmed(w.GitRoot, "merge-base", tip, w.BaseCommit)if err != nil || mergeBase == "" {return true // Unrelated histories: nothing to prove against.@@ -1824,13 +2084,17 @@ func (w *LocalWorktree) repairWouldRevertBase(tip string) bool {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+ // Judge the agent's side as the repair will commit it. For a turn without+ // commits 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. For a turn with commits it is Tip's tree.+ agentTree := tip+ if !committedOnly {+ agentTree, err = stagedWorktreeTree(w.Path)+ if err != nil {+ return true+ }}scratch := ""defer func() {@@ -2026,7 +2290,8 @@ func (w *LocalWorktree) recordState(checkpoint string, logger *slog.Logger) erro}// dropBranch deletes a task branch that carries nothing worth keeping, together-// with its recorded snapshot — the two are meaningless apart.+// with its recorded snapshot and any leftovers saved on it — they are+// meaningless apart.func dropBranch(gitRoot, branch string, logger *slog.Logger) {if branch == "" {return@@ -2036,6 +2301,7 @@ func dropBranch(gitRoot, branch string, logger *slog.Logger) {logger.Debug("execenv: no local-directory snapshot to drop for task branch","branch", branch, "output", strings.TrimSpace(out))}+ deleteLeftoverRefs(gitRoot, branch, logger)}// pruneOrphanedStateRefs drops the snapshot of any branch that is no longer@@ -2077,6 +2343,48 @@ func pruneOrphanedStateRefs(gitRoot string, logger *slog.Logger) {"git_root", gitRoot, "branch", branch)}}+ pruneOrphanedLeftoverRefs(gitRoot, logger)+}++// pruneOrphanedLeftoverRefs is pruneOrphanedStateRefs for the leftovers saved+// on a branch: once the user has deleted or merged the branch away, they go+// with it, for the same reason — each one pins a whole tree against `git gc`.+func pruneOrphanedLeftoverRefs(gitRoot string, logger *slog.Logger) {+ out, err := runGitTrimmed(gitRoot, "for-each-ref", "--format=%(refname)", leftoverRefPrefix)+ if err != nil {+ if logger != nil {+ logger.Debug("execenv: could not list leftover refs", "git_root", gitRoot, "error", err)+ }+ return+ }+ for _, ref := range strings.Split(out, "\n") {+ ref = strings.TrimSpace(ref)+ rest, ok := strings.CutPrefix(ref, leftoverRefPrefix)+ if !ok {+ continue+ }+ // refs/multica/leftovers/<branch>/<key>: the branch is everything before+ // the last segment.+ cut := strings.LastIndex(rest, "/")+ if cut <= 0 {+ continue+ }+ branch := rest[:cut]+ if _, headErr := runGit(gitRoot, "show-ref", "--verify", "--quiet", "refs/heads/"+branch); headErr == nil {+ continue+ }+ if out, delErr := runGit(gitRoot, "update-ref", "-d", ref); delErr != nil {+ if logger != nil {+ logger.Warn("execenv: could not drop a leftover ref of a deleted task branch (non-fatal)",+ "ref", ref, "output", strings.TrimSpace(out), "error", delErr)+ }+ continue+ }+ if logger != nil {+ logger.Info("execenv: dropped the leftovers of a branch that no longer exists",+ "git_root", gitRoot, "branch", branch, "ref", ref)+ }+ }}// checkUntrackedReplayable refuses a directory whose untracked content is toodiff --git a/server/internal/daemon/execenv/local_worktree_delivery_repair_test.go b/server/internal/daemon/execenv/local_worktree_delivery_repair_test.goindex 4dbff7c8ba..109fd248c9 100644--- a/server/internal/daemon/execenv/local_worktree_delivery_repair_test.go+++ b/server/internal/daemon/execenv/local_worktree_delivery_repair_test.go@@ -20,7 +20,7 @@ func applyRepairSteps(t *testing.T, wt *LocalWorktree, problem *DeliveryProblem)// 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) {+func requireRepairable(t *testing.T, repo string, wt *LocalWorktree, wantReason string, wantFiles map[string]string) LocalWorktreeOutcome {t.Helper()problem := wt.CheckDelivery()if problem == nil {@@ -50,6 +50,7 @@ func requireRepairable(t *testing.T, repo string, wt *LocalWorktree, wantReasont.Errorf("%s on the branch = %q, want %q", name, got, strings.TrimSpace(want))}}+ return outcome}// #9404 shape one: the agent squashes its commits and drops the empty baseline@@ -86,7 +87,10 @@ func TestCheckDeliveryRepairsWorkCommittedOffTheBranch(t *testing.T) {}// 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.+// Its own commits there extend the task branch; only HEAD is elsewhere. What+// it left uncommitted stays off the branch, exactly as it would have on the+// task branch itself (#9788): the repair delivers the commits, and Finalize+// saves the leftover edit aside.func TestCheckDeliveryRepairsWorkOnAFeatureBranch(t *testing.T) {t.Parallel()repo := newTestRepo(t)@@ -99,10 +103,136 @@ func TestCheckDeliveryRepairsWorkOnAFeatureBranch(t *testing.T) {// 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{+ problem := wt.CheckDelivery()+ if problem == nil || !problem.CommittedOnly {+ t.Fatalf("CheckDelivery = %+v, want a repair that delivers only the agent's commits", problem)+ }+ outcome := requireRepairable(t, repo, wt, "did not deliver onto its own branch", map[string]string{"agent.txt": "feature",- "tracked.txt": "edited",+ "tracked.txt": "original",})+ requireLeftovers(t, repo, outcome, wt.Branch, map[string]string{"tracked.txt": "edited"})+}++// #9404 shape one again, with leftovers: the agent committed, squashed past+// the baseline, and also left a generated file behind. The repair restores the+// ancestry and delivers the squashed commit's content, and the generated file+// is saved aside instead of riding along in the repair commit.+func TestCheckDeliveryRepairOfASquashKeepsLeftoversOffTheBranch(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")+ gitRun(t, wt.Path, "reset", "--soft", wt.BaseCommit+"^")+ gitRun(t, wt.Path, "commit", "-m", "squashed")+ writeFile(t, filepath.Join(wt.WorkDir, "artifacts", "render.bin"), "generated\n")+ // Staged is not committed: it stays a leftover too.+ gitRun(t, wt.Path, "add", "artifacts/render.bin")++ outcome := requireRepairable(t, repo, wt, "no longer contains", map[string]string{"agent.txt": "turn one"})+ if _, err := gitTry(t, repo, "cat-file", "-e", wt.Branch+":artifacts/render.bin"); err == nil {+ t.Error("the generated file the agent never committed reached the branch through the repair")+ }+ requireLeftovers(t, repo, outcome, wt.Branch, map[string]string{"artifacts/render.bin": "generated"})+}++// #9870 review: the committed-only repair loads Tip's tree into the index to+// commit it, which discards the agent's index. Anything only the index made+// visible to `git add -A` — a file staged past the ignore rules with `git add+// -f`, or registered with `git add -N -f` — then turned back into an ignored+// untracked file, Finalize found nothing to save, and the file was deleted+// with the worktree. The repair's last step now stages exactly what Finalize+// would have saved without the repair, so for every shape of leftover the+// saved ref is the same whether or not the turn needed repairing.+func TestCheckDeliveryRepairSavesTheSameLeftoversAsNoRepair(t *testing.T) {+ t.Parallel()+ shapes := map[string]func(t *testing.T, dir string){+ "forced add of an ignored file": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "fixtures", "sample.bin"), "staged past the ignore rule\n")+ gitRun(t, dir, "add", "-f", "fixtures/sample.bin")+ },+ "intent to add an ignored file": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "fixtures", "sample.bin"), "registered past the ignore rule\n")+ gitRun(t, dir, "add", "-N", "-f", "fixtures/sample.bin")+ },+ "intent to add a file": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "notes.txt"), "registered\n")+ gitRun(t, dir, "add", "-N", "notes.txt")+ },+ "staged file": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "notes.txt"), "staged\n")+ gitRun(t, dir, "add", "notes.txt")+ },+ "partly staged edit": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "tracked.txt"), "staged version\n")+ gitRun(t, dir, "add", "tracked.txt")+ writeFile(t, filepath.Join(dir, "tracked.txt"), "newer version on disk\n")+ },+ "unstaged edit, untracked file and deletions": func(t *testing.T, dir string) {+ writeFile(t, filepath.Join(dir, "tracked.txt"), "edited\n")+ writeFile(t, filepath.Join(dir, "scratch.log"), "untracked\n")+ gitRun(t, dir, "rm", "-q", "keep.txt")+ if err := os.Remove(filepath.Join(dir, ".gitignore")); err != nil {+ t.Fatal(err)+ }+ },+ }+ for name, leaveBehind := range shapes {+ t.Run(name, func(t *testing.T) {+ t.Parallel()+ turn := func(t *testing.T, repair bool) (string, LocalWorktreeOutcome, *LocalWorktree) {+ t.Helper()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, ".gitignore"), "fixtures/*.bin\n")+ gitRun(t, repo, "add", ".gitignore")+ gitRun(t, repo, "commit", "-m", "ignore generated fixtures")+ wt := prepareTurn(t, repo, "MUL-9404", turnOneTask)+ if repair {+ gitRun(t, wt.Path, "checkout", "--quiet", "-b", "feature/x")+ }+ writeFile(t, filepath.Join(wt.WorkDir, "doc.md"), "delivered documentation\n")+ gitRun(t, wt.Path, "add", "doc.md")+ gitRun(t, wt.Path, "commit", "-m", "docs")+ leaveBehind(t, wt.WorkDir)+ if repair {+ problem := wt.CheckDelivery()+ if problem == nil || !problem.CommittedOnly || problem.LeftoverTree == "" {+ t.Fatalf("CheckDelivery = %+v, want a committed-only repair carrying the leftovers", problem)+ }+ applyRepairSteps(t, wt, problem)+ if again := wt.CheckDelivery(); again != nil {+ t.Fatalf("the repair steps did not fix the delivery: %s", again.Reason)+ }+ } else if problem := wt.CheckDelivery(); problem != nil {+ t.Fatalf("a turn on its own branch was sent to repair: %s", problem.Reason)+ }+ outcome := finalizeOK(t, wt)+ if outcome.LeftoverRef == "" {+ t.Fatal("no leftovers saved")+ }+ if files := gitRun(t, repo, "diff", "--name-only", wt.BaseCommit, wt.Branch); files != "doc.md" {+ t.Errorf("the branch gained %q, want just the committed doc.md", files)+ }+ if _, err := os.Stat(wt.Path); !os.IsNotExist(err) {+ t.Errorf("worktree still present after Finalize: %v", err)+ }+ return repo, outcome, wt+ }+ plainRepo, plain, _ := turn(t, false)+ repairedRepo, repaired, _ := turn(t, true)+ // Both repos hold the same content, so equal leftovers are equal+ // tree ids.+ want := gitRun(t, plainRepo, "rev-parse", plain.LeftoverRef+"^{tree}")+ if got := gitRun(t, repairedRepo, "rev-parse", repaired.LeftoverRef+"^{tree}"); got != want {+ t.Errorf("leftovers after the repair differ from leftovers without it:\nwithout repair:\n%s\nafter repair:\n%s",+ gitRun(t, plainRepo, "show", "--stat", "--format=", plain.LeftoverRef),+ gitRun(t, repairedRepo, "show", "--stat", "--format=", repaired.LeftoverRef))+ }+ })+ }}// Uncommitted changes on a detached HEAD would be auto-committed onto thediff --git a/server/internal/daemon/execenv/local_worktree_leftovers_test.go b/server/internal/daemon/execenv/local_worktree_leftovers_test.gonew file mode 100644index 0000000000..8953e656cd--- /dev/null+++ b/server/internal/daemon/execenv/local_worktree_leftovers_test.go@@ -0,0 +1,371 @@+package execenv++import (+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+)++// Tests for #9788: an agent that commits its own work this turn delivers only+// those commits, and whatever it left uncommitted is saved under a hidden ref+// instead of being auto-committed onto the branch.++// leftoverRefs lists every leftover ref saved for branch.+func leftoverRefs(t *testing.T, repo, branch string) []string {+ t.Helper()+ out := gitRun(t, repo, "for-each-ref", "--format=%(refname)", leftoverRefPrefix+branch+"/")+ if out == "" {+ return nil+ }+ return strings.Split(out, "\n")+}++// requireLeftovers asserts the outcome names one saved leftover ref for+// branch, that the ref's parent is what the branch delivered, and that it+// carries wantFiles.+func requireLeftovers(t *testing.T, repo string, outcome LocalWorktreeOutcome, branch string, wantFiles map[string]string) {+ t.Helper()+ if outcome.AutoCommitted {+ t.Error("AutoCommitted = true, want the leftovers kept off the branch")+ }+ if !strings.HasPrefix(outcome.LeftoverRef, leftoverRefPrefix+branch+"/") {+ t.Fatalf("LeftoverRef = %q, want one under %s%s/", outcome.LeftoverRef, leftoverRefPrefix, branch)+ }+ if refs := leftoverRefs(t, repo, branch); len(refs) != 1 || refs[0] != outcome.LeftoverRef {+ t.Fatalf("leftover refs = %v, want just %s", refs, outcome.LeftoverRef)+ }+ if parent, tip := gitRun(t, repo, "rev-parse", outcome.LeftoverRef+"^"), gitRun(t, repo, "rev-parse", branch); parent != tip {+ t.Errorf("leftover commit's parent = %s, want the delivered tip %s", parent, tip)+ }+ for name, want := range wantFiles {+ if got := gitRun(t, repo, "show", outcome.LeftoverRef+":"+name); got != strings.TrimSpace(want) {+ t.Errorf("%s in the leftovers = %q, want %q", name, got, strings.TrimSpace(want))+ }+ }+}++// The #9788 report: the agent commits only the intended change and leaves a+// generated file and a scratch helper behind. Before, the daemon committed+// both onto the branch with --no-verify; now the branch carries only the+// agent's commit, and the leftovers — untracked, modified and deleted files+// alike — are recoverable from the hidden ref.+func TestFinalizeKeepsLeftoversOffTheBranchWhenTheAgentCommitted(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, ".gitignore"), "build/\n")+ gitRun(t, repo, "add", ".gitignore")+ gitRun(t, repo, "commit", "-m", "ignore build output")+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)++ writeFile(t, filepath.Join(wt.WorkDir, "doc.md"), "intended\n")+ gitRun(t, wt.Path, "add", "doc.md")+ gitRun(t, wt.Path, "commit", "-m", "docs: intended change")+ committed := gitRun(t, wt.Path, "rev-parse", "HEAD")++ writeFile(t, filepath.Join(wt.WorkDir, "artifacts", "repro", "render.bin"), "generated media\n")+ writeFile(t, filepath.Join(wt.WorkDir, "upload_helper.py"), "print('one-off')\n")+ writeFile(t, filepath.Join(wt.WorkDir, "tracked.txt"), "edited but not committed\n")+ if err := os.Remove(filepath.Join(wt.WorkDir, "keep.txt")); err != nil {+ t.Fatal(err)+ }+ writeFile(t, filepath.Join(wt.WorkDir, "build", "out.o"), "ignored\n")++ outcome := finalizeOK(t, wt)+ if outcome.Branch != wt.Branch {+ t.Fatalf("Branch = %q, want %q", outcome.Branch, wt.Branch)+ }+ if tip := gitRun(t, repo, "rev-parse", wt.Branch); tip != committed {+ t.Fatalf("branch tip = %s, want the agent's own commit %s: the leftovers were committed onto it", tip, committed)+ }+ if got := gitRun(t, repo, "show", wt.Branch+":tracked.txt"); got != "original" {+ t.Errorf("tracked.txt on the branch = %q, want the committed version", got)+ }+ if got := gitRun(t, repo, "show", wt.Branch+":keep.txt"); got != "keep" {+ t.Errorf("keep.txt on the branch = %q, want it still there", got)+ }++ requireLeftovers(t, repo, outcome, wt.Branch, map[string]string{+ "artifacts/repro/render.bin": "generated media",+ "upload_helper.py": "print('one-off')",+ "tracked.txt": "edited but not committed",+ })+ ref := outcome.LeftoverRef+ if _, err := gitTry(t, repo, "cat-file", "-e", ref+":keep.txt"); err == nil {+ t.Error("the leftovers lost the agent's uncommitted deletion of keep.txt")+ }+ if _, err := gitTry(t, repo, "cat-file", "-e", ref+":build/out.o"); err == nil {+ t.Error("a gitignored file was saved with the leftovers")+ }+ if !strings.HasSuffix(ref, "/"+taskKey(turnOneTask)) {+ t.Errorf("leftover ref %s is not named after the task", ref)+ }+ message := gitRun(t, repo, "log", "-1", "--format=%B", ref)+ for _, want := range []string{"left uncommitted", "artifacts/repro/render.bin", "git restore --source="} {+ if !strings.Contains(message, want) {+ t.Errorf("leftover commit message is missing %q:\n%s", want, message)+ }+ }+ if _, err := os.Stat(wt.Path); !os.IsNotExist(err) {+ t.Errorf("worktree still present after Finalize: %v", err)+ }+ // The ref is enough to get a file back.+ gitRun(t, repo, "restore", "--source="+ref, "--", "upload_helper.py")+ if got := readFile(t, filepath.Join(repo, "upload_helper.py")); got != "print('one-off')\n" {+ t.Errorf("restored helper = %q", got)+ }+}++// The repository's commit hooks are no longer bypassed for the leftovers,+// because nothing is committed for them at all: a pre-commit size guard that+// rejects the generated file sees only the agent's own commits.+func TestFinalizeDoesNotCommitLeftoversPastAPreCommitHook(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell hook")+ }+ repo := newTestRepo(t)+ hook := filepath.Join(repo, ".git", "hooks", "pre-commit")+ writeFile(t, hook, "#!/bin/sh\nif git diff --cached --name-only | grep -q '^artifacts/'; then echo 'artifacts are not allowed' >&2; exit 1; fi\n")+ if err := os.Chmod(hook, 0o755); err != nil {+ t.Fatal(err)+ }+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "doc.md"), "intended\n")+ gitRun(t, wt.Path, "add", "doc.md")+ gitRun(t, wt.Path, "commit", "-m", "docs: intended change")+ writeFile(t, filepath.Join(wt.WorkDir, "artifacts", "big.bin"), strings.Repeat("x", 1<<20))++ outcome := finalizeOK(t, wt)+ if files := gitRun(t, repo, "log", "--format=", "--name-only", wt.BaseCommit+".."+wt.Branch); files != "doc.md" {+ t.Fatalf("files the branch gained = %q, want just doc.md", files)+ }+ requireLeftovers(t, repo, outcome, wt.Branch, nil)+}++// An agent that made no commit still delivers everything it left: for it the+// uncommitted files ARE the work, and no leftover ref is written.+func TestFinalizeStillAutoCommitsWhenTheAgentMadeNoCommit(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "uncommitted work\n")++ outcome := finalizeOK(t, wt)+ if !outcome.AutoCommitted || outcome.LeftoverRef != "" {+ t.Fatalf("AutoCommitted = %v, LeftoverRef = %q; want the work committed onto the branch", outcome.AutoCommitted, outcome.LeftoverRef)+ }+ if got := gitRun(t, repo, "show", wt.Branch+":agent.txt"); got != "uncommitted work" {+ t.Errorf("agent.txt on the branch = %q", got)+ }+ if refs := leftoverRefs(t, repo, wt.Branch); len(refs) != 0 {+ t.Errorf("leftover refs written for a turn without commits: %v", refs)+ }+}++// A committed turn with nothing left over saves nothing.+func TestFinalizeSavesNoLeftoversForACleanCommittedTurn(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "work\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")++ outcome := finalizeOK(t, wt)+ if outcome.AutoCommitted || outcome.LeftoverRef != "" {+ t.Fatalf("AutoCommitted = %v, LeftoverRef = %q; want neither", outcome.AutoCommitted, outcome.LeftoverRef)+ }+ if refs := leftoverRefs(t, repo, wt.Branch); len(refs) != 0 {+ t.Errorf("leftover refs = %v, want none", refs)+ }+}++// On a continued branch "this turn" starts at the tip the previous turn+// delivered, and the leftovers are never replayed into the next turn: they+// are not part of the branch, and the user's own directory never had them.+func TestFinalizeKeepsLeftoversOffAContinuedBranch(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ first := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(first.WorkDir, "one.txt"), "turn one\n")+ finalizeOK(t, first)++ second := prepareTurn(t, repo, "MUL-9788", 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", "two.txt")+ gitRun(t, second.Path, "commit", "-m", "turn two")+ writeFile(t, filepath.Join(second.WorkDir, "scratch.log"), "scratch\n")+ outcome := finalizeOK(t, second)+ requireLeftovers(t, repo, outcome, second.Branch, map[string]string{"scratch.log": "scratch"})+ if !strings.HasSuffix(outcome.LeftoverRef, "/"+taskKey(turnTwoTask)) {+ t.Errorf("leftover ref %s is not named after the second turn", outcome.LeftoverRef)+ }++ third := prepareTurn(t, repo, "MUL-9788", turnThreeTask)+ if _, err := os.Stat(filepath.Join(third.WorkDir, "scratch.log")); !os.IsNotExist(err) {+ t.Errorf("the previous turn's leftover reappeared in the next turn: %v", err)+ }+ for _, name := range []string{"one.txt", "two.txt"} {+ if _, err := os.Stat(filepath.Join(third.WorkDir, name)); err != nil {+ t.Errorf("third turn is missing delivered %s: %v", name, err)+ }+ }+ finalizeOK(t, third)+}++// A turn that started on an unresolved merge keeps the old rule. Its+// uncommitted changes include the user's own replayed edits, which the branch+// is about to be recorded as carrying; saving those aside after a partial+// commit would record edits as delivered that the branch does not hold.+func TestFinalizeCommitsEverythingOnATurnThatStartedMidMerge(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ writeFile(t, filepath.Join(repo, "tracked.txt"), "user A\n")+ first := prepareTurn(t, repo, "MUL-9788", 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")+ writeFile(t, filepath.Join(repo, "notes.txt"), "user's other edit\n")++ second := prepareTurn(t, repo, "MUL-9788", turnTwoTask)+ if len(second.ReplayConflicts) != 1 {+ t.Fatalf("expected a replay conflict, got %v", second.ReplayConflicts)+ }+ // The prompt states the exception from this same predicate.+ if first.CommitsAllLeftovers() || !second.CommitsAllLeftovers() {+ t.Fatalf("CommitsAllLeftovers: first turn %v, mid-merge turn %v; want false, true",+ first.CommitsAllLeftovers(), second.CommitsAllLeftovers())+ }+ // The agent resolves and commits only the conflicted file, then leaves+ // generated output behind.+ writeFile(t, filepath.Join(second.WorkDir, "tracked.txt"), "agent B and user C\n")+ gitRun(t, second.Path, "add", "tracked.txt")+ gitRun(t, second.Path, "reset", "-q", "--", "notes.txt")+ gitRun(t, second.Path, "commit", "-m", "resolve")+ writeFile(t, filepath.Join(second.WorkDir, "generated.bin"), "scratch output\n")++ outcome := finalizeOK(t, second)+ if outcome.LeftoverRef != "" || !outcome.AutoCommitted {+ t.Fatalf("AutoCommitted = %v, LeftoverRef = %q; want the user's replayed edit committed", outcome.AutoCommitted, outcome.LeftoverRef)+ }+ if got := gitRun(t, repo, "show", second.Branch+":notes.txt"); got != "user's other edit" {+ t.Errorf("notes.txt on the branch = %q, want the user's replayed edit", got)+ }+ // This is the behaviour the prompt has to warn about.+ if got := gitRun(t, repo, "show", second.Branch+":generated.bin"); got != "scratch output" {+ t.Errorf("generated.bin on the branch = %q, want it committed under the exception", got)+ }+}++// When the leftovers cannot be saved, nothing is lost: the worktree stays, as+// it does for an auto-commit that fails, and the delivery is not recorded.+func TestFinalizeKeepsTheWorktreeWhenLeftoversCannotBeSaved(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "work\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ committed := gitRun(t, wt.Path, "rev-parse", "HEAD")+ writeFile(t, filepath.Join(wt.WorkDir, "scratch.log"), "scratch\n")+ // A ref sitting where the branch's leftover directory has to go makes+ // every ref below it impossible to create.+ gitRun(t, repo, "update-ref", strings.TrimSuffix(leftoverRefPrefix, "/")+"/"+wt.Branch, committed)++ outcome, err := wt.Finalize(worktreeTestLogger())+ if err == nil {+ t.Fatal("Finalize succeeded although the leftovers could not be saved")+ }+ if !strings.Contains(err.Error(), "left uncommitted") || outcome.PreservedPath != wt.Path {+ t.Fatalf("err = %v, PreservedPath = %q; want the worktree preserved", err, outcome.PreservedPath)+ }+ if got := readFile(t, filepath.Join(wt.WorkDir, "scratch.log")); got != "scratch\n" {+ t.Errorf("the leftover is gone from the preserved worktree: %q", got)+ }+ ref, _ := readUserStateRef(repo, wt.Branch)+ if record, recErr := readBranchRecord(repo, ref); recErr != nil || record.checkpoint == committed {+ t.Errorf("the delivery was recorded although its leftovers were not saved (record %+v, err %v)", record, recErr)+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// A task re-dispatched under the same id never overwrites what the first+// attempt left: the second save takes a name of its own.+func TestSaveLeftoversNeverOverwritesAnEarlierSave(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ wt := prepareTurn(t, repo, "MUL-9788", turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "work\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ tip := gitRun(t, wt.Path, "rev-parse", "HEAD")+ writeFile(t, filepath.Join(wt.WorkDir, "scratch.log"), "first\n")++ first, err := wt.saveLeftovers(tip, worktreeTestLogger())+ if err != nil || first == "" {+ t.Fatalf("first save: %q, %v", first, err)+ }+ firstCommit := gitRun(t, repo, "rev-parse", first)+ writeFile(t, filepath.Join(wt.WorkDir, "scratch.log"), "second\n")+ second, err := wt.saveLeftovers(tip, worktreeTestLogger())+ if err != nil || second == "" || second == first {+ t.Fatalf("second save: %q, %v; want a ref other than %s", second, err, first)+ }+ if got := gitRun(t, repo, "rev-parse", first); got != firstCommit {+ t.Errorf("the first save was overwritten: %s, want %s", got, firstCommit)+ }+ if got := gitRun(t, repo, "show", second+":scratch.log"); got != "second" {+ t.Errorf("second save holds %q", got)+ }+ _ = removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger())+}++// Leftover refs go with their branch: Multica drops them when it drops the+// branch, and a later prepare prunes those of a branch the user deleted.+func TestLeftoverRefsAreDroppedWithTheirBranch(t *testing.T) {+ t.Parallel()+ committedTurnWithLeftovers := func(t *testing.T, repo, key string) string {+ t.Helper()+ wt := prepareTurn(t, repo, key, turnOneTask)+ writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "work\n")+ gitRun(t, wt.Path, "add", "-A")+ gitRun(t, wt.Path, "commit", "-m", "work")+ writeFile(t, filepath.Join(wt.WorkDir, "scratch.log"), "scratch\n")+ if outcome := finalizeOK(t, wt); outcome.LeftoverRef == "" {+ t.Fatal("no leftovers saved")+ }+ return wt.Branch+ }++ t.Run("dropBranch", func(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ branch := committedTurnWithLeftovers(t, repo, "MUL-9788")+ dropBranch(repo, branch, worktreeTestLogger())+ if refs := leftoverRefs(t, repo, branch); len(refs) != 0 {+ t.Errorf("leftover refs survived dropBranch: %v", refs)+ }+ })++ t.Run("pruned after the user deletes the branch", func(t *testing.T) {+ t.Parallel()+ repo := newTestRepo(t)+ branch := committedTurnWithLeftovers(t, repo, "MUL-9788")+ kept := committedTurnWithLeftovers(t, repo, "MUL-1")+ gitRun(t, repo, "branch", "-D", branch)++ next := prepareTurn(t, repo, "MUL-2", turnTwoTask)+ if refs := leftoverRefs(t, repo, branch); len(refs) != 0 {+ t.Errorf("leftover refs of a deleted branch survived the next prepare: %v", refs)+ }+ if refs := leftoverRefs(t, repo, kept); len(refs) != 1 {+ t.Errorf("leftover refs of a live branch were pruned: %v", refs)+ }+ finalizeOK(t, next)+ })+}diff --git a/server/internal/daemon/execenv/local_worktree_test.go b/server/internal/daemon/execenv/local_worktree_test.goindex d4d269a3e2..94fcf1d41f 100644--- a/server/internal/daemon/execenv/local_worktree_test.go+++ b/server/internal/daemon/execenv/local_worktree_test.go@@ -2346,9 +2346,9 @@ func TestIsolatedPrepareCarriesTheStateFinalizeNeeds(t *testing.T) {}// The proofs Finalize makes all hang off state that crosses as JSON —// createdBranch among them, without which a read-only turn keeps its branch.- if !wt.tracksState || wt.userState == "" || wt.owner != testBranchOwner || !wt.createdBranch {- t.Fatalf("state lost crossing the helper boundary: tracksState=%v userState=%q owner=%+v createdBranch=%v",- wt.tracksState, wt.userState, wt.owner, wt.createdBranch)+ if !wt.tracksState || wt.userState == "" || wt.owner != testBranchOwner || !wt.createdBranch || wt.taskID != turnOneTask {+ t.Fatalf("state lost crossing the helper boundary: tracksState=%v userState=%q owner=%+v createdBranch=%v taskID=%q",+ wt.tracksState, wt.userState, wt.owner, wt.createdBranch, wt.taskID)}writeFile(t, filepath.Join(wt.WorkDir, "agent.txt"), "work from turn one\n")diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex f59fa4209d..bf117f80d0 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -64,7 +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))+ b.WriteString(buildWorktreeBranchBlock(opts.worktreeBranch, opts.worktreeBase, opts.worktreeCommitsAllLeftovers))if task.PriorSessionResumeUnavailable {b.WriteString(sessionContinuityNoticeFor(task))}@@ -138,10 +138,11 @@ func buildJoinedWakeupsBlock(notes string) string {// daemon's own execution context can answer. Kept behind PromptOption so the// common BuildPrompt(task, provider) call sites stay unchanged.type promptOpts struct {- sharedLocalDirectory bool- worktreeReplayConflicts []string- worktreeBranch string- worktreeBase string+ sharedLocalDirectory bool+ worktreeReplayConflicts []string+ worktreeBranch string+ worktreeBase string+ worktreeCommitsAllLeftovers bool}// PromptOption tunes per-turn prompt copy with run-scoped context.@@ -179,10 +180,26 @@ func WithWorktreeBranch(branch, base string) PromptOption {}}+// WithWorktreeCommitsAllLeftovers marks a worktree turn whose uncommitted+// files will all be committed onto the branch at the end, even after the+// agent's own commits — execenv.LocalWorktree.CommitsAllLeftovers. The task+// branch block then states that instead of the usual rule, so the agent knows+// to clear out what it does not want delivered (#9788 review).+func WithWorktreeCommitsAllLeftovers() PromptOption {+ return func(o *promptOpts) { o.worktreeCommitsAllLeftovers = true }+}+// buildWorktreeBranchBlock states the delivery contract of a worktree turn.+// That includes what happens to uncommitted files: Finalize commits them for+// an agent that made no commit and keeps them off the branch for one that did+// (#9788), and an agent that is not told so cannot choose which side it lands+// on — it leaves scratch output behind assuming it will not be delivered. A+// turn that started on an unresolved merge of the user's edits is the+// exception (commitsAllLeftovers): there everything is committed either way,+// and the block says so rather than promising what Finalize will not do.// 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 {+func buildWorktreeBranchBlock(branch, base string, commitsAllLeftovers bool) string {if branch == "" || base == "" {return ""}@@ -191,6 +208,12 @@ func buildWorktreeBranchBlock(branch, base string) string {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")+ if commitsAllLeftovers {+ b.WriteString("- This run starts by finishing a merge of the user's edits, so when it ends everything you leave that is not gitignored is committed onto the branch for you — even if you have made commits of your own — without running the repository's commit hooks. That keeps the user's edits from being dropped. Delete scratch files and generated output you do not want delivered before you finish.\n")+ } else {+ b.WriteString("- If you commit, only your commits are delivered. Whatever you leave uncommitted after committing — generated output, scratch files, edits you did not commit — is saved aside for the user and does not reach the branch, so commit everything that belongs to the work.\n")+ b.WriteString("- If you make no commit, everything you leave that is not gitignored is committed onto the branch for you when the run ends, without running the repository's commit hooks. Delete scratch files and generated output you do not want delivered before you finish.\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()}@@ -204,7 +227,11 @@ func BuildWorktreeDeliveryRepairPrompt(problem *execenv.DeliveryProblem) stringb.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")+ if problem.CommittedOnly {+ b.WriteString("Fix it in this worktree. This sequence puts exactly what your commits contain on the branch as one commit, and leaves your files as they are; its last line stages everything you left uncommitted, so none of it is lost. Uncommitted changes still do not reach the branch: like any change left uncommitted after you commit, they are saved aside rather than delivered:\n\n```sh\n")+ } else {+ 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 {@@ -216,7 +243,7 @@ func BuildWorktreeDeliveryRepairPrompt(problem *execenv.DeliveryProblem) stringb.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)+ fmt.Fprintf(&b, "Before the `git commit` line, 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()}diff --git a/server/internal/daemon/worktree_delivery_repair_test.go b/server/internal/daemon/worktree_delivery_repair_test.goindex 4d7be4fcb5..467c474688 100644--- a/server/internal/daemon/worktree_delivery_repair_test.go+++ b/server/internal/daemon/worktree_delivery_repair_test.go@@ -33,25 +33,70 @@ func TestWorktreeBranchBlock(t *testing.T) {"`abc123def`","Do not squash, amend, rebase or reset past `abc123def`","git push origin HEAD:<name>",+ // #9788: the agent is told what happens to what it leaves uncommitted,+ // on both sides of the rule.+ "If you commit, only your commits are delivered",+ "does not reach the branch",+ "If you make no commit, everything you leave that is not gitignored is committed onto the branch for you",+ "without running the repository's commit hooks",} {if !strings.Contains(out, want) {t.Errorf("prompt missing %q:\n%s", want, out)}}++ // #9870 review: a turn that started mid-merge commits everything it leaves+ // even after the agent's own commits, so it must not be promised the+ // usual rule.+ pending := BuildPrompt(task, "claude", WithWorktreeBranch("agent/j/mul-9404", "abc123def"), WithWorktreeCommitsAllLeftovers())+ for _, want := range []string{+ "## Your task branch",+ "everything you leave that is not gitignored is committed onto the branch for you — even if you have made commits of your own",+ "Delete scratch files and generated output you do not want delivered",+ } {+ if !strings.Contains(pending, want) {+ t.Errorf("mid-merge prompt missing %q:\n%s", want, pending)+ }+ }+ if strings.Contains(pending, "If you commit, only your commits are delivered") {+ t.Errorf("mid-merge prompt promises the rule Finalize does not apply to it:\n%s", pending)+ }}// 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.+// same argv — the commit message carries an apostrophe. Both shapes of the+// sequence are checked: a turn that made commits of its own gets the one that+// delivers only those commits (#9788).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",+ for _, tc := range []struct {+ name string+ committedOnly bool+ want []string+ }{+ {name: "no commits of its own", want: []string{"keeps every file exactly as it is now", "git add -A"}},+ {name: "committed this turn", committedOnly: true, want: []string{"exactly what your commits contain", "stages everything you left uncommitted", "saved aside rather than delivered", "git read-tree fff000", "git read-tree 4b825dc"}},+ } {+ t.Run(tc.name, func(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",+ CommittedOnly: tc.committedOnly,+ }+ if tc.committedOnly {+ problem.LeftoverTree = "4b825dc"+ }+ checkWorktreeDeliveryRepairPrompt(t, problem, tc.want)+ })}+}++func checkWorktreeDeliveryRepairPrompt(t *testing.T, problem *execenv.DeliveryProblem, extra []string) {+ t.Helper()out := BuildWorktreeDeliveryRepairPrompt(problem)- for _, want := range []string{problem.Reason, "`agent/j/mul-9404`", "git diff --cached abc123def", "no new comments or status updates"} {+ for _, want := range append([]string{problem.Reason, "`agent/j/mul-9404`", "git diff --cached abc123def", "no new comments or status updates"}, extra...) {if !strings.Contains(out, want) {t.Errorf("repair prompt missing %q:\n%s", want, out)}