Skip to content

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

Go

feat(daemon): worktree mode for local_directory resources (MUL-5707) (#6759)

Bohan Jiangc9727e6b2bac
diff --git a/apps/desktop/src/main/local-directory.ts b/apps/desktop/src/main/local-directory.ts
index 5e9311a447..4f523229a5 100644
--- a/apps/desktop/src/main/local-directory.ts
+++ b/apps/desktop/src/main/local-directory.ts
@@ -1,7 +1,7 @@
import { ipcMain, dialog, BrowserWindow } from "electron";
import { access, stat } from "fs/promises";
import { constants as fsConstants } from "fs";
-import { basename, isAbsolute } from "path";
+import { basename, dirname, isAbsolute, join } from "path";
export interface PickDirectoryResult {
ok: boolean;
@@ -24,6 +24,15 @@ export interface ValidateLocalDirectoryResult {
| "not_writable"
| "error";
error?: string;
+ /**
+ * Whether the directory sits inside a git working tree. Only set when ok=true.
+ *
+ * Worktree execution mode requires a git repo, and only the desktop app can
+ * see the filesystem — the server cannot. Reporting it here lets the picker
+ * disable that mode with a reason at selection time, instead of letting the
+ * user save a resource whose very first task fails.
+ */
+ is_git_repo?: boolean;
}
async function validateLocalDirectory(
@@ -50,7 +59,32 @@ async function validateLocalDirectory(
} catch {
return { ok: false, reason: "not_writable" };
}
- return { ok: true };
+ return { ok: true, is_git_repo: await isInsideGitWorkTree(path) };
+}
+
+/**
+ * Walks up from `path` looking for a `.git` entry, mirroring how git itself
+ * resolves a working tree — so a subdirectory of a repo reports true, matching
+ * what the daemon does with `rev-parse --show-toplevel` at task time.
+ *
+ * `.git` is accepted as either a directory (ordinary clone) or a file (a linked
+ * worktree, where it holds a gitdir pointer). Any error means "can't tell",
+ * which is reported as not-a-repo: this only drives a UI hint, and the daemon
+ * re-checks authoritatively before running anything.
+ */
+async function isInsideGitWorkTree(path: string): Promise<boolean> {
+ let current = path;
+ for (;;) {
+ try {
+ await stat(join(current, ".git"));
+ return true;
+ } catch {
+ // Not here — keep walking up.
+ }
+ const parent = dirname(current);
+ if (parent === current) return false;
+ current = parent;
+ }
}
function errorMessage(err: unknown): string {
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index 524810f213..4f64e96abc 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -98,6 +98,9 @@ interface DesktopAPI {
| "not_writable"
| "error";
error?: string;
+ /** Whether the path sits inside a git working tree. Only set when ok=true.
+ * Drives the worktree execution-mode option in the resource UI. */
+ is_git_repo?: boolean;
}>;
/** Listen for Cmd/Ctrl+W tab-close requests from the main process.
* Returns an unsubscribe function. */
diff --git a/apps/docs/content/docs/project-resources.ja.mdx b/apps/docs/content/docs/project-resources.ja.mdx
index 51ce45cbb8..7979b8900b 100644
--- a/apps/docs/content/docs/project-resources.ja.mdx
+++ b/apps/docs/content/docs/project-resources.ja.mdx
@@ -39,7 +39,7 @@ import { Callout } from "fumadocs-ui/components/callout";
<Callout type="warning">
**これは非常口であって、より便利なデフォルトではありません。** `local_directory` は他に選択肢がない人のために存在します — 典型例は、チェックアウトが数十ギガバイトになるゲームプロジェクトで、タスクごとの再クローンが現実的に不可能なケースです。
-対象のディレクトリが普通にクローンできる通常の git リポジトリなら、**代わりに `github_repo` を使ってください**。既定でワークツリーモードで動作するため、同じリポジトリに対するタスクを無制限に並行実行できます。`local_directory` を選ぶということは、そのフォルダ上のタスクが以降 **常に一度に1つずつ直列で** 実行されるということです。決める前に下の「選ぶとき」を読んでください。
+対象のディレクトリが普通にクローンできる通常の git リポジトリなら、**代わりに `github_repo` を使ってください**。既定でワークツリーモードで動作するため、同じリポジトリに対するタスクを無制限に並行実行できます。`local_directory` は **既定では一度に1つのタスクしか実行しません**。ディレクトリ自体が git リポジトリであれば、ワークツリーモードを有効にして並行実行を取り戻せます(「タスクがディレクトリを共有する方法」を参照)。決める前に下の「選ぶとき」を読んでください。
</Callout>
@@ -52,16 +52,41 @@ import { Callout } from "fumadocs-ui/components/callout";
同じデーモンに紐づけられるローカルディレクトリは、プロジェクトごとに最大 1 つです。チーム内の別々のコンピュータは、同じプロジェクトにそれぞれ自分のディレクトリを紐づけられます。
<Callout type="warning">
-ローカルディレクトリは隔離された環境ではありません。エージェントは現在のブランチと未コミットのファイルをそのまま参照・変更します。Multica がブランチの切り替え、stash、commit、push、PR の作成を自動で行うことはありません。
+既定の `in_place` モードでは、ローカルディレクトリは隔離された環境ではありません。エージェントは現在のブランチと未コミットのファイルをそのまま参照・変更し、Multica がブランチの切り替え、stash、commit、push、PR の作成を自動で行うこともありません。ワークツリーモードはこの点を変えます — 下の「タスクがディレクトリを共有する方法」を参照してください。
</Callout>
-## ローカルディレクトリの直列実行
+## タスクがディレクトリを共有する方法
-2 つのタスクが同じ実体のディレクトリを使う場合、後から来たタスクは `waiting_local_directory` に入り、先のタスクがディレクトリを解放してから続行します。異なるシンボリックリンク経由で同じディレクトリに到達する 2 つのパスも、同じように直列化されます。
+ローカルディレクトリには 2 つの実行モードがあり、リソースごとに設定します。リソースパネルから切り替えられるほか、CLI では `--execution-mode` を使います。
+
+### `in_place`(既定)
+
+エージェントはあなたのディレクトリで直接作業し、タスクは一度に1つずつ実行されます。2 つのタスクが同じ実体のディレクトリを使う場合、後から来たタスクは `waiting_local_directory` に入り、先のタスクがディレクトリを解放してから続行します。異なるシンボリックリンク経由で同じディレクトリに到達する 2 つのパスも、同じように直列化されます。
待機中にディレクトリが変更されることはありません。待機中のタスクはキャンセルできます。キャンセルしなければ、ディレクトリが使えるようになるまで待ち続けます。
-複数の変更を同時に進めたい場合は、GitHub リポジトリリソースを使い、作業ごとの作業ディレクトリをランタイムに用意させてください。
+### `worktree`
+
+各タスクが、あなたのリポジトリの独立した [git ワークツリー](https://git-scm.com/docs/git-worktree) を受け取ります。ワークツリーはランタイム自身のワークスペースディレクトリ内に作成されます。**同じディレクトリに対するタスクは並行して実行され、待機は発生しません**。どのタスクもあなたの作業コピーには書き込みません。
+
+このモードには、コミットが 1 つ以上ある git リポジトリであることが必要です。そうでない場合、タスクは黙って直列実行に戻るのではなく、明示的なエラーで失敗します。そのマシンのランタイムも、このモードを実装しているバージョンである必要があり、これは 2 回検証されます。リソースの保存時に古すぎれば拒否されアップグレードを促され、さらに各タスクは実際にそれを受け取ったランタイムに対して再度検証されます — つまりリソース保存後にダウングレードされたマシンでは、タスクが黙ってその場で実行されるのではなく、理由付きでキャンセルされます。`worktree` を選ぶことは隔離を求めることであり、代わりに作業コピーを書き換えることがフォールバックになることはありません。
+
+エージェントが見るもの、あなたが受け取るもの:
+
+- **エージェントは `HEAD` ではなく、あなたが今見ている状態から開始します。** 未コミットの変更と未追跡ファイルがワークツリーに再現されるため、すでに手元にないコードをレビューすることはありません。あなた自身の作業コピー、インデックス、stash リストが変更されることはありません。その状態を忠実に再現できない場合 — 再現の上限(2000 ファイル / 200 MiB)を超える未追跡コンテンツがある場合を含む — タスクは、見覚えのないツリーから開始する代わりに失敗します。通常の対処法は、まだ無視されていないビルド成果物を gitignore に加えるか削除することです。
+- **成果物はあなたのリポジトリ内のブランチ**で、`agent/<agent>/<task>` という名前が付きます。実行の「実行詳細」パネルにブランチ名が表示され(コピーも可能)、`git branch` でも見つけられます。`git log` / `git diff` でレビューし、マージするか cherry-pick するかは自分で決めます。Multica が代わりにマージすることはありません。途中で失敗した実行もブランチを報告します。エージェントが作った分はすでにコミットされているからです。
+- **黙って失われるものはありません。** エージェントが未コミットのまま残した変更は、ワークツリーが削除される前にそのブランチへコミットされます。**タスクが途中で失敗した場合も同様です。** ごくまれにそのコミット自体が実行できない場合 — 例えば `commit.gpgSign` が有効で、ランタイムが署名鍵を利用できないリポジトリ — ワークツリーは削除されずに意図的に保持され、タスクは失敗として報告されます。あなたのリポジトリで `git worktree list` を実行すると、その変更を保持しているディレクトリが表示されます。
+- **何も変更しなかったタスクは、何も残しません。** そのブランチは `git branch` に空の項目として残らず、削除されます。
+
+ワークツリーはランタイムのワークスペースディレクトリ内にあるため、通常のクリーンアップ周期で回収されます。あなたのリポジトリに残るのはブランチだけです。
+
+<Callout type="warn">
+**セルフホスト運用者向け:** このモードの分離はサーバー側で強制されます(リソース保存時と、ランタイムが各タスクを取得する時点の二重チェック)。そのため、ランタイムをいつダウングレードしても検出されます。検出できない唯一の組み合わせは、最低バージョン未満のランタイムが接続されたまま、サーバーをこの機能より前のビルドへロールバックすることです — 古いサーバーにはこのゲートがなく、古いランタイムは `execution_mode` を無視してタスクを元のディレクトリで直接実行してしまいます。`worktree` リソースが存在する間は、対象マシンのランタイムがすべて最新でない限り、サーバーをこのリリースより前へロールバックしないでください。
+</Callout>
+
+<Callout type="info">
+ワークツリーモードは git リポジトリを対象とします。git 管理外の通常のディレクトリは引き続き直列実行です — それが `in_place` の役割です。
+</Callout>
## 実行中に書き込まれるもの
@@ -90,6 +115,18 @@ multica project resource add <project-id> \
--local-path /absolute/path/to/repo \
--daemon-id <daemon-id>
+# ローカル git リポジトリを紐づけ、タスクを各自のワークツリーで並行実行させる
+multica project resource add <project-id> \
+ --type local_directory \
+ --local-path /absolute/path/to/repo \
+ --daemon-id <daemon-id> \
+ --execution-mode worktree
+
+# 既存のローカルディレクトリのモードを切り替える
+multica project resource update <project-id> <resource-id> --execution-mode worktree
+multica project resource update <project-id> <resource-id> --execution-mode in_place
+
+
# リソースを削除する
multica project resource remove <project-id> <resource-id>
```
diff --git a/apps/docs/content/docs/project-resources.ko.mdx b/apps/docs/content/docs/project-resources.ko.mdx
index 41386f48a9..a0935e6b9e 100644
--- a/apps/docs/content/docs/project-resources.ko.mdx
+++ b/apps/docs/content/docs/project-resources.ko.mdx
@@ -39,7 +39,7 @@ import { Callout } from "fumadocs-ui/components/callout";
<Callout type="warning">
**이것은 비상구이지, 더 편리한 기본값이 아닙니다.** `local_directory`는 다른 선택지가 없는 사람들을 위해 존재합니다 — 대표적인 사례는 체크아웃 하나가 수십 기가바이트인 게임 프로젝트로, 작업마다 다시 클론하는 것이 현실적으로 불가능한 경우입니다.
-대상 디렉터리가 평범하게 클론할 수 있는 일반 git 저장소라면 **대신 `github_repo`를 사용하세요**: 기본적으로 워크트리 모드로 동작하므로 같은 저장소에 대한 작업을 무제한으로 동시에 실행할 수 있습니다. `local_directory`를 선택한다는 것은 그 폴더의 작업이 이후로 **항상 한 번에 하나씩 직렬로** 실행된다는 뜻입니다. 결정하기 전에 위의 리소스 비교를 확인하세요.
+대상 디렉터리가 평범하게 클론할 수 있는 일반 git 저장소라면 **대신 `github_repo`를 사용하세요**: 기본적으로 워크트리 모드로 동작하므로 같은 저장소에 대한 작업을 무제한으로 동시에 실행할 수 있습니다. `local_directory`는 **기본적으로 한 번에 하나의 작업만 실행합니다**. 디렉터리 자체가 git 저장소라면 워크트리 모드를 켜서 동시 실행을 되찾을 수 있습니다(“작업이 디렉터리를 공유하는 방식” 참고). 결정하기 전에 위의 리소스 비교를 확인하세요.
</Callout>
@@ -52,16 +52,41 @@ import { Callout } from "fumadocs-ui/components/callout";
프로젝트 하나에는 같은 데몬에서 로컬 디렉터리를 최대 하나만 연결할 수 있습니다. 팀의 서로 다른 컴퓨터에서는 같은 프로젝트에 각자의 디렉터리를 연결할 수 있습니다.
<Callout type="warning">
-로컬 디렉터리는 격리된 환경이 아닙니다. 에이전트가 현재 브랜치와 커밋하지 않은 파일을 직접 보고 수정합니다. Multica는 브랜치 전환, stash, commit, push, PR 생성을 자동으로 수행하지 않습니다.
+기본값인 `in_place` 모드에서 로컬 디렉터리는 격리된 환경이 아닙니다. 에이전트가 현재 브랜치와 커밋하지 않은 파일을 직접 보고 수정하며, Multica는 브랜치 전환, stash, commit, push, PR 생성을 자동으로 수행하지 않습니다. 워크트리 모드는 이 점을 바꿉니다 — 아래 “작업이 디렉터리를 공유하는 방식”을 참고하세요.
</Callout>
-## 로컬 디렉터리 직렬 실행
+## 작업이 디렉터리를 공유하는 방식
-두 실행 태스크가 같은 실제 디렉터리를 사용하면 나중에 도착한 태스크가 `waiting_local_directory` 상태로 들어가 앞선 태스크가 디렉터리를 해제할 때까지 기다립니다. 서로 다른 심볼릭 링크 경로가 같은 디렉터리를 가리켜도 직렬로 실행됩니다.
+로컬 디렉터리에는 두 가지 실행 모드가 있으며 리소스별로 설정합니다. 리소스 패널에서 전환할 수 있고, CLI에서는 `--execution-mode`를 사용합니다.
+
+### `in_place`(기본값)
+
+에이전트가 사용자의 디렉터리에서 직접 작업하며, 작업은 한 번에 하나씩 실행됩니다. 두 실행 태스크가 같은 실제 디렉터리를 사용하면 나중에 도착한 태스크가 `waiting_local_directory` 상태로 들어가 앞선 태스크가 디렉터리를 해제할 때까지 기다립니다. 서로 다른 심볼릭 링크 경로가 같은 디렉터리를 가리켜도 직렬로 실행됩니다.
기다리는 동안 디렉터리는 변경되지 않습니다. 대기 중인 태스크는 취소할 수 있으며 취소하지 않으면 디렉터리를 사용할 수 있을 때까지 계속 기다립니다.
-여러 변경 작업을 동시에 처리해야 한다면 GitHub 저장소 리소스를 사용하세요. 런타임이 작업마다 별도 작업 디렉터리를 준비합니다.
+### `worktree`
+
+각 작업이 저장소의 독립된 [git 워크트리](https://git-scm.com/docs/git-worktree)를 받으며, 워크트리는 런타임 자체의 작업 공간 디렉터리 안에 생성됩니다. **같은 디렉터리에 대한 작업들이 동시에 실행되고 어느 것도 대기하지 않으며**, 어느 것도 사용자의 작업 사본에 쓰지 않습니다.
+
+이 모드는 커밋이 하나 이상 있는 git 저장소를 요구합니다. 그렇지 않으면 조용히 직렬 실행으로 되돌아가는 대신 명시적인 오류로 실패합니다. 해당 머신의 런타임도 이 모드를 구현한 버전이어야 하며, 이는 두 번 확인됩니다. 리소스를 저장할 때 너무 오래되었으면 거부되고 업그레이드 안내가 표시되며, 각 작업은 실제로 그것을 가져간 런타임을 기준으로 다시 확인됩니다 — 따라서 리소스를 저장한 뒤 다운그레이드된 머신에서는 작업이 조용히 제자리에서 실행되는 대신 이유와 함께 취소됩니다. `worktree`를 요청하는 것은 격리를 요청하는 것이며, 대신 작업 사본을 수정하는 것이 대체 동작이 되는 일은 없습니다.
+
+에이전트가 보는 것과 사용자가 받는 것:
+
+- **에이전트는 `HEAD`가 아니라 지금 보고 있는 상태에서 시작합니다.** 커밋하지 않은 수정과 추적되지 않은 파일이 워크트리로 재현되므로, 더 이상 갖고 있지 않은 코드를 검토하지 않습니다. 사용자의 작업 사본, 인덱스, stash 목록은 절대 건드리지 않습니다. 그 상태를 충실히 재현할 수 없으면 — 재현 한도(2000개 파일 / 200 MiB)를 넘는 추적되지 않은 콘텐츠가 있는 경우 포함 — 알아볼 수 없는 트리에서 시작하는 대신 작업이 실패합니다. 보통은 아직 무시되지 않은 빌드 산출물을 gitignore에 추가하거나 정리하면 해결됩니다.
+- **결과물은 저장소 안의 브랜치**이며 이름은 `agent/<agent>/<task>` 형식입니다. 실행의 **실행 세부 정보** 패널에 브랜치 이름이 표시되고 복사할 수 있으며, `git branch`로도 찾을 수 있습니다. `git log` / `git diff`로 검토한 뒤 병합할지 cherry-pick할지 직접 결정합니다. Multica가 대신 병합하지 않습니다. 도중에 실패한 실행도 브랜치를 보고합니다. 에이전트가 만든 부분은 이미 커밋되어 있기 때문입니다.
+- **조용히 사라지는 것은 없습니다.** 에이전트가 커밋하지 않고 남긴 변경 사항은 워크트리가 제거되기 전에 해당 브랜치로 커밋되며, **작업이 도중에 실패한 경우에도 마찬가지입니다.** 드물게 그 커밋 자체를 할 수 없는 경우 — 예를 들어 `commit.gpgSign`이 켜져 있고 런타임이 서명 키를 사용할 수 없는 저장소 — 워크트리는 제거되지 않고 의도적으로 유지되며, 작업은 실패로 보고되고, 저장소에서 `git worktree list`를 실행하면 해당 변경 사항이 있는 디렉터리를 확인할 수 있습니다.
+- **아무것도 변경하지 않은 작업은 아무것도 남기지 않습니다.** 해당 브랜치는 `git branch`에 빈 항목으로 남지 않고 삭제됩니다.
+
+워크트리는 런타임의 작업 공간 디렉터리 안에 있으므로 일반적인 정리 주기에 따라 회수되며, 저장소에는 브랜치만 남습니다.
+
+<Callout type="warn">
+**셀프 호스팅 운영자 주의:** 이 모드의 격리는 서버가 강제합니다(리소스 저장 시 한 번, 런타임이 각 작업을 가져갈 때 다시 한 번). 따라서 런타임을 언제 다운그레이드하더라도 차단됩니다. 유일하게 차단되지 않는 조합은 최소 버전 미만의 런타임이 연결된 상태에서 서버를 이 기능 이전 빌드로 롤백하는 것입니다 — 구버전 서버에는 이 게이트가 없고, 구버전 런타임은 `execution_mode`를 무시한 채 작업을 원본 디렉터리에서 그대로 실행합니다. `worktree` 리소스가 존재하는 동안에는 해당 머신의 런타임이 모두 최신이 아닌 한 서버를 이 릴리스 이전으로 롤백하지 마십시오.
+</Callout>
+
+<Callout type="info">
+워크트리 모드는 git 저장소를 대상으로 합니다. git으로 관리되지 않는 일반 디렉터리는 계속 직렬로 실행됩니다 — 그것이 `in_place`의 역할입니다.
+</Callout>
## 실행 중 기록되는 내용
@@ -90,6 +115,18 @@ multica project resource add <project-id> \
--local-path /absolute/path/to/repo \
--daemon-id <daemon-id>
+# 로컬 git 저장소를 연결하고 작업을 각자의 워크트리에서 동시에 실행
+multica project resource add <project-id> \
+ --type local_directory \
+ --local-path /absolute/path/to/repo \
+ --daemon-id <daemon-id> \
+ --execution-mode worktree
+
+# 기존 로컬 디렉터리의 모드 전환
+multica project resource update <project-id> <resource-id> --execution-mode worktree
+multica project resource update <project-id> <resource-id> --execution-mode in_place
+
+
# 리소스 제거
multica project resource remove <project-id> <resource-id>
```
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdx
index 08c0a1d3c6..25fcbf4259 100644
--- a/apps/docs/content/docs/project-resources.mdx
+++ b/apps/docs/content/docs/project-resources.mdx
@@ -39,7 +39,7 @@ The UI for adding a local directory is Desktop-only, because browsers cannot pic
<Callout type="warning">
**This is an escape hatch, not a more convenient default.** `local_directory` exists for people who have no other option — the canonical case is a game project whose checkout is tens of gigabytes, where re-cloning per task is simply not viable.
-If your directory is an ordinary git repo you can clone, **use `github_repo` instead**: it runs in worktree mode by default, so tasks on the same repo run with unlimited concurrency. Choosing `local_directory` means every task on that folder runs **strictly one at a time, forever**. Read "When to pick" below before you commit to it.
+If your directory is an ordinary git repo you can clone, **use `github_repo` instead**: it runs in worktree mode by default, so tasks on the same repo run with unlimited concurrency. A `local_directory` runs **one task at a time by default**; if the directory is a git repo you can opt into worktree mode to get concurrency back (see "How tasks share the directory"). Read "When to pick" below before you commit to it.
</Callout>
@@ -52,16 +52,41 @@ The directory must be an absolute path, must already exist, and must be readable
Each project can link at most one local directory per daemon. Different computers on a team can each link their own directory for the same project.
<Callout type="warning">
-A local directory is not an isolated environment. The agent directly sees and modifies your current branch and uncommitted files; Multica does not automatically switch branches, stash, commit, push, or open PRs.
+In the default `in_place` mode a local directory is not an isolated environment: the agent directly sees and modifies your current branch and uncommitted files, and Multica does not automatically switch branches, stash, commit, push, or open PRs. Worktree mode changes this — see "How tasks share the directory" below.
</Callout>
-## Local directories run serially
+## How tasks share the directory
-When two tasks use the same real directory, the later one enters `waiting_local_directory` and continues after the earlier one releases the directory. Two paths that reach the same directory through different symlinks serialize the same way.
+A local directory has two execution modes, set per resource with `execution_mode`.
+
+### `in_place` (default)
+
+The agent works directly in your directory, and tasks run one at a time. When two tasks use the same real directory, the later one enters `waiting_local_directory` and continues after the earlier one releases the directory. Two paths that reach the same directory through different symlinks serialize the same way.
Waiting does not modify the directory. A waiting task can be cancelled; otherwise it waits until the directory becomes available.
-To work on several changes at once, use a GitHub repository resource so the runtime prepares a separate working directory for each piece of work.
+### `worktree`
+
+Each task gets its own [git worktree](https://git-scm.com/docs/git-worktree) of your repo, created inside the runtime's own workspace directory. **Tasks on the same directory run concurrently — none of them wait**, and none of them write to your working copy.
+
+Requires the directory to be a git repository with at least one commit. If it is not, tasks fail with an explicit error rather than quietly falling back to serial execution. The runtime on that machine must also be new enough to implement the mode, and that is enforced twice: saving the resource is refused with an upgrade hint while the runtime is too old, and each task is checked again against the runtime that actually claims it — so a machine downgraded after the resource was saved has its tasks cancelled with a reason instead of silently running them in place. Asking for `worktree` is asking for isolation; editing your working copy instead is never the fallback.
+
+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 task 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**, named `agent/<agent>/<task>`. 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.
+- **Nothing is silently dropped.** Anything the agent leaves uncommitted is committed to that branch before the worktree is removed, including when the task 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 task is reported as failed, and `git worktree list` in your repo points at the directory holding the work.
+- **A task that changes nothing leaves nothing behind.** Its branch is deleted rather than left as an empty entry in `git branch`.
+
+Because the worktree lives in the runtime's workspace directory, it is reclaimed on the normal cleanup schedule; only the branch persists in your repo.
+
+<Callout type="warn">
+**Self-hosted operators:** isolation for this mode is enforced by the server (at save time and again when a runtime claims each task), so a runtime downgraded at any point is caught. The combination that is *not* caught is rolling the server back to a build that predates this feature while runtimes below the minimum are still connected — an old server has no gate, and an old runtime ignores `execution_mode` and would run the task in place. Do not roll the server back past this release while `worktree` resources exist unless every runtime on those machines is up to date.
+</Callout>
+
+<Callout type="info">
+Worktree mode covers git repositories. A plain non-git directory still runs serially — that is what `in_place` is for.
+</Callout>
## What gets written during a run
@@ -90,6 +115,17 @@ multica project resource add <project-id> \
--local-path /absolute/path/to/repo \
--daemon-id <daemon-id>
+# Link a local git repo and let tasks run concurrently in their own worktrees
+multica project resource add <project-id> \
+ --type local_directory \
+ --local-path /absolute/path/to/repo \
+ --daemon-id <daemon-id> \
+ --execution-mode worktree
+
+# Switch an existing local directory between modes
+multica project resource update <project-id> <resource-id> --execution-mode worktree
+multica project resource update <project-id> <resource-id> --execution-mode in_place
+
# Remove a resource
multica project resource remove <project-id> <resource-id>
```
diff --git a/apps/docs/content/docs/project-resources.zh.mdx b/apps/docs/content/docs/project-resources.zh.mdx
index 357a8f266d..9facc11b66 100644
--- a/apps/docs/content/docs/project-resources.zh.mdx
+++ b/apps/docs/content/docs/project-resources.zh.mdx
@@ -39,7 +39,7 @@ import { Callout } from "fumadocs-ui/components/callout";
<Callout type="warning">
**这是逃生舱,不是更方便的默认项。** `local_directory` 是给那些"不得不这么开发"的人准备的 —— 典型是一个 checkout 就几十 GB 的游戏项目,不可能每来一条任务就重新 clone 一份。
-如果你的目录只是一个能正常 clone 的普通 git 仓库,**请用 `github_repo`**:它默认走 worktree 模式,同一个仓库上的任务可以无限并发。选 `local_directory` 意味着这个目录上的任务从此**只能一条一条串行跑**。先看上面的两种资源对照再决定。
+如果你的目录只是一个能正常 clone 的普通 git 仓库,**请用 `github_repo`**:它默认走 worktree 模式,同一个仓库上的任务可以无限并发。`local_directory` **默认一次只跑一条任务**;如果这个目录本身是 git 仓库,可以主动开启 worktree 模式把并发拿回来(见“任务如何共享这个目录”)。先看上面的两种资源对照再决定。
</Callout>
@@ -52,16 +52,41 @@ import { Callout } from "fumadocs-ui/components/callout";
每个项目在同一台守护进程上最多关联一个本地目录。团队中的不同电脑可以分别为同一个项目关联各自的目录。
<Callout type="warning">
-本地目录不是隔离环境。智能体会直接看到并修改当前分支和未提交的文件;Multica 不会自动切换分支、stash、commit、push 或创建 PR。
+在默认的 `in_place` 模式下,本地目录不是隔离环境:智能体会直接看到并修改当前分支和未提交的文件,Multica 也不会自动切换分支、stash、commit、push 或创建 PR。worktree 模式会改变这一点 —— 见下面的“任务如何共享这个目录”。
</Callout>
-## 本地目录串行执行
+## 任务如何共享这个目录
-两条执行任务使用同一个真实目录时,后到的任务进入 `waiting_local_directory`,等前一条释放目录后继续。两个路径经不同符号链接指向同一目录时,同样串行。
+本地目录有两种执行模式,按资源逐个设置。在资源面板里可以直接切换,CLI 用 `--execution-mode`。
+
+### `in_place`(默认)
+
+智能体直接在你的目录里工作,任务一次只跑一条。两条执行任务使用同一个真实目录时,后到的任务进入 `waiting_local_directory`,等前一条释放目录后继续。两个路径经不同符号链接指向同一目录时,同样串行。
等待不会修改目录。等待中的任务可以取消,否则会一直等到目录可用。
-需要同时处理多项改动时,使用 GitHub 仓库资源,让运行时为不同工作准备各自的工作目录。
+### `worktree`
+
+每条任务拿到你仓库的一个独立 [git worktree](https://git-scm.com/docs/git-worktree),建在运行时自己的工作区目录里。**同一目录上的任务并发执行,谁都不用排队**,并且都不会写你的工作副本。
+
+要求这个目录是一个至少有一次提交的 git 仓库。如果不是,任务会明确报错,而不是悄悄退回串行。那台机器上的运行时版本也必须支持该模式,并且会检查两次:保存资源时版本过旧会被拒绝并提示升级;每条任务在被真正领取时还会再按领取它的运行时检查一次 —— 所以资源保存之后才降级的机器,其任务会被带原因取消,而不是悄悄原地跑掉。选择 `worktree` 就是在要求隔离,把它换成“直接改你的工作副本”永远不是兜底方案。
+
+智能体看到什么、你拿回什么:
+
+- **智能体从你眼前的状态开始,而不是从 `HEAD` 开始。** 你未提交的改动和未跟踪的文件会被回放进 worktree,所以它不会去 review 一份你已经不用的代码。你自己的工作副本、暂存区和 stash 列表都不会被动到。如果这个状态无法忠实还原 —— 包括未跟踪内容超出回放上限(2000 个文件 / 200 MiB)—— 任务会直接失败,而不是从一棵你认不出来的树开始。通常的解决办法是把还没被忽略的构建产物加进 gitignore 或清理掉。
+- **结果是你仓库里的一个分支**,命名为 `agent/<agent>/<task>`。执行记录的**运行详情**面板里会显示分支名(可直接复制),也可以用 `git branch` 找到它。用 `git log` / `git diff` review,然后自己决定 merge 还是 cherry-pick。Multica 不会替你合并。中途失败的任务同样会报告它的分支,因为它已经把智能体做出来的部分提交进去了。
+- **不会静默丢东西。** 智能体留下的未提交改动,会在 worktree 被移除前提交到那个分支上,**任务中途失败时同样如此**。极少数情况下连这次提交都做不了 —— 例如仓库开了 `commit.gpgSign` 而运行时拿不到签名密钥 —— worktree 会被刻意保留而不是删除,任务标记为失败,并且在你仓库里执行 `git worktree list` 就能看到存放这些改动的目录。
+- **没有产生改动的任务不留下任何东西。** 它的分支会被删除,而不是作为一个空条目留在 `git branch` 里。
+
+由于 worktree 位于运行时的工作区目录内,它会按正常的清理周期回收;只有分支会留在你的仓库里。
+
+<Callout type="warn">
+**自托管运维注意:** 该模式的隔离由服务端强制(保存资源时检查一次,运行时领取每条任务时再检查一次),所以无论何时降级运行时都会被拦住。唯一拦不住的组合是:把服务端回滚到本功能之前的版本,同时还连着低于最低版本的运行时 —— 旧服务端没有这道门禁,而旧运行时会忽略 `execution_mode`、直接在原目录里跑任务。只要还存在 `worktree` 资源,就不要把服务端回滚到本版本之前,除非那些机器上的运行时全部升级到位。
+</Callout>
+
+<Callout type="info">
+worktree 模式面向 git 仓库。普通的非 git 目录仍然串行执行 —— 这正是 `in_place` 的用途。
+</Callout>
## 执行期间写入的内容
@@ -90,6 +115,17 @@ multica project resource add <project-id> \
--local-path /absolute/path/to/repo \
--daemon-id <daemon-id>
+# 关联一个本地 git 仓库,并让任务在各自的 worktree 中并发执行
+multica project resource add <project-id> \
+ --type local_directory \
+ --local-path /absolute/path/to/repo \
+ --daemon-id <daemon-id> \
+ --execution-mode worktree
+
+# 为已有的本地目录切换模式
+multica project resource update <project-id> <resource-id> --execution-mode worktree
+multica project resource update <project-id> <resource-id> --execution-mode in_place
+
# 移除资源
multica project resource remove <project-id> <resource-id>
```
diff --git a/packages/core/runtimes/cli-version.ts b/packages/core/runtimes/cli-version.ts
index 4775b8b254..456a06d5f9 100644
--- a/packages/core/runtimes/cli-version.ts
+++ b/packages/core/runtimes/cli-version.ts
@@ -144,3 +144,27 @@ function meetsMinCliVersion(detected: string | undefined | null, minimum: string
if (!parsed) return false;
return !lessThan(parsed, parseSemver(minimum)!);
}
+
+/**
+ * Minimum daemon CLI version that implements worktree mode for
+ * `local_directory` resources (`execution_mode: "worktree"`).
+ *
+ * Server twin: `MinLocalWorktreeCLIVersion` in `server/pkg/agent/version.go`.
+ * Keep the two in lockstep — the server refuses to SAVE a worktree resource
+ * below this floor, and this constant only exists so the UI can say so before
+ * the user submits rather than surfacing a bare 422.
+ *
+ * HARD gate, unlike `handoffSupported`: a daemon below the floor does not know
+ * the field exists, so it would run the task in place — editing the working
+ * copy the user asked to isolate. Degrading to "just try it" is not an option.
+ */
+export const MIN_LOCAL_WORKTREE_CLI_VERSION = "0.4.24";
+
+/**
+ * Whether a daemon-reported CLI version can run worktree mode. Missing /
+ * unparsable / below-minimum are `false`; dev-built daemons (git-describe
+ * shape) pass, matching every other gate in this file.
+ */
+export function localWorktreeSupported(detected: string | undefined | null): boolean {
+ return meetsMinCliVersion(detected, MIN_LOCAL_WORKTREE_CLI_VERSION);
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 33339a6fd7..dbee9d3812 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -297,7 +297,14 @@ export interface AgentTask {
error: string | null;
// Empty string when the task is not in a failed state (the backend uses
// `omitempty`, so the field may also be missing on non-failed tasks).
- failure_reason?: TaskFailureReason | "";
+ // Open string on the wire, not a closed enum: the backend's classifier
+ // taxonomy has grown far past TaskFailureReason (21+ refined
+ // `agent_error.*` reasons since MUL-1949, `local_directory_error`, …) and
+ // keeps growing — an installed client will meet reasons its build
+ // predates. TaskFailureReason stays in the union for autocomplete on the
+ // coarse values; `string & {}` admits the rest without collapsing the
+ // hints.
+ failure_reason?: TaskFailureReason | (string & {}) | "";
created_at: string;
/** Non-empty when the task was spawned from a chat session. */
chat_session_id?: string;
@@ -366,6 +373,18 @@ export interface AgentTask {
* shares and screenshots also stay safe).
*/
relative_work_dir?: string;
+ /**
+ * Git branch this run delivered its work on. Set only by worktree-mode
+ * local_directory tasks, where the agent never touches the user's working
+ * copy — the branch is the only pointer to what it produced.
+ *
+ * Present on failed runs too: worktree mode commits whatever the agent left
+ * before tearing the worktree down, so a run that died partway still has
+ * something worth finding. Unlike `work_dir` this is safe to render
+ * verbatim; it is a ref inside the user's own repo, not a filesystem path.
+ * Older backends omit it — render conditionally.
+ */
+ branch_name?: string;
/**
* Resolved accountable-human provenance of this run (MUL-4302 §9): who it ran
* "on behalf of", how that was resolved, and the evidence/lineage. Present on
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 0b9608f410..1ee4f019ac 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -146,6 +146,7 @@ export type {
ProjectResourceRef,
GithubRepoResourceRef,
LocalDirectoryResourceRef,
+ LocalDirectoryExecutionMode,
CreateProjectResourceRequest,
UpdateProjectResourceRequest,
ListProjectResourcesResponse,
diff --git a/packages/core/types/project.ts b/packages/core/types/project.ts
index d47f678e9f..ad2ca3d335 100644
--- a/packages/core/types/project.ts
+++ b/packages/core/types/project.ts
@@ -62,8 +62,8 @@ export interface ListProjectsResponse {
//
// Known types (UI must default-case unknown server-side additions):
// - github_repo: cloud-side git checkout, ref = { url, ref?, default_branch_hint? }
-// - local_directory: in-place agent execution on a specific daemon,
-// ref = { local_path, daemon_id, label? }
+// - local_directory: agent execution on a specific daemon,
+// ref = { local_path, daemon_id, label?, execution_mode? }
export type ProjectResourceType = "github_repo" | "local_directory";
export interface GithubRepoResourceRef {
@@ -72,10 +72,26 @@ export interface GithubRepoResourceRef {
default_branch_hint?: string;
}
+/**
+ * How tasks sharing one local directory are executed.
+ *
+ * - `in_place`: the agent works directly in the user's directory and tasks run
+ * one at a time — a second task waits in `waiting_local_directory`. Edits
+ * land in the user's working copy.
+ * - `worktree`: each task gets its own git worktree of that repo inside the
+ * runtime's workspace, so tasks run concurrently and deliver their work as an
+ * `agent/<agent>/<task>` branch instead of touching the working copy.
+ *
+ * Absent means `in_place`: resources created before the mode existed keep their
+ * original behavior, so this is optional rather than defaulted on the server.
+ */
+export type LocalDirectoryExecutionMode = "in_place" | "worktree";
+
export interface LocalDirectoryResourceRef {
local_path: string;
daemon_id: string;
label?: string;
+ execution_mode?: LocalDirectoryExecutionMode;
}
export type ProjectResourceRef =
diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsx
index e1cece70c3..e4f415d26a 100644
--- a/packages/views/agents/components/tabs/activity-tab.tsx
+++ b/packages/views/agents/components/tabs/activity-tab.tsx
@@ -35,7 +35,7 @@ import { AppLink } from "../../../navigation";
import { TranscriptButton } from "../../../common/task-transcript";
import { AttributionBadge } from "../../../issues/components/attribution-badge";
import { taskStatusConfig } from "../../config";
-import { failureReasonLabel } from "./task-failure";
+import { cancelReasonLabel, failureReasonLabel } from "./task-failure";
import { Sparkline } from "../sparkline";
import { useT, useTimeAgo } from "../../../i18n";
@@ -586,9 +586,14 @@ function TaskRow({
// Failure reason. The back-end emits "" on non-failed tasks (omitempty
// strips it on the wire) so the truthy guard is the right shape.
// failureReasonLabel takes the raw open string — the taxonomy has 21
- // values and grows, so there is no enum to cast to.
+ // values and grows, so there is no enum to cast to. Cancelled rows get a
+ // label only when the SERVER cancelled them for a persisted reason
+ // (worktree claim gate, preserved-work delivery); a user's own cancel
+ // stays a plain "Cancelled".
const failureLabel =
- task.status === "failed" ? failureReasonLabel(task.failure_reason) : null;
+ task.status === "failed"
+ ? failureReasonLabel(task.failure_reason)
+ : cancelReasonLabel(task);
// Only show duration for terminal rows. An active row's duration is
// inferred from the timeText already ("Started 2m ago") and adding a
@@ -677,7 +682,11 @@ function TaskRow({
{failureLabel && (
<>
<Sep />
- <span className="text-destructive">{failureLabel}</span>
+ {/* Hover reveals the actionable text ("upgrade the daemon on
+ that machine", "work preserved at …"), not just the bucket. */}
+ <span className="text-destructive" title={task.error ?? undefined}>
+ {failureLabel}
+ </span>
</>
)}
{/* Accountable member (MUL-4302 §9): whose behalf this run is on.
diff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.ts
index ac8099ec52..0710d14b9c 100644
--- a/packages/views/agents/components/tabs/task-failure.test.ts
+++ b/packages/views/agents/components/tabs/task-failure.test.ts
@@ -1,44 +1,49 @@
import { describe, expect, it } from "vitest";
-import { failureReasonLabel } from "./task-failure";
+import { cancelReasonLabel, failureReasonLabel } from "./task-failure";
-// This is the copy the Usage page's Errors breakdown drills into: a top
-// offender is only actionable if the runs it links to actually say why they
-// failed.
-describe("failureReasonLabel", () => {
- it("labels the refined agent_error.* reasons the backend has written since MUL-1949", () => {
- // Regression: this used to be a Record indexed with a cast to the old
- // 6-value coarse enum, so every one of these resolved to `undefined` and
- // the row rendered no reason at all.
- expect(failureReasonLabel("agent_error.provider_auth_or_access")).toBe(
- "Provider auth failed",
- );
- expect(failureReasonLabel("agent_error.provider_capacity_or_rate_limit")).toBe(
- "Rate limited by provider",
- );
- expect(failureReasonLabel("agent_error.context_overflow")).toBe(
- "Context window exceeded",
- );
- expect(failureReasonLabel("queued_expired")).toBe("Expired in queue");
+// cancelReasonLabel decides which cancelled rows explain themselves. The rule
+// it must hold: a SERVER-cancelled row (persisted reason) reads like a failed
+// row, a user's own cancel stays a plain "Cancelled" — labelling every cancel
+// would bury the rows that actually need the user to act.
+describe("cancelReasonLabel", () => {
+ it("returns null for a user-initiated cancel", () => {
+ expect(cancelReasonLabel({ status: "cancelled", error: null, failure_reason: null })).toBeNull();
+ });
+
+ it("only ever labels cancelled rows — failed rows have their own path", () => {
+ expect(
+ cancelReasonLabel({ status: "failed", error: "boom", failure_reason: "timeout" }),
+ ).toBeNull();
});
- it("still labels the pre-MUL-1949 coarse reasons on historical rows", () => {
- expect(failureReasonLabel("agent_error")).toBe("Agent execution error");
- expect(failureReasonLabel("runtime_offline")).toBe("Daemon offline");
- expect(failureReasonLabel("manual")).toBe("Cancelled by user");
+ it("labels the worktree claim gate's cancellation", () => {
+ expect(
+ cancelReasonLabel({
+ status: "cancelled",
+ error: "worktree mode needs daemon version 0.4.24 or newer",
+ failure_reason: "local_directory_error",
+ }),
+ ).toBe("Local directory error");
});
- it("falls back to the raw wire value for a reason this build predates", () => {
- // Truthful and searchable beats blank — the operator can paste it into a
- // log search.
- expect(failureReasonLabel("agent_error.from_a_newer_backend")).toBe(
- "agent_error.from_a_newer_backend",
- );
+ it("falls back to a generic system label when only error text was persisted", () => {
+ expect(
+ cancelReasonLabel({
+ status: "cancelled",
+ error: "work preserved in the worktree at /env/worktree",
+ failure_reason: null,
+ }),
+ ).toBe("Cancelled by the system");
+ });
+});
+
+describe("failureReasonLabel", () => {
+ it("covers the local_directory bucket the worktree paths write", () => {
+ expect(failureReasonLabel("local_directory_error")).toBe("Local directory error");
});
- it("returns null when there is no reason to show", () => {
- expect(failureReasonLabel("")).toBeNull();
- expect(failureReasonLabel(null)).toBeNull();
- expect(failureReasonLabel(undefined)).toBeNull();
+ it("still falls back to the raw wire value for unknown reasons", () => {
+ expect(failureReasonLabel("brand_new_reason")).toBe("brand_new_reason");
});
});
diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.ts
index 6d3850a045..ef349f8767 100644
--- a/packages/views/agents/components/tabs/task-failure.ts
+++ b/packages/views/agents/components/tabs/task-failure.ts
@@ -45,6 +45,7 @@ const REASON_LABEL: Record<string, string> = {
// Provider-specific operational reasons, outside the canonical taxonomy.
codex_resume_oversized: "Session too large to resume",
+ local_directory_error: "Local directory error",
// Pre-MUL-1949 coarse values, still present on historical rows.
agent_error: "Agent execution error",
@@ -67,3 +68,24 @@ export function failureReasonLabel(
if (!reason) return null;
return REASON_LABEL[reason] ?? reason;
}
+
+/**
+ * Label for a cancelled task the SERVER cancelled for a persisted reason —
+ * the worktree claim gate refusing a too-old daemon, or a cancel-ack carrying
+ * a preserved-work error. Those are conditions only the user can fix, so the
+ * row must explain itself like a failed row does.
+ *
+ * Returns `null` for a user-initiated cancel (no persisted reason): the user
+ * knows why they clicked, and stamping a label on every ordinary cancel would
+ * bury the rows that actually need attention.
+ */
+export function cancelReasonLabel(task: {
+ status: string;
+ error?: string | null;
+ failure_reason?: string | null;
+}): string | null {
+ if (task.status !== "cancelled") return null;
+ const reason = failureReasonLabel(task.failure_reason);
+ if (reason) return reason;
+ return task.error ? "Cancelled by the system" : null;
+}
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index 76cedb3ab6..0e28709c2e 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -609,3 +609,63 @@ describe("AgentTranscriptDialog", () => {
expect(await screen.findByText(expected)).toBeInTheDocument();
});
});
+
+// A worktree-mode run never touches the user's working copy: the branch is the
+// only pointer to what it produced. Showing it in Run details is what makes the
+// result findable — including for a run that failed partway, which still
+// commits whatever the agent had done.
+describe("AgentTranscriptDialog — delivered branch", () => {
+ it("shows the branch and copies it", async () => {
+ renderDialog(items, {
+ task: { ...baseTask, branch_name: "agent/j/abc12345" },
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: "Run details" }));
+
+ expect(screen.getByText("agent/j/abc12345")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByTitle("Copy branch name"));
+ expect(copyTextMock).toHaveBeenCalledWith("agent/j/abc12345");
+ });
+
+ it("renders nothing for tasks that delivered no branch", async () => {
+ renderDialog(items, { task: { ...baseTask, branch_name: undefined } });
+
+ await userEvent.click(screen.getByRole("button", { name: "Run details" }));
+
+ expect(screen.queryByTitle("Copy branch name")).not.toBeInTheDocument();
+ });
+});
+
+// A server-cancelled run (worktree claim gate, preserved-work delivery) must
+// explain itself: the reason rides the status badge and the full persisted
+// error is readable in Run details. A user's own cancel stays a plain
+// "Cancelled" — they know why they clicked.
+describe("AgentTranscriptDialog — cancel reason", () => {
+ const gateError = "worktree mode needs daemon version 0.4.24 or newer on that machine";
+
+ it("labels a server-cancelled run and surfaces the persisted reason", async () => {
+ renderDialog(items, {
+ task: {
+ ...baseTask,
+ status: "cancelled",
+ error: gateError,
+ failure_reason: "local_directory_error",
+ },
+ });
+
+ expect(screen.getByText(/Local directory error/)).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Run details" }));
+ expect(screen.getByText(gateError)).toBeInTheDocument();
+ });
+
+ it("keeps a user-initiated cancel a plain Cancelled", () => {
+ renderDialog(items, {
+ task: { ...baseTask, status: "cancelled", error: null },
+ });
+
+ expect(screen.getByText("Cancelled")).toBeInTheDocument();
+ expect(screen.queryByText(/Local directory error/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index deb192d374..e5fc157f38 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -39,6 +39,7 @@ import {
} from "@multica/ui/components/ui/dropdown-menu";
import { ActorAvatar } from "../actor-avatar";
import { AttributionBadge } from "../../issues/components/attribution-badge";
+import { cancelReasonLabel } from "../../agents/components/tabs/task-failure";
import { RichContent } from "../../rich-content";
import { api } from "@multica/core/api";
import {
@@ -233,6 +234,7 @@ export function AgentTranscriptDialog({
const [elapsed, setElapsed] = useState("");
const [copied, setCopied] = useState(false);
const [copiedWorkdir, setCopiedWorkdir] = useState(false);
+ const [copiedBranch, setCopiedBranch] = useState(false);
const [agentInfo, setAgentInfo] = useState<Agent | null>(null);
const [runtimeInfo, setRuntimeInfo] = useState<AgentRuntime | null>(null);
// Row-level expand overrides. A row the user toggled follows the toggle; any
@@ -491,6 +493,17 @@ export function AgentTranscriptDialog({
});
}, [task.relative_work_dir]);
+ // Worktree-mode runs deliver a branch instead of edits in the working copy,
+ // so copying the name is the fastest path to `git diff <branch>`.
+ const handleCopyBranch = useCallback(() => {
+ if (!task.branch_name) return;
+ void copyText(task.branch_name).then((ok) => {
+ if (!ok) return;
+ setCopiedBranch(true);
+ setTimeout(() => setCopiedBranch(false), 2000);
+ });
+ }, [task.branch_name]);
+
const handleCopyAll = useCallback(() => {
// Copy the full body of each event (not the truncated row summary), with
// the same secret redaction the detail view applies.
@@ -554,13 +567,21 @@ export function AgentTranscriptDialog({
{t(($) => $.transcript.status_failed)}
</span>
);
- case "cancelled":
+ case "cancelled": {
+ // A server-cancelled run (worktree claim gate, preserved-work
+ // delivery) carries a persisted reason the user must act on; surface
+ // it on the badge instead of a bare "Cancelled". User-initiated
+ // cancels have no reason and keep the plain label.
+ const cancelReason = cancelReasonLabel(task);
return (
- <span className={cn(base, "bg-muted text-muted-foreground")}>
+ <span className={cn(base, "bg-muted text-muted-foreground")} title={task.error ?? undefined}>
<XCircle className="h-3 w-3" />
- {t(($) => $.transcript.status_cancelled)}
+ {cancelReason
+ ? `${t(($) => $.transcript.status_cancelled)} · ${cancelReason}`
+ : t(($) => $.transcript.status_cancelled)}
</span>
);
+ }
case "queued":
return (
<span className={cn(base, "bg-muted text-muted-foreground")}>
@@ -633,6 +654,8 @@ export function AgentTranscriptDialog({
const hasRunDetails =
!!runtimeInfo ||
!!task.relative_work_dir ||
+ !!task.branch_name ||
+ !!task.error ||
!!createdLabel ||
!!startedLabel ||
!!completedLabel ||
@@ -745,6 +768,26 @@ export function AgentTranscriptDialog({
copyTitle={t(($) => $.transcript.copy_workdir)}
/>
)}
+ {task.branch_name && (
+ <RunDetailRow
+ label={t(($) => $.transcript.details_branch)}
+ value={task.branch_name}
+ mono
+ onCopy={handleCopyBranch}
+ copied={copiedBranch}
+ copyTitle={t(($) => $.transcript.copy_branch)}
+ />
+ )}
+ {/* The full persisted error, for failed AND
+ server-cancelled runs — this is where "which
+ worktree holds my preserved work" and "which
+ machine needs upgrading" are actually readable. */}
+ {task.error && (
+ <RunDetailRow
+ label={t(($) => $.transcript.details_reason)}
+ value={task.error}
+ />
+ )}
{createdLabel && (
<RunDetailRow label={t(($) => $.transcript.details_created)} value={createdLabel} />
)}
diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsx
index 7d626b5dc2..4a29249b28 100644
--- a/packages/views/issues/components/execution-log-section.tsx
+++ b/packages/views/issues/components/execution-log-section.tsx
@@ -17,7 +17,7 @@ import {
import { ActorAvatar } from "../../common/actor-avatar";
import { formatDuration } from "../../agents/components/agent-activity-hover-content";
import { TranscriptButton } from "../../common/task-transcript";
-import { failureReasonLabel } from "../../agents/components/tabs/task-failure";
+import { cancelReasonLabel, failureReasonLabel } from "../../agents/components/tabs/task-failure";
import { useT } from "../../i18n";
import {
formatTokens,
@@ -432,8 +432,17 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
const label = useStatusLabel(task.status);
const trigger = useTriggerText(task);
const time = task.completed_at ? timeAgo(task.completed_at) : "—";
+ // A failed run always explains itself. A cancelled one only when the SERVER
+ // cancelled it for a persisted reason (worktree claim gate, preserved-work
+ // delivery) — a user-initiated cancel stays a plain "Cancelled".
const failureLabel =
- task.status === "failed" ? failureReasonLabel(task.failure_reason) : null;
+ task.status === "failed"
+ ? failureReasonLabel(task.failure_reason)
+ : cancelReasonLabel(task);
+ // Hovering the status mark reveals the actionable text ("upgrade the daemon
+ // on that machine", "work preserved at …"), not just the reason bucket.
+ const statusTitle =
+ failureLabel && task.error ? `${failureLabel}: ${task.error}` : (failureLabel ?? label);
// What this run cost, in the slot the relative timestamp used to hold.
//
@@ -493,7 +502,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {
<RowShell task={task} title={rowTitle}>
<TriggerText text={trigger} />
<TaskCommentCoverage task={task} />
- <RowStatus title={failureLabel ?? label}>
+ <RowStatus title={statusTitle}>
<TaskStatusIcon status={task.status} />
<span className="sr-only">
{[failureLabel ?? label, time].filter(Boolean).join(" · ")}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index fe6b2ad718..d7653c4035 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -838,7 +838,10 @@
"details_cache_read": "Cache read",
"details_cache_write": "Cache write",
"details_cost": "Cost",
- "usage_chip_title": "Tokens and estimated cost for this run"
+ "usage_chip_title": "Tokens and estimated cost for this run",
+ "details_branch": "Branch",
+ "details_reason": "Reason",
+ "copy_branch": "Copy branch name"
},
"task_failure": {
"agent_error": "Agent execution error",
diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.json
index 2d9ba1f18b..1c6225bf8e 100644
--- a/packages/views/locales/en/projects.json
+++ b/packages/views/locales/en/projects.json
@@ -117,7 +117,24 @@
"local_validate_not_a_directory": "Path is not a directory.",
"local_validate_not_readable": "Directory is not readable.",
"local_validate_not_writable": "Directory is not writable.",
- "local_validate_unsupported": "Local directories can only be picked on the desktop app."
+ "local_validate_unsupported": "Local directories can only be picked on the desktop app.",
+ "mode_dialog_title": "How should tasks use this folder?",
+ "mode_dialog_description": "This decides how you get an agent's work back, and whether tasks on this folder can run at the same time.",
+ "mode_in_place_title": "Edit this folder directly",
+ "mode_in_place_description": "One task at a time. Changes appear in your working copy as the agent makes them, ready for you to keep working on.",
+ "mode_worktree_title": "Run in parallel, isolated",
+ "mode_worktree_description": "Tasks run at the same time without touching your working copy. Each one hands back an agent/… branch in this repo for you to review and merge.",
+ "mode_worktree_needs_git": "This folder is not a git repository, so there is nowhere to put the branch. Pick a repository, or keep editing the folder directly.",
+ "mode_worktree_needs_upgrade": "The Multica app on the machine this folder lives on is {{current}}; running tasks in parallel needs {{min}} or newer. Update it there, then switch this on.",
+ "mode_version_unknown": "an older version",
+ "mode_cancel": "Cancel",
+ "mode_save": "Save",
+ "mode_add": "Add folder",
+ "mode_edit_tooltip": "Change how tasks use this folder",
+ "mode_badge_worktree": "Parallel",
+ "mode_badge_worktree_tooltip": "Tasks run at the same time in their own git worktree and hand back a branch. Your working copy is untouched.",
+ "toast_local_mode_updated": "Execution mode updated",
+ "toast_local_mode_update_failed": "Could not update the execution mode"
},
"delete_dialog": {
"title": "Delete project",
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 1c8a971144..a9330cb251 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -716,7 +716,10 @@
"details_cache_read": "キャッシュ読み取り",
"details_cache_write": "キャッシュ書き込み",
"details_cost": "費用",
- "usage_chip_title": "この実行のトークンと推定費用"
+ "usage_chip_title": "この実行のトークンと推定費用",
+ "details_branch": "ブランチ",
+ "details_reason": "理由",
+ "copy_branch": "ブランチ名をコピー"
},
"task_failure": {
"agent_error": "エージェント実行エラー",
diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.json
index a467e03ab3..e60f19c46b 100644
--- a/packages/views/locales/ja/projects.json
+++ b/packages/views/locales/ja/projects.json
@@ -116,7 +116,24 @@
"local_validate_not_a_directory": "パスはディレクトリではありません。",
"local_validate_not_readable": "ディレクトリを読み取れません。",
"local_validate_not_writable": "ディレクトリに書き込めません。",
- "local_validate_unsupported": "ローカルディレクトリはデスクトップアプリでのみ選択できます。"
+ "local_validate_unsupported": "ローカルディレクトリはデスクトップアプリでのみ選択できます。",
+ "mode_dialog_title": "タスクはこのフォルダをどう使いますか?",
+ "mode_dialog_description": "エージェントの成果物を受け取る方法と、このフォルダのタスクを同時に実行できるかが決まります。",
+ "mode_in_place_title": "このフォルダを直接編集する",
+ "mode_in_place_description": "タスクは一度に1つずつ。エージェントの変更はそのまま作業コピーに現れ、続けて作業できます。",
+ "mode_worktree_title": "隔離して並行実行する",
+ "mode_worktree_description": "タスクは作業コピーに触れずに同時実行されます。それぞれがこのリポジトリの agent/… ブランチを返すので、レビューしてマージします。",
+ "mode_worktree_needs_git": "このフォルダは git リポジトリではないため、ブランチを作成できません。リポジトリを選ぶか、フォルダを直接編集してください。",
+ "mode_worktree_needs_upgrade": "このフォルダがあるマシンの Multica は {{current}} です。並行実行には {{min}} 以降が必要です。そのマシンで更新してから有効にしてください。",
+ "mode_version_unknown": "古いバージョン",
+ "mode_cancel": "キャンセル",
+ "mode_save": "保存",
+ "mode_add": "フォルダを追加",
+ "mode_edit_tooltip": "タスクがこのフォルダを使う方法を変更",
+ "mode_badge_worktree": "並行",
+ "mode_badge_worktree_tooltip": "タスクはそれぞれの git ワークツリーで同時に実行され、ブランチとして成果を返します。作業コピーは変更されません。",
+ "toast_local_mode_updated": "実行モードを更新しました",
+ "toast_local_mode_update_failed": "実行モードを更新できませんでした"
},
"delete_dialog": {
"title": "プロジェクトを削除",
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index c83ffb79cd..440917f00b 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -724,7 +724,10 @@
"details_cache_read": "캐시 읽기",
"details_cache_write": "캐시 쓰기",
"details_cost": "비용",
- "usage_chip_title": "이 실행의 토큰 및 예상 비용"
+ "usage_chip_title": "이 실행의 토큰 및 예상 비용",
+ "details_branch": "브랜치",
+ "details_reason": "사유",
+ "copy_branch": "브랜치 이름 복사"
},
"task_failure": {
"agent_error": "에이전트 실행 오류",
diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.json
index cef18e0fc7..11f53f131d 100644
--- a/packages/views/locales/ko/projects.json
+++ b/packages/views/locales/ko/projects.json
@@ -116,7 +116,24 @@
"local_validate_not_a_directory": "디렉터리가 아닙니다.",
"local_validate_not_readable": "디렉터리를 읽을 수 없습니다.",
"local_validate_not_writable": "디렉터리에 쓸 수 없습니다.",
- "local_validate_unsupported": "로컬 디렉터리는 데스크톱 앱에서만 선택할 수 있습니다."
+ "local_validate_unsupported": "로컬 디렉터리는 데스크톱 앱에서만 선택할 수 있습니다.",
+ "mode_dialog_title": "작업이 이 폴더를 어떻게 사용할까요?",
+ "mode_dialog_description": "에이전트의 결과물을 받는 방식과, 이 폴더의 작업을 동시에 실행할 수 있는지가 정해집니다.",
+ "mode_in_place_title": "이 폴더를 직접 수정",
+ "mode_in_place_description": "한 번에 하나의 작업만 실행됩니다. 에이전트의 변경 사항이 작업 사본에 바로 나타나므로 이어서 작업할 수 있습니다.",
+ "mode_worktree_title": "격리해서 병렬 실행",
+ "mode_worktree_description": "작업이 작업 사본을 건드리지 않고 동시에 실행됩니다. 각 작업은 이 저장소의 agent/… 브랜치를 돌려주며, 검토 후 병합하면 됩니다.",
+ "mode_worktree_needs_git": "이 폴더는 git 저장소가 아니어서 브랜치를 만들 수 없습니다. 저장소를 선택하거나 폴더를 직접 수정하세요.",
+ "mode_worktree_needs_upgrade": "이 폴더가 있는 컴퓨터의 Multica는 {{current}}입니다. 병렬 실행에는 {{min}} 이상이 필요합니다. 해당 컴퓨터에서 업데이트한 뒤 켜세요.",
+ "mode_version_unknown": "이전 버전",
+ "mode_cancel": "취소",
+ "mode_save": "저장",
+ "mode_add": "폴더 추가",
+ "mode_edit_tooltip": "작업이 이 폴더를 사용하는 방식 변경",
+ "mode_badge_worktree": "병렬",
+ "mode_badge_worktree_tooltip": "작업이 각자의 git 워크트리에서 동시에 실행되고 브랜치로 결과를 돌려줍니다. 작업 사본은 변경되지 않습니다.",
+ "toast_local_mode_updated": "실행 모드를 업데이트했습니다",
+ "toast_local_mode_update_failed": "실행 모드를 업데이트하지 못했습니다"
},
"delete_dialog": {
"title": "프로젝트 삭제",
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 425c8924d6..4e150ae17f 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -823,7 +823,10 @@
"details_cache_read": "缓存读",
"details_cache_write": "缓存写",
"details_cost": "费用",
- "usage_chip_title": "这次运行消耗的 token 与估算费用"
+ "usage_chip_title": "这次运行消耗的 token 与估算费用",
+ "details_branch": "分支",
+ "details_reason": "原因",
+ "copy_branch": "复制分支名"
},
"task_failure": {
"agent_error": "智能体执行出错",
diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.json
index 3a6318741e..88edbe63a5 100644
--- a/packages/views/locales/zh-Hans/projects.json
+++ b/packages/views/locales/zh-Hans/projects.json
@@ -116,7 +116,24 @@
"local_validate_not_a_directory": "该路径不是目录。",
"local_validate_not_readable": "目录不可读。",
"local_validate_not_writable": "目录不可写。",
- "local_validate_unsupported": "本地目录仅能在桌面端选择。"
+ "local_validate_unsupported": "本地目录仅能在桌面端选择。",
+ "mode_dialog_title": "任务如何使用这个文件夹?",
+ "mode_dialog_description": "这决定了你如何拿到智能体的工作成果,以及这个文件夹上的任务能否同时运行。",
+ "mode_in_place_title": "直接修改这个文件夹",
+ "mode_in_place_description": "一次只跑一条任务。智能体的改动会直接出现在你的工作区里,你可以接着改。",
+ "mode_worktree_title": "并行隔离运行",
+ "mode_worktree_description": "任务可以同时跑,互不干扰,也不碰你的工作区。每条任务的结果是这个仓库里的一个 agent/… 分支,由你 review 后合并。",
+ "mode_worktree_needs_git": "这个文件夹不是 git 仓库,分支无处可放。请选择一个仓库,或者继续直接修改这个文件夹。",
+ "mode_worktree_needs_upgrade": "这个文件夹所在机器上的 Multica 是 {{current}},并行运行需要 {{min}} 或更新的版本。在那台机器上升级后即可开启。",
+ "mode_version_unknown": "较旧的版本",
+ "mode_cancel": "取消",
+ "mode_save": "保存",
+ "mode_add": "添加文件夹",
+ "mode_edit_tooltip": "修改任务使用这个文件夹的方式",
+ "mode_badge_worktree": "并行",
+ "mode_badge_worktree_tooltip": "任务在各自的 git worktree 中同时运行,并以分支形式交付结果。你的工作区不会被改动。",
+ "toast_local_mode_updated": "已更新执行方式",
+ "toast_local_mode_update_failed": "无法更新执行方式"
},
"delete_dialog": {
"title": "删除项目",
diff --git a/packages/views/platform/local-directory.ts b/packages/views/platform/local-directory.ts
index fb119901a8..cc1252edf6 100644
--- a/packages/views/platform/local-directory.ts
+++ b/packages/views/platform/local-directory.ts
@@ -23,6 +23,12 @@ export type ValidateLocalDirectoryResult = {
| "error"
| "unsupported";
error?: string;
+ /**
+ * Whether the directory sits inside a git working tree. Only meaningful when
+ * ok=true; absent from an older desktop build, which is why callers must
+ * treat `undefined` as "unknown" rather than "not a repo".
+ */
+ is_git_repo?: boolean;
};
interface DesktopLocalDirectoryAPI {
diff --git a/packages/views/projects/components/local-directory-mode-dialog.test.tsx b/packages/views/projects/components/local-directory-mode-dialog.test.tsx
new file mode 100644
index 0000000000..4bd64346a0
--- /dev/null
+++ b/packages/views/projects/components/local-directory-mode-dialog.test.tsx
@@ -0,0 +1,115 @@
+// @vitest-environment jsdom
+
+import { describe, it, expect, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { I18nProvider } from "@multica/core/i18n/react";
+import type { LocalDirectoryExecutionMode } from "@multica/core/types";
+import enProjects from "../../locales/en/projects.json";
+import enCommon from "../../locales/en/common.json";
+import { LocalDirectoryModeDialog } from "./local-directory-mode-dialog";
+import type { WorktreeUnavailableReason } from "./local-directory-mode-dialog";
+
+const TEST_RESOURCES = { en: { projects: enProjects, common: enCommon } };
+
+function renderDialog(
+ overrides: {
+ value?: LocalDirectoryExecutionMode;
+ unavailableReason?: WorktreeUnavailableReason;
+ currentVersion?: string;
+ errorMessage?: string;
+ onConfirm?: (mode: LocalDirectoryExecutionMode) => void;
+ } = {},
+) {
+ const onConfirm = overrides.onConfirm ?? vi.fn();
+ render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <LocalDirectoryModeDialog
+ open
+ onOpenChange={() => {}}
+ path="/Users/dev/work/game-client"
+ value={overrides.value ?? "in_place"}
+ unavailableReason={overrides.unavailableReason}
+ currentVersion={overrides.currentVersion}
+ minVersion="0.4.24"
+ errorMessage={overrides.errorMessage}
+ confirmLabel="Save"
+ onConfirm={onConfirm}
+ />
+ </I18nProvider>,
+ );
+ return { onConfirm };
+}
+
+function worktreeOption(): HTMLElement {
+ return screen.getAllByRole("radio")[1] as HTMLElement;
+}
+
+describe("LocalDirectoryModeDialog", () => {
+ it("leads with what the user gets back, not the mode identifiers", () => {
+ renderDialog();
+ // The identifiers stay visible as a secondary hint for anyone cross-
+ // referencing the CLI or docs, but the decision is framed by outcome.
+ expect(screen.getByText("Edit this folder directly")).toBeTruthy();
+ expect(screen.getByText("Run in parallel, isolated")).toBeTruthy();
+ expect(screen.getByText("in_place")).toBeTruthy();
+ expect(screen.getByText("worktree")).toBeTruthy();
+ expect(screen.getByText("/Users/dev/work/game-client")).toBeTruthy();
+ });
+
+ it("marks the current mode as selected", () => {
+ renderDialog({ value: "worktree" });
+ expect(worktreeOption().getAttribute("aria-checked")).toBe("true");
+ expect(screen.getAllByRole("radio")[0]?.getAttribute("aria-checked")).toBe(
+ "false",
+ );
+ });
+
+ it("confirms the newly picked mode, not the one it opened with", () => {
+ const onConfirm = vi.fn();
+ renderDialog({ value: "in_place", onConfirm });
+
+ fireEvent.click(worktreeOption());
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(onConfirm).toHaveBeenCalledWith("worktree");
+ });
+
+ // A non-git folder cannot produce a branch, so offering the option would
+ // guarantee the user's first task fails. Disable it where they choose.
+ it("disables parallel mode for a non-git folder and says why", () => {
+ const onConfirm = vi.fn();
+ renderDialog({ unavailableReason: "not_git", onConfirm });
+
+ const option = worktreeOption();
+ expect(option.hasAttribute("disabled")).toBe(true);
+ expect(screen.getByText(/not a git repository/i)).toBeTruthy();
+
+ fireEvent.click(option);
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ // Still the mode it opened with — the disabled option cannot be selected.
+ expect(onConfirm).toHaveBeenCalledWith("in_place");
+ });
+
+ // The server refuses the save below the version floor; saying so up front
+ // beats a bare 422 after the user has already committed to the choice.
+ it("disables parallel mode for an outdated daemon and names both versions", () => {
+ renderDialog({
+ unavailableReason: "daemon_outdated",
+ currentVersion: "0.4.10",
+ });
+
+ expect(worktreeOption().hasAttribute("disabled")).toBe(true);
+ const notice = screen.getByText(/0\.4\.10/);
+ expect(notice.textContent).toContain("0.4.24");
+ });
+
+ it("falls back to a readable phrase when the daemon reports no version", () => {
+ renderDialog({ unavailableReason: "daemon_outdated", currentVersion: "" });
+ expect(screen.getByText(/an older version/i)).toBeTruthy();
+ });
+
+ it("shows a server rejection inline so the dialog stays actionable", () => {
+ renderDialog({ errorMessage: "daemon is too old to run worktree mode" });
+ expect(screen.getByText(/too old to run worktree mode/i)).toBeTruthy();
+ });
+});
diff --git a/packages/views/projects/components/local-directory-mode-dialog.tsx b/packages/views/projects/components/local-directory-mode-dialog.tsx
new file mode 100644
index 0000000000..89cadef1f0
--- /dev/null
+++ b/packages/views/projects/components/local-directory-mode-dialog.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { GitBranch, Pencil, TriangleAlert } from "lucide-react";
+import type { LocalDirectoryExecutionMode } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { useT } from "../../i18n/use-t";
+
+/**
+ * Why the worktree option may be unavailable. The two cases need different
+ * copy and different remedies, so they are distinct rather than one boolean:
+ * `not_git` is fixed by choosing a different folder, `daemon_outdated` by
+ * updating the app on that machine.
+ *
+ * `undefined` means available.
+ */
+export type WorktreeUnavailableReason = "not_git" | "daemon_outdated";
+
+interface LocalDirectoryModeDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Absolute path being configured, shown so the user knows what they picked. */
+ path: string;
+ /** Mode to preselect — the current mode when editing, in_place when adding. */
+ value: LocalDirectoryExecutionMode;
+ /** Set when worktree cannot be chosen; the option renders disabled with a reason. */
+ unavailableReason?: WorktreeUnavailableReason;
+ /** Daemon version strings for the outdated message. */
+ currentVersion?: string;
+ minVersion?: string;
+ /** Server-side rejection to show inline (e.g. a 422 that only the API can detect). */
+ errorMessage?: string;
+ saving?: boolean;
+ /** Confirm label differs between adding a resource and editing one. */
+ confirmLabel: string;
+ onConfirm: (mode: LocalDirectoryExecutionMode) => void;
+}
+
+/**
+ * Mode picker for a local_directory resource.
+ *
+ * Deliberately does NOT surface the raw `in_place` / `worktree` identifiers as
+ * the primary label. The choice a user is actually making is about how they get
+ * their results back — edits appearing in their working copy versus a branch
+ * they review — so the options lead with that, and the identifier is only a
+ * secondary hint for anyone matching this against the CLI or the docs.
+ */
+export function LocalDirectoryModeDialog({
+ open,
+ onOpenChange,
+ path,
+ value,
+ unavailableReason,
+ currentVersion,
+ minVersion,
+ errorMessage,
+ saving = false,
+ confirmLabel,
+ onConfirm,
+}: LocalDirectoryModeDialogProps) {
+ const { t } = useT("projects");
+ const [selected, setSelected] = useState<LocalDirectoryExecutionMode>(value);
+
+ // Re-sync when the dialog is reopened for a different resource, otherwise the
+ // previous row's mode would be preselected for this one.
+ useEffect(() => {
+ if (open) setSelected(value);
+ }, [open, value]);
+
+ const worktreeDisabled = unavailableReason !== undefined;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.resources.mode_dialog_title)}</DialogTitle>
+ <DialogDescription>
+ {t(($) => $.resources.mode_dialog_description)}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="rounded-md bg-muted px-2.5 py-1.5 font-mono text-micro text-muted-foreground break-all">
+ {path}
+ </div>
+
+ <div className="flex flex-col gap-2">
+ <ModeOption
+ icon={<Pencil className="size-4" />}
+ title={t(($) => $.resources.mode_in_place_title)}
+ description={t(($) => $.resources.mode_in_place_description)}
+ identifier="in_place"
+ selected={selected === "in_place"}
+ onSelect={() => setSelected("in_place")}
+ />
+ <ModeOption
+ icon={<GitBranch className="size-4" />}
+ title={t(($) => $.resources.mode_worktree_title)}
+ description={t(($) => $.resources.mode_worktree_description)}
+ identifier="worktree"
+ selected={selected === "worktree"}
+ disabled={worktreeDisabled}
+ disabledReason={
+ unavailableReason === "not_git"
+ ? t(($) => $.resources.mode_worktree_needs_git)
+ : unavailableReason === "daemon_outdated"
+ ? t(($) => $.resources.mode_worktree_needs_upgrade, {
+ current:
+ currentVersion && currentVersion.length > 0
+ ? currentVersion
+ : t(($) => $.resources.mode_version_unknown),
+ min: minVersion ?? "",
+ })
+ : undefined
+ }
+ onSelect={() => setSelected("worktree")}
+ />
+ </div>
+
+ {errorMessage && (
+ <div className="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-caption text-destructive">
+ <TriangleAlert className="size-3.5 mt-0.5 shrink-0" />
+ <span>{errorMessage}</span>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ disabled={saving}
+ >
+ {t(($) => $.resources.mode_cancel)}
+ </Button>
+ <Button onClick={() => onConfirm(selected)} disabled={saving}>
+ {confirmLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+interface ModeOptionProps {
+ icon: React.ReactNode;
+ title: string;
+ description: string;
+ identifier: string;
+ selected: boolean;
+ disabled?: boolean;
+ disabledReason?: string;
+ onSelect: () => void;
+}
+
+function ModeOption({
+ icon,
+ title,
+ description,
+ identifier,
+ selected,
+ disabled = false,
+ disabledReason,
+ onSelect,
+}: ModeOptionProps) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={disabled}
+ onClick={onSelect}
+ // Selection is carried by border + ring rather than a background tint so
+ // it stays legible while hovered — hover only moves the background.
+ className={`flex w-full items-start gap-3 rounded-lg border p-3 text-left transition-colors ${
+ selected
+ ? "border-primary ring-1 ring-primary"
+ : "border-border hover:bg-muted/50"
+ } ${disabled ? "cursor-not-allowed opacity-60" : ""}`}
+ >
+ <span
+ className={`mt-0.5 shrink-0 ${
+ selected ? "text-primary" : "text-muted-foreground"
+ }`}
+ >
+ {icon}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex items-center gap-2">
+ <span className="text-body font-medium">{title}</span>
+ <span className="font-mono text-micro text-muted-foreground">
+ {identifier}
+ </span>
+ </span>
+ <span className="mt-0.5 block text-caption text-muted-foreground">
+ {description}
+ </span>
+ {disabled && disabledReason && (
+ <span className="mt-1.5 flex items-start gap-1.5 text-caption text-warning">
+ <TriangleAlert className="size-3 mt-0.5 shrink-0" />
+ <span>{disabledReason}</span>
+ </span>
+ )}
+ </span>
+ </button>
+ );
+}
diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsx
index ef181747c1..4ff94acf68 100644
--- a/packages/views/projects/components/project-resources-section.tsx
+++ b/packages/views/projects/components/project-resources-section.tsx
@@ -6,6 +6,7 @@ import {
ChevronRight,
FolderGit,
FolderOpen,
+ GitBranch,
Pencil,
Plus,
Search,
@@ -22,9 +23,17 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentWorkspace } from "@multica/core/paths";
import type {
GithubRepoResourceRef,
+ LocalDirectoryExecutionMode,
LocalDirectoryResourceRef,
ProjectResource,
} from "@multica/core/types";
+import {
+ MIN_LOCAL_WORKTREE_CLI_VERSION,
+ localWorktreeSupported,
+ readRuntimeCliVersion,
+ runtimeListOptions,
+} from "@multica/core/runtimes";
+import { Badge } from "@multica/ui/components/ui/badge";
import { Button } from "@multica/ui/components/ui/button";
import {
Popover,
@@ -43,6 +52,10 @@ import {
validateLocalDirectory,
type ValidateLocalDirectoryResult,
} from "../../platform";
+import {
+ LocalDirectoryModeDialog,
+ type WorktreeUnavailableReason,
+} from "./local-directory-mode-dialog";
import { useT } from "../../i18n";
import { githubShortLabel } from "../../common/github-url";
@@ -64,6 +77,31 @@ function isLocalDirectoryRef(r: ProjectResource): r is ProjectResource & {
return r.resource_type === "local_directory";
}
+/**
+ * Reads the execution mode off a stored ref. An absent or unrecognised value is
+ * reported as in_place, matching the server: the field is optional, and a mode
+ * written by a newer client must not render as anything other than the
+ * conservative default here.
+ */
+function executionModeOf(
+ ref: LocalDirectoryResourceRef,
+): LocalDirectoryExecutionMode {
+ return ref.execution_mode === "worktree" ? "worktree" : "in_place";
+}
+
+/** Pending mode edit — either for a directory being added, or an existing row. */
+type ModeDialogState = {
+ path: string;
+ daemonId: string | null;
+ mode: LocalDirectoryExecutionMode;
+ /** undefined = unknown (older desktop build); treated as "cannot verify". */
+ isGitRepo: boolean | undefined;
+ /** Set for an edit; absent when adding a new resource. */
+ resource?: ProjectResource & { resource_ref: LocalDirectoryResourceRef };
+ /** Only used when adding. */
+ label?: string;
+};
+
export function ProjectResourcesSection({ projectId }: { projectId: string }) {
const { t } = useT("projects");
const wsId = useWorkspaceId();
@@ -73,6 +111,9 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
const [addOpen, setAddOpen] = useState(false);
const [repoSearch, setRepoSearch] = useState("");
const [picking, setPicking] = useState(false);
+ const [modeDialog, setModeDialog] = useState<ModeDialogState | null>(null);
+ const [modeSaving, setModeSaving] = useState(false);
+ const [modeError, setModeError] = useState<string | null>(null);
const { data: resources = [] } = useQuery(
projectResourcesOptions(wsId, projectId),
@@ -88,6 +129,27 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
const desktopMode = isDesktopShell();
const localDaemonId = daemonStatus.daemonId;
+ // Worktree mode needs a daemon new enough to implement it. An older daemon
+ // does not know the field exists and would run the task in place — editing
+ // the working copy the user asked to isolate — so the server refuses the
+ // save. Checking here too turns that 422 into a disabled option with a
+ // reason, at the moment the user is choosing.
+ const { data: runtimes = [] } = useQuery(runtimeListOptions(wsId));
+ // Keyed on the resource's OWN daemon, not the machine the browser happens to
+ // be on: a resource is pinned to one machine, and its mode can legitimately
+ // be changed from the web app or from a different device. Using the local
+ // daemon here would report "too old" for every resource whenever the viewer
+ // is not on that machine.
+ const cliVersionForDaemon = (daemonId: string | null): string => {
+ if (!daemonId) return "";
+ return (
+ runtimes
+ .filter((rt) => rt.daemon_id === daemonId)
+ .map((rt) => readRuntimeCliVersion(rt.metadata))
+ .find((v) => v && v.length > 0) ?? ""
+ );
+ };
+
const attachedUrls = new Set(
resources.filter(isGithubRef).map((r) => r.resource_ref.url),
);
@@ -169,15 +231,17 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
);
return;
}
- await createResource.mutateAsync({
- resource_type: "local_directory",
- resource_ref: {
- local_path: path,
- daemon_id: localDaemonId,
- label: fallbackLabel,
- },
+ // Ask for the execution mode before creating. It is part of what the
+ // user is choosing — whether tasks edit this folder or hand back a
+ // branch — not a setting to discover afterwards.
+ setModeError(null);
+ setModeDialog({
+ path,
+ daemonId: localDaemonId,
+ mode: "in_place",
+ isGitRepo: validation.is_git_repo,
+ label: fallbackLabel,
});
- toast.success(t(($) => $.resources.toast_local_attached));
setAddOpen(false);
} catch (err) {
const msg =
@@ -190,6 +254,54 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
}
};
+ const handleConfirmMode = async (mode: LocalDirectoryExecutionMode) => {
+ if (!modeDialog || modeSaving) return;
+ setModeSaving(true);
+ setModeError(null);
+ try {
+ if (modeDialog.resource) {
+ const ref = modeDialog.resource.resource_ref;
+ if (executionModeOf(ref) === mode) {
+ setModeDialog(null);
+ return;
+ }
+ await updateResource.mutateAsync({
+ resourceId: modeDialog.resource.id,
+ data: {
+ // Spread first so every other ref field survives the edit — the
+ // server replaces the whole ref, it does not deep-merge.
+ resource_ref: { ...ref, execution_mode: mode },
+ },
+ });
+ toast.success(t(($) => $.resources.toast_local_mode_updated));
+ } else {
+ if (!localDaemonId) return;
+ await createResource.mutateAsync({
+ resource_type: "local_directory",
+ resource_ref: {
+ local_path: modeDialog.path,
+ daemon_id: localDaemonId,
+ label: modeDialog.label ?? modeDialog.path,
+ execution_mode: mode,
+ },
+ });
+ toast.success(t(($) => $.resources.toast_local_attached));
+ }
+ setModeDialog(null);
+ } catch (err) {
+ // Keep the dialog open and show the reason inline: the most likely
+ // failure is the server's daemon-version gate, and closing the dialog
+ // would leave the user with a toast and no way to act on it.
+ setModeError(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.resources.toast_local_mode_update_failed),
+ );
+ } finally {
+ setModeSaving(false);
+ }
+ };
+
const handleRemove = async (resource: ProjectResource) => {
try {
await deleteResource.mutateAsync(resource.id);
@@ -259,6 +371,20 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
canEdit={desktopMode}
onRemove={() => handleRemove(resource)}
onRenameLocalDirectory={handleRenameLocalDirectory}
+ onEditLocalDirectoryMode={(target) => {
+ setModeError(null);
+ setModeDialog({
+ path: target.resource_ref.local_path,
+ daemonId: target.resource_ref.daemon_id,
+ mode: executionModeOf(target.resource_ref),
+ // The path is already saved, so there is nothing to
+ // re-validate from the browser; the desktop check only
+ // runs at pick time. Unknown means the option stays
+ // available and the daemon has the final say.
+ isGitRepo: undefined,
+ resource: target,
+ });
+ }}
/>
))}
</div>
@@ -384,10 +510,56 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {
)}
</div>
)}
+ {modeDialog && (
+ <LocalDirectoryModeDialog
+ open
+ onOpenChange={(next) => {
+ if (!next) {
+ setModeDialog(null);
+ setModeError(null);
+ }
+ }}
+ path={modeDialog.path}
+ value={modeDialog.mode}
+ unavailableReason={worktreeUnavailableReason(
+ modeDialog.isGitRepo,
+ localWorktreeSupported(cliVersionForDaemon(modeDialog.daemonId)),
+ )}
+ currentVersion={cliVersionForDaemon(modeDialog.daemonId)}
+ minVersion={MIN_LOCAL_WORKTREE_CLI_VERSION}
+ errorMessage={modeError ?? undefined}
+ saving={modeSaving}
+ confirmLabel={
+ modeDialog.resource
+ ? t(($) => $.resources.mode_save)
+ : t(($) => $.resources.mode_add)
+ }
+ onConfirm={(mode) => void handleConfirmMode(mode)}
+ />
+ )}
</div>
);
}
+/**
+ * Which blocker (if any) applies to the worktree option.
+ *
+ * `isGitRepo === false` is a hard no — the daemon would fail every task on that
+ * folder. `undefined` means we could not check (an older desktop build, or an
+ * existing row whose path was validated at pick time), and is deliberately
+ * permissive: the daemon re-checks authoritatively, so guessing "not a repo"
+ * here would block a perfectly valid setup. The daemon-version gate is checked
+ * second because upgrading is the more actionable of the two.
+ */
+function worktreeUnavailableReason(
+ isGitRepo: boolean | undefined,
+ daemonSupportsWorktree: boolean,
+): WorktreeUnavailableReason | undefined {
+ if (isGitRepo === false) return "not_git";
+ if (!daemonSupportsWorktree) return "daemon_outdated";
+ return undefined;
+}
+
interface ResourceRowProps {
resource: ProjectResource;
localDaemonId: string | null;
@@ -397,6 +569,9 @@ interface ResourceRowProps {
resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },
nextLabel: string,
) => Promise<void>;
+ onEditLocalDirectoryMode: (
+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },
+ ) => void;
}
function ResourceRow({
@@ -405,6 +580,7 @@ function ResourceRow({
canEdit,
onRemove,
onRenameLocalDirectory,
+ onEditLocalDirectoryMode,
}: ResourceRowProps) {
const { t } = useT("projects");
if (isGithubRef(resource)) {
@@ -449,6 +625,7 @@ function ResourceRow({
canEdit={canEdit}
onRemove={onRemove}
onRename={onRenameLocalDirectory}
+ onEditMode={onEditLocalDirectoryMode}
/>
);
}
@@ -479,6 +656,9 @@ interface LocalDirectoryRowProps {
resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },
nextLabel: string,
) => Promise<void>;
+ onEditMode: (
+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },
+ ) => void;
}
function LocalDirectoryRow({
@@ -487,9 +667,11 @@ function LocalDirectoryRow({
canEdit,
onRemove,
onRename,
+ onEditMode,
}: LocalDirectoryRowProps) {
const { t } = useT("projects");
const ref = resource.resource_ref;
+ const mode = executionModeOf(ref);
const display = (ref.label || resource.label || ref.local_path).trim() ||
ref.local_path;
const isForeignDaemon =
@@ -563,6 +745,38 @@ function LocalDirectoryRow({
</TooltipContent>
</Tooltip>
)}
+ {/* Always visible, unlike the hover-only actions: without it there is no
+ way to tell whether tasks on this folder edit it directly or hand back
+ a branch, which is the first thing someone asks when a task queues (or
+ does not). */}
+ {mode === "worktree" && !editing && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Badge variant="secondary" className="shrink-0 gap-1 font-normal">
+ <GitBranch className="size-3" />
+ {t(($) => $.resources.mode_badge_worktree)}
+ </Badge>
+ }
+ />
+ <TooltipContent side="top">
+ {t(($) => $.resources.mode_badge_worktree_tooltip)}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {/* Not gated on `mismatch`: switching the mode only rewrites a field, so
+ it works from the web app or another device, unlike rename (whose
+ label belongs to the owning machine) or the folder picker. */}
+ {!editing && (
+ <button
+ type="button"
+ onClick={() => onEditMode(resource)}
+ className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"
+ title={t(($) => $.resources.mode_edit_tooltip)}
+ >
+ <GitBranch className="size-3 text-muted-foreground" />
+ </button>
+ )}
{canEdit && !mismatch && !editing && (
<button
type="button"
diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.go
index 0dbb44c3cc..8c1e405e1a 100644
--- a/server/cmd/multica/cmd_project.go
+++ b/server/cmd/multica/cmd_project.go
@@ -154,6 +154,7 @@ func init() {
projectResourceAddCmd.Flags().String("local-path", "", "Shortcut: absolute path to the working directory (only used when --type local_directory)")
projectResourceAddCmd.Flags().String("daemon-id", "", "Shortcut: id of the daemon that owns the local path (only used when --type local_directory)")
projectResourceAddCmd.Flags().String("ref-label", "", "Shortcut: optional label embedded in resource_ref (only used when --type local_directory)")
+ projectResourceAddCmd.Flags().String("execution-mode", "", "Shortcut: how tasks share the directory — in_place (default, one task at a time) or worktree (each task gets its own git worktree; requires a git repo) (only used when --type local_directory)")
projectResourceAddCmd.Flags().String("ref", "", "Generic JSON resource_ref payload, or a github_repo checkout ref when used with --url")
projectResourceAddCmd.Flags().String("label", "", "Optional human-readable label")
projectResourceAddCmd.Flags().String("output", "json", "Output format: table or json")
@@ -165,6 +166,7 @@ func init() {
projectResourceUpdateCmd.Flags().String("local-path", "", "Shortcut: new absolute local path (local_directory)")
projectResourceUpdateCmd.Flags().String("daemon-id", "", "Shortcut: new daemon id (local_directory)")
projectResourceUpdateCmd.Flags().String("ref-label", "", "Shortcut: new label embedded in resource_ref (local_directory)")
+ projectResourceUpdateCmd.Flags().String("execution-mode", "", "Shortcut: new execution mode — in_place or worktree (local_directory)")
projectResourceUpdateCmd.Flags().String("ref", "", "Generic JSON resource_ref payload, or a github_repo checkout ref")
projectResourceUpdateCmd.Flags().String("label", "", "New human-readable label; pass an empty string to clear")
projectResourceUpdateCmd.Flags().Bool("clear-label", false, "Clear the human-readable label")
@@ -607,6 +609,9 @@ func runProjectResourceAdd(cmd *cobra.Command, args []string) error {
if refLabel, _ := cmd.Flags().GetString("ref-label"); strings.TrimSpace(refLabel) != "" {
ref["label"] = strings.TrimSpace(refLabel)
}
+ if mode, _ := cmd.Flags().GetString("execution-mode"); strings.TrimSpace(mode) != "" {
+ ref["execution_mode"] = strings.TrimSpace(mode)
+ }
body["resource_ref"] = ref
default:
return fmt.Errorf("type %q has no built-in CLI shortcut; pass the payload via --ref '<json>'", resourceType)
@@ -845,7 +850,8 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existing
pathSet := cmd.Flags().Changed("local-path")
daemonSet := cmd.Flags().Changed("daemon-id")
labelSet := cmd.Flags().Changed("ref-label")
- if !pathSet && !daemonSet && !labelSet {
+ modeSet := cmd.Flags().Changed("execution-mode")
+ if !pathSet && !daemonSet && !labelSet && !modeSet {
return nil, false, nil
}
ref := map[string]any{}
@@ -859,6 +865,9 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existing
if l, ok := existingRef["label"].(string); ok && strings.TrimSpace(l) != "" {
ref["label"] = strings.TrimSpace(l)
}
+ if m, ok := existingRef["execution_mode"].(string); ok && strings.TrimSpace(m) != "" {
+ ref["execution_mode"] = strings.TrimSpace(m)
+ }
}
if pathSet {
pathVal := strings.TrimSpace(mustString(cmd, "local-path"))
@@ -882,6 +891,16 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existing
ref["label"] = refLabel
}
}
+ if modeSet {
+ // An empty value clears the field back to the in_place default,
+ // mirroring how --ref-label clears a label.
+ mode := strings.TrimSpace(mustString(cmd, "execution-mode"))
+ if mode == "" {
+ delete(ref, "execution_mode")
+ } else {
+ ref["execution_mode"] = mode
+ }
+ }
if v, ok := ref["local_path"].(string); !ok || v == "" {
return nil, false, fmt.Errorf("local_directory: --local-path is required (no existing local_path to merge with)")
}
@@ -893,7 +912,7 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existing
// Unknown type or empty (resource not found) — caller must use --ref.
if cmd.Flags().Changed("url") || cmd.Flags().Changed("default-branch-hint") ||
cmd.Flags().Changed("local-path") || cmd.Flags().Changed("daemon-id") ||
- cmd.Flags().Changed("ref-label") {
+ cmd.Flags().Changed("ref-label") || cmd.Flags().Changed("execution-mode") {
return nil, false, fmt.Errorf("no built-in shortcut for resource type %q; pass the full payload via --ref '<json>'", resourceType)
}
return nil, false, nil
diff --git a/server/cmd/multica/cmd_project_test.go b/server/cmd/multica/cmd_project_test.go
index 6b925c97b9..7067627897 100644
--- a/server/cmd/multica/cmd_project_test.go
+++ b/server/cmd/multica/cmd_project_test.go
@@ -36,6 +36,7 @@ func newProjectResourceUpdateTestCmd() *cobra.Command {
c.Flags().String("local-path", "", "")
c.Flags().String("daemon-id", "", "")
c.Flags().String("ref-label", "", "")
+ c.Flags().String("execution-mode", "", "")
c.Flags().String("ref", "", "")
c.Flags().String("label", "", "")
c.Flags().Bool("clear-label", false, "")
@@ -326,3 +327,61 @@ func TestBuildResourceRefFromFlagsLocalDirectoryMerges(t *testing.T) {
}
})
}
+
+// Switching an existing resource between in_place and worktree is a one-flag
+// edit, and an unrelated edit must not silently reset the mode — that would
+// drop a user back to serialised tasks without telling them.
+func TestBuildResourceRefFromFlagsLocalDirectoryExecutionMode(t *testing.T) {
+ t.Run("sets worktree mode", func(t *testing.T) {
+ cmd := newProjectResourceUpdateTestCmd()
+ _ = cmd.Flags().Set("execution-mode", "worktree")
+ existing := map[string]any{"local_path": "/Users/foo/work/a", "daemon_id": "d1"}
+ ref, has, err := buildResourceRefFromFlags(cmd, "local_directory", existing)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !has {
+ t.Fatal("expected has=true")
+ }
+ if ref["execution_mode"] != "worktree" {
+ t.Errorf("execution_mode = %v, want worktree", ref["execution_mode"])
+ }
+ })
+
+ t.Run("unrelated edit preserves existing mode", func(t *testing.T) {
+ cmd := newProjectResourceUpdateTestCmd()
+ _ = cmd.Flags().Set("ref-label", "renamed")
+ existing := map[string]any{
+ "local_path": "/Users/foo/work/a",
+ "daemon_id": "d1",
+ "execution_mode": "worktree",
+ }
+ ref, _, err := buildResourceRefFromFlags(cmd, "local_directory", existing)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if ref["execution_mode"] != "worktree" {
+ t.Errorf("execution_mode lost on an unrelated edit: %v", ref["execution_mode"])
+ }
+ })
+
+ t.Run("empty value clears back to the default", func(t *testing.T) {
+ cmd := newProjectResourceUpdateTestCmd()
+ _ = cmd.Flags().Set("execution-mode", "")
+ existing := map[string]any{
+ "local_path": "/Users/foo/work/a",
+ "daemon_id": "d1",
+ "execution_mode": "worktree",
+ }
+ ref, has, err := buildResourceRefFromFlags(cmd, "local_directory", existing)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !has {
+ t.Fatal("expected has=true")
+ }
+ if _, ok := ref["execution_mode"]; ok {
+ t.Errorf("expected execution_mode cleared, got %v", ref["execution_mode"])
+ }
+ })
+}
diff --git a/server/cmd/server/autopilot_listeners_test.go b/server/cmd/server/autopilot_listeners_test.go
index d688fd0d43..1fd116d09b 100644
--- a/server/cmd/server/autopilot_listeners_test.go
+++ b/server/cmd/server/autopilot_listeners_test.go
@@ -37,7 +37,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
{
name: "completed",
finalize: func(task db.AgentTaskQueue) {
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
},
@@ -47,7 +47,7 @@ func TestAutopilotRunOnlyTaskTerminalEventsUpdateRun(t *testing.T) {
{
name: "failed",
finalize: func(task db.AgentTaskQueue) {
- if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "agent_error", false, ""); err != nil {
+ if _, err := taskSvc.FailTask(ctx, task.ID, "boom", "", "", "", "agent_error", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
},
@@ -230,7 +230,7 @@ func TestAutopilotCreateIssueTaskNoProgressFailureUpdatesRun(t *testing.T) {
runTaskWithBudget(t, f.queries, f.taskID, 1)
const errMsg = "codex app-server no progress timeout after 30s"
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "codex_semantic_inactivity", false, ""); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "", "codex_semantic_inactivity", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
@@ -258,7 +258,7 @@ func TestAutopilotCreateIssueTaskAgentErrorFailureUpdatesRun(t *testing.T) {
// agent_error is not in retryableReasons, so the first terminal failure is
// final — the run must fail carrying the agent's error text.
const errMsg = "build failed: ./pkg/foo: undefined: Bar"
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "agent_error", false, ""); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, errMsg, "", "", "", "agent_error", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
@@ -287,7 +287,7 @@ func TestAutopilotCreateIssueTaskRetryPendingKeepsRunOpen(t *testing.T) {
// timeout is retryable, so FailTask enqueues a fresh attempt before it
// broadcasts the failure event.
- if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime went offline", "", "", "timeout", false, ""); err != nil {
+ if _, err := f.taskSvc.FailTask(ctx, f.taskID, "runtime went offline", "", "", "", "timeout", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/cmd/server/quick_create_subscriber_test.go b/server/cmd/server/quick_create_subscriber_test.go
index b9623f4307..1f76bb7328 100644
--- a/server/cmd/server/quick_create_subscriber_test.go
+++ b/server/cmd/server/quick_create_subscriber_test.go
@@ -75,7 +75,7 @@ func TestQuickCreateFailure_DoesNotSubscribeRequester(t *testing.T) {
// No issue with origin_type=quick_create + this task id exists. Completion
// hits the failure branch and writes a failure inbox; no subscriber row.
- if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, []byte(`{"output":"done"}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -147,7 +147,7 @@ func TestQuickCreateFailure_SurfacesAgentOutput(t *testing.T) {
// only output (per the quick-create prompt contract).
const agentErr = "Error: an active issue already exists: JKY-30 (blocked). Pass --allow-duplicate to override."
result, _ := json.Marshal(map[string]any{"output": agentErr})
- if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -229,7 +229,7 @@ func TestQuickCreateLookupFault_WritesUnconfirmedInbox(t *testing.T) {
result, _ := json.Marshal(map[string]any{
"output": "Error: an active issue already exists: JKY-30 (blocked).",
})
- if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -301,7 +301,7 @@ func TestQuickCreateFailure_RedactsAgentOutput(t *testing.T) {
result, _ := json.Marshal(map[string]any{
"output": "Error: create failed while authenticating with " + fakeToken,
})
- if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
+ if _, err := taskSvc.CompleteTask(ctx, task.ID, result, "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
@@ -375,7 +375,7 @@ func TestQuickCreateLookupCancelled_StillWritesUnconfirmedInbox(t *testing.T) {
)
result, _ := json.Marshal(map[string]any{"output": "Error: something went wrong"})
- if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", false, ""); err != nil {
+ if _, err := faulting.CompleteTask(ctx, task.ID, result, "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if ctx.Err() == nil {
diff --git a/server/cmd/server/retired_session_test.go b/server/cmd/server/retired_session_test.go
index 3606418c52..5322932943 100644
--- a/server/cmd/server/retired_session_test.go
+++ b/server/cmd/server/retired_session_test.go
@@ -262,7 +262,7 @@ func TestFailTaskClearsPoisonedChatPointer(t *testing.T) {
// The un-upgraded-daemon shape: catchall reason, poisoning only in the text.
if _, err := taskSvc.FailTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(taskID), Valid: true},
"Invalid request: the message at position 37 with role 'assistant' must not be empty",
- "CHAT-PTR-S", "/tmp/chat", "agent_error.unknown", false, ""); err != nil {
+ "CHAT-PTR-S", "/tmp/chat", "", "agent_error.unknown", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
@@ -306,7 +306,7 @@ func TestFailTaskKeepsChatPointerOnTransientFailure(t *testing.T) {
taskSvc := service.NewTaskService(queries, testPool, nil, events.New())
if _, err := taskSvc.FailTask(ctx, pgtype.UUID{Bytes: parseUUIDBytes(taskID), Valid: true},
- "Connection closed mid-response", "CHAT-KEEP-S", "/tmp/chat",
+ "Connection closed mid-response", "CHAT-KEEP-S", "/tmp/chat", "",
"agent_error.provider_network", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 2203ec8157..8f8334907a 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -339,13 +339,44 @@ func (c *Client) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID, reas
}, nil)
}
+// TaskCancelAck is the payload of the daemon's cancel acknowledgement.
+type TaskCancelAck struct {
+ // BranchName: a cancelled worktree task has already finalized — its
+ // partial work is committed to a branch in the user's repo. The cancel
+ // path discards the rest of the result, so this ack is the only channel
+ // left to report where that work went.
+ BranchName string
+ // ErrorMessage / FailureReason: set when the cancelled run additionally
+ // FAILED to persist its work (worktree Finalize abort). There is no branch
+ // then; the error text carrying the preserved-worktree path is the only
+ // pointer to the agent's work, and without this the cancel path would
+ // swallow it entirely.
+ ErrorMessage string
+ FailureReason string
+}
+
// AckTaskCancelled tells the server this daemon observed the task's
// cancellation and has finished flushing the transcript (runner.run only
// returns after executeAndDrain's drain wait), so the server can settle its
// deferred chat finalization now instead of waiting out the sweeper grace
// period (#5219). Idempotent server-side.
-func (c *Client) AckTaskCancelled(ctx context.Context, taskID string) error {
- return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/cancel-ack", taskID), map[string]any{}, nil)
+//
+// Retried on transient errors like the complete/fail callbacks: when the ack
+// carries a branch or an error it is a terminal delivery — the only pointer to
+// the cancelled task's work — and a single lost POST would lose it forever.
+// The server never overwrites already-recorded values, so replays are safe.
+func (c *Client) AckTaskCancelled(ctx context.Context, taskID string, ack TaskCancelAck) error {
+ body := map[string]any{}
+ if ack.BranchName != "" {
+ body["branch_name"] = ack.BranchName
+ }
+ if ack.ErrorMessage != "" {
+ body["error_message"] = ack.ErrorMessage
+ }
+ if ack.FailureReason != "" {
+ body["failure_reason"] = ack.FailureReason
+ }
+ return c.postJSONWithRetry(ctx, fmt.Sprintf("/api/daemon/tasks/%s/cancel-ack", taskID), body, nil, defaultTerminalRetrySchedule)
}
func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, step, total int) error {
@@ -401,7 +432,7 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas
}, nil)
}
-func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool, retiredSessionID string) error {
+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID string) error {
body := map[string]any{"error": errMsg}
if sessionID != "" {
body["session_id"] = sessionID
@@ -409,6 +440,12 @@ func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDi
if workDir != "" {
body["work_dir"] = workDir
}
+ // A failed run can still have delivered a branch: worktree mode commits
+ // whatever the agent left before removing the worktree, so partial work
+ // survives — but only if its name travels with the failure report.
+ if branchName != "" {
+ body["branch_name"] = branchName
+ }
if failureReason != "" {
body["failure_reason"] = failureReason
}
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index 360ae181af..7d2c8b2389 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -290,7 +290,7 @@ func TestFailTask_RetriesOnTransient5xxThenSucceeds(t *testing.T) {
defer srv.Close()
c := NewClient(srv.URL)
- if err := c.FailTask(context.Background(), "task-1", "boom", "", "", "timeout", true, ""); err != nil {
+ if err := c.FailTask(context.Background(), "task-1", "boom", "", "", "", "timeout", true, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
if got := calls.Load(); got != 3 {
@@ -427,7 +427,7 @@ func TestTerminalReportsCarryRetiredSessionID(t *testing.T) {
name: "fail",
endpoint: "/api/daemon/tasks/task-1/fail",
call: func(c *Client) error {
- return c.FailTask(context.Background(), "task-1", "boom", "", "/tmp/wd", "api_invalid_request", false, "POISONED-S")
+ return c.FailTask(context.Background(), "task-1", "boom", "", "/tmp/wd", "", "api_invalid_request", false, "POISONED-S")
},
},
} {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c4fe9071f6..7554afc8cd 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -4903,11 +4903,25 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// Check if we were cancelled by the polling goroutine.
select {
case <-cancelledByPoll:
- taskLog.Info("task cancelled during execution, discarding result")
+ taskLog.Info("task cancelled during execution, discarding result",
+ "branch_name", result.BranchName, "error", err)
// runner.run has returned, so the transcript flush is complete —
// tell the server it can settle its deferred chat finalization
- // (#5219). Best-effort: the sweeper grace period covers a lost ack.
- if ackErr := d.client.AckTaskCancelled(ctx, task.ID); ackErr != nil {
+ // (#5219). The sweeper grace period covers a lost ack's chat settle,
+ // but NOT the payload: the branch rides along because the worktree was
+ // already finalized before this check, and when Finalize instead
+ // ABORTED, the preserved-worktree error is the only pointer left to
+ // the agent's work — everything else on this path is discarded. Other
+ // run errors stay discarded: on a cancelled run they are expected
+ // noise (context canceled, killed process), and persisting them would
+ // stamp a bogus reason on every ordinary mid-run cancel.
+ ack := TaskCancelAck{BranchName: result.BranchName}
+ var preserved *worktreePreservedError
+ if errors.As(err, &preserved) {
+ ack.ErrorMessage = preserved.Error()
+ ack.FailureReason = "local_directory_error"
+ }
+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID, ack); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
return
@@ -4941,10 +4955,18 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// anyway. Reuse shouldInterruptAgent so this guard honors the same
// signals as the in-flight watcher.
if status, err := d.client.GetTaskStatus(ctx, task.ID); shouldInterruptAgent(status, err) {
- taskLog.Info("task cancelled during execution, discarding result", "status", status, "error", err)
+ taskLog.Info("task cancelled during execution, discarding result",
+ "status", status, "error", err, "branch_name", result.BranchName)
// Same contract as the poll-cancelled path above: the transcript is
- // flushed, so let the server settle its deferred chat finalization.
- if ackErr := d.client.AckTaskCancelled(ctx, task.ID); ackErr != nil {
+ // flushed, so let the server settle its deferred chat finalization, and
+ // carry the finalized branch so cancelled work stays discoverable. No
+ // error to carry here — this branch is only reached with err == nil.
+ // This fires for ANY observed terminal status; the server applies the
+ // payload only to a cancelled row (status CAS), because for
+ // completed/failed rows the complete/fail callback is the
+ // authoritative channel and a stale run's late ack must not touch
+ // them.
+ if ackErr := d.client.AckTaskCancelled(ctx, task.ID, TaskCancelAck{BranchName: result.BranchName}); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
return
@@ -4964,7 +4986,15 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// sibling workdir (which is the user's path) or the envRoot
// itself (we want output/ and logs/ to linger for forensic
// access).
- if assignment, _ := localDirectoryAssignmentForTask(task, d.cfg.DaemonID); assignment != nil {
+ //
+ // Worktree mode is excluded: its workdir is a disposable
+ // worktree INSIDE envRoot, already removed by Finalize, and
+ // the deliverable lives on as a branch in the user's repo.
+ // Stamping it would hand every worktree task a permanently
+ // exempt env root, so the directory would accumulate one env
+ // root per task forever — the exact cost the exemption was
+ // meant to trade away for a user's own files.
+ if assignment, _ := localDirectoryAssignmentForTask(task, d.cfg.DaemonID); assignment != nil && !assignment.UsesWorktree() {
meta.LocalDirectory = true
}
if err := execenv.WriteGCMeta(result.EnvRoot, meta, taskLog); err != nil {
@@ -4974,6 +5004,16 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
}
}
+// worktreePreservedError marks a task error that must survive the cancel path:
+// its message names the preserved worktree holding the agent's uncommitted
+// work. Every other error on a cancelled run is expected noise (context
+// canceled, killed process) and stays discarded; this one is the only pointer
+// to real work and rides the cancel ack to the server.
+type worktreePreservedError struct{ err error }
+
+func (e *worktreePreservedError) Error() string { return e.err.Error() }
+func (e *worktreePreservedError) Unwrap() error { return e.err }
+
func taskRunFailureReason(err error) string {
if errors.Is(err, errTaskPrepareTimeout) {
return taskfailure.ReasonTimeout.String()
@@ -5027,6 +5067,21 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
return nil, false
}
taskLog = taskLog.With("local_directory", assignment.AbsPath)
+ // Check the mode before the path: a mode this daemon can't honour is a
+ // version-skew problem the user fixes by upgrading, and reporting a path
+ // complaint first would send them looking in the wrong place.
+ if err := assignment.ValidateExecutionMode(); err != nil {
+ taskLog.Error("local_directory: unsupported execution mode", "error", err)
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: err.Error(),
+ failureReason: "local_directory_error",
+ }); failErr != nil {
+ taskLog.Error("fail task after local_directory mode check", "error", failErr)
+ }
+ return nil, true
+ }
if err := validateLocalPath(assignment.AbsPath); err != nil {
taskLog.Error("local_directory: path validation failed", "error", err)
if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
@@ -5040,6 +5095,17 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
return nil, true
}
+ // Worktree mode is the whole point of not serialising: each task gets its
+ // own checkout of the repo inside its env root, so there is no shared
+ // mutable state on the user's path to protect. Skipping the mutex here is
+ // what lets sibling tasks on one directory run concurrently. Path
+ // validation above still applies — git needs to write worktree
+ // registrations into the user's repo.
+ if assignment.UsesWorktree() {
+ taskLog.Info("local_directory: worktree mode, skipping path mutex")
+ return nil, false
+ }
+
// While the lock is contended the daemon would otherwise sit blocked on
// the path mutex with no signal back from the server — the main
// per-task watcher only starts after the lock is acquired. If the user
@@ -5194,9 +5260,13 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
// "agent_error" coarse bucket.
fallbackErrMsg := fmt.Sprintf("complete task failed: %s", err.Error())
if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
- kind: terminalTaskReportFail,
- taskID: taskID,
- errorMessage: fallbackErrMsg,
+ kind: terminalTaskReportFail,
+ taskID: taskID,
+ errorMessage: fallbackErrMsg,
+ // The agent succeeded here — only the server's complete callback was
+ // rejected. Its branch is real and already committed, so it must
+ // survive the downgrade to a failure report.
+ branchName: result.BranchName,
sessionID: result.SessionID,
workDir: result.WorkDir,
failureReason: taskfailure.Classify(fallbackErrMsg).String(),
@@ -5226,11 +5296,16 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
}
taskLog.Info("task did not complete, reporting failure", "status", result.Status, "failure_reason", failureReason)
if err := d.reportTerminalTask(ctx, terminalTaskReport{
- kind: terminalTaskReportFail,
- taskID: taskID,
- errorMessage: result.Comment,
- sessionID: result.SessionID,
- workDir: result.WorkDir,
+ kind: terminalTaskReportFail,
+ taskID: taskID,
+ errorMessage: result.Comment,
+ sessionID: result.SessionID,
+ workDir: result.WorkDir,
+ // Worktree mode commits the agent's leftovers before tearing the
+ // worktree down, so a failed run routinely still has a branch. This
+ // is the case where the user most needs it: the task went wrong and
+ // they want to see how far it got.
+ branchName: result.BranchName,
failureReason: failureReason,
sessionRolloutMissing: result.SessionRolloutMissing,
retiredSessionID: result.RetiredSessionID,
@@ -5253,7 +5328,7 @@ func (d *Daemon) reportTerminalTask(parentCtx context.Context, report terminalTa
case terminalTaskReportComplete:
return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir, report.sessionRolloutMissing, report.retiredSessionID)
case terminalTaskReportFail:
- return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID)
+ return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.branchName, report.failureReason, report.sessionRolloutMissing, report.retiredSessionID)
default:
return fmt.Errorf("unsupported terminal task report kind %d", report.kind)
}
@@ -6178,12 +6253,81 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
CodexCustomArgs: codexSandboxArgs,
Task: taskCtx,
}
- if localAssignment != nil {
- prepParams.LocalWorkDir = localAssignment.AbsPath
- }
- env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)
- if err != nil {
- return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)
+ if localAssignment.UsesWorktree() {
+ prepParams.LocalWorktree = &execenv.LocalWorktreeParams{LocalPath: localAssignment.AbsPath}
+ // Take the per-path mutex for the snapshot alone, then hand it
+ // straight back — long enough to read a consistent tree, short
+ // enough that worktree tasks still overlap for the run itself.
+ //
+ // A worktree task skips this lock for its execution, but the
+ // snapshot is the one moment it READS the user's directory, and the
+ // same real path can be attached to another project as an in_place
+ // resource (each project may attach it once, so several can).
+ // Snapshotting underneath a running in_place task would capture a
+ // half-written tree plus that task's in-flight sidecars.
+ //
+ // The wait gets the same visibility plumbing as the in-place
+ // acquire in acquireLocalDirectoryLockIfNeeded, because the holder
+ // can be an in-place task that runs for hours: without the status
+ // update the user sees a bare "preparing" with no hint the task is
+ // queued behind the directory, and without the poller a task the
+ // user cancels keeps its daemon slot pinned until the prepare
+ // timeout — the run-phase cancellation watcher only starts after
+ // launch. The prepare-lease extender is already running for this
+ // whole phase, so only status, accounting, and cancellation are
+ // mirrored here.
+ waitCtx, waitCancel := context.WithCancel(prepareCtx)
+ defer waitCancel()
+ pollInterval := d.cancelPollInterval
+ if pollInterval == 0 {
+ pollInterval = 5 * time.Second
+ }
+ // LocalPathLocker invokes onWait synchronously, in this goroutine,
+ // at most once per Acquire — see the in-place call site.
+ waitCounted := false
+ release, lockErr := d.localPathLocks.Acquire(waitCtx, localAssignment.RealPath, task.ID, func(holder string) {
+ d.resourceWaitTasks.Add(1)
+ waitCounted = true
+ reason := fmt.Sprintf("local_directory %s", localAssignment.AbsPath)
+ if holder != "" {
+ reason = fmt.Sprintf("%s (held by task %s)", reason, shortID(holder))
+ }
+ taskLog.Info("local_directory: worktree snapshot waiting for holder",
+ "holder", shortID(holder))
+ if waitErr := d.client.MarkTaskWaitingLocalDirectory(waitCtx, task.ID, reason); waitErr != nil {
+ // Non-fatal: the wait still happens, the UI just won't
+ // show the explicit "waiting" badge.
+ taskLog.Warn("local_directory: mark waiting status failed", "error", waitErr)
+ }
+ cancelled := d.watchTaskCancellation(waitCtx, task.ID, pollInterval, taskLog)
+ go func() {
+ select {
+ case <-cancelled:
+ waitCancel()
+ case <-waitCtx.Done():
+ }
+ }()
+ })
+ if waitCounted {
+ d.resourceWaitTasks.Add(-1)
+ }
+ if lockErr != nil {
+ return TaskResult{}, fmt.Errorf("local_directory worktree: wait for a consistent snapshot of %s: %w",
+ localAssignment.AbsPath, lockErr)
+ }
+ env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)
+ release()
+ if err != nil {
+ return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)
+ }
+ } else {
+ if localAssignment != nil {
+ prepParams.LocalWorkDir = localAssignment.AbsPath
+ }
+ env, err = d.prepareExecutionEnvironment(prepareCtx, prepParams)
+ if err != nil {
+ return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)
+ }
}
}
// Belt-and-suspenders: also mark whatever root we ended up with, in case
@@ -6192,6 +6336,110 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
d.markActiveEnvRoot(env.RootDir)
defer d.unmarkActiveEnvRoot(env.RootDir)
}
+ // Finalize the worktree on EVERY exit path, success or failure: commit
+ // whatever the agent left uncommitted, then unregister the worktree from
+ // the user's repo. Deferred against the named return so a task that fails
+ // mid-run still hands back the branch holding its partial work instead of
+ // letting `git worktree remove --force` delete it. A failing task is
+ // exactly when the user most wants to see how far the agent got.
+ if env.LocalWorktree != nil {
+ defer func() {
+ outcome, finalizeErr := env.LocalWorktree.Finalize(taskLog)
+ if outcome.Branch != "" {
+ taskResult.BranchName = outcome.Branch
+ }
+ if finalizeErr == nil {
+ return
+ }
+ // The agent's changes could not be committed, so Finalize kept the
+ // worktree instead of deleting them. Fail the task: a "completed"
+ // task whose branch is missing the work reads as success, and the
+ // user would never learn the changes are sitting in an env root the
+ // GC reclaims on a timer.
+ //
+ // Wrapped in worktreePreservedError so the cancel path can
+ // recognise it: a cancelled task discards its result and error, but
+ // THIS error names the preserved worktree holding the agent's work
+ // and must ride the cancel ack instead of vanishing into a log.
+ // Joined rather than replacing an earlier failure — that one is
+ // usually the more useful primary cause, but the preserved path
+ // must not be displaced by it.
+ taskLog.Error("local_directory: worktree finalize could not persist the agent's changes",
+ "error", finalizeErr, "preserved_path", outcome.PreservedPath)
+ wrapped := &worktreePreservedError{err: fmt.Errorf("local_directory worktree: %w", finalizeErr)}
+ if returnErr == nil {
+ returnErr = wrapped
+ } else {
+ returnErr = errors.Join(returnErr, wrapped)
+ }
+ }()
+ }
+ // Workdir is preserved for reuse by future tasks on the same (agent,
+ // issue) pair in cloud mode; the work_dir path is stored in DB on task
+ // completion and passed back via PriorWorkDir on the next claim, so
+ // rewriting the marker block in place is the right behavior.
+ //
+ // In local_directory mode the workdir is the user's own repo, reuse is
+ // already disabled above (see localAssignment == nil), and the brief
+ // would otherwise live on inside the user's repository — a subsequent
+ // manual `claude` / `codex` run in that directory would pick
+ // up stale Multica instructions (issue id, trigger comment id, reply
+ // rules) and start acting on the previous task's context. Excise the
+ // marker block on the way out instead.
+ //
+ // Worktree mode runs the same pass for a different reason: the worktree is
+ // disposable, but its branch is the deliverable, and Finalize commits
+ // whatever is still on disk. Without this the sidecars would land in every
+ // task's diff. The .git/info/exclude trick repocache uses for github_repo
+ // worktrees is not available here — a linked worktree resolves info/exclude
+ // to the user's own common git dir, so using it would silently change what
+ // `git status` hides in the user's checkout. Removing the files we wrote is
+ // both narrower and exact; it also leaves a genuine agent edit to a tracked
+ // CLAUDE.md intact, since CleanupRuntimeConfig only excises our marker block.
+ //
+ // Ordering: registered immediately after the Finalize defer above, so LIFO
+ // runs cleanup first and Finalize commits an already-clean worktree. It must
+ // also precede every early return between here and provider launch
+ // (temp-dir setup, StartTask): those paths still run Finalize, and without
+ // this pass Finalize would auto-commit the sidecars Prepare just wrote and
+ // deliver a branch whose only content is Multica's own runtime files — or,
+ // in place, leave them behind in the user's tree.
+ if env.LocalDirectory || env.LocalWorktree != nil {
+ defer func() {
+ var cleanupErr error
+ if cerr := execenv.CleanupRuntimeConfig(env.WorkDir, provider); cerr != nil {
+ cleanupErr = cerr
+ d.logger.Warn("execenv: cleanup runtime config failed", "error", cerr)
+ }
+ // Excise the sidecar tree (.agent_context/, .multica/,
+ // provider-specific .claude/skills/ etc.) that Prepare wrote
+ // into the user's repo. Without this pass the user's tree
+ // accumulates one directory layer per task — see MUL-2784.
+ // CleanupRuntimeConfig handles the runtime brief inside
+ // CLAUDE.md / AGENTS.md; CleanupSidecars handles
+ // every other file Prepare placed under WorkDir. Together
+ // they round-trip the workdir to its exact pre-task bytes.
+ if cerr := execenv.CleanupSidecars(env.RootDir); cerr != nil {
+ if cleanupErr == nil {
+ cleanupErr = cerr
+ }
+ d.logger.Warn("execenv: cleanup sidecars failed", "error", cerr)
+ }
+ // In worktree mode a failed cleanup is NOT survivable: Finalize is
+ // about to `git add -A`, so whatever the cleanup could not remove
+ // gets committed and delivered as the task's branch — a diff whose
+ // content is Multica's own runtime files, which is precisely what
+ // this mode promises never to produce. Tell Finalize to abort
+ // instead, so nothing is committed and the worktree is kept for
+ // inspection. (In place there is no commit and no branch, so a
+ // cleanup failure stays a warning: the leftover files are visible
+ // in the user's own tree and removable by hand.)
+ if cleanupErr != nil && env.LocalWorktree != nil {
+ env.LocalWorktree.AbortWithReason(fmt.Errorf(
+ "could not remove the runtime's own files from the worktree before committing: %w", cleanupErr))
+ }
+ }()
+ }
taskTempDir, err := ensureTaskTempDir(env.RootDir, task.WorkspaceID, task.ID)
if err != nil {
return TaskResult{}, fmt.Errorf("prepare task temp dir: %w", err)
@@ -6237,37 +6485,6 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err != nil {
d.logger.Warn("execenv: inject runtime config failed (non-fatal)", "error", err)
}
- // Workdir is preserved for reuse by future tasks on the same (agent,
- // issue) pair in cloud mode; the work_dir path is stored in DB on task
- // completion and passed back via PriorWorkDir on the next claim, so
- // rewriting the marker block in place is the right behavior.
- //
- // In local_directory mode the workdir is the user's own repo, reuse is
- // already disabled above (see localAssignment == nil), and the brief
- // would otherwise live on inside the user's repository — a subsequent
- // manual `claude` / `codex` run in that directory would pick
- // up stale Multica instructions (issue id, trigger comment id, reply
- // rules) and start acting on the previous task's context. Excise the
- // marker block on the way out instead.
- if env.LocalDirectory {
- defer func() {
- if cerr := execenv.CleanupRuntimeConfig(env.WorkDir, provider); cerr != nil {
- d.logger.Warn("execenv: cleanup runtime config failed (non-fatal)", "error", cerr)
- }
- // Excise the sidecar tree (.agent_context/, .multica/,
- // provider-specific .claude/skills/ etc.) that Prepare wrote
- // into the user's repo. Without this pass the user's tree
- // accumulates one directory layer per task — see MUL-2784.
- // CleanupRuntimeConfig handles the runtime brief inside
- // CLAUDE.md / AGENTS.md; CleanupSidecars handles
- // every other file Prepare placed under WorkDir. Together
- // they round-trip the workdir to its exact pre-task bytes.
- if cerr := execenv.CleanupSidecars(env.RootDir); cerr != nil {
- d.logger.Warn("execenv: cleanup sidecars failed (non-fatal)", "error", cerr)
- }
- }()
- }
-
prompt := BuildPrompt(task, provider)
// Pass task-scoped auth credentials and context so the spawned agent CLI
diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.go
index 4c6871fd14..b8a19d47e8 100644
--- a/server/internal/daemon/execenv/codex_home.go
+++ b/server/internal/daemon/execenv/codex_home.go
@@ -63,8 +63,15 @@ type CodexHomeOptions struct {
// whole shared history back in. Empty means a fresh thread (no rollout to
// expose). See prepareCodexSessionsDir (MUL-4424).
ResumeSessionID string
- // IsLocalDirectory marks a local_directory task — one running in the user's
- // own project directory. These tasks get a fresh codex-home per task ID (the
+ // IsLocalDirectory marks a task whose env root is never reused across task
+ // IDs — every local_directory task, in_place or worktree. Worktree tasks
+ // get a fresh env root per task just like in-place ones do
+ // (shouldReusePriorWorkdir refuses any local assignment), so they need the
+ // same per-issue session store; keying this on "runs in the user's
+ // directory" instead would silently drop a Codex agent's conversation
+ // history between turns on the same issue.
+ //
+ // These tasks get a fresh codex-home per task ID (the
// daemon never reuses their workdir), so their sessions/ is pointed at the
// per-issue store (SessionStoreKey) that survives across task IDs and holds
// ONLY this issue's rollouts — never the machine's whole ~/.codex/sessions.
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index f1e88e6a53..0b90da2f42 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -68,6 +68,13 @@ type PrepareParams struct {
// substituted. Used by the local_directory project_resource flow
// (MUL-2663). When set, the envRoot/workdir directory is not created.
LocalWorkDir string
+ // LocalWorktree, when non-nil, is the worktree-mode counterpart of
+ // LocalWorkDir: instead of running in the user's directory, the task gets
+ // its own git worktree of that repo inside envRoot and delivers its work
+ // as a branch. Tasks sharing the directory then run concurrently.
+ // Mutually exclusive with LocalWorkDir — the daemon picks one based on the
+ // resource's execution_mode.
+ LocalWorktree *LocalWorktreeParams
// HermesSourceHome is the shared Hermes home the per-task overlay is seeded
// from — resolved by the daemon via execenv.ResolveHermesProfile so it honors
// the agent's custom_env HERMES_HOME and any -p/--profile or sticky selection.
@@ -232,11 +239,21 @@ type Environment struct {
// outside RootDir (the local_directory flow). Callers that key behavior
// on "may I remove WorkDir as scratch?" must check this — for example
// the GC loop never deletes the user's directory.
+ //
+ // Deliberately FALSE in worktree mode: there the workdir is a disposable
+ // git worktree inside RootDir, so the env root is ordinary daemon-owned
+ // scratch that the GC should reclaim on the normal schedule, and the
+ // sidecar rollback that protects a user's directory is unnecessary.
LocalDirectory bool
// MulticaConfigRoot is the private per-task config directory exported to
// child CLI invocations. It prevents implicit discovery of the daemon
// owner's ~/.multica profile without changing the provider-facing HOME.
MulticaConfigRoot string
+ // LocalWorktree is set when the task runs in worktree mode against a
+ // local_directory resource. The daemon calls Finalize on it after the
+ // agent exits to commit leftovers, drop the worktree, and learn the
+ // branch name to report as the task's result.
+ LocalWorktree *LocalWorktree
// CodexHome is the path to the per-task CODEX_HOME directory (set only for codex provider).
CodexHome string
// ClaudeSettingsPath is a task-local --settings JSON file that applies
@@ -343,9 +360,9 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// envRoot.
workDir := filepath.Join(envRoot, "workdir")
scratchDirs := []string{filepath.Join(envRoot, "output"), filepath.Join(envRoot, "logs")}
- if params.LocalWorkDir == "" {
+ if params.LocalWorkDir == "" && params.LocalWorktree == nil {
scratchDirs = append(scratchDirs, workDir)
- } else {
+ } else if params.LocalWorkDir != "" {
workDir = params.LocalWorkDir
}
for _, dir := range scratchDirs {
@@ -361,10 +378,49 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
return nil, fmt.Errorf("execenv: restrict task-local Multica config directory: %w", err)
}
+ // Worktree mode: build the task's own checkout of the user's repo inside
+ // envRoot and use it as the workdir. Done before any context file is
+ // written so the sidecars land inside the disposable worktree instead of
+ // the user's directory.
+ var localWorktree *LocalWorktree
+ // Tracks whether Prepare reached its successful return. Everything after
+ // worktree creation can still fail — context files, provider homes, MCP
+ // config — and on those paths the caller never receives an Environment, so
+ // nothing downstream knows a worktree exists to clean up. Without the
+ // rollback below, each such failure would leave a registration in the
+ // user's repo and a branch that no task ever ran in.
+ prepareSucceeded := false
+ if params.LocalWorktree != nil {
+ wtParams := *params.LocalWorktree
+ wtParams.EnvRoot = envRoot
+ wtParams.AgentName = params.AgentName
+ wtParams.TaskID = params.TaskID
+ var err error
+ localWorktree, err = PrepareLocalWorktree(wtParams, logger)
+ if err != nil {
+ return nil, err
+ }
+ defer func() {
+ if prepareSucceeded {
+ return
+ }
+ // Safe to discard unconditionally: no agent has run yet, so the
+ // worktree holds only what Prepare itself put there.
+ localWorktree.Discard(logger)
+ }()
+ workDir = localWorktree.WorkDir
+ // The resource may point at a subdirectory that holds only ignored
+ // files, in which case git doesn't materialise it in the worktree.
+ if err := os.MkdirAll(workDir, 0o755); err != nil {
+ return nil, fmt.Errorf("execenv: create worktree workdir %s: %w", workDir, err)
+ }
+ }
+
env := &Environment{
RootDir: envRoot,
WorkDir: workDir,
LocalDirectory: params.LocalWorkDir != "",
+ LocalWorktree: localWorktree,
MulticaConfigRoot: multicaConfigRoot,
logger: logger,
}
@@ -403,7 +459,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// For Codex, set up a per-task CODEX_HOME seeded from ~/.codex/ with skills.
if params.Provider == "codex" {
codexHome := filepath.Join(envRoot, codexHomeDirName)
- if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "", SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task), CodexCustomArgs: params.CodexCustomArgs}, logger); err != nil {
+ if err := prepareCodexHomeWithOpts(codexHome, CodexHomeOptions{CodexVersion: params.CodexVersion, IsLocalDirectory: params.LocalWorkDir != "" || params.LocalWorktree != nil, SessionStoreKey: codexSessionStoreKey(params.Profile, params.Task), CodexCustomArgs: params.CodexCustomArgs}, logger); err != nil {
return nil, fmt.Errorf("execenv: prepare codex-home: %w", err)
}
if err := hydrateCodexSkills(codexHome, params.Task.AgentSkills, params.Task.DisabledRuntimeSkills, logger); err != nil {
@@ -499,6 +555,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
}
logger.Info("execenv: prepared env", "root", envRoot, "repos_available", len(params.Task.Repos))
+ prepareSucceeded = true
return env, nil
}
diff --git a/server/internal/daemon/execenv/local_worktree.go b/server/internal/daemon/execenv/local_worktree.go
new file mode 100644
index 0000000000..6d0f99584c
--- /dev/null
+++ b/server/internal/daemon/execenv/local_worktree.go
@@ -0,0 +1,744 @@
+package execenv
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Local worktree mode gives every task on a local_directory resource its own
+// git worktree of the user's repo, created inside the daemon-owned env root.
+// Tasks on the same directory then run concurrently instead of queueing on the
+// per-path mutex, and each one delivers its work as a branch in the user's own
+// repo — discoverable with `git branch`, no new result channel needed.
+//
+// Three properties this file exists to guarantee:
+//
+// 1. The agent sees what the user sees. `git worktree add` alone would check
+// out HEAD, silently hiding the user's uncommitted work. We replay the
+// dirty state into the worktree instead (tracked edits via a stash commit,
+// untracked files by copy).
+// 2. The user's directory is never written to. Everything — including the
+// sidecar context files Prepare writes — lands inside the worktree, which
+// is disposable. The only lasting effect on the user's repo is the branch.
+// 3. Nothing is silently discarded. Whatever the agent leaves uncommitted is
+// committed to the branch before the worktree goes away.
+
+const (
+ // localWorktreeDirName is the env-root-relative directory holding the
+ // worktree. Kept short: on Windows the worktree path plus the deepest
+ // repo path must stay under MAX_PATH for tools that predate long paths.
+ localWorktreeDirName = "worktree"
+
+ // gitTimeout bounds every git invocation this file makes. These are all
+ // local-only operations (no network), so a slow one means a wedged index
+ // lock rather than a slow remote; failing the task beats hanging a daemon
+ // slot forever.
+ gitTimeout = 2 * time.Minute
+
+ // maxUntrackedFiles / maxUntrackedBytes bound the untracked-file replay.
+ // `--exclude-standard` already drops anything gitignored (node_modules,
+ // build output, venvs), so a repo hitting these limits has an unusual
+ // amount of untracked-but-not-ignored content. We copy up to the bound and
+ // report the remainder rather than silently truncating or hanging on a
+ // multi-gigabyte copy.
+ maxUntrackedFiles = 2000
+ maxUntrackedBytes = 200 << 20 // 200 MiB
+)
+
+// gitRootLocks serialises git admin operations per repository. Concurrent
+// `git worktree add` / `remove` / `prune` on one repo race on the same
+// lockfiles (worktrees/, packed-refs.lock, config.lock), and unlike a fetch
+// these are fast, so a plain mutex costs nothing. Keyed by the repo root so
+// tasks on different repos never wait on each other.
+var gitRootLocks sync.Map // gitRoot -> *sync.Mutex
+
+func lockGitRoot(gitRoot string) func() {
+ v, _ := gitRootLocks.LoadOrStore(gitRoot, &sync.Mutex{})
+ mu := v.(*sync.Mutex)
+ mu.Lock()
+ return mu.Unlock
+}
+
+// LocalWorktreeParams describes the worktree Prepare should build for a
+// local_directory task running in worktree mode.
+type LocalWorktreeParams struct {
+ // LocalPath is the user's configured directory. It may be the repo root
+ // or any subdirectory of it; the worktree always covers the whole repo,
+ // and the agent's cwd is the matching subdirectory inside it.
+ LocalPath string
+ // EnvRoot is the daemon-owned task env root. The worktree is created
+ // inside it so the ordinary env-root GC reclaims it.
+ EnvRoot string
+ // AgentName and TaskID name the branch: agent/<name>/<short-task-id>.
+ AgentName string
+ TaskID string
+}
+
+// LocalWorktree is a prepared worktree plus everything the daemon needs to
+// finalize it after the agent exits.
+type LocalWorktree struct {
+ // GitRoot is the user's repository root — the repo that owns the branch.
+ GitRoot string
+ // Path is the worktree root inside the env root.
+ Path string
+ // WorkDir is the agent's cwd: Path, plus the offset of LocalPath inside
+ // the repo when the user pointed the resource at a subdirectory.
+ WorkDir string
+ // Branch is the branch created for this task, in the user's repo.
+ Branch string
+ // BaseCommit is the commit the worktree started from. Finalize compares
+ // the branch tip against it to decide whether the task produced anything.
+ BaseCommit string
+ // DirtyBaseCaptured records that the user had uncommitted tracked edits
+ // which were replayed into the worktree.
+ DirtyBaseCaptured bool
+ // 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).
+ aborted error
+ // UntrackedCopied / UntrackedSkipped report the untracked-file replay.
+ // A non-zero skip count means the bounds below were hit and the agent is
+ // looking at less than the user has on disk; it is logged at warn level so
+ // the gap is findable rather than invisible.
+ UntrackedCopied int
+ UntrackedSkipped int
+}
+
+// LocalWorktreeOutcome is what a finished worktree task delivered.
+type LocalWorktreeOutcome struct {
+ // Branch is the branch holding the task's work, or "" when the task made
+ // no changes at all (a read-only run) — in that case the branch is deleted
+ // so it never shows up in the user's `git branch` as an empty artifact.
+ Branch string
+ // AutoCommitted is true when the agent left uncommitted changes that
+ // Finalize committed so they would survive the worktree's removal.
+ AutoCommitted bool
+ // 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.
+ PreservedPath string
+}
+
+// PrepareLocalWorktree creates the task's worktree and replays the user's
+// uncommitted state into it. It never writes to the user's working tree: the
+// dirty state is read through `git stash create`, which builds a commit object
+// without touching the index or the files on disk.
+func PrepareLocalWorktree(params LocalWorktreeParams, logger *slog.Logger) (*LocalWorktree, error) {
+ if params.LocalPath == "" {
+ return nil, errors.New("execenv: local worktree requires a local path")
+ }
+ if params.EnvRoot == "" {
+ return nil, errors.New("execenv: local worktree requires an env root")
+ }
+ if params.TaskID == "" {
+ return nil, errors.New("execenv: local worktree requires a task id")
+ }
+
+ gitRoot, err := resolveGitRoot(params.LocalPath)
+ if err != nil {
+ return nil, err
+ }
+
+ // The agent's cwd keeps the user's chosen depth: a resource pointed at
+ // <repo>/services/api must land the agent in <worktree>/services/api, not
+ // at the repo root, or the task's whole notion of "the project" shifts.
+ //
+ // Canonicalise before the comparison: gitRoot comes back canonical, while
+ // the configured path routinely isn't (on macOS every /tmp and /var path is
+ // a symlink into /private). Comparing the two forms directly reads a repo
+ // root as "outside itself".
+ localPath := params.LocalPath
+ if resolved, evalErr := filepath.EvalSymlinks(localPath); evalErr == nil {
+ localPath = resolved
+ }
+ rel, err := filepath.Rel(gitRoot, localPath)
+ if err != nil {
+ return nil, fmt.Errorf("execenv: locate %q inside repo %q: %w", localPath, gitRoot, err)
+ }
+ if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return nil, fmt.Errorf("execenv: %q is not inside its repository root %q", localPath, gitRoot)
+ }
+
+ worktreePath := filepath.Join(params.EnvRoot, localWorktreeDirName)
+
+ // Everything below mutates the repo's worktree admin state, so take the
+ // per-repo lock first — including the stale-path cleanup, which runs `git
+ // worktree remove` and would otherwise race a sibling task's `worktree add`.
+ unlock := lockGitRoot(gitRoot)
+ defer unlock()
+
+ if _, statErr := os.Stat(worktreePath); statErr == nil {
+ // Prepare wipes and recreates envRoot, so an existing worktree path
+ // means a stale registration in the user's repo pointing here. Remove
+ // both rather than failing the task.
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ }
+
+ // Self-heal registrations orphaned by a crashed daemon: their env roots are
+ // long gone, but the user's repo still lists them. Prune only drops entries
+ // whose directory no longer exists, so it can never disturb a live task.
+ if out, pruneErr := runGit(gitRoot, "worktree", "prune"); pruneErr != nil && logger != nil {
+ logger.Warn("execenv: git worktree prune failed (non-fatal)",
+ "git_root", gitRoot, "output", out, "error", pruneErr)
+ }
+
+ headSHA, err := runGitTrimmed(gitRoot, "rev-parse", "--verify", "HEAD")
+ if err != nil {
+ return nil, fmt.Errorf("execenv: repository %q has no commit to branch from "+
+ "(worktree mode needs at least one commit; make an initial commit or switch the resource back to in_place): %w", gitRoot, err)
+ }
+
+ // `git stash create` builds a commit capturing tracked modifications and
+ // returns its sha WITHOUT stashing — the user's index and working tree are
+ // untouched. Empty output means the tree is clean. The identity args cover
+ // a repo with no user.email configured: writing a commit object needs a
+ // committer, and without them the user's uncommitted work would be dropped
+ // on a technicality.
+ stashSHA, stashErr := runGitTrimmed(gitRoot, append(commitIdentityArgs(gitRoot), "stash", "create")...)
+ if stashErr != nil {
+ // Fail closed. The promise of this mode is that the agent reasons about
+ // the code the user actually has; silently starting from HEAD instead
+ // would have it review a tree the user never saw and report confidently
+ // on it. A task that does not start is recoverable — one that answers
+ // from the wrong sources is not.
+ return nil, fmt.Errorf("execenv: could not capture the uncommitted changes in %q, "+
+ "so the worktree would not match what you have on disk: %w", gitRoot, stashErr)
+ }
+
+ branch := fmt.Sprintf("agent/%s/%s", sanitizeName(params.AgentName), shortID(params.TaskID))
+ actualBranch, err := addLocalWorktree(gitRoot, worktreePath, branch, headSHA)
+ if err != nil {
+ return nil, err
+ }
+
+ wt := &LocalWorktree{
+ GitRoot: gitRoot,
+ Path: worktreePath,
+ WorkDir: filepath.Join(worktreePath, rel),
+ Branch: actualBranch,
+ BaseCommit: headSHA,
+ }
+
+ // Replay tracked edits. Applied as unstaged modifications on top of HEAD so
+ // the branch history stays linear and the agent sees the same
+ // work-in-progress the user has open in their editor.
+ //
+ // Every failure below aborts the prepare and tears the worktree back down.
+ // A half-replayed tree is the worst outcome available: it looks like a
+ // working checkout, so nothing downstream questions it, while the agent
+ // silently reads different code than the user has.
+ if stashSHA != "" {
+ if out, applyErr := runGit(worktreePath, "stash", "apply", stashSHA); applyErr != nil {
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ deleteBranch(gitRoot, actualBranch, logger)
+ return nil, fmt.Errorf("execenv: could not replay the uncommitted changes from %q into the task worktree "+
+ "(the agent would have seen a different tree than you have): %s: %w",
+ gitRoot, strings.TrimSpace(out), applyErr)
+ }
+ wt.DirtyBaseCaptured = true
+ }
+
+ copied, skipped, err := copyUntrackedFiles(gitRoot, worktreePath, logger)
+ if err != nil {
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ deleteBranch(gitRoot, actualBranch, logger)
+ return nil, fmt.Errorf("execenv: could not replay the untracked files from %q into the task worktree: %w", gitRoot, err)
+ }
+ if skipped > 0 {
+ // Any untracked file we could not reproduce makes the worktree a tree
+ // the user would not recognise, so this fails rather than quietly
+ // under-copying. Causes: the size/count bounds (usually build output
+ // that should have been gitignored), an untracked symlink, or a file
+ // that disappeared mid-snapshot. The message names the common fix
+ // without claiming to know which one it was.
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ deleteBranch(gitRoot, actualBranch, logger)
+ return nil, fmt.Errorf("execenv: could not replay every untracked file from %q into the task worktree "+
+ "(copied %d, %d left over; the replay covers regular files up to %d files / %d MiB and does not follow symlinks) "+
+ "— gitignore or clean up the untracked files, or switch the resource back to in_place",
+ gitRoot, copied, skipped, maxUntrackedFiles, maxUntrackedBytes>>20)
+ }
+ wt.UntrackedCopied = copied
+ wt.UntrackedSkipped = skipped
+
+ // Commit the replayed state as a baseline so "did this task change
+ // anything?" has an exact answer later. Without it the user's own
+ // uncommitted work counts as a change: a read-only task on a repo with an
+ // untracked scratch file would auto-commit that file at the end and leave
+ // behind a branch the agent never touched. The baseline also makes the
+ // delivered branch readable — `git diff <baseline>..<branch>` is precisely
+ // the agent's work, with the user's WIP as its own labelled commit.
+ dirty, dirtyErr := worktreeIsDirty(worktreePath)
+ if dirtyErr != nil {
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ deleteBranch(gitRoot, actualBranch, logger)
+ return nil, fmt.Errorf("execenv: could not inspect the prepared worktree for %q: %w", gitRoot, dirtyErr)
+ }
+ if dirty {
+ baseline, baseErr := commitBaseline(worktreePath)
+ if baseErr != nil {
+ // Without a baseline the task cannot tell the user's work from the
+ // agent's, so it would later commit the user's files as if the agent
+ // had produced them. Refuse rather than deliver a misleading branch.
+ removeLocalWorktreeDir(gitRoot, worktreePath, logger)
+ deleteBranch(gitRoot, actualBranch, logger)
+ return nil, fmt.Errorf("execenv: could not record a baseline commit for the replayed state of %q: %w", gitRoot, baseErr)
+ }
+ wt.BaseCommit = baseline
+ }
+
+ // Note on keeping sidecars out of the delivered branch: we deliberately do
+ // NOT write .git/info/exclude here. A linked worktree reads info/exclude
+ // from the repo's COMMON git dir, so the only file that would take effect
+ // is the user's own .git/info/exclude — editing it would change what `git
+ // status` shows in the user's checkout, which is theirs, not ours. Instead
+ // the daemon runs the existing CleanupRuntimeConfig + CleanupSidecars pass
+ // over the worktree before Finalize, so the sidecars are simply gone by the
+ // time anything is committed. That also preserves a genuine agent edit to a
+ // tracked CLAUDE.md, which a blanket exclude would have swallowed.
+
+ if logger != nil {
+ logger.Info("execenv: local worktree ready",
+ "git_root", gitRoot,
+ "path", worktreePath,
+ "branch", actualBranch,
+ "base", headSHA,
+ "dirty_base_captured", wt.DirtyBaseCaptured,
+ "untracked_copied", copied,
+ "untracked_skipped", skipped,
+ )
+ }
+ return wt, nil
+}
+
+// Finalize commits whatever the agent left behind, removes the worktree, and
+// reports the branch. Called after the agent exits, before the env root is
+// handed to the GC.
+//
+// The auto-commit is the reason a worktree task can't lose work: `git worktree
+// remove --force` would happily delete uncommitted edits, and the user would
+// 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.
+func (w *LocalWorktree) Finalize(logger *slog.Logger) (LocalWorktreeOutcome, error) {
+ if w == nil {
+ return LocalWorktreeOutcome{}, nil
+ }
+ unlock := lockGitRoot(w.GitRoot)
+ defer unlock()
+
+ outcome := LocalWorktreeOutcome{Branch: w.Branch}
+
+ // Something before the commit went wrong in a way that would make the
+ // delivered branch misleading. Commit nothing and keep the worktree: the
+ // agent's work is still in it, and so is whatever the caller could not
+ // clean up, which a human can now look at directly.
+ if w.aborted != nil {
+ // Report NO branch. One exists in the user's repo, but nothing was
+ // committed to it, so naming it as this task's result would point them
+ // at a branch that is missing the very work they are looking for. The
+ // preserved worktree path below is the honest pointer.
+ outcome.Branch = ""
+ outcome.PreservedPath = w.Path
+ if logger != nil {
+ logger.Error("execenv: worktree finalize aborted; nothing committed, worktree kept for inspection",
+ "path", w.Path, "branch", w.Branch, "git_root", w.GitRoot, "error", w.aborted)
+ }
+ return outcome, fmt.Errorf(
+ "refusing to deliver branch %s: %w; the task worktree is preserved at %s (listed by `git worktree list` in %s)",
+ w.Branch, w.aborted, w.Path, w.GitRoot)
+ }
+
+ // Treat "can't tell" like "dirty": committing costs an empty commit at
+ // worst, while assuming clean risks deleting the agent's edits.
+ dirty, statusErr := worktreeIsDirty(w.Path)
+ if statusErr != nil {
+ if logger != nil {
+ logger.Warn("execenv: inspect worktree status failed; committing defensively",
+ "path", w.Path, "error", statusErr)
+ }
+ dirty = true
+ }
+ if dirty {
+ committed, err := w.commitAll(logger)
+ if err != nil {
+ outcome.PreservedPath = w.Path
+ if logger != nil {
+ logger.Error("execenv: could not commit the agent's changes; keeping the worktree so the work is recoverable",
+ "path", w.Path, "branch", w.Branch, "git_root", w.GitRoot, "error", err)
+ }
+ return outcome, fmt.Errorf(
+ "could not commit the agent's changes to 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, err, w.Path, w.GitRoot)
+ }
+ outcome.AutoCommitted = committed
+ }
+
+ // A branch still sitting exactly on its base commit means the task changed
+ // nothing — the read-only case. Delete it so the user's branch list only
+ // ever grows for tasks that actually produced work.
+ tip, err := runGitTrimmed(w.Path, "rev-parse", "--verify", "HEAD")
+ producedWork := err != nil || tip != w.BaseCommit
+
+ removeLocalWorktreeDir(w.GitRoot, w.Path, logger)
+
+ if !producedWork {
+ deleteBranch(w.GitRoot, w.Branch, logger)
+ outcome.Branch = ""
+ }
+
+ if logger != nil {
+ logger.Info("execenv: local worktree finalized",
+ "git_root", w.GitRoot,
+ "branch", outcome.Branch,
+ "auto_committed", outcome.AutoCommitted,
+ "produced_work", producedWork,
+ )
+ }
+ return outcome, nil
+}
+
+// Discard tears a worktree down without delivering anything: unregister it,
+// delete its directory, drop its branch.
+//
+// For the abandon-before-the-agent-ran case only. Finalize is the path that
+// preserves work; this one assumes there is none to preserve, so callers must
+// be sure nothing has run in the worktree yet.
+func (w *LocalWorktree) Discard(logger *slog.Logger) {
+ if w == nil {
+ return
+ }
+ unlock := lockGitRoot(w.GitRoot)
+ defer unlock()
+ removeLocalWorktreeDir(w.GitRoot, w.Path, logger)
+ deleteBranch(w.GitRoot, w.Branch, logger)
+ if logger != nil {
+ logger.Info("execenv: local worktree discarded before the agent ran",
+ "git_root", w.GitRoot, "path", w.Path, "branch", w.Branch)
+ }
+}
+
+// AbortWithReason marks the worktree undeliverable. Finalize will then commit
+// nothing, remove nothing, and return an error naming the preserved path.
+//
+// This exists because the decision "is this branch safe to deliver?" is made
+// outside this package — the daemon knows whether its own sidecar cleanup
+// succeeded — while the only code that can act on it is Finalize. The first
+// reason wins: it is the one closest to the root cause.
+func (w *LocalWorktree) AbortWithReason(err error) {
+ if w == nil || err == nil || w.aborted != nil {
+ return
+ }
+ w.aborted = err
+}
+
+// commitBaseline records the user's replayed uncommitted state as the first
+// commit on the task branch, returning the new tip.
+func commitBaseline(worktreePath string) (string, error) {
+ if _, err := commitEverything(worktreePath, "chore(agent): baseline — uncommitted work from the local directory"); err != nil {
+ return "", err
+ }
+ tip, err := runGitTrimmed(worktreePath, "rev-parse", "--verify", "HEAD")
+ if err != nil {
+ return "", fmt.Errorf("resolve baseline commit: %w", err)
+ }
+ return tip, nil
+}
+
+// commitAll stages and commits everything the agent left behind. Returns
+// whether a commit was actually created; an error means the changes are still
+// only on disk and the caller must not delete the worktree.
+func (w *LocalWorktree) commitAll(logger *slog.Logger) (bool, error) {
+ return commitEverything(w.Path, "chore(agent): uncommitted changes from task")
+}
+
+// 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.
+func commitEverything(worktreePath, message string) (bool, error) {
+ if out, err := runGit(worktreePath, "add", "-A"); err != nil {
+ return false, fmt.Errorf("git add: %s: %w", strings.TrimSpace(out), err)
+ }
+ // --no-verify: the user's commit hooks are written for the user's own
+ // workflow (interactive linters, test suites, signing prompts) and a hook
+ // failure here would mean losing the agent's work to save a lint run. Note
+ // it does NOT disable commit.gpgSign, which is why the caller has to treat
+ // a commit failure as "keep the worktree" rather than a warning.
+ args := append(commitIdentityArgs(worktreePath), "commit", "--no-verify", "-m", message)
+ if out, err := runGit(worktreePath, args...); err != nil {
+ if strings.Contains(out, "nothing to commit") {
+ return false, nil
+ }
+ return false, fmt.Errorf("git commit: %s: %w", strings.TrimSpace(out), err)
+ }
+ return true, nil
+}
+
+// commitIdentityArgs supplies a committer identity only when the repo doesn't
+// already have one. A repo with user.email configured keeps it, so commits
+// still look like they came from the user's own setup.
+func commitIdentityArgs(dir string) []string {
+ if email, err := runGitTrimmed(dir, "config", "user.email"); err == nil && email != "" {
+ return nil
+ }
+ return []string{
+ "-c", "user.name=Multica Agent",
+ }
+}
+
+func worktreeIsDirty(worktreePath string) (bool, error) {
+ out, err := runGit(worktreePath, "status", "--porcelain")
+ if err != nil {
+ return false, fmt.Errorf("git status: %s: %w", strings.TrimSpace(out), err)
+ }
+ return strings.TrimSpace(out) != "", nil
+}
+
+// removeLocalWorktreeDir unregisters the worktree from the user's repo and
+// deletes its directory. The branch is deliberately left alone — it is the
+// task's deliverable.
+func removeLocalWorktreeDir(gitRoot, worktreePath string, logger *slog.Logger) {
+ if out, err := runGit(gitRoot, "worktree", "remove", "--force", worktreePath); err != nil {
+ if logger != nil {
+ logger.Warn("execenv: git worktree remove failed; pruning registration",
+ "path", worktreePath, "output", out, "error", err)
+ }
+ // Fall back to deleting the directory ourselves and dropping the now
+ // dangling registration, so the user's repo isn't left listing a
+ // worktree that no longer exists.
+ if rmErr := os.RemoveAll(worktreePath); rmErr != nil && logger != nil {
+ logger.Warn("execenv: remove worktree directory failed", "path", worktreePath, "error", rmErr)
+ }
+ if out, pruneErr := runGit(gitRoot, "worktree", "prune"); pruneErr != nil && logger != nil {
+ logger.Warn("execenv: git worktree prune failed", "output", out, "error", pruneErr)
+ }
+ }
+}
+
+// deleteBranch drops a task branch that carries nothing worth keeping — an
+// empty read-only run, or a prepare that aborted partway. Best-effort: a
+// leftover branch is untidy, never harmful.
+func deleteBranch(gitRoot, branch string, logger *slog.Logger) {
+ if branch == "" {
+ return
+ }
+ if out, err := runGit(gitRoot, "branch", "-D", branch); err != nil && logger != nil {
+ logger.Warn("execenv: delete task branch failed (non-fatal)",
+ "branch", branch, "output", out, "error", err)
+ }
+}
+
+// resolveGitRoot returns the repository root containing dir. Worktree mode is
+// opt-in per resource, so a non-git directory here is a misconfiguration the
+// user needs to see and fix — we fail closed with an actionable message rather
+// than silently degrading to the in-place lock, which would leave the user
+// wondering why their tasks still queue.
+func resolveGitRoot(dir string) (string, error) {
+ root, err := runGitTrimmed(dir, "rev-parse", "--show-toplevel")
+ if err != nil || root == "" {
+ return "", fmt.Errorf("execenv: local_directory %q is not a git repository, "+
+ "but its project resource is set to execution_mode=worktree; "+
+ "initialise a repository there or switch the resource back to in_place", dir)
+ }
+ // EvalSymlinks so the root matches the path git reports from inside the
+ // worktree later — on macOS /tmp vs /private/tmp otherwise produce two
+ // different lock keys for one repo.
+ if resolved, evalErr := filepath.EvalSymlinks(root); evalErr == nil {
+ root = resolved
+ }
+ return filepath.Clean(root), nil
+}
+
+// addLocalWorktree creates the worktree, retrying once under a suffixed branch
+// name when the branch already exists (a re-dispatched task keeps its id, so
+// its branch can survive from the previous run).
+func addLocalWorktree(gitRoot, worktreePath, branch, baseRef string) (string, error) {
+ out, err := runGit(gitRoot, "worktree", "add", "-b", branch, worktreePath, baseRef)
+ if err != nil && strings.Contains(strings.ToLower(out), "already exists") {
+ branch = fmt.Sprintf("%s-%d", branch, time.Now().Unix())
+ out, err = runGit(gitRoot, "worktree", "add", "-b", branch, worktreePath, baseRef)
+ }
+ if err != nil {
+ return "", fmt.Errorf("execenv: git worktree add: %s: %w", strings.TrimSpace(out), err)
+ }
+ return branch, nil
+}
+
+// copyUntrackedFiles replays the user's untracked-but-not-ignored files into
+// the worktree. `git worktree add` only materialises committed content, so
+// without this a brand-new file the user just created would be invisible to the
+// agent. Bounded by maxUntrackedFiles / maxUntrackedBytes; the number skipped
+// is returned so the caller can tell the user instead of quietly under-copying.
+func copyUntrackedFiles(gitRoot, worktreePath string, logger *slog.Logger) (copied, skipped int, err error) {
+ // stdout only: a warning on stderr would otherwise be split apart and
+ // treated as file paths to copy. Raw, not trimmed: with -z the entries are
+ // exact filenames, and a file whose name begins or ends with whitespace
+ // would be trim-corrupted into a path that fails to stat and silently
+ // vanishes from the replay.
+ out, err := runGitStdout(gitRoot, "ls-files", "--others", "--exclude-standard", "-z")
+ if err != nil {
+ return 0, 0, fmt.Errorf("git ls-files: %w", err)
+ }
+
+ var budget int64 = maxUntrackedBytes
+ for _, rel := range strings.Split(out, "\x00") {
+ if rel == "" {
+ continue
+ }
+ // Never replay Multica's own sidecars. They are untracked files in the
+ // user's directory whenever an in_place task is mid-flight on the same
+ // path, or was killed before its cleanup ran. Copying them would put
+ // another issue's brief inside this task's worktree — where the agent
+ // would read it as its own context — and commit it to the branch.
+ if isMulticaSidecarPath(rel) {
+ continue
+ }
+ if copied >= maxUntrackedFiles || budget <= 0 {
+ skipped++
+ continue
+ }
+ src := filepath.Join(gitRoot, rel)
+ info, statErr := os.Lstat(src)
+ if statErr != nil {
+ // Listed a moment ago, unreadable now — the tree changed under us,
+ // so the snapshot no longer matches what the user has. Counted, not
+ // skipped silently: the caller fails the task on a non-zero count.
+ skipped++
+ if logger != nil {
+ logger.Warn("execenv: untracked file vanished between listing and copy",
+ "file", rel, "error", statErr)
+ }
+ continue
+ }
+ if info.Mode()&os.ModeSymlink != 0 {
+ // An untracked symlink is content the user can see. Reproducing it
+ // faithfully means deciding whether to copy the link or its target
+ // — including targets outside the repo — so this replay does not
+ // try. Count it so the task fails rather than handing the agent a
+ // tree with a file quietly missing.
+ skipped++
+ if logger != nil {
+ logger.Warn("execenv: untracked symlink not replayed into worktree", "file", rel)
+ }
+ continue
+ }
+ if !info.Mode().IsRegular() {
+ // Sockets, FIFOs, devices: not content, and not something an agent
+ // can meaningfully read from a copy. Skipping them does not make the
+ // snapshot misleading, so this one stays uncounted.
+ continue
+ }
+ if info.Size() > budget {
+ skipped++
+ continue
+ }
+ if copyErr := copyUntrackedFile(src, filepath.Join(worktreePath, rel), info.Mode()); copyErr != nil {
+ skipped++
+ if logger != nil {
+ logger.Warn("execenv: copy untracked file into worktree failed", "file", rel, "error", copyErr)
+ }
+ continue
+ }
+ budget -= info.Size()
+ copied++
+ }
+ return copied, skipped, nil
+}
+
+// copyUntrackedFile copies one untracked file into the worktree, creating
+// parent directories and preserving the executable bit — a script the user just
+// wrote and hasn't committed has to stay runnable for the agent.
+// multicaSidecarDirNames are the directories Prepare writes into a workdir. A
+// task running in_place on the same directory leaves these present as
+// untracked files for the length of its run, so a concurrent worktree snapshot
+// sees them. CLAUDE.md / AGENTS.md are deliberately absent: those are
+// ordinarily the user's own tracked files, and the runtime only injects a
+// marker block into them, which CleanupRuntimeConfig removes.
+var multicaSidecarDirNames = []string{
+ ".agent_context",
+ ".multica",
+}
+
+// isMulticaSidecarPath reports whether a repo-relative path is one of the
+// daemon's own sidecars rather than the user's content. Matched as a whole
+// path segment at ANY depth, not just the repo root: an in_place resource may
+// point at a subdirectory of this repo, in which case its sidecars sit at
+// <subdir>/.agent_context — replaying those would put another issue's brief
+// inside this task's worktree and commit it to the delivered branch.
+func isMulticaSidecarPath(rel string) bool {
+ for _, seg := range strings.Split(filepath.ToSlash(rel), "/") {
+ for _, name := range multicaSidecarDirNames {
+ if seg == name {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func copyUntrackedFile(src, dst string, mode os.FileMode) error {
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return err
+ }
+ if err := copyFile(src, dst); err != nil {
+ return err
+ }
+ return os.Chmod(dst, mode.Perm())
+}
+
+// runGit runs git in dir and returns combined output. Callers inspect the
+// output for git's own error text, so stdout and stderr stay merged.
+func runGit(dir string, args ...string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
+ defer cancel()
+
+ full := append([]string{"-C", dir}, args...)
+ cmd := exec.CommandContext(ctx, "git", full...)
+ cmd.WaitDelay = 5 * time.Second
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+}
+
+// runGitTrimmed runs git for its stdout value, discarding stderr so a
+// diagnostic line can't be mistaken for the value (`rev-parse` output, a
+// config value, a stash sha).
+func runGitTrimmed(dir string, args ...string) (string, error) {
+ out, err := runGitStdout(dir, args...)
+ if err != nil {
+ return "", err
+ }
+ return strings.TrimSpace(out), nil
+}
+
+// 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.
+func runGitStdout(dir string, args ...string) (string, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
+ defer cancel()
+
+ full := append([]string{"-C", dir}, args...)
+ cmd := exec.CommandContext(ctx, "git", full...)
+ cmd.WaitDelay = 5 * time.Second
+ out, err := cmd.Output()
+ if err != nil {
+ return "", 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
new file mode 100644
index 0000000000..30613f5572
--- /dev/null
+++ b/server/internal/daemon/execenv/local_worktree_test.go
@@ -0,0 +1,754 @@
+package execenv
+
+import (
+ "errors"
+ "io"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func worktreeTestLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+// newTestRepo creates a git repo with one commit and returns its path. The
+// repo carries its own identity config so tests don't depend on the machine's
+// global git setup.
+func newTestRepo(t *testing.T) string {
+ t.Helper()
+ requireGit(t)
+ dir := t.TempDir()
+ // macOS hands out /var/folders temp dirs that are symlinks to /private/var.
+ // resolveGitRoot canonicalises, so the test must compare against the
+ // canonical form too.
+ if resolved, err := filepath.EvalSymlinks(dir); err == nil {
+ dir = resolved
+ }
+ gitRun(t, dir, "init", "-b", "main")
+ gitRun(t, dir, "config", "user.name", "Test User")
+ gitRun(t, dir, "config", "user.email", "[email protected]")
+ writeFile(t, filepath.Join(dir, "tracked.txt"), "original\n")
+ writeFile(t, filepath.Join(dir, "keep.txt"), "keep\n")
+ gitRun(t, dir, "add", ".")
+ gitRun(t, dir, "commit", "-m", "initial")
+ return dir
+}
+
+// requireGit skips the whole test when git is missing from the environment.
+// This is the ONLY place a skip is allowed: once a test is past it, every git
+// command is part of the assertion surface, so a failure there is a real
+// regression and must fail loudly. An earlier version skipped on any git error,
+// which would have turned "the delivered branch is gone" into a green run.
+func requireGit(t *testing.T) {
+ t.Helper()
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skipf("git is not available: %v", err)
+ }
+}
+
+func gitRun(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v failed: %s: %v", args, out, err)
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func gitTry(t *testing.T, dir string, args ...string) (string, error) {
+ t.Helper()
+ cmd := exec.Command("git", append([]string{"-C", dir}, args...)...)
+ out, err := cmd.CombinedOutput()
+ return strings.TrimSpace(string(out)), err
+}
+
+func readFile(t *testing.T, path string) string {
+ t.Helper()
+ b, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ return string(b)
+}
+
+func prepareForTest(t *testing.T, localPath string) *LocalWorktree {
+ t.Helper()
+ wt, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: localPath,
+ EnvRoot: t.TempDir(),
+ AgentName: "J",
+ TaskID: "11112222-3333-4444-5555-666677778888",
+ }, worktreeTestLogger())
+ if err != nil {
+ t.Fatalf("PrepareLocalWorktree: %v", err)
+ }
+ return wt
+}
+
+// The agent must see the user's uncommitted work, not a clean HEAD checkout.
+// This is the property that makes worktree mode usable rather than confusing:
+// otherwise the agent silently reviews code the user hasn't got open.
+func TestPrepareLocalWorktreeReplaysUncommittedWork(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by user\n")
+ writeFile(t, filepath.Join(repo, "brand-new.txt"), "untracked\n")
+ writeFile(t, filepath.Join(repo, "nested/deep.txt"), "nested untracked\n")
+
+ wt := prepareForTest(t, repo)
+
+ if got := readFile(t, filepath.Join(wt.Path, "tracked.txt")); got != "edited by user\n" {
+ t.Errorf("tracked edit not replayed into worktree: got %q", got)
+ }
+ if got := readFile(t, filepath.Join(wt.Path, "brand-new.txt")); got != "untracked\n" {
+ t.Errorf("untracked file not copied: got %q", got)
+ }
+ if got := readFile(t, filepath.Join(wt.Path, "nested/deep.txt")); got != "nested untracked\n" {
+ t.Errorf("nested untracked file not copied: got %q", got)
+ }
+ if !wt.DirtyBaseCaptured {
+ t.Error("DirtyBaseCaptured = false, want true")
+ }
+ if wt.UntrackedCopied != 2 {
+ t.Errorf("UntrackedCopied = %d, want 2", wt.UntrackedCopied)
+ }
+}
+
+// Capturing the dirty state must not disturb the user's own working tree —
+// they may have a build running against it. `git stash create` writes a commit
+// object but must leave the index, the files, and the stash list alone.
+func TestPrepareLocalWorktreeLeavesUserTreeUntouched(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by user\n")
+ writeFile(t, filepath.Join(repo, "brand-new.txt"), "untracked\n")
+ statusBefore := gitRun(t, repo, "status", "--porcelain")
+
+ prepareForTest(t, repo)
+
+ if got := readFile(t, filepath.Join(repo, "tracked.txt")); got != "edited by user\n" {
+ t.Errorf("user's file changed: got %q", got)
+ }
+ if got := gitRun(t, repo, "status", "--porcelain"); got != statusBefore {
+ t.Errorf("user's git status changed:\nbefore %q\nafter %q", statusBefore, got)
+ }
+ if got := gitRun(t, repo, "stash", "list"); got != "" {
+ t.Errorf("stash list should stay empty, got %q", got)
+ }
+}
+
+// The deliverable is a branch. Whatever the agent leaves uncommitted must be
+// committed onto it before the worktree is removed, or `git worktree remove
+// --force` would delete the work with no way back.
+func TestFinalizeCommitsLeftoversAndKeepsBranch(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+
+ writeFile(t, filepath.Join(wt.Path, "agent-output.txt"), "work product\n")
+
+ outcome := finalizeOK(t, wt)
+
+ if !outcome.AutoCommitted {
+ t.Error("AutoCommitted = false, want true")
+ }
+ if outcome.Branch != wt.Branch {
+ t.Errorf("Branch = %q, want %q", outcome.Branch, wt.Branch)
+ }
+ if _, err := os.Stat(wt.Path); !os.IsNotExist(err) {
+ t.Errorf("worktree directory still present after Finalize: %v", err)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); strings.Contains(list, wt.Path) {
+ t.Errorf("worktree still registered in user's repo:\n%s", list)
+ }
+ // The branch must survive in the user's repo, carrying the agent's file.
+ if got := gitRun(t, repo, "show", wt.Branch+":agent-output.txt"); got != "work product" {
+ t.Errorf("branch does not carry agent output, got %q", got)
+ }
+ // The user's own checkout must be untouched by any of it.
+ if _, err := os.Stat(filepath.Join(repo, "agent-output.txt")); !os.IsNotExist(err) {
+ t.Error("agent output leaked into the user's working tree")
+ }
+}
+
+// A read-only task changes nothing. Leaving an empty branch behind for every
+// such run would turn `git branch` into noise, so the branch is dropped and the
+// result reports no branch at all.
+func TestFinalizeDropsBranchWhenNothingChanged(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+
+ outcome := finalizeOK(t, wt)
+
+ if outcome.Branch != "" {
+ t.Errorf("Branch = %q, want empty for a no-op task", outcome.Branch)
+ }
+ if outcome.AutoCommitted {
+ t.Error("AutoCommitted = true, want false")
+ }
+ if out, err := gitTry(t, repo, "rev-parse", "--verify", wt.Branch); err == nil {
+ t.Errorf("empty branch should have been deleted, still resolves to %s", out)
+ }
+}
+
+// The user's own uncommitted work must not be mistaken for the agent's output.
+// It is committed as a baseline at prepare time, so a task that changes nothing
+// still counts as a no-op and leaves no branch — the user's WIP is already safe
+// in their own working tree, and a branch duplicating it is pure noise.
+func TestFinalizeDropsBranchWhenOnlyBaseWasDirty(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by user\n")
+ writeFile(t, filepath.Join(repo, "scratch.txt"), "untracked scratch\n")
+ wt := prepareForTest(t, repo)
+
+ // The baseline must be a commit of its own, not left as pending changes.
+ if wt.BaseCommit == "" {
+ t.Fatal("no baseline commit recorded for a dirty base")
+ }
+ if dirty, err := worktreeIsDirty(wt.Path); err != nil || dirty {
+ t.Errorf("worktree still dirty after baseline commit (dirty=%v, err=%v)", dirty, err)
+ }
+
+ outcome := finalizeOK(t, wt)
+
+ if outcome.Branch != "" {
+ t.Errorf("Branch = %q, want empty: the agent changed nothing", outcome.Branch)
+ }
+ if outcome.AutoCommitted {
+ t.Error("AutoCommitted = true, but there was nothing of the agent's to commit")
+ }
+}
+
+// With a dirty base, the delivered branch separates the two authorships: the
+// user's WIP is the baseline commit, the agent's work sits on top. That is what
+// makes `git diff <baseline>..<branch>` a readable review of the agent alone.
+func TestFinalizeSeparatesUserBaselineFromAgentWork(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by user\n")
+ wt := prepareForTest(t, repo)
+
+ writeFile(t, filepath.Join(wt.Path, "agent-output.txt"), "work product\n")
+ outcome := finalizeOK(t, wt)
+
+ if outcome.Branch == "" {
+ t.Fatal("no branch delivered for a task that changed a file")
+ }
+ // The agent's commit alone.
+ agentFiles := gitRun(t, repo, "diff", "--name-only", wt.BaseCommit, outcome.Branch)
+ if agentFiles != "agent-output.txt" {
+ t.Errorf("agent diff = %q, want just agent-output.txt", agentFiles)
+ }
+ // And the user's uncommitted edit still reached the branch.
+ if got := gitRun(t, repo, "show", outcome.Branch+":tracked.txt"); got != "edited by user" {
+ t.Errorf("branch lost the user's uncommitted edit, got %q", got)
+ }
+}
+
+// A resource may point at a subdirectory of a repo. The worktree covers the
+// whole repo, but the agent has to land at the same depth the user chose.
+func TestPrepareLocalWorktreeSubdirectory(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, "services/api/main.go"), "package main\n")
+ gitRun(t, repo, "add", ".")
+ gitRun(t, repo, "commit", "-m", "add service")
+
+ sub := filepath.Join(repo, "services/api")
+ wt := prepareForTest(t, sub)
+
+ if wt.GitRoot != repo {
+ t.Errorf("GitRoot = %q, want repo root %q", wt.GitRoot, repo)
+ }
+ want := filepath.Join(wt.Path, "services", "api")
+ if wt.WorkDir != want {
+ t.Errorf("WorkDir = %q, want %q", wt.WorkDir, want)
+ }
+ if got := readFile(t, filepath.Join(wt.WorkDir, "main.go")); got != "package main\n" {
+ t.Errorf("subdirectory content missing from worktree: %q", got)
+ }
+}
+
+// Worktree mode is opt-in per resource, so a non-git directory means the user
+// configured something that cannot work. Fail with an actionable message rather
+// than silently running in-place, which would leave them wondering why their
+// tasks still queue one at a time.
+func TestPrepareLocalWorktreeRejectsNonGitDirectory(t *testing.T) {
+ _, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: t.TempDir(),
+ EnvRoot: t.TempDir(),
+ TaskID: "task-1",
+ }, worktreeTestLogger())
+ if err == nil {
+ t.Fatal("expected an error for a non-git directory")
+ }
+ if !strings.Contains(err.Error(), "not a git repository") || !strings.Contains(err.Error(), "in_place") {
+ t.Errorf("error should name the problem and the fix, got: %v", err)
+ }
+}
+
+// A repo with no commits has nothing to branch from. The message has to say so,
+// because "git worktree add failed" alone sends the user hunting in the wrong
+// place.
+func TestPrepareLocalWorktreeRejectsRepoWithoutCommits(t *testing.T) {
+ dir := t.TempDir()
+ gitRun(t, dir, "init", "-b", "main")
+
+ _, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: dir,
+ EnvRoot: t.TempDir(),
+ TaskID: "task-1",
+ }, worktreeTestLogger())
+ if err == nil {
+ t.Fatal("expected an error for a repo with no commits")
+ }
+ if !strings.Contains(err.Error(), "no commit") {
+ t.Errorf("error should explain the missing commit, got: %v", err)
+ }
+}
+
+// Concurrency is the entire point of the mode: two tasks on one directory must
+// both get a working checkout, with distinct branches, without corrupting git's
+// admin files.
+func TestPrepareLocalWorktreeConcurrentTasks(t *testing.T) {
+ repo := newTestRepo(t)
+
+ const tasks = 4
+ var (
+ wg sync.WaitGroup
+ mu sync.Mutex
+ results []*LocalWorktree
+ errs []error
+ )
+ for i := range tasks {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ wt, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: repo,
+ EnvRoot: t.TempDir(),
+ AgentName: "J",
+ TaskID: strings.Repeat(string(rune('a'+i)), 8),
+ }, worktreeTestLogger())
+ mu.Lock()
+ defer mu.Unlock()
+ if err != nil {
+ errs = append(errs, err)
+ return
+ }
+ results = append(results, wt)
+ }(i)
+ }
+ wg.Wait()
+
+ for _, err := range errs {
+ t.Errorf("concurrent prepare failed: %v", err)
+ }
+ if len(results) != tasks {
+ t.Fatalf("got %d worktrees, want %d", len(results), tasks)
+ }
+ branches := map[string]bool{}
+ for _, wt := range results {
+ if branches[wt.Branch] {
+ t.Errorf("duplicate branch %q across concurrent tasks", wt.Branch)
+ }
+ branches[wt.Branch] = true
+ if got := readFile(t, filepath.Join(wt.Path, "tracked.txt")); got != "original\n" {
+ t.Errorf("worktree %s has wrong content: %q", wt.Path, got)
+ }
+ }
+ for _, wt := range results {
+ finalizeOK(t, wt)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); strings.Count(list, "\n") != 0 {
+ t.Errorf("worktrees left registered after finalize:\n%s", list)
+ }
+}
+
+// End-to-end shape of a worktree-mode task: Prepare builds the env and writes
+// its sidecars into the worktree, the daemon's cleanup pass removes them, and
+// Finalize delivers a branch carrying only the agent's real work. The
+// sidecar-free branch is the user-visible contract — a diff full of
+// .agent_context/ scaffolding would make the mode unusable for review.
+func TestWorktreeModeDeliversBranchWithoutSidecars(t *testing.T) {
+ repo := newTestRepo(t)
+ // Start dirty, so the branch gets a baseline commit as well as the agent's
+ // own — a sidecar could otherwise hide in either one.
+ writeFile(t, filepath.Join(repo, "tracked.txt"), "edited by user\n")
+ originalHead := gitRun(t, repo, "rev-parse", "HEAD")
+ envRoot := filepath.Join(t.TempDir(), "env")
+
+ env, err := Prepare(PrepareParams{
+ WorkspacesRoot: filepath.Dir(envRoot),
+ WorkspaceID: "ws-1",
+ TaskID: "11112222-3333-4444-5555-666677778888",
+ AgentName: "J",
+ Provider: "claude",
+ LocalWorktree: &LocalWorktreeParams{LocalPath: repo},
+ Task: TaskContextForEnv{IssueID: "issue-1", AgentName: "J"},
+ }, worktreeTestLogger())
+ if err != nil {
+ t.Fatalf("Prepare: %v", err)
+ }
+ if env.LocalWorktree == nil {
+ t.Fatal("Prepare did not build a worktree")
+ }
+ // The env root is ordinary daemon-owned scratch in this mode, so the GC
+ // exemption meant for a user's own directory must not apply.
+ if env.LocalDirectory {
+ t.Error("LocalDirectory = true in worktree mode; the GC would exempt this env root forever")
+ }
+ if env.WorkDir != env.LocalWorktree.Path {
+ t.Errorf("WorkDir = %q, want the worktree root %q", env.WorkDir, env.LocalWorktree.Path)
+ }
+ if _, err := os.Stat(filepath.Join(env.WorkDir, ".agent_context")); err != nil {
+ t.Fatalf("precondition: Prepare should have written sidecars into the worktree: %v", err)
+ }
+
+ // The agent's actual work.
+ writeFile(t, filepath.Join(env.WorkDir, "real-change.txt"), "actual work\n")
+
+ // What the daemon runs before Finalize.
+ if err := CleanupRuntimeConfig(env.WorkDir, "claude"); err != nil {
+ t.Fatalf("CleanupRuntimeConfig: %v", err)
+ }
+ if err := CleanupSidecars(env.RootDir); err != nil {
+ t.Fatalf("CleanupSidecars: %v", err)
+ }
+ outcome := finalizeOK(t, env.LocalWorktree)
+
+ if outcome.Branch == "" {
+ t.Fatal("no branch delivered for a task that changed a file")
+ }
+ // Every file the branch touches, across the baseline and agent commits.
+ files := gitRun(t, repo, "diff", "--name-only", originalHead, outcome.Branch)
+ if !strings.Contains(files, "real-change.txt") {
+ t.Errorf("branch is missing the agent's work:\n%s", files)
+ }
+ for _, sidecar := range []string{".agent_context", ".multica", "CLAUDE.md"} {
+ if strings.Contains(files, sidecar) {
+ t.Errorf("sidecar %q leaked into the delivered branch:\n%s", sidecar, files)
+ }
+ }
+ // The user's own checkout keeps exactly the edit it started with, and
+ // nothing the agent or the runtime produced.
+ if got := gitRun(t, repo, "status", "--porcelain"); got != "M tracked.txt" {
+ t.Errorf("user's working tree changed, want only their own edit:\n%s", got)
+ }
+}
+
+// A crashed daemon leaves a registration pointing at an env root that GC later
+// deletes. The next task on the same repo must clean that up rather than
+// accumulating dead entries in the user's `git worktree list` forever.
+func TestPrepareLocalWorktreePrunesStaleRegistrations(t *testing.T) {
+ repo := newTestRepo(t)
+ orphanEnv := t.TempDir()
+ orphan, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: repo,
+ EnvRoot: orphanEnv,
+ AgentName: "J",
+ TaskID: "dead-task",
+ }, worktreeTestLogger())
+ if err != nil {
+ t.Fatalf("seed orphan worktree: %v", err)
+ }
+ // Simulate the crash: the directory disappears with GC, the registration
+ // survives in the user's repo.
+ if err := os.RemoveAll(orphan.Path); err != nil {
+ t.Fatalf("remove orphan worktree dir: %v", err)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); !strings.Contains(list, orphan.Path) {
+ t.Fatalf("precondition failed: orphan not registered:\n%s", list)
+ }
+
+ wt := prepareForTest(t, repo)
+ t.Cleanup(func() { finalizeOK(t, wt) })
+
+ if list := gitRun(t, repo, "worktree", "list"); strings.Contains(list, orphan.Path) {
+ t.Errorf("stale registration not pruned:\n%s", list)
+ }
+}
+
+// finalizeOK finalizes a worktree and fails the test if the work could not be
+// persisted. Tests that exercise the failure path call Finalize directly.
+func finalizeOK(t *testing.T, wt *LocalWorktree) LocalWorktreeOutcome {
+ t.Helper()
+ outcome, err := wt.Finalize(worktreeTestLogger())
+ if err != nil {
+ t.Fatalf("Finalize: %v", err)
+ }
+ return outcome
+}
+
+// The one operation in this flow that can destroy work is `git worktree remove
+// --force`. If the agent's changes could not be committed, removing the
+// worktree would delete the only copy — so Finalize must keep it and say so.
+// commit.gpgSign with no usable key is the realistic trigger: --no-verify does
+// not disable signing.
+func TestFinalizeKeepsWorktreeWhenCommitFails(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+
+ writeFile(t, filepath.Join(wt.Path, "agent-output.txt"), "irreplaceable work\n")
+
+ // Force every commit in this worktree to fail the way a signing setup the
+ // daemon can't satisfy would.
+ gitRun(t, wt.Path, "config", "commit.gpgSign", "true")
+ gitRun(t, wt.Path, "config", "gpg.program", filepath.Join(repo, "definitely-not-a-real-gpg"))
+
+ outcome, err := wt.Finalize(worktreeTestLogger())
+
+ if err == nil {
+ t.Fatal("Finalize returned nil error after the commit failed")
+ }
+ if outcome.PreservedPath != wt.Path {
+ t.Errorf("PreservedPath = %q, want %q", outcome.PreservedPath, wt.Path)
+ }
+ // The whole point: the work is still on disk.
+ if got := readFile(t, filepath.Join(wt.Path, "agent-output.txt")); got != "irreplaceable work\n" {
+ t.Errorf("agent work was destroyed despite the commit failure, got %q", got)
+ }
+ // And it stays discoverable through git rather than only a log line.
+ if list := gitRun(t, repo, "worktree", "list"); !strings.Contains(list, wt.Path) {
+ t.Errorf("preserved worktree is no longer registered, so the user cannot find it:\n%s", list)
+ }
+ if !strings.Contains(err.Error(), wt.Path) {
+ t.Errorf("error should name the preserved path, got: %v", err)
+ }
+}
+
+// An in_place task on the same directory leaves .agent_context/ and .multica/
+// in the user's tree while it runs. A concurrent worktree snapshot sees them as
+// untracked files; copying them would hand this task another issue's brief and
+// commit it to the branch.
+func TestPrepareLocalWorktreeSkipsMulticaSidecars(t *testing.T) {
+ repo := newTestRepo(t)
+ writeFile(t, filepath.Join(repo, ".agent_context", "issue_context.md"), "OTHER issue's brief\n")
+ writeFile(t, filepath.Join(repo, ".multica", "project", "resources.json"), "{}\n")
+ // An in_place resource may point at a SUBDIRECTORY of this repo, in which
+ // case its sidecars sit below that subdirectory, not at the repo root.
+ writeFile(t, filepath.Join(repo, "services", "api", ".agent_context", "issue_context.md"), "yet another issue's brief\n")
+ writeFile(t, filepath.Join(repo, "services", "api", ".multica", "task.json"), "{}\n")
+ writeFile(t, filepath.Join(repo, "real-untracked.txt"), "user's own file\n")
+ writeFile(t, filepath.Join(repo, "services", "api", "notes.txt"), "user's nested file\n")
+
+ wt := prepareForTest(t, repo)
+ t.Cleanup(func() { finalizeOK(t, wt) })
+
+ if _, err := os.Stat(filepath.Join(wt.Path, ".agent_context")); !os.IsNotExist(err) {
+ t.Error("another task's .agent_context was copied into this worktree")
+ }
+ if _, err := os.Stat(filepath.Join(wt.Path, ".multica")); !os.IsNotExist(err) {
+ t.Error("another task's .multica was copied into this worktree")
+ }
+ if _, err := os.Stat(filepath.Join(wt.Path, "services", "api", ".agent_context")); !os.IsNotExist(err) {
+ t.Error("a subdirectory task's .agent_context was copied into this worktree")
+ }
+ if _, err := os.Stat(filepath.Join(wt.Path, "services", "api", ".multica")); !os.IsNotExist(err) {
+ t.Error("a subdirectory task's .multica was copied into this worktree")
+ }
+ if got := readFile(t, filepath.Join(wt.Path, "real-untracked.txt")); got != "user's own file\n" {
+ t.Errorf("the user's own untracked file was not replayed: %q", got)
+ }
+ if got := readFile(t, filepath.Join(wt.Path, "services", "api", "notes.txt")); got != "user's nested file\n" {
+ t.Errorf("the user's nested untracked file was not replayed: %q", got)
+ }
+}
+
+// Silently starting from HEAD when the user's uncommitted state cannot be
+// replayed would have the agent review code the user never wrote and report on
+// it confidently. Refusing to start is the recoverable outcome.
+func TestPrepareLocalWorktreeFailsWhenUntrackedReplayIsTruncated(t *testing.T) {
+ repo := newTestRepo(t)
+ // One file over the copy budget is enough to prove the bound fails closed
+ // rather than under-copying; writing 2001 files would only be slower.
+ big := strings.Repeat("x", 1024)
+ for i := range maxUntrackedFiles + 1 {
+ writeFile(t, filepath.Join(repo, "untracked", "f"+string(rune('a'+i%26))+strings.Repeat("z", i/26)+".txt"), big)
+ }
+
+ _, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: repo,
+ EnvRoot: t.TempDir(),
+ AgentName: "J",
+ TaskID: "task-truncated",
+ }, worktreeTestLogger())
+
+ if err == nil {
+ t.Fatal("expected prepare to fail rather than replay a truncated tree")
+ }
+ if !strings.Contains(err.Error(), "in_place") {
+ t.Errorf("error should offer a way out, got: %v", err)
+ }
+ // A failed prepare must not leave a half-built worktree registered.
+ if list := gitRun(t, repo, "worktree", "list"); strings.Count(list, "\n") != 0 {
+ t.Errorf("aborted prepare left a worktree registered:\n%s", list)
+ }
+ if branches := gitRun(t, repo, "branch", "--list", "agent/*"); branches != "" {
+ t.Errorf("aborted prepare left a branch behind: %q", branches)
+ }
+}
+
+// Worktree tasks get a fresh env root per task ID, exactly like in_place ones
+// (shouldReusePriorWorkdir refuses any local assignment). So they need the same
+// per-issue Codex session store: without it, each comment turn on an issue
+// starts a new empty CODEX_HOME, the prior rollout is invisible, and the agent
+// silently loses the conversation it was having with the user.
+func TestPrepareWorktreeModeUsesPerIssueCodexSessionStore(t *testing.T) {
+ repo := newTestRepo(t)
+ workspacesRoot := t.TempDir()
+ codexHome := t.TempDir()
+ t.Setenv("CODEX_HOME", codexHome)
+
+ prepareTurn := func(taskID string) *Environment {
+ t.Helper()
+ env, err := Prepare(PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: "ws-1",
+ TaskID: taskID,
+ AgentName: "J",
+ Provider: "codex",
+ LocalWorktree: &LocalWorktreeParams{LocalPath: repo},
+ Task: TaskContextForEnv{IssueID: "issue-1", AgentID: "agent-1", AgentName: "J"},
+ }, worktreeTestLogger())
+ if err != nil {
+ t.Fatalf("Prepare(%s): %v", taskID, err)
+ }
+ t.Cleanup(func() { finalizeOK(t, env.LocalWorktree) })
+ return env
+ }
+
+ // Two turns on the same issue, different task IDs — the shape of a
+ // follow-up comment.
+ first := prepareTurn("aaaa1111-2222-3333-4444-555566667777")
+ second := prepareTurn("bbbb1111-2222-3333-4444-555566667777")
+
+ sessionsOf := func(env *Environment) string {
+ t.Helper()
+ target, err := filepath.EvalSymlinks(filepath.Join(env.CodexHome, "sessions"))
+ if err != nil {
+ t.Fatalf("resolve sessions dir: %v", err)
+ }
+ return target
+ }
+
+ firstSessions := sessionsOf(first)
+ secondSessions := sessionsOf(second)
+ if firstSessions != secondSessions {
+ t.Errorf("each turn got its own sessions dir, so Codex cannot resume:\n first %s\n second %s",
+ firstSessions, secondSessions)
+ }
+ // And it must be the stable per-issue store, not a task-local directory.
+ if strings.Contains(firstSessions, shortID("aaaa1111-2222-3333-4444-555566667777")) {
+ t.Errorf("sessions dir is task-scoped (%s); it will not survive the next turn", firstSessions)
+ }
+}
+
+// The daemon runs its sidecar cleanup before Finalize commits. If that cleanup
+// fails, committing anyway would deliver a branch whose content is Multica's
+// own runtime files — the exact leak this mode promises to prevent. The abort
+// must therefore stop the commit AND keep the worktree, since the agent's work
+// is still in it.
+func TestFinalizeAbortRefusesToCommitAndKeepsWorktree(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+
+ writeFile(t, filepath.Join(wt.Path, "agent-output.txt"), "real work\n")
+ writeFile(t, filepath.Join(wt.Path, ".agent_context", "issue_context.md"), "runtime brief\n")
+
+ wt.AbortWithReason(errors.New("cleanup failed"))
+ outcome, err := wt.Finalize(worktreeTestLogger())
+
+ if err == nil {
+ t.Fatal("Finalize returned nil error after an abort")
+ }
+ if outcome.Branch != "" {
+ t.Errorf("Branch = %q, want empty: nothing may be delivered after an abort", outcome.Branch)
+ }
+ if outcome.AutoCommitted {
+ t.Error("AutoCommitted = true; the abort must prevent the commit")
+ }
+ if outcome.PreservedPath != wt.Path {
+ t.Errorf("PreservedPath = %q, want %q", outcome.PreservedPath, wt.Path)
+ }
+ // Nothing committed: the branch must still be sitting on its base.
+ tip := gitRun(t, repo, "rev-parse", wt.Branch)
+ if tip != wt.BaseCommit {
+ t.Errorf("branch moved to %s; the sidecar-carrying commit was delivered anyway", tip)
+ }
+ // And the work is still recoverable on disk.
+ if got := readFile(t, filepath.Join(wt.Path, "agent-output.txt")); got != "real work\n" {
+ t.Errorf("agent work was destroyed: %q", got)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); !strings.Contains(list, wt.Path) {
+ t.Errorf("preserved worktree is no longer registered:\n%s", list)
+ }
+}
+
+// The first reason is the one closest to the root cause, so later aborts must
+// not overwrite it.
+func TestAbortWithReasonKeepsFirstReason(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+ t.Cleanup(func() { removeLocalWorktreeDir(repo, wt.Path, worktreeTestLogger()) })
+
+ wt.AbortWithReason(errors.New("first"))
+ wt.AbortWithReason(errors.New("second"))
+ wt.AbortWithReason(nil)
+
+ _, err := wt.Finalize(worktreeTestLogger())
+ if err == nil || !strings.Contains(err.Error(), "first") {
+ t.Fatalf("want the first reason preserved, got: %v", err)
+ }
+ if strings.Contains(err.Error(), "second") {
+ t.Errorf("later abort overwrote the original reason: %v", err)
+ }
+}
+
+// An untracked symlink is content the user can see. Replaying it faithfully is
+// ambiguous (link vs target, targets outside the repo), so the snapshot must
+// fail rather than hand the agent a tree with a file quietly missing.
+func TestPrepareLocalWorktreeFailsOnUntrackedSymlink(t *testing.T) {
+ repo := newTestRepo(t)
+ if err := os.Symlink(filepath.Join(repo, "tracked.txt"), filepath.Join(repo, "shortcut.txt")); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+
+ _, err := PrepareLocalWorktree(LocalWorktreeParams{
+ LocalPath: repo,
+ EnvRoot: t.TempDir(),
+ AgentName: "J",
+ TaskID: "task-symlink",
+ }, worktreeTestLogger())
+
+ if err == nil {
+ t.Fatal("expected prepare to fail rather than silently drop the symlink")
+ }
+ if !strings.Contains(err.Error(), "untracked") {
+ t.Errorf("error should name the untracked replay, got: %v", err)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); strings.Count(list, "\n") != 0 {
+ t.Errorf("aborted prepare left a worktree registered:\n%s", list)
+ }
+}
+
+// Discard is the abandon path for a Prepare that fails after the worktree
+// exists. Without it every such failure leaves a registration in the user's
+// repo and a branch no task ever ran in.
+func TestDiscardRemovesWorktreeAndBranch(t *testing.T) {
+ repo := newTestRepo(t)
+ wt := prepareForTest(t, repo)
+
+ wt.Discard(worktreeTestLogger())
+
+ if _, err := os.Stat(wt.Path); !os.IsNotExist(err) {
+ t.Errorf("worktree directory survived Discard: %v", err)
+ }
+ if list := gitRun(t, repo, "worktree", "list"); strings.Contains(list, wt.Path) {
+ t.Errorf("worktree still registered after Discard:\n%s", list)
+ }
+ if out, err := gitTry(t, repo, "rev-parse", "--verify", wt.Branch); err == nil {
+ t.Errorf("branch survived Discard, resolves to %s", out)
+ }
+}
diff --git a/server/internal/daemon/local_directory.go b/server/internal/daemon/local_directory.go
index 6e78e4266e..78989191b9 100644
--- a/server/internal/daemon/local_directory.go
+++ b/server/internal/daemon/local_directory.go
@@ -19,13 +19,23 @@ import (
// constant — keep in sync if the type string is ever renamed.
const localDirectoryResourceType = "local_directory"
+// Execution modes for local_directory resources. Mirrors the server-side
+// constants in handler/project_resource.go — keep in sync. An absent or empty
+// value means in_place, so resources created before worktree mode existed keep
+// their original behavior.
+const (
+ localDirectoryModeInPlace = "in_place"
+ localDirectoryModeWorktree = "worktree"
+)
+
// localDirectoryRef mirrors the server-side ref shape for local_directory
// project resources. Defined locally so the daemon does not have to import
// the server handler package.
type localDirectoryRef struct {
- LocalPath string `json:"local_path"`
- DaemonID string `json:"daemon_id"`
- Label string `json:"label,omitempty"`
+ LocalPath string `json:"local_path"`
+ DaemonID string `json:"daemon_id"`
+ Label string `json:"label,omitempty"`
+ ExecutionMode string `json:"execution_mode,omitempty"`
}
// localDirectoryAssignment is the resolved view of a task's local_directory
@@ -40,6 +50,40 @@ type localDirectoryAssignment struct {
RealPath string // canonical key for the path mutex
}
+// UsesWorktree reports whether this assignment runs each task in its own git
+// worktree instead of in the user's directory. Worktree tasks skip the per-path
+// mutex entirely — that is the whole point of the mode — so every caller that
+// serialises, cleans up sidecars, or exempts the env root from GC must branch
+// on this rather than on "is there a local_directory assignment at all".
+func (a *localDirectoryAssignment) UsesWorktree() bool {
+ return a != nil && strings.TrimSpace(a.Ref.ExecutionMode) == localDirectoryModeWorktree
+}
+
+// ValidateExecutionMode rejects a mode this daemon does not implement.
+//
+// Falling back to in_place would be the wrong direction, even though it is the
+// older and more conservative code path. execution_mode is how a user asks for
+// ISOLATION, not merely for concurrency: silently running in_place instead
+// would let the agent edit the working copy the user explicitly asked it to
+// stay out of. Losing concurrency is a nuisance; ignoring a request to not
+// touch someone's files is a broken promise. So an unrecognised mode fails the
+// task with a message naming the version skew.
+func (a *localDirectoryAssignment) ValidateExecutionMode() error {
+ if a == nil {
+ return nil
+ }
+ switch strings.TrimSpace(a.Ref.ExecutionMode) {
+ case "", localDirectoryModeInPlace, localDirectoryModeWorktree:
+ return nil
+ default:
+ return fmt.Errorf(
+ "local_directory: this daemon does not support execution_mode %q for %q "+
+ "(update the daemon, or set the resource's execution mode to %q or %q); "+
+ "refusing to run in place, since that would modify a directory the resource asked to isolate",
+ a.Ref.ExecutionMode, a.AbsPath, localDirectoryModeInPlace, localDirectoryModeWorktree)
+ }
+}
+
// localDirectoryAssignmentForTask returns the local_directory assignment a task
// should execute inside. Squad-leader tasks are coordinators: they may create
// child issues or comments, but should not bind to the user's repo worktree or
diff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.go
index 5e6ade895a..5815d59bf7 100644
--- a/server/internal/daemon/local_directory_test.go
+++ b/server/internal/daemon/local_directory_test.go
@@ -791,3 +791,177 @@ func TestAcquireLocalDirectoryLock_EarlyFailureReportsWithCancelledParent(t *tes
t.Fatalf("fail callback calls = %d, want %d", got, len(tests))
}
}
+
+// Worktree mode exists to let sibling tasks on one directory run at the same
+// time, so the per-path mutex must not be taken at all. If it were, the mode
+// would look implemented while still serialising every task.
+func TestAcquireLocalDirectoryLockSkipsWorktreeMode(t *testing.T) {
+ t.Parallel()
+
+ const daemonID = "d-mine"
+ tmp := t.TempDir()
+ raw, err := json.Marshal(localDirectoryRef{
+ LocalPath: tmp,
+ DaemonID: daemonID,
+ ExecutionMode: localDirectoryModeWorktree,
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ resources := []ProjectResourceData{
+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: raw},
+ }
+
+ assignment, err := localDirectoryAssignmentForTask(Task{ID: "t1", ProjectResources: resources}, daemonID)
+ if err != nil {
+ t.Fatalf("assignment: %v", err)
+ }
+ if !assignment.UsesWorktree() {
+ t.Fatal("UsesWorktree() = false for execution_mode=worktree")
+ }
+
+ d := &Daemon{
+ cfg: Config{DaemonID: daemonID},
+ localPathLocks: NewLocalPathLocker(),
+ logger: slog.Default(),
+ }
+
+ // Two tasks on the same path must both proceed without a release callback
+ // and without either becoming the lock holder.
+ for _, taskID := range []string{"task-a", "task-b"} {
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(
+ context.Background(),
+ Task{ID: taskID, ProjectResources: resources},
+ slog.Default(),
+ )
+ if abort {
+ t.Fatalf("%s: acquisition aborted", taskID)
+ }
+ if release != nil {
+ t.Fatalf("%s: got a release callback, so the path mutex was taken", taskID)
+ }
+ }
+ if got := d.localPathLocks.Holder(assignment.RealPath); got != "" {
+ t.Fatalf("holder = %q, want empty: worktree mode must not lock the path", got)
+ }
+}
+
+// The default and any unrecognised mode must keep the historical exclusive
+// lock. Failing open here would let a daemon older than the resource run two
+// tasks in one directory at once.
+func TestUsesWorktreeDefaultsToExclusive(t *testing.T) {
+ t.Parallel()
+
+ cases := []struct {
+ mode string
+ want bool
+ }{
+ {"", false},
+ {localDirectoryModeInPlace, false},
+ {localDirectoryModeWorktree, true},
+ {" worktree ", true},
+ {"snapshot", false},
+ {"WORKTREE", false},
+ }
+ for _, tc := range cases {
+ a := &localDirectoryAssignment{Ref: localDirectoryRef{ExecutionMode: tc.mode}}
+ if got := a.UsesWorktree(); got != tc.want {
+ t.Errorf("UsesWorktree(%q) = %v, want %v", tc.mode, got, tc.want)
+ }
+ }
+ var nilAssignment *localDirectoryAssignment
+ if nilAssignment.UsesWorktree() {
+ t.Error("UsesWorktree() on nil assignment = true, want false")
+ }
+}
+
+// An unknown execution_mode means the resource was written by a newer server
+// than this daemon. Running in_place anyway would edit the very directory the
+// user asked to be isolated from, so the task must fail instead.
+func TestAcquireLocalDirectoryLockRejectsUnknownExecutionMode(t *testing.T) {
+ t.Parallel()
+
+ const daemonID = "d-mine"
+ tmp := t.TempDir()
+ raw, err := json.Marshal(localDirectoryRef{
+ LocalPath: tmp,
+ DaemonID: daemonID,
+ ExecutionMode: "snapshot", // a mode only a future daemon implements
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ resources := []ProjectResourceData{
+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: raw},
+ }
+
+ assignment, err := localDirectoryAssignmentForTask(Task{ID: "t1", ProjectResources: resources}, daemonID)
+ if err != nil {
+ t.Fatalf("assignment: %v", err)
+ }
+ if assignment.UsesWorktree() {
+ t.Fatal("an unknown mode must not be treated as worktree")
+ }
+ modeErr := assignment.ValidateExecutionMode()
+ if modeErr == nil {
+ t.Fatal("ValidateExecutionMode accepted an unknown mode")
+ }
+ if !strings.Contains(modeErr.Error(), "snapshot") {
+ t.Errorf("error should name the unsupported mode, got: %v", modeErr)
+ }
+
+ // The daemon must report the task as failed rather than quietly running it.
+ var failCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.HasSuffix(r.URL.Path, "/fail") {
+ failCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ t.Errorf("unexpected daemon call: %s %s", r.Method, r.URL.Path)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ locker := NewLocalPathLocker()
+ d := &Daemon{
+ cfg: Config{DaemonID: daemonID},
+ client: NewClient(srv.URL),
+ localPathLocks: locker,
+ logger: slog.Default(),
+ }
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(
+ context.Background(),
+ Task{ID: "t1", ProjectResources: resources},
+ slog.Default(),
+ )
+ if !abort {
+ t.Error("abort = false; the task was allowed to run with an unsupported mode")
+ }
+ if release != nil {
+ t.Error("an aborted task must not hold the path lock")
+ }
+ if failCalls.Load() == 0 {
+ t.Error("the task was not reported as failed, so the skew would be invisible")
+ }
+ if got := locker.Holder(assignment.RealPath); got != "" {
+ t.Errorf("holder = %q, want empty after an aborted task", got)
+ }
+}
+
+// Known modes must keep working — the guard above must not become a blanket
+// rejection.
+func TestValidateExecutionModeAcceptsKnownModes(t *testing.T) {
+ t.Parallel()
+
+ for _, mode := range []string{"", localDirectoryModeInPlace, localDirectoryModeWorktree, " worktree "} {
+ a := &localDirectoryAssignment{Ref: localDirectoryRef{ExecutionMode: mode}}
+ if err := a.ValidateExecutionMode(); err != nil {
+ t.Errorf("ValidateExecutionMode(%q) = %v, want nil", mode, err)
+ }
+ }
+ var nilAssignment *localDirectoryAssignment
+ if err := nilAssignment.ValidateExecutionMode(); err != nil {
+ t.Errorf("nil assignment should validate, got %v", err)
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index cdd731bac4..196fb9e5ce 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -347,7 +347,13 @@ type AgentTaskResponse struct {
// when WorkDir is empty, or when stripping leaves nothing. See
// relativeWorkDir() for the full rules. Older clients can still read
// WorkDir directly; newer UIs should prefer RelativeWorkDir.
- RelativeWorkDir string `json:"relative_work_dir,omitempty"`
+ RelativeWorkDir string `json:"relative_work_dir,omitempty"`
+ // BranchName is the git branch this run delivered its work on, set only by
+ // worktree-mode local_directory tasks. Unlike WorkDir it is safe to show
+ // verbatim: it is a ref inside the user's own repo, not a filesystem path.
+ // Populated on both terminal paths — a failed run can still have committed
+ // partial work, and that is when the pointer matters most.
+ BranchName string `json:"branch_name,omitempty"`
TriggerCommentID *string `json:"trigger_comment_id,omitempty"` // comment that triggered this task
CoalescedCommentIDs []string `json:"coalesced_comment_ids,omitempty"` // MUL-4195: earlier comments folded into this run when it had not yet started, so a single run still covers every deliberate comment; trigger_comment_id is the newest. Surfaced so the UI can show which comments a run covered. omitempty so old clients ignore it
CoalescedComments []CoalescedCommentData `json:"coalesced_comments,omitempty"` // MUL-4195: full detail (thread_id/author/created_at/content) of the folded comments, so the daemon prompt can address each without assuming they share the triggering thread. omitempty so old clients ignore it
@@ -669,6 +675,10 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
if t.HandoffNote.Valid {
handoffNote = t.HandoffNote.String
}
+ branchName := ""
+ if t.BranchName.Valid {
+ branchName = t.BranchName.String
+ }
return AgentTaskResponse{
ID: uuidToString(t.ID),
AgentID: uuidToString(t.AgentID),
@@ -683,6 +693,7 @@ func taskToResponse(t db.AgentTaskQueue, workspaceID string) AgentTaskResponse {
Result: result,
Error: textToPtr(t.Error),
FailureReason: failureReason,
+ BranchName: branchName,
Attempt: t.Attempt,
MaxAttempts: t.MaxAttempts,
ParentTaskID: uuidToPtr(t.ParentTaskID),
diff --git a/server/internal/handler/chat_attachment_reply_test.go b/server/internal/handler/chat_attachment_reply_test.go
index 65e7299adc..7c9d5d9f16 100644
--- a/server/internal/handler/chat_attachment_reply_test.go
+++ b/server/internal/handler/chat_attachment_reply_test.go
@@ -277,7 +277,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"here is the chart"}`), "", "", false, ""); err != nil {
+ parseUUID(taskID), []byte(`{"output":"here is the chart"}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
msgID, content, ok := assistantMessageForTask(t, taskID)
@@ -298,7 +298,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":""}`), "", "", false, ""); err != nil {
+ parseUUID(taskID), []byte(`{"output":""}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
msgID, content, ok := assistantMessageForTask(t, taskID)
@@ -317,7 +317,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
t.Run("empty output + no attachment creates no message", func(t *testing.T) {
taskID := seedRunningChatTask(t, agentID, sessionID)
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":""}`), "", "", false, ""); err != nil {
+ parseUUID(taskID), []byte(`{"output":""}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if _, _, ok := assistantMessageForTask(t, taskID); ok {
@@ -340,7 +340,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, looseID) })
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
if got := attachmentMessageID(t, looseID); got != nil {
@@ -378,7 +378,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
}
if _, err := testHandler.TaskService.CompleteTask(context.Background(),
- parseUUID(taskID), []byte(`{"output":"done"}`), "", "", false, ""); err != nil {
+ parseUUID(taskID), []byte(`{"output":"done"}`), "", "", "", false, ""); err != nil {
t.Fatalf("CompleteTask: %v", err)
}
got := attachmentMessageID(t, claimedID)
@@ -391,7 +391,7 @@ func TestCompleteTask_BindsChatAttachments(t *testing.T) {
taskID := seedRunningChatTask(t, agentID, sessionID)
attID := seedAgentChatAttachment(t, agentID, sessionID, taskID)
if _, err := testHandler.TaskService.FailTask(context.Background(),
- parseUUID(taskID), "agent crashed", "", "", "", false, ""); err != nil {
+ parseUUID(taskID), "agent crashed", "", "", "", "", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
if got := attachmentMessageID(t, attID); got != nil {
diff --git a/server/internal/handler/chat_channel_debounce_boundary_test.go b/server/internal/handler/chat_channel_debounce_boundary_test.go
index 72bbc07d7d..9748fbf7b6 100644
--- a/server/internal/handler/chat_channel_debounce_boundary_test.go
+++ b/server/internal/handler/chat_channel_debounce_boundary_test.go
@@ -115,7 +115,7 @@ func TestChannelChat_ReplyLandingInsideDebounceWindowStillAnswersTheNextMessage(
stranded := appendChannelUserMessage(t, ctx, sessionID, "挺好的 正常了")
// Turn 1 finishes inside that window and writes its reply.
- if _, err := testHandler.TaskService.CompleteTask(ctx, first.ID, completeResult(t, "通了。"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, first.ID, completeResult(t, "通了。"), "", "", "", false, ""); err != nil {
t.Fatalf("complete turn 1: %v", err)
}
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 86ad691f68..cfe9422f99 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -120,7 +120,7 @@ func TestDirectChat_TaskOwnsItsOwnInputBatch(t *testing.T) {
// coalesced pair. The claim leaves T1 dispatched; move it to running so the
// completion CAS (WHERE status='running') applies.
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "上海晴"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "上海晴"), "", "", "", false, ""); err != nil {
t.Fatalf("complete first task: %v", err)
}
claimed2 := claimTaskForRuntimeGuard(t, runtimeID, daemonID)
@@ -166,7 +166,7 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
t.Fatalf("claim moved already-visible A from %s to %s", inputABeforeClaim[0].CreatedAt.Time, inputAAfterClaim[0].CreatedAt.Time)
}
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "assistant A"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "assistant A"), "", "", "", false, ""); err != nil {
t.Fatalf("complete turn A: %v", err)
}
transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
@@ -239,7 +239,7 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
}
markTaskRunning(t, ctx, t2)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "assistant B"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "assistant B"), "", "", "", false, ""); err != nil {
t.Fatalf("complete turn B: %v", err)
}
transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
@@ -256,7 +256,7 @@ func TestDirectChat_ClaimKeepsQueuedTurnsPairedWithReplies(t *testing.T) {
assertChatTranscriptContents(t, transcript, []string{"user A", "assistant A", "user B", "assistant B", "user C"})
markTaskRunning(t, ctx, t3)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t3), completeResult(t, "assistant C"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t3), completeResult(t, "assistant C"), "", "", "", false, ""); err != nil {
t.Fatalf("complete turn C: %v", err)
}
transcript, err = testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
@@ -397,7 +397,7 @@ func TestCompleteTask_ChatEmptyOutputWritesNoResponse(t *testing.T) {
markTaskRunning(t, ctx, taskID)
// Whitespace-only output trims to empty → no_response.
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, " "), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, " "), "", "", "", false, ""); err != nil {
t.Fatalf("complete task: %v", err)
}
@@ -426,7 +426,7 @@ func TestCompleteTask_ChatNonEmptyOutputWritesMessage(t *testing.T) {
taskID := sendDirectChat(t, ctx, agentID, sessionID, "hello")
markTaskRunning(t, ctx, taskID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "hi there"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, "hi there"), "sess-1", "/tmp/wd", "", false, ""); err != nil {
t.Fatalf("complete task: %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -453,11 +453,11 @@ func TestCompleteTask_ChatCallbackIdempotent(t *testing.T) {
markTaskRunning(t, ctx, taskID)
res := completeResult(t, "reply")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", "", false, ""); err != nil {
t.Fatalf("first complete: %v", err)
}
// Replay: the status CAS fails, so this is an idempotent no-op success.
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), res, "", "", "", false, ""); err != nil {
t.Fatalf("replayed complete must be idempotent success, got %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 1 {
@@ -478,7 +478,7 @@ func TestFailTask_ChatRetryInheritsInputOwnerAndPriority(t *testing.T) {
rootID := sendDirectChat(t, ctx, agentID, sessionID, "root question")
markTaskRunning(t, ctx, rootID)
- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(rootID), "runtime went away", "", "", "runtime_offline", false, ""); err != nil {
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(rootID), "runtime went away", "", "", "", "runtime_offline", false, ""); err != nil {
t.Fatalf("fail task: %v", err)
}
@@ -533,7 +533,7 @@ func TestFailTask_ChatFailureKeepsNextTurnAfterOutcome(t *testing.T) {
sendDirectChat(t, ctx, agentID, sessionID, "user B")
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(t1), "assistant failure", "", "", "agent_error.unknown", false, ""); err != nil {
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(t1), "assistant failure", "", "", "", "agent_error.unknown", false, ""); err != nil {
t.Fatalf("fail turn A: %v", err)
}
transcript, err := testHandler.Queries.ListChatMessages(ctx, parseUUID(sessionID))
@@ -722,7 +722,7 @@ func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
// Empty output → no row at all.
emptyTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", "", false, ""); err != nil {
t.Fatalf("complete channel task (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
@@ -731,7 +731,7 @@ func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
// Non-empty output → one ordinary message (kind 'message', not no_response).
textTask := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "channel reply"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "channel reply"), "", "", "", false, ""); err != nil {
t.Fatalf("complete channel task (text): %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -757,7 +757,7 @@ func TestCompleteTask_SealedChannelEmptyOutputWritesNoRow(t *testing.T) {
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "sealed channel chat")
emptyTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "[Image]")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel task (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
@@ -766,7 +766,7 @@ func TestCompleteTask_SealedChannelEmptyOutputWritesNoRow(t *testing.T) {
// Non-empty output still writes one ordinary message.
textTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "hello")
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "sealed channel reply"), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "sealed channel reply"), "", "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel task (text): %v", err)
}
rows := assistantRows(t, ctx, sessionID)
@@ -797,7 +797,7 @@ func TestCompleteTask_SealedChannelRetryEmptyOutputWritesNoRow(t *testing.T) {
t.Fatalf("setup: create retry clone: %v", err)
}
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(retryTask), completeResult(t, ""), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(retryTask), completeResult(t, ""), "", "", "", false, ""); err != nil {
t.Fatalf("complete sealed channel retry (empty): %v", err)
}
if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
@@ -818,7 +818,7 @@ func TestCompleteTask_ChatQuickActions(t *testing.T) {
`[{"label":"Draft it","prompt":"Draft the complete plan","primary":true},` +
`{"label":"Make a checklist","prompt":"Turn this into a checklist"}]` +
"\n```"
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, output), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), completeResult(t, output), "", "", "", false, ""); err != nil {
t.Fatalf("complete task: %v", err)
}
@@ -848,7 +848,7 @@ func TestCompleteTask_ChatQuickActions(t *testing.T) {
actionsOnlyTask := sendDirectChat(t, ctx, agentID, sessionID, "give me options only")
markTaskRunning(t, ctx, actionsOnlyTask)
actionsOnly := "```quick-actions\n[{\"label\":\"Continue\",\"prompt\":\"Continue the plan\"}]\n```"
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(actionsOnlyTask), completeResult(t, actionsOnly), "", "", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(actionsOnlyTask), completeResult(t, actionsOnly), "", "", "", false, ""); err != nil {
t.Fatalf("complete actions-only task: %v", err)
}
rows = assistantRows(t, ctx, sessionID)
@@ -883,7 +883,7 @@ func TestCompleteTask_ChatQuickActionsSupplement(t *testing.T) {
if err != nil {
t.Fatalf("marshal complete request: %v", err)
}
- task, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), result, "", "", false, "")
+ task, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(taskID), result, "", "", "", false, "")
if err != nil {
t.Fatalf("complete task: %v", err)
}
@@ -962,7 +962,7 @@ func TestChatQuickActions_ContextAnchorsOnTargetTurn(t *testing.T) {
taskID := sendDirectChat(t, ctx, agentID, sessionID, "first question")
markTaskRunning(t, ctx, taskID)
task, err := testHandler.TaskService.CompleteTask(
- ctx, parseUUID(taskID), completeResult(t, "ANCHOR REPLY"), "", "", false, "")
+ ctx, parseUUID(taskID), completeResult(t, "ANCHOR REPLY"), "", "", "", false, "")
if err != nil {
t.Fatalf("complete turn 1: %v", err)
}
@@ -1028,7 +1028,7 @@ func TestRegenerateChatQuickActions_StaleTargetRejected(t *testing.T) {
// Turn 1: a resumable assistant reply (session_id + runtime bound) is latest.
t1 := sendDirectChat(t, ctx, agentID, sessionID, "first question")
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", "", false, ""); err != nil {
t.Fatalf("complete turn 1: %v", err)
}
session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
@@ -1055,7 +1055,7 @@ func TestRegenerateChatQuickActions_StaleTargetRejected(t *testing.T) {
// Turn 2 lands, so m1 is no longer the latest.
t2 := sendDirectChat(t, ctx, agentID, sessionID, "second question")
markTaskRunning(t, ctx, t2)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "second reply"), "sess-2", "/tmp/wd", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t2), completeResult(t, "second reply"), "sess-2", "/tmp/wd", "", false, ""); err != nil {
t.Fatalf("complete turn 2: %v", err)
}
session, err = testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
@@ -1095,7 +1095,7 @@ func TestRegenerateChatQuickActions_ActiveTurnRejected(t *testing.T) {
// Turn 1 completes with a resumable session → m1 is the latest assistant turn.
t1 := sendDirectChat(t, ctx, agentID, sessionID, "first")
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", "", false, ""); err != nil {
t.Fatalf("complete turn 1: %v", err)
}
session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
@@ -1137,7 +1137,7 @@ func TestRegenerateChatQuickActions_DeferredActiveTurnRejected(t *testing.T) {
t1 := sendDirectChat(t, ctx, agentID, sessionID, "first")
markTaskRunning(t, ctx, t1)
- if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", false, ""); err != nil {
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(t1), completeResult(t, "first reply"), "sess-1", "/tmp/wd", "", false, ""); err != nil {
t.Fatalf("complete turn 1: %v", err)
}
session, err := testHandler.Queries.GetChatSession(ctx, parseUUID(sessionID))
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index e1900bb7eb..810cc3b6a5 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -27,6 +27,7 @@ import (
"github.com/multica-ai/multica/server/internal/runtimeapps"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
+ agentpkg "github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
"github.com/multica-ai/multica/server/pkg/redact"
@@ -2686,9 +2687,102 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
)
}
+ // Last gate before dispatch: refuse to hand a worktree-mode local_directory
+ // task to a daemon that cannot implement the mode.
+ //
+ // The save-time gate in project_resource.go cannot cover this. It checks the
+ // version at the moment the resource is written; a machine downgraded
+ // afterwards still claims tasks, and an old daemon json-skips execution_mode
+ // entirely — it would run the task IN PLACE, editing the working copy the
+ // user asked to isolate. That is the exact outcome worktree mode exists to
+ // prevent, so it fails closed here, against the version of the runtime that
+ // is actually claiming.
+ if reason := worktreeClaimBlockReason(resp.ProjectResources, runtime); reason != "" {
+ slog.Error("task claim: runtime too old for worktree mode; cancelling rather than running in place",
+ "task_id", uuidToString(task.ID),
+ "runtime_id", runtimeID,
+ "daemon_id", runtime.DaemonID.String,
+ "reason", reason,
+ )
+ // Cancel rather than leave it dispatched: the resource is pinned to this
+ // daemon, so redelivery would hand it straight back to the same too-old
+ // runtime forever.
+ //
+ // Cancel WITH the reason persisted on the row. The 4xx below only
+ // reaches the daemon's log, and the batch-claim path drops the task from
+ // its response entirely — so without this the user is left with a task
+ // that says "cancelled" and nothing else, for a condition only they can
+ // fix (update the app on that machine).
+ //
+ // Through the TaskService, not a raw query: cancellation has side
+ // effects beyond the row — audit capture, chat settle, agent status
+ // reconcile, the task:cancelled broadcast that clears live cards, and
+ // NotifyTaskFinished waking capacity/serial waiters. A direct query
+ // leaves all of those stale.
+ if _, cerr := h.TaskService.CancelTaskWithReason(r.Context(), task.ID, reason, "local_directory_error"); cerr != nil {
+ // The cancel did not commit, so the row is still claimed. The
+ // daemon is about to be refused, so left alone the task would
+ // strand in dispatched until stale reclaim, with no visible
+ // reason. Requeue it instead — the next claim re-runs this gate
+ // and retries the cancel — and report a 5xx so the daemon reads
+ // this as a transient server problem, not a claim refusal.
+ slog.Error("task claim: cancel after worktree version gate failed; requeueing so the gate can run again",
+ "task_id", uuidToString(task.ID), "error", cerr)
+ if _, rerr := h.TaskService.RequeueTaskAfterClaimFailure(r.Context(), *task); rerr != nil {
+ slog.Error("task claim: requeue after worktree-gate cancel failure failed; stale reclaim will recover it",
+ "task_id", uuidToString(task.ID), "error", rerr)
+ }
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_worktree_gate_cancel",
+ status: http.StatusInternalServerError,
+ message: "failed to cancel a worktree task blocked by daemon version; task requeued",
+ }
+ }
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, &claimBuildFailure{
+ outcome: "error_worktree_daemon_version",
+ status: http.StatusUnprocessableEntity,
+ message: reason,
+ }
+ }
+
return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount, nil
}
+// worktreeClaimBlockReason returns a user-facing reason when this runtime must
+// not run the task, or "" when it may proceed.
+//
+// Only resources bound to the claiming runtime's own daemon are considered: a
+// project may carry one local_directory per machine, and another machine's
+// worktree resource says nothing about this one's ability to run the task.
+func worktreeClaimBlockReason(resources []ProjectResourceData, runtime db.AgentRuntime) string {
+ if !runtime.DaemonID.Valid || runtime.DaemonID.String == "" {
+ return ""
+ }
+ for _, res := range resources {
+ if res.ResourceType != "local_directory" {
+ continue
+ }
+ var ref localDirectoryRef
+ if err := json.Unmarshal(res.ResourceRef, &ref); err != nil {
+ continue
+ }
+ if ref.ExecutionMode != localDirectoryModeWorktree || ref.DaemonID != runtime.DaemonID.String {
+ continue
+ }
+ current := readRuntimeCLIVersion(runtime.Metadata)
+ if err := agentpkg.CheckMinCLIVersionFor(current, agentpkg.MinLocalWorktreeCLIVersion); err != nil {
+ shown := current
+ if strings.TrimSpace(shown) == "" {
+ shown = "unknown"
+ }
+ return fmt.Sprintf(
+ "this project's local directory %q is set to run tasks in isolated git worktrees, but the Multica runtime on that machine is %s and needs %s or newer; update it, or switch the resource back to in_place",
+ ref.LocalPath, shown, agentpkg.MinLocalWorktreeCLIVersion)
+ }
+ }
+ return ""
+}
+
// ClaimTaskByRuntime atomically claims the next queued task for a runtime.
// The response includes the agent's name and skills, fetched fresh from the DB.
func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
@@ -3115,6 +3209,10 @@ type TaskCompleteRequest struct {
Output string `json:"output"`
SessionID string `json:"session_id"` // Claude session ID for future resumption
WorkDir string `json:"work_dir"` // working directory used during execution
+ // BranchName is the branch this run delivered its work on. Worktree-mode
+ // local_directory tasks never touch the user's working copy, so this is the
+ // only pointer to where the changes went. Empty for every other task kind.
+ BranchName string `json:"branch_name,omitempty"`
// SessionRolloutMissing: the daemon withheld this task's Codex session
// because its rollout was missing (MUL-5305). Clear the resume pointer and
// flag the continuity gap for the next claim.
@@ -3158,10 +3256,14 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
"failure_reason", taskfailure.ReasonAgentContextOverflow,
)
h.failTask(w, r, taskID, workspaceID, TaskFailRequest{
- Error: req.Output,
- FailureReason: string(taskfailure.ReasonAgentContextOverflow),
- SessionID: req.SessionID,
- WorkDir: req.WorkDir,
+ Error: req.Output,
+ FailureReason: string(taskfailure.ReasonAgentContextOverflow),
+ SessionID: req.SessionID,
+ WorkDir: req.WorkDir,
+ // Carry the branch across the reroute. The run still delivered one:
+ // it ran out of context, it did not fail to produce anything, and
+ // dropping the name here would hide the work it did commit.
+ BranchName: req.BranchName,
SessionRolloutMissing: req.SessionRolloutMissing,
RetiredSessionID: req.RetiredSessionID,
})
@@ -3173,7 +3275,7 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
// transaction (force session_id NULL + flag the row), so an auto-retry the
// same commit creates and wakes can never observe the withheld pointer or a
// missing continuity-gap flag.
- task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.SessionRolloutMissing, req.RetiredSessionID)
+ task, err := h.TaskService.CompleteTask(r.Context(), parseUUID(taskID), result, req.SessionID, req.WorkDir, req.BranchName, req.SessionRolloutMissing, req.RetiredSessionID)
if err != nil {
// A CompleteTask error is an infrastructure failure (transaction /
// assistant-outcome write), not a bad request: an already-finalized
@@ -3802,6 +3904,10 @@ type TaskFailRequest struct {
SessionID string `json:"session_id,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
FailureReason string `json:"failure_reason,omitempty"`
+ // BranchName: a failed run can still have produced a branch — worktree mode
+ // commits whatever the agent left before tearing the worktree down. Report
+ // it so a partially-successful run is still findable.
+ BranchName string `json:"branch_name,omitempty"`
// SessionRolloutMissing: the daemon withheld this task's Codex session
// because its rollout was missing (MUL-5305). Clear the resume pointer and
// flag the continuity gap for the next claim.
@@ -3842,7 +3948,7 @@ func (h *Handler) failTask(w http.ResponseWriter, r *http.Request, taskID, works
// keep a stale mid-flight pin) and flagging the row in the same commit that
// creates and wakes the auto-retry, so the retry can never claim the withheld
// pointer or miss the continuity gap.
- task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID)
+ task, err := h.TaskService.FailTask(r.Context(), parseUUID(taskID), req.Error, req.SessionID, req.WorkDir, req.BranchName, req.FailureReason, req.SessionRolloutMissing, req.RetiredSessionID)
if err != nil {
// A FailTask error is an infrastructure failure (the terminal
// transaction that also clears the withheld session, writes the
@@ -3955,12 +4061,76 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {
// task cancellation and finished flushing the transcript. Settles the chat
// finalization that CancelTaskWithResult deferred for a started-but-empty
// transcript (#5219); idempotent when nothing was deferred.
+// TaskCancelAckRequest is the body of the daemon's cancel acknowledgement.
+type TaskCancelAckRequest struct {
+ // BranchName: a cancelled worktree task has already committed whatever the
+ // agent produced — the worktree is finalized before the daemon learns of
+ // the cancellation. The rest of the result is discarded on this path, so
+ // this is the only channel that can report where the work went.
+ BranchName string `json:"branch_name,omitempty"`
+ // ErrorMessage / FailureReason: set when the cancelled run's worktree
+ // Finalize ABORTED — there is no branch, and the error text naming the
+ // preserved worktree is the only pointer left to the agent's work.
+ ErrorMessage string `json:"error_message,omitempty"`
+ FailureReason string `json:"failure_reason,omitempty"`
+}
+
func (h *Handler) AckTaskCancelled(w http.ResponseWriter, r *http.Request) {
taskID := chi.URLParam(r, "taskId")
task, ok := h.requireDaemonTaskAccess(w, r, taskID)
if !ok {
return
}
+ // Body is optional: older daemons send `{}`, and a decode failure must not
+ // break the cancellation contract this endpoint exists for.
+ var req TaskCancelAckRequest
+ _ = json.NewDecoder(r.Body).Decode(&req)
+
+ // Terminal deliveries first, failing LOUD on persistence errors: these
+ // fields are the only pointer to a cancelled task's work, and the daemon
+ // retries this ack on transient failures — a warn-and-200 would turn one
+ // DB blip into a permanently undiscoverable branch. Both writes never
+ // overwrite already-recorded values, so replays are idempotent — and both
+ // carry a status='cancelled' CAS, because the daemon acks on EVERY
+ // terminal status it observes: a late ack from a stale run must not stamp
+ // its branch or error onto a completed/failed row whose own callback is
+ // the authoritative channel. A CAS-refused write is a deliberate no-op
+ // (Exec reports no error), so the ack still returns 200 — there is
+ // nothing for the daemon to retry — and the rebroadcast below is guarded
+ // by the same status check inside RebroadcastCancelledTask.
+ delivered := false
+ if branch := strings.TrimSpace(req.BranchName); branch != "" {
+ if err := h.Queries.SetAgentTaskBranchName(r.Context(), db.SetAgentTaskBranchNameParams{
+ ID: task.ID,
+ BranchName: pgtype.Text{String: branch, Valid: true},
+ }); err != nil {
+ slog.Error("cancel ack: record branch name failed",
+ "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to record branch name")
+ return
+ }
+ delivered = true
+ }
+ if msg := strings.TrimSpace(req.ErrorMessage); msg != "" {
+ reason := strings.TrimSpace(req.FailureReason)
+ if err := h.Queries.SetAgentTaskErrorIfEmpty(r.Context(), db.SetAgentTaskErrorIfEmptyParams{
+ ID: task.ID,
+ Error: pgtype.Text{String: msg, Valid: true},
+ FailureReason: pgtype.Text{String: reason, Valid: reason != ""},
+ }); err != nil {
+ slog.Error("cancel ack: record preserved-work error failed",
+ "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to record task error")
+ return
+ }
+ delivered = true
+ }
+ if delivered {
+ // The task:cancelled broadcast fired at cancel time, before this ack —
+ // clients may already hold a refetched row without the branch/error
+ // and will not refetch again on their own.
+ h.TaskService.RebroadcastCancelledTask(r.Context(), task.ID)
+ }
h.TaskService.FinalizeDeferredCancelledChat(r.Context(), task.ID)
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
diff --git a/server/internal/handler/daemon_claim_cancelled_session_test.go b/server/internal/handler/daemon_claim_cancelled_session_test.go
index fd27acda9e..1eb3de02b6 100644
--- a/server/internal/handler/daemon_claim_cancelled_session_test.go
+++ b/server/internal/handler/daemon_claim_cancelled_session_test.go
@@ -770,14 +770,14 @@ func TestTerminalReports_TakeChatSessionLockBeforeTask(t *testing.T) {
callCtx, cancel := raceCtx()
defer cancel()
_, err := testHandler.TaskService.CompleteTask(callCtx, parseUUID(taskID),
- []byte(`"done"`), "turn2-session", "/tmp/turn2-workdir", false, "")
+ []byte(`"done"`), "turn2-session", "/tmp/turn2-workdir", "", false, "")
return err
},
"fail": func(taskID string) error {
callCtx, cancel := raceCtx()
defer cancel()
_, err := testHandler.TaskService.FailTask(callCtx, parseUUID(taskID),
- "boom", "turn2-session", "/tmp/turn2-workdir", "agent_error", false, "")
+ "boom", "turn2-session", "/tmp/turn2-workdir", "", "agent_error", false, "")
return err
},
}
@@ -874,7 +874,7 @@ func TestCancelAndPin_ConcurrentWithTerminalReport(t *testing.T) {
callCtx, cancel := raceCtx()
defer cancel()
_, err := testHandler.TaskService.CompleteTask(callCtx, parseUUID(taskID),
- []byte(`"done"`), "turn2-session", "/tmp/turn2-workdir", false, "")
+ []byte(`"done"`), "turn2-session", "/tmp/turn2-workdir", "", false, "")
return err
},
},
@@ -904,7 +904,7 @@ func TestCancelAndPin_ConcurrentWithTerminalReport(t *testing.T) {
callCtx, cancel := raceCtx()
defer cancel()
_, err := testHandler.TaskService.FailTask(callCtx, parseUUID(taskID),
- "boom", "turn3-session", "/tmp/turn3-workdir", "agent_error", false, "")
+ "boom", "turn3-session", "/tmp/turn3-workdir", "", "agent_error", false, "")
return err
},
},
diff --git a/server/internal/handler/issue_child_done_test.go b/server/internal/handler/issue_child_done_test.go
index e67ab29756..010ded4355 100644
--- a/server/internal/handler/issue_child_done_test.go
+++ b/server/internal/handler/issue_child_done_test.go
@@ -625,7 +625,7 @@ func TestStageLeaderPrepareTimeoutRetryCanAdvanceNextStage(t *testing.T) {
t.Fatalf("dispatch original leader task: %v", err)
}
- if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(originalID), "task preparation timed out after 5m0s", "", "", "timeout", false, ""); err != nil {
+ if _, err := testHandler.TaskService.FailTask(ctx, parseUUID(originalID), "task preparation timed out after 5m0s", "", "", "", "timeout", false, ""); err != nil {
t.Fatalf("fail original leader task: %v", err)
}
diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.go
index e6c9c2cea6..6699df88ff 100644
--- a/server/internal/handler/project_resource.go
+++ b/server/internal/handler/project_resource.go
@@ -11,6 +11,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ agentpkg "github.com/multica-ai/multica/server/pkg/agent"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -108,17 +109,114 @@ func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {
return out, nil
}
+// Execution modes for resource_type=local_directory. The zero value (absent
+// field) means in_place, so resources created before worktree mode existed keep
+// their original behavior without a data migration.
+const (
+ // localDirectoryModeInPlace runs the agent directly in the user's
+ // directory, serialised by the daemon's per-path mutex: one task at a
+ // time, edits land in the user's working tree.
+ localDirectoryModeInPlace = "in_place"
+ // localDirectoryModeWorktree runs each task in its own git worktree of
+ // the user's repo, created inside the daemon's env root. Tasks on the
+ // same directory run concurrently and deliver their work as a branch.
+ // Only valid when the directory is a git working tree — the daemon
+ // verifies that at task time, since the server can't see the filesystem.
+ localDirectoryModeWorktree = "worktree"
+)
+
// localDirectoryRef is the JSONB shape stored for resource_type=local_directory.
-// It pins a project to an existing directory on a specific user machine, so
-// agent tasks run in-place rather than in an isolated git worktree. The
+// It pins a project to an existing directory on a specific user machine. The
// daemon_id scopes the path to one daemon registration — the same string path
// on a different machine is a different resource. The optional label is a
// human-readable hint used by the UI; the row-level project_resource.label
// column remains the generic column for any resource type.
+//
+// execution_mode selects how tasks share that directory: in_place (default)
+// keeps the historical one-task-at-a-time behavior, worktree gives each task an
+// isolated git worktree so tasks run concurrently.
type localDirectoryRef struct {
- LocalPath string `json:"local_path"`
- DaemonID string `json:"daemon_id"`
- Label string `json:"label,omitempty"`
+ LocalPath string `json:"local_path"`
+ DaemonID string `json:"daemon_id"`
+ Label string `json:"label,omitempty"`
+ ExecutionMode string `json:"execution_mode,omitempty"`
+}
+
+// requireWorktreeCapableDaemon rejects saving a local_directory ref that asks
+// for execution_mode=worktree while the daemon owning the path is too old to
+// implement the mode. An old daemon does not know the field exists: it would
+// json-skip it and run tasks IN PLACE, editing the working copy the user
+// explicitly asked to isolate — and it predates the daemon-side unknown-mode
+// refusal, so only the server can stop it. Gating at save time surfaces the
+// failure at the moment the user can act on it (upgrade the daemon), instead
+// of as a silently-wrong task later.
+//
+// Residual gap, accepted for now: a daemon downgraded AFTER the resource was
+// saved is not caught here; closing that needs a claim-time gate.
+//
+// Returns true to proceed; on false the 422 response has already been written,
+// using the same daemon_version_unsupported code as the quick-create gate so
+// clients can branch on it.
+func (h *Handler) requireWorktreeCapableDaemon(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, resourceType string, normalizedRef json.RawMessage) bool {
+ if resourceType != "local_directory" {
+ return true
+ }
+ var ref localDirectoryRef
+ if err := json.Unmarshal(normalizedRef, &ref); err != nil || ref.ExecutionMode != localDirectoryModeWorktree {
+ return true
+ }
+
+ // One machine hosts one runtime row per provider, all registered by the
+ // same daemon binary, so the freshest row's metadata.cli_version is the
+ // machine's current binary. A workspace has a handful of runtimes; the
+ // unfiltered list is a tiny read.
+ runtimes, err := h.Queries.ListAgentRuntimes(r.Context(), workspaceID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check daemon version")
+ return false
+ }
+ current := latestDaemonCLIVersion(runtimes, ref.DaemonID)
+ minimum := agentpkg.MinLocalWorktreeCLIVersion
+ if err := agentpkg.CheckMinCLIVersionFor(current, minimum); err != nil {
+ // Fail closed on missing/unparsable versions too — including a
+ // daemon_id with no registered runtime at all: a worktree resource
+ // that can never dispatch correctly is worse than a save-time error.
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]any{
+ "error": fmt.Sprintf(
+ "local_directory: execution_mode=worktree needs daemon version %s or newer, but daemon %s reports %q; upgrade the daemon (or keep the resource on in_place)",
+ minimum, ref.DaemonID, current),
+ "code": "daemon_version_unsupported",
+ "current_version": current,
+ "min_version": minimum,
+ "daemon_id": ref.DaemonID,
+ })
+ return false
+ }
+ return true
+}
+
+// latestDaemonCLIVersion returns the cli_version of the freshest runtime row
+// registered by daemonID, or "" when the daemon has no row carrying one. Rows
+// without a version are skipped rather than treated as authoritative: one
+// machine registers a row per provider, and only the freshest version-bearing
+// row reflects the binary currently running there.
+func latestDaemonCLIVersion(runtimes []db.AgentRuntime, daemonID string) string {
+ current := ""
+ var currentSeen pgtype.Timestamptz
+ for _, rt := range runtimes {
+ if !rt.DaemonID.Valid || rt.DaemonID.String != daemonID {
+ continue
+ }
+ v := readRuntimeCLIVersion(rt.Metadata)
+ if v == "" {
+ continue
+ }
+ if current == "" || (rt.LastSeenAt.Valid && rt.LastSeenAt.Time.After(currentSeen.Time)) {
+ current = v
+ currentSeen = rt.LastSeenAt
+ }
+ }
+ return current
}
func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {
@@ -138,6 +236,13 @@ func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {
return nil, errors.New("local_directory: daemon_id is required")
}
payload.Label = strings.TrimSpace(payload.Label)
+ payload.ExecutionMode = strings.TrimSpace(payload.ExecutionMode)
+ switch payload.ExecutionMode {
+ case "", localDirectoryModeInPlace, localDirectoryModeWorktree:
+ default:
+ return nil, fmt.Errorf("local_directory: execution_mode must be %q or %q, got %q",
+ localDirectoryModeInPlace, localDirectoryModeWorktree, payload.ExecutionMode)
+ }
out, err := json.Marshal(payload)
if err != nil {
return nil, err
@@ -286,6 +391,10 @@ func (h *Handler) CreateProjectResource(w http.ResponseWriter, r *http.Request)
return
}
+ if !h.requireWorktreeCapableDaemon(w, r, project.WorkspaceID, req.ResourceType, normalizedRef) {
+ return
+ }
+
var label pgtype.Text
if req.Label != nil && strings.TrimSpace(*req.Label) != "" {
label = pgtype.Text{String: strings.TrimSpace(*req.Label), Valid: true}
@@ -388,6 +497,15 @@ func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request)
return
}
+ // Gate only when the caller is changing the ref: a label/position-only
+ // update must not start failing because the daemon's version drifted
+ // after the mode was legitimately saved.
+ if _, refProvided := raw["resource_ref"]; refProvided {
+ if !h.requireWorktreeCapableDaemon(w, r, project.WorkspaceID, existing.ResourceType, nextRef) {
+ return
+ }
+ }
+
nextLabel := existing.Label
if rawLabel, ok := raw["label"]; ok {
var labelStr *string
diff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.go
index 1c7530a78b..f833bb702c 100644
--- a/server/internal/handler/project_resource_test.go
+++ b/server/internal/handler/project_resource_test.go
@@ -6,6 +6,10 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
func TestProjectResourceLifecycle(t *testing.T) {
@@ -1102,3 +1106,136 @@ func TestCreateProjectBundledLocalDirectoryDaemonConflict(t *testing.T) {
t.Errorf("per-daemon bundle: expected 2 resources, got %d", len(resp.Resources))
}
}
+
+// execution_mode selects between the historical exclusive in-place run and
+// worktree mode. It is validated at the API boundary so a typo is caught at
+// save time; a daemon new enough to know the field refuses unknown values
+// rather than falling back to in_place, so the two checks together keep a
+// mistyped mode from ever running.
+func TestValidateLocalDirectoryRefExecutionMode(t *testing.T) {
+ accepted := []struct {
+ name string
+ mode string
+ want string
+ }{
+ {"absent means in_place", "", ""},
+ {"explicit in_place", "in_place", "in_place"},
+ {"worktree", "worktree", "worktree"},
+ {"surrounding whitespace is trimmed", " worktree ", "worktree"},
+ }
+ for _, tc := range accepted {
+ t.Run(tc.name, func(t *testing.T) {
+ ref := map[string]any{"local_path": "/Users/foo/work", "daemon_id": "d1"}
+ if tc.mode != "" {
+ ref["execution_mode"] = tc.mode
+ }
+ raw, err := json.Marshal(ref)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ out, err := validateLocalDirectoryRef(raw)
+ if err != nil {
+ t.Fatalf("validateLocalDirectoryRef: %v", err)
+ }
+ var got localDirectoryRef
+ if err := json.Unmarshal(out, &got); err != nil {
+ t.Fatalf("unmarshal normalized ref: %v", err)
+ }
+ if got.ExecutionMode != tc.want {
+ t.Errorf("ExecutionMode = %q, want %q", got.ExecutionMode, tc.want)
+ }
+ })
+ }
+
+ rejected := []string{"snapshot", "WORKTREE", "in-place", "true"}
+ for _, mode := range rejected {
+ t.Run("rejects "+mode, func(t *testing.T) {
+ raw, err := json.Marshal(map[string]any{
+ "local_path": "/Users/foo/work",
+ "daemon_id": "d1",
+ "execution_mode": mode,
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if _, err := validateLocalDirectoryRef(raw); err == nil {
+ t.Errorf("execution_mode %q was accepted, want a validation error", mode)
+ }
+ })
+ }
+}
+
+// latestDaemonCLIVersion feeds the worktree-mode save gate: an old daemon
+// json-skips execution_mode and would run tasks in place, so the gate has to
+// read the version of the binary actually running on the machine — the
+// freshest version-bearing row for that daemon_id, never a stale sibling row.
+func TestLatestDaemonCLIVersion(t *testing.T) {
+ row := func(daemonID, version string, seen time.Time) db.AgentRuntime {
+ rt := db.AgentRuntime{
+ DaemonID: pgtype.Text{String: daemonID, Valid: daemonID != ""},
+ LastSeenAt: pgtype.Timestamptz{Time: seen, Valid: !seen.IsZero()},
+ }
+ if version != "" {
+ rt.Metadata = []byte(`{"cli_version":"` + version + `"}`)
+ }
+ return rt
+ }
+ base := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
+
+ tests := []struct {
+ name string
+ runtimes []db.AgentRuntime
+ daemonID string
+ want string
+ }{
+ {
+ name: "no rows at all",
+ runtimes: nil,
+ daemonID: "d1",
+ want: "",
+ },
+ {
+ name: "only other daemons",
+ runtimes: []db.AgentRuntime{row("d2", "0.9.9", base)},
+ daemonID: "d1",
+ want: "",
+ },
+ {
+ name: "single match",
+ runtimes: []db.AgentRuntime{row("d1", "0.4.24", base)},
+ daemonID: "d1",
+ want: "0.4.24",
+ },
+ {
+ name: "freshest row wins regardless of order",
+ runtimes: []db.AgentRuntime{
+ row("d1", "0.4.30", base.Add(2*time.Hour)),
+ row("d1", "0.4.20", base),
+ },
+ daemonID: "d1",
+ want: "0.4.30",
+ },
+ {
+ name: "stale-but-fresher row without a version does not mask an older versioned row",
+ runtimes: []db.AgentRuntime{
+ row("d1", "", base.Add(2*time.Hour)),
+ row("d1", "0.4.24", base),
+ },
+ daemonID: "d1",
+ want: "0.4.24",
+ },
+ {
+ name: "match with no version anywhere",
+ runtimes: []db.AgentRuntime{row("d1", "", base)},
+ daemonID: "d1",
+ want: "",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := latestDaemonCLIVersion(tc.runtimes, tc.daemonID); got != tc.want {
+ t.Errorf("latestDaemonCLIVersion = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/worktree_claim_gate_test.go b/server/internal/handler/worktree_claim_gate_test.go
new file mode 100644
index 0000000000..1b1dcc5838
--- /dev/null
+++ b/server/internal/handler/worktree_claim_gate_test.go
@@ -0,0 +1,780 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func localDirRef(t *testing.T, path, daemonID, mode string) json.RawMessage {
+ t.Helper()
+ raw, err := json.Marshal(map[string]string{
+ "local_path": path, "daemon_id": daemonID, "execution_mode": mode,
+ })
+ if err != nil {
+ t.Fatalf("marshal ref: %v", err)
+ }
+ return raw
+}
+
+func runtimeWithVersion(daemonID, cliVersion string) db.AgentRuntime {
+ rt := db.AgentRuntime{DaemonID: pgtype.Text{String: daemonID, Valid: daemonID != ""}}
+ if cliVersion != "" {
+ rt.Metadata, _ = json.Marshal(map[string]string{"cli_version": cliVersion})
+ }
+ return rt
+}
+
+// The save-time gate cannot cover a machine downgraded after the resource was
+// written, and an old daemon json-skips execution_mode entirely — it would run
+// the task IN PLACE, editing the working copy the user asked to isolate. This
+// is the last point where that can be stopped.
+func TestWorktreeClaimBlockReason(t *testing.T) {
+ const daemon = "daemon-a"
+
+ worktreeRes := []ProjectResourceData{{
+ ID: "r1", ResourceType: "local_directory",
+ ResourceRef: localDirRef(t, "/Users/dev/game", daemon, "worktree"),
+ }}
+
+ t.Run("blocks a runtime below the floor", func(t *testing.T) {
+ reason := worktreeClaimBlockReason(worktreeRes, runtimeWithVersion(daemon, "0.4.10"))
+ if reason == "" {
+ t.Fatal("an outdated runtime was allowed to claim a worktree task")
+ }
+ if !strings.Contains(reason, "/Users/dev/game") || !strings.Contains(reason, "0.4.10") {
+ t.Errorf("reason should name the directory and the version, got: %q", reason)
+ }
+ })
+
+ t.Run("blocks a runtime reporting no version at all", func(t *testing.T) {
+ // Fail closed: "no version" is what a daemon far older than the field
+ // looks like, which is exactly the dangerous case.
+ if worktreeClaimBlockReason(worktreeRes, runtimeWithVersion(daemon, "")) == "" {
+ t.Error("a runtime with no reported version was allowed to claim")
+ }
+ })
+
+ t.Run("allows a runtime at or above the floor", func(t *testing.T) {
+ if reason := worktreeClaimBlockReason(worktreeRes, runtimeWithVersion(daemon, "9.9.9")); reason != "" {
+ t.Errorf("a new enough runtime was blocked: %q", reason)
+ }
+ })
+
+ t.Run("ignores in_place and absent modes", func(t *testing.T) {
+ for _, mode := range []string{"in_place", ""} {
+ res := []ProjectResourceData{{
+ ID: "r1", ResourceType: "local_directory",
+ ResourceRef: localDirRef(t, "/Users/dev/game", daemon, mode),
+ }}
+ if reason := worktreeClaimBlockReason(res, runtimeWithVersion(daemon, "0.1.0")); reason != "" {
+ t.Errorf("mode %q blocked an old daemon that can run it fine: %q", mode, reason)
+ }
+ }
+ })
+
+ // A project may carry one local_directory per machine. Another machine's
+ // worktree resource says nothing about this runtime's ability to run.
+ t.Run("ignores a resource bound to a different daemon", func(t *testing.T) {
+ other := []ProjectResourceData{{
+ ID: "r1", ResourceType: "local_directory",
+ ResourceRef: localDirRef(t, "/Users/dev/game", "daemon-b", "worktree"),
+ }}
+ if reason := worktreeClaimBlockReason(other, runtimeWithVersion(daemon, "0.1.0")); reason != "" {
+ t.Errorf("another machine's resource blocked this claim: %q", reason)
+ }
+ })
+
+ t.Run("ignores non-local_directory resources", func(t *testing.T) {
+ repo := []ProjectResourceData{{
+ ID: "r1", ResourceType: "github_repo",
+ ResourceRef: json.RawMessage(`{"url":"https://github.com/a/b"}`),
+ }}
+ if reason := worktreeClaimBlockReason(repo, runtimeWithVersion(daemon, "0.1.0")); reason != "" {
+ t.Errorf("github_repo resource blocked a claim: %q", reason)
+ }
+ })
+
+ t.Run("ignores a runtime with no daemon id", func(t *testing.T) {
+ if reason := worktreeClaimBlockReason(worktreeRes, runtimeWithVersion("", "0.1.0")); reason != "" {
+ t.Errorf("cloud runtime blocked: %q", reason)
+ }
+ })
+
+ t.Run("survives a malformed ref", func(t *testing.T) {
+ bad := []ProjectResourceData{{
+ ID: "r1", ResourceType: "local_directory",
+ ResourceRef: json.RawMessage(`{"local_path": 42}`),
+ }}
+ if reason := worktreeClaimBlockReason(bad, runtimeWithVersion(daemon, "0.1.0")); reason != "" {
+ t.Errorf("malformed ref produced a block: %q", reason)
+ }
+ })
+}
+
+// branch_name has to survive the whole way to the task row on BOTH terminal
+// paths. It was previously dropped at decode (the request struct had no field),
+// so the daemon sent it and nobody received it. The failure path matters most:
+// worktree mode commits the agent's leftovers before tearing the worktree down,
+// so a run that died partway still produced something the user needs to find.
+func TestBranchNameRoundTripsThroughBothTerminalPaths(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+
+ // The terminal handlers resolve the task's workspace through its issue, so
+ // a bare task row reads as "failed to load task".
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'branch name round-trip fixture', 'in_progress', 'none', $2, 'member', 993310, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ newRunningTask := func(t *testing.T) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at)
+ VALUES ($1, $2, $3, 'running', 0, now())
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+ }
+
+ post := func(t *testing.T, taskID, endpoint string, body map[string]any, call func(http.ResponseWriter, *http.Request)) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
+ body, testWorkspaceID, "legit-daemon")
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("taskId", taskID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ call(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: expected 200, got %d: %s", endpoint, w.Code, w.Body.String())
+ }
+ }
+
+ readBranch := func(t *testing.T, taskID string) string {
+ t.Helper()
+ var branch pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT branch_name FROM agent_task_queue WHERE id = $1`, taskID).Scan(&branch); err != nil {
+ t.Fatalf("read branch_name: %v", err)
+ }
+ return branch.String
+ }
+
+ t.Run("complete", func(t *testing.T) {
+ taskID := newRunningTask(t)
+ post(t, taskID, "complete", map[string]any{
+ "output": "done", "branch_name": "agent/j/abc12345",
+ }, testHandler.CompleteTask)
+ if got := readBranch(t, taskID); got != "agent/j/abc12345" {
+ t.Errorf("branch_name = %q, want it persisted from the complete callback", got)
+ }
+ })
+
+ t.Run("fail", func(t *testing.T) {
+ taskID := newRunningTask(t)
+ post(t, taskID, "fail", map[string]any{
+ "error": "agent crashed", "branch_name": "agent/j/def67890",
+ }, testHandler.FailTask)
+ if got := readBranch(t, taskID); got != "agent/j/def67890" {
+ t.Errorf("branch_name = %q, want the partial work still findable after a failure", got)
+ }
+ })
+
+ t.Run("absent stays empty for non-worktree tasks", func(t *testing.T) {
+ taskID := newRunningTask(t)
+ post(t, taskID, "complete", map[string]any{"output": "done"}, testHandler.CompleteTask)
+ if got := readBranch(t, taskID); got != "" {
+ t.Errorf("branch_name = %q, want empty when the daemon reports none", got)
+ }
+ })
+}
+
+// Every terminal path that can carry a branch must carry it. A worktree run
+// commits before it learns its fate, so the branch is equally real whether the
+// run completed, failed, was rerouted, or was cancelled — and the user has no
+// other way to find it.
+func TestBranchNameSurvivesEveryTerminalPath(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'terminal path branch fixture', 'in_progress', 'none', $2, 'member', 993311, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ newTask := func(t *testing.T, status string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, started_at)
+ VALUES ($1, $2, $3, $4, 0, now())
+ RETURNING id
+ `, agentID, runtimeID, issueID, status).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+ return taskID
+ }
+ post := func(t *testing.T, taskID, endpoint string, body map[string]any, call func(http.ResponseWriter, *http.Request)) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
+ body, testWorkspaceID, "legit-daemon")
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("taskId", taskID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ call(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s: expected 200, got %d: %s", endpoint, w.Code, w.Body.String())
+ }
+ }
+ readBranch := func(t *testing.T, taskID string) string {
+ t.Helper()
+ var branch pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT branch_name FROM agent_task_queue WHERE id = $1`, taskID).Scan(&branch); err != nil {
+ t.Fatalf("read branch_name: %v", err)
+ }
+ return branch.String
+ }
+
+ // A context-exhausted "success" is rerouted to the failure path server-side.
+ // The run still delivered a branch; the reroute must not eat it.
+ t.Run("context-exhausted reroute keeps the branch", func(t *testing.T) {
+ taskID := newTask(t, "running")
+ post(t, taskID, "complete", map[string]any{
+ "output": "Prompt is too long and cannot be compacted further.",
+ "branch_name": "agent/j/ctx11111",
+ }, testHandler.CompleteTask)
+
+ var status string
+ if err := testPool.QueryRow(ctx,
+ `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read status: %v", err)
+ }
+ if status != "failed" {
+ t.Fatalf("precondition: expected the reroute to record a failure, got %q", status)
+ }
+ if got := readBranch(t, taskID); got != "agent/j/ctx11111" {
+ t.Errorf("branch_name = %q, want it carried across the complete→fail reroute", got)
+ }
+ })
+
+ // Cancellation discards the whole result payload, but the worktree was
+ // finalized before the daemon learned of the cancel — so the branch exists
+ // and the ack is the only channel left to report it.
+ t.Run("cancel ack records the branch", func(t *testing.T) {
+ taskID := newTask(t, "cancelled")
+ post(t, taskID, "cancel-ack", map[string]any{
+ "branch_name": "agent/j/cancel11",
+ }, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "agent/j/cancel11" {
+ t.Errorf("branch_name = %q, want the cancelled run's committed work discoverable", got)
+ }
+ })
+
+ // Older daemons post an empty body here; that must stay a valid ack.
+ t.Run("cancel ack without a branch still succeeds", func(t *testing.T) {
+ taskID := newTask(t, "cancelled")
+ post(t, taskID, "cancel-ack", map[string]any{}, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "" {
+ t.Errorf("branch_name = %q, want empty", got)
+ }
+ })
+
+ // A name recorded by a terminal callback is authoritative; a later ack must
+ // not clobber it.
+ t.Run("cancel ack does not overwrite an existing branch", func(t *testing.T) {
+ taskID := newTask(t, "running")
+ post(t, taskID, "complete", map[string]any{
+ "output": "done", "branch_name": "agent/j/original",
+ }, testHandler.CompleteTask)
+ post(t, taskID, "cancel-ack", map[string]any{
+ "branch_name": "agent/j/latecomer",
+ }, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "agent/j/original" {
+ t.Errorf("branch_name = %q, want the original preserved", got)
+ }
+ })
+
+ readError := func(t *testing.T, taskID string) (string, string) {
+ t.Helper()
+ var errText, failureReason pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT error, failure_reason FROM agent_task_queue WHERE id = $1`, taskID).Scan(&errText, &failureReason); err != nil {
+ t.Fatalf("read error columns: %v", err)
+ }
+ return errText.String, failureReason.String
+ }
+
+ // Cancel + Finalize-abort: no branch exists, and the error naming the
+ // preserved worktree is the only pointer left to the agent's work. The ack
+ // must land it on the row for the UI to show.
+ t.Run("cancel ack records a preserved-worktree error", func(t *testing.T) {
+ taskID := newTask(t, "cancelled")
+ const preserved = "local_directory worktree: could not commit; the work is preserved in the worktree at /env/worktree"
+ post(t, taskID, "cancel-ack", map[string]any{
+ "error_message": preserved,
+ "failure_reason": "local_directory_error",
+ }, testHandler.AckTaskCancelled)
+ gotErr, gotReason := readError(t, taskID)
+ if gotErr != preserved {
+ t.Errorf("error = %q, want the preserved-worktree message", gotErr)
+ }
+ if gotReason != "local_directory_error" {
+ t.Errorf("failure_reason = %q, want local_directory_error", gotReason)
+ }
+ })
+
+ // A reason already recorded (fail callback, claim gate) is authoritative;
+ // a replayed or late ack must not clobber it.
+ t.Run("cancel ack does not overwrite an existing error", func(t *testing.T) {
+ taskID := newTask(t, "cancelled")
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_task_queue SET error = 'original reason', failure_reason = 'timeout' WHERE id = $1`,
+ taskID); err != nil {
+ t.Fatalf("seed existing error: %v", err)
+ }
+ post(t, taskID, "cancel-ack", map[string]any{
+ "error_message": "latecomer",
+ "failure_reason": "local_directory_error",
+ }, testHandler.AckTaskCancelled)
+ gotErr, gotReason := readError(t, taskID)
+ if gotErr != "original reason" || gotReason != "timeout" {
+ t.Errorf("error/failure_reason = %q/%q, want the original pair preserved", gotErr, gotReason)
+ }
+ })
+
+ // Replaying the same ack (the daemon retries on transient errors) must be
+ // idempotent: same row state, still a 200.
+ t.Run("cancel ack replay is idempotent", func(t *testing.T) {
+ taskID := newTask(t, "cancelled")
+ body := map[string]any{
+ "branch_name": "agent/j/replay11",
+ "error_message": "preserved at /env/worktree",
+ "failure_reason": "local_directory_error",
+ }
+ post(t, taskID, "cancel-ack", body, testHandler.AckTaskCancelled)
+ post(t, taskID, "cancel-ack", body, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "agent/j/replay11" {
+ t.Errorf("branch_name = %q after replay, want agent/j/replay11", got)
+ }
+ gotErr, _ := readError(t, taskID)
+ if gotErr != "preserved at /env/worktree" {
+ t.Errorf("error = %q after replay, want unchanged", gotErr)
+ }
+ })
+
+ // The daemon acks on EVERY terminal status it observes, so a stale run's
+ // late ack can arrive for a row that completed or failed WITHOUT a branch.
+ // Those rows' own complete/fail callbacks are the authoritative channel —
+ // the ack's status CAS must keep it from backfilling them.
+ t.Run("late cancel ack leaves a completed row untouched", func(t *testing.T) {
+ taskID := newTask(t, "running")
+ post(t, taskID, "complete", map[string]any{"output": "all done"}, testHandler.CompleteTask)
+ post(t, taskID, "cancel-ack", map[string]any{
+ "branch_name": "agent/j/stale011",
+ "error_message": "stale preserved-path message",
+ "failure_reason": "local_directory_error",
+ }, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "" {
+ t.Errorf("branch_name = %q, want empty — a late ack backfilled a completed row", got)
+ }
+ gotErr, gotReason := readError(t, taskID)
+ if gotErr != "" || gotReason != "" {
+ t.Errorf("error/failure_reason = %q/%q, want both empty on a completed row", gotErr, gotReason)
+ }
+ })
+
+ t.Run("late cancel ack leaves a failed row untouched", func(t *testing.T) {
+ taskID := newTask(t, "running")
+ post(t, taskID, "fail", map[string]any{"error": "agent crashed"}, testHandler.FailTask)
+ post(t, taskID, "cancel-ack", map[string]any{
+ "branch_name": "agent/j/stale012",
+ }, testHandler.AckTaskCancelled)
+ if got := readBranch(t, taskID); got != "" {
+ t.Errorf("branch_name = %q, want empty — a late ack backfilled a failed row", got)
+ }
+ gotErr, _ := readError(t, taskID)
+ if gotErr != "agent crashed" {
+ t.Errorf("error = %q, want the fail callback's own message preserved", gotErr)
+ }
+ })
+}
+
+// The claim gate cancels the task; the reason has to land on the row. The 4xx
+// only reaches the daemon's log, and batch claim drops the task from its
+// response entirely — so without a persisted reason the user sees a bare
+// "cancelled" for a condition only they can fix.
+func TestWorktreeClaimGateCancelPersistsReason(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ var agentID, runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1
+ `, testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {
+ t.Fatalf("setup: get agent: %v", err)
+ }
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, dispatched_at)
+ VALUES ($1, $2, 'dispatched', 0, now())
+ RETURNING id
+ `, agentID, runtimeID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ const reason = "worktree mode needs a newer runtime on that machine"
+ if _, err := testHandler.Queries.CancelAgentTaskWithReason(ctx, db.CancelAgentTaskWithReasonParams{
+ ID: parseUUID(taskID),
+ Error: pgtype.Text{String: reason, Valid: true},
+ FailureReason: pgtype.Text{String: "local_directory_error", Valid: true},
+ }); err != nil {
+ t.Fatalf("CancelAgentTaskWithReason: %v", err)
+ }
+
+ var status string
+ var errText, failureReason pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, error, failure_reason FROM agent_task_queue WHERE id = $1`,
+ taskID).Scan(&status, &errText, &failureReason); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "cancelled" {
+ t.Errorf("status = %q, want cancelled", status)
+ }
+ if errText.String != reason {
+ t.Errorf("error = %q, want the user-facing reason persisted", errText.String)
+ }
+ if failureReason.String != "local_directory_error" {
+ t.Errorf("failure_reason = %q, want local_directory_error", failureReason.String)
+ }
+}
+
+// seedWorktreeGateClaimFixture builds the full claim-path scenario the gate
+// exists for: a runtime whose machine reports cliVersion, an agent bound to
+// it, and a queued issue task whose project carries a worktree-mode
+// local_directory resource pinned to that same machine.
+func seedWorktreeGateClaimFixture(t *testing.T, ctx context.Context, label, daemonID, cliVersion string) (runtimeID, taskID string) {
+ t.Helper()
+
+ metadata := "{}"
+ if cliVersion != "" {
+ metadata = `{"cli_version":"` + cliVersion + `"}`
+ }
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider,
+ status, device_info, metadata, last_seen_at, visibility, owner_id
+ )
+ VALUES ($1, $2, $3, 'local', 'handler_test_runtime', 'online', 'worktree gate fixture', $4::jsonb, now(), 'private', $5)
+ RETURNING id
+ `, testWorkspaceID, daemonID, label+" runtime", metadata, testUserID).Scan(&runtimeID); err != nil {
+ t.Fatalf("setup: create runtime: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, $2, '', 'local', '{}'::jsonb, $3, 'private', 1, $4)
+ RETURNING id
+ `, testWorkspaceID, label+" agent", runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("setup: create agent: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, agentID) })
+
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id
+ `, testWorkspaceID, label+" project").Scan(&projectID); err != nil {
+ t.Fatalf("setup: create project: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, projectID) })
+
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO project_resource (project_id, workspace_id, resource_type, resource_ref, position)
+ VALUES ($1, $2, 'local_directory', $3::jsonb, 0)
+ `, projectID, testWorkspaceID,
+ `{"local_path":"/Users/dev/wtgate","daemon_id":"`+daemonID+`","execution_mode":"worktree"}`); err != nil {
+ t.Fatalf("setup: create project_resource: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM project_resource WHERE project_id = $1`, projectID)
+ })
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES (
+ $1, $2, $3, 'in_progress', 'none', $4, 'member',
+ (SELECT COALESCE(MAX(number), 82649) + 1 FROM issue WHERE workspace_id = $1),
+ 0
+ )
+ RETURNING id
+ `, testWorkspaceID, projectID, label+" issue", testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)
+ VALUES ($1, $2, $3, 'queued', 0)
+ RETURNING id
+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
+
+ return runtimeID, taskID
+}
+
+// assertWorktreeGateCancelled reads the task row and asserts the gate left it
+// in the state the user can act on: cancelled, with the reason persisted.
+func assertWorktreeGateCancelled(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ var status string
+ var errText, failureReason pgtype.Text
+ if err := testPool.QueryRow(ctx,
+ `SELECT status, error, failure_reason FROM agent_task_queue WHERE id = $1`,
+ taskID).Scan(&status, &errText, &failureReason); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "cancelled" {
+ t.Errorf("status = %q, want cancelled", status)
+ }
+ if !strings.Contains(errText.String, "/Users/dev/wtgate") {
+ t.Errorf("error = %q, want the persisted reason naming the directory", errText.String)
+ }
+ if failureReason.String != "local_directory_error" {
+ t.Errorf("failure_reason = %q, want local_directory_error", failureReason.String)
+ }
+}
+
+// TestClaimTask_WorktreeGateSingular drives the REAL singular claim endpoint
+// against a too-old runtime: the daemon must get the reason as a 422, and the
+// row must land cancelled-with-reason via the full TaskService path — not a
+// bare status flip that leaves agent status and live cards stale.
+func TestClaimTask_WorktreeGateSingular(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ const daemonID = "wtgate-singular-daemon"
+ runtimeID, taskID := seedWorktreeGateClaimFixture(t, ctx, "WT gate singular", daemonID, "0.4.10")
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, daemonID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+
+ if w.Code != http.StatusUnprocessableEntity {
+ t.Fatalf("expected 422 for a too-old runtime, got %d: %s", w.Code, w.Body.String())
+ }
+ if body := w.Body.String(); !strings.Contains(body, "/Users/dev/wtgate") || !strings.Contains(body, "0.4.10") {
+ t.Errorf("422 body should carry the actionable reason, got: %s", body)
+ }
+ assertWorktreeGateCancelled(t, ctx, taskID)
+}
+
+// TestClaimTask_WorktreeGateBatch drives the REAL batch claim endpoint: the
+// blocked task is omitted from the response (the daemon never sees it), so the
+// persisted row reason is the ONLY explanation the user gets — assert both.
+func TestClaimTask_WorktreeGateBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ // The batch token and body share batchClaimTestDaemonID; the runtime row
+ // and resource ref must use the same machine for the gate to key on it.
+ runtimeID, taskID := seedWorktreeGateClaimFixture(t, ctx, "WT gate batch", batchClaimTestDaemonID, "0.4.10")
+
+ w := postBatchClaim(t, testWorkspaceID, []string{runtimeID}, 5)
+ if w.Code != http.StatusOK {
+ t.Fatalf("batch claim: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Tasks []AgentTaskResponse `json:"tasks"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(resp.Tasks) != 0 {
+ t.Fatalf("blocked worktree task leaked into the batch response: %+v", resp.Tasks)
+ }
+ assertWorktreeGateCancelled(t, ctx, taskID)
+}
+
+// TestClaimTask_WorktreeGateAllowsCurrentRuntime is the control: the same
+// fixture with a new-enough runtime claims normally, proving the gate blocks
+// on version — not on worktree resources in general.
+func TestClaimTask_WorktreeGateAllowsCurrentRuntime(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ const daemonID = "wtgate-ok-daemon"
+ runtimeID, taskID := seedWorktreeGateClaimFixture(t, ctx, "WT gate ok", daemonID, "9.9.9")
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, daemonID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200 for a current runtime, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Task *AgentTaskResponse `json:"task"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp.Task == nil {
+ t.Fatal("expected the task to be claimed by a new-enough runtime")
+ }
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "dispatched" {
+ t.Errorf("status = %q, want dispatched", status)
+ }
+}
+
+// injectCancelFailureForTask installs a row-scoped trigger that makes any
+// UPDATE flipping this task to 'cancelled' raise — real fault injection at the
+// layer the gate's cancel actually fails at. The requeue path (status back to
+// 'queued') passes through untouched, which is exactly the recovery the gate
+// must take.
+func injectCancelFailureForTask(t *testing.T, ctx context.Context, taskID string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ CREATE OR REPLACE FUNCTION wtgate_fail_cancel() RETURNS trigger AS $fn$
+ BEGIN
+ IF NEW.status = 'cancelled' THEN
+ RAISE EXCEPTION 'injected cancel failure';
+ END IF;
+ RETURN NEW;
+ END $fn$ LANGUAGE plpgsql
+ `); err != nil {
+ t.Fatalf("create fault function: %v", err)
+ }
+ if _, err := testPool.Exec(ctx,
+ `CREATE TRIGGER wtgate_fail_cancel_trg BEFORE UPDATE ON agent_task_queue
+ FOR EACH ROW WHEN (OLD.id = '`+taskID+`'::uuid) EXECUTE FUNCTION wtgate_fail_cancel()`); err != nil {
+ t.Fatalf("create fault trigger: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DROP TRIGGER IF EXISTS wtgate_fail_cancel_trg ON agent_task_queue`)
+ testPool.Exec(ctx, `DROP FUNCTION IF EXISTS wtgate_fail_cancel`)
+ })
+}
+
+// When the gate's cancel itself fails, the claimed row must NOT strand in
+// dispatched (the daemon was refused the task, so nothing would ever run or
+// release it until stale reclaim). The gate requeues it so the next claim
+// re-runs the gate and retries the cancel.
+func TestClaimTask_WorktreeGateCancelFailureRequeuesSingular(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ const daemonID = "wtgate-cancelfail-daemon"
+ runtimeID, taskID := seedWorktreeGateClaimFixture(t, ctx, "WT gate cancelfail", daemonID, "0.4.10")
+ injectCancelFailureForTask(t, ctx, taskID)
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, daemonID)
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("expected 500 (transient server problem, not a claim refusal), got %d: %s", w.Code, w.Body.String())
+ }
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "queued" {
+ t.Errorf("status = %q, want queued — a stranded dispatched row waits on stale reclaim with no reason", status)
+ }
+}
+
+func TestClaimTask_WorktreeGateCancelFailureRequeuesBatch(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ runtimeID, taskID := seedWorktreeGateClaimFixture(t, ctx, "WT gate cancelfail batch", batchClaimTestDaemonID, "0.4.10")
+ injectCancelFailureForTask(t, ctx, taskID)
+
+ w := postBatchClaim(t, testWorkspaceID, []string{runtimeID}, 5)
+ if w.Code != http.StatusOK {
+ t.Fatalf("batch claim: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Tasks []AgentTaskResponse `json:"tasks"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(resp.Tasks) != 0 {
+ t.Fatalf("blocked worktree task leaked into the batch response: %+v", resp.Tasks)
+ }
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if status != "queued" {
+ t.Errorf("status = %q, want queued after the batch gate's cancel failed", status)
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md
index bc663ec423..80811069eb 100644
--- a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md
@@ -29,7 +29,8 @@ A project's `description` is also durable context: when an issue (or a quick-cre
Common resource types:
- `github_repo` — durable GitHub repo context, with `resource_ref.url`, optional checkout `ref`, and optional prompt-only `default_branch_hint`;
-- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, and optional label.
+- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, optional label, and
+ optional `execution_mode` (`in_place`, the default, or `worktree`).
## CLI
@@ -46,11 +47,22 @@ multica project resource list <project-id> --output json
multica project resource add <project-id> --type github_repo --url <github-url> --output json
multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json
multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --output json
+multica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --execution-mode worktree --output json
+multica project resource update <project-id> <resource-id> --execution-mode in_place --output json
multica project resource update <project-id> <resource-id> --url <new-github-url> --output json
multica project resource update <project-id> <resource-id> --ref <branch-or-sha> --output json
multica project resource remove <project-id> <resource-id> --output json
```
+`--execution-mode` decides how tasks share a `local_directory`. `in_place` (default) runs the agent in the user's
+directory, one task at a time; a second task waits in `waiting_local_directory`. `worktree` gives each task its own
+git worktree of that repo, so tasks run concurrently and each delivers its work as an `agent/<agent>/<task>` branch
+in the user's repo instead of editing the working copy. `worktree` requires the path to be a git repository with at
+least one commit; tasks fail with an explicit error otherwise. The daemon version is gated twice — at save time and again
+against the daemon that claims each task — so a downgraded machine gets its tasks cancelled rather than run in place. Saving `worktree` is also refused (HTTP 422, code
+`daemon_version_unsupported`) while the daemon on that machine is older than the release that ships the mode — the
+fix is upgrading that daemon, then retrying. Pass an empty value to clear it back to the default.
+
For `github_repo`, non-JSON `--ref` sets `resource_ref.ref`, the default checkout branch/tag/SHA for future tasks in that project. JSON `--ref '<json>'` remains the escape hatch for full payloads or resource types not covered by shortcuts.
`--start-date` / `--due-date` are optional calendar days (`YYYY-MM-DD`, like issue dates). On `project update`, pass an empty string (`--start-date ""`) to clear a date; an unset flag leaves it untouched.
diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md b/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md
index ca9b17990e..834c979966 100644
--- a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md
+++ b/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md
@@ -4,7 +4,9 @@
- The same file registers `project resource list/add/update/remove`.
- `project create --repo` attaches `github_repo` resources during project creation.
- `project create` / `project update` accept `--start-date` / `--due-date` (calendar days, `YYYY-MM-DD`), mapping to the project `start_date` / `due_date` columns (migration `166_project_dates`); an empty `--start-date ""`/`--due-date ""` on update clears the date, mirroring the issue date flags in `cmd_issue.go`.
-- `project resource add` supports shortcuts for `github_repo` (`--url`, non-JSON `--ref` for checkout ref, `--default-branch-hint`) and `local_directory` (`--local-path`, `--daemon-id`, `--ref-label`), or generic JSON `--ref '<json>'`.
+- `project resource add` supports shortcuts for `github_repo` (`--url`, non-JSON `--ref` for checkout ref, `--default-branch-hint`) and `local_directory` (`--local-path`, `--daemon-id`, `--ref-label`, `--execution-mode`), or generic JSON `--ref '<json>'`.
+- `local_directory.execution_mode` is validated in `server/internal/handler/project_resource.go` (`validateLocalDirectoryRef`); the daemon reads it in `server/internal/daemon/local_directory.go` (`localDirectoryAssignment.UsesWorktree`) and builds the per-task worktree in `server/internal/daemon/execenv/local_worktree.go`.
+- Saving `execution_mode=worktree` is gated on the daemon's registered `cli_version` by `requireWorktreeCapableDaemon` in `server/internal/handler/project_resource.go` (floor: `MinLocalWorktreeCLIVersion` in `server/pkg/agent/version.go`); too old → HTTP 422 `daemon_version_unsupported`.
- `project resource update` merges shortcut edits with existing `resource_ref` so a partial edit does not clobber required fields; non-JSON `--ref` updates `github_repo.resource_ref.ref`.
- `server/cmd/server/router.go` exposes `/api/projects` plus `/api/projects/{projectId}/resources` routes.
- `server/pkg/db/queries/project_resource.sql` is the CRUD query surface for `project_resource` rows.
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index 5bf6ea4137..ec131f80cf 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -132,7 +132,7 @@ func TestFailTaskProviderNetworkBudget(t *testing.T) {
pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE parent_task_id = $1 OR id = $1`, parentID)
})
- if _, err := svc.FailTask(ctx, parentID, "API Error: Connection closed mid-response.", "src-session", "/tmp/src-workdir", "agent_error.provider_network", false, ""); err != nil {
+ if _, err := svc.FailTask(ctx, parentID, "API Error: Connection closed mid-response.", "src-session", "/tmp/src-workdir", "", "agent_error.provider_network", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index cda806e19c..a187af5b46 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2303,6 +2303,14 @@ type CancelTaskOptions struct {
QueuedOnly bool
ExpectedChatSession pgtype.UUID
QueueAction string
+ // ErrorMessage / FailureReason, when set, are persisted onto the cancelled
+ // row. Only for cancellations the USER did not ask for (e.g. the worktree
+ // claim gate refusing a too-old daemon): a user-initiated cancel needs no
+ // explanation, but a server-initiated one without a persisted reason
+ // surfaces as an unexplained "cancelled" whose only trace is a 4xx in a
+ // daemon log the user never sees.
+ ErrorMessage string
+ FailureReason string
}
// CancelTask cancels a single task by ID. It broadcasts a task:cancelled event
@@ -2321,6 +2329,24 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
return &result.Task, nil
}
+// CancelTaskWithReason cancels a task the SERVER decided to stop, persisting an
+// actionable reason onto the row. It runs the same full cancellation flow as
+// CancelTask — audit capture, chat settle, agent status reconcile,
+// task:cancelled broadcast, NotifyTaskFinished — because a raw
+// CancelAgentTaskWithReason query bypass leaves the agent pill running, the
+// live card stale, and any capacity/serial waiter unwoken.
+func (s *TaskService) CancelTaskWithReason(ctx context.Context, taskID pgtype.UUID, errorMessage, failureReason string) (*db.AgentTaskQueue, error) {
+ result, err := s.CancelTaskWithResult(ctx, taskID, CancelTaskOptions{
+ ClientSupportsDraftRestore: true,
+ ErrorMessage: errorMessage,
+ FailureReason: failureReason,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &result.Task, nil
+}
+
// CancelTaskWithResult cancels a single task and returns any chat-specific
// cleanup result needed by user-facing callers.
func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UUID, opts CancelTaskOptions) (*CancelTaskResult, error) {
@@ -2359,7 +2385,19 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
if err := lockChatSessionForTaskWrite(ctx, qtx, taskID); err != nil {
return err
}
- cancelled, err := qtx.CancelAgentTask(ctx, taskID)
+ var (
+ cancelled db.AgentTaskQueue
+ err error
+ )
+ if opts.ErrorMessage != "" || opts.FailureReason != "" {
+ cancelled, err = qtx.CancelAgentTaskWithReason(ctx, db.CancelAgentTaskWithReasonParams{
+ ID: taskID,
+ Error: pgtype.Text{String: opts.ErrorMessage, Valid: opts.ErrorMessage != ""},
+ FailureReason: pgtype.Text{String: opts.FailureReason, Valid: opts.FailureReason != ""},
+ })
+ } else {
+ cancelled, err = qtx.CancelAgentTask(ctx, taskID)
+ }
if err != nil {
return err
}
@@ -2700,6 +2738,27 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
// atomic, so concurrent callers cannot finalize the same task twice and a
// call with no pending marker is a no-op. The settled outcome is broadcast
// as chat:cancel_finalized since the cancel HTTP response has long returned.
+// RebroadcastCancelledTask re-announces an already-cancelled task after a
+// post-terminal delivery landed on its row (the cancel-ack's branch name or
+// preserved-worktree error). The original task:cancelled broadcast fired at
+// cancel time, BEFORE the daemon's ack — clients may have refetched a row
+// without the delivery and will not refetch again on their own. Consumers
+// treat task:cancelled as idempotent cache invalidation, so a replay is safe.
+func (s *TaskService) RebroadcastCancelledTask(ctx context.Context, taskID pgtype.UUID) {
+ task, err := s.Queries.GetAgentTask(ctx, taskID)
+ if err != nil {
+ slog.Warn("rebroadcast cancelled task: load failed",
+ "task_id", util.UUIDToString(taskID), "error", err)
+ return
+ }
+ if task.Status != "cancelled" {
+ // A complete/fail callback already announced its own terminal event
+ // carrying the row's final fields; nothing stale to refresh.
+ return
+ }
+ s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)
+}
+
func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) {
var (
task db.AgentTaskQueue
@@ -3481,7 +3540,7 @@ func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID
// queued chat message could be claimed in the window between the task
// flipping to 'completed' and chat_session.session_id being refreshed,
// causing the new task to resume against a stale (or NULL) session.
-func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
+func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, result []byte, sessionID, workDir, branchName string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
var task db.AgentTaskQueue
// chatAssistantMsg is the single assistant outcome row written for a chat
// task inside the completion transaction below. It is broadcast (chat:done)
@@ -3496,6 +3555,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
Result: result,
SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ BranchName: pgtype.Text{String: branchName, Valid: branchName != ""},
SessionRolloutMissing: sessionRolloutMissing,
RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
})
@@ -3885,7 +3945,7 @@ func (s *TaskService) observeChatOutputLocalPath(task db.AgentTaskQueue, body st
// coarse bucket. Daemon callers that already produced a refined reason
// (via classifyPoisonedError, the timeout / runtime classifier, etc.)
// will have their value preserved untouched.
-func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, failureReason string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
+func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID string) (*db.AgentTaskQueue, error) {
// MUL-2946: synthesise a refined reason from the error text whenever the
// caller didn't supply one. This is the last write-path guard against
// "agent_error" coarse rows ending up in agent_task_queue.failure_reason
@@ -3954,11 +4014,16 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
return err
}
t, err := qtx.FailAgentTask(ctx, db.FailAgentTaskParams{
- ID: taskID,
- Error: pgtype.Text{String: errMsg, Valid: true},
- FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
- SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
- WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ ID: taskID,
+ Error: pgtype.Text{String: errMsg, Valid: true},
+ FailureReason: pgtype.Text{String: failureReason, Valid: failureReason != ""},
+ SessionID: pgtype.Text{String: sessionID, Valid: sessionID != ""},
+ WorkDir: pgtype.Text{String: workDir, Valid: workDir != ""},
+ // A failed run can still have produced a branch: worktree mode
+ // commits whatever the agent left before tearing the worktree down,
+ // precisely so partial work survives. Dropping the name here would
+ // leave that commit with no pointer to it.
+ BranchName: pgtype.Text{String: branchName, Valid: branchName != ""},
SessionRolloutMissing: sessionRolloutMissing,
RetiredSessionID: pgtype.Text{String: retiredSessionID, Valid: retiredSessionID != ""},
})
diff --git a/server/internal/service/task_channel_seal_race_test.go b/server/internal/service/task_channel_seal_race_test.go
index d5c689b6a3..b965a4f36a 100644
--- a/server/internal/service/task_channel_seal_race_test.go
+++ b/server/internal/service/task_channel_seal_race_test.go
@@ -60,7 +60,7 @@ func TestEnqueueChatTaskSealsMessageStrandedByPredecessorReply(t *testing.T) {
// Turn 1 completes inside that window: its reply row is NEWER than the
// waiting message, but it answers turn 1's batch, not this message.
- if _, err := svc.CompleteTask(ctx, first.ID, []byte(`{"output":"通了。"}`), "", "", false, ""); err != nil {
+ if _, err := svc.CompleteTask(ctx, first.ID, []byte(`{"output":"通了。"}`), "", "", "", false, ""); err != nil {
t.Fatalf("complete turn 1: %v", err)
}
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 5489a27273..ba95376630 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -110,7 +110,7 @@ func TestCompleteTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.CompleteTask(context.Background(), taskID, nil, "", "", false, "")
+ got, err := svc.CompleteTask(context.Background(), taskID, nil, "", "", "", false, "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
@@ -152,7 +152,7 @@ func TestFailTask_AlreadyFinalized(t *testing.T) {
Bus: events.New(),
}
- got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", false, "")
+ got, err := svc.FailTask(context.Background(), taskID, "agent crashed", "", "", "", "", false, "")
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
diff --git a/server/internal/service/task_failure_event_test.go b/server/internal/service/task_failure_event_test.go
index b42865d189..12bae68fe9 100644
--- a/server/internal/service/task_failure_event_test.go
+++ b/server/internal/service/task_failure_event_test.go
@@ -120,7 +120,7 @@ func TestFailTaskPublishesDeliverableChannelFailure(t *testing.T) {
var got events.Event
bus.Subscribe(protocol.EventTaskFailed, func(e events.Event) { got = e })
svc := &TaskService{Queries: q, TxStarter: pool, Bus: bus}
- if _, err := svc.FailTask(ctx, util.MustParseUUID(taskID), "provider failed", "", "", "agent_error", false, ""); err != nil {
+ if _, err := svc.FailTask(ctx, util.MustParseUUID(taskID), "provider failed", "", "", "", "agent_error", false, ""); err != nil {
t.Fatalf("FailTask: %v", err)
}
diff --git a/server/migrations/308_agent_task_branch_name.down.sql b/server/migrations/308_agent_task_branch_name.down.sql
new file mode 100644
index 0000000000..77e9609fdd
--- /dev/null
+++ b/server/migrations/308_agent_task_branch_name.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS branch_name;
diff --git a/server/migrations/308_agent_task_branch_name.up.sql b/server/migrations/308_agent_task_branch_name.up.sql
new file mode 100644
index 0000000000..df30975f5c
--- /dev/null
+++ b/server/migrations/308_agent_task_branch_name.up.sql
@@ -0,0 +1,31 @@
+-- Records the git branch a task delivered its work on.
+--
+-- Worktree-mode local_directory tasks hand their result back as a branch in the
+-- user's own repo rather than as edits to the working copy, so the branch name
+-- is the only pointer to where the work went. It is written on BOTH terminal
+-- paths: a task that fails partway still commits whatever the agent produced,
+-- and that is exactly when the user most needs to be told where to look.
+--
+-- Nullable and unindexed on purpose: only worktree tasks populate it, and it is
+-- read alongside the task row that is already being fetched by primary key.
+ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS branch_name TEXT;
+
+-- Rollout / rollback note for worktree mode (MUL-5707).
+--
+-- Isolation for a worktree resource is enforced in two places, both of which
+-- live in server code shipped with this migration: the save-time daemon-version
+-- gate, and the claim-time gate that re-checks the runtime actually taking the
+-- task. Those cover a daemon downgraded at any point after the resource was
+-- created.
+--
+-- The one combination they cannot cover is rolling the SERVER back to before
+-- this change while a daemon below MinLocalWorktreeCLIVersion is still in the
+-- fleet: an old server has no gate, and an old daemon json-skips execution_mode
+-- and would run the task in place, editing the working copy the resource asked
+-- to isolate. So: do not roll the server back past this change while any
+-- worktree local_directory resource exists, unless every daemon in those
+-- workspaces is at or above the floor.
+--
+-- Rolling the server back with only CURRENT daemons is safe for isolation — a
+-- current daemon implements the mode itself and refuses modes it does not
+-- recognise. The only loss is branch_name, which an old server drops.
diff --git a/server/pkg/agent/version.go b/server/pkg/agent/version.go
index 41bf227047..255a8f48bb 100644
--- a/server/pkg/agent/version.go
+++ b/server/pkg/agent/version.go
@@ -34,6 +34,19 @@ const MinQuickCreateCLIVersion = "0.2.21"
// older floor above; only requests using these optional fields need this gate.
const MinQuickCreateFieldsCLIVersion = "0.4.3"
+// MinLocalWorktreeCLIVersion is the first daemon release that implements
+// execution_mode=worktree for local_directory resources (MUL-5707). A daemon
+// older than this does not know the field exists: it json-skips it and runs
+// the task IN PLACE, editing the working copy the user explicitly asked to
+// isolate. (Daemons FROM this version refuse unknown future modes themselves —
+// see localDirectoryAssignment.ValidateExecutionMode — but a daemon that
+// predates the field cannot refuse what it cannot see, so the server has to.)
+// The handler rejects saving a worktree-mode resource while the owning
+// daemon's registered CLI version is missing or below this floor. Hard
+// requirement, fail closed. Keep in sync with the release that actually ships
+// worktree mode when tagging.
+const MinLocalWorktreeCLIVersion = "0.4.24"
+
// MinHandoffCLIVersion is the lowest multica CLI version whose daemon renders
// the assignment handoff note into the run's opening prompt + issue_context.md
// (MUL-3375). Unlike quick-create this is a SOFT gate: assigning an issue with
diff --git a/server/pkg/agent/worktree_version_floor_test.go b/server/pkg/agent/worktree_version_floor_test.go
new file mode 100644
index 0000000000..f07d88d98b
--- /dev/null
+++ b/server/pkg/agent/worktree_version_floor_test.go
@@ -0,0 +1,32 @@
+package agent
+
+import (
+ "os"
+ "path/filepath"
+ "regexp"
+ "testing"
+)
+
+// The worktree version floor is enforced in three places that must agree:
+//
+// server — refuses to save a worktree resource below it, and refuses to hand
+// a worktree task to a runtime below it at claim time;
+// frontend — disables the option and explains why before the user submits.
+//
+// If they drift, the UI offers a mode the server will refuse, or worse, the
+// frontend permits a version the server no longer gates. Pin them together.
+func TestWorktreeCLIVersionFloorMatchesFrontend(t *testing.T) {
+ path := filepath.Join("..", "..", "..", "packages", "core", "runtimes", "cli-version.ts")
+ src, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ m := regexp.MustCompile(`MIN_LOCAL_WORKTREE_CLI_VERSION\s*=\s*"([^"]+)"`).FindSubmatch(src)
+ if m == nil {
+ t.Fatal("MIN_LOCAL_WORKTREE_CLI_VERSION not found in packages/core/runtimes/cli-version.ts")
+ }
+ if got := string(m[1]); got != MinLocalWorktreeCLIVersion {
+ t.Errorf("frontend floor %s != server floor %s; the save gate, the claim gate and the UI must agree",
+ got, MinLocalWorktreeCLIVersion)
+ }
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 68f80788e5..dd1769d3e5 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -204,7 +204,7 @@ const cancelAgentTask = `-- name: CancelAgentTask :one
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
@@ -263,6 +263,93 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
+ )
+ return i, err
+}
+
+const cancelAgentTaskWithReason = `-- name: CancelAgentTaskWithReason :one
+UPDATE agent_task_queue
+SET status = 'cancelled',
+ completed_at = now(),
+ error = $1,
+ failure_reason = $2,
+ prepare_lease_expires_at = NULL
+WHERE id = $3 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
+`
+
+type CancelAgentTaskWithReasonParams struct {
+ Error pgtype.Text `json:"error"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Cancels a task AND records why, for cancellations the user did not ask for.
+//
+// Plain CancelAgentTask leaves error/failure_reason NULL, which is right for a
+// user-initiated cancel — the user knows why. A server-initiated one is the
+// opposite: without a persisted reason the run surfaces as an unexplained
+// "cancelled", and the only trace is a 4xx in a daemon log the user never sees.
+// Retrying cannot help either (the task is refused for a durable reason), so
+// this is a terminal state that has to carry its own explanation.
+func (q *Queries) CancelAgentTaskWithReason(ctx context.Context, arg CancelAgentTaskWithReasonParams) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, cancelAgentTaskWithReason, arg.Error, arg.FailureReason, arg.ID)
+ var i AgentTaskQueue
+ err := row.Scan(
+ &i.ID,
+ &i.AgentID,
+ &i.IssueID,
+ &i.Status,
+ &i.Priority,
+ &i.DispatchedAt,
+ &i.StartedAt,
+ &i.CompletedAt,
+ &i.Result,
+ &i.Error,
+ &i.CreatedAt,
+ &i.Context,
+ &i.RuntimeID,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.TriggerCommentID,
+ &i.ChatSessionID,
+ &i.AutopilotRunID,
+ &i.Attempt,
+ &i.MaxAttempts,
+ &i.ParentTaskID,
+ &i.FailureReason,
+ &i.TriggerSummary,
+ &i.ForceFreshSession,
+ &i.IsLeaderTask,
+ &i.WaitReason,
+ &i.InitiatorUserID,
+ &i.HandoffNote,
+ &i.PrepareLeaseExpiresAt,
+ &i.SquadID,
+ &i.RuntimeMcpOverlay,
+ &i.EscalationForTaskID,
+ &i.FireAt,
+ &i.OriginatorUserID,
+ &i.RuntimeConnectedApps,
+ &i.CoalescedCommentIds,
+ &i.DeliveredCommentIds,
+ &i.ChatInputTaskID,
+ &i.ChatFinalizeDeferredAt,
+ &i.OriginatorSource,
+ &i.DelegatedFromTaskID,
+ &i.RetryOfTaskID,
+ &i.RerunOfTaskID,
+ &i.RuleVersionID,
+ &i.TriggerEvidenceKind,
+ &i.TriggerEvidenceRefID,
+ &i.AccountableUserID,
+ &i.SessionRolloutMissing,
+ &i.RetiredSessionID,
+ &i.QuickActionsDisabled,
+ &i.RegenerateQuickActionsFor,
+ &i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -271,7 +358,7 @@ const cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Bulk-cancel every active (queued/dispatched/running) task for an agent.
@@ -341,6 +428,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -356,7 +444,7 @@ const cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :m
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Cancels active tasks belonging to a chat session. Called from
@@ -426,6 +514,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -441,7 +530,7 @@ const cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :many
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Cancels every active task on the issue and returns the affected rows so the
@@ -511,6 +600,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -526,7 +616,7 @@ const cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgen
UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CancelAgentTasksByIssueAndAgentParams struct {
@@ -600,6 +690,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -616,7 +707,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE (trigger_comment_id = $1 OR $1 = ANY(coalesced_comment_ids))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Cancels active tasks whose planned batch contains the edited/deleted comment.
@@ -685,6 +776,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -705,9 +797,9 @@ WITH cancelled AS (
AND fallback.status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
AND primary_task.issue_id = $1
AND primary_task.agent_id = $2
- RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.plugin_execution_manifest_id
+ RETURNING fallback.id, fallback.agent_id, fallback.issue_id, fallback.status, fallback.priority, fallback.dispatched_at, fallback.started_at, fallback.completed_at, fallback.result, fallback.error, fallback.created_at, fallback.context, fallback.runtime_id, fallback.session_id, fallback.work_dir, fallback.trigger_comment_id, fallback.chat_session_id, fallback.autopilot_run_id, fallback.attempt, fallback.max_attempts, fallback.parent_task_id, fallback.failure_reason, fallback.trigger_summary, fallback.force_fresh_session, fallback.is_leader_task, fallback.wait_reason, fallback.initiator_user_id, fallback.handoff_note, fallback.prepare_lease_expires_at, fallback.squad_id, fallback.runtime_mcp_overlay, fallback.escalation_for_task_id, fallback.fire_at, fallback.originator_user_id, fallback.runtime_connected_apps, fallback.coalesced_comment_ids, fallback.delivered_comment_ids, fallback.chat_input_task_id, fallback.chat_finalize_deferred_at, fallback.originator_source, fallback.delegated_from_task_id, fallback.retry_of_task_id, fallback.rerun_of_task_id, fallback.rule_version_id, fallback.trigger_evidence_kind, fallback.trigger_evidence_ref_id, fallback.accountable_user_id, fallback.session_rollout_missing, fallback.retired_session_id, fallback.quick_actions_disabled, fallback.regenerate_quick_actions_for, fallback.plugin_execution_manifest_id, fallback.branch_name
)
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM cancelled
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM cancelled
`
type CancelDeferredEscalationsForIssueAgentParams struct {
@@ -768,6 +860,7 @@ type CancelDeferredEscalationsForIssueAgentRow struct {
QuickActionsDisabled bool `json:"quick_actions_disabled"`
RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
PluginExecutionManifestID pgtype.UUID `json:"plugin_execution_manifest_id"`
+ BranchName pgtype.Text `json:"branch_name"`
}
func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, arg CancelDeferredEscalationsForIssueAgentParams) ([]CancelDeferredEscalationsForIssueAgentRow, error) {
@@ -832,6 +925,7 @@ func (q *Queries) CancelDeferredEscalationsForIssueAgent(ctx context.Context, ar
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -848,7 +942,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE escalation_for_task_id = $1
AND status IN ('deferred', 'queued', 'dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalationForTaskID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -913,6 +1007,7 @@ func (q *Queries) CancelDeferredEscalationsForTask(ctx context.Context, escalati
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -930,7 +1025,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1
AND chat_session_id = $2
AND status = 'queued'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CancelQueuedAgentTaskParams struct {
@@ -996,6 +1091,7 @@ func (q *Queries) CancelQueuedAgentTask(ctx context.Context, arg CancelQueuedAge
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -1023,7 +1119,7 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE queued.chat_session_id = $1
AND queued.status = 'queued'
AND queued.id IS DISTINCT FROM (SELECT id FROM head)
-RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.plugin_execution_manifest_id
+RETURNING queued.id, queued.agent_id, queued.issue_id, queued.status, queued.priority, queued.dispatched_at, queued.started_at, queued.completed_at, queued.result, queued.error, queued.created_at, queued.context, queued.runtime_id, queued.session_id, queued.work_dir, queued.trigger_comment_id, queued.chat_session_id, queued.autopilot_run_id, queued.attempt, queued.max_attempts, queued.parent_task_id, queued.failure_reason, queued.trigger_summary, queued.force_fresh_session, queued.is_leader_task, queued.wait_reason, queued.initiator_user_id, queued.handoff_note, queued.prepare_lease_expires_at, queued.squad_id, queued.runtime_mcp_overlay, queued.escalation_for_task_id, queued.fire_at, queued.originator_user_id, queued.runtime_connected_apps, queued.coalesced_comment_ids, queued.delivered_comment_ids, queued.chat_input_task_id, queued.chat_finalize_deferred_at, queued.originator_source, queued.delegated_from_task_id, queued.retry_of_task_id, queued.rerun_of_task_id, queued.rule_version_id, queued.trigger_evidence_kind, queued.trigger_evidence_ref_id, queued.accountable_user_id, queued.session_rollout_missing, queued.retired_session_id, queued.quick_actions_disabled, queued.regenerate_quick_actions_for, queued.plugin_execution_manifest_id, queued.branch_name
`
// Clear only positional follow-ups. The first visible task is current even
@@ -1092,6 +1188,7 @@ func (q *Queries) CancelQueuedAgentTasksForSession(ctx context.Context, chatSess
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -1132,7 +1229,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type ClaimAgentTaskParams struct {
@@ -1205,6 +1302,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, arg ClaimAgentTaskParams)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -1213,7 +1311,7 @@ const claimChatFinalizeDeferred = `-- name: ClaimChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = NULL
WHERE id = $1 AND chat_finalize_deferred_at IS NOT NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Atomically claims the deferred marker so the daemon ack and the sweeper
@@ -1274,6 +1372,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -1462,11 +1561,12 @@ UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2,
session_id = CASE WHEN $5 THEN NULL ELSE $3 END,
work_dir = $4,
+ branch_name = COALESCE($6, branch_name),
session_rollout_missing = $5,
- retired_session_id = COALESCE($6, retired_session_id),
+ retired_session_id = COALESCE($7, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status = 'running'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CompleteAgentTaskParams struct {
@@ -1475,6 +1575,7 @@ type CompleteAgentTaskParams struct {
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
SessionRolloutMissing bool `json:"session_rollout_missing"`
+ BranchName pgtype.Text `json:"branch_name"`
RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
@@ -1496,6 +1597,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
arg.SessionID,
arg.WorkDir,
arg.SessionRolloutMissing,
+ arg.BranchName,
arg.RetiredSessionID,
)
var i AgentTaskQueue
@@ -1552,6 +1654,7 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -1772,7 +1875,7 @@ SELECT
$21,
$22
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateAgentTaskParams struct {
@@ -1890,6 +1993,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -1916,7 +2020,7 @@ SELECT
$18,
$19
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateDeferredAgentTaskParams struct {
@@ -2028,6 +2132,7 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferre
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2064,7 +2169,7 @@ SELECT
$22,
$23
WHERE lock_task_owner_rows($1, $3, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateDeferredChannelIssueTaskParams struct {
@@ -2180,6 +2285,7 @@ func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg Create
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2200,7 +2306,7 @@ SELECT
$10,
$11
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateQuickCreateTaskParams struct {
@@ -2295,6 +2401,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2331,7 +2438,7 @@ SELECT
FROM agent_task_queue p
WHERE p.id = $1
AND lock_task_owner_rows(p.agent_id, p.issue_id, p.runtime_id)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateRetryTaskParams struct {
@@ -2460,6 +2567,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2585,7 +2693,7 @@ FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.plugin_execution_manifest_id
+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing, t.retired_session_id, t.quick_actions_disabled, t.regenerate_quick_actions_for, t.plugin_execution_manifest_id, t.branch_name
`
type ExpireStaleQueuedTasksParams struct {
@@ -2678,6 +2786,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -2696,7 +2805,7 @@ WHERE id = $1
AND runtime_id = $2
AND status IN ('dispatched', 'waiting_local_directory')
AND started_at IS NULL
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type ExtendAgentTaskPrepareLeaseParams struct {
@@ -2765,6 +2874,7 @@ func (q *Queries) ExtendAgentTaskPrepareLease(ctx context.Context, arg ExtendAge
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2777,11 +2887,12 @@ SET status = 'failed',
failure_reason = COALESCE($3, 'agent_error'),
session_id = CASE WHEN $4 THEN NULL ELSE COALESCE($5, session_id) END,
work_dir = COALESCE($6, work_dir),
+ branch_name = COALESCE($7, branch_name),
session_rollout_missing = $4,
- retired_session_id = COALESCE($7, retired_session_id),
+ retired_session_id = COALESCE($8, retired_session_id),
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type FailAgentTaskParams struct {
@@ -2791,6 +2902,7 @@ type FailAgentTaskParams struct {
SessionRolloutMissing bool `json:"session_rollout_missing"`
SessionID pgtype.Text `json:"session_id"`
WorkDir pgtype.Text `json:"work_dir"`
+ BranchName pgtype.Text `json:"branch_name"`
RetiredSessionID pgtype.Text `json:"retired_session_id"`
}
@@ -2817,6 +2929,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
arg.SessionRolloutMissing,
arg.SessionID,
arg.WorkDir,
+ arg.BranchName,
arg.RetiredSessionID,
)
var i AgentTaskQueue
@@ -2873,6 +2986,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2897,7 +3011,7 @@ WHERE (
AND r.last_seen_at >= now() - make_interval(secs => $3::double precision)
)
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type FailStaleTasksParams struct {
@@ -3005,6 +3119,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -3241,7 +3356,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa
}
const getAgentTask = `-- name: GetAgentTask :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE id = $1
`
@@ -3301,12 +3416,13 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
const getAgentTaskInWorkspace = `-- name: GetAgentTaskInWorkspace :one
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE atq.id = $1 AND a.workspace_id = $2
`
@@ -3379,6 +3495,7 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -4055,7 +4172,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim
}
const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
ORDER BY created_at DESC
`
@@ -4127,6 +4244,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4139,7 +4257,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI
}
const listAgentTasks = `-- name: ListAgentTasks :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE agent_id = $1
ORDER BY created_at DESC
`
@@ -4206,6 +4324,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4393,7 +4512,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U
}
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
AND chat_finalize_deferred_at < now() - make_interval(secs => $1::double precision)
ORDER BY chat_finalize_deferred_at
@@ -4470,6 +4589,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4482,7 +4602,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE runtime_id = $1 AND status IN ('queued', 'dispatched')
ORDER BY priority DESC, created_at ASC
`
@@ -4549,6 +4669,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4561,7 +4682,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp
}
const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE runtime_id = $1 AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -4636,6 +4757,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4648,7 +4770,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim
}
const listQueuedClaimCandidatesByRuntimes = `-- name: ListQueuedClaimCandidatesByRuntimes :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE runtime_id = ANY($1::uuid[]) AND status = 'queued'
ORDER BY priority DESC, created_at ASC
`
@@ -4725,6 +4847,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4737,7 +4860,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntimes(ctx context.Context, runti
}
const listTasksByIssue = `-- name: ListTasksByIssue :many
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE issue_id = $1
ORDER BY created_at DESC
`
@@ -4804,6 +4927,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -4877,16 +5001,16 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI
}
const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many
-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id FROM agent_task_queue atq
+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
UNION ALL
-SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.plugin_execution_manifest_id FROM agent a
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing, latest.retired_session_id, latest.quick_actions_disabled, latest.regenerate_quick_actions_for, latest.plugin_execution_manifest_id, latest.branch_name FROM agent a
JOIN LATERAL (
- SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing, atq.retired_session_id, atq.quick_actions_disabled, atq.regenerate_quick_actions_for, atq.plugin_execution_manifest_id, atq.branch_name
FROM agent_task_queue atq
WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
@@ -4983,6 +5107,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -5232,7 +5357,7 @@ SET status = 'waiting_local_directory',
wait_reason = $2,
prepare_lease_expires_at = now() + make_interval(secs => $3::double precision)
WHERE id = $1 AND status = 'dispatched'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type MarkAgentTaskWaitingLocalDirectoryParams struct {
@@ -5306,6 +5431,7 @@ func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg Ma
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -5314,7 +5440,7 @@ const markChatFinalizeDeferred = `-- name: MarkChatFinalizeDeferred :one
UPDATE agent_task_queue
SET chat_finalize_deferred_at = now()
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Arms the deferred chat-finalize marker for a cancelled chat task whose
@@ -5375,6 +5501,7 @@ func (q *Queries) MarkChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -5517,7 +5644,7 @@ const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTas
UPDATE agent_task_queue
SET status = 'queued', fire_at = NULL
WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Early promotion is idempotent at the service layer: a task already promoted
@@ -5578,6 +5705,7 @@ func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -5588,7 +5716,7 @@ SET status = 'queued'
WHERE runtime_id = $1
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {
@@ -5653,6 +5781,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntime(ctx context.Context, runtime
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -5670,7 +5799,7 @@ SET status = 'queued'
WHERE runtime_id = ANY($1::uuid[])
AND status = 'deferred'
AND fire_at <= now()
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all
@@ -5737,6 +5866,7 @@ func (q *Queries) PromoteDueDeferredTasksForRuntimes(ctx context.Context, runtim
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -5837,7 +5967,7 @@ WHERE id = (
LIMIT 1
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type ReclaimStaleDispatchedTaskForRuntimeParams struct {
@@ -5907,6 +6037,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -5926,7 +6057,7 @@ WHERE id IN (
LIMIT $4::int
FOR UPDATE SKIP LOCKED
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type ReclaimStaleDispatchedTasksForRuntimesParams struct {
@@ -6010,6 +6141,7 @@ func (q *Queries) ReclaimStaleDispatchedTasksForRuntimes(ctx context.Context, ar
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -6030,7 +6162,7 @@ SET status = 'failed',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Called by the daemon at startup. Atomically fails any dispatched/running/
@@ -6101,6 +6233,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -6248,7 +6381,7 @@ WHERE id = $1
AND status = 'dispatched'
AND started_at IS NULL
AND dispatched_at = $3
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type RequeueAgentTaskAfterClaimFailureParams struct {
@@ -6318,6 +6451,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Req
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -6364,6 +6498,60 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro
return i, err
}
+const setAgentTaskBranchName = `-- name: SetAgentTaskBranchName :exec
+UPDATE agent_task_queue
+SET branch_name = COALESCE(branch_name, $1)
+WHERE id = $2 AND status = 'cancelled'
+`
+
+type SetAgentTaskBranchNameParams struct {
+ BranchName pgtype.Text `json:"branch_name"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Records the delivered branch on a CANCELLED task. Needed because the daemon
+// finalizes its worktree (committing whatever the agent produced) BEFORE it
+// learns the task was cancelled, so the branch exists but the cancel path has
+// no result payload to carry it. Without this the branch is real and
+// completely undiscoverable from the UI.
+//
+// Never overwrites a name already recorded by a complete/fail callback, and
+// never touches any OTHER terminal state: the daemon acks on every terminal
+// status it observes, so a late or replayed ack from a stale run could
+// otherwise write its branch into a completed/failed row whose own callback —
+// the authoritative channel for those states — recorded nothing. status is
+// stable once terminal, so this CAS cannot race a legitimate write.
+func (q *Queries) SetAgentTaskBranchName(ctx context.Context, arg SetAgentTaskBranchNameParams) error {
+ _, err := q.db.Exec(ctx, setAgentTaskBranchName, arg.BranchName, arg.ID)
+ return err
+}
+
+const setAgentTaskErrorIfEmpty = `-- name: SetAgentTaskErrorIfEmpty :exec
+UPDATE agent_task_queue
+SET error = $1,
+ failure_reason = COALESCE(failure_reason, $2)
+WHERE id = $3 AND (error IS NULL OR error = '') AND status = 'cancelled'
+`
+
+type SetAgentTaskErrorIfEmptyParams struct {
+ Error pgtype.Text `json:"error"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Companion to SetAgentTaskBranchName for the cancel-ack path. A cancelled
+// worktree task whose Finalize ABORTED has no branch to deliver — the error
+// text carrying the preserved-worktree path is the only pointer to the agent's
+// work, and the cancel flow discarded the rest of the result. A user-initiated
+// cancel leaves error NULL, so filling it here never overwrites a reason
+// recorded by a fail callback or the claim gate; the status CAS keeps a late
+// ack from stamping an error onto a completed/failed row (see
+// SetAgentTaskBranchName above).
+func (q *Queries) SetAgentTaskErrorIfEmpty(ctx context.Context, arg SetAgentTaskErrorIfEmptyParams) error {
+ _, err := q.db.Exec(ctx, setAgentTaskErrorIfEmpty, arg.Error, arg.FailureReason, arg.ID)
+ return err
+}
+
const setDeferredChannelIssueTaskRuntimeOverlay = `-- name: SetDeferredChannelIssueTaskRuntimeOverlay :execrows
UPDATE agent_task_queue
SET runtime_mcp_overlay = $1,
@@ -6452,7 +6640,7 @@ SET status = 'running',
wait_reason = NULL,
prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Transitions a task to running. Accepts either 'dispatched' (the normal
@@ -6517,6 +6705,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index 2ba37ff479..74b20a80a5 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -289,7 +289,7 @@ SELECT
$10,
$11
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateAutopilotTaskParams struct {
@@ -393,6 +393,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -756,7 +757,7 @@ func (q *Queries) GetAutopilotRunByWebhookDelivery(ctx context.Context, webhookD
}
const getAutopilotTaskByRun = `-- name: GetAutopilotTaskByRun :one
-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id FROM agent_task_queue
+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name FROM agent_task_queue
WHERE autopilot_run_id = $1
ORDER BY created_at
LIMIT 1
@@ -820,6 +821,7 @@ func (q *Queries) GetAutopilotTaskByRun(ctx context.Context, autopilotRunID pgty
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 464a9e9858..24cedb66ef 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -354,7 +354,7 @@ SELECT
$14,
$6::timestamptz
WHERE lock_task_owner_rows($1, NULL, $2)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CreateChatTaskParams struct {
@@ -452,6 +452,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -519,7 +520,7 @@ FROM (
WHERE task.id = $1
AND pending.max_until IS NOT NULL
AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name
`
// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
@@ -584,6 +585,7 @@ func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
@@ -2434,7 +2436,7 @@ WHERE task.chat_session_id = $1
AND message.message_kind != 'channel_command'
AND message.channel_media_pending_until > now()
)
-RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing, task.retired_session_id, task.quick_actions_disabled, task.regenerate_quick_actions_for, task.plugin_execution_manifest_id, task.branch_name
`
// Media completion may race with the 3s run batcher. Promote every original
@@ -2505,6 +2507,7 @@ func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatS
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -2843,7 +2846,7 @@ const setChatTaskInputOwnerSelf = `-- name: SetChatTaskInputOwnerSelf :one
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Stamps a freshly-created direct-chat task as the owner of its own input batch
@@ -2909,6 +2912,7 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
)
return i, err
}
diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.go
index a0a9793645..d7f906ed9f 100644
--- a/server/pkg/db/generated/dingtalk.sql.go
+++ b/server/pkg/db/generated/dingtalk.sql.go
@@ -260,6 +260,9 @@ type GetDingTalkGroupRouteInWorkspaceParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
}
+// Handler diagnosis deliberately uses the same active-installation boundary as
+// reassignment. Retained routes stay available for reconnect internally, but a
+// revoked installation's route is not a PATCH-visible resource.
func (q *Queries) GetDingTalkGroupRouteInWorkspace(ctx context.Context, arg GetDingTalkGroupRouteInWorkspaceParams) (DingtalkGroupRoute, error) {
row := q.db.QueryRow(ctx, getDingTalkGroupRouteInWorkspace, arg.ID, arg.WorkspaceID)
var i DingtalkGroupRoute
@@ -420,14 +423,14 @@ const reassignDingTalkGroupRoute = `-- name: ReassignDingTalkGroupRoute :one
WITH workspace_guard AS MATERIALIZED (
SELECT w.id
FROM workspace w
- WHERE w.id = $2
+ WHERE w.id = $1
FOR KEY SHARE
), target_agent AS MATERIALIZED (
SELECT a.id
FROM agent a
JOIN workspace_guard w ON w.id = a.workspace_id
- WHERE a.id = $1
- AND a.workspace_id = $2
+ WHERE a.id = $2
+ AND a.workspace_id = $1
AND a.kind = 'user'
AND a.archived_at IS NULL
FOR SHARE
@@ -436,8 +439,8 @@ WITH workspace_guard AS MATERIALIZED (
FROM channel_installation i
JOIN dingtalk_group_route r ON r.installation_id = i.id
WHERE r.id = $3
- AND r.workspace_id = $2
- AND i.workspace_id = $2
+ AND r.workspace_id = $1
+ AND i.workspace_id = $1
AND i.channel_type = 'dingtalk'
AND i.status = 'active'
AND EXISTS (SELECT 1 FROM target_agent)
@@ -447,11 +450,11 @@ WITH workspace_guard AS MATERIALIZED (
FROM dingtalk_group_route r
JOIN active_installation i ON i.id = r.installation_id
WHERE r.id = $3
- AND r.workspace_id = $2
+ AND r.workspace_id = $1
FOR UPDATE OF r
), updated AS (
UPDATE dingtalk_group_route r
- SET agent_id = $1,
+ SET agent_id = $2,
revision = r.revision + 1,
updated_at = now()
FROM target t
@@ -474,8 +477,8 @@ FROM updated
`
type ReassignDingTalkGroupRouteParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
ID pgtype.UUID `json:"id"`
}
@@ -503,7 +506,7 @@ type ReassignDingTalkGroupRouteRow struct {
// PATCH-first may finish before revoke, while revoke-first makes PATCH wait,
// re-check status, and return no row without touching the route or binding.
func (q *Queries) ReassignDingTalkGroupRoute(ctx context.Context, arg ReassignDingTalkGroupRouteParams) (ReassignDingTalkGroupRouteRow, error) {
- row := q.db.QueryRow(ctx, reassignDingTalkGroupRoute, arg.AgentID, arg.WorkspaceID, arg.ID)
+ row := q.db.QueryRow(ctx, reassignDingTalkGroupRoute, arg.WorkspaceID, arg.AgentID, arg.ID)
var i ReassignDingTalkGroupRouteRow
err := row.Scan(
&i.ID,
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 7ec96f1bf4..08a577458c 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -162,6 +162,7 @@ type AgentTaskQueue struct {
QuickActionsDisabled bool `json:"quick_actions_disabled"`
RegenerateQuickActionsFor pgtype.UUID `json:"regenerate_quick_actions_for"`
PluginExecutionManifestID pgtype.UUID `json:"plugin_execution_manifest_id"`
+ BranchName pgtype.Text `json:"branch_name"`
}
type AgentToLabel struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index ad15cd0d8f..c0f4c8f0ec 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -16,7 +16,7 @@ UPDATE agent_task_queue
SET status = 'cancelled', completed_at = now()
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
type CancelAgentTasksByRuntimeOrAgentParams struct {
@@ -108,6 +108,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
@@ -226,7 +227,7 @@ WHERE status IN ('dispatched', 'running', 'waiting_local_directory')
AND runtime_id IN (
SELECT id FROM agent_runtime WHERE status = 'offline'
)
-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id
+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, plugin_execution_manifest_id, branch_name
`
// Marks dispatched/running/waiting_local_directory tasks as failed when
@@ -294,6 +295,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ
&i.QuickActionsDisabled,
&i.RegenerateQuickActionsFor,
&i.PluginExecutionManifestID,
+ &i.BranchName,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index e4e99a013b..45bc0a480a 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -811,6 +811,7 @@ UPDATE agent_task_queue
SET status = 'completed', completed_at = now(), result = $2,
session_id = CASE WHEN sqlc.arg('session_rollout_missing') THEN NULL ELSE $3 END,
work_dir = $4,
+ branch_name = COALESCE(sqlc.narg('branch_name'), branch_name),
session_rollout_missing = sqlc.arg('session_rollout_missing'),
retired_session_id = COALESCE(sqlc.narg('retired_session_id'), retired_session_id),
prepare_lease_expires_at = NULL
@@ -1043,6 +1044,7 @@ SET status = 'failed',
failure_reason = COALESCE(sqlc.narg('failure_reason'), 'agent_error'),
session_id = CASE WHEN sqlc.arg('session_rollout_missing') THEN NULL ELSE COALESCE(sqlc.narg('session_id'), session_id) END,
work_dir = COALESCE(sqlc.narg('work_dir'), work_dir),
+ branch_name = COALESCE(sqlc.narg('branch_name'), branch_name),
session_rollout_missing = sqlc.arg('session_rollout_missing'),
retired_session_id = COALESCE(sqlc.narg('retired_session_id'), retired_session_id),
prepare_lease_expires_at = NULL
@@ -1197,6 +1199,55 @@ SET status = 'cancelled', completed_at = now(), prepare_lease_expires_at = NULL
WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
RETURNING *;
+-- name: SetAgentTaskBranchName :exec
+-- Records the delivered branch on a CANCELLED task. Needed because the daemon
+-- finalizes its worktree (committing whatever the agent produced) BEFORE it
+-- learns the task was cancelled, so the branch exists but the cancel path has
+-- no result payload to carry it. Without this the branch is real and
+-- completely undiscoverable from the UI.
+--
+-- Never overwrites a name already recorded by a complete/fail callback, and
+-- never touches any OTHER terminal state: the daemon acks on every terminal
+-- status it observes, so a late or replayed ack from a stale run could
+-- otherwise write its branch into a completed/failed row whose own callback —
+-- the authoritative channel for those states — recorded nothing. status is
+-- stable once terminal, so this CAS cannot race a legitimate write.
+UPDATE agent_task_queue
+SET branch_name = COALESCE(branch_name, sqlc.arg('branch_name'))
+WHERE id = sqlc.arg('id') AND status = 'cancelled';
+
+-- name: SetAgentTaskErrorIfEmpty :exec
+-- Companion to SetAgentTaskBranchName for the cancel-ack path. A cancelled
+-- worktree task whose Finalize ABORTED has no branch to deliver — the error
+-- text carrying the preserved-worktree path is the only pointer to the agent's
+-- work, and the cancel flow discarded the rest of the result. A user-initiated
+-- cancel leaves error NULL, so filling it here never overwrites a reason
+-- recorded by a fail callback or the claim gate; the status CAS keeps a late
+-- ack from stamping an error onto a completed/failed row (see
+-- SetAgentTaskBranchName above).
+UPDATE agent_task_queue
+SET error = sqlc.arg('error'),
+ failure_reason = COALESCE(failure_reason, sqlc.arg('failure_reason'))
+WHERE id = sqlc.arg('id') AND (error IS NULL OR error = '') AND status = 'cancelled';
+
+-- name: CancelAgentTaskWithReason :one
+-- Cancels a task AND records why, for cancellations the user did not ask for.
+--
+-- Plain CancelAgentTask leaves error/failure_reason NULL, which is right for a
+-- user-initiated cancel — the user knows why. A server-initiated one is the
+-- opposite: without a persisted reason the run surfaces as an unexplained
+-- "cancelled", and the only trace is a 4xx in a daemon log the user never sees.
+-- Retrying cannot help either (the task is refused for a durable reason), so
+-- this is a terminal state that has to carry its own explanation.
+UPDATE agent_task_queue
+SET status = 'cancelled',
+ completed_at = now(),
+ error = sqlc.arg('error'),
+ failure_reason = sqlc.arg('failure_reason'),
+ prepare_lease_expires_at = NULL
+WHERE id = sqlc.arg('id') AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')
+RETURNING *;
+
-- name: CancelQueuedAgentTask :one
-- Queue editing is a compare-and-set: never cancel a task that the daemon
-- promoted between the user's click and this statement.