Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7063 fix(cursor): bound stalled runs after background shell launch (#8050)
makesomethingshit8661e586f626
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5114811b65..c820dfa359 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -11,6 +11,37 @@ concurrency:cancel-in-progress: truejobs:+ cursor-background-lifecycle:+ needs: changes+ if: ${{ needs.changes.outputs.backend == 'true' }}+ runs-on: ${{ matrix.os }}+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ steps:+ - uses: actions/checkout@v6+ - uses: actions/setup-go@v5+ with:+ go-version: "1.26.x"+ cache-dependency-path: server/go.sum+ - name: Verify Cursor background lifecycle and watchdog races+ shell: bash+ working-directory: server+ # Explicit, verbose selection prevents the Unix regression from silently+ # disappearing behind a build tag or the ordinary Windows test subset.+ run: |+ go test -race ./pkg/agent -v -run 'TestCursorBackground|TestCaptureCursorBackground' -count=1+ go test -race ./internal/daemon -v -run 'Test.*Background.*Watchdog|Test.*IdleWatchdog' -count=1+ - name: Repeat macOS finalization and verify cgo-free ownership+ if: runner.os == 'macOS'+ shell: bash+ working-directory: server+ run: |+ go test ./pkg/agent -run '^TestCursorBackgroundLifecycle/finish$' -count=5+ go test -race ./pkg/agent -run '^TestCursorBackgroundLifecycle/finish$' -count=5+ CGO_ENABLED=0 go test ./pkg/agent -run '^TestCaptureCursorBackground(KernelRejectsStaleIdentity|DetachedSession|LateDescendant)$' -count=1+# Decides whether the heavy frontend validation jobs, the backend Go jobs# and sqlc verification have anything to do.# The frontend jobs validate the web/desktop apps, the shared packages,diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 8a8d19d18d..7352fe6e75 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -234,7 +234,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | デーモン 1 つあたりの同時実行上限 || `MULTICA_AGENT_TIMEOUT` | `0` | 1 回の実行の絶対時間上限。`0` は上限なし || `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 出力もツール実行もない状態の静穏上限。`0` で watchdog 全体を無効化 |-| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | 単一のツール呼び出しが静穏なままでいられる上限。モデルより長い余裕をツールに与えたい場合のみ設定し、`0` はツール実行中に強制停止しません |+| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | 単一のツール呼び出しが静穏なままでいられる上限。モデルより長い余裕をツールに与えたい場合のみ設定し、`0` はツール実行中に強制停止しません。Cursor のバックグラウンドシェルは、起動したプロセスが終了するまで実行中として扱われます。この上限に達すると、デーモンはそれらのプロセスを停止し、Cursor が最終結果を出すための新しい watchdog 予算を与えます。プロセスの所有権やクリーンアップを検証できない場合は、通常の実行キャンセル方針に従います || `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 専用の静穏しきい値 || `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | Codex のセマンティック静穏しきい値。Codex 自身のタイマーはツール実行中かどうかを判別できないため、独自の短い上限を持たず idle / tool 予算の大きい方に追従します || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 初回ターンの無進捗上限を明示的に上書き;`0` はデフォルトを維持。実効の初回ターン待機は依然として `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` と全体の実行タイムアウトに制限される——`MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` をこの値より厳密に大きく(余裕を持たせて)設定すること。さもないと待機はその値で打ち切られ、モデルカタログの起動リトライがスキップされる。同値では不十分:セマンティックタイマーが先に起動するため、同値の場合でもリトライが失われることがある |@@ -256,6 +256,10 @@ MULTICA_CLAUDE_PATH=/opt/bin/claudeMULTICA_CLAUDE_ARGS=--max-turns 40```+Cursor の検証済みバックグラウンドクリーンアップには、Linux 6.9 以降(プロセスグループ pidfd)、macOS カーネルによるプロセス識別子の照会と audit token を用いたシグナル送信のサポート、または Windows で正常に割り当てられた入れ子の Job Object が必要です。macOS では各プロセスへのシグナル送信にカーネルが検証する PID version を用いるため、同一セッションのグループに参加する必要はありません。これらの macOS API は非公開であり、プロセス捕捉時に確認されます。所有権を確保できなかったバックグラウンドプロセスは元のツール結果を返し、ツール watchdog が `0` の場合も含めて通常の idle watchdog に従います。すでに所有している作業は、クリーンアップを確認できない場合も実行中のままです。ツール watchdog を `0` にした場合はこの境界自体が存在せず、所有済みのバックグラウンド作業が生きている限り実行は継続します。その場合の実行は `MULTICA_AGENT_TIMEOUT` だけに制限され、これも既定値は `0` です。++所有している Cursor のバックグラウンドプロセスは、実行が正常に完了したときにも停止されます。したがって、その実行が起動したバックグラウンドサーバーが意図的に終了処理後まで生き残ることはありません。macOS は保持された元の親プロセスの識別子によって後から生まれた子プロセスを認識できますが、観測前に中間プロセスが消えた連鎖は証明できません。そのようなプロセス、追跡対象のグループから外れた作業、および継続的な所有権や送信のエラーは、バックグラウンド作業を残す可能性があります。確認できなかったクリーンアップはログに記録され、「クリーンアップ成功」による回復ウィンドウを与えることはありません。数値の PID やプロセスグループだけを根拠に未知のプロセスを終了させることはありません。+優先順位はコマンドラインフラグ → 環境変数 → `~/.multica/config.json` → 組み込みデフォルトです。watchdog の動作は[デーモンとランタイム](/daemon-runtimes)を参照してください。### デーモン設定の永続化diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 856c2603b2..c0725a29c8 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -234,7 +234,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | 데몬 하나의 동시 실행 상한 || `MULTICA_AGENT_TIMEOUT` | `0` | 단일 실행의 절대 시간 제한. `0`은 제한 없음 || `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 출력과 도구 실행이 모두 없을 때의 무응답 상한. `0`이면 watchdog 전체가 비활성화됩니다 |-| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | 단일 도구 호출이 계속 무응답인 시간 상한. 모델보다 도구에 더 여유를 주고 싶을 때만 따로 설정하며, `0`이면 도구 실행 중에는 강제 종료하지 않습니다 |+| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | 단일 도구 호출이 계속 무응답인 시간 상한. 모델보다 도구에 더 여유를 주고 싶을 때만 따로 설정하며, `0`이면 도구 실행 중에는 강제 종료하지 않습니다. Cursor의 백그라운드 셸은 실행한 프로세스가 종료될 때까지 실행 중으로 간주됩니다. 이 상한에 도달하면 데몬이 해당 프로세스를 정리하고, Cursor가 최종 결과를 내도록 새 watchdog 예산을 부여합니다. 프로세스 소유권이나 정리를 검증할 수 없으면 일반적인 실행 취소 정책이 적용됩니다 || `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 전용 무응답 기준값 || `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | Codex 의미 활동 없음 기준값. Codex 자체 타이머는 도구 실행 중인지 알 수 없으므로 별도의 짧은 상한 대신 idle / tool 예산 중 큰 값을 따릅니다 || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 첫 턴 무진행 상한의 명시적 재정의; `0` 은 기본값 유지. 실제 첫 턴 대기는 여전히 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 및 전체 실행 타임아웃으로 제한됨 — `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 을 이 값보다 엄격히 크게(여유를 두고) 설정해야 하며, 그렇지 않으면 대기가 그 값으로 잘리고 모델 카탈로그 시작 재시도가 건너뛰어짐. 값이 같으면 충분하지 않음: 의미 타이머가 먼저 시작되므로 값이 같을 때도 재시도가 손실될 수 있음 |@@ -256,6 +256,10 @@ MULTICA_CLAUDE_PATH=/opt/bin/claudeMULTICA_CLAUDE_ARGS=--max-turns 40```+Cursor의 검증된 백그라운드 정리에는 Linux 6.9 이상(프로세스 그룹 pidfd), 프로세스 신원 조회와 audit token 시그널링에 대한 macOS 커널 지원, 또는 Windows에서 성공적으로 할당된 중첩 Job Object가 필요합니다. macOS에서는 커널이 검증하는 PID version으로 각 프로세스에 시그널을 보내므로 같은 세션의 그룹에 합류할 필요가 없습니다. 이 macOS API들은 비공개이며 확보 시점에 확인합니다. 소유권을 확보하지 못한 실행은 원래의 도구 결과를 반환하고, 도구 watchdog이 `0`인 경우를 포함해 일반적인 idle watchdog을 따릅니다. 이미 확보한 작업은 정리를 확인할 수 없을 때 계속 실행 중으로 남습니다. 도구 watchdog을 `0`으로 두면 이러한 경계 자체가 없습니다. 확보한 백그라운드 작업이 살아 있는 동안 실행이 계속되며, 이때 실행은 기본값이 역시 `0`인 `MULTICA_AGENT_TIMEOUT`에만 제한됩니다.++확보한 Cursor 백그라운드 프로세스는 실행이 정상적으로 완료될 때도 정리됩니다. 따라서 해당 실행이 시작한 백그라운드 서버가 의도적으로 종료 처리 이후까지 살아남지는 않습니다. macOS는 보존된 원래 부모 프로세스 신원을 통해 나중에 생성된 자식 프로세스를 인식할 수 있지만, 관찰 이전에 중간 프로세스가 사라진 연결 고리는 증명할 수 없습니다. 그러한 프로세스, 추적 중인 그룹을 벗어난 작업, 그리고 지속적인 소유권 또는 시그널링 오류는 백그라운드 작업을 남길 수 있습니다. 확인되지 않은 정리는 로그로 남으며 '정리 성공'에 따른 복구 창을 부여하지 않습니다. 숫자 PID나 프로세스 그룹만을 근거로 알 수 없는 프로세스를 종료하지 않습니다.+우선순위는 명령줄 flag → 환경 변수 → `~/.multica/config.json` → 내장 기본값입니다. watchdog 동작은 [데몬과 런타임](/daemon-runtimes)을 참고하세요.### 데몬 설정 영속화diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 62f2bdf9b5..6c5b6c8933 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -234,7 +234,7 @@ The variables below are read on the computer that runs your agents, not in the A| `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | Concurrent run ceiling per daemon || `MULTICA_AGENT_TIMEOUT` | `0` | Absolute time limit per run; `0` means no limit || `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | Silence ceiling with no output and no tool execution; `0` disables the watchdog entirely |-| `MULTICA_AGENT_TOOL_WATCHDOG` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Silence ceiling for a single tool call; set it only to give tools more room than the model gets, `0` never force-stops a tool call |+| `MULTICA_AGENT_TOOL_WATCHDOG` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Silence ceiling for a single tool call; set it only to give tools more room than the model gets, `0` never force-stops a tool call. Cursor background shells stay in flight until their owned processes exit; at this boundary the daemon stops those processes and gives Cursor a fresh watchdog budget to produce its terminal result. If process ownership or cleanup cannot be verified, the ordinary run-cancellation policy applies || `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode-specific silence threshold || `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Codex semantic-silence threshold. Codex's own timer cannot see that a tool is running, so it tracks the larger of the idle / tool budgets instead of holding a separate, shorter ceiling || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Explicit override for the Codex first-turn no-progress ceiling; `0` keeps the default. The effective first-turn wait stays bounded by `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` and the overall execution timeout — set `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` strictly above this value (with some margin), or the wait is truncated to it and the model-catalog startup retry is skipped. Equal values are not enough: the semantic timer is armed first, so at equal durations the retry can still be lost |@@ -256,6 +256,10 @@ MULTICA_CLAUDE_PATH=/opt/bin/claudeMULTICA_CLAUDE_ARGS=--max-turns 40```+Cursor's verified background cleanup requires Linux 6.9 or newer (process-group pidfds), macOS kernel support for process identity queries and audit-token signalling, or a successfully assigned nested Job Object on Windows. On macOS, each process is signalled using a kernel-checked PID version; no same-session group join is required. These macOS APIs are private and checked at capture time. A launch that cannot be claimed returns its original tool result and uses the ordinary idle watchdog, including when the tool watchdog is `0`. Already-claimed work remains in flight if cleanup cannot be confirmed. With the tool watchdog set to `0` there is no such boundary at all: claimed background work keeps the run in flight for as long as it lives, so the run is bounded only by `MULTICA_AGENT_TIMEOUT`, which is `0` by default.++Owned Cursor background processes are also stopped when the run completes normally, so a background server started by that run does not intentionally survive finalization. macOS can recognize late children through retained original-parent identities, but cannot prove a chain whose intermediate processes disappeared before observation. Such processes, work that leaves the tracked group, or persistent ownership/signalling errors can leave background work behind. Unconfirmed cleanup is logged and never grants a successful-cleanup recovery window; unknown processes are not killed based only on their numeric PID or process group.+Precedence is command-line flag → environment variable → `~/.multica/config.json` → built-in default. For watchdog behavior, see [Daemon and runtimes](/daemon-runtimes).### Persisting daemon configurationdiff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex b40c2c5aef..0e1650aa2d 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -234,7 +234,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | 单个守护进程的并发运行上限 || `MULTICA_AGENT_TIMEOUT` | `0` | 单次执行的绝对时限;`0` 表示不设置 || `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 没有输出且没有工具执行时的静默上限;`0` 表示整套 watchdog 关闭 |-| `MULTICA_AGENT_TOOL_WATCHDOG` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | 单个工具调用持续静默的上限;只有希望工具比模型有更多余量时才单独设置,`0` 表示工具执行期间永不强制停止 |+| `MULTICA_AGENT_TOOL_WATCHDOG` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | 单个工具调用持续静默的上限;只有希望工具比模型有更多余量时才单独设置,`0` 表示工具执行期间永不强制停止。Cursor 的后台 shell 在它启动的进程退出前一直算作执行中;到达这个上限时,守护进程会停止这些进程,并给 Cursor 一段新的 watchdog 预算来产出终态结果。若进程归属或清理无法验证,则回到普通的运行取消策略 || `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 专用静默阈值 || `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | Codex 语义静默阈值。Codex 自己的计时器看不到工具是否在执行,因此跟随 idle / tool 预算中较大的那个,而不再单独保留一个更短的上限 || `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | 显式覆盖 Codex 首轮无进展上限;`0` 保持默认值。实际首轮等待仍受 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 和总执行超时限制——需将 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 设为严格大于此值(并留出余量),否则等待会被截断至该值,且会跳过模型目录启动重试。设为相等还不够:语义计时器先启动,两者相等时仍可能丢失该重试 |@@ -256,6 +256,10 @@ MULTICA_CLAUDE_PATH=/opt/bin/claudeMULTICA_CLAUDE_ARGS=--max-turns 40```+Cursor 已验证的后台清理需要 Linux 6.9 及以上(进程组 pidfd)、macOS 内核对进程身份查询与 audit token 发信号的支持,或 Windows 上成功分配的嵌套 Job Object。在 macOS 上,每个进程都按内核校验的 PID version 发信号,不需要加入同一 session 的进程组;这些 macOS 接口是私有的,会在捕获时做探测。无法认领的后台启动会返回它原本的工具结果并回到普通的 idle watchdog,工具 watchdog 为 `0` 时同样如此。已经认领的工作在清理无法确认时会继续算作执行中。当工具 watchdog 设为 `0` 时则完全没有这个边界:已认领的后台工作只要还活着就一直让运行处于执行中,此时运行仅受 `MULTICA_AGENT_TIMEOUT` 约束,而它默认也是 `0`。++运行正常结束时,被认领的 Cursor 后台进程同样会被停止,因此该次运行启动的后台服务不会有意地在收尾之后继续存活。macOS 可以通过保留的原始父进程身份识别后期产生的子进程,但无法证明中间进程在被观察到之前就已消失的那条链路。这类进程、离开被追踪进程组的工作,以及持续的归属或发信号错误,都可能留下残余的后台工作。未确认的清理会被记录下来,且永远不会换取一次「清理成功」的恢复窗口;不会仅凭数字 PID 或进程组就去杀掉未知进程。+优先级为命令行 flag → 环境变量 → `~/.multica/config.json` → 内置默认。watchdog 的行为见[守护进程与运行时](/daemon-runtimes)。### 守护进程配置的持久化diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 1ddcd0fe05..3d925afbfe 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -149,7 +149,7 @@ type Config struct {CodexThreadHandshakeTimeout time.DurationOpenCodeIdleWatchdog time.Duration // OpenCode-specific no-message window; 0 falls back to AgentIdleWatchdog and values above it cannot extend the global boundAgentIdleWatchdog time.Duration // force-stop a run when the backend goes silent this long with an empty queue (0 = disabled)- AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = never force-stop during a tool call); defaults to AgentIdleWatchdog, so operators tune one number unless they deliberately want a wider tool budget+ AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = never force-stop during a tool call, which now also covers a live Cursor background shell); defaults to AgentIdleWatchdog, so operators tune one number unless they deliberately want a wider tool budgetClaudeArgs []stringCodexArgs []stringCodebuddyArgs []string@@ -361,6 +361,14 @@ func LoadConfig(overrides Overrides) (Config, error) {// MULTICA_AGENT_TOOL_WATCHDOG still overrides for the deliberate "tools may// run longer than the model may think" case, and 0 keeps its meaning: never// force-stop while a tool is in flight.+ //+ // A Cursor background shell counts as in flight for as long as the launched+ // process lives, not just until Cursor reports the launch complete — that is+ // what keeps a legitimate long background job on the tool budget instead of+ // the shorter idle one. The consequence at 0 is the same one a foreground+ // tool that never returns already has: such a run is bounded only by+ // MULTICA_AGENT_TIMEOUT, which is itself 0 by default. Operators who want a+ // stalled background shell bounded must leave this non-zero.agentToolWatchdog, err := durationFromEnv("MULTICA_AGENT_TOOL_WATCHDOG", agentIdleWatchdog)if err != nil {return Config{}, errdiff --git a/server/internal/daemon/cursor_background_watchdog_test.go b/server/internal/daemon/cursor_background_watchdog_test.gonew file mode 100644index 0000000000..c29a3ac6c7--- /dev/null+++ b/server/internal/daemon/cursor_background_watchdog_test.go@@ -0,0 +1,253 @@+package daemon++import (+ "context"+ "log/slog"+ "sync/atomic"+ "testing"+ "testing/synctest"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++type backgroundToolBackend struct {+ natural time.Duration+ mixed, invalid, noResult bool+ dropTranscript bool+ interrupts atomic.Int32+ cleaned atomic.Bool+}++func (b *backgroundToolBackend) Execute(ctx context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {+ messages := make(chan agent.Message, 8)+ results := make(chan agent.Result, 1)+ stopped := make(chan struct{})+ var nativeCount atomic.Int32+ var nativeActivity atomic.Int64+ nativeActivity.Store(time.Now().UnixNano())+ nativeCount.Store(1)+ if !b.dropTranscript {+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}+ }+ if b.mixed {+ nativeCount.Add(1)+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "read", CallID: "fg"}+ }+ go func() {+ defer close(messages)+ defer close(results)+ var natural <-chan time.Time+ if b.natural > 0 {+ natural = time.After(b.natural)+ }+ select {+ case <-natural:+ nativeActivity.Store(time.Now().UnixNano())+ if !b.dropTranscript {+ messages <- agent.Message{Type: agent.MessageToolResult, Tool: "shell", CallID: "bg", Output: "raw launch result"}+ }+ nativeCount.Add(-1)+ case <-stopped:+ case <-ctx.Done():+ results <- agent.Result{Status: "aborted"}+ return+ }+ if b.mixed || b.noResult {+ <-ctx.Done()+ results <- agent.Result{Status: "aborted"}+ return+ }+ finishDelay := 10 * time.Millisecond+ if b.dropTranscript {+ finishDelay = 30 * time.Millisecond+ }+ select {+ case <-time.After(finishDelay):+ results <- agent.Result{Status: "completed", Output: "Cursor terminal result"}+ case <-ctx.Done():+ results <- agent.Result{Status: "aborted"}+ }+ }()+ return &agent.Session{Messages: messages, Result: results, ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) }, InterruptBackgroundTools: func() bool {+ b.interrupts.Add(1)+ if b.invalid || !b.cleaned.CompareAndSwap(false, true) {+ return false+ }+ nativeActivity.Store(time.Now().UnixNano())+ if !b.dropTranscript {+ messages <- agent.Message{Type: agent.MessageToolResult, Tool: "shell", CallID: "bg", Output: "raw launch result"}+ }+ nativeCount.Add(-1)+ close(stopped)+ return true+ }}, nil+}++func TestExecuteAndDrain_BackgroundToolWatchdog(t *testing.T) {+ for _, tc := range []struct {+ name string+ idle, tool, natural time.Duration+ mixed, invalid, noResult bool+ status string+ cleanup bool+ }{+ {name: "silent beyond idle under tool budget", idle: 50 * time.Millisecond, tool: time.Second, natural: 250 * time.Millisecond, status: "completed"},+ {name: "budget stops tool and preserves result", idle: 50 * time.Millisecond, tool: 100 * time.Millisecond, status: "completed", cleanup: true},+ {name: "disabled suite", tool: 50 * time.Millisecond, natural: 150 * time.Millisecond, status: "completed"},+ {name: "disabled tool budget", idle: 50 * time.Millisecond, natural: 150 * time.Millisecond, status: "completed"},+ {name: "unverified process falls back", idle: 50 * time.Millisecond, tool: 100 * time.Millisecond, invalid: true, status: "idle_watchdog"},+ {name: "foreground still gets bounded", idle: 50 * time.Millisecond, tool: 100 * time.Millisecond, mixed: true, status: "idle_watchdog", cleanup: true},+ {name: "missing terminal still gets bounded", idle: 50 * time.Millisecond, tool: 100 * time.Millisecond, noResult: true, status: "idle_watchdog", cleanup: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog, d.cfg.AgentToolWatchdog = tc.idle, tc.tool+ backend := &backgroundToolBackend{natural: tc.natural, mixed: tc.mixed, invalid: tc.invalid, noResult: tc.noResult}+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.Default(), "background-watchdog", "", new(atomic.Int32))+ if err != nil || result.Status != tc.status {+ t.Fatalf("result=%+v error=%v, want %s", result, err, tc.status)+ }+ if backend.cleaned.Load() != tc.cleanup {+ t.Fatalf("cleanup=%v want %v", backend.cleaned.Load(), tc.cleanup)+ }+ if tc.natural > 0 && backend.interrupts.Load() != 0 {+ t.Fatalf("legitimate/disabled run interrupted %d times", backend.interrupts.Load())+ }+ if tc.status == "completed" && result.Output != "Cursor terminal result" {+ t.Fatalf("native result lost: %+v", result)+ }+ })+ }+}++func TestBackgroundToolWatchdogShortOverride(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ var last, threshold atomic.Int64+ var tools atomic.Int32+ var fired atomic.Bool+ last.Store(time.Now().UnixNano())+ tools.Store(1)+ calls := 0+ go new(Daemon).runIdleWatchdog(ctx, 10*time.Minute, time.Minute, &last, tools.Load, &fired, &threshold, cancel, make(chan agent.Message), func() bool { calls++; cancel(); return true }, nil, slog.Default())+ synctest.Wait()+ time.Sleep(time.Minute)+ synctest.Wait()+ if calls != 1 || fired.Load() {+ t.Fatalf("short tool budget: calls=%d fired=%v", calls, fired.Load())+ }+ })+}++func TestBackgroundToolWatchdogNaturalExitRace(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ var last, threshold atomic.Int64+ var tools atomic.Int32+ var fired atomic.Bool+ last.Store(time.Now().UnixNano())+ tools.Store(1)+ go new(Daemon).runIdleWatchdog(ctx, time.Minute, time.Minute, &last, tools.Load, &fired, &threshold, cancel, make(chan agent.Message), func() bool {+ tools.Store(0)+ last.Store(time.Now().UnixNano())+ return false+ }, nil, slog.Default())+ synctest.Wait()+ time.Sleep(time.Minute)+ synctest.Wait()+ if fired.Load() || ctx.Err() != nil {+ t.Fatal("stale tool threshold cancelled after natural completion")+ }+ })+}++func TestBackgroundToolWatchdogFreshActivityDuringRevalidation(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ var last, threshold atomic.Int64+ var fired atomic.Bool+ last.Store(time.Now().UnixNano())+ refreshAtBoundary, refreshed := false, false+ // Match Session.ToolActivity's production callback: refreshing native+ // activity publishes a timestamp even when the tool count stays positive.+ toolState := func() int32 {+ if refreshAtBoundary && !refreshed {+ last.Store(time.Now().UnixNano())+ refreshed = true+ }+ return 1+ }+ go new(Daemon).runIdleWatchdog(ctx, time.Minute, time.Minute, &last, toolState, &fired, &threshold, cancel, make(chan agent.Message), func() bool {+ refreshAtBoundary = true+ return false+ }, nil, slog.Default())+ synctest.Wait()+ time.Sleep(time.Minute)+ synctest.Wait()+ if !refreshed || fired.Load() || ctx.Err() != nil {+ t.Fatalf("fresh native activity lost: refreshed=%v fired=%v err=%v", refreshed, fired.Load(), ctx.Err())+ }+ time.Sleep(59 * time.Second)+ synctest.Wait()+ if fired.Load() || ctx.Err() != nil {+ t.Fatal("watchdog did not grant the renewed tool budget")+ }+ time.Sleep(time.Second)+ synctest.Wait()+ if !fired.Load() || ctx.Err() == nil {+ t.Fatal("genuine inactivity after the renewed budget did not fire")+ }+ })+}++func TestExecuteAndDrain_BackgroundNativeCountSurvivesDroppedTranscript(t *testing.T) {+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond+ d.cfg.AgentToolWatchdog = time.Second+ backend := &backgroundToolBackend{natural: 200 * time.Millisecond, dropTranscript: true}+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.Default(), "dropped-transcript", "", new(atomic.Int32))+ if err != nil || result.Status != "completed" || backend.interrupts.Load() != 0 {+ t.Fatalf("native tool state lost: %+v err=%v", result, err)+ }+}++// TestCursorBackgroundCapturedDisabledToolWatchdog is the deliberate mirror of+// TestCursorBackgroundUncapturedDisabledToolWatchdog. When ownership WAS+// captured the launched process is genuinely in flight, so a zero tool budget+// means what it says and nothing force-stops the run — the same outcome a+// foreground tool that never returns already has. The uncaptured case releases+// its tool precisely because nothing was claimed there; these two must not be+// "fixed" into agreeing without changing what MULTICA_AGENT_TOOL_WATCHDOG=0+// promises. See the knob's documentation in config.go.+func TestCursorBackgroundCapturedDisabledToolWatchdog(t *testing.T) {+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond+ d.cfg.AgentToolWatchdog = 0++ // noResult: the launched process never exits on its own (GH #7833's dev+ // server). invalid stays false, so ownership is held and the tool is real.+ backend := &backgroundToolBackend{noResult: true}++ // Stands in for MULTICA_AGENT_TIMEOUT, which is 0 (unbounded) by default.+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)+ defer cancel()+ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.Default(), "captured-background", "", new(atomic.Int32))+ if err != nil {+ t.Fatalf("executeAndDrain: %v", err)+ }+ if result.Status == "idle_watchdog" {+ t.Fatalf("a held background tool was force-stopped despite a zero tool budget: %+v", result)+ }+ if backend.interrupts.Load() != 0 {+ t.Fatalf("cleanup ran %d times without a tool budget", backend.interrupts.Load())+ }+}diff --git a/server/internal/daemon/cursor_terminal_boundary_test.go b/server/internal/daemon/cursor_terminal_boundary_test.gonew file mode 100644index 0000000000..02200e1591--- /dev/null+++ b/server/internal/daemon/cursor_terminal_boundary_test.go@@ -0,0 +1,284 @@+package daemon++import (+ "context"+ "log/slog"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "testing/synctest"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++// The ordering both tests below pin is the one that loses a completed run:+//+// 1. the tool watchdog enters the background-cleanup callback,+// 2. Cursor reads its authoritative terminal result and blocks behind the same+// cleanup lock, so nothing it does is visible yet,+// 3. cleanup fails, leaving native accounting and its timestamp untouched,+// 4. no transcript message arrives to rescue the tick.+//+// Before the terminal boundary existed, the watchdog then cancelled the run and+// executeAndDrain re-tagged Cursor's completed result as idle_watchdog.++// TestIdleWatchdogYieldsToTerminalObservedDuringCleanup drives that exact+// interleaving deterministically: the cleanup callback itself publishes the+// terminal observation, so step 2 provably happens while step 1 is in progress.+func TestIdleWatchdogYieldsToTerminalObservedDuringCleanup(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ var last, threshold atomic.Int64+ var fired atomic.Bool+ var terminal atomic.Bool+ last.Store(time.Now().UnixNano())++ // A held background tool: in flight, and its activity never moves.+ tools := func() int32 { return 1 }+ interrupts := 0+ interrupt := func() bool {+ interrupts+++ // Cursor read its terminal result while this call held the lock.+ terminal.Store(true)+ // Ownership could not be confirmed, so nothing is released.+ return false+ }++ go new(Daemon).runIdleWatchdog(ctx, time.Minute, time.Minute, &last, tools, &fired, &threshold,+ cancel, make(chan agent.Message), interrupt, terminal.Load, slog.Default())++ synctest.Wait()+ time.Sleep(time.Minute)+ synctest.Wait()++ if interrupts == 0 {+ t.Fatal("never reached the cleanup boundary; the interleaving was not exercised")+ }+ if fired.Load() || ctx.Err() != nil {+ t.Fatalf("a decided outcome was force-stopped: fired=%v err=%v", fired.Load(), ctx.Err())+ }++ // And it stays decided: further budgets must not revive the hang verdict.+ time.Sleep(5 * time.Minute)+ synctest.Wait()+ if fired.Load() || ctx.Err() != nil {+ t.Fatalf("terminal boundary expired: fired=%v err=%v", fired.Load(), ctx.Err())+ }+ })+}++// terminalRaceBackend reproduces the same ordering through executeAndDrain, so+// the re-tagging half of the defect is covered too. Ordering is enforced by+// channel handshakes; only the watchdog budget itself uses time.+type terminalRaceBackend struct {+ interrupted chan struct{}+ terminal atomic.Bool+ interrupts atomic.Int32+}++func (b *terminalRaceBackend) Execute(ctx context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {+ messages := make(chan agent.Message, 4)+ results := make(chan agent.Result, 1)+ var nativeCount atomic.Int32+ var nativeActivity atomic.Int64+ nativeCount.Store(1)+ nativeActivity.Store(time.Now().UnixNano())+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}++ go func() {+ defer close(messages)+ defer close(results)+ select {+ case <-b.interrupted:+ // Cleanup already failed and the terminal observation is published;+ // Cursor now finishes normally with its authoritative result.+ results <- agent.Result{Status: "completed", Output: "Cursor terminal result"}+ case <-ctx.Done():+ results <- agent.Result{Status: "aborted"}+ }+ }()++ return &agent.Session{+ Messages: messages,+ Result: results,+ ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) },+ TerminalObserved: b.terminal.Load,+ InterruptBackgroundTools: func() bool {+ b.interrupts.Add(1)+ // Step 2: the terminal result becomes decided while cleanup holds+ // the lock. Native accounting deliberately stays untouched.+ b.terminal.Store(true)+ select {+ case <-b.interrupted:+ default:+ close(b.interrupted)+ }+ // Step 3: ownership could not be confirmed.+ return false+ },+ }, nil+}++func TestExecuteAndDrainKeepsTerminalResultObservedDuringCleanup(t *testing.T) {+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond+ d.cfg.AgentToolWatchdog = 50 * time.Millisecond++ backend := &terminalRaceBackend{interrupted: make(chan struct{})}+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.Default(), "terminal-race", "", new(atomic.Int32))+ if err != nil {+ t.Fatalf("executeAndDrain: %v", err)+ }+ if backend.interrupts.Load() == 0 {+ t.Fatal("never reached the cleanup boundary; the interleaving was not exercised")+ }+ if result.Status != "completed" || result.Output != "Cursor terminal result" {+ t.Fatalf("Cursor's authoritative result was rewritten: %+v", result)+ }+}++// handoffProbe both proves and sequences the branch under test. The daemon logs+// once, on entering the post-force-stop hand-off, and that record is the only+// externally visible evidence of which arm executeAndDrain took. Closing the+// gate from the handler is what keeps Result unavailable until then, so the+// outer select provably cannot satisfy itself on the Result arm instead.+type handoffProbe struct {+ slog.Handler+ gate chan struct{}+ once sync.Once+ seen atomic.Bool+ prefix string+}++func (h *handoffProbe) Handle(ctx context.Context, r slog.Record) error {+ if strings.HasPrefix(r.Message, h.prefix) {+ h.seen.Store(true)+ h.once.Do(func() { close(h.gate) })+ }+ return nil+}++func (h *handoffProbe) Enabled(context.Context, slog.Level) bool { return true }+func (h *handoffProbe) WithAttrs([]slog.Attr) slog.Handler { return h }+func (h *handoffProbe) WithGroup(string) slog.Handler { return h }++// lateTerminalBackend hands its result over only once the daemon has entered+// the hand-off, which is the ordering the previous version of this test could+// not guarantee: there the backend sent immediately on cancellation, so the+// outer select could take the Result arm and the drain-timeout classifier was+// never exercised at all.+type lateTerminalBackend struct {+ terminal atomic.Bool+ cancels atomic.Int32+ gate <-chan struct{}+}++func (b *lateTerminalBackend) Execute(ctx context.Context, _ string, _ agent.ExecOptions) (*agent.Session, error) {+ messages := make(chan agent.Message, 4)+ results := make(chan agent.Result, 1)+ var nativeCount atomic.Int32+ var nativeActivity atomic.Int64+ nativeCount.Store(1)+ nativeActivity.Store(time.Now().UnixNano())+ messages <- agent.Message{Type: agent.MessageToolUse, Tool: "shell", CallID: "bg"}++ go func() {+ defer close(results)+ <-ctx.Done()+ b.cancels.Add(1)+ // Let waitForDrain complete so the hand-off is reached, then stay silent+ // until it is: this is the backend still finalizing, which is why the+ // cancellation surfaces on the drain arm rather than the Result arm.+ close(messages)+ <-b.gate+ // The contract: publish the observation before sending Result, so the+ // daemon's read after delivery cannot lose a race.+ b.terminal.Store(true)+ results <- agent.Result{Status: "completed", Output: "Cursor terminal result"}+ }()++ return &agent.Session{+ Messages: messages,+ Result: results,+ ToolActivity: func() (int32, time.Time) { return nativeCount.Load(), time.Unix(0, nativeActivity.Load()) },+ TerminalObserved: b.terminal.Load,+ // Nothing can be released: cleanup could not confirm ownership.+ InterruptBackgroundTools: func() bool { return false },+ }, nil+}++// TestExecuteAndDrainKeepsTerminalResultHandedOverAfterForceStop pins the arm+// that kept losing: the watchdog fires with the terminal result not yet+// published, so the run reaches the drain-timeout classifier rather than the+// Result arm, and the decided outcome still has to survive. The probe asserts+// that branch really ran instead of inferring it from a passing status.+func TestExecuteAndDrainKeepsTerminalResultHandedOverAfterForceStop(t *testing.T) {+ probe := &handoffProbe{gate: make(chan struct{}), prefix: "idle watchdog fired; waiting"}+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond+ d.cfg.AgentToolWatchdog = 50 * time.Millisecond++ backend := &lateTerminalBackend{gate: probe.gate}+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()++ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.New(probe), "late-terminal", "", new(atomic.Int32))+ if err != nil {+ t.Fatalf("executeAndDrain: %v", err)+ }+ if backend.cancels.Load() == 0 {+ t.Fatal("the watchdog never cancelled; this test did not exercise the fired path")+ }+ if !probe.seen.Load() {+ t.Fatal("the post-force-stop hand-off never ran; the drain arm was not exercised")+ }+ if result.Status != "completed" || result.Output != "Cursor terminal result" {+ t.Fatalf("a decided outcome was reclassified after the force stop: %+v", result)+ }+}++// wedgedBackend offers no terminal boundary and never finishes: the shape the+// idle watchdog exists for. It must be classified the moment the watchdog+// fires, with no hand-off wait, because a result that could outrank the force+// stop is precisely what this backend cannot produce.+type wedgedBackend struct{}++func (wedgedBackend) Execute(context.Context, string, agent.ExecOptions) (*agent.Session, error) {+ messages := make(chan agent.Message, 1)+ messages <- agent.Message{Type: agent.MessageText, Content: "hello"}+ // Neither closed nor written to again, and no TerminalObserved.+ return &agent.Session{Messages: messages, Result: make(chan agent.Result)}, nil+}++// TestExecuteAndDrainDoesNotDelayBackendsWithoutATerminalBoundary keeps the+// hand-off from becoming a tax on every force stop. Waiting is only justified+// for a backend that can hand back an outcome outranking the watchdog; for the+// rest the point of the watchdog is to free the runtime slot promptly.+func TestExecuteAndDrainDoesNotDelayBackendsWithoutATerminalBoundary(t *testing.T) {+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ start := time.Now()+ result, _, err := d.executeAndDrain(ctx, wedgedBackend{}, "p", agent.ExecOptions{}, slog.Default(), "wedged", "", new(atomic.Int32))+ elapsed := time.Since(start)+ if err != nil {+ t.Fatalf("executeAndDrain: %v", err)+ }+ if result.Status != "idle_watchdog" {+ t.Fatalf("status=%q, want idle_watchdog", result.Status)+ }+ if elapsed > 5*d.cfg.AgentIdleWatchdog {+ t.Fatalf("force stop took %s, want under %s: a backend with no terminal boundary must not wait for a hand-off it cannot make",+ elapsed, 5*d.cfg.AgentIdleWatchdog)+ }+}diff --git a/server/internal/daemon/cursor_uncaptured_watchdog_test.go b/server/internal/daemon/cursor_uncaptured_watchdog_test.gonew file mode 100644index 0000000000..383ff8d45b--- /dev/null+++ b/server/internal/daemon/cursor_uncaptured_watchdog_test.go@@ -0,0 +1,41 @@+//go:build linux || darwin++package daemon++import (+ "context"+ "log/slog"+ "os"+ "path/filepath"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++func TestCursorBackgroundUncapturedDisabledToolWatchdog(t *testing.T) {+ fake := filepath.Join(t.TempDir(), "cursor-agent")+ const script = `#!/bin/sh+cat >/dev/null+printf '%s\n' '{"type":"tool_call","subtype":"started","call_id":"bg","tool_call":{"shellToolCall":{"args":{}}}}'+printf '%s\n' '{"type":"tool_call","subtype":"completed","call_id":"bg","tool_call":{"shellToolCall":{"result":{"isBackground":true,"success":{"pid":-1}}}}}'+exec sleep 30+`+ if err := os.WriteFile(fake, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ backend, err := agent.New("cursor", agent.Config{ExecutablePath: fake, Logger: slog.Default()})+ if err != nil {+ t.Fatal(err)+ }+ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond+ d.cfg.AgentToolWatchdog = 0+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)+ defer cancel()+ result, _, err := d.executeAndDrain(ctx, backend, "test", agent.ExecOptions{}, slog.Default(), "uncaptured-background", "", new(atomic.Int32))+ if err != nil || result.Status != "idle_watchdog" || ctx.Err() != nil {+ t.Fatalf("uncaptured background escaped idle budget: result=%+v err=%v context=%v", result, err, ctx.Err())+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex ef5ec42591..83ddea31c7 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8916,8 +8916,36 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro}var idleWatchdogThreshold atomic.Int64idleWatchdogThreshold.Store(int64(idleWindow))+ watchdogToolCount := inFlightTools.Load+ if session.ToolActivity != nil {+ watchdogToolCount = func() int32 {+ count, at := session.ToolActivity()+ for {+ previous := lastActivityAt.Load()+ if at.UnixNano() <= previous || lastActivityAt.CompareAndSwap(previous, at.UnixNano()) {+ break+ }+ }+ return count+ }+ }+ // A backend that can prove its outcome is already decided outranks every+ // liveness policy below: a run whose terminal result has been read is not a+ // hang, no matter how long its cleanup then takes.+ // Nil is meaningful and kept distinguishable: a backend that offers no+ // terminal boundary is one whose result cannot outrank a force stop, so it+ // must not be given a hand-off window it can never use. Every such backend+ // keeps the previous behaviour, including a wedged one, which is force+ // stopped and classified without waiting for anything.+ handsOverTerminal := session.TerminalObserved != nil+ terminalObserved := session.TerminalObserved+ if terminalObserved == nil {+ terminalObserved = func() bool { return false }+ }+ watchdogCtx, stopWatchdog := context.WithCancel(agentCtx)+ defer stopWatchdog()if idleWindow > 0 {- go d.runIdleWatchdog(agentCtx, idleWindow, d.cfg.AgentToolWatchdog, &lastActivityAt, &inFlightTools, &idleWatchdogFired, &idleWatchdogThreshold, agentCancel, session.Messages, taskLog)+ go d.runIdleWatchdog(watchdogCtx, idleWindow, d.cfg.AgentToolWatchdog, &lastActivityAt, watchdogToolCount, &idleWatchdogFired, &idleWatchdogThreshold, agentCancel, session.Messages, session.InterruptBackgroundTools, terminalObserved, taskLog)}// drainFinished closes after the drain goroutine has flushed the last@@ -9155,8 +9183,12 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, proselect {case result := <-session.Result:+ stopWatchdog()waitForDrain()- if idleWatchdogFired.Load() {+ // terminalObserved outranks a watchdog that fired anyway: if the backend+ // had already read its authoritative result, this is the real outcome and+ // re-tagging it would report a completed run as a hang.+ if idleWatchdogFired.Load() && !terminalObserved() {// The backend's wait goroutine (e.g. claude.go) translates the// SIGKILL we delivered via agentCancel into Status="aborted".// Re-tag it as "idle_watchdog" so runTask routes the@@ -9179,6 +9211,51 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro// classifiers so a watchdog-induced stop isn't misreported as// "task cancelled by server".if idleWatchdogFired.Load() {+ // For a backend that publishes a terminal boundary, enter the+ // hand-off without asking terminalObserved first. Reading a flag and+ // then acting on it is exactly the window this branch kept losing:+ // the backend can publish between the read and the classifier below.+ // Waiting for the result instead makes its delivery the+ // linearization point, and the backend contract — publish the+ // observation before sending Result — is what makes the check after+ // delivery reliable rather than lucky.+ //+ // Such a backend always closes Result, so a wedged one still ends+ // this wait promptly through the closed channel rather than the+ // budget.+ if handsOverTerminal {+ taskLog.Info("idle watchdog fired; waiting for the backend to hand over its result",+ "budget", terminalResultHandoffBudget.String())+ select {+ case result, ok := <-session.Result:+ if ok && terminalObserved() {+ // The backend had already read its authoritative+ // result, so this is the real outcome, not a hang.+ return result, toolCount.Load(), nil+ }+ if ok {+ // The backend's wait goroutine (e.g. claude.go)+ // translates the SIGKILL we delivered via agentCancel+ // into Status="aborted". Re-tag it as "idle_watchdog"+ // so runTask routes the disposition through a dedicated+ // failure_reason, not the generic "agent_error" bucket+ // the aborted path falls into.+ result.Status = "idle_watchdog"+ if result.Error == "" {+ result.Error = idleWatchdogReason(time.Duration(idleWatchdogThreshold.Load()))+ }+ return result, toolCount.Load(), nil+ }+ // Closed with no value: the backend gave up without an+ // outcome, so the liveness verdict is the only one left.+ case <-time.After(terminalResultHandoffBudget):+ // A backend that neither delivers nor closes is itself the+ // hang. Linearizing here keeps the branch bounded whatever+ // a backend does.+ taskLog.Warn("backend did not hand over a result within the budget; classifying by liveness",+ "budget", terminalResultHandoffBudget.String())+ }+ }return agent.Result{Status: "idle_watchdog",Error: idleWatchdogReason(time.Duration(idleWatchdogThreshold.Load())),@@ -9202,6 +9279,25 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro}}+// terminalResultHandoffBudget is how long executeAndDrain waits, after force-+// stopping a run, for the backend to hand over whatever result it has. It only+// decides how long we believe a backend before falling back to the liveness+// verdict; the backend caps its own finalization, so in practice the wait ends+// far sooner.+//+// The value is derived from the slowest finalization this daemon drives today,+// Cursor's, rather than picked: a concurrent background-cleanup pass we may have+// to wait behind (cursorCloseBudget, 10s), the closing pass itself (another+// 10s), one already-started process termination per pass overshooting its+// budget by that termination's own bound (~1s each), and the process WaitDelay+// after cancellation (0.5s) — about 22.5s. 30s leaves margin without letting a+// wedged backend hold a runtime slot indefinitely.+//+// Deliberately not a term: the background reaper's tick. Closing its stop+// channel wakes it immediately rather than at the next tick, so it adds+// nothing to this ceiling.+const terminalResultHandoffBudget = 30 * time.Second+// idleWatchdogReason formats the human-facing explanation surfaced on// idle_watchdog dispositions. Centralised so the result-arrival branch and the// drain-timeout branch in executeAndDrain emit identical wording.@@ -9254,8 +9350,12 @@ func idleWatchdogTickInterval(window time.Duration) time.Duration {//// Polling rate comes from idleWatchdogTickInterval, so a run is force-stopped// somewhere between its budget and budget + tick, never earlier.-func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools *atomic.Int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, taskLog *slog.Logger) {- ticker := time.NewTicker(idleWatchdogTickInterval(window))+func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow time.Duration, lastActivityAt *atomic.Int64, inFlightTools func() int32, fired *atomic.Bool, firedThreshold *atomic.Int64, cancel context.CancelFunc, messages <-chan agent.Message, interruptBackground func() bool, terminalObserved func() bool, taskLog *slog.Logger) {+ tickWindow := window+ if toolWindow > 0 && toolWindow < tickWindow {+ tickWindow = toolWindow+ }+ ticker := time.NewTicker(idleWatchdogTickInterval(tickWindow))defer ticker.Stop()for {select {@@ -9267,7 +9367,7 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow ti// tool_use and tool_result), so it gets the larger toolWindow;// toolWindow <= 0 disables the in-flight bound entirely.threshold := window- toolInFlight := inFlightTools.Load() > 0+ toolInFlight := inFlightTools() > 0if toolInFlight {if toolWindow <= 0 {continue@@ -9285,6 +9385,41 @@ func (d *Daemon) runIdleWatchdog(agentCtx context.Context, window, toolWindow tiif len(messages) > 0 {continue}+ // Cursor can stop its owned background tools without aborting the+ // agent. The same watchdog owns both the budget and this recovery,+ // so no competing timer can cancel Cursor while it reports a result.+ if agentCtx.Err() != nil {+ return+ }+ if terminalObserved != nil && terminalObserved() {+ return+ }+ if toolInFlight && interruptBackground != nil && interruptBackground() {+ lastActivityAt.Store(time.Now().UnixNano())+ taskLog.Info("tool watchdog stopped background tools; waiting for agent result")+ continue+ }+ // A natural tool completion may race the callback or the tick.+ if agentCtx.Err() != nil {+ return+ }+ // Refresh native tool activity BEFORE reading its timestamp. The+ // callback may publish newer activity without changing the count.+ currentToolInFlight := inFlightTools() > 0+ currentActivity := lastActivityAt.Load()+ if currentActivity != last.UnixNano() ||+ currentToolInFlight != toolInFlight || len(messages) > 0 {+ continue+ }+ if agentCtx.Err() != nil {+ return+ }+ // Last gate before force-stopping. The terminal result can land while+ // this tick is deciding — including while it is blocked inside the+ // interrupt callback above — and a decided outcome is never a hang.+ if terminalObserved != nil && terminalObserved() {+ return+ }// No "task" field here: taskLog already carries the full id.taskLog.Warn("idle watchdog firing: no agent activity, force-stopping run","idle_for", idleFor.Round(time.Second).String(),diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex e4dc50c8f7..4dd1a11fe6 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -147,6 +147,34 @@ func runContext(ctx context.Context, timeout time.Duration) (context.Context, co// Session represents a running agent execution.type Session struct {+ // ToolActivity optionally reports backend-owned tool accounting and its last+ // transition time, independent of the best-effort transcript. Nil uses the+ // daemon's message-based accounting. The timestamp gives completed tools a+ // fresh idle budget even when their transcript message has not drained yet.+ ToolActivity func() (int32, time.Time)+ // InterruptBackgroundTools stops owned background tools at the daemon's+ // tool watchdog boundary without cancelling the agent. True means at least+ // one tool completed/was stopped and released from accounting; the watchdog+ // gives the agent a fresh budget to report its authoritative result.+ // Implementations must be concurrency-safe and return false after cleanup.+ //+ // This is reached only at the tool budget, so a zero tool budget never calls+ // it: work that is genuinely in flight is what that setting declines to+ // force-stop. The daemon's AgentToolWatchdog documentation states the+ // operator-facing consequence.+ InterruptBackgroundTools func() bool+ // TerminalObserved reports whether the backend has already read its+ // authoritative terminal result. Once true the run's outcome is decided and+ // no liveness policy may reclassify it, however long the backend then takes+ // to finish cleaning up. Backends must publish this before any cleanup that+ // can block or fail, otherwise a completed run can still be re-tagged as a+ // hang. Nil means the backend offers no such boundary.+ //+ // It must also be published before the backend sends on Result. The daemon+ // reads it only after a result is in hand, so that ordering is what makes+ // the read reliable instead of a race: delivering the result establishes+ // the happens-before, and no flag read has to win a timing window.+ TerminalObserved func() bool// Messages streams events as the agent works. The channel is closed// when the agent finishes (before Result is sent).Messages <-chan Messagediff --git a/server/pkg/agent/claude_deadlock_test.go b/server/pkg/agent/claude_deadlock_test.goindex 83a8929b1a..76467ccc2f 100644--- a/server/pkg/agent/claude_deadlock_test.go+++ b/server/pkg/agent/claude_deadlock_test.go@@ -28,6 +28,11 @@ func TestMain(m *testing.M) {runFakeOpencodeStdinHelper()os.Exit(0)}+ // Cursor lifecycle fixtures re-execute this binary with the CLI's real argv.+ if mode := os.Getenv(cursorFakeModeEnv); mode != "" {+ runFakeCursorStream(mode)+ os.Exit(0)+ }switch mode := os.Getenv("CLAUDE_FAKE_MODE"); mode {case "":os.Exit(m.Run())diff --git a/server/pkg/agent/cursor.go b/server/pkg/agent/cursor.goindex 8864bb4768..75ac15277d 100644--- a/server/pkg/agent/cursor.go+++ b/server/pkg/agent/cursor.go@@ -70,6 +70,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptmsgCh := make(chan Message, 256)resCh := make(chan Result, 1)+ background := newCursorBackgroundTools(runCtx, cmd, msgCh, b.cfg.Logger)// The prompt is delivered on stdin (see buildCursorArgs). Write it from its// own goroutine so it cannot deadlock against the stdout reader below: a@@ -88,12 +89,14 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptdefer cancel()defer close(msgCh)defer close(resCh)+ defer background.Close()// Close stdout when the context is cancelled so scanner.Scan() unblocks.// Closing stdin too releases a prompt write still blocked on a full pipe// (e.g. the child died before draining it), so that goroutine cannot leak.go func() {<-runCtx.Done()+ background.Close()closeStdin()_ = stdout.Close()}()@@ -140,6 +143,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptscanner := newAgentStreamScanner(stdout)+ scanLoop:for scanner.Scan() {raw := scanner.Text()line := normalizeCursorStreamLine(raw)@@ -161,6 +165,9 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptswitch evt.Type {case "system":+ if evt.Subtype == "task_notification" {+ background.Reap()+ }if evt.Subtype == "init" {trySend(msgCh, Message{Type: MessageStatus, Status: "running"})}@@ -174,7 +181,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptcase "assistant":assistantEventCount++- assistantBytes += b.handleCursorAssistant(&evt, msgCh, &output)+ assistantBytes += b.handleCursorAssistant(&evt, background.Send, &output)case "thinking":// Reasoning is a top-level event streamed as deltas, not a@@ -207,7 +214,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptcase "started":call := parseCursorToolCall(&evt)toolUseCount++- trySend(msgCh, Message{+ background.Send(Message{Type: MessageToolUse,Tool: call.Name,CallID: call.CallID,@@ -215,12 +222,11 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt})case "completed":call := parseCursorToolCall(&evt)- trySend(msgCh, Message{- Type: MessageToolResult,- Tool: call.Name,- CallID: call.CallID,- Output: call.Result,- })+ if call.Background {+ background.Add(call)+ } else {+ background.SendResult(call)+ }default:unhandledSubtypeCount++}@@ -231,7 +237,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptif evt.Parameters != nil {_ = json.Unmarshal(evt.Parameters, ¶ms)}- trySend(msgCh, Message{+ background.Send(Message{Type: MessageToolUse,Tool: evt.ToolName,CallID: evt.ToolID,@@ -239,7 +245,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt})case "tool_result":- trySend(msgCh, Message{+ background.Send(Message{Type: MessageToolResult,CallID: evt.ToolID,Output: evt.Output,@@ -247,10 +253,17 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptcase "result":resultSeen = true+ // Publish the decided outcome BEFORE cleanup. Close() can block+ // on the tracker lock behind a tool watchdog Interrupt already in+ // progress, and that Interrupt can return false without moving+ // native accounting — which would leave the watchdog free to+ // cancel and re-tag this completed run as idle_watchdog.+ background.ObserveTerminal()+ background.Close()if evt.IsError || evt.Subtype == "error" {+ resultIsError = truefinalStatus = "failed"finalError = cursorErrorText(&evt)- resultIsError = true}resultBytes = len(evt.ResultText)if evt.ResultText != "" && output.Len() == 0 {@@ -265,6 +278,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// event but keep a worker process alive. Treat result as the// protocol boundary so the daemon can report completion.cancel()+ break scanLoopcase "error":errMsg := cursorErrorText(&evt)@@ -331,6 +345,7 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOptresultUsage = stepUsage}+ background.Close()exitErr := cmd.Wait()releaseProcessGroup(cmd)duration := time.Since(startTime)@@ -448,7 +463,13 @@ func (b *cursorBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}}()- return &Session{Messages: msgCh, Result: resCh}, nil+ return &Session{+ Messages: msgCh,+ Result: resCh,+ ToolActivity: background.Activity,+ InterruptBackgroundTools: background.Interrupt,+ TerminalObserved: background.TerminalObserved,+ }, nil}const cursorIncompleteFinalizationWarning = "actions completed before finalization may already have taken effect"@@ -583,7 +604,7 @@ func (t *cursorUnhandledTypeTally) summary() string {// returns how many bytes of model-authored text it appended to output. The// caller tracks that separately from output.Len(), which also absorbs the// terminal result text.-func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<- Message, output *strings.Builder) int {+func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, send func(Message), output *strings.Builder) int {if evt.Message == nil {return 0}@@ -604,18 +625,18 @@ func (b *cursorBackend) handleCursorAssistant(evt *cursorStreamEvent, ch chan<-if block.Text != "" {output.WriteString(block.Text)written += len(block.Text)- trySend(ch, Message{Type: MessageText, Content: block.Text})+ send(Message{Type: MessageText, Content: block.Text})}case "thinking":if block.Text != "" {- trySend(ch, Message{Type: MessageThinking, Content: block.Text})+ send(Message{Type: MessageThinking, Content: block.Text})}case "tool_use":var input map[string]anyif block.Input != nil {_ = json.Unmarshal(block.Input, &input)}- trySend(ch, Message{+ send(Message{Type: MessageToolUse,Tool: block.Name,CallID: block.ID,@@ -669,6 +690,9 @@ type cursorToolCall struct {CallID stringInput map[string]anyResult string++ Background bool+ PID int}// cursorToolCallKeySuffix is how Cursor names the per-tool payload: the tool is@@ -714,10 +738,32 @@ func parseCursorToolCall(evt *cursorStreamEvent) cursorToolCall {call.Input = payload.Argsif len(payload.Result) > 0 {call.Result = string(payload.Result)+ if call.Name == "shell" {+ call.Background = cursorResultReportsBackground(payload.Result)+ var metadata struct {+ Success struct {+ PID int `json:"pid"`+ } `json:"success"`+ }+ if json.Unmarshal(payload.Result, &metadata) == nil && call.Background {+ call.PID = metadata.Success.PID+ }+ }}return call}+// cursorResultReportsBackground reads only the root boolean, never output text.+func cursorResultReportsBackground(raw json.RawMessage) bool {+ var resultMeta struct {+ IsBackground bool `json:"isBackground"`+ }+ if err := json.Unmarshal(raw, &resultMeta); err != nil {+ return false+ }+ return resultMeta.IsBackground+}+// cursorToolPayloadKey picks the `<name>ToolCall` key of a tool_call envelope.// Observed payloads carry exactly one; the sort keeps the choice deterministic// if a future CLI ever emits more than one.diff --git a/server/pkg/agent/cursor_background.go b/server/pkg/agent/cursor_background.gonew file mode 100644index 0000000000..21d798eff1--- /dev/null+++ b/server/pkg/agent/cursor_background.go@@ -0,0 +1,242 @@+package agent++import (+ "context"+ "log/slog"+ "os/exec"+ "sync"+ "sync/atomic"+ "time"+)++type cursorBackgroundTool struct {+ call cursorToolCall+ process *cursorBackgroundProcess+}++// The daemon owns the only budget timer. This tracker owns process cleanup and+// the matching tool result, so expiration cannot race a second run-cancel timer.+type cursorBackgroundTools struct {+ ctx context.Context+ cmd *exec.Cmd+ messages chan<- Message+ logger *slog.Logger+ mu sync.Mutex+ tools []cursorBackgroundTool+ closed bool+ stop chan struct{}+ done chan struct{}+ once sync.Once+ inFlight atomic.Int32+ lastToolActivity atomic.Int64+ // closeBudget overrides cursorCloseBudget for this tracker. Zero — the value+ // every production construction path leaves it at — means the constant.+ closeBudget time.Duration+ // terminal is set the moment Cursor's authoritative result is read, before+ // Close() takes mu. Cleanup can block on that lock behind an in-progress+ // Interrupt and can legitimately fail, so it cannot be the signal that the+ // outcome is decided; this flag is, and it is deliberately lock-free.+ terminal atomic.Bool+}++// ObserveTerminal records that the backend has read its authoritative terminal+// result. Call it before any cleanup that may block or fail.+func (b *cursorBackgroundTools) ObserveTerminal() { b.terminal.Store(true) }++// TerminalObserved reports whether the run's outcome is already decided.+func (b *cursorBackgroundTools) TerminalObserved() bool { return b.terminal.Load() }++func newCursorBackgroundTools(ctx context.Context, cmd *exec.Cmd, messages chan<- Message, logger *slog.Logger) *cursorBackgroundTools {+ b := &cursorBackgroundTools{ctx: ctx, cmd: cmd, messages: messages, logger: logger, stop: make(chan struct{}), done: make(chan struct{})}+ go func() {+ defer close(b.done)+ // This only observes natural process exit; it never measures inactivity.+ ticker := time.NewTicker(time.Second)+ defer ticker.Stop()+ for {+ select {+ case <-ticker.C:+ b.Reap()+ case <-b.stop:+ return+ case <-ctx.Done():+ return+ }+ }+ }()+ return b+}++func (b *cursorBackgroundTools) Activity() (int32, time.Time) {+ return b.inFlight.Load(), time.Unix(0, b.lastToolActivity.Load())+}++func (b *cursorBackgroundTools) Send(msg Message) {+ if msg.Type == MessageToolUse || msg.Type == MessageToolResult {+ now := time.Now().UnixNano()+ for {+ previous := b.lastToolActivity.Load()+ if now <= previous || b.lastToolActivity.CompareAndSwap(previous, now) {+ break+ }+ }+ }+ if msg.Type == MessageToolUse {+ b.inFlight.Add(1)+ }+ // Publish completion before switching to the idle budget. Otherwise the+ // watchdog can see zero tools with the old timestamp and an empty queue.+ trySend(b.messages, msg)+ if msg.Type == MessageToolResult {+ for {+ count := b.inFlight.Load()+ if count <= 0 || b.inFlight.CompareAndSwap(count, count-1) {+ break+ }+ }+ }+}++func (b *cursorBackgroundTools) SendResult(call cursorToolCall) {+ b.Send(Message{Type: MessageToolResult, Tool: call.Name, CallID: call.CallID, Output: call.Result})+}++func (b *cursorBackgroundTools) Add(call cursorToolCall) {+ b.mu.Lock()+ defer b.mu.Unlock()+ if b.closed {+ return+ }+ for _, tool := range b.tools {+ if call.CallID != "" && tool.call.CallID == call.CallID {+ return+ }+ }+ p, err := captureCursorBackgroundProcess(b.cmd, call.PID)+ if err != nil {+ // No work was claimed. Preserve Cursor's launch completion so the idle+ // watchdog remains available even when the tool watchdog is disabled.+ // This grants no cleanup recovery window and never signals the PID.+ b.logger.Warn("cannot own Cursor background shell; returning launch result for idle watchdog fallback", "error", err)+ b.SendResult(call)+ return+ }+ b.tools = append(b.tools, cursorBackgroundTool{call: call, process: p})+}++// cursorCloseBudget bounds the WHOLE of Close(), not each process in it.+// Per-process termination is already bounded, but the number of background+// shells one run may launch is not, so "bounded per process" is not a bound on+// finalization. It has to be one, because Close() runs after the terminal+// result has been observed — the point at which the daemon's watchdog has+// deliberately stopped supervising this run, and MULTICA_AGENT_TIMEOUT is 0 by+// default. Work still unconfirmed when the budget runs out takes the existing+// unconfirmed-at-close path: its result is preserved and its cleanup is logged+// as unconfirmed, never reported as successful.+const cursorCloseBudget = 10 * time.Second++func (b *cursorBackgroundTools) Reap() {+ b.mu.Lock()+ defer b.mu.Unlock()+ if !b.closed {+ b.finish(false, time.Now().Add(b.budget()))+ }+}++// budget resolves the per-pass cleanup bound. Every pass that holds mu is+// bounded by it, not just the closing one: Close() has to wait for this lock,+// so an unbounded pass held by anyone else is an unbounded Close(), which is+// the same defect one level down.+func (b *cursorBackgroundTools) budget() time.Duration {+ if b.closeBudget > 0 {+ return b.closeBudget+ }+ return cursorCloseBudget+}++// Interrupt is called synchronously by the daemon's tool watchdog. Each tool+// can grant a recovery window only once: it is removed with its tool result.+func (b *cursorBackgroundTools) Interrupt() bool {+ b.mu.Lock()+ defer b.mu.Unlock()+ if b.closed || b.ctx.Err() != nil {+ return false+ }+ return b.finish(true, time.Now().Add(b.budget()))+}++// finish is called with mu held. A failed ownership check or cleanup never+// decrements the tool count; only confirmed process exit releases its result.+//+// A non-zero deadline caps the whole pass rather than each process: once it has+// passed, the remaining tools are left untouched and unconfirmed instead of+// each adding its own termination wait.+func (b *cursorBackgroundTools) finish(interrupt bool, deadline time.Time) bool {+ completed := false+ remaining := b.tools[:0]+ for _, tool := range b.tools {+ if tool.process == nil {+ remaining = append(remaining, tool)+ continue+ }+ if !deadline.IsZero() && !time.Now().Before(deadline) {+ remaining = append(remaining, tool)+ continue+ }+ alive, err := tool.process.Alive()+ if err == nil && alive && interrupt {+ err = tool.process.Terminate()+ if err == nil {+ alive, err = tool.process.Alive()+ }+ }+ if err != nil || alive {+ if err != nil && interrupt {+ b.logger.Warn("could not stop Cursor background shell", "error", err)+ }+ remaining = append(remaining, tool)+ continue+ }+ b.SendResult(tool.call)+ tool.process.Close()+ completed = true+ }+ b.tools = remaining+ return completed+}++func (b *cursorBackgroundTools) Close() {+ b.once.Do(func() {+ // Taken before the lock on purpose: waiting for a concurrent pass is+ // part of what Close() has to bound, not something outside its budget.+ // Every other pass is bounded by the same value, so the wait is too.+ deadline := time.Now().Add(b.budget())+ b.mu.Lock()+ b.closed = true+ // If waiting for the lock already consumed the budget, the closing pass+ // still gets a full one of its own: the bound this guards is "Close()+ // returns", and giving it zero time would just push every tool onto the+ // unconfirmed path without trying. Two budgets is the honest ceiling,+ // and terminalResultHandoffBudget is derived from exactly that.+ if !time.Now().Before(deadline) {+ deadline = time.Now().Add(b.budget())+ }+ b.finish(true, deadline)+ if len(b.tools) > 0 {+ // Retry a transient lookup/termination failure before releasing the+ // final claim. Persistent errors remain explicitly unconfirmed.+ b.finish(true, deadline)+ }+ for _, tool := range b.tools {+ // The stream is closing, so preserve even unverifiable launch+ // payloads without pretending cleanup succeeded in native accounting.+ b.logger.Warn("Cursor background cleanup unconfirmed at close", "call_id", tool.call.CallID)+ trySend(b.messages, Message{Type: MessageToolResult, Tool: tool.call.Name, CallID: tool.call.CallID, Output: tool.call.Result})+ tool.process.Close()+ }+ b.tools = nil+ b.mu.Unlock()+ close(b.stop)+ <-b.done+ })+}diff --git a/server/pkg/agent/cursor_background_identity_darwin_test.go b/server/pkg/agent/cursor_background_identity_darwin_test.gonew file mode 100644index 0000000000..a5e29ec30d--- /dev/null+++ b/server/pkg/agent/cursor_background_identity_darwin_test.go@@ -0,0 +1,38 @@+//go:build darwin++package agent++import (+ "os"+ "os/exec"+ "syscall"+ "testing"+ "unsafe"+)++func TestCaptureCursorBackgroundKernelRejectsStaleIdentity(t *testing.T) {+ var layout cursorDarwinIdentity+ if unsafe.Sizeof(layout) != 56 || unsafe.Offsetof(layout.unique) != 16 || unsafe.Offsetof(layout.version) != 32 {+ t.Fatal("Darwin process identity ABI layout changed")+ }+ child := exec.Command(os.Args[0])+ child.Env = append(os.Environ(), cursorFakeModeEnv+"=leaf", "CURSOR_FAKE_DURATION=30s")+ if err := child.Start(); err != nil {+ t.Fatal(err)+ }+ defer func() { _ = child.Process.Kill(); _ = child.Wait() }()+ identity, err := readCursorDarwinIdentity(child.Process.Pid)+ if err != nil {+ t.Fatal(err)+ }+ if err := signalCursorDarwinIdentity(child.Process.Pid, identity.version+1, syscall.SIGKILL); err != syscall.ESRCH {+ t.Fatalf("kernel accepted a stale PID version: %v", err)+ }+ if err := child.Process.Signal(syscall.Signal(0)); err != nil {+ t.Fatalf("stale identity signalled a live process: %v", err)+ }+ if err := signalCursorDarwinIdentity(child.Process.Pid, identity.version, syscall.SIGKILL); err != nil {+ t.Fatalf("kernel could not signal the verified identity: %v", err)+ }+ assertCursorTestProcessGone(t, child.Process.Pid)+}diff --git a/server/pkg/agent/cursor_background_late_child_test.go b/server/pkg/agent/cursor_background_late_child_test.gonew file mode 100644index 0000000000..199be6c2de--- /dev/null+++ b/server/pkg/agent/cursor_background_late_child_test.go@@ -0,0 +1,100 @@+//go:build linux || darwin || windows++package agent++import (+ "encoding/json"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "syscall"+ "testing"+ "time"+)++func TestCaptureCursorBackgroundLateDescendant(t *testing.T) {+ dir := t.TempDir()+ gate := filepath.Join(dir, "fork")+ root := exec.Command(os.Args[0])+ root.Env = append(os.Environ(), cursorFakeModeEnv+"=late", "CURSOR_FAKE_DIR="+dir,+ "CURSOR_FAKE_FORK_GATE="+gate, "CURSOR_FAKE_DURATION=30s")+ configureProcessGroup(root)+ hideAgentWindow(root)+ if err := startOwnedProcessTree(root, slog.Default()); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { signalProcessGroup(root, syscall.SIGKILL); _ = root.Wait(); releaseProcessGroup(root) })+ readPIDs := func(count int) []int {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ var pids []int+ data, _ := os.ReadFile(filepath.Join(dir, "0.json"))+ if json.Unmarshal(data, &pids) == nil && len(pids) == count {+ return pids+ }+ time.Sleep(5 * time.Millisecond)+ }+ t.Fatalf("fixture did not publish %d PIDs", count)+ return nil+ }+ leaderPID := readPIDs(1)[0]+ // The fork gate is still closed: the shell has no child to snapshot yet.+ owned, err := captureCursorBackgroundProcess(root, leaderPID)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = owned.Terminate(); owned.Close() })+ unrelated := exec.Command(os.Args[0])+ unrelated.Env = append(os.Environ(), cursorFakeModeEnv+"=leaf", "CURSOR_FAKE_DURATION=30s")+ configureProcessGroup(unrelated)+ hideAgentWindow(unrelated)+ if err := unrelated.Start(); err != nil {+ t.Fatal(err)+ }+ unrelatedDone := make(chan struct{})+ go func() { _ = unrelated.Wait(); close(unrelatedDone) }()+ t.Cleanup(func() { _ = unrelated.Process.Kill(); <-unrelatedDone })+ if err := os.WriteFile(gate, nil, 0600); err != nil {+ t.Fatal(err)+ }+ pids := readPIDs(2)+ // Test-only failure cleanup uses the fixture's known process identities.+ // Production gets no refresh between capture, fork and leader exit.+ late, err := os.FindProcess(pids[1])+ if err != nil {+ t.Fatal(err)+ }+ cleaned := false+ t.Cleanup(func() {+ if !cleaned {+ _ = late.Kill()+ }+ _ = late.Release()+ })+ leader, err := os.FindProcess(leaderPID)+ if err != nil {+ t.Fatal(err)+ }+ defer leader.Release()+ if err := leader.Kill(); err != nil {+ t.Fatal(err)+ }+ assertCursorTestProcessGone(t, leaderPID)+ if err := owned.Terminate(); err != nil {+ t.Fatalf("late-descendant cleanup failed: %v", err)+ }+ assertCursorTestProcessGone(t, pids[1])+ cleaned = true+ if alive, err := owned.Alive(); alive || err != nil {+ t.Fatalf("late descendant remains: alive=%v err=%v", alive, err)+ }+ select {+ case <-unrelatedDone:+ t.Fatal("unrelated process was signalled")+ default:+ }+ owned.Close()+ owned.Close()+}diff --git a/server/pkg/agent/cursor_background_lifecycle_other_test.go b/server/pkg/agent/cursor_background_lifecycle_other_test.gonew file mode 100644index 0000000000..084d384b9b--- /dev/null+++ b/server/pkg/agent/cursor_background_lifecycle_other_test.go@@ -0,0 +1,15 @@+//go:build !windows && !linux && !darwin++package agent++import (+ "os/exec"+ "testing"+)++func configureCursorTestBackgroundProcess(cmd *exec.Cmd) { configureProcessGroup(cmd) }++func assertCursorTestProcessGone(t *testing.T, _ int) {+ t.Helper()+ t.Skip("background process ownership is unavailable on this platform")+}diff --git a/server/pkg/agent/cursor_background_lifecycle_unix_test.go b/server/pkg/agent/cursor_background_lifecycle_unix_test.gonew file mode 100644index 0000000000..9bf0bf3e6c--- /dev/null+++ b/server/pkg/agent/cursor_background_lifecycle_unix_test.go@@ -0,0 +1,34 @@+//go:build linux || darwin++package agent++import (+ "os"+ "os/exec"+ "syscall"+ "testing"+ "time"+)++func configureCursorTestBackgroundProcess(cmd *exec.Cmd) {+ if os.Getenv("CURSOR_FAKE_SETSID") == "1" {+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}+ return+ }+ configureProcessGroup(cmd)+}++func assertCursorTestProcessGone(t *testing.T, pid int) {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for {+ info, err := readCursorUnixProcessInfo(pid)+ if err != nil || info.zombie {+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("background process %d survived", pid)+ }+ time.Sleep(10 * time.Millisecond)+ }+}diff --git a/server/pkg/agent/cursor_background_lifecycle_windows_test.go b/server/pkg/agent/cursor_background_lifecycle_windows_test.gonew file mode 100644index 0000000000..1e9fa22c2f--- /dev/null+++ b/server/pkg/agent/cursor_background_lifecycle_windows_test.go@@ -0,0 +1,51 @@+//go:build windows++package agent++import (+ "errors"+ "golang.org/x/sys/windows"+ "log/slog"+ "os"+ "os/exec"+ "syscall"+ "testing"+)++func configureCursorTestBackgroundProcess(cmd *exec.Cmd) { configureProcessGroup(cmd) }++func TestCaptureCursorBackgroundProcessRejectsForeignJob(t *testing.T) {+ spawn := func() *exec.Cmd {+ cmd := exec.Command(os.Args[0])+ cmd.Env = append(os.Environ(), cursorFakeModeEnv+"=leaf", "CURSOR_FAKE_DURATION=30s")+ hideAgentWindow(cmd)+ if err := startOwnedProcessTree(cmd, slog.Default()); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { signalProcessGroup(cmd, syscall.SIGKILL); _ = cmd.Wait(); releaseProcessGroup(cmd) })+ return cmd+ }+ root, other := spawn(), spawn()+ for _, pid := range []int{root.Process.Pid, other.Process.Pid, os.Getpid(), -1} {+ if p, err := captureCursorBackgroundProcess(root, pid); err == nil {+ p.Close()+ t.Fatalf("accepted non-background PID %d", pid)+ }+ }+}++func assertCursorTestProcessGone(t *testing.T, pid int) {+ t.Helper()+ handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))+ if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ defer windows.CloseHandle(handle)+ status, err := windows.WaitForSingleObject(handle, 2000)+ if err != nil || status != windows.WAIT_OBJECT_0 {+ t.Fatalf("background process %d survived: wait=%d err=%v", pid, status, err)+ }+}diff --git a/server/pkg/agent/cursor_background_process.go b/server/pkg/agent/cursor_background_process.gonew file mode 100644index 0000000000..4f34c0d36d--- /dev/null+++ b/server/pkg/agent/cursor_background_process.go@@ -0,0 +1,65 @@+package agent++import (+ "errors"+ "sync"+)++var (+ errCursorBackgroundProcessInvalid = errors.New("cursor background process is not an owned descendant")+ errCursorBackgroundProcessIdentity = errors.New("cursor background process identity can no longer be proven")+)++// cursorBackgroundProcess is a platform-owned handle for the process Cursor+// reports in a completed shellToolCall. The handle deliberately owns more than+// the reported PID: a PID can be reused after the shell exits.+type cursorBackgroundProcess struct {+ mu sync.Mutex+ closed bool+ platform cursorBackgroundProcessPlatform+}++type cursorBackgroundProcessPlatform interface {+ alive() (bool, error)+ terminate() error+ close()+}++func (p *cursorBackgroundProcess) Alive() (bool, error) {+ if p == nil {+ return false, nil+ }+ p.mu.Lock()+ defer p.mu.Unlock()+ if p.closed || p.platform == nil {+ return false, nil+ }+ return p.platform.alive()+}++func (p *cursorBackgroundProcess) Terminate() error {+ if p == nil {+ return nil+ }+ p.mu.Lock()+ defer p.mu.Unlock()+ if p.closed || p.platform == nil {+ return nil+ }+ return p.platform.terminate()+}++func (p *cursorBackgroundProcess) Close() {+ if p == nil {+ return+ }+ p.mu.Lock()+ defer p.mu.Unlock()+ if p.closed {+ return+ }+ p.closed = true+ if p.platform != nil {+ p.platform.close()+ }+}diff --git a/server/pkg/agent/cursor_background_process_darwin.go b/server/pkg/agent/cursor_background_process_darwin.gonew file mode 100644index 0000000000..c77dfae755--- /dev/null+++ b/server/pkg/agent/cursor_background_process_darwin.go@@ -0,0 +1,208 @@+//go:build darwin++package agent++import (+ "errors"+ "syscall"+ "unsafe"++ "golang.org/x/sys/unix"+)++type cursorUnixGroupHandle struct {+ pgid int+ known map[uint64]struct{}+}++func captureCursorUnixGroup(pgid int) (*cursorUnixGroupHandle, error) {+ // Probe with a positive PID beyond XNU's PID_MAX (99999). PID zero is+ // rejected as EINVAL on some kernels, indistinguishable from a missing API.+ // Unsupported kernels fail closed; numeric kill is not a safe fallback.+ if err := signalCursorDarwinIdentity(1<<31-1, 0, syscall.SIGKILL); err != syscall.ESRCH {+ return nil, errors.Join(errors.New("Cursor background identity signalling is unavailable on this macOS kernel"), err)+ }+ identity, err := readCursorDarwinIdentity(pgid)+ if err != nil {+ return nil, err+ }+ g := &cursorUnixGroupHandle{pgid: pgid, known: map[uint64]struct{}{identity.unique: {}}}+ if err := g.signal(0); err != nil {+ return nil, err+ }+ return g, nil+}++func (g *cursorUnixGroupHandle) signal(sig syscall.Signal) error {+ all, err := listCursorUnixProcessInfos()+ if err != nil {+ return err+ }+ candidates := make(map[int]cursorDarwinIdentity)+ for _, info := range all {+ if info.pgid != g.pgid || info.zombie {+ continue+ }+ identity, err := readCursorDarwinIdentity(info.pid)+ if err != nil {+ if err == syscall.ESRCH {+ continue+ }+ return err+ }+ current, err := readCursorUnixProcessInfo(info.pid)+ if err != nil || current.zombie || current.start != info.start || current.pgid != g.pgid {+ continue+ }+ candidates[info.pid] = identity+ }+ if len(candidates) == 0 {+ remaining, err := listCursorUnixProcessGroup(g.pgid)+ if err != nil {+ return err+ }+ if len(remaining) != 0 {+ return errCursorBackgroundProcessIdentity+ }+ return syscall.ESRCH+ }+ // Retain observed birth identities after exit. Parent unique IDs survive+ // reparenting, allowing a late direct child to prove its origin even after+ // its leader exits. An entirely unseen intermediate generation is a limit:+ // never infer ownership just because an unknown process has this PGID.+ for changed := true; changed; {+ changed = false+ for _, identity := range candidates {+ if _, known := g.known[identity.unique]; known {+ continue+ }+ if _, parentKnown := g.known[identity.parentUnique]; parentKnown {+ g.known[identity.unique] = struct{}{}+ changed = true+ }+ }+ }+ owned := 0+ var signalErr error+ for pid, identity := range candidates {+ if _, known := g.known[identity.unique]; !known {+ continue+ }+ owned+++ if sig != 0 {+ // The kernel checks pidversion and holds the exact process reference+ // while signalling. PID reuse or exec after this snapshot is rejected.+ err := signalCursorDarwinIdentity(pid, identity.version, sig)+ if err != nil && err != syscall.ESRCH {+ signalErr = errors.Join(signalErr, err)+ }+ }+ }+ if owned == 0 {+ return errCursorBackgroundProcessIdentity+ }+ return signalErr+}+func (g *cursorUnixGroupHandle) close() { g.known = nil }++func cursorUnixIsDescendant(pid int, root cursorUnixProcessInfo) bool {+ rootIdentity, err := readCursorDarwinIdentity(root.pid)+ if err != nil {+ return false+ }+ currentRoot, err := readCursorUnixProcessInfo(root.pid)+ if err != nil || currentRoot.start != root.start {+ return false+ }+ // Cursor may already be an unreaped zombie while we drain its last output.+ // Original parent identities still prove ancestry after reparenting to init.+ var expected uint64+ seen := make(map[uint64]bool)+ for pid > 1 {+ identity, err := readCursorDarwinIdentity(pid)+ if err != nil || (expected != 0 && identity.unique != expected) || seen[identity.unique] {+ return false+ }+ if identity.unique == rootIdentity.unique || identity.parentUnique == rootIdentity.unique {+ return true+ }+ seen[identity.unique] = true+ info, err := readCursorUnixProcessInfo(pid)+ if err != nil {+ return false+ }+ expected, pid = identity.parentUnique, info.ppid+ }+ return false+}++// XNU bsd/sys/proc_info_private.h defines this 56-byte ABI. Only the kernel's+// unique birth ID and PID version are used; no Mach port or cgo is required.+type cursorDarwinIdentity struct {+ uuid [16]byte+ unique, parentUnique uint64+ version, parentVersion uint32+ reserved [2]uint64+}++func readCursorDarwinIdentity(pid int) (cursorDarwinIdentity, error) {+ var identity cursorDarwinIdentity+ // arg=1 includes unreaped zombies, needed to identify a root that exited+ // while its final stream events were buffered. Executable-work scans filter them.+ n, _, errno := syscall.Syscall6(unix.SYS_PROC_INFO, 2, uintptr(pid), 17, 1, uintptr(unsafe.Pointer(&identity)), unsafe.Sizeof(identity))+ if errno != 0 {+ return identity, errno+ }+ if n != 56 || identity.unique == 0 {+ return identity, errCursorBackgroundProcessIdentity+ }+ return identity, nil+}++func signalCursorDarwinIdentity(pid int, version uint32, sig syscall.Signal) error {+ // proc_signal_with_audittoken consumes PID and pidversion from the token;+ // permissions still come from the caller's real credentials.+ var token [8]uint32+ token[5], token[7] = uint32(pid), version+ _, _, errno := syscall.Syscall6(unix.SYS_PROC_INFO, 0x11, 0, uintptr(sig), 0, uintptr(unsafe.Pointer(&token)), unsafe.Sizeof(token))+ if errno != 0 {+ return errno+ }+ return nil+}++// Darwin's proc state constants are defined in <sys/proc.h>; x/sys/unix does+// not export SZOMB on all supported Darwin architectures.+const cursorDarwinZombieState = 5++func readCursorUnixProcessInfo(pid int) (cursorUnixProcessInfo, error) {+ proc, err := unix.SysctlKinfoProc("kern.proc.pid", pid)+ if err != nil {+ return cursorUnixProcessInfo{}, err+ }+ return cursorUnixProcessInfo{+ pid: int(proc.Proc.P_pid),+ ppid: int(proc.Eproc.Ppid),+ pgid: int(proc.Eproc.Pgid),+ start: uint64(proc.Proc.P_starttime.Sec)*1_000_000 + uint64(proc.Proc.P_starttime.Usec),+ zombie: proc.Proc.P_stat == cursorDarwinZombieState,+ }, nil+}++func listCursorUnixProcessInfos() ([]cursorUnixProcessInfo, error) {+ procs, err := unix.SysctlKinfoProcSlice("kern.proc.all")+ if err != nil {+ return nil, err+ }+ infos := make([]cursorUnixProcessInfo, 0, len(procs))+ for _, proc := range procs {+ infos = append(infos, cursorUnixProcessInfo{+ pid: int(proc.Proc.P_pid),+ ppid: int(proc.Eproc.Ppid),+ pgid: int(proc.Eproc.Pgid),+ start: uint64(proc.Proc.P_starttime.Sec)*1_000_000 + uint64(proc.Proc.P_starttime.Usec),+ zombie: proc.Proc.P_stat == cursorDarwinZombieState,+ })+ }+ return infos, nil+}diff --git a/server/pkg/agent/cursor_background_process_darwin_test.go b/server/pkg/agent/cursor_background_process_darwin_test.gonew file mode 100644index 0000000000..7de03ebcb1--- /dev/null+++ b/server/pkg/agent/cursor_background_process_darwin_test.go@@ -0,0 +1,62 @@+//go:build darwin++package agent++import (+ "encoding/json"+ "os"+ "os/exec"+ "path/filepath"+ "syscall"+ "testing"+ "time"+)++func TestCaptureCursorBackgroundDetachedSession(t *testing.T) {+ pidFile := filepath.Join(t.TempDir(), "pids.json")+ child := exec.Command(os.Args[0])+ child.Env = append(os.Environ(), cursorFakeModeEnv+"=shell", "CURSOR_FAKE_DURATION=30s", "CURSOR_FAKE_PIDS="+pidFile)+ child.SysProcAttr = &syscall.SysProcAttr{Setsid: true}+ if err := child.Start(); err != nil {+ t.Fatal(err)+ }+ defer func() { _ = child.Process.Kill(); _ = child.Wait() }()+ self, err := os.FindProcess(os.Getpid())+ if err != nil {+ t.Fatal(err)+ }+ defer self.Release()+ var pids []int+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ data, _ := os.ReadFile(pidFile)+ if json.Unmarshal(data, &pids) == nil && len(pids) == 2 {+ break+ }+ time.Sleep(5 * time.Millisecond)+ }+ if len(pids) != 2 {+ t.Fatal("fixture did not publish detached shell and child")+ }+ defer syscall.Kill(pids[1], syscall.SIGKILL)+ owned, err := captureCursorBackgroundProcess(&exec.Cmd{Process: self}, child.Process.Pid)+ if err != nil {+ t.Fatalf("capture detached Cursor shell: %v", err)+ }+ defer owned.Close()+ group := owned.platform.(*cursorUnixBackgroundProcess)+ group.leaderStart+++ if err := owned.Terminate(); err == nil {+ t.Fatal("signalled a detached shell with a changed identity")+ }+ group.leaderStart--+ if err := child.Process.Signal(syscall.Signal(0)); err != nil {+ t.Fatalf("identity rejection signalled the detached shell: %v", err)+ }+ if err := owned.Terminate(); err != nil {+ t.Fatal(err)+ }+ for _, pid := range pids {+ assertCursorTestProcessGone(t, pid)+ }+}diff --git a/server/pkg/agent/cursor_background_process_linux.go b/server/pkg/agent/cursor_background_process_linux.gonew file mode 100644index 0000000000..ee65aa58c4--- /dev/null+++ b/server/pkg/agent/cursor_background_process_linux.go@@ -0,0 +1,113 @@+//go:build linux++package agent++import (+ "fmt"+ "os"+ "path/filepath"+ "strconv"+ "strings"+ "syscall"++ "golang.org/x/sys/unix"+)++// Linux 6.9's UAPI flag is not yet exported by x/sys/unix. It targets the+// pidfd's retained struct pid as a group, including children after leader exit.+const cursorPidfdSignalProcessGroup = 1 << 2++type cursorUnixGroupHandle struct{ fd int }++func captureCursorUnixGroup(pgid int) (*cursorUnixGroupHandle, error) {+ fd, err := unix.PidfdOpen(pgid, 0)+ if err != nil {+ return nil, err+ }+ g := &cursorUnixGroupHandle{fd: fd}+ // Probe support without sending a signal. Older kernels fail closed;+ // silently falling back to kill(-pgid) would lose durable ownership.+ if err := g.signal(0); err != nil {+ g.close()+ return nil, err+ }+ return g, nil+}++func (g *cursorUnixGroupHandle) signal(sig syscall.Signal) error {+ return unix.PidfdSendSignal(g.fd, unix.Signal(sig), nil, cursorPidfdSignalProcessGroup)+}+func (g *cursorUnixGroupHandle) close() { _ = unix.Close(g.fd) }++func readCursorUnixProcessInfo(pid int) (cursorUnixProcessInfo, error) {+ data, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))+ if err != nil {+ return cursorUnixProcessInfo{}, err+ }+ raw := string(data)+ openParen := strings.IndexByte(raw, '(')+ closeParen := strings.LastIndex(raw, ") ")+ if openParen <= 0 || closeParen < openParen {+ return cursorUnixProcessInfo{}, fmt.Errorf("malformed /proc/%d/stat", pid)+ }+ parsedPID, err := strconv.Atoi(strings.TrimSpace(raw[:openParen]))+ if err != nil || parsedPID != pid {+ return cursorUnixProcessInfo{}, fmt.Errorf("unexpected pid in /proc/%d/stat", pid)+ }+ fields := strings.Fields(raw[closeParen+2:])+ if len(fields) <= 19 {+ return cursorUnixProcessInfo{}, fmt.Errorf("short /proc/%d/stat", pid)+ }+ ppid, err := strconv.Atoi(fields[1])+ if err != nil {+ return cursorUnixProcessInfo{}, err+ }+ pgid, err := strconv.Atoi(fields[2])+ if err != nil {+ return cursorUnixProcessInfo{}, err+ }+ start, err := strconv.ParseUint(fields[19], 10, 64)+ if err != nil {+ return cursorUnixProcessInfo{}, err+ }+ return cursorUnixProcessInfo{pid: pid, ppid: ppid, pgid: pgid, start: start, zombie: fields[0] == "Z"}, nil+}++func listCursorUnixProcessInfos() ([]cursorUnixProcessInfo, error) {+ entries, err := os.ReadDir("/proc")+ if err != nil {+ return nil, err+ }+ infos := make([]cursorUnixProcessInfo, 0, len(entries))+ for _, entry := range entries {+ pid, err := strconv.Atoi(entry.Name())+ if err != nil {+ continue+ }+ info, err := readCursorUnixProcessInfo(pid)+ if err == nil && !info.zombie {+ infos = append(infos, info)+ }+ }+ return infos, nil+}++func cursorUnixIsDescendant(pid int, root cursorUnixProcessInfo) bool {+ seen := make(map[int]struct{}, 8)+ for pid > 1 {+ if pid == root.pid {+ info, err := readCursorUnixProcessInfo(pid)+ return err == nil && info.pid == root.pid && info.start == root.start+ }+ if _, ok := seen[pid]; ok {+ return false+ }+ seen[pid] = struct{}{}+ info, err := readCursorUnixProcessInfo(pid)+ if err != nil {+ return false+ }+ pid = info.ppid+ }+ return false+}diff --git a/server/pkg/agent/cursor_background_process_other.go b/server/pkg/agent/cursor_background_process_other.gonew file mode 100644index 0000000000..e92abbd33e--- /dev/null+++ b/server/pkg/agent/cursor_background_process_other.go@@ -0,0 +1,12 @@+//go:build !windows && !linux && !darwin++package agent++import (+ "errors"+ "os/exec"+)++func captureCursorBackgroundProcess(_ *exec.Cmd, _ int) (*cursorBackgroundProcess, error) {+ return nil, errors.New("cursor background process ownership is unsupported on this platform")+}diff --git a/server/pkg/agent/cursor_background_process_unix.go b/server/pkg/agent/cursor_background_process_unix.gonew file mode 100644index 0000000000..eb4a3c8874--- /dev/null+++ b/server/pkg/agent/cursor_background_process_unix.go@@ -0,0 +1,137 @@+//go:build linux || darwin++package agent++import (+ "fmt"+ "os/exec"+ "syscall"+ "time"+)++type cursorUnixProcessInfo struct {+ pid int+ ppid int+ pgid int+ start uint64+ zombie bool+}++type cursorUnixBackgroundProcess struct {+ pgid int+ leaderStart uint64+ group *cursorUnixGroupHandle+}++func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundProcess, error) {+ return captureCursorUnixBackgroundProcess(cmd, pid, captureCursorUnixGroup)+}++func captureCursorUnixBackgroundProcess(cmd *exec.Cmd, pid int, retainGroup func(int) (*cursorUnixGroupHandle, error)) (*cursorBackgroundProcess, error) {+ if cmd == nil || cmd.Process == nil || pid <= 0 || pid == cmd.Process.Pid {+ return nil, errCursorBackgroundProcessInvalid+ }+ root, err := readCursorUnixProcessInfo(cmd.Process.Pid)+ if err != nil {+ return nil, fmt.Errorf("read Cursor process: %w", err)+ }+ target, err := readCursorUnixProcessInfo(pid)+ if err != nil || target.zombie || target.pid != pid {+ return nil, errCursorBackgroundProcessInvalid+ }+ if target.pgid != target.pid || target.pgid == root.pgid {+ return nil, errCursorBackgroundProcessInvalid+ }+ if !cursorUnixIsDescendant(pid, root) {+ return nil, errCursorBackgroundProcessInvalid+ }+ leader, err := readCursorUnixProcessInfo(target.pgid)+ if err != nil || leader.pid != target.pgid || leader.pgid != target.pgid || leader.start != target.start {+ return nil, errCursorBackgroundProcessInvalid+ }+ group, err := retainGroup(target.pgid)+ if err != nil {+ return nil, fmt.Errorf("retain Cursor shell process group: %w", err)+ }+ // The ancestry above proves where this process came from. The Cursor root+ // may now exit and reparent it; retain the claim while the target identity+ // is unchanged, without requiring its original parent to remain alive.+ leader, err = readCursorUnixProcessInfo(pid)+ if err != nil || leader.pid != target.pid || leader.start != target.start || leader.zombie || leader.pgid != target.pgid {+ group.close()+ return nil, errCursorBackgroundProcessInvalid+ }+ return &cursorBackgroundProcess{platform: &cursorUnixBackgroundProcess{+ pgid: target.pgid,+ leaderStart: target.start,+ group: group,+ }}, nil+}++func (p *cursorUnixBackgroundProcess) alive() (bool, error) {+ owned, err := p.groupOwned()+ if err != nil || !owned {+ return false, err+ }+ return true, nil+}++func (p *cursorUnixBackgroundProcess) terminate() error {+ deadline := time.Now().Add(time.Second)+ for {+ owned, err := p.groupOwned()+ if err != nil {+ return err+ }+ if !owned {+ return nil+ }+ // A shell can fork during cleanup. Revalidate and stop newly proven+ // members within this existing cleanup bound, without a liveness timer.+ if err := p.group.signal(syscall.SIGKILL); err != nil && err != syscall.ESRCH {+ return err+ }+ if time.Now().After(deadline) {+ return fmt.Errorf("Cursor background process group %d still active after %s", p.pgid, time.Second)+ }+ time.Sleep(10 * time.Millisecond)+ }+}++func (p *cursorUnixBackgroundProcess) close() { p.group.close() }++func (p *cursorUnixBackgroundProcess) groupOwned() (bool, error) {+ leader, leaderErr := readCursorUnixProcessInfo(p.pgid)+ if leaderErr == nil && !leader.zombie && leader.pid == p.pgid && leader.pgid == p.pgid {+ if leader.start != p.leaderStart {+ return false, errCursorBackgroundProcessIdentity+ }+ }+ // Linux retains a kernel group reference; Darwin verifies individual birth+ // identities and lineage. Neither signals an unverified numeric PGID.+ if err := p.group.signal(0); err != nil {+ if err == syscall.ESRCH {+ return false, nil+ }+ return false, err+ }+ members, err := listCursorUnixProcessGroup(p.pgid)+ if err != nil {+ return false, err+ }+ return len(members) > 0, nil+}++func listCursorUnixProcessGroup(pgid int) (map[int]uint64, error) {+ all, err := listCursorUnixProcessInfos()+ if err != nil {+ return nil, err+ }+ members := make(map[int]uint64)+ for _, info := range all {+ if info.pgid == pgid && !info.zombie {+ members[info.pid] = info.start+ }+ }+ return members, nil+}diff --git a/server/pkg/agent/cursor_background_process_unix_test.go b/server/pkg/agent/cursor_background_process_unix_test.gonew file mode 100644index 0000000000..226ee7bd98--- /dev/null+++ b/server/pkg/agent/cursor_background_process_unix_test.go@@ -0,0 +1,135 @@+//go:build linux || darwin++package agent++import (+ "encoding/json"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "syscall"+ "testing"+ "time"+)++func TestCaptureCursorBackgroundProcessReapsLeaderExitedGroup(t *testing.T) {+ dir := t.TempDir()+ root := exec.Command(os.Args[0])+ root.Env = append(os.Environ(), cursorFakeModeEnv+"=budget", "CURSOR_FAKE_DIR="+dir, "CURSOR_FAKE_DURATION=30s")+ configureProcessGroup(root)+ if err := startOwnedProcessTree(root, slog.Default()); err != nil {+ t.Fatal(err)+ }+ defer func() { signalProcessGroup(root, syscall.SIGKILL); _ = root.Wait() }()+ var pids []int+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ data, _ := os.ReadFile(filepath.Join(dir, "0.json"))+ if json.Unmarshal(data, &pids) == nil && len(pids) == 2 {+ break+ }+ time.Sleep(10 * time.Millisecond)+ }+ if len(pids) != 2 {+ t.Fatal("fixture did not publish shell and child PIDs")+ }+ owned, err := captureCursorBackgroundProcess(root, pids[0])+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = owned.Terminate(); owned.Close() }()+ group := owned.platform.(*cursorUnixBackgroundProcess)+ group.leaderStart+++ if err := owned.Terminate(); err == nil {+ t.Fatal("signalled a process whose recorded identity changed")+ }+ group.leaderStart--+ if err := syscall.Kill(pids[0], syscall.SIGKILL); err != nil {+ t.Fatal(err)+ }+ assertCursorTestProcessGone(t, pids[0])+ if err := owned.Terminate(); err != nil {+ t.Fatalf("cleanup with exited leader: %v", err)+ }+ assertCursorTestProcessGone(t, pids[1])+ if alive, err := owned.Alive(); alive || err != nil {+ t.Fatalf("Alive=%v err=%v", alive, err)+ }+}++func TestCaptureCursorBackgroundProcessRejectsUnrelatedPID(t *testing.T) {+ spawn := func() *exec.Cmd {+ cmd := exec.Command(os.Args[0])+ cmd.Env = append(os.Environ(), cursorFakeModeEnv+"=leaf", "CURSOR_FAKE_DURATION=30s")+ cmd.Stdout = io.Discard+ configureProcessGroup(cmd)+ if err := startOwnedProcessTree(cmd, slog.Default()); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { signalProcessGroup(cmd, syscall.SIGKILL); _ = cmd.Wait() })+ return cmd+ }+ root, other := spawn(), spawn()+ if _, err := captureCursorBackgroundProcess(root, other.Process.Pid); err == nil {+ t.Fatal("accepted unrelated process")+ }+}++func TestCaptureCursorBackgroundSurvivesRootExitDuringCapture(t *testing.T) {+ dir := t.TempDir()+ root := exec.Command(os.Args[0])+ root.Env = append(os.Environ(), cursorFakeModeEnv+"=budget", "CURSOR_FAKE_DIR="+dir, "CURSOR_FAKE_DURATION=30s")+ configureProcessGroup(root)+ if err := root.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = root.Process.Kill(); _ = root.Wait() })+ var pids []int+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ data, _ := os.ReadFile(filepath.Join(dir, "0.json"))+ if json.Unmarshal(data, &pids) == nil && len(pids) == 2 {+ break+ }+ time.Sleep(5 * time.Millisecond)+ }+ if len(pids) != 2 {+ t.Fatal("fixture did not publish shell and child PIDs")+ }+ t.Cleanup(func() {+ for _, pid := range pids {+ _ = syscall.Kill(pid, syscall.SIGKILL)+ }+ })+ rootInfo, err := readCursorUnixProcessInfo(root.Process.Pid)+ if err != nil {+ t.Fatal(err)+ }+ rootInfo.start+++ if cursorUnixIsDescendant(pids[0], rootInfo) {+ t.Fatal("accepted ancestry through a reused root identity")+ }+ owned, err := captureCursorUnixBackgroundProcess(root, pids[0], func(pgid int) (*cursorUnixGroupHandle, error) {+ group, err := captureCursorUnixGroup(pgid)+ if err != nil {+ return nil, err+ }+ // Ancestry has been proven and the handle retained. Force the root to+ // exit here, before post-capture validation, as normal finalization can.+ _ = root.Process.Kill()+ _ = root.Wait()+ return group, nil+ })+ if err != nil {+ t.Fatalf("lost verified background work when Cursor root exited: %v", err)+ }+ defer owned.Close()+ if err := owned.Terminate(); err != nil {+ t.Fatal(err)+ }+ for _, pid := range pids {+ assertCursorTestProcessGone(t, pid)+ }+}diff --git a/server/pkg/agent/cursor_background_process_windows.go b/server/pkg/agent/cursor_background_process_windows.gonew file mode 100644index 0000000000..407274eb3c--- /dev/null+++ b/server/pkg/agent/cursor_background_process_windows.go@@ -0,0 +1,192 @@+//go:build windows++package agent++import (+ "errors"+ "fmt"+ "os/exec"+ "time"+ "unsafe"++ "golang.org/x/sys/windows"+)++type cursorWindowsBackgroundProcess struct{ job windows.Handle }++var cursorIsProcessInJob = windows.NewLazySystemDLL("kernel32.dll").NewProc("IsProcessInJob")++func cursorProcessInJob(process, job windows.Handle) (bool, error) {+ var member int32+ ok, _, err := cursorIsProcessInJob.Call(uintptr(process), uintptr(job), uintptr(unsafe.Pointer(&member)))+ if ok == 0 {+ return false, err+ }+ return member != 0, nil+}++func cursorProcessCreated(process windows.Handle) (uint64, error) {+ var created, exited, kernel, user windows.Filetime+ err := windows.GetProcessTimes(process, &created, &exited, &kernel, &user)+ return uint64(created.HighDateTime)<<32 | uint64(created.LowDateTime), err+}++func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundProcess, error) {+ if cmd == nil || cmd.Process == nil || pid <= 0 || uint64(pid) > uint64(^uint32(0)) || pid == cmd.Process.Pid {+ return nil, errCursorBackgroundProcessInvalid+ }+ root, ok := lookupProcessTree(cmd)+ if !ok {+ return nil, errCursorBackgroundProcessInvalid+ }+ parents, err := cursorWindowsProcessParents()+ if err != nil {+ return nil, err+ }+ type heldProcess struct {+ pid uint32+ handle windows.Handle+ created uint64+ }+ var held []heldProcess+ defer func() {+ for _, p := range held {+ _ = windows.CloseHandle(p.handle)+ }+ }()+ open := func(pid uint32) (heldProcess, error) {+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, pid)+ if err != nil {+ return heldProcess{}, err+ }+ created, err := cursorProcessCreated(h)+ member, memberErr := cursorProcessInJob(h, root.job)+ if err != nil || memberErr != nil || !member {+ _ = windows.CloseHandle(h)+ return heldProcess{}, errCursorBackgroundProcessInvalid+ }+ p := heldProcess{pid, h, created}+ held = append(held, p)+ return p, nil+ }+ target, err := open(uint32(pid))+ if err != nil {+ return nil, err+ }+ // Held handles and creation ordering reject reused parent PIDs. Membership+ // of this launch's Job also prevents a payload from claiming another task.+ child := target+ seen := map[uint32]bool{}+ for child.pid != uint32(cmd.Process.Pid) {+ parentPID := parents[child.pid]+ if parentPID == 0 || seen[parentPID] {+ return nil, errCursorBackgroundProcessInvalid+ }+ seen[parentPID] = true+ parent, err := open(parentPID)+ if err != nil || parent.created > child.created {+ return nil, errCursorBackgroundProcessInvalid+ }+ child = parent+ }+ job, err := windows.CreateJobObject(nil, nil)+ if err != nil {+ return nil, err+ }+ success := false+ defer func() {+ if !success {+ _ = windows.CloseHandle(job)+ }+ }()+ if err := windows.AssignProcessToJobObject(job, target.handle); err != nil {+ return nil, err+ }+ // Assign each parent BEFORE enumerating its immediate children. New children+ // now inherit the Job, and pre-existing children are attached breadth first.+ queue := []heldProcess{target}+ for len(queue) > 0 {+ parent := queue[0]+ queue = queue[1:]+ parents, err := cursorWindowsProcessParents()+ if err != nil {+ return nil, err+ }+ for childPID, parentPID := range parents {+ if parentPID != parent.pid {+ continue+ }+ child, err := open(childPID)+ if err != nil {+ return nil, err+ }+ if child.created < parent.created {+ return nil, errCursorBackgroundProcessIdentity+ }+ member, err := cursorProcessInJob(child.handle, job)+ if err != nil {+ return nil, err+ }+ if member {+ continue+ }+ if err := windows.AssignProcessToJobObject(job, child.handle); err != nil {+ return nil, err+ }+ queue = append(queue, child)+ }+ }+ // A failed capture must not kill a healthy shell. Enable kill-on-close only+ // after the whole observed subtree has been claimed successfully.+ info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{}+ info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if _, err := windows.SetInformationJobObject(job, windows.JobObjectExtendedLimitInformation, uintptr(unsafe.Pointer(&info)), uint32(unsafe.Sizeof(info))); err != nil {+ return nil, err+ }+ success = true+ return &cursorBackgroundProcess{platform: &cursorWindowsBackgroundProcess{job: job}}, nil+}++func (p *cursorWindowsBackgroundProcess) alive() (bool, error) {+ active, err := (ownedProcessTree{job: p.job}).activeProcesses()+ return active > 0, err+}+func (p *cursorWindowsBackgroundProcess) terminate() error {+ if err := windows.TerminateJobObject(p.job, 1); err != nil {+ return err+ }+ deadline := time.Now().Add(time.Second)+ for {+ alive, err := p.alive()+ if err != nil || !alive {+ return err+ }+ if time.Now().After(deadline) {+ return fmt.Errorf("Cursor background job did not exit after one second")+ }+ time.Sleep(10 * time.Millisecond)+ }+}+func (p *cursorWindowsBackgroundProcess) close() { _ = windows.CloseHandle(p.job) }++func cursorWindowsProcessParents() (map[uint32]uint32, error) {+ snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)+ if err != nil {+ return nil, err+ }+ defer windows.CloseHandle(snapshot)+ parents := make(map[uint32]uint32)+ entry := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))}+ if err := windows.Process32First(snapshot, &entry); err != nil {+ return nil, err+ }+ for {+ parents[entry.ProcessID] = entry.ParentProcessID+ if err := windows.Process32Next(snapshot, &entry); err != nil {+ if errors.Is(err, windows.ERROR_NO_MORE_FILES) {+ return parents, nil+ }+ return nil, err+ }+ }+}diff --git a/server/pkg/agent/cursor_close_budget_test.go b/server/pkg/agent/cursor_close_budget_test.gonew file mode 100644index 0000000000..6e9f44dd5b--- /dev/null+++ b/server/pkg/agent/cursor_close_budget_test.go@@ -0,0 +1,133 @@+package agent++import (+ "context"+ "log/slog"+ "sync"+ "testing"+ "time"+)++// stuckBackgroundProcess never dies and takes a fixed time to signal, which is+// the shape that makes per-process bounds insufficient: each one is bounded,+// but a run may launch any number of them.+type stuckBackgroundProcess struct {+ signal time.Duration+ // entered, when set, is closed the first time this process is signalled.+ // finish() holds mu for the whole pass, so that close is proof the caller+ // owns the lock — which a channel closed just before calling Interrupt is+ // not: it only says the goroutine was about to try.+ entered chan struct{}+ once sync.Once+}++func (p *stuckBackgroundProcess) alive() (bool, error) { return true, nil }+func (p *stuckBackgroundProcess) terminate() error {+ if p.entered != nil {+ p.once.Do(func() { close(p.entered) })+ }+ time.Sleep(p.signal)+ return nil+}+func (p *stuckBackgroundProcess) close() {}++// TestCursorBackgroundCloseIsBoundedAcrossTools pins the bound that matters+// after a terminal result: Close() runs once the daemon's watchdog has stopped+// supervising the run, so "each process is bounded" is not enough — the whole+// pass has to be. Unconfirmed work must still surface its launch result.+func TestCursorBackgroundCloseIsBoundedAcrossTools(t *testing.T) {+ const (+ tools = 40+ signal = 100 * time.Millisecond+ budget = 300 * time.Millisecond+ )+ // Without a whole-pass bound this would take tools*signal*2 = 8s.+ unbounded := tools * signal * 2++ messages := make(chan Message, 4*tools)+ b := newCursorBackgroundTools(context.Background(), nil, messages, slog.Default())+ b.closeBudget = budget+ for i := 0; i < tools; i++ {+ b.tools = append(b.tools, cursorBackgroundTool{+ call: cursorToolCall{Name: "shell", CallID: "bg", Result: `{"isBackground":true}`},+ process: &cursorBackgroundProcess{platform: &stuckBackgroundProcess{signal: signal}},+ })+ }++ start := time.Now()+ b.Close()+ elapsed := time.Since(start)++ // One in-flight signal may still be running when the budget expires.+ if limit := budget + signal + 2*time.Second; elapsed > limit {+ t.Fatalf("Close took %s, want under %s (unbounded would be ~%s)", elapsed, limit, unbounded)+ }+ if elapsed >= unbounded {+ t.Fatalf("Close took %s: the whole-pass budget did not apply", elapsed)+ }++ // Every tool still hands back its original launch result, none of it+ // reported as confirmed cleanup.+ close(messages)+ results := 0+ for msg := range messages {+ if msg.Type == MessageToolResult {+ results+++ }+ }+ if results != tools {+ t.Fatalf("released %d tool results, want %d: unconfirmed work must not be dropped", results, tools)+ }+}++// TestCursorBackgroundCloseIsBoundedBehindAConcurrentPass covers the gap the+// first test cannot see: Close() takes its deadline before the lock, but the+// bound only holds if whoever already holds that lock is bounded too. An+// unbounded Interrupt() scanning an unbounded number of tools is an unbounded+// Close(), one level down — and Interrupt-holds-the-lock-while-the-terminal-+// result-arrives is the exact topology this whole boundary exists for.+func TestCursorBackgroundCloseIsBoundedBehindAConcurrentPass(t *testing.T) {+ const (+ tools = 20+ signal = 50 * time.Millisecond+ budget = 100 * time.Millisecond+ )+ messages := make(chan Message, 8*tools)+ b := newCursorBackgroundTools(context.Background(), nil, messages, slog.Default())+ b.closeBudget = budget+ // Only the first process carries the gate; it is the one the interrupting+ // pass reaches first, so closing it happens inside that pass's critical+ // section.+ entered := make(chan struct{})+ for i := 0; i < tools; i++ {+ platform := &stuckBackgroundProcess{signal: signal}+ if i == 0 {+ platform.entered = entered+ }+ b.tools = append(b.tools, cursorBackgroundTool{+ call: cursorToolCall{Name: "shell", CallID: "bg", Result: `{"isBackground":true}`},+ process: &cursorBackgroundProcess{platform: platform},+ })+ }++ // The watchdog's cleanup pass must already hold the lock before Close() asks+ // for it, or Close() can win the lock and finish on its own — and then an+ // unbounded Interrupt() would still pass this test. Waiting for the gate+ // inside the pass is what makes the ordering a fact rather than a scheduling+ // habit. Unbounded, that pass alone would take tools*signal = 1s.+ go b.Interrupt()+ <-entered++ start := time.Now()+ b.Close()+ elapsed := time.Since(start)++ // Worst case is one lock wait plus the closing pass, each bounded, plus a+ // signal that was already in flight when a budget expired.+ if limit := 2*budget + 2*signal + 2*time.Second; elapsed > limit {+ t.Fatalf("Close took %s behind a concurrent pass, want under %s", elapsed, limit)+ }+ if elapsed >= tools*signal {+ t.Fatalf("Close took %s: the concurrent pass was not bounded", elapsed)+ }+}diff --git a/server/pkg/agent/cursor_liveness_test.go b/server/pkg/agent/cursor_liveness_test.gonew file mode 100644index 0000000000..25c315431e--- /dev/null+++ b/server/pkg/agent/cursor_liveness_test.go@@ -0,0 +1,472 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strconv"+ "testing"+ "time"+)++const cursorFakeModeEnv = "CURSOR_FAKE_MODE"++type cursorCleanupRetryProcess struct {+ checks, stops, closes int+ stopped bool+ stopFailures int+}++func (p *cursorCleanupRetryProcess) alive() (bool, error) {+ p.checks+++ if p.checks == 1 {+ return false, errors.New("temporary ownership lookup failure")+ }+ return !p.stopped, nil+}+func (p *cursorCleanupRetryProcess) terminate() error {+ p.stops+++ if p.stops <= p.stopFailures {+ return errors.New("temporary termination failure")+ }+ p.stopped = true+ return nil+}++func TestCursorBackgroundCloseRetriesTermination(t *testing.T) {+ for _, failures := range []int{1, 2} {+ t.Run(strconv.Itoa(failures), func(t *testing.T) {+ messages := make(chan Message, 4)+ tracker := newCursorBackgroundTools(context.Background(), nil, messages, slog.Default())+ defer tracker.Close()+ p := &cursorCleanupRetryProcess{checks: 1, stopFailures: failures}+ tracker.Send(Message{Type: MessageToolUse, Tool: "shell", CallID: "retry"})+ tracker.mu.Lock()+ tracker.tools = append(tracker.tools, cursorBackgroundTool{+ call: cursorToolCall{Name: "shell", CallID: "retry", Result: "raw launch"},+ process: &cursorBackgroundProcess{platform: p},+ })+ tracker.mu.Unlock()+ tracker.Close()+ wantCount := int32(0)+ if failures == 2 {+ wantCount = 1+ }+ if count, _ := tracker.Activity(); count != wantCount || p.stops != 2 || p.closes != 1 {+ t.Fatalf("termination retry: count=%d stops=%d closes=%d", count, p.stops, p.closes)+ }+ <-messages+ if msg := <-messages; msg.Output != "raw launch" || len(messages) != 0 || tracker.Interrupt() {+ t.Fatalf("incorrect final result or repeated recovery: %+v", msg)+ }+ })+ }+}+func (p *cursorCleanupRetryProcess) close() { p.closes++ }++func TestCursorBackgroundCloseRetriesUnconfirmedCleanup(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ messages := make(chan Message, 4)+ tracker := newCursorBackgroundTools(ctx, nil, messages, slog.Default())+ p := &cursorCleanupRetryProcess{}+ tracker.Send(Message{Type: MessageToolUse, Tool: "shell", CallID: "retry"})+ tracker.mu.Lock()+ tracker.tools = append(tracker.tools, cursorBackgroundTool{+ call: cursorToolCall{Name: "shell", CallID: "retry", Result: "raw launch"},+ process: &cursorBackgroundProcess{platform: p},+ })+ tracker.mu.Unlock()+ if tracker.Interrupt() {+ t.Fatal("failed ownership lookup granted recovery")+ }+ if count, _ := tracker.Activity(); count != 1 || len(messages) != 1 {+ t.Fatal("failed cleanup released its tool result")+ }+ tracker.Close()+ tracker.Close()+ if count, _ := tracker.Activity(); count != 0 || p.stops != 1 || p.closes != 1 || tracker.Interrupt() {+ t.Fatalf("cleanup lifecycle: count=%d stops=%d closes=%d", count, p.stops, p.closes)+ }+ <-messages+ if msg := <-messages; msg.CallID != "retry" || msg.Output != "raw launch" || len(messages) != 0 {+ t.Fatalf("missing or repeated matching result: %+v", msg)+ }+}++// The fake shell has its own group and an already-running child before Cursor+// reports success.pid, matching the process relationships observed in #8050.+func runFakeCursorStream(mode string) {+ if mode == "leaf" {+ duration, _ := time.ParseDuration(os.Getenv("CURSOR_FAKE_DURATION"))+ time.Sleep(duration)+ return+ }+ if mode == "shell" {+ if gate := os.Getenv("CURSOR_FAKE_FORK_GATE"); gate != "" {+ for {+ if _, err := os.Stat(gate); err == nil {+ break+ }+ time.Sleep(5 * time.Millisecond)+ }+ }+ child := exec.Command(os.Args[0])+ child.Env = append(os.Environ(), cursorFakeModeEnv+"=leaf")+ hideAgentWindow(child)+ if err := child.Start(); err != nil {+ panic(err)+ }+ data, _ := json.Marshal([]int{os.Getpid(), child.Process.Pid})+ if err := os.WriteFile(os.Getenv("CURSOR_FAKE_PIDS"), data, 0600); err != nil {+ panic(err)+ }+ _ = child.Wait()+ return+ }+ _, _ = io.Copy(io.Discard, os.Stdin)+ if mode == "burst" {+ for i := 0; i < 600; i++ {+ fmt.Printf("{\"type\":\"tool_use\",\"tool_id\":\"%d\",\"tool_name\":\"read\"}\n", i)+ fmt.Printf("{\"type\":\"tool_result\",\"tool_id\":\"%d\",\"output\":\"ok\"}\n", i)+ }+ fmt.Println(`{"type":"result","subtype":"success","result":"done"}`)+ return+ }+ count := 1+ if mode == "multiple" {+ count = 2+ }+ var children []*exec.Cmd+ for i := 0; i < count; i++ {+ child := exec.Command(os.Args[0])+ pidFile := filepath.Join(os.Getenv("CURSOR_FAKE_DIR"), strconv.Itoa(i)+".json")+ child.Env = append(os.Environ(), cursorFakeModeEnv+"=shell", "CURSOR_FAKE_PIDS="+pidFile)+ hideAgentWindow(child)+ configureCursorTestBackgroundProcess(child)+ if err := child.Start(); err != nil {+ panic(err)+ }+ children = append(children, child)+ if mode == "late" {+ data, _ := json.Marshal([]int{child.Process.Pid})+ if err := os.WriteFile(pidFile, data, 0600); err != nil {+ panic(err)+ }+ }+ for mode != "late" {+ var pids []int+ data, _ := os.ReadFile(pidFile)+ if json.Unmarshal(data, &pids) == nil && len(pids) == 2 {+ break+ }+ time.Sleep(5 * time.Millisecond)+ }+ fmt.Printf("{\"type\":\"tool_call\",\"subtype\":\"started\",\"call_id\":\"bg-%d\",\"tool_call\":{\"shellToolCall\":{\"args\":{}}}}\n", i)+ fmt.Printf("{\"type\":\"tool_call\",\"subtype\":\"completed\",\"call_id\":\"bg-%d\",\"tool_call\":{\"shellToolCall\":{\"result\":{\"isBackground\":true,\"success\":{\"pid\":%d,\"shellId\":\"shell-%d\"}}}}}\n", i, child.Process.Pid, i)+ }+ fmt.Println(`{"type":"thinking","subtype":"delta","text":"ready"}`)+ fmt.Println(`{"type":"thinking","subtype":"completed"}`)+ if mode != "finish" {+ for _, child := range children {+ _ = child.Wait()+ }+ }+ fmt.Println(`{"type":"system","subtype":"task_notification"}`)+ fmt.Println(`{"type":"result","subtype":"success","session_id":"background-session","result":"background work finished"}`)+}++func TestCursorResultWithoutMessageConsumer(t *testing.T) {+ backend, err := New("cursor", Config{ExecutablePath: os.Args[0], Logger: slog.Default(), Env: map[string]string{cursorFakeModeEnv: "burst"}})+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "overflow the optional transcript", ExecOptions{})+ if err != nil {+ t.Fatal(err)+ }+ select {+ case result := <-session.Result:+ if result.Status != "completed" || result.Output != "done" {+ t.Fatalf("result-only caller blocked: %+v", result)+ }+ case <-ctx.Done():+ t.Fatal("Result depended on draining Messages")+ }+ count, _ := session.ToolActivity()+ if count == 0 {+ return+ }+ t.Fatalf("dropped transcript corrupted tool accounting: %d", count)+}++func TestCursorBackgroundLifecycle(t *testing.T) {+ if runtime.GOOS != "windows" && runtime.GOOS != "linux" && runtime.GOOS != "darwin" {+ t.Skip("background process ownership is unavailable on this platform")+ }+ for _, mode := range []string{"natural", "budget", "multiple", "finish", "cancel"} {+ t.Run(mode, func(t *testing.T) {+ self, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ duration := "30s"+ if mode == "natural" {+ duration = "800ms"+ }+ backend, err := New("cursor", Config{ExecutablePath: self, Logger: slog.Default(), Env: map[string]string{+ cursorFakeModeEnv: mode, "CURSOR_FAKE_DIR": dir, "CURSOR_FAKE_DURATION": duration, "CURSOR_FAKE_SETSID": "1",+ }})+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "test background lifecycle", ExecOptions{})+ if err != nil {+ t.Fatal(err)+ }+ ready := make(chan struct{})+ done := make(chan struct{})+ var messages []Message+ go func() {+ defer close(done)+ for msg := range session.Messages {+ messages = append(messages, msg)+ if msg.Type == MessageThinking && msg.Content == "ready" {+ close(ready)+ }+ }+ }()+ select {+ case <-ready:+ case <-ctx.Done():+ t.Fatal("fake never reached background observation")+ }+ switch mode {+ case "budget", "multiple":+ if !session.InterruptBackgroundTools() {+ t.Fatal("tool budget did not clean up owned background processes")+ }+ if session.InterruptBackgroundTools() {+ t.Fatal("completed tools granted a second recovery window")+ }+ case "cancel":+ cancel()+ case "natural":+ // A silent job must retain its tool boundary until natural exit.+ select {+ case result := <-session.Result:+ t.Fatalf("background job ended early: %+v", result)+ case <-time.After(150 * time.Millisecond):+ }+ }+ var result Result+ select {+ case result = <-session.Result:+ case <-time.After(10 * time.Second):+ t.Fatal("Cursor did not finalize")+ }+ <-done+ wantStatus := "completed"+ if mode == "cancel" {+ wantStatus = "aborted"+ }+ if result.Status != wantStatus {+ t.Fatalf("status=%q error=%q, want %s", result.Status, result.Error, wantStatus)+ }+ if mode != "cancel" && (result.Output != "background work finished" || result.SessionID != "background-session") {+ t.Fatalf("authoritative result lost: %+v", result)+ }+ started, completed := 0, 0+ for _, msg := range messages {+ switch msg.Type {+ case MessageToolUse:+ started+++ case MessageToolResult:+ completed+++ var raw struct {+ IsBackground bool `json:"isBackground"`+ }+ if json.Unmarshal([]byte(msg.Output), &raw) != nil || !raw.IsBackground {+ t.Fatalf("raw tool result lost: %q", msg.Output)+ }+ }+ }+ if mode != "cancel" && (started == 0 || started != completed) {+ t.Fatalf("unbalanced lifecycle: started=%d completed=%d", started, completed)+ }+ files, _ := filepath.Glob(filepath.Join(dir, "*.json"))+ for _, file := range files {+ data, err := os.ReadFile(file)+ if err != nil {+ t.Fatal(err)+ }+ var pids []int+ if err := json.Unmarshal(data, &pids); err != nil {+ t.Fatal(err)+ }+ for _, pid := range pids {+ assertCursorTestProcessGone(t, pid)+ }+ }+ })+ }+}++func TestCursorBackgroundUnverifiedPIDReturnsToIdleBudget(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ messages := make(chan Message, 1)+ tracker := newCursorBackgroundTools(ctx, nil, messages, slog.Default())+ defer tracker.Close()+ tracker.Send(Message{Type: MessageToolUse, Tool: "shell", CallID: "unverified"})+ <-messages+ call := cursorToolCall{Name: "shell", CallID: "unverified", Background: true, PID: -1, Result: `{"isBackground":true}`}+ tracker.Add(call)+ tracker.Reap()+ if tracker.Interrupt() {+ t.Fatal("unverified PID granted a cleanup recovery window")+ }+ if count, _ := tracker.Activity(); count != 0 || len(messages) != 1 {+ t.Fatalf("uncaptured launch did not release its result: count=%d messages=%d", count, len(messages))+ }+ if msg := <-messages; msg.Output != call.Result {+ t.Fatalf("raw launch result lost: %+v", msg)+ }+ tracker.Close()+ if tracker.Interrupt() || len(messages) != 0 {+ t.Fatal("closed tracker granted recovery or duplicated the launch result")+ }+}++func TestCursorBackgroundPIDParsing(t *testing.T) {+ for _, tc := range []struct {+ result string+ background bool+ pid int+ }{+ {`{"isBackground":true,"success":{"pid":42,"shellId":"s"}}`, true, 42},+ {`{"isBackground":true,"success":{"pid":"42"}}`, true, 0},+ {`{"isBackground":true}`, true, 0},+ {`{"isBackground":false,"success":{"pid":42}}`, false, 0},+ {`{"stdout":"isBackground: true pid:42"}`, false, 0},+ } {+ evt := cursorStreamEvent{CallID: "c", ToolCall: json.RawMessage(`{"shellToolCall":{"result":` + tc.result + `}}`)}+ call := parseCursorToolCall(&evt)+ if call.PID != tc.pid || call.Background != tc.background || call.Result != tc.result {+ t.Fatalf("parse %s: %+v", tc.result, call)+ }+ }+}+func TestCursorBackgroundOutputTextCannotFakeLifecycleIsStructural(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ event string+ wantName string+ wantBackground bool+ wantResult string+ }{+ {+ name: "root boolean true is the observation",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c1",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},"result":{"success":{"exitCode":0},"isBackground":true},"toolCallId":"c1"}}}`,+ wantName: "shell",+ wantBackground: true,+ wantResult: `{"success":{"exitCode":0},"isBackground":true}`,+ },+ {+ name: "isBackground on another tool is not a launched shell",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c9",` ++ `"tool_call":{"readToolCall":{"args":{"path":"server.log"},` ++ `"result":{"content":"ok","isBackground":true},"toolCallId":"c9"}}}`,+ wantName: "read",+ wantResult: `{"content":"ok","isBackground":true}`,+ },+ {+ name: "explicit false is foreground",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c2",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"ls"},"result":{"success":{"exitCode":0},"isBackground":false},"toolCallId":"c2"}}}`,+ wantName: "shell",+ wantResult: `{"success":{"exitCode":0},"isBackground":false}`,+ },+ {+ name: "isBackground only inside captured stdout is not an observation",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c3",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"grep -r isBackground ."},` ++ `"result":{"stdout":"{\"isBackground\":true}","exitCode":0},"toolCallId":"c3"}}}`,+ wantName: "shell",+ wantResult: `{"stdout":"{\"isBackground\":true}","exitCode":0}`,+ },+ {+ name: "a nested isBackground is not a root field",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c4",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},` ++ `"result":{"meta":{"isBackground":true},"exitCode":0},"toolCallId":"c4"}}}`,+ wantName: "shell",+ wantResult: `{"meta":{"isBackground":true},"exitCode":0}`,+ },+ {+ name: "a string where the boolean belongs is not an observation",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c5",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},` ++ `"result":{"isBackground":"true"},"toolCallId":"c5"}}}`,+ wantName: "shell",+ wantResult: `{"isBackground":"true"}`,+ },+ {+ name: "non-object result is not an observation",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c6",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},"result":[{"isBackground":true}],"toolCallId":"c6"}}}`,+ wantName: "shell",+ wantResult: `[{"isBackground":true}]`,+ },+ {+ name: "missing result stays foreground",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c7",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},"toolCallId":"c7"}}}`,+ wantName: "shell",+ },+ {+ name: "null result stays foreground",+ event: `{"type":"tool_call","subtype":"completed","call_id":"c8",` ++ `"tool_call":{"shellToolCall":{"args":{"command":"serve"},"result":null,"toolCallId":"c8"}}}`,+ wantName: "shell",+ wantResult: `null`,+ },+ }++ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()++ var evt cursorStreamEvent+ if err := json.Unmarshal([]byte(tt.event), &evt); err != nil {+ t.Fatalf("unmarshal event: %v", err)+ }+ call := parseCursorToolCall(&evt)+ if call.Background != tt.wantBackground {+ t.Errorf("Background = %v, want %v", call.Background, tt.wantBackground)+ }+ if call.Result != tt.wantResult {+ t.Errorf("Result = %q, want %q (raw result must be preserved verbatim)", call.Result, tt.wantResult)+ }+ if call.Name != tt.wantName || call.CallID == "" {+ t.Errorf("tool identity lost: name=%q want %q, callID=%q", call.Name, tt.wantName, call.CallID)+ }+ })+ }+}diff --git a/server/pkg/agent/cursor_test.go b/server/pkg/agent/cursor_test.goindex c9be588656..dfc8a18400 100644--- a/server/pkg/agent/cursor_test.go+++ b/server/pkg/agent/cursor_test.go@@ -192,7 +192,7 @@ func TestCursorHandleAssistantText(t *testing.T) {}),}- b.handleCursorAssistant(evt, ch, &output)+ b.handleCursorAssistant(evt, func(msg Message) { ch <- msg }, &output)if output.String() != "Hello from Cursor" {t.Fatalf("expected output 'Hello from Cursor', got %q", output.String())@@ -229,7 +229,7 @@ func TestCursorHandleAssistantToolUse(t *testing.T) {}),}- b.handleCursorAssistant(evt, ch, &output)+ b.handleCursorAssistant(evt, func(msg Message) { ch <- msg }, &output)select {case m := <-ch:@@ -421,7 +421,7 @@ func TestCursorUsageOnlyFromResult(t *testing.T) {}),}- b.handleCursorAssistant(evt, ch, &output)+ b.handleCursorAssistant(evt, func(msg Message) { ch <- msg }, &output)if output.String() != "hello" {t.Fatalf("expected 'hello', got %q", output.String())