Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8686 fix(daemon): reclaim build caches from idle chats (#10038)
Frezc9c0967a0db82
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 4e94291eff..cdae2118f8 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -357,14 +357,14 @@ Daemon behavior is configured via flags or environment variables:#### Workspace garbage collection-The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and applies several disk-reclamation policies:+The daemon periodically scans `MULTICA_WORKSPACES_ROOT` for cleanup. The active-directory guard uses the resolved path so a symlink or Windows junction and its target share the same guard.- **Full task cleanup** — when an issue's status is `done` or `cancelled` and has been idle for `MULTICA_GC_TTL`, the entire task directory is removed.- **Completed-task retention bound** — `MULTICA_GC_COMPLETED_TASK_TTL` fully removes an inactive issue task once its `.gc_meta.json` `completed_at` age exceeds the configured duration, even while the parent issue remains open. Cleanup waits for a successful parent-issue status check, never removes an active environment, and never fully removes a `local_directory` environment. A later rerun provisions a fresh environment instead of resuming the removed checkout.- The default depends on where the daemon points: `14d` against Multica Cloud, and `0` (disabled, retain indefinitely) for self-host and every other origin — including cloud staging and previews. Set the variable to opt in or out on either side; an explicit `0` disables the policy on Cloud too.- Removing an environment discards work an agent left uncommitted or unpushed on its branch, along with that task's `output/` and `logs/`. The per-issue Codex session store lives outside `MULTICA_WORKSPACES_ROOT` under its own TTL, so a later rerun still resumes the agent's prior session — it just starts from a fresh checkout. Size the TTL against that trade, and keep it comfortably above `MULTICA_GC_INTERVAL`: the active-root guard protects a task that is currently running, not one whose follow-up run is queued but unclaimed.- **Orphan cleanup** — task directories with no `.gc_meta.json` (e.g. left over from a daemon crash) are removed once they exceed `MULTICA_GC_ORPHAN_TTL`.-- **Artifact-only cleanup** — when a task has been completed for at least `MULTICA_GC_ARTIFACT_TTL` but the issue is still open, regenerable build outputs whose directory basename matches `MULTICA_GC_ARTIFACT_PATTERNS` are removed. The daemon also reclaims the exact managed path `codex-home/.sandbox-bin`; old task metadata without `completed_at` becomes eligible for this managed-only cleanup after its `.gc_meta.json` file has been idle for `MULTICA_GC_ORPHAN_TTL`. The rest of the task (source, `.git`, `output/`, `logs/`, `.gc_meta.json`, Codex auth/config/session state) is preserved so the agent can resume it.+- **Artifact-only cleanup** — when a task has been completed for at least `MULTICA_GC_ARTIFACT_TTL` but the issue is still open, regenerable build outputs whose directory basename matches `MULTICA_GC_ARTIFACT_PATTERNS` are removed. The daemon also reclaims the exact managed path `codex-home/.sandbox-bin`; old task metadata without `completed_at` becomes eligible for this managed-only cleanup after its `.gc_meta.json` file has been idle for `MULTICA_GC_ORPHAN_TTL`. The rest of the task (source, `.git`, `output/`, `logs/`, `.gc_meta.json`, Codex auth/config/session state) is preserved so the agent can resume it. The same basename patterns apply to unarchived chats that use a daemon-managed work directory once the chat status check succeeds and the last run has been complete for `MULTICA_GC_ARTIFACT_TTL`. After a successful cleanup, the daemon skips repeat scans for that run. A later completed run becomes eligible again after the same delay.- **Managed-cache reclamation** — the exact managed path above is reclaimed for *every* task kind once the task has been completed for `MULTICA_GC_ARTIFACT_TTL`, not just for issue tasks whose issue is still open. It applies even while the parent record says the directory itself must stay — an active chat session, a still-running autopilot run — and even when the parent record could not be reached this cycle, because the contents are regenerable and the next run re-provisions them on demand. A task currently running on the directory is never touched. Set `MULTICA_GC_ARTIFACT_TTL=0` to disable this along with the rest of artifact cleanup.- **Repo cache eviction** — the bare git clones under `.repos/` are shared object stores: each task workdir is a `git worktree` off one of them rather than its own clone, so a task's `.git` is only a pointer file. They are evicted only when all of the following hold: the repo is no longer attached to any workspace this daemon watches, it has no worktrees left, and no task has created a worktree from it for `MULTICA_GC_REPO_TTL`. A cache created before this stamp existed is not treated as ancient — its clock starts at the first GC cycle that sees it, so upgrading does not wipe every cache. Evicting is safe by construction: the next task that needs the repo re-clones it on demand, so a wrong eviction costs a clone, not a failure.diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex 13ad513831..921ca8b89b 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -147,6 +147,8 @@ Chaque exécution a un répertoire sous la racine des espaces de travail (par dTant que la tâche reste ouverte, 12 heures après la fin d'une exécution, seul le contenu régénérable est supprimé : les répertoires `node_modules`, `.next` et `.turbo`, ainsi que le cache que le daemon prépare pour Codex. Le reste est conservé. Un daemon connecté à Multica Cloud supprime aussi le répertoire entier 14 jours après la fin de l'exécution, que la tâche soit fermée ou non ; les daemons auto-hébergés ne le font pas par défaut.+Pour un chat non archivé qui utilise un répertoire de travail géré par Multica, le daemon applique le même nettoyage du contenu régénérable, par défaut 12 heures après la fin de la dernière exécution. Le daemon mémorise le nettoyage réussi et évite les parcours répétés pour cette exécution. Une exécution ultérieure devient éligible après le même délai. Si le chat s'exécute directement dans le répertoire local d'un projet, ce nettoyage se limite au cache `codex-home/.sandbox-bin` du daemon dans le répertoire de suivi de l'exécution.+Une exécution sur le répertoire local d'un projet travaille dans votre propre répertoire, auquel le daemon ne touche jamais. Le répertoire de suivi que Multica crée pour cette exécution (journaux, etc.) est conservé lui aussi ; seuls les caches régénérables qu'il contient sont nettoyés.### Cache de dépôts partagédiff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 7ffd016390..09979006d6 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -147,6 +147,8 @@ CodeBuddy、Kimi CLI、Pi は起動時に自分でユーザーレベルの設定タスクがまだ閉じていない場合、実行完了から 12 時間後に再生成できる内容だけを削除します。対象は `node_modules`、`.next`、`.turbo` ディレクトリと、デーモンが Codex 用に用意したキャッシュで、ほかは残ります。Multica Cloud に接続したデーモンは、タスクが閉じているかどうかにかかわらず、実行完了から 14 日後にディレクトリ全体も削除します。セルフホストでは既定でこれを行いません。+Multica が管理する作業ディレクトリを使う未アーカイブのチャットでは、既定で最後の実行が終わってから 12 時間後に、同じルールで再生成できる内容を削除します。クリーンアップに成功した実行については、デーモンは繰り返しスキャンを省きます。新しい実行が完了すると、同じ待ち時間を経て再び対象になります。チャットをプロジェクトのローカルディレクトリで直接実行した場合は、実行の記録ディレクトリにあるデーモンの `codex-home/.sandbox-bin` キャッシュだけがこのクリーンアップの対象です。+プロジェクトのローカルディレクトリでの実行は、あなた自身のディレクトリで作業し、デーモンはそこに触れません。Multica がその実行用に作る記録ディレクトリ(ログなど)も残り、中の再生成できるキャッシュだけが片付けられます。### 共有のリポジトリキャッシュdiff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex a9dc74b5c7..ab25413c60 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -147,6 +147,8 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽태스크가 아직 닫히지 않았다면 실행 완료 12시간 뒤에 다시 만들 수 있는 내용만 지웁니다. 대상은 `node_modules`, `.next`, `.turbo` 디렉터리와 데몬이 Codex용으로 준비한 캐시이며 나머지는 남습니다. Multica Cloud에 연결된 데몬은 태스크가 닫혔는지와 관계없이 실행 완료 14일 뒤에 디렉터리 전체도 삭제합니다. 셀프 호스팅에서는 기본적으로 이 단계를 하지 않습니다.+보관하지 않은 채팅이 Multica에서 관리하는 작업 디렉터리를 사용하면, 기본적으로 마지막 실행이 끝나고 12시간 뒤에 같은 규칙으로 다시 만들 수 있는 내용을 정리합니다. 정리에 성공하면 데몬은 해당 실행의 반복 스캔을 건너뜁니다. 이후 실행이 끝나면 같은 시간이 지난 뒤 다시 정리 대상이 됩니다. 채팅을 프로젝트의 로컬 디렉터리에서 직접 실행한 경우에는 실행 기록 디렉터리 안에 있는 데몬의 `codex-home/.sandbox-bin` 캐시만 이 정리의 대상입니다.+프로젝트 로컬 디렉터리에서의 실행은 사용자 자신의 디렉터리에서 작업하며 데몬은 그 디렉터리를 건드리지 않습니다. Multica가 그 실행을 위해 따로 만드는 기록 디렉터리(로그 등)도 유지되고, 그 안의 다시 만들 수 있는 캐시만 정리됩니다.### 공유 저장소 캐시diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex ae79500408..1628421102 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -147,6 +147,8 @@ Each run gets a directory under the workspaces root (default `~/multica_workspacWhile the issue is still open, 12 hours after a run completes only regenerable content is removed: `node_modules`, `.next`, and `.turbo` directories, plus the cache the daemon prepares for Codex. Everything else stays. A daemon connected to Multica Cloud also removes the whole directory 14 days after the run completes, whether or not the issue is closed; self-hosted daemons do not do this by default.+For an unarchived chat in a work directory managed by Multica, the daemon applies the same regenerable content cleanup 12 hours after its last run ends by default. After a successful cleanup, the daemon skips repeat scans for that run. A later completed run becomes eligible again after the same delay. When a chat runs directly in a project's local directory, this cleanup is limited to the daemon's `codex-home/.sandbox-bin` cache in the run's record directory.+A run on a project's local directory works in your own directory, which the daemon never touches. The record directory Multica creates for that run (logs and so on) is kept too; only regenerable caches inside it are cleaned.### Shared repository cachediff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex e3e3fe144f..b5d3b727d9 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -148,6 +148,8 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與任務仍未關閉時,執行完成 12 小時後只刪可以重新生成的內容:目錄中的 `node_modules`、`.next`、`.turbo`,以及守護程序為 Codex 準備的快取,其餘保留。連線 Multica Cloud 的守護程序還會在執行完成 14 天後刪除整個目錄,不論任務是否關閉;自託管預設不做這一步。+未歸檔的聊天如果使用 Multica 管理的工作目錄,守護程序預設會在最後一次執行結束 12 小時後,按同樣的規則清理可重新生成的內容。清理成功後,守護程序會略過該次執行的重複掃描。後續執行結束並經過相同的等待時間後,就會再次符合清理條件。聊天直接在專案本地目錄執行時,這項清理只處理執行記錄目錄中的 `codex-home/.sandbox-bin` 快取。+專案本地目錄上的執行直接改你自己的目錄,守護程序不會動它;Multica 為這次執行另建的記錄目錄(日誌等)也會保留,只清理其中可再生成的快取。### 共享的倉庫快取diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 5e8b014496..13710effbd 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -148,6 +148,8 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul任务仍未关闭时,运行完成 12 小时后只删可以重新生成的内容:目录中的 `node_modules`、`.next`、`.turbo`,以及守护进程为 Codex 准备的缓存,其余保留。连接 Multica Cloud 的守护进程还会在运行完成 14 天后删除整个目录,不论任务是否关闭;自托管默认不做这一步。+未归档的聊天如果使用 Multica 管理的工作目录,守护进程默认会在最后一次运行结束 12 小时后按同样的规则清理可重新生成的内容。清理成功后,守护进程会跳过该次运行的重复扫描。后续运行结束后,经过同样的等待时间便可再次清理。聊天直接在项目本地目录中运行时,这项清理只针对运行记录目录中的 `codex-home/.sandbox-bin` 缓存。+项目本地目录上的运行直接改你自己的目录,守护进程不会动它;Multica 为这次运行另建的记录目录(日志等)也会保留,只清理其中可再生成的缓存。### 共享的仓库缓存diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex 8c8ea21916..d9e67e1138 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -272,7 +272,7 @@ Le daemon nettoie régulièrement les répertoires des exécutions, les caches d| `MULTICA_GC_TTL` | `24h` | Délai après lequel les répertoires d'exécution sont supprimés une fois la tâche passée dans la catégorie `done` ou `closed`, ou la session de chat archivée || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud `14d` ; auto-hébergé `0` | Délai après la fin d'une exécution de tâche au bout duquel tout son répertoire est supprimé, que la tâche soit fermée ou non ; `0` désactive. Ne s'applique pas aux exécutions sur le répertoire local d'un projet || `MULTICA_GC_ORPHAN_TTL` | `72h` | Durée sans modification après laquelle un répertoire sans propriétaire identifié est supprimé |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | Délai après la fin d'une exécution au bout duquel le contenu régénérable est supprimé (les répertoires de la ligne suivante et le cache que le daemon prépare pour Codex) ; `0` le conserve |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | Délai entre la fin d'une exécution et le nettoyage du contenu régénérable. Les règles de la ligne suivante s'appliquent aux tâches ouvertes et aux chats non archivés qui utilisent un répertoire de travail géré. Le même délai s'applique au cache Codex géré par le daemon. `0` conserve ces caches || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | Noms de répertoires considérés comme régénérables, séparés par des virgules. La définir **remplace** la liste par défaut : ajoutez les valeurs par défaut si vous voulez les garder. Les entrées contenant `/` ou `\` sont ignorées || `MULTICA_GC_REPO_TTL` | `30d` | Durée sans checkout après laquelle un cache de dépôt nu qui n'est plus référencé et n'a plus de worktree est supprimé ; `0` le conserve || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | Exécuter ou non `git reflog expire` et `git gc` sur un cache de dépôt après la suppression des branches d'agent périmées ; `false` désactive seulement cette étape |diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 7732d6a11c..05a74dcdae 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -275,7 +275,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_GC_TTL` | `24h` | タスクが `done` または `closed` カテゴリに入ってから、またはチャットセッションがアーカイブされてから、実行ディレクトリを削除するまでの時間 || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud は `14d`、セルフホストは `0` | タスクの実行が完了してからディレクトリ全体を削除するまでの時間。タスクが閉じているかどうかは問わない。`0` で無効。プロジェクトのローカルディレクトリでの実行には適用されない || `MULTICA_GC_ORPHAN_TTL` | `72h` | 持ち主が見つからないディレクトリを、変更がないまま何時間経ったら削除するか |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 実行完了後、再生成できる内容(次の行のディレクトリと、デーモンが Codex 用に用意するキャッシュ)を削除するまでの時間。`0` で削除しない |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 実行終了からデーモンが再生成できる内容を削除するまでの時間。次の行のパターンは、まだ閉じていないタスクと、管理対象の作業ディレクトリを使う未アーカイブのチャットに適用される。デーモンが管理する Codex キャッシュにも同じ時間が適用される。`0` でこれらのキャッシュを保持する || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 再生成できるとみなすディレクトリ名(カンマ区切り)。設定するとデフォルトの一覧を**置き換える**ため、デフォルトも残したいなら一緒に書く。`/` や `\` を含む項目は無視される || `MULTICA_GC_REPO_TTL` | `30d` | どこからも参照されず worktree も残っていないベアリポジトリキャッシュを、チェックアウトがないまま何日経ったら削除するか。`0` で削除しない || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | 古いエージェントブランチを消したあと、リポジトリキャッシュに `git reflog expire` と `git gc` を実行するか。`false` でこの手順だけを止める |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 024a2ea5d8..af4d60378c 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -275,7 +275,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_GC_TTL` | `24h` | 태스크가 `done` 또는 `closed` 분류에 들어가거나 채팅 세션이 보관된 뒤, 실행 디렉터리를 삭제하기까지의 시간 || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud `14d`, 셀프 호스팅 `0` | 태스크 실행이 완료된 뒤 디렉터리 전체를 삭제하기까지의 시간. 태스크가 닫혔는지와 관계없음. `0`이면 끔. 프로젝트 로컬 디렉터리에서의 실행에는 적용되지 않음 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 소속을 찾을 수 없는 디렉터리가 변경 없이 얼마나 지나면 삭제할지 |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 실행 완료 후 다시 만들 수 있는 내용(다음 행의 디렉터리와 데몬이 Codex용으로 준비하는 캐시)을 삭제하기까지의 시간. `0`이면 삭제하지 않음 |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 실행이 끝난 뒤 데몬이 다시 만들 수 있는 내용을 정리하기까지의 시간. 다음 행의 패턴은 열린 태스크와 관리되는 작업 디렉터리를 쓰는 미보관 채팅에 적용됨. 데몬이 관리하는 Codex 캐시에도 같은 시간이 적용됨. `0`이면 이 캐시를 유지함 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 다시 만들 수 있다고 보는 디렉터리 이름(쉼표로 구분). 설정하면 기본 목록을 **대체**하므로 기본 항목도 유지하려면 함께 적어야 함. `/`나 `\`가 들어간 항목은 무시됨 || `MULTICA_GC_REPO_TTL` | `30d` | 더 이상 참조되지 않고 worktree도 없는 bare 저장소 캐시를, 체크아웃 없이 얼마나 지나면 삭제할지. `0`이면 삭제하지 않음 || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | 오래된 에이전트 브랜치를 지운 뒤 저장소 캐시에 `git reflog expire`와 `git gc`를 실행할지. `false`면 이 단계만 끔 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex e5e9ffa618..9cd36bae15 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -281,7 +281,7 @@ The daemon periodically cleans up run directories, repository caches, session re| `MULTICA_GC_TTL` | `24h` | How long after an issue enters the `done` or `closed` category, or a chat session is archived, its run directories are removed || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud `14d`; self-hosted `0` | How long after an issue run completes its whole directory is removed, whether or not the issue is closed; `0` turns this off. Does not apply to runs on a project's local directory || `MULTICA_GC_ORPHAN_TTL` | `72h` | How long a directory with no owner found must go unchanged before it is removed |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | How long after a run completes regenerable content is removed (the directories in the next row plus the cache the daemon prepares for Codex); `0` keeps it |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | How long after a run ends before the daemon cleans regenerable content. The patterns in the next row apply to open issues and to unarchived chats with managed work directories. The same duration applies to the daemon-managed Codex cache. `0` keeps these caches || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | Directory names treated as regenerable, comma-separated. Setting it **replaces** the default list, so include the defaults if you still want them; entries containing `/` or `\` are ignored || `MULTICA_GC_REPO_TTL` | `30d` | How long a bare repository cache that is no longer referenced and has no worktrees must go without a checkout before it is removed; `0` keeps it || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | Whether to run `git reflog expire` and `git gc` on a repository cache after stale agent branches are removed; `false` turns off only this step |diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdxindex 41bf674de5..b18c41d872 100644--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx@@ -271,7 +271,7 @@ API key 與 base URL 都為空時,這一層關閉,不會發出任何上游| `MULTICA_GC_TTL` | `24h` | 任務進入 `done` 或 `closed` 分類、或聊天會話歸檔後,再過多久刪除對應執行目錄 || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud `14d`;自託管 `0` | 任務執行完成多久後刪除整個目錄,不論任務是否關閉;`0` 表示關閉。不作用於專案本地目錄上的執行 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 找不到歸屬的目錄多久沒有改動後刪除 |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 執行完成多久後刪除可再生成的內容(下一行的目錄和守護程序為 Codex 準備的快取);`0` 表示不刪 |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 從執行結束到守護程序清理可重新生成內容的時間。下一行的目錄名稱規則適用於未關閉的任務,以及使用受管理工作目錄的未歸檔聊天。守護程序管理的 Codex 快取也適用相同時長。設為 `0` 可保留這些快取 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 按目錄名匹配的可再生成內容,逗號分隔。設定後**替換**預設列表,要保留預設項就一併寫上;含 `/` 或 `\` 的項會被忽略 || `MULTICA_GC_REPO_TTL` | `30d` | 不再被引用、也沒有 worktree 的裸倉庫快取,多久沒有檢出後刪除;`0` 表示不刪 || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | 刪掉過期的 AI 代理分支後,是否對倉庫快取執行 `git reflog expire` 和 `git gc`;設為 `false` 只關掉這一步 |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex ca0243b468..afa7862d57 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -275,7 +275,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_GC_TTL` | `24h` | 任务进入 `done` 或 `closed` 分类、或聊天会话归档后,再过多久删除对应运行目录 || `MULTICA_GC_COMPLETED_TASK_TTL` | Multica Cloud `14d`;自托管 `0` | 任务运行完成多久后删除整个目录,不论任务是否关闭;`0` 表示关闭。不作用于项目本地目录上的运行 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 找不到归属的目录多久没有改动后删除 |-| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 运行完成多久后删除可再生成的内容(下一行的目录和守护进程为 Codex 准备的缓存);`0` 表示不删 |+| `MULTICA_GC_ARTIFACT_TTL` | `12h` | 从运行结束到守护进程清理可重新生成内容的时间。下一行的目录名规则适用于未关闭的任务,以及使用托管工作目录的未归档聊天。守护进程管理的 Codex 缓存也适用相同时长。设为 `0` 可保留这些缓存 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 按目录名匹配的可再生成内容,逗号分隔。设置后**替换**默认列表,要保留默认项就一并写上;含 `/` 或 `\` 的项会被忽略 || `MULTICA_GC_REPO_TTL` | `30d` | 不再被引用、也没有 worktree 的裸仓库缓存,多久没有检出后删除;`0` 表示不删 || `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` | 删掉过期的智能体分支后,是否对仓库缓存运行 `git reflog expire` 和 `git gc`;设为 `false` 只关掉这一步 |diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex a3f23cd195..f7c233548a 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -696,7 +696,7 @@ type Daemon struct {activeEnvRootsMu sync.MutexactiveEnvRootsCond *sync.Cond // signalled when an in-flight env-root GC mutation finishes- activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)+ activeEnvRoots map[string]int // env root guard key -> reference count (handles reuse paths marked twice)deletingEnvRoots map[string]bool // env roots reserved by GC; new tasks wait until the mutation finishesactiveStoresMu sync.Mutex@@ -5772,13 +5772,11 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {taskLog.Error("resolve stable task env root", "error", resolveRootErr)}if resolvedEnvRoot != "" {- d.markActiveEnvRoot(resolvedEnvRoot)- defer d.unmarkActiveEnvRoot(resolvedEnvRoot)+ defer d.markActiveEnvRoot(resolvedEnvRoot)()}if task.PriorWorkDir != "" {if priorRoot := filepath.Dir(task.PriorWorkDir); priorRoot != "" && priorRoot != resolvedEnvRoot {- d.markActiveEnvRoot(priorRoot)- defer d.unmarkActiveEnvRoot(priorRoot)+ defer d.markActiveEnvRoot(priorRoot)()}}@@ -8033,18 +8031,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif err != nil {return TaskResult{}, fmt.Errorf("resolve stable task env root: %w", err)}- d.markActiveEnvRoot(resolvedRoot)- defer d.unmarkActiveEnvRoot(resolvedRoot)+ defer d.markActiveEnvRoot(resolvedRoot)()if task.PriorWorkDir != "" {priorRoot := filepath.Dir(task.PriorWorkDir)if priorRoot != resolvedRoot {- d.markActiveEnvRoot(priorRoot)- defer d.unmarkActiveEnvRoot(priorRoot)+ defer d.markActiveEnvRoot(priorRoot)()}}// Claim the env root HERE, in the daemon parent, and hold it for the whole- // task run — the same lifetime as unmarkActiveEnvRoot above.+ // task run, for the same lifetime as the active guard above.//// It cannot be claimed inside preparation: production preparation runs in a// short-lived helper process (prepareExecutionEnvironment ->@@ -8443,8 +8439,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Belt-and-suspenders: also mark whatever root we ended up with, in case// future changes diverge from ResolveRootDir.if env.RootDir != resolvedRoot && env.RootDir != "" {- d.markActiveEnvRoot(env.RootDir)- defer d.unmarkActiveEnvRoot(env.RootDir)+ defer d.markActiveEnvRoot(env.RootDir)()}// Finalize the worktree on EVERY exit path, success or failure: commit// whatever the agent left uncommitted, then unregister the worktree from@@ -10558,42 +10553,58 @@ func convertProjectResourcesForEnv(resources []ProjectResourceData) []execenv.Prreturn result}-// markActiveEnvRoot records that a task is currently using the given env root,-// so the GC loop won't reclaim its artifacts mid-execution. Calls are-// reference-counted so a reuse path marked twice (predicted + prior) only-// becomes inactive after both unmark calls.-func (d *Daemon) markActiveEnvRoot(envRoot string) {- if envRoot == "" {- return- }- d.activeEnvRootsMu.Lock()- defer d.activeEnvRootsMu.Unlock()- d.ensureActiveEnvRootStateLocked()- for d.deletingEnvRoots[envRoot] {- d.activeEnvRootsCond.Wait()+// envRootGuardKey gives a reused root and the path GC scans through the+// configured workspaces root the same identity, even before a new task root+// has been created. The key is used only for locking, never as a deletion path.+func envRootGuardKey(envRoot string) (string, error) {+ key, err := util.ResolveSymlinksBestEffort(envRoot)+ if runtime.GOOS == "windows" {+ // A junction can spell the target with different casing.+ key = strings.ToLower(key)}- d.activeEnvRoots[envRoot]+++ return key, err}-func (d *Daemon) unmarkActiveEnvRoot(envRoot string) {- if envRoot == "" {- return+// markActiveEnvRoot protects a root until the returned function is called.+// The release uses the original key even if a link is moved in the meantime.+func (d *Daemon) markActiveEnvRoot(envRoot string) (release func()) {+ key, err := envRootGuardKey(envRoot)+ if err != nil {+ // Keep the original guard for this path. GC skips paths whose+ // identity it cannot resolve.+ key = filepath.Clean(envRoot)+ }+ if key == "" {+ return func() {}}d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()d.ensureActiveEnvRootStateLocked()- if d.activeEnvRoots[envRoot] <= 1 {- delete(d.activeEnvRoots, envRoot)- return+ for d.deletingEnvRoots[key] {+ d.activeEnvRootsCond.Wait()+ }+ d.activeEnvRoots[key]++++ return func() {+ d.activeEnvRootsMu.Lock()+ defer d.activeEnvRootsMu.Unlock()+ if d.activeEnvRoots[key] <= 1 {+ delete(d.activeEnvRoots, key)+ return+ }+ d.activeEnvRoots[key]--}- d.activeEnvRoots[envRoot]--}func (d *Daemon) isActiveEnvRoot(envRoot string) bool {+ key, err := envRootGuardKey(envRoot)+ if err != nil {+ return true+ }d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()d.ensureActiveEnvRootStateLocked()- return d.activeEnvRoots[envRoot] > 0+ return d.activeEnvRoots[key] > 0}func (d *Daemon) ensureActiveEnvRootStateLocked() {@@ -10614,19 +10625,20 @@ func (d *Daemon) ensureActiveEnvRootStateLocked() {// the active task and skips, or task startup waits for the mutation to finish// and recreates/uses the post-GC environment.func (d *Daemon) reserveEnvRootForGC(envRoot string) (release func(), ok bool) {- if envRoot == "" {+ key, err := envRootGuardKey(envRoot)+ if err != nil || key == "" {return nil, false}d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()d.ensureActiveEnvRootStateLocked()- if d.activeEnvRoots[envRoot] > 0 || d.deletingEnvRoots[envRoot] {+ if d.activeEnvRoots[key] > 0 || d.deletingEnvRoots[key] {return nil, false}- d.deletingEnvRoots[envRoot] = true+ d.deletingEnvRoots[key] = truereturn func() {d.activeEnvRootsMu.Lock()- delete(d.deletingEnvRoots, envRoot)+ delete(d.deletingEnvRoots, key)d.activeEnvRootsCond.Broadcast()d.activeEnvRootsMu.Unlock()}, truediff --git a/server/internal/daemon/env_root_guard_test.go b/server/internal/daemon/env_root_guard_test.gonew file mode 100644index 0000000000..5139914178--- /dev/null+++ b/server/internal/daemon/env_root_guard_test.go@@ -0,0 +1,118 @@+package daemon++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++func TestEnvRootGuardSharesSymlinkAliases(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ alias := filepath.Join(t.TempDir(), "alias")+ if err := os.Symlink(root, alias); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ assertEnvRootGuardSharesAliases(t, root, alias)+}++func TestGCSkipsActiveChatViaSymlinkedRoot(t *testing.T) {+ t.Parallel()+ const chatID = "aaaaaaaa-0000-0000-0000-000000000009"+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))+ root := d.cfg.WorkspacesRoot+ alias := filepath.Join(t.TempDir(), "alias")+ if err := os.Symlink(root, alias); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ d.cfg.WorkspacesRoot = alias+ taskDir := createTaskDir(t, root, "ws", "idle-chat", &execenv.GCMeta{+ Kind: execenv.GCKindChat,+ ChatSessionID: chatID,+ WorkspaceID: "ws",+ CompletedAt: time.Now().Add(-2 * d.cfg.GCArtifactTTL),+ })+ const cacheDir = "workdir/repo/node_modules"+ writeFile(t, filepath.Join(taskDir, cacheDir, "dependency", "index.js"), 32)++ // A continued run uses the real path persisted by the previous turn,+ // while the GC scans the configured root through the symlink.+ release := d.markActiveEnvRoot(taskDir)+ d.gcWorkspace(t.Context(), filepath.Join(alias, "ws"), &gcStats{})+ assertKept(t, taskDir, cacheDir)+ release()++ d.gcWorkspace(t.Context(), filepath.Join(alias, "ws"), &gcStats{})+ assertGone(t, taskDir, cacheDir)+}++func assertEnvRootGuardSharesAliases(t *testing.T, root, alias string) {+ t.Helper()+ d := &Daemon{}+ taskRoot := filepath.Join(root, "workspace", "task")+ aliasedTaskRoot := filepath.Join(alias, "workspace", "task")++ // A fresh run is marked before its predicted directory exists. GC sees+ // the same directory after preparation, possibly through the other path.+ releaseAlias := d.markActiveEnvRoot(aliasedTaskRoot)+ if err := os.MkdirAll(taskRoot, 0o755); err != nil {+ t.Fatal(err)+ }+ if !d.isActiveEnvRoot(taskRoot) {+ t.Fatal("a fresh directory lost its active mark when accessed through its real path")+ }+ releaseTask := d.markActiveEnvRoot(taskRoot)+ releaseAlias()+ if !d.isActiveEnvRoot(aliasedTaskRoot) {+ t.Fatal("the active mark on the real path did not protect the aliased path")+ }+ if release, ok := d.reserveEnvRootForGC(aliasedTaskRoot); ok {+ release()+ t.Fatal("GC reserved an alias of an active directory")+ }+ releaseTask()++ started := make(chan struct{})+ entered := make(chan func(), 1)+ func() {+ releaseGC, ok := d.reserveEnvRootForGC(aliasedTaskRoot)+ if !ok {+ t.Fatal("GC could not reserve the inactive directory through its alias")+ }+ defer releaseGC()+ if release, ok := d.reserveEnvRootForGC(taskRoot); ok {+ release()+ t.Fatal("GC reserved the same directory twice using different paths")+ }+ go func() {+ close(started)+ entered <- d.markActiveEnvRoot(taskRoot)+ }()+ <-started+ select {+ case release := <-entered:+ release()+ t.Fatal("a task entered through the real path while GC held the alias")+ case <-time.After(50 * time.Millisecond):+ }+ }()+ select {+ case release := <-entered:+ release()+ case <-time.After(5 * time.Second):+ t.Fatal("task could not enter after GC released the alias")+ }++ releaseAlias = d.markActiveEnvRoot(aliasedTaskRoot)+ if err := os.Remove(alias); err != nil {+ t.Fatal(err)+ }+ releaseAlias()+ if d.isActiveEnvRoot(taskRoot) {+ t.Fatal("removing the alias before release stranded the original directory's mark")+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 19efc2fc9c..c7f0a80a65 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -226,8 +226,8 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)continue}}- action := d.shouldCleanTaskDir(ctx, taskDir)- cleanedHere += d.applyGCAction(ctx, taskDir, action, stats)+ action, chatMeta := d.taskDirGCDecision(ctx, taskDir)+ cleanedHere += d.applyGCActionWithChatMeta(ctx, taskDir, action, stats, chatMeta)}workspaceIDs := make([]string, 0, len(issueCandidatesByWorkspace))for workspaceID := range issueCandidatesByWorkspace {@@ -322,6 +322,10 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand// atomically reserves the env root because a task can start while the server// reconciliation request is in flight.func (d *Daemon) applyGCAction(ctx context.Context, taskDir string, action gcAction, stats *gcStats) int {+ return d.applyGCActionWithChatMeta(ctx, taskDir, action, stats, nil)+}++func (d *Daemon) applyGCActionWithChatMeta(ctx context.Context, taskDir string, action gcAction, stats *gcStats, chatMeta *execenv.GCMeta) int {if action != gcActionSkip {if _, err := d.gcTaskDirOwner(taskDir); err != nil {d.logger.Warn("gc: refusing to mutate unowned task directory", "dir", taskDir, "error", err)@@ -365,6 +369,9 @@ func (d *Daemon) applyGCAction(ctx context.Context, taskDir string, action gcActremoved, bytes, perPattern := d.cleanTaskArtifacts(ctx, taskDir, d.cfg.GCArtifactPatterns)recordArtifactCleanup(stats, removed, bytes, perPattern)stats.skipped++ // task dir itself preserved+ case gcActionCleanChatArtifacts:+ d.cleanIdleChatArtifacts(ctx, taskDir, chatMeta, stats)+ stats.skipped++ // task dir itself preservedcase gcActionCleanManagedArtifacts:removed, bytes, perPattern := d.cleanManagedTaskArtifacts(taskDir)recordArtifactCleanup(stats, removed, bytes, perPattern)@@ -398,12 +405,18 @@ const (gcActionOrphan // no meta or unknown issue and dir is oldgcActionCleanArtifacts // task completed long enough ago; drop regenerable artifacts onlygcActionCleanManagedArtifacts // preserve the task and drop exact daemon-managed artifacts only+ gcActionCleanChatArtifacts // sweep an idle chat once per completed run and artifact policy)// shouldCleanTaskDir decides whether a task directory should be removed.// Dispatches on meta.Kind so chat / autopilot / quick-create tasks each// follow the parent record that actually governs their lifecycle.func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcAction {+ action, _ := d.taskDirGCDecision(ctx, taskDir)+ return action+}++func (d *Daemon) taskDirGCDecision(ctx context.Context, taskDir string) (gcAction, *execenv.GCMeta) {// A task currently running on this env root must never be reclaimed —// not even on the done/cancelled or orphan-404 paths. A re-dispatched or// still-running task can reuse the prior workdir of an already-done issue@@ -411,21 +424,21 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActio// updated_at), so the regular TTL check alone wouldn't notice the resumed// activity.if d.isActiveEnvRoot(taskDir) {- return gcActionSkip+ return gcActionSkip, nil}meta, err := execenv.ReadGCMeta(taskDir)if err != nil {if _, ownerErr := d.gcTaskDirOwner(taskDir); ownerErr != nil {d.logger.Warn("gc: skipping directory without valid task ownership", "dir", taskDir, "error", ownerErr)- return gcActionSkip+ return gcActionSkip, nil}- return d.orphanByMTime(taskDir, "no meta")+ return d.orphanByMTime(taskDir, "no meta"), nil}action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)action = d.applyLocalDirectoryGCOverride(meta, action)- return d.applyManagedArtifactFallback(taskDir, meta, action)+ return d.applyManagedArtifactFallback(taskDir, meta, action), meta}// applyManagedArtifactFallback upgrades a skip into managed-artifact cleanup@@ -733,18 +746,14 @@ func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *execeswitch status.Status {case "active":- // An active chat session's directory must never be reclaimed by mtime- // — that would silently kill a user's idle session and break- // "PriorWorkDir" resume on their next message.- //- // This protects the session's own data, not the daemon's regenerable- // caches. shouldCleanTaskDir layers applyManagedArtifactFallback on top- // of this skip, so a session idle past GCArtifactTTL gives back- // codex-home/.sandbox-bin and the next message re-provisions it. That- // costs a ~285 MiB Codex bootstrap on resume and is the same trade-off- // gcDecisionIssueResult already makes for a completed task whose issue- // is still open — without it an active session pins the cache forever- // (#6782).+ // Keep the workdir for the next message. In-place chats keep using+ // the exact daemon-managed cache fallback.+ if d.idleChatArtifactEligible(meta) {+ matcher := newArtifactMatcher(d.cfg.GCArtifactPatterns, execenv.ManagedReclaimableArtifactSubpaths())+ if !chatArtifactSweepRecorded(taskDir, chatArtifactSweepMarker(meta, matcher)) {+ return gcActionCleanChatArtifacts+ }+ }return gcActionSkipcase "archived":if time.Since(status.UpdatedAt) > d.cfg.GCTTL {@@ -1050,8 +1059,17 @@ func hasManagedArtifact(taskDir string) bool {}func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string, matcher artifactMatcher) (removed int, bytes int64, perPattern map[string]int) {+ removed, bytes, perPattern, _ = d.sweepTaskArtifacts(ctx, taskDir, matcher)+ return+}++func (d *Daemon) sweepTaskArtifacts(ctx context.Context, taskDir string, matcher artifactMatcher) (removed int, bytes int64, perPattern map[string]int, complete bool) {perPattern = map[string]int{}- if taskDir == "" || (len(matcher.basenames) == 0 && len(matcher.exactPaths) == 0) {+ if taskDir == "" || ctx.Err() != nil {+ return+ }+ if len(matcher.basenames) == 0 && len(matcher.exactPaths) == 0 {+ complete = truereturn}@@ -1060,11 +1078,13 @@ func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string,return}+ complete = truewalkErr := filepath.WalkDir(absRoot, func(path string, entry os.DirEntry, err error) error {if ctx.Err() != nil {return context.Cause(ctx)}if err != nil {+ complete = falsereturn nil // best-effort — keep walking}if path == absRoot {@@ -1082,6 +1102,7 @@ func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string,// Dir on some platforms; lstat to be sure.info, statErr := os.Lstat(path)if statErr != nil {+ complete = falsereturn nil}if info.Mode()&linkedDirModes != 0 {@@ -1101,6 +1122,7 @@ func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string,// Fail closed. A malformed or temporarily unreadable checkout is not// evidence that a matched directory is safe to remove.d.logger.Warn("gc: artifact retained because git tracking could not be determined", "path", path, "error", preserveErr)+ complete = falsereturn filepath.SkipDir}if preserve {@@ -1120,6 +1142,7 @@ func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string,}if rmErr := os.RemoveAll(path); rmErr != nil {d.logger.Warn("gc: artifact remove failed", "path", path, "error", rmErr)+ complete = falsereturn filepath.SkipDir}removed++@@ -1132,6 +1155,7 @@ func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string,if walkErr != nil {d.logger.Warn("gc: artifact walk failed", "dir", taskDir, "error", walkErr)}+ complete = complete && walkErr == nil && ctx.Err() == nilreturn}diff --git a/server/internal/daemon/gc_chat_artifacts.go b/server/internal/daemon/gc_chat_artifacts.gonew file mode 100644index 0000000000..92cc37808d--- /dev/null+++ b/server/internal/daemon/gc_chat_artifacts.go@@ -0,0 +1,83 @@+package daemon++import (+ "bytes"+ "context"+ "crypto/sha256"+ "fmt"+ "maps"+ "os"+ "path/filepath"+ "slices"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++const chatArtifactSweepFile = ".gc_chat_artifacts"++func (d *Daemon) idleChatArtifactEligible(meta *execenv.GCMeta) bool {+ return !meta.LocalDirectory && d.cfg.GCArtifactTTL > 0 &&+ !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL+}++// cleanIdleChatArtifacts runs under the env root reservation. A chat can run+// again while its server status is being checked, so revalidate the completion+// before touching the workdir or recording a sweep.+func (d *Daemon) cleanIdleChatArtifacts(ctx context.Context, taskDir string, checked *execenv.GCMeta, stats *gcStats) {+ if checked == nil || ctx.Err() != nil {+ return+ }+ meta, err := execenv.ReadGCMeta(taskDir)+ if err != nil || meta.Kind != execenv.GCKindChat || !d.idleChatArtifactEligible(meta) ||+ meta.WorkspaceID != checked.WorkspaceID || meta.ChatSessionID != checked.ChatSessionID ||+ meta.TaskID != checked.TaskID || !meta.CompletedAt.Equal(checked.CompletedAt) {+ return+ }++ matcher := newArtifactMatcher(d.cfg.GCArtifactPatterns, execenv.ManagedReclaimableArtifactSubpaths())+ marker := chatArtifactSweepMarker(meta, matcher)+ if chatArtifactSweepRecorded(taskDir, marker) {+ return+ }++ removed, size, perPattern, complete := d.sweepTaskArtifacts(ctx, taskDir, matcher)+ recordArtifactCleanup(stats, removed, size, perPattern)+ if complete && ctx.Err() == nil {+ if err := writeChatArtifactSweep(filepath.Join(taskDir, chatArtifactSweepFile), marker[:]); err != nil {+ d.logger.Warn("gc: write chat artifact sweep marker failed", "dir", taskDir, "error", err)+ }+ }+}++func chatArtifactSweepMarker(meta *execenv.GCMeta, matcher artifactMatcher) [sha256.Size]byte {+ return sha256.Sum256(fmt.Appendf(nil, "v1:%q:%q:%q:%q:%q:%q", meta.WorkspaceID, meta.ChatSessionID, meta.TaskID,+ meta.CompletedAt.UTC().Format(time.RFC3339Nano), slices.Sorted(maps.Keys(matcher.basenames)), matcher.managedSubpaths()))+}++func chatArtifactSweepRecorded(taskDir string, marker [sha256.Size]byte) bool {+ path := filepath.Join(taskDir, chatArtifactSweepFile)+ info, err := os.Lstat(path)+ if err != nil || !info.Mode().IsRegular() || info.Size() != int64(len(marker)) {+ return false+ }+ saved, err := os.ReadFile(path)+ return err == nil && bytes.Equal(saved, marker[:])+}++func writeChatArtifactSweep(path string, marker []byte) error {+ tmp, err := os.CreateTemp(filepath.Dir(path), chatArtifactSweepFile+"-*")+ if err != nil {+ return err+ }+ defer os.Remove(tmp.Name())+ _, writeErr := tmp.Write(marker)+ closeErr := tmp.Close()+ if writeErr != nil {+ return writeErr+ }+ if closeErr != nil {+ return closeErr+ }+ return os.Rename(tmp.Name(), path)+}diff --git a/server/internal/daemon/gc_junction_windows_test.go b/server/internal/daemon/gc_junction_windows_test.goindex 866f1f0e90..a7c06fb2a4 100644--- a/server/internal/daemon/gc_junction_windows_test.go+++ b/server/internal/daemon/gc_junction_windows_test.go@@ -43,6 +43,13 @@ func createJunction(t *testing.T, src, dst string) {}func TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction(t *testing.T) {+ t.Run("active environment guard", func(t *testing.T) {+ root := t.TempDir()+ alias := filepath.Join(t.TempDir(), "alias")+ createJunction(t, root, alias)+ assertEnvRootGuardSharesAliases(t, root, alias)+ })+d := newGCTestDaemon(t, http.NewServeMux())taskDir := t.TempDir()diff --git a/server/internal/daemon/gc_managed_artifact_test.go b/server/internal/daemon/gc_managed_artifact_test.goindex a878063cd2..cbea9251d4 100644--- a/server/internal/daemon/gc_managed_artifact_test.go+++ b/server/internal/daemon/gc_managed_artifact_test.go@@ -4,6 +4,8 @@ import ("context""encoding/json""fmt"+ "io"+ "log/slog""net/http""os""path/filepath"@@ -21,7 +23,10 @@ import (//// sandboxBinRel is the exact managed subpath, spelled out here so a change to// ManagedReclaimableArtifactSubpaths has to face these tests.-const sandboxBinRel = "codex-home/.sandbox-bin"+const (+ sandboxBinRel = "codex-home/.sandbox-bin"+ chatCacheFile = "workdir/repo/node_modules/dependency/index.js"+)// chatGCMux serves a chat gc-check that reports the given status.func chatGCMux(chatID, status string) *http.ServeMux {@@ -52,10 +57,7 @@ func assertKept(t *testing.T, taskDir string, rels ...string) {}}-// TestManagedArtifact_IdleActiveChatReclaimsSandboxBin is the #6782 regression-// test: an active chat session idle past GCArtifactTTL gives the managed Codex-// cache back, while everything the session owns survives.-func TestManagedArtifact_IdleActiveChatReclaimsSandboxBin(t *testing.T) {+func TestGC_IdleActiveChatReclaimsArtifacts(t *testing.T) {t.Parallel()chatID := "aaaaaaaa-0000-0000-0000-000000000001"d := newGCTestDaemon(t, chatGCMux(chatID, "active"))@@ -68,34 +70,161 @@ func TestManagedArtifact_IdleActiveChatReclaimsSandboxBin(t *testing.T) {}taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "idle-chat", meta)writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)- // Everything below must survive: session data, the audit trail, and a- // user-owned directory that merely shares the managed basename.+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)+ writeFile(t, filepath.Join(taskDir, "workdir/repo/packages/app/.turbo/cache"), 32)+ writeFile(t, filepath.Join(taskDir, "workdir/repo/src/index.ts"), 32)writeFile(t, filepath.Join(taskDir, "logs/run.log"), 32)writeFile(t, filepath.Join(taskDir, "output/result.md"), 32)writeFile(t, filepath.Join(taskDir, "codex-home/auth.json"), 32)writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/user-owned"), 32)stats := &gcStats{byPattern: map[string]int{}}- action := d.shouldCleanTaskDir(context.Background(), taskDir)- if action != gcActionCleanManagedArtifacts {- t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)- }- d.applyGCAction(context.Background(), taskDir, action, stats)+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), stats)assertGone(t, taskDir, sandboxBinRel)+ assertGone(t, taskDir, "workdir/repo/node_modules")+ assertGone(t, taskDir, "workdir/repo/packages/app/.turbo")assertKept(t, taskDir,+ "workdir/repo/src/index.ts","logs/run.log","output/result.md","codex-home/auth.json","workdir/repo/.sandbox-bin/user-owned",".gc_meta.json",)- if stats.artifactRemoved != 1 {- t.Fatalf("artifact_removed = %d, want 1", stats.artifactRemoved)+ if stats.artifactRemoved != 3 {+ t.Fatalf("artifact_removed = %d, want 3", stats.artifactRemoved)}if got := stats.byPattern[managedArtifactPatternPrefix+sandboxBinRel]; got != 1 {t.Fatalf("managed pattern count = %d, want 1", got)}+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected no second sweep after removing the caches, got %v", action)+ }+}++func TestGC_IdleChatSweepsOncePerCompletionAndPatternSet(t *testing.T) {+ t.Parallel()+ chatID := "aaaaaaaa-0000-0000-0000-000000000008"+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))+ meta := execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: chatID, WorkspaceID: "ws",+ CompletedAt: time.Now().Add(-24 * time.Hour),+ }+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "idle-chat", &meta)+ ctx := context.Background()++ // A successful sweep with no matches must also be remembered across restarts.+ d.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ restarted := New(d.cfg, d.logger)+ restarted.client = d.client+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 32)+ if action := restarted.shouldCleanTaskDir(ctx, taskDir); action != gcActionCleanManagedArtifacts {+ t.Fatalf("expected only exact-cache cleanup for an already swept run, got %v", action)+ }+ restarted.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, chatCacheFile)+ assertGone(t, taskDir, sandboxBinRel)++ // Equivalent pattern configurations must not cause another sweep.+ restarted.cfg.GCArtifactPatterns = []string{".turbo", ".next", "node_modules", ".next"}+ if action := restarted.shouldCleanTaskDir(ctx, taskDir); action != gcActionSkip {+ t.Fatalf("expected no cleanup for an already swept run, got %v", action)+ }+ restarted.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, chatCacheFile)++ // A new effective pattern must be considered for this same completed run.+ restarted.cfg.GCArtifactPatterns = append(restarted.cfg.GCArtifactPatterns, ".cache")+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.cache/data"), 32)+ restarted.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertGone(t, taskDir, "workdir/repo/.cache")+ assertGone(t, taskDir, "workdir/repo/node_modules")++ // A later completed run can create fresh artifacts under the same workdir.+ meta.CompletedAt = meta.CompletedAt.Add(time.Hour)+ createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "idle-chat", &meta)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)+ restarted.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertGone(t, taskDir, "workdir/repo/node_modules")+}++func TestGC_IdleChatSkipsChangedCompletion(t *testing.T) {+ t.Parallel()+ chatID := "aaaaaaaa-0000-0000-0000-000000000009"+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))+ meta := execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: chatID, WorkspaceID: "ws",+ CompletedAt: time.Now().Add(-24 * time.Hour),+ }+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "resumed-chat", &meta)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)+ ctx := context.Background()+ action, checked := d.taskDirGCDecision(ctx, taskDir)+ if action != gcActionCleanChatArtifacts {+ t.Fatalf("expected initial completion to be eligible, got %v", action)+ }++ // Even if the new completion would otherwise be eligible, it was not+ // the completion associated with the chat status request.+ meta.CompletedAt = meta.CompletedAt.Add(time.Hour)+ createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "resumed-chat", &meta)+ d.applyGCActionWithChatMeta(ctx, taskDir, action, &gcStats{}, checked)+ assertKept(t, taskDir, chatCacheFile)+ assertGone(t, taskDir, chatArtifactSweepFile)+ d.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertGone(t, taskDir, "workdir/repo/node_modules")+}++func TestGC_IdleChatRetriesIncompleteSweep(t *testing.T) {+ t.Parallel()+ chatID := "aaaaaaaa-0000-0000-0000-00000000000a"+ for _, reason := range []string{"git lookup failure", "cancelled after first removal"} {+ t.Run(reason, func(t *testing.T) {+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "idle-chat", &execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: chatID, WorkspaceID: "ws",+ CompletedAt: time.Now().Add(-24 * time.Hour),+ })+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ gitFile := filepath.Join(taskDir, "workdir/repo/.git")+ if reason == "git lookup failure" {+ writeFile(t, gitFile, 32) // malformed checkout metadata makes Git refuse the lookup+ } else {+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.next/data"), 32)+ d.logger = slog.New(cancelAfterArtifactRemoval{slog.NewTextHandler(io.Discard, nil), cancel})+ }+ d.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, chatCacheFile)+ assertGone(t, taskDir, chatArtifactSweepFile)+ if reason == "git lookup failure" {+ if err := os.Remove(gitFile); err != nil {+ t.Fatal(err)+ }+ } else {+ assertGone(t, taskDir, "workdir/repo/.next")+ }++ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertGone(t, taskDir, "workdir/repo/node_modules")+ assertKept(t, taskDir, chatArtifactSweepFile)+ })+ }+}++type cancelAfterArtifactRemoval struct {+ slog.Handler+ cancel context.CancelFunc+}++func (h cancelAfterArtifactRemoval) Handle(ctx context.Context, record slog.Record) error {+ if record.Message == "gc: artifact removed" {+ h.cancel()+ }+ return h.Handler.Handle(ctx, record)}// A chat session that completed recently keeps its cache — resuming inside the@@ -112,11 +241,10 @@ func TestManagedArtifact_FreshActiveChatKeepsSandboxBin(t *testing.T) {CompletedAt: time.Now().Add(-1 * time.Hour), // well inside the 12h TTL})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)- if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {- t.Fatalf("want gcActionSkip inside the TTL, got %d", got)- }- assertKept(t, taskDir, sandboxBinRel+"/codex")+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, sandboxBinRel+"/codex", chatCacheFile)}// MULTICA_GC_ARTIFACT_TTL=0 disables the managed reclaim along with the rest of@@ -134,11 +262,10 @@ func TestManagedArtifact_ArtifactTTLZeroDisablesFallback(t *testing.T) {CompletedAt: time.Now().Add(-365 * 24 * time.Hour),})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)- if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {- t.Fatalf("want gcActionSkip with artifact TTL disabled, got %d", got)- }- assertKept(t, taskDir, sandboxBinRel+"/codex")+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, sandboxBinRel+"/codex", chatCacheFile)}// Metadata with no completed_at stays with the per-kind legacy handling rather@@ -154,11 +281,10 @@ func TestManagedArtifact_ZeroCompletedAtIsLeftAlone(t *testing.T) {WorkspaceID: "ws",})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)- if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {- t.Fatalf("want gcActionSkip for zero completed_at, got %d", got)- }- assertKept(t, taskDir, sandboxBinRel+"/codex")+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, sandboxBinRel+"/codex", chatCacheFile)}// The fallback is a one-way upgrade from skip: it must never weaken a decision@@ -232,16 +358,15 @@ func TestManagedArtifact_ActiveEnvRootKeepsSandboxBin(t *testing.T) {CompletedAt: time.Now().Add(-365 * 24 * time.Hour),})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)d.markActiveEnvRoot(taskDir)- if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {- t.Fatalf("want gcActionSkip for an active env root, got %d", got)- }- assertKept(t, taskDir, sandboxBinRel+"/codex")+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, sandboxBinRel+"/codex", chatCacheFile)}-// local_directory tasks keep their envRoot forever, so the managed cache is the-// only thing the GC may ever take from them. The fallback must still apply.+// Unarchived in-place chats keep their record directory and use the exact+// managed-cache fallback.func TestManagedArtifact_LocalDirectoryChatReclaimsSandboxBin(t *testing.T) {t.Parallel()chatID := "aaaaaaaa-0000-0000-0000-000000000006"@@ -255,25 +380,21 @@ func TestManagedArtifact_LocalDirectoryChatReclaimsSandboxBin(t *testing.T) {CompletedAt: time.Now().Add(-24 * time.Hour),})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, "output/node_modules/dependency/index.js"), 32)writeFile(t, filepath.Join(taskDir, "logs/run.log"), 32)- action := d.shouldCleanTaskDir(context.Background(), taskDir)- if action != gcActionCleanManagedArtifacts {- t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)- }- d.applyGCAction(context.Background(), taskDir, action, &gcStats{byPattern: map[string]int{}})+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})assertGone(t, taskDir, sandboxBinRel)- assertKept(t, taskDir, "logs/run.log", ".gc_meta.json")+ assertKept(t, taskDir, "logs/run.log", "output/node_modules/dependency/index.js", ".gc_meta.json")}-// Once the cache is gone, a long-lived active chat must stop re-deciding to-// reclaim it. completed_at never moves again for a session that stays active,-// so without a presence check the GC would take an env-root reservation and run-// a removal pass every cycle, forever, for a directory with nothing to give.-func TestManagedArtifact_SecondCycleIsANoOp(t *testing.T) {+// Failed chat status checks allow the exact managed-cache fallback only.+func TestManagedArtifact_ChatStatusUnavailableReclaimsOnlyManagedCache(t *testing.T) {t.Parallel()chatID := "aaaaaaaa-0000-0000-0000-000000000007"- d := newGCTestDaemon(t, chatGCMux(chatID, "active"))+ d := newGCTestDaemon(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusServiceUnavailable)+ }))taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "repeat-chat", &execenv.GCMeta{Kind: execenv.GCKindChat,@@ -282,13 +403,11 @@ func TestManagedArtifact_SecondCycleIsANoOp(t *testing.T) {CompletedAt: time.Now().Add(-24 * time.Hour),})writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)+ writeFile(t, filepath.Join(taskDir, chatCacheFile), 32)- first := d.shouldCleanTaskDir(context.Background(), taskDir)- if first != gcActionCleanManagedArtifacts {- t.Fatalf("first cycle: want gcActionCleanManagedArtifacts, got %d", first)- }- d.applyGCAction(context.Background(), taskDir, first, &gcStats{byPattern: map[string]int{}})+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})assertGone(t, taskDir, sandboxBinRel)+ assertKept(t, taskDir, chatCacheFile)for cycle := 2; cycle <= 3; cycle++ {if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex ab2b1cec39..b3863d9106 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -1243,8 +1243,7 @@ func TestShouldCleanTaskDir_CompletedTaskTTLPreservesActiveEnv(t *testing.T) {Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",CompletedAt: time.Now().Add(-2 * time.Hour),})- d.markActiveEnvRoot(taskDir)- defer d.unmarkActiveEnvRoot(taskDir)+ defer d.markActiveEnvRoot(taskDir)()if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {t.Fatalf("expected active env to remain despite completed-task TTL, got %d", action)@@ -1334,8 +1333,7 @@ func TestShouldCleanTaskDir_ActiveEnvRootSkipsArtifactCleanup(t *testing.T) {CompletedAt: time.Now().Add(-24 * time.Hour),})- d.markActiveEnvRoot(taskDir)- defer d.unmarkActiveEnvRoot(taskDir)+ defer d.markActiveEnvRoot(taskDir)()if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {t.Fatalf("expected gcActionSkip while task is active, got %d", action)@@ -1367,8 +1365,7 @@ func TestShouldCleanTaskDir_ActiveEnvRootSkipsFullCleanup(t *testing.T) {CompletedAt: time.Now().Add(-30 * 24 * time.Hour),})- d.markActiveEnvRoot(taskDir)- defer d.unmarkActiveEnvRoot(taskDir)+ defer d.markActiveEnvRoot(taskDir)()if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {t.Fatalf("expected gcActionSkip on active env root with done+stale issue, got %d", action)@@ -1393,8 +1390,7 @@ func TestShouldCleanTaskDir_ActiveEnvRootSkipsOrphan404(t *testing.T) {CompletedAt: time.Now(),})- d.markActiveEnvRoot(taskDir)- defer d.unmarkActiveEnvRoot(taskDir)+ defer d.markActiveEnvRoot(taskDir)()if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {t.Fatalf("expected gcActionSkip on active env root with 404 issue, got %d", action)@@ -1408,8 +1404,7 @@ func TestShouldCleanTaskDir_ActiveEnvRootSkipsNoMetaOrphan(t *testing.T) {d.cfg.GCOrphanTTL = 0taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-no-meta", nil)- d.markActiveEnvRoot(taskDir)- defer d.unmarkActiveEnvRoot(taskDir)+ defer d.markActiveEnvRoot(taskDir)()if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {t.Fatalf("expected gcActionSkip on active env root with no-meta orphan, got %d", action)@@ -1712,16 +1707,16 @@ func TestActiveEnvRootRefcount(t *testing.T) {if d.isActiveEnvRoot(root) {t.Fatal("expected inactive before mark")}- d.markActiveEnvRoot(root)- d.markActiveEnvRoot(root) // second mark from reuse path+ releaseFirst := d.markActiveEnvRoot(root)+ releaseSecond := d.markActiveEnvRoot(root) // second mark from reuse pathif !d.isActiveEnvRoot(root) {t.Fatal("expected active after mark")}- d.unmarkActiveEnvRoot(root)+ releaseFirst()if !d.isActiveEnvRoot(root) {t.Fatal("expected still active after one unmark")}- d.unmarkActiveEnvRoot(root)+ releaseSecond()if d.isActiveEnvRoot(root) {t.Fatal("expected inactive after both unmarks")}@@ -1733,11 +1728,11 @@ func TestReserveEnvRootForGCIsExclusive(t *testing.T) {d := newGCTestDaemon(t, http.NewServeMux())root := "/tmp/fake/gc-reservation"- d.markActiveEnvRoot(root)+ releaseActive := d.markActiveEnvRoot(root)if _, ok := d.reserveEnvRootForGC(root); ok {t.Fatal("GC reservation must fail while a task is active")}- d.unmarkActiveEnvRoot(root)+ releaseActive()release, ok := d.reserveEnvRootForGC(root)if !ok {@@ -2521,17 +2516,8 @@ func TestShouldCleanTaskDir_ChatHardDeletedFreshMtime(t *testing.T) {}}-// TestShouldCleanTaskDir_ChatActiveResistsOldMtime is the explicit acceptance-// criterion #2: an active chat session whose workdir is older than-// GCOrphanTTL must NOT be reclaimed. The only path to clean an active-// session's workdir is for the user to archive or hard-delete the session.-//-// #6782 narrowed this from "the GC does nothing" to "the GC never removes the-// directory": a session idle past GCArtifactTTL now gives back the regenerable-// codex-home/.sandbox-bin cache, which the next message re-provisions. The-// acceptance criterion is unchanged — the session's own data survives — so-// this asserts the surviving contents rather than the bare action value.-// TestManagedArtifact_IdleActiveChatReclaimsSandboxBin covers the carve-out.+// An unarchived chat keeps its workdir even after the orphan TTL.+// Artifact cleanup can reclaim regenerable caches while preserving its data.func TestShouldCleanTaskDir_ChatActiveResistsOldMtime(t *testing.T) {t.Parallel()chatID := "ffffffff-ffff-ffff-ffff-ffffffffff01"diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.goindex 2d44f85803..43a0a3efa6 100644--- a/server/internal/daemon/workdir_race_test.go+++ b/server/internal/daemon/workdir_race_test.go@@ -794,7 +794,7 @@ func prepareTimeoutStopsLeaseDuringBlockedStart(t *testing.T, budget time.Durati// TestHandleTask_KeepsEnvRootActiveAcrossCompletion is the regression guard// for issue #3999 race B. After runner.run returns, the in-process active-// guard installed inside runTask (defer unmarkActiveEnvRoot at the+// guard installed inside runTask (deferred release at the// goroutine's exit) has already fired by the time handleTask calls// reportTaskResult and execenv.WriteGCMeta. Without an outer guard at the// handleTask level, the GC loop sees a window where the directory has@@ -848,8 +848,7 @@ func TestHandleTask_KeepsEnvRootActiveAcrossCompletion(t *testing.T) {// isActiveEnvRoot back to false before reportTaskResult fires.d.runner = taskRunnerFunc(func(_ context.Context, tk Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {predicted := execenv.PredictRootDir(taskRootDirParams(d.cfg.WorkspacesRoot, tk))- d.markActiveEnvRoot(predicted)- defer d.unmarkActiveEnvRoot(predicted)+ defer d.markActiveEnvRoot(predicted)()return TaskResult{Status: "completed",EnvRoot: predicted,