Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): reclaim Codex caches and expire local task homes (MUL-9157) (#10528)
Bohan Jiangcfcc4d055713
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex fc42cd119c..ffe8a96ebb 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -560,7 +560,7 @@ jobs:# These fixtures must redirect both the Windows user profile and the# platform-native Hermes home; otherwise discovery scans the runner's# real skills instead of the test directories.- run: go test ./internal/daemon -v -run '^(TestListRuntimeLocalSkills_HermesFollowsTaskHome|TestLocalSkills_DiscoversACPProviderRoots)$' -count=1 -timeout=5m+ run: go test ./internal/daemon -v -run '^(TestListRuntimeLocalSkills_HermesFollowsTaskHome|TestLocalSkills_DiscoversACPProviderRoots|TestGC_LocalCodexHomePreservesJunctionTargets)$' -count=1 -timeout=5m- name: Test Windows Git Bash temp lifecycleworking-directory: serverdiff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex 921ca8b89b..2dd496ace5 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -145,11 +145,11 @@ Chaque exécution a un répertoire sous la racine des espaces de travail (par d| Automatisation (Exécution seule), création rapide | Au nettoyage suivant la fin de l'exécution || Sans propriétaire identifié (métadonnées absentes, ou enregistrement disparu côté serveur) | Après 72 heures sans modification du répertoire |-Tant 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.+Tant que la tâche reste ouverte, seul le contenu régénérable est supprimé 12 heures après la fin d'une exécution : `node_modules`, `.next`, `.turbo` et les chemins exacts `.sandbox-bin`, `.tmp/plugins`, `.tmp/marketplaces`, `cache/remote_plugin_catalog` sous `codex-home`. Les autres fichiers, dont les bases SQLite et leurs WAL, sont conservés. Les répertoires d'exécution de tâches gérés sont aussi supprimés entièrement 14 jours après la fin par défaut, que la tâche soit fermée ou non.-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.+Pour un chat non archivé dans un répertoire de travail géré par Multica, le daemon applique le même nettoyage régénérable, par défaut 12 heures après la dernière exécution. Il 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. Pour un chat directement dans le répertoire local d'un projet, seuls les chemins exacts de cache Codex ci-dessus sont nettoyés.-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.+Le daemon ne supprime jamais le répertoire local du projet. Le répertoire de suivi conserve les journaux du daemon et `output/`. Après `MULTICA_GC_COMPLETED_TASK_TTL` (14 jours par défaut), il supprime tout le `codex-home` si les historiques de session sont stockés hors du répertoire de suivi. Les homes contenant l'unique historique local sont conservés. La valeur `0` désactive cette expiration. Une exécution ultérieure recrée le home et reconnecte le stockage de conversation ; celui-ci reste soumis à sa propre politique de conservation ci-dessous.### 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 09979006d6..2b7054dc65 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -145,11 +145,11 @@ CodeBuddy、Kimi CLI、Pi は起動時に自分でユーザーレベルの設定| オートパイロット(実行のみ)、クイック作成 | 実行が終わった後の次のクリーンアップ || 持ち主が見つからない(メタデータがない、またはサーバー上に該当する記録がない) | ディレクトリが 72 時間変更されていないとき |-タスクがまだ閉じていない場合、実行完了から 12 時間後に再生成できる内容だけを削除します。対象は `node_modules`、`.next`、`.turbo` ディレクトリと、デーモンが Codex 用に用意したキャッシュで、ほかは残ります。Multica Cloud に接続したデーモンは、タスクが閉じているかどうかにかかわらず、実行完了から 14 日後にディレクトリ全体も削除します。セルフホストでは既定でこれを行いません。+タスクがまだ閉じていない場合、実行完了から 12 時間後に再生成できる内容だけを削除します。対象は `node_modules`、`.next`、`.turbo` と、`codex-home` 内の正確なパス `.sandbox-bin`、`.tmp/plugins`、`.tmp/marketplaces`、`cache/remote_plugin_catalog` です。SQLite データベースと WAL を含むほかのファイルは残ります。管理対象のタスク実行ディレクトリは、タスクが閉じているかどうかにかかわらず、既定で完了から 14 日後に全体も削除されます。-Multica が管理する作業ディレクトリを使う未アーカイブのチャットでは、既定で最後の実行が終わってから 12 時間後に、同じルールで再生成できる内容を削除します。クリーンアップに成功した実行については、デーモンは繰り返しスキャンを省きます。新しい実行が完了すると、同じ待ち時間を経て再び対象になります。チャットをプロジェクトのローカルディレクトリで直接実行した場合は、実行の記録ディレクトリにあるデーモンの `codex-home/.sandbox-bin` キャッシュだけがこのクリーンアップの対象です。+Multica が管理する作業ディレクトリを使う未アーカイブのチャットでは、既定で最後の実行が終わってから 12 時間後に、同じルールで再生成できる内容を削除します。クリーンアップに成功した実行については繰り返しスキャンを省きます。新しい実行が完了すると、同じ待ち時間を経て再び対象になります。プロジェクトのローカルディレクトリで直接実行するチャットでは、上記の正確な Codex キャッシュパスだけを削除します。-プロジェクトのローカルディレクトリでの実行は、あなた自身のディレクトリで作業し、デーモンはそこに触れません。Multica がその実行用に作る記録ディレクトリ(ログなど)も残り、中の再生成できるキャッシュだけが片付けられます。+プロジェクトのローカルディレクトリはデーモンが削除しません。実行の記録ディレクトリには daemon のログと `output/` が残ります。完了から `MULTICA_GC_COMPLETED_TASK_TTL`(既定 14 日)が経過し、セッション履歴が記録ディレクトリの外にある場合、`codex-home` 全体を削除します。タスク内だけに履歴がある home は保持します。`0` でこの期限による削除を無効にできます。次の実行は home を再作成し、会話ストアに再接続します。ストアには下記の独立した保持期間が引き続き適用されます。### 共有のリポジトリキャッシュdiff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex ab25413c60..208b716e1c 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -145,11 +145,11 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽| 오토파일럿(실행만), 빠른 생성 | 실행이 끝난 뒤 다음 정리 때 || 소속을 찾을 수 없음(메타데이터가 없거나 서버에 해당 기록이 없음) | 디렉터리가 72시간 동안 변경되지 않았을 때 |-태스크가 아직 닫히지 않았다면 실행 완료 12시간 뒤에 다시 만들 수 있는 내용만 지웁니다. 대상은 `node_modules`, `.next`, `.turbo` 디렉터리와 데몬이 Codex용으로 준비한 캐시이며 나머지는 남습니다. Multica Cloud에 연결된 데몬은 태스크가 닫혔는지와 관계없이 실행 완료 14일 뒤에 디렉터리 전체도 삭제합니다. 셀프 호스팅에서는 기본적으로 이 단계를 하지 않습니다.+태스크가 열려 있으면 실행 완료 12시간 후 다시 만들 수 있는 내용만 삭제합니다. 대상은 `node_modules`, `.next`, `.turbo`와 `codex-home` 안의 정확한 경로 `.sandbox-bin`, `.tmp/plugins`, `.tmp/marketplaces`, `cache/remote_plugin_catalog`입니다. SQLite 데이터베이스와 WAL을 포함한 나머지 파일은 유지합니다. 관리되는 태스크 실행 디렉터리는 태스크 종료 여부와 관계없이 기본적으로 완료 14일 후 전체도 삭제됩니다.-보관하지 않은 채팅이 Multica에서 관리하는 작업 디렉터리를 사용하면, 기본적으로 마지막 실행이 끝나고 12시간 뒤에 같은 규칙으로 다시 만들 수 있는 내용을 정리합니다. 정리에 성공하면 데몬은 해당 실행의 반복 스캔을 건너뜁니다. 이후 실행이 끝나면 같은 시간이 지난 뒤 다시 정리 대상이 됩니다. 채팅을 프로젝트의 로컬 디렉터리에서 직접 실행한 경우에는 실행 기록 디렉터리 안에 있는 데몬의 `codex-home/.sandbox-bin` 캐시만 이 정리의 대상입니다.+보관하지 않은 채팅이 Multica에서 관리하는 작업 디렉터리를 사용하면 기본적으로 마지막 실행이 끝나고 12시간 뒤 같은 규칙으로 다시 만들 수 있는 내용을 정리합니다. 정리에 성공하면 해당 실행의 반복 스캔을 건너뜁니다. 이후 실행이 끝나면 같은 시간이 지난 뒤 다시 정리 대상이 됩니다. 프로젝트 로컬 디렉터리에서 직접 실행하는 채팅은 위의 정확한 Codex 캐시 경로만 정리합니다.-프로젝트 로컬 디렉터리에서의 실행은 사용자 자신의 디렉터리에서 작업하며 데몬은 그 디렉터리를 건드리지 않습니다. Multica가 그 실행을 위해 따로 만드는 기록 디렉터리(로그 등)도 유지되고, 그 안의 다시 만들 수 있는 캐시만 정리됩니다.+프로젝트 로컬 디렉터리는 데몬이 삭제하지 않습니다. 실행 기록 디렉터리에는 daemon 로그와 `output/`을 유지합니다. 완료 후 `MULTICA_GC_COMPLETED_TASK_TTL`(기본 14일)이 지나고 세션 기록이 기록 디렉터리 밖에 있으면 `codex-home` 전체를 삭제합니다. 태스크 안에만 세션 기록이 있는 home은 유지합니다. `0`으로 설정하면 home 만료 삭제를 끕니다. 다음 실행은 home을 다시 만들고 대화 저장소를 연결합니다. 저장소에는 아래의 별도 보존 정책이 계속 적용됩니다.### 공유 저장소 캐시diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex cc10456474..91963cd05b 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -147,11 +147,11 @@ Each run gets a directory under the workspaces root (default `~/multica_workspac| Autopilot (Run Only), quick create | On the next cleanup after the run ends || No owner found (missing metadata, or the server no longer has the record) | After 72 hours without changes to the directory |-While 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.+While the issue is still open, 12 hours after a run completes only regenerable content is removed: `node_modules`, `.next`, and `.turbo` directories, plus these exact paths under `codex-home`: `.sandbox-bin`, `.tmp/plugins`, `.tmp/marketplaces`, and `cache/remote_plugin_catalog`. Other files, including SQLite databases and their WAL files, stay. Managed issue-run directories are also removed 14 days after completion by default, whether or not the issue is closed.-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.+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. For chats in a project's local directory, only the exact Codex cache paths above are cleaned.-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.+A run on a project's local directory works in your own directory, which the daemon never touches. Its record directory keeps daemon logs and `output/`. After `MULTICA_GC_COMPLETED_TASK_TTL` (14 days by default), the daemon removes its entire `codex-home` if session history is stored outside the record directory. Homes with task-local session history are retained. Set the variable to `0` to disable home expiry. A later run rebuilds the home and reconnects the conversation store; that store still follows its own session retention policy below.### Shared repository cachediff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex b5d3b727d9..5494b2bcdd 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -146,11 +146,11 @@ CodeBuddy、Kimi CLI 和 Pi 啟動時會自己載入使用者級配置,並與| 自動化(僅執行)、快速建立 | 執行結束後的下一輪清理 || 找不到歸屬(目錄缺少後設資料,或伺服器上已沒有對應記錄) | 目錄 72 小時沒有改動 |-任務仍未關閉時,執行完成 12 小時後只刪可以重新生成的內容:目錄中的 `node_modules`、`.next`、`.turbo`,以及守護程序為 Codex 準備的快取,其餘保留。連線 Multica Cloud 的守護程序還會在執行完成 14 天後刪除整個目錄,不論任務是否關閉;自託管預設不做這一步。+任務仍未關閉時,執行完成 12 小時後只刪可以重新生成的內容:目錄中的 `node_modules`、`.next`、`.turbo`,以及 `codex-home` 下的四個精確路徑:`.sandbox-bin`、`.tmp/plugins`、`.tmp/marketplaces`、`cache/remote_plugin_catalog`。其他檔案(包括 SQLite 資料庫和 WAL 檔案)保留。受管的任務執行目錄預設還會在執行完成 14 天後整體刪除,不論任務是否關閉。-未歸檔的聊天如果使用 Multica 管理的工作目錄,守護程序預設會在最後一次執行結束 12 小時後,按同樣的規則清理可重新生成的內容。清理成功後,守護程序會略過該次執行的重複掃描。後續執行結束並經過相同的等待時間後,就會再次符合清理條件。聊天直接在專案本地目錄執行時,這項清理只處理執行記錄目錄中的 `codex-home/.sandbox-bin` 快取。+未歸檔的聊天如果使用 Multica 管理的工作目錄,守護程序預設會在最後一次執行結束 12 小時後,按同樣的規則清理可重新生成的內容。清理成功後,守護程序會略過該次執行的重複掃描。後續執行結束並經過相同的等待時間後,就會再次符合清理條件。聊天直接在專案本地目錄執行時,只清理上述精確路徑中的 Codex 快取。-專案本地目錄上的執行直接改你自己的目錄,守護程序不會動它;Multica 為這次執行另建的記錄目錄(日誌等)也會保留,只清理其中可再生成的快取。+專案本地目錄上的執行直接修改你自己的目錄,守護程序不會動它。執行記錄目錄保留 daemon 日誌和 `output/`。執行完成超過 `MULTICA_GC_COMPLETED_TASK_TTL`(預設 14 天)後,如果會話記錄保存在記錄目錄外,就刪除整個 `codex-home`;仍保存任務本地會話記錄的 home 會保留。將該變數設為 `0` 可關閉 home 到期清理。後續執行會重建 home 並重新連接會話儲存;會話儲存仍遵循下文獨立的保留策略。### 共享的倉庫快取diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 30d72b9ac9..5841a967b6 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -148,11 +148,11 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul| 自动化(仅运行)、快速创建 | 运行结束后的下一轮清理 || 找不到归属(目录缺少元数据,或服务器上已没有对应记录) | 目录 72 小时没有改动 |-任务仍未关闭时,运行完成 12 小时后只删可以重新生成的内容:目录中的 `node_modules`、`.next`、`.turbo`,以及守护进程为 Codex 准备的缓存,其余保留。连接 Multica Cloud 的守护进程还会在运行完成 14 天后删除整个目录,不论任务是否关闭;自托管默认不做这一步。+任务仍未关闭时,运行完成 12 小时后只删可以重新生成的内容:目录中的 `node_modules`、`.next`、`.turbo`,以及 `codex-home` 下的四个精确路径:`.sandbox-bin`、`.tmp/plugins`、`.tmp/marketplaces`、`cache/remote_plugin_catalog`。其他文件(包括 SQLite 数据库和 WAL 文件)保留。托管的任务运行目录默认还会在运行完成 14 天后整体删除,不论任务是否关闭。-未归档的聊天如果使用 Multica 管理的工作目录,守护进程默认会在最后一次运行结束 12 小时后按同样的规则清理可重新生成的内容。清理成功后,守护进程会跳过该次运行的重复扫描。后续运行结束后,经过同样的等待时间便可再次清理。聊天直接在项目本地目录中运行时,这项清理只针对运行记录目录中的 `codex-home/.sandbox-bin` 缓存。+未归档的聊天如果使用 Multica 管理的工作目录,守护进程默认会在最后一次运行结束 12 小时后按同样的规则清理可重新生成的内容。清理成功后,守护进程会跳过该次运行的重复扫描。后续运行结束后,经过同样的等待时间便可再次清理。聊天直接在项目本地目录中运行时,只清理上述精确路径中的 Codex 缓存。-项目本地目录上的运行直接改你自己的目录,守护进程不会动它;Multica 为这次运行另建的记录目录(日志等)也会保留,只清理其中可再生成的缓存。+项目本地目录上的运行直接改你自己的目录,守护进程不会动它。运行记录目录保留 daemon 日志和 `output/`。运行完成超过 `MULTICA_GC_COMPLETED_TASK_TTL`(默认 14 天)后,如果会话记录保存在记录目录外,就删除整个 `codex-home`;仍保存任务本地会话记录的 home 会保留。将该变量设为 `0` 可关闭 home 到期清理。后续运行会重建 home 并重新连接会话存储;会话存储仍遵循下文独立的保留策略。### 共享的仓库缓存diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex 2e79c5b3df..7a69fdf91a 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -273,7 +273,7 @@ Le daemon nettoie régulièrement les répertoires des exécutions, les caches d| `MULTICA_GC_ENABLED` | `true` | `false` ou `0` désactive toute la boucle de nettoyage || `MULTICA_GC_INTERVAL` | `2h` | Intervalle entre deux passes ; la première a lieu environ 30 secondes après le démarrage du daemon || `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` | `14d` | 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_COMPLETED_TASK_TTL` | `14d` | Délai après la fin avant suppression du répertoire de tâche géré, ou seulement de `codex-home` pour une exécution locale. Journaux du daemon, sorties et sessions externes sont conservés ; les homes contenant des sessions locales restent. `0` désactive cette expiration || `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 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 |diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 98239eec2d..d45e3fbd0c 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -276,7 +276,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_GC_ENABLED` | `true` | `false` または `0` でクリーンアップ全体を止める || `MULTICA_GC_INTERVAL` | `2h` | クリーンアップの間隔。デーモン起動の約 30 秒後に最初の 1 回を実行 || `MULTICA_GC_TTL` | `24h` | タスクが `done` または `closed` カテゴリに入ってから、またはチャットセッションがアーカイブされてから、実行ディレクトリを削除するまでの時間 |-| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | タスクの実行が完了してからディレクトリ全体を削除するまでの時間。タスクが閉じているかどうかは問わない。`0` で無効。プロジェクトのローカルディレクトリでの実行には適用されない |+| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 実行完了後、管理対象のタスクディレクトリを削除するまでの時間。ローカルディレクトリ実行は `codex-home` のみ削除し、daemon ログ、出力、外部のセッションを保持。ローカル履歴を持つ home は保持。`0` で無効 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 持ち主が見つからないディレクトリを、変更がないまま何時間経ったら削除するか || `MULTICA_GC_ARTIFACT_TTL` | `12h` | 実行終了からデーモンが再生成できる内容を削除するまでの時間。次の行のパターンは、まだ閉じていないタスクと、管理対象の作業ディレクトリを使う未アーカイブのチャットに適用される。デーモンが管理する Codex キャッシュにも同じ時間が適用される。`0` でこれらのキャッシュを保持する || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 再生成できるとみなすディレクトリ名(カンマ区切り)。設定するとデフォルトの一覧を**置き換える**ため、デフォルトも残したいなら一緒に書く。`/` や `\` を含む項目は無視される |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex 06c43adae3..f8848d693c 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -276,7 +276,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_GC_ENABLED` | `true` | `false` 또는 `0`이면 정리 전체를 끕니다 || `MULTICA_GC_INTERVAL` | `2h` | 정리 간격. 데몬 시작 약 30초 뒤에 첫 정리를 합니다 || `MULTICA_GC_TTL` | `24h` | 태스크가 `done` 또는 `closed` 분류에 들어가거나 채팅 세션이 보관된 뒤, 실행 디렉터리를 삭제하기까지의 시간 |-| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 태스크 실행이 완료된 뒤 디렉터리 전체를 삭제하기까지의 시간. 태스크가 닫혔는지와 관계없음. `0`이면 끔. 프로젝트 로컬 디렉터리에서의 실행에는 적용되지 않음 |+| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 완료 후 관리 태스크 디렉터리를 삭제할 때까지의 시간. 로컬 디렉터리 실행은 `codex-home`만 삭제하고 daemon 로그, 출력, 외부 세션은 유지. 로컬 세션 기록이 있는 home은 유지. `0`이면 끔 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 소속을 찾을 수 없는 디렉터리가 변경 없이 얼마나 지나면 삭제할지 || `MULTICA_GC_ARTIFACT_TTL` | `12h` | 실행이 끝난 뒤 데몬이 다시 만들 수 있는 내용을 정리하기까지의 시간. 다음 행의 패턴은 열린 태스크와 관리되는 작업 디렉터리를 쓰는 미보관 채팅에 적용됨. 데몬이 관리하는 Codex 캐시에도 같은 시간이 적용됨. `0`이면 이 캐시를 유지함 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 다시 만들 수 있다고 보는 디렉터리 이름(쉼표로 구분). 설정하면 기본 목록을 **대체**하므로 기본 항목도 유지하려면 함께 적어야 함. `/`나 `\`가 들어간 항목은 무시됨 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 892e5181ac..9b7864f532 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -282,7 +282,7 @@ The daemon periodically cleans up run directories, repository caches, session re| `MULTICA_GC_ENABLED` | `true` | Set to `false` or `0` to turn the whole cleanup loop off || `MULTICA_GC_INTERVAL` | `2h` | Time between cleanup passes; the first pass runs about 30 seconds after the daemon starts || `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` | `14d` | 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_COMPLETED_TASK_TTL` | `14d` | How long after completion managed issue-run directories, or only `codex-home` for local-directory runs, are removed. Local runs retain daemon logs, output, and externally stored sessions; homes with local session history stay. `0` disables this expiry || `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 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 |diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdxindex 6f1f45c35a..935900f865 100644--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx@@ -272,7 +272,7 @@ API key 與 base URL 都為空時,這一層關閉,不會發出任何上游| `MULTICA_GC_ENABLED` | `true` | 設為 `false` 或 `0` 關閉整個清理迴圈 || `MULTICA_GC_INTERVAL` | `2h` | 兩輪清理之間的間隔;守護程序啟動約 30 秒後先清理一次 || `MULTICA_GC_TTL` | `24h` | 任務進入 `done` 或 `closed` 分類、或聊天會話歸檔後,再過多久刪除對應執行目錄 |-| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 任務執行完成多久後刪除整個目錄,不論任務是否關閉;`0` 表示關閉。不作用於專案本地目錄上的執行 |+| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 執行完成後多久刪除受管任務目錄;本地目錄執行只刪除 `codex-home`,保留 daemon 日誌、輸出和外部會話儲存,仍有本地會話記錄的 home 不刪除。`0` 表示關閉此到期清理 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 找不到歸屬的目錄多久沒有改動後刪除 || `MULTICA_GC_ARTIFACT_TTL` | `12h` | 從執行結束到守護程序清理可重新生成內容的時間。下一行的目錄名稱規則適用於未關閉的任務,以及使用受管理工作目錄的未歸檔聊天。守護程序管理的 Codex 快取也適用相同時長。設為 `0` 可保留這些快取 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 按目錄名匹配的可再生成內容,逗號分隔。設定後**替換**預設列表,要保留預設項就一併寫上;含 `/` 或 `\` 的項會被忽略 |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 8c63788f12..41a3c3e722 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -276,7 +276,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_GC_ENABLED` | `true` | 设为 `false` 或 `0` 关闭整个清理循环 || `MULTICA_GC_INTERVAL` | `2h` | 两轮清理之间的间隔;守护进程启动约 30 秒后先清理一次 || `MULTICA_GC_TTL` | `24h` | 任务进入 `done` 或 `closed` 分类、或聊天会话归档后,再过多久删除对应运行目录 |-| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 任务运行完成多久后删除整个目录,不论任务是否关闭;`0` 表示关闭。不作用于项目本地目录上的运行 |+| `MULTICA_GC_COMPLETED_TASK_TTL` | `14d` | 运行完成后多久删除托管任务目录;本地目录运行只删除 `codex-home`,保留 daemon 日志、输出和外部会话存储,仍有本地会话记录的 home 不删除。`0` 表示关闭此到期清理 || `MULTICA_GC_ORPHAN_TTL` | `72h` | 找不到归属的目录多久没有改动后删除 || `MULTICA_GC_ARTIFACT_TTL` | `12h` | 从运行结束到守护进程清理可重新生成内容的时间。下一行的目录名规则适用于未关闭的任务,以及使用托管工作目录的未归档聊天。守护进程管理的 Codex 缓存也适用相同时长。设为 `0` 可保留这些缓存 || `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` | 按目录名匹配的可再生成内容,逗号分隔。设置后**替换**默认列表,要保留默认项就一并写上;含 `/` 或 `\` 的项会被忽略 |diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex d5371be062..7772da2d71 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -117,7 +117,7 @@ type Config struct {GCEnabled bool // enable periodic workspace garbage collection (default: true)GCInterval time.Duration // how often the GC loop runs (default: 2h)GCTTL time.Duration // clean dirs whose issue is done/cancelled and updated_at < now()-TTL (default: 24h)- GCCompletedTaskTTL time.Duration // fully clean inactive issue-task envs completed at least this long ago, regardless of parent issue status (default: 14d; 0 disables; local_directory envs are never fully removed)+ GCCompletedTaskTTL time.Duration // fully clean inactive issue-task envs; local_directory envs expire only codex-home, preserving daemon logs/output and externally stored sessions (default: 14d; 0 disables)GCOrphanTTL time.Duration // clean orphan dirs with no meta, or dirs whose issue gc-check returns 404, once they exceed this age (default: 72h). The 404 path uses the same TTL — a scoped-down token can't instantly wipe live workspaces.GCArtifactTTL time.Duration // once a task has been completed for at least this long, drop regenerable artifacts: pattern-matched build outputs when the parent record keeps the directory (an open issue), and the exact daemon-managed Codex cache for every task kind (default: 12h, set 0 to disable both)GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)@@ -578,6 +578,8 @@ func LoadConfig(overrides Overrides) (Config, error) {// time main has usually moved far enough that a fresh checkout beats a// stale worktree. Operators who want the old keep-until-terminal behavior// set MULTICA_GC_COMPLETED_TASK_TTL=0.+ // Local-directory tasks keep their daemon logs and output; this TTL removes+ // only their Codex home, and only when session history is stored elsewhere.gcCompletedTaskTTL, err := durationFromEnv("MULTICA_GC_COMPLETED_TASK_TTL", DefaultGCCompletedTaskTTL)if err != nil {return Config{}, errdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 8de019df8a..212ebf80fe 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -520,6 +520,9 @@ type Daemon struct {// went away is a few bytes, not a leak worth a lifecycle.registerSerial sync.Map+ // Unowned directories remain untouched; warn once per path per daemon.+ gcUnownedWarnings sync.Map+// agentsAvailable holds the current built-in agent CLI availability set —// the same shape as cfg.Agents, which it supersedes as the read path.//diff --git a/server/internal/daemon/diskusage_test.go b/server/internal/daemon/diskusage_test.goindex 3350261495..c24630e421 100644--- a/server/internal/daemon/diskusage_test.go+++ b/server/internal/daemon/diskusage_test.go@@ -16,6 +16,8 @@ import ("github.com/multica-ai/multica/server/internal/daemon/execenv")+const managedCodexArtifactPaths = "codex-home/.sandbox-bin,codex-home/.tmp/marketplaces,codex-home/.tmp/plugins,codex-home/cache/remote_plugin_catalog"+func writeFile(t *testing.T, path string, size int) {t.Helper()if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {@@ -310,27 +312,30 @@ func TestScanDiskUsage_ManagedCodexSandboxIsExactAndDeduplicated(t *testing.T) {taskDir := filepath.Join(root, wsID, "tttttttt")writeFile(t, filepath.Join(taskDir, "codex-home/.sandbox-bin/codex.exe"), 300)writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/cache"), 400)+ for _, rel := range []string{".tmp/plugins", ".tmp/marketplaces", "cache/remote_plugin_catalog"} {+ writeFile(t, filepath.Join(taskDir, "codex-home", rel, "catalog"), 100)+ }report, err := ScanDiskUsage(root, nil)if err != nil {t.Fatalf("ScanDiskUsage managed-only: %v", err)}- if got := report.Tasks[0].SizeBytes; got != 700 {- t.Fatalf("size_bytes=%d, want 700", got)+ if got := report.Tasks[0].SizeBytes; got != 1000 {+ t.Fatalf("size_bytes=%d, want 1000", got)}- if got := report.Tasks[0].ArtifactSizeBytes; got != 300 {- t.Fatalf("artifact_size_bytes=%d, want exact managed 300", got)+ if got := report.Tasks[0].ArtifactSizeBytes; got != 600 {+ t.Fatalf("artifact_size_bytes=%d, want exact managed 600", got)}- if got := strings.Join(report.ManagedArtifactSubpaths, ","); got != "codex-home/.sandbox-bin" {- t.Fatalf("managed artifact paths=%q, want codex-home/.sandbox-bin", got)+ if got := strings.Join(report.ManagedArtifactSubpaths, ","); got != managedCodexArtifactPaths {+ t.Fatalf("managed artifact paths=%q, want %s", got, managedCodexArtifactPaths)}report, err = ScanDiskUsage(root, []string{".sandbox-bin"})if err != nil {t.Fatalf("ScanDiskUsage broad basename: %v", err)}- if got := report.Tasks[0].ArtifactSizeBytes; got != 700 {- t.Fatalf("artifact_size_bytes=%d, want 700 without double counting", got)+ if got := report.Tasks[0].ArtifactSizeBytes; got != 1000 {+ t.Fatalf("artifact_size_bytes=%d, want 1000 without double counting", got)}}@@ -547,8 +552,8 @@ func TestScanDiskUsageRoots_SumsAcrossRoots(t *testing.T) {if agg.TotalWorkspaceCount != 2 {t.Fatalf("TotalWorkspaceCount = %d, want 2", agg.TotalWorkspaceCount)}- if got := strings.Join(agg.ManagedArtifactSubpaths, ","); got != "codex-home/.sandbox-bin" {- t.Fatalf("managed artifact paths=%q, want codex-home/.sandbox-bin", got)+ if got := strings.Join(agg.ManagedArtifactSubpaths, ","); got != managedCodexArtifactPaths {+ t.Fatalf("managed artifact paths=%q, want %s", got, managedCodexArtifactPaths)}}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex b410db7d0d..2f4c5e3411 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -1160,8 +1160,8 @@ type GCMeta struct {// this by never falling into the gcActionClean branch (which would// RemoveAll envRoot — safe by structure, but we still want to keep the// envRoot's output/ and logs/ around longer so users can inspect what- // the agent did in their own tree). Pattern-based artifact cleanup is- // still allowed.+ // the agent did in their own tree). Artifact cleanup and expiry of the+ // Codex home are still allowed; locally stored session history is retained.LocalDirectory bool `json:"local_directory,omitempty"`}diff --git a/server/internal/daemon/execenv/reclaimable.go b/server/internal/daemon/execenv/reclaimable.goindex c478d061f6..3dfb434f1d 100644--- a/server/internal/daemon/execenv/reclaimable.go+++ b/server/internal/daemon/execenv/reclaimable.go@@ -12,5 +12,10 @@ const (// relative paths rather than basenames: a repository may legitimately contain// a directory with the same leaf name.func ManagedReclaimableArtifactSubpaths() []string {- return []string{filepath.Join(codexHomeDirName, codexSandboxBinDirName)}+ return []string{+ filepath.Join(codexHomeDirName, codexSandboxBinDirName),+ filepath.Join(codexHomeDirName, ".tmp", "plugins"),+ filepath.Join(codexHomeDirName, ".tmp", "marketplaces"),+ filepath.Join(codexHomeDirName, "cache", "remote_plugin_catalog"),+ }}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 46e919a7af..c67bcaedf9 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -64,12 +64,14 @@ func (d *Daemon) gcLoop(ctx context.Context) {// gcStats accumulates byte counts and per-pattern hit counts for one GC cycle.type gcStats struct {- cleaned int // whole task dirs removed by a parent-lifecycle or completed-task policy- orphaned int // whole task dirs removed (no meta / unreachable issue)- skipped int // task dirs left untouched- artifactDirs int // task dirs that had at least one artifact reclaimed- artifactRemoved int // count of removed artifact subdirs- storesReclaimed int // per-conversation Codex session stores reclaimed past their TTL+ cleaned int // whole task dirs removed by a parent-lifecycle or completed-task policy+ orphaned int // whole task dirs removed (no meta / unreachable issue)+ skipped int // task dirs retained, possibly after partial cleanup+ localDirectoriesRetained int // local-directory task roots preserved for daemon logs and output+ codexHomesReclaimed int // expired local-directory Codex homes removed without their linked stores+ artifactDirs int // task dirs that had at least one artifact reclaimed+ artifactRemoved int // count of removed artifact subdirs+ storesReclaimed int // per-conversation Codex session stores reclaimed past their TTL// hermesMemoryStoresReclaimed is counted separately from storesReclaimed:// the two stores hold different things on different TTLs, so folding them// into one number would make either figure unreadable for an operator.@@ -175,11 +177,13 @@ func (d *Daemon) runGC(ctx context.Context) {}}- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.hermesSessionStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 || stats.taskTempDirsReclaimed > 0 || stats.taskRootIndexEntriesReclaimed > 0 {+ if stats.cleaned > 0 || stats.orphaned > 0 || stats.localDirectoriesRetained > 0 || stats.codexHomesReclaimed > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.hermesSessionStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 || stats.taskTempDirsReclaimed > 0 || stats.taskRootIndexEntriesReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,"skipped", stats.skipped,+ "local_directories_retained", stats.localDirectoriesRetained,+ "codex_homes_reclaimed", stats.codexHomesReclaimed,"artifact_dirs", stats.artifactDirs,"artifact_removed", stats.artifactRemoved,"codex_session_stores_reclaimed", stats.storesReclaimed,@@ -217,6 +221,9 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)continue}meta, metaErr := execenv.ReadGCMeta(taskDir)+ if metaErr == nil && meta.LocalDirectory {+ stats.localDirectoriesRetained+++ }if metaErr == nil && meta.Kind == execenv.GCKindIssue && strings.TrimSpace(meta.IssueID) != "" {if workspaceID := strings.TrimSpace(meta.WorkspaceID); workspaceID != "" {issueCandidatesByWorkspace[workspaceID] = append(@@ -226,8 +233,8 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)continue}}- action, chatMeta := d.taskDirGCDecision(ctx, taskDir)- cleanedHere += d.applyGCActionWithChatMeta(ctx, taskDir, action, stats, chatMeta)+ action, meta, removal := d.taskDirGCDecision(ctx, taskDir)+ cleanedHere += d.applyGCActionWithChatMeta(ctx, taskDir, action, stats, meta, removal)}workspaceIDs := make([]string, 0, len(issueCandidatesByWorkspace))for workspaceID := range issueCandidatesByWorkspace {@@ -303,17 +310,17 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, candissueID := strings.TrimSpace(candidate.meta.IssueID)result, ok := results[issueID]if !ok || result.Err != nil {- // No usable answer about the parent issue this cycle, so the task- // data stays. The regenerable Codex cache is still fair game —- // see applyManagedArtifactFallback.- action := d.applyManagedArtifactFallback(candidate.taskDir, candidate.meta, gcActionSkip)+ // No usable parent answer means no whole-directory deletion. Exact+ // caches and expired local Codex homes use task completion instead.+ action := d.applyLocalDirectoryGCOverride(candidate.taskDir, candidate.meta, gcActionSkip)+ action = d.applyManagedArtifactFallback(candidate.taskDir, candidate.meta, action)cleaned += d.applyGCAction(ctx, candidate.taskDir, action, stats)continue}- action := d.gcDecisionIssueResult(candidate.taskDir, candidate.meta, result)- action = d.applyLocalDirectoryGCOverride(candidate.meta, action)+ action, removal := d.gcDecisionIssueResult(candidate.taskDir, candidate.meta, result)+ action = d.applyLocalDirectoryGCOverride(candidate.taskDir, candidate.meta, action)action = d.applyManagedArtifactFallback(candidate.taskDir, candidate.meta, action)- cleaned += d.applyGCAction(ctx, candidate.taskDir, action, stats)+ cleaned += d.applyGCActionWithChatMeta(ctx, candidate.taskDir, action, stats, candidate.meta, removal)}return cleaned}@@ -322,13 +329,17 @@ 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)+ return d.applyGCActionWithChatMeta(ctx, taskDir, action, stats, nil, gcRemovalDetails{})}-func (d *Daemon) applyGCActionWithChatMeta(ctx context.Context, taskDir string, action gcAction, stats *gcStats, chatMeta *execenv.GCMeta) int {+func (d *Daemon) applyGCActionWithChatMeta(ctx context.Context, taskDir string, action gcAction, stats *gcStats, checkedMeta *execenv.GCMeta, removal gcRemovalDetails) int {+ if ctx.Err() != nil {+ stats.skipped+++ return 0+ }if action != gcActionSkip {if _, err := d.gcTaskDirOwner(taskDir); err != nil {- d.logger.Warn("gc: refusing to mutate unowned task directory", "dir", taskDir, "error", err)+ d.warnUnownedTaskDir(taskDir, err)stats.skipped++return 0}@@ -341,44 +352,79 @@ func (d *Daemon) applyGCActionWithChatMeta(ctx context.Context, taskDir string,// Re-read provenance after taking the exclusion lock so a concurrent// reset cannot change ownership between validation and mutation.if _, err := d.gcTaskDirOwner(taskDir); err != nil {- d.logger.Warn("gc: refusing to mutate task directory after ownership changed", "dir", taskDir, "error", err)+ d.warnUnownedTaskDir(taskDir, err)stats.skipped++return 0}}+ bytesBefore := stats.bytesReclaimed+ removedBefore := stats.artifactRemovedswitch action {- case gcActionClean:+ case gcActionClean, gcActionOrphan:bytes, removed := d.cleanTaskDir(taskDir)if !removed {stats.skipped++return 0}- stats.cleaned++- stats.bytesReclaimed += bytes- return 1- case gcActionOrphan:- bytes, removed := d.cleanTaskDir(taskDir)- if !removed {- stats.skipped++- return 0+ if action == gcActionOrphan {+ stats.orphaned+++ } else {+ stats.cleaned++}- stats.orphaned++stats.bytesReclaimed += bytes+ attrs := []any{"dir", taskDir, "bytes_reclaimed", bytes, "reason", removal.reason}+ if removal.retention > 0 {+ attrs = append(attrs, "retention", removal.retention)+ }+ if removal.status != "" {+ attrs = append(attrs, "status", removal.status)+ }+ if checkedMeta != nil {+ attrs = append(attrs, "kind", string(checkedMeta.Kind))+ switch checkedMeta.Kind {+ case execenv.GCKindIssue:+ attrs = append(attrs, "issue", checkedMeta.IssueID)+ case execenv.GCKindChat:+ attrs = append(attrs, "chat_session", checkedMeta.ChatSessionID)+ case execenv.GCKindAutopilotRun:+ attrs = append(attrs, "autopilot_run", checkedMeta.AutopilotRunID)+ case execenv.GCKindQuickCreate:+ attrs = append(attrs, "task", checkedMeta.TaskID)+ }+ }+ d.logger.Info("gc: removed", attrs...)return 1case gcActionCleanArtifacts:removed, bytes, perPattern := d.cleanTaskArtifacts(ctx, taskDir, d.cfg.GCArtifactPatterns)recordArtifactCleanup(stats, removed, bytes, perPattern)stats.skipped++ // task dir itself preservedcase gcActionCleanChatArtifacts:- d.cleanIdleChatArtifacts(ctx, taskDir, chatMeta, stats)+ d.cleanIdleChatArtifacts(ctx, taskDir, checkedMeta, stats)stats.skipped++ // task dir itself preservedcase gcActionCleanManagedArtifacts:removed, bytes, perPattern := d.cleanManagedTaskArtifacts(taskDir)recordArtifactCleanup(stats, removed, bytes, perPattern)stats.skipped++ // task dir itself preserved+ case gcActionCleanCodexHome:+ d.cleanLocalCodexHome(taskDir, stats)+ // The completed-task TTL can be configured shorter than the artifact+ // TTL. Removing the home must not accelerate other artifact cleanup.+ meta, err := execenv.ReadGCMeta(taskDir)+ if err == nil && d.cfg.GCArtifactTTL > 0 && !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL {+ removed, bytes, perPattern := d.cleanTaskArtifacts(ctx, taskDir, d.cfg.GCArtifactPatterns)+ recordArtifactCleanup(stats, removed, bytes, perPattern)+ }+ stats.skipped++ // daemon logs and output are retaineddefault:stats.skipped++}+ if stats.artifactRemoved > removedBefore {+ if meta, err := execenv.ReadGCMeta(taskDir); err == nil && meta.LocalDirectory {+ d.logger.Info("gc: local task directory retained after cache cleanup", "dir", taskDir,+ "reason", "local directory policy preserves daemon logs and output",+ "bytes_reclaimed", stats.bytesReclaimed-bytesBefore)+ }+ }return 0}@@ -397,6 +443,12 @@ func recordArtifactCleanup(stats *gcStats, removed int, bytes int64, perPattern}}+type gcRemovalDetails struct {+ reason string+ status string+ retention time.Duration+}+type gcAction intconst (@@ -406,17 +458,18 @@ const (gcActionCleanArtifacts // task completed long enough ago; drop regenerable artifacts onlygcActionCleanManagedArtifacts // preserve the task and drop exact daemon-managed artifacts onlygcActionCleanChatArtifacts // sweep an idle chat once per completed run and artifact policy+ gcActionCleanCodexHome // expire a local-directory Codex home, preserving the task logbook)// 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)+ action, _, _ := d.taskDirGCDecision(ctx, taskDir)return action}-func (d *Daemon) taskDirGCDecision(ctx context.Context, taskDir string) (gcAction, *execenv.GCMeta) {+func (d *Daemon) taskDirGCDecision(ctx context.Context, taskDir string) (gcAction, *execenv.GCMeta, gcRemovalDetails) {// 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@@ -424,21 +477,22 @@ func (d *Daemon) taskDirGCDecision(ctx context.Context, taskDir string) (gcActio// updated_at), so the regular TTL check alone wouldn't notice the resumed// activity. A directory a running environment serves from is in use too.if d.isActiveEnvRoot(taskDir) || d.environments.servesFrom(taskDir) {- return gcActionSkip, nil+ return gcActionSkip, nil, gcRemovalDetails{}}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, nil+ d.warnUnownedTaskDir(taskDir, ownerErr)+ return gcActionSkip, nil, gcRemovalDetails{}}- return d.orphanByMTime(taskDir, "no meta"), nil+ action, removal := d.orphanByMTime(taskDir, "no meta")+ return action, nil, removal}- action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)- action = d.applyLocalDirectoryGCOverride(meta, action)- return d.applyManagedArtifactFallback(taskDir, meta, action), meta+ action, removal := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)+ action = d.applyLocalDirectoryGCOverride(taskDir, meta, action)+ return d.applyManagedArtifactFallback(taskDir, meta, action), meta, removal}// applyManagedArtifactFallback upgrades a skip into managed-artifact cleanup@@ -481,23 +535,22 @@ func (d *Daemon) applyManagedArtifactFallback(taskDir string, meta *execenv.GCMeif !hasManagedArtifact(taskDir) {return action}- d.logger.Info("gc: eligible for managed artifact cleanup",- "dir", filepath.Base(taskDir),- "kind", string(meta.Kind),- "completed_at", meta.CompletedAt.Format(time.RFC3339),- )return gcActionCleanManagedArtifacts}-func (d *Daemon) applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAction) gcAction {+func (d *Daemon) applyLocalDirectoryGCOverride(taskDir string, meta *execenv.GCMeta, action gcAction) gcAction {if !meta.LocalDirectory {return action}+ if d.localCodexHomeEligible(taskDir, meta) {+ return gcActionCleanCodexHome+ }// local_directory tasks keep their envRoot indefinitely so the user// can inspect output/ and logs/ for forensic context. The WorkDir is// the user's own path and lives outside taskDir. The envRoot contains// the daemon's durable logbook plus regenerable tool caches, so keep the- // former while allowing narrowly scoped cleanup of the latter.+ // former while allowing cache cleanup and, after GCCompletedTaskTTL,+ // removal of the Codex home when its session history is stored elsewhere.//// gcActionClean → demote to artifact-pattern cleanup so envRoot// (and especially the logbook) survives.@@ -525,7 +578,7 @@ func (d *Daemon) applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAc// shouldCleanTaskDirForKind runs the per-Kind dispatch without applying the// local_directory override. Split out so shouldCleanTaskDir can intercept// the result.-func (d *Daemon) shouldCleanTaskDirForKind(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {+func (d *Daemon) shouldCleanTaskDirForKind(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {switch meta.Kind {case execenv.GCKindIssue:return d.gcDecisionIssue(ctx, taskDir, meta)@@ -545,16 +598,15 @@ func (d *Daemon) shouldCleanTaskDirForKind(ctx context.Context, taskDir string,// orphanByMTime returns gcActionOrphan if the directory is older than// GCOrphanTTL, gcActionSkip otherwise. Centralizes the "we have no parent// record signal so just look at the disk" fallback used by every kind.-func (d *Daemon) orphanByMTime(taskDir, reason string) gcAction {+func (d *Daemon) orphanByMTime(taskDir, reason string) (gcAction, gcRemovalDetails) {info, err := os.Stat(taskDir)if err != nil {- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}if time.Since(info.ModTime()) > d.cfg.GCOrphanTTL {- d.logger.Info("gc: orphan directory", "dir", taskDir, "reason", reason, "age", time.Since(info.ModTime()).Round(time.Hour))- return gcActionOrphan+ return gcActionOrphan, gcRemovalDetails{reason: reason, retention: d.cfg.GCOrphanTTL}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// isAccessNotFound detects the 404 returned by gc-check endpoints. The same@@ -566,7 +618,7 @@ func isAccessNotFound(err error) bool {return errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusNotFound}-func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {+func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {if strings.TrimSpace(meta.IssueID) == "" {return d.orphanByMTime(taskDir, "empty issue id")}@@ -580,7 +632,7 @@ func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *exec// can't instantly wipe dirs whose issues are still live.return d.orphanByMTime(taskDir, "issue not accessible")}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}return d.gcDecisionIssueResult(taskDir, meta, IssueGCCheckResult{@@ -592,7 +644,7 @@ func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *exec})}-func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, result IssueGCCheckResult) gcAction {+func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, result IssueGCCheckResult) (gcAction, gcRemovalDetails) {if !result.Found {return d.orphanByMTime(taskDir, "issue not accessible")}@@ -600,14 +652,7 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, resterminal, recognized := issueGCLifecycle(result)if terminal && time.Since(result.UpdatedAt) > d.cfg.GCTTL {- d.logger.Info("gc: eligible for cleanup",- "dir", filepath.Base(taskDir),- "kind", "issue",- "issue", meta.IssueID,- "status", result.Status,- "updated_at", result.UpdatedAt.Format(time.RFC3339),- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "terminal issue retention expired", status: result.Status, retention: d.cfg.GCTTL}}// Operators may opt into a hard retention bound for completed issue-task@@ -623,26 +668,11 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res!meta.CompletedAt.IsZero() &&recognized &&time.Since(meta.CompletedAt) > d.cfg.GCCompletedTaskTTL {- d.logger.Info("gc: completed task eligible for full cleanup",- "dir", filepath.Base(taskDir),- "kind", "issue",- "issue", meta.IssueID,- "status", result.Status,- "completed_at", meta.CompletedAt.Format(time.RFC3339),- "completed_task_ttl", d.cfg.GCCompletedTaskTTL,- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "completed task retention expired", status: result.Status, retention: d.cfg.GCCompletedTaskTTL}}if d.cfg.GCArtifactTTL > 0 && !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL {- d.logger.Info("gc: eligible for artifact cleanup",- "dir", filepath.Base(taskDir),- "kind", "issue",- "issue", meta.IssueID,- "status", result.Status,- "completed_at", meta.CompletedAt.Format(time.RFC3339),- )- return gcActionCleanArtifacts+ return gcActionCleanArtifacts, gcRemovalDetails{}}// Old metadata may not have completed_at. Keep that case conservative:@@ -652,18 +682,11 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res// even when activity below taskDir leaves the root directory mtime stale.if d.cfg.GCArtifactTTL > 0 && meta.CompletedAt.IsZero() {if age, ok := gcMetaFileAge(taskDir); ok && age > d.cfg.GCOrphanTTL {- d.logger.Info("gc: legacy task eligible for managed artifact cleanup",- "dir", filepath.Base(taskDir),- "kind", "issue",- "issue", meta.IssueID,- "status", result.Status,- "age", age.Round(time.Hour),- )- return gcActionCleanManagedArtifacts+ return gcActionCleanManagedArtifacts, gcRemovalDetails{}}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// issueGCLifecycle answers the only two questions GC asks about a parent issue:@@ -716,7 +739,7 @@ func gcMetaFileAge(taskDir string) (time.Duration, bool) {return time.Since(info.ModTime()), true}-func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {+func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {if strings.TrimSpace(meta.ChatSessionID) == "" {return d.orphanByMTime(taskDir, "empty chat session id")}@@ -733,15 +756,9 @@ func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *exece// We don't gate on mtime: every chat_session_id in a meta file// was written by this daemon under its current token, so there// is no cross-workspace probe to defend against.- d.logger.Info("gc: eligible for cleanup",- "dir", filepath.Base(taskDir),- "kind", "chat",- "chat_session", meta.ChatSessionID,- "reason", "session not accessible (hard-deleted)",- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "chat session not accessible (hard-deleted)"}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}switch status.Status {@@ -751,26 +768,19 @@ func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *execeif d.idleChatArtifactEligible(meta) {matcher := newArtifactMatcher(d.cfg.GCArtifactPatterns, execenv.ManagedReclaimableArtifactSubpaths())if !chatArtifactSweepRecorded(taskDir, chatArtifactSweepMarker(meta, matcher)) {- return gcActionCleanChatArtifacts+ return gcActionCleanChatArtifacts, gcRemovalDetails{}}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}case "archived":if time.Since(status.UpdatedAt) > d.cfg.GCTTL {- d.logger.Info("gc: eligible for cleanup",- "dir", filepath.Base(taskDir),- "kind", "chat",- "chat_session", meta.ChatSessionID,- "status", status.Status,- "updated_at", status.UpdatedAt.Format(time.RFC3339),- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "archived chat retention expired", status: status.Status, retention: d.cfg.GCTTL}}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}-func (d *Daemon) gcDecisionAutopilotRun(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {+func (d *Daemon) gcDecisionAutopilotRun(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {if strings.TrimSpace(meta.AutopilotRunID) == "" {return d.orphanByMTime(taskDir, "empty autopilot run id")}@@ -780,7 +790,7 @@ func (d *Daemon) gcDecisionAutopilotRun(ctx context.Context, taskDir string, metif isAccessNotFound(err) {return d.orphanByMTime(taskDir, "autopilot run not accessible")}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// Terminal states per the autopilot_run CHECK constraint:@@ -801,15 +811,9 @@ func (d *Daemon) gcDecisionAutopilotRun(ctx context.Context, taskDir string, met// active-env-root short-circuit in shouldCleanTaskDir still protects a run// that is mid-flight, so this can't pull the rug from under live work.if isAutopilotRunTerminal(status.Status) {- d.logger.Info("gc: eligible for cleanup",- "dir", filepath.Base(taskDir),- "kind", "autopilot_run",- "autopilot_run", meta.AutopilotRunID,- "status", status.Status,- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "autopilot run finished", status: status.Status}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// isAutopilotRunTerminal mirrors the run.status CHECK in@@ -825,7 +829,7 @@ func isAutopilotRunTerminal(status string) bool {}}-func (d *Daemon) gcDecisionQuickCreate(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {+func (d *Daemon) gcDecisionQuickCreate(ctx context.Context, taskDir string, meta *execenv.GCMeta) (gcAction, gcRemovalDetails) {if strings.TrimSpace(meta.TaskID) == "" {return d.orphanByMTime(taskDir, "empty task id")}@@ -838,7 +842,7 @@ func (d *Daemon) gcDecisionQuickCreate(ctx context.Context, taskDir string, meta// tokens — same reasoning as the issue path.return d.orphanByMTime(taskDir, "task not accessible")}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// Quick-create workdirs are not reused by the issue task that@@ -848,15 +852,9 @@ func (d *Daemon) gcDecisionQuickCreate(ctx context.Context, taskDir string, meta// waiting for GCTTL. If the user wants to revisit, the linked issue// has the agent's output already.if isAgentTaskTerminal(status.Status) {- d.logger.Info("gc: eligible for cleanup",- "dir", filepath.Base(taskDir),- "kind", "quick_create",- "task", meta.TaskID,- "status", status.Status,- )- return gcActionClean+ return gcActionClean, gcRemovalDetails{reason: "quick-create task finished", status: status.Status}}- return gcActionSkip+ return gcActionSkip, gcRemovalDetails{}}// isAgentTaskTerminal reports whether a value of agent_task_queue.status@@ -871,6 +869,12 @@ func isAgentTaskTerminal(status string) bool {}}+func (d *Daemon) warnUnownedTaskDir(taskDir string, err error) {+ if _, warned := d.gcUnownedWarnings.LoadOrStore(taskDir, struct{}{}); !warned {+ d.logger.Warn("gc: skipping directory without valid task ownership", "dir", taskDir, "error", err)+ }+}+// gcTaskDirOwner returns authoritative provenance only when both the marker// and its position under WorkspacesRoot agree. Missing GC metadata is not// ownership proof: partially prepared roots have .task_owner, while arbitrary@@ -897,11 +901,12 @@ func (d *Daemon) gcTaskDirOwner(taskDir string) (*execenv.EnvRootOwner, error) {if err := execenv.ValidateEnvRootOwnerPath(d.cfg.WorkspacesRoot, taskDir, validated); err != nil {return nil, err}+ d.gcUnownedWarnings.Delete(taskDir)return &validated, nil}-// cleanTaskDir removes a proven daemon-owned task directory, logs the-// reclaimed bytes, and returns that count for the cycle summary. A failed or+// cleanTaskDir removes a proven daemon-owned task directory and returns the+// reclaimed bytes for the removal log and cycle summary. A failed or// refused removal reports removed=false.func (d *Daemon) cleanTaskDir(taskDir string) (bytes int64, removed bool) {// Measure first, prove ownership second. dirSize walks the entire tree,@@ -918,8 +923,6 @@ func (d *Daemon) cleanTaskDir(taskDir string) (bytes int64, removed bool) {if err := os.RemoveAll(taskDir); err != nil {d.logger.Warn("gc: remove task dir failed", "dir", taskDir, "error", err)return 0, false- } else {- d.logger.Info("gc: removed", "dir", taskDir, "bytes_reclaimed", bytes)}if err := execenv.RemoveRootDirRecord(d.cfg.WorkspacesRoot, taskDir, *owner); err != nil {d.logger.Warn("gc: remove stable task root record failed", "dir", taskDir, "error", err)diff --git a/server/internal/daemon/gc_codex_home.go b/server/internal/daemon/gc_codex_home.gonew file mode 100644index 0000000000..6e442f48b0--- /dev/null+++ b/server/internal/daemon/gc_codex_home.go@@ -0,0 +1,83 @@+package daemon++import (+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/util"+)++func (d *Daemon) localCodexHomeEligible(taskDir string, meta *execenv.GCMeta) bool {+ return meta.LocalDirectory && d.cfg.GCCompletedTaskTTL > 0 &&+ !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCCompletedTaskTTL &&+ localCodexHomeTarget(taskDir) != ""+}++func localCodexHomeTarget(taskDir string) string {+ root, err := filepath.Abs(taskDir)+ if err != nil {+ return ""+ }+ home, ok := managedArtifactTarget(root, "codex-home")+ if !ok {+ return ""+ }+ resolvedRoot, err := util.ResolveSymlinks(root)+ if err != nil {+ return ""+ }+ // Current local-directory tasks link their rollouts to a conversation+ // store outside the env root. Older homes can still own the only copy;+ // retain those homes instead of silently losing resume history.+ for _, name := range []string{"sessions", "archived_sessions"} {+ path := filepath.Join(home, name)+ info, err := os.Lstat(path)+ if errors.Is(err, fs.ErrNotExist) {+ continue+ }+ if err != nil || info.Mode()&linkedDirModes == 0 {+ return ""+ }+ target, err := util.ResolveSymlinks(path)+ if errors.Is(err, fs.ErrNotExist) {+ // The independent session-store TTL can leave a dangling link.+ // No transcript remains behind that link for home GC to destroy.+ continue+ }+ if err != nil {+ return ""+ }+ if isPathWithin(resolvedRoot, target) {+ return ""+ }+ }+ return home+}++// cleanLocalCodexHome runs under the same env-root reservation as other GC+// mutations. Re-read completion in case a task finished during the API lookup.+func (d *Daemon) cleanLocalCodexHome(taskDir string, stats *gcStats) {+ meta, err := execenv.ReadGCMeta(taskDir)+ if err != nil || !d.localCodexHomeEligible(taskDir, meta) {+ return+ }+ home := localCodexHomeTarget(taskDir)+ if home == "" {+ return+ }+ size := dirSize(home)+ if err := os.RemoveAll(home); err != nil {+ d.logger.Warn("gc: remove local Codex home failed", "dir", taskDir, "error", err)+ return+ }+ stats.codexHomesReclaimed+++ stats.bytesReclaimed += size+ d.logger.Info("gc: local Codex home removed", "dir", taskDir,+ "reason", "completed task retention expired; daemon logs and output retained",+ "completed_at", meta.CompletedAt.Format(time.RFC3339),+ "completed_task_ttl", d.cfg.GCCompletedTaskTTL, "bytes_reclaimed", size)+}diff --git a/server/internal/daemon/gc_codex_home_test.go b/server/internal/daemon/gc_codex_home_test.gonew file mode 100644index 0000000000..5115704e92--- /dev/null+++ b/server/internal/daemon/gc_codex_home_test.go@@ -0,0 +1,258 @@+package daemon++import (+ "bytes"+ "context"+ "log/slog"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++func TestGC_LocalCodexHomeRetentionAndResume(t *testing.T) {+ sharedHome := t.TempDir()+ t.Setenv("CODEX_HOME", sharedHome)+ d := newGCTestDaemon(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"issues":[{"id":"issue","found":true,"status":"done","updated_at":"2026-01-01T00:00:00Z"}]}`))+ }))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ params := execenv.PrepareParams{+ WorkspacesRoot: d.cfg.WorkspacesRoot, WorkspaceID: "ws", TaskID: "task-first",+ Provider: "codex", LocalWorkDir: t.TempDir(),+ Task: execenv.TaskContextForEnv{AgentID: "agent", IssueID: "issue"},+ }+ env, err := execenv.Prepare(params, d.logger)+ if err != nil {+ t.Fatal(err)+ }+ const sessionID = "019f59d9-a6aa-7a53-b173-1eccc4b4c873"+ rolloutRel := filepath.Join("sessions", "2026", "07", "13", "rollout-2026-07-13T00-00-00-"+sessionID+".jsonl")+ rollout := []byte(`{"timestamp":"2026-07-13T00:00:00Z","type":"session_meta","payload":{"id":"` + sessionID + `","timestamp":"2026-07-13T00:00:00Z","cwd":"/project","originator":"codex_cli_rs","cli_version":"0.143.0","source":"cli","model_provider":"openai"}}` + "\n")+ writeFile(t, filepath.Join(env.CodexHome, rolloutRel), 0)+ if err := os.WriteFile(filepath.Join(env.CodexHome, rolloutRel), rollout, 0o644); err != nil {+ t.Fatal(err)+ }+ writeFile(t, filepath.Join(env.CodexHome, "state_5.sqlite"), 64)+ writeFile(t, filepath.Join(env.CodexHome, "logs_1.sqlite-wal"), 32)+ writeFile(t, filepath.Join(env.RootDir, "logs", "run.log"), 16)+ writeFile(t, filepath.Join(env.RootDir, "output", "result.md"), 8)+ writeFile(t, filepath.Join(params.LocalWorkDir, "node_modules", "keep"), 4)+ meta := execenv.GCMeta{Kind: execenv.GCKindIssue, IssueID: "issue", WorkspaceID: "ws", TaskID: params.TaskID,+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour)}+ mustWriteMeta(t, env.RootDir, meta)+ wantBytes := dirSize(env.CodexHome)+ stats := &gcStats{}+ d.gcWorkspace(context.Background(), filepath.Dir(env.RootDir), stats)+ assertGone(t, env.RootDir, "codex-home")+ assertKept(t, env.RootDir, "logs/run.log", "output/result.md", ".gc_meta.json", ".task_owner")+ assertKept(t, params.LocalWorkDir, "node_modules/keep")+ if stats.codexHomesReclaimed != 1 || stats.localDirectoriesRetained != 1 || stats.bytesReclaimed != wantBytes {+ t.Fatalf("stats = %+v, want one reclaimed home and %d bytes excluding linked session store", stats, wantBytes)+ }++ // Local-directory follow-ups get a new task root. Preparing it must restore+ // the old rollout from the conversation store after GC removed the old home.+ params.TaskID = "task-second"+ next, err := execenv.Prepare(params, d.logger)+ if err != nil {+ t.Fatal(err)+ }+ if !execenv.CodexResumeRolloutPresent(next.CodexHome, sessionID) {+ t.Fatal("follow-up cannot resume the retained rollout after codex-home GC")+ }+ data, err := os.ReadFile(filepath.Join(next.CodexHome, rolloutRel))+ if err != nil || !bytes.Equal(data, rollout) {+ t.Fatalf("rollout changed after GC: size=%d err=%v", len(data), err)+ }+}++func TestGC_LocalCodexHomeRetentionGuards(t *testing.T) {+ for _, name := range []string{"expired", "recent", "disabled", "no completion", "active", "unowned", "linked home", "local sessions", "archived sessions", "sessions inside root"} {+ t.Run(name, func(t *testing.T) {+ d := newGCTestDaemon(t, chatGCMux("chat", "active"))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ // Home retention is independent of the shorter artifact TTL.+ d.cfg.GCArtifactTTL = 0+ meta := execenv.GCMeta{Kind: execenv.GCKindChat, ChatSessionID: "chat", WorkspaceID: "ws",+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour)}+ if name == "recent" {+ meta.CompletedAt = time.Now().Add(-13 * 24 * time.Hour)+ }+ if name == "no completion" {+ meta.CompletedAt = time.Time{}+ }+ if name == "disabled" {+ d.cfg.GCCompletedTaskTTL = 0+ }+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &meta)+ writeFile(t, filepath.Join(taskDir, "codex-home", "state_5.sqlite"), 32)+ if name == "active" {+ defer d.markActiveEnvRoot(taskDir)()+ }+ if name == "unowned" {+ if err := os.Remove(filepath.Join(taskDir, ".task_owner")); err != nil {+ t.Fatal(err)+ }+ }+ if name == "local sessions" {+ writeFile(t, filepath.Join(taskDir, "codex-home/sessions/rollout.jsonl"), 8)+ }+ if name == "archived sessions" {+ writeFile(t, filepath.Join(taskDir, "codex-home/archived_sessions/rollout.jsonl"), 8)+ }+ if name == "sessions inside root" {+ store := filepath.Join(taskDir, "conversation")+ writeFile(t, filepath.Join(store, "rollout.jsonl"), 8)+ if err := os.Symlink(store, filepath.Join(taskDir, "codex-home/sessions")); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ }+ if name == "linked home" {+ outside := t.TempDir()+ if err := os.Rename(filepath.Join(taskDir, "codex-home"), filepath.Join(outside, "home")); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(outside, "home"), filepath.Join(taskDir, "codex-home")); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ }+ stats := &gcStats{}+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), stats)+ if name == "expired" {+ assertGone(t, taskDir, "codex-home")+ } else {+ assertKept(t, taskDir, "codex-home/state_5.sqlite")+ }+ assertKept(t, taskDir, ".gc_meta.json")+ })+ }+}++func TestGC_LocalRetentionLogsActualCleanup(t *testing.T) {+ d := newGCTestDaemon(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(`{"issues":[{"id":"issue","found":true,"status":"done","updated_at":"2026-01-01T00:00:00Z"}]}`))+ }))+ var logs bytes.Buffer+ d.logger = slog.New(slog.NewTextHandler(&logs, nil))+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &execenv.GCMeta{+ Kind: execenv.GCKindIssue, IssueID: "issue", WorkspaceID: "ws", LocalDirectory: true,+ CompletedAt: time.Now().Add(-24 * time.Hour),+ })+ writeFile(t, filepath.Join(taskDir, "codex-home/cache/remote_plugin_catalog/catalog.json"), 64)+ d.runGC(context.Background())+ assertGone(t, taskDir, "codex-home/cache/remote_plugin_catalog")+ if strings.Contains(logs.String(), "eligible for cleanup") {+ t.Fatalf("misleading full cleanup log: %s", &logs)+ }+ if !strings.Contains(logs.String(), "local_directories_retained=1") {+ t.Fatalf("missing retention summary: %s", &logs)+ }+ logs.Reset()+ d.runGC(context.Background())+ if strings.Contains(logs.String(), "eligible for") || strings.Contains(logs.String(), "artifact removed") {+ t.Fatalf("idle cycle repeated cleanup logs: %s", &logs)+ }+}++func TestGC_LocalCodexHomeRechecksActivity(t *testing.T) {+ t.Parallel()+ for _, name := range []string{"active after decision", "completed again", "cancelled"} {+ t.Run(name, func(t *testing.T) {+ d := newGCTestDaemon(t, chatGCMux("chat", "active"))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ meta := execenv.GCMeta{Kind: execenv.GCKindChat, ChatSessionID: "chat", WorkspaceID: "ws",+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour)}+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &meta)+ writeFile(t, filepath.Join(taskDir, "codex-home/state_5.sqlite"), 32)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ action := d.shouldCleanTaskDir(ctx, taskDir)+ if action != gcActionCleanCodexHome {+ t.Fatalf("action = %v, want home cleanup", action)+ }+ switch name {+ case "active after decision":+ defer d.markActiveEnvRoot(taskDir)()+ case "completed again":+ meta.CompletedAt = time.Now()+ mustWriteMeta(t, taskDir, meta)+ case "cancelled":+ cancel()+ }+ stats := &gcStats{}+ d.applyGCAction(ctx, taskDir, action, stats)+ assertKept(t, taskDir, "codex-home/state_5.sqlite")+ if stats.codexHomesReclaimed != 0 {+ t.Fatalf("unexpected cleanup: %+v", stats)+ }+ })+ }+}++func TestGC_UnownedDirectoryWarnsOnce(t *testing.T) {+ t.Parallel()+ d := newGCTestDaemon(t, http.NewServeMux())+ var logs bytes.Buffer+ d.logger = slog.New(slog.NewTextHandler(&logs, nil))+ taskDir := filepath.Join(d.cfg.WorkspacesRoot, "ws", "user-directory")+ writeFile(t, filepath.Join(taskDir, "keep"), 8)+ for i := 0; i < 2; i++ {+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ }+ assertKept(t, taskDir, "keep")+ if got := strings.Count(logs.String(), "level=WARN"); got != 1 {+ t.Fatalf("warnings = %d, want 1: %s", got, &logs)+ }+}++func TestGC_LocalCodexHomeAfterSessionStoreRemoval(t *testing.T) {+ t.Parallel()+ for _, sessionDir := range []string{"sessions", "archived_sessions"} {+ t.Run(sessionDir, func(t *testing.T) {+ d := newGCTestDaemon(t, chatGCMux("chat", "active"))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ d.cfg.GCArtifactTTL = 0+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: "chat", WorkspaceID: "ws",+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour),+ })+ writeFile(t, filepath.Join(taskDir, "codex-home/state_5.sqlite"), 32)+ store := filepath.Join(t.TempDir(), "conversation")+ writeFile(t, filepath.Join(store, "rollout.jsonl"), 64)+ if err := os.Symlink(store, filepath.Join(taskDir, "codex-home", sessionDir)); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ // The independent session TTL expires before home retention.+ if err := os.RemoveAll(store); err != nil {+ t.Fatal(err)+ }+ stats := &gcStats{}+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), stats)+ assertGone(t, taskDir, "codex-home")+ if stats.codexHomesReclaimed != 1 || stats.bytesReclaimed != 32 {+ t.Fatalf("expired session store blocked home reclamation: %+v", stats)+ }+ })+ }+}++func TestGC_LocalCodexHomeKeepsUnresolvableSessionLink(t *testing.T) {+ t.Parallel()+ d := newGCTestDaemon(t, chatGCMux("chat", "active"))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: "chat", WorkspaceID: "ws",+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour),+ })+ writeFile(t, filepath.Join(taskDir, "codex-home/state_5.sqlite"), 32)+ if err := os.Symlink("sessions", filepath.Join(taskDir, "codex-home/sessions")); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ assertKept(t, taskDir, "codex-home/state_5.sqlite")+}diff --git a/server/internal/daemon/gc_junction_windows_test.go b/server/internal/daemon/gc_junction_windows_test.goindex a7c06fb2a4..103a80dd6c 100644--- a/server/internal/daemon/gc_junction_windows_test.go+++ b/server/internal/daemon/gc_junction_windows_test.go@@ -9,6 +9,9 @@ import ("os/exec""path/filepath""testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv")// The per-task codex-home links shared user content into the task directory —@@ -94,3 +97,47 @@ func TestTaskSize_DoesNotCountDirectoryJunction(t *testing.T) {t.Errorf("artifacts = %d, want 0", artifacts)}}++func TestGC_LocalCodexHomePreservesJunctionTargets(t *testing.T) {+ for _, name := range []string{"live store", "expired store", "store inside task root", "junctioned workspaces root"} {+ t.Run(name, func(t *testing.T) {+ d := newGCTestDaemon(t, chatGCMux("chat", "active"))+ d.cfg.GCCompletedTaskTTL = DefaultGCCompletedTaskTTL+ if name == "junctioned workspaces root" {+ d.cfg.WorkspacesRoot, _ = junctionedWorkspacesRoot(t)+ }+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-task", &execenv.GCMeta{+ Kind: execenv.GCKindChat, ChatSessionID: "chat", WorkspaceID: "ws",+ LocalDirectory: true, CompletedAt: time.Now().Add(-15 * 24 * time.Hour),+ })+ writeFile(t, filepath.Join(taskDir, "codex-home/state_5.sqlite"), 32)+ store, skills, plugins := filepath.Join(t.TempDir(), "conversation"), t.TempDir(), t.TempDir()+ if name == "store inside task root" {+ store = filepath.Join(taskDir, "conversation")+ }+ for _, target := range []string{store, skills, plugins} {+ writeFile(t, filepath.Join(target, "keep"), 64)+ }+ createJunction(t, store, filepath.Join(taskDir, "codex-home/sessions"))+ createJunction(t, skills, filepath.Join(taskDir, "codex-home/skills"))+ createJunction(t, plugins, filepath.Join(taskDir, "codex-home/plugins/cache"))+ if name == "expired store" {+ if err := os.RemoveAll(store); err != nil {+ t.Fatal(err)+ }+ }+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ if name == "store inside task root" {+ assertKept(t, taskDir, "codex-home/state_5.sqlite")+ } else {+ assertGone(t, taskDir, "codex-home")+ }+ for _, target := range []string{skills, plugins} {+ assertKept(t, target, "keep")+ }+ if name != "expired store" {+ assertKept(t, store, "keep")+ }+ })+ }+}diff --git a/server/internal/daemon/gc_managed_artifact_test.go b/server/internal/daemon/gc_managed_artifact_test.goindex cbea9251d4..491feeb6d9 100644--- a/server/internal/daemon/gc_managed_artifact_test.go+++ b/server/internal/daemon/gc_managed_artifact_test.go@@ -161,7 +161,7 @@ func TestGC_IdleChatSkipsChangedCompletion(t *testing.T) {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)+ action, checked, removal := d.taskDirGCDecision(ctx, taskDir)if action != gcActionCleanChatArtifacts {t.Fatalf("expected initial completion to be eligible, got %v", action)}@@ -170,7 +170,7 @@ func TestGC_IdleChatSkipsChangedCompletion(t *testing.T) {// 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)+ d.applyGCActionWithChatMeta(ctx, taskDir, action, &gcStats{}, checked, removal)assertKept(t, taskDir, chatCacheFile)assertGone(t, taskDir, chatArtifactSweepFile)d.gcWorkspace(ctx, filepath.Dir(taskDir), &gcStats{})diff --git a/server/internal/daemon/gc_plugin_cache_test.go b/server/internal/daemon/gc_plugin_cache_test.gonew file mode 100644index 0000000000..4ee7452ad7--- /dev/null+++ b/server/internal/daemon/gc_plugin_cache_test.go@@ -0,0 +1,71 @@+package daemon++import (+ "context"+ "net/http"+ "os"+ "path/filepath"+ "testing"+)++func TestGC_PluginCachesAreExactReclaimablePaths(t *testing.T) {+ t.Parallel()+ for _, managedOnly := range []bool{false, true} {+ name := "artifact sweep"+ if managedOnly {+ name = "managed only"+ }+ t.Run(name, func(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := t.TempDir()+ for _, rel := range []string{"codex-home/.tmp/plugins", "codex-home/.tmp/marketplaces", "codex-home/cache/remote_plugin_catalog"} {+ writeFile(t, filepath.Join(taskDir, rel, "cache.json"), 64)+ }+ kept := []string{"codex-home/plugins/cache/keep", "codex-home/state_5.sqlite", "codex-home/state_5.sqlite-wal", "codex-home/logs_1.sqlite-wal", "codex-home/session_index.jsonl", "codex-home/.tmp/other/keep", "workdir/repo/cache/remote_plugin_catalog/keep", "workdir/repo/.tmp/plugins/keep"}+ for _, rel := range kept {+ writeFile(t, filepath.Join(taskDir, rel), 8)+ }+ var removed int+ var size int64+ if managedOnly {+ removed, size, _ = d.cleanManagedTaskArtifacts(taskDir)+ } else {+ removed, size, _ = d.cleanTaskArtifacts(context.Background(), taskDir, nil)+ }+ if removed != 3 || size != 192 {+ t.Fatalf("cleanup = %d paths, %d bytes; want 3, 192", removed, size)+ }+ assertKept(t, taskDir, kept...)+ if hasManagedArtifact(taskDir) {+ t.Fatal("reclaimed caches must not trigger another sweep")+ }+ })+ }+}++func TestGC_PluginCachesDoNotFollowLinks(t *testing.T) {+ t.Parallel()+ for _, rel := range []string{"codex-home", "codex-home/.tmp", "codex-home/.tmp/plugins", "codex-home/.tmp/marketplaces", "codex-home/cache", "codex-home/cache/remote_plugin_catalog"} {+ t.Run(rel, func(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir, outside := t.TempDir(), t.TempDir()+ for _, keep := range []string{"keep", ".tmp/plugins/keep", ".tmp/marketplaces/keep", "plugins/keep", "marketplaces/keep", "cache/remote_plugin_catalog/keep", "remote_plugin_catalog/keep"} {+ writeFile(t, filepath.Join(outside, keep), 8)+ }+ link := filepath.Join(taskDir, rel)+ if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, link); err != nil {+ t.Skipf("symlink unavailable: %v", err)+ }+ if removed, _, _ := d.cleanManagedTaskArtifacts(taskDir); removed != 0 {+ t.Fatalf("removed %d paths through a link", removed)+ }+ if removed, _, _ := d.cleanTaskArtifacts(context.Background(), taskDir, nil); removed != 0 {+ t.Fatalf("sweep removed %d paths through a link", removed)+ }+ assertKept(t, outside, "keep", ".tmp/plugins/keep", ".tmp/marketplaces/keep", "plugins/keep", "marketplaces/keep", "cache/remote_plugin_catalog/keep", "remote_plugin_catalog/keep")+ })+ }+}diff --git a/server/internal/daemon/gc_removal_logging_test.go b/server/internal/daemon/gc_removal_logging_test.gonew file mode 100644index 0000000000..4ce5c078be--- /dev/null+++ b/server/internal/daemon/gc_removal_logging_test.go@@ -0,0 +1,97 @@+package daemon++import (+ "bytes"+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++func TestGC_RemovalLogsLifecycleReason(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name, status, reason string+ kind execenv.GCMetaKind+ retention time.Duration+ singleIssue, missingMeta, notFound bool+ }{+ {name: "terminal issue batch", kind: execenv.GCKindIssue, status: "done", reason: "terminal issue retention expired", retention: 24 * time.Hour},+ {name: "terminal issue single", kind: execenv.GCKindIssue, singleIssue: true, status: "done", reason: "terminal issue retention expired", retention: 24 * time.Hour},+ {name: "completed open issue", kind: execenv.GCKindIssue, status: "in_review", reason: "completed task retention expired", retention: DefaultGCCompletedTaskTTL},+ {name: "orphan without metadata", missingMeta: true, reason: "no meta", retention: 72 * time.Hour},+ {name: "inaccessible issue", kind: execenv.GCKindIssue, notFound: true, reason: "issue not accessible", retention: 72 * time.Hour},+ {name: "archived chat", kind: execenv.GCKindChat, status: "archived", reason: "archived chat retention expired", retention: 24 * time.Hour},+ {name: "deleted chat", kind: execenv.GCKindChat, notFound: true, reason: "chat session not accessible (hard-deleted)"},+ {name: "autopilot", kind: execenv.GCKindAutopilotRun, status: "completed", reason: "autopilot run finished"},+ {name: "quick create", kind: execenv.GCKindQuickCreate, status: "completed", reason: "quick-create task finished"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newGCTestDaemon(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if tc.notFound {+ http.NotFound(w, r)+ return+ }+ if strings.Contains(r.URL.Path, "/workspaces/") {+ _ = json.NewEncoder(w).Encode(map[string]any{"issues": []IssueGCCheckResult{{ID: "issue", Found: true, Status: tc.status, UpdatedAt: time.Now().Add(-48 * time.Hour)}}})+ } else {+ _ = json.NewEncoder(w).Encode(map[string]any{"status": tc.status, "updated_at": time.Now().Add(-48 * time.Hour)})+ }+ }))+ d.cfg.GCTTL, d.cfg.GCOrphanTTL, d.cfg.GCCompletedTaskTTL = 24*time.Hour, 72*time.Hour, DefaultGCCompletedTaskTTL+ var logs bytes.Buffer+ d.logger = slog.New(slog.NewJSONHandler(&logs, nil))+ meta := &execenv.GCMeta{Kind: tc.kind, WorkspaceID: "ws", IssueID: "issue", ChatSessionID: "chat", AutopilotRunID: "run", TaskID: "task",+ CompletedAt: time.Now().Add(-15 * 24 * time.Hour)}+ if tc.singleIssue {+ meta.WorkspaceID = ""+ }+ if tc.missingMeta {+ meta = nil+ }+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "owned-task", meta)+ writeFile(t, filepath.Join(taskDir, "output/result.md"), 8)+ past := time.Now().Add(-73 * time.Hour)+ if err := os.Chtimes(taskDir, past, past); err != nil {+ t.Fatal(err)+ }+ d.gcWorkspace(context.Background(), filepath.Dir(taskDir), &gcStats{})+ if _, err := os.Stat(taskDir); !os.IsNotExist(err) {+ t.Fatalf("task dir not removed: %v", err)+ }+ removed := 0+ for _, line := range strings.Split(strings.TrimSpace(logs.String()), "\n") {+ var record map[string]any+ if err := json.Unmarshal([]byte(line), &record); err != nil {+ t.Fatal(err)+ }+ if record["msg"] != "gc: removed" {+ continue+ }+ removed+++ if record["reason"] != tc.reason {+ t.Fatalf("removal reason = %v, want %s", record["reason"], tc.reason)+ }+ if tc.status != "" && record["status"] != tc.status {+ t.Fatalf("missing observed status: %v", record)+ }+ if tc.retention > 0 && record["retention"] != float64(tc.retention) {+ t.Fatalf("missing retention duration: %v", record)+ }+ if tc.kind == execenv.GCKindIssue && record["issue"] != "issue" {+ t.Fatalf("missing issue identity: %v", record)+ }+ }+ if removed != 1 {+ t.Fatalf("removal log count = %d, want 1: %s", removed, &logs)+ }+ })+ }+}