Skip to content

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

Go

feat(cli): persist daemon log rotation policy per profile (BOYF-1051, MUL-9728) (#11077)

沙雕的小鱼儿 boyfeiyu6b70cf657641
diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdx
index 74b81597f2..3d595f5e8f 100644
--- a/apps/docs/content/docs/environment-variables.fr.mdx
+++ b/apps/docs/content/docs/environment-variables.fr.mdx
@@ -287,13 +287,13 @@ Le daemon journalise au niveau `debug` par défaut. Définissez `LOG_LEVEL` (`de
Quand le daemon tourne en arrière-plan (sans terminal attaché), il écrit ses journaux dans `~/.multica/daemon.log`, ou `~/.multica/profiles/<name>/daemon.log` pour un profil nommé, avec une rotation par taille ; les fichiers issus de la rotation sont compressés en gzip.
-| Variable | Valeur par défaut | Description |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | Taille en Mo à partir de laquelle `daemon.log` tourne |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | Nombre maximal de fichiers tournés conservés |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | Nombre de jours de conservation des fichiers tournés |
+| Variable | Clé du profil | Valeur par défaut | Description |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | Taille en Mo à partir de laquelle `daemon.log` tourne |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | Nombre maximal de fichiers tournés conservés |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | Nombre de jours de conservation des fichiers tournés |
-Les trois attendent un entier positif ; `0`, une valeur négative ou illisible reprend la valeur par défaut au lieu de signifier « illimité ». Un fichier tourné est supprimé dès que la limite de nombre ou d'âge est atteinte. La sortie des plantages va dans `daemon.err.log`, dans le même répertoire, renommé en `daemon.err.log.1` au démarrage s'il dépasse 5 Mo.
+Les trois valeurs doivent être des entiers positifs. Enregistrez les clés avec `multica --profile dev config set <key> <value>` ; `config show` affiche les valeurs enregistrées. Passez `""` pour effacer une clé. Les changements prennent effet au prochain démarrage ou redémarrage du daemon. Les variables d’environnement valides priment sur le profil. Une valeur absente, vide, nulle, négative, mal formée ou trop grande utilise la valeur valide du profil, puis la valeur par défaut du tableau. La taille et le nombre de jours doivent aussi permettre une conversion sans dépassement en octets et en durée ; `config set` refuse les valeurs invalides. Zéro ne désactive pas la rétention. Un fichier tourné est supprimé dès que la limite de nombre ou d’âge est atteinte. La sortie des plantages va dans `daemon.err.log`, dans le même répertoire, renommé en `daemon.err.log.1` au démarrage s’il dépasse 5 Mo.
### Chemins, modèles et arguments par outil
@@ -396,6 +396,9 @@ Clés prises en charge :
| `disable_auto_update` | suit l'environnement | `true` désactive la mise à jour automatique ; `false` efface la surcharge locale et revient à la variable d'environnement ou à la valeur par défaut |
| `auto_update_check_interval` | `6h` | Intervalle de vérification des mises à jour |
| `disable_auto_reload` | suit l'environnement | `true` empêche le daemon de suivre un binaire remplacé sur disque ; `false` efface la surcharge locale. Résolu indépendamment de `disable_auto_update` |
+| `daemon_log_max_size_mb` | `20` | Taille en Mo à partir de laquelle `daemon.log` tourne ; voir [Journaux du daemon](#daemon-logs) |
+| `daemon_log_max_backups` | `5` | Nombre maximal de fichiers de journaux tournés conservés |
+| `daemon_log_max_age_days` | `30` | Nombre de jours de conservation des fichiers tournés |
Quelques règles concernant les valeurs :
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 06ce8a67e4..51c9cd28a8 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -290,13 +290,13 @@ API key と base URL の両方が空の場合、このレイヤーは無効に
デーモンがバックグラウンドで(ターミナルにつながずに)動いているとき、ログは `~/.multica/daemon.log`(名前付きプロファイルでは `~/.multica/profiles/<name>/daemon.log`)に書かれ、サイズでローテーションされます。ローテーション後のファイルは gzip で圧縮されます。
-| 変数 | デフォルト | 説明 |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | `daemon.log` をローテーションするサイズ(MB) |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | 残すローテーション済みファイルの最大数 |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | ローテーション済みファイルを残す日数 |
+| 変数 | プロファイル設定キー | デフォルト | 説明 |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | `daemon.log` をローテーションするサイズ(MB) |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | 残すローテーション済みファイルの最大数 |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | ローテーション済みファイルを残す日数 |
-3 つとも正の整数を取ります。`0`、負の数、解釈できない値はデフォルトとして扱われ、「無制限」にはなりません。ローテーション済みファイルは、個数と日数のどちらかの上限に先に達した時点で削除されます。クラッシュ時の出力は同じディレクトリの `daemon.err.log` に書かれ、起動時に 5 MB を超えていれば `daemon.err.log.1` に名前が変わります。
+3 つとも正の整数を取ります。`multica --profile dev config set <key> <value>` で保存し、`config show` で保存値を確認します。`""` を渡すと設定を解除できます。変更は次回のデーモン起動または再起動時に反映されます。有効な環境変数はプロファイルより優先されます。未設定、空白、ゼロ、負数、不正な形式、オーバーフローの場合は有効なプロファイル値、それもなければ表のデフォルト値を使います。サイズと日数はバイト数や時間への変換でもオーバーフローしてはならず、`config set` は不正な値を拒否します。ゼロで保持制限を無効にはできません。ローテーション済みファイルは、個数と日数のどちらかの上限に先に達した時点で削除されます。クラッシュ時の出力は同じディレクトリの `daemon.err.log` に書かれ、起動時に 5 MB を超えていれば `daemon.err.log.1` に名前が変わります。
### ツールごとのパス、モデル、引数
@@ -399,6 +399,9 @@ multica config show
| `disable_auto_update` | 環境に従う | `true` で自動更新を無効化。`false` はローカルの上書きをクリアし、環境変数またはデフォルトに戻します |
| `auto_update_check_interval` | `6h` | 更新チェックの間隔 |
| `disable_auto_reload` | 環境に従う | `true` でディスク上の置き換えへの追従を停止。`false` はローカルの上書きをクリア。`disable_auto_update` とは別に解決されます |
+| `daemon_log_max_size_mb` | `20` | `daemon.log` をローテーションするサイズ(MB)。[デーモンのログ](#daemon-logs)を参照 |
+| `daemon_log_max_backups` | `5` | 残すローテーション済みファイルの最大数 |
+| `daemon_log_max_age_days` | `30` | ローテーション済みファイルを残す日数 |
値のルール:
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 094493e4b8..49a601ea44 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -290,13 +290,13 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스
데몬이 백그라운드에서(터미널에 연결되지 않은 채) 실행될 때 로그는 `~/.multica/daemon.log`(이름 있는 프로필은 `~/.multica/profiles/<name>/daemon.log`)에 기록되고 크기에 따라 순환됩니다. 순환된 파일은 gzip으로 압축됩니다.
-| 변수 | 기본값 | 설명 |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | `daemon.log`를 순환할 크기(MB) |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | 보관할 순환 파일의 최대 개수 |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | 순환 파일을 보관할 일수 |
+| 변수 | 프로필 설정 키 | 기본값 | 설명 |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | `daemon.log`를 순환할 크기(MB) |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | 보관할 순환 파일의 최대 개수 |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | 순환 파일을 보관할 일수 |
-세 변수 모두 양의 정수를 받습니다. `0`, 음수, 해석할 수 없는 값은 기본값으로 처리되며 "무제한"이 되지 않습니다. 순환 파일은 개수와 일수 중 먼저 도달한 한도에 따라 삭제됩니다. 충돌 출력은 같은 디렉터리의 `daemon.err.log`에 기록되며, 시작할 때 5MB를 넘으면 `daemon.err.log.1`로 이름이 바뀝니다.
+세 값 모두 양의 정수를 받습니다. `multica --profile dev config set <key> <value>`로 저장하고 `config show`로 저장된 값을 확인합니다. `""`를 전달하면 설정을 지웁니다. 변경 사항은 다음 데몬 시작 또는 재시작에 적용됩니다. 유효한 환경 변수는 프로필보다 우선합니다. 미설정, 공백, 0, 음수, 잘못된 형식 또는 오버플로 값은 유효한 프로필 값으로, 그 값도 없으면 표의 기본값으로 돌아갑니다. 크기와 일수는 바이트와 시간으로 변환할 때도 오버플로가 없어야 하며, `config set`은 잘못된 값을 거부합니다. 0으로 보관 제한을 해제할 수 없습니다. 순환 파일은 개수와 일수 중 먼저 도달한 한도에 따라 삭제됩니다. 충돌 출력은 같은 디렉터리의 `daemon.err.log`에 기록되며, 시작할 때 5MB를 넘으면 `daemon.err.log.1`로 이름이 바뀝니다.
### 도구별 경로, 모델, 인수
@@ -399,6 +399,9 @@ multica config show
| `disable_auto_update` | 환경을 따름 | `true`는 자동 업데이트를 끔. `false`는 로컬 덮어쓰기를 지우고 환경 변수 또는 기본값으로 복귀 |
| `auto_update_check_interval` | `6h` | 업데이트 확인 간격 |
| `disable_auto_reload` | 환경을 따름 | `true`는 디스크에서 교체된 바이너리 추적을 끔. `false`는 로컬 덮어쓰기를 지움. `disable_auto_update`와 별도로 해석됨 |
+| `daemon_log_max_size_mb` | `20` | `daemon.log`를 순환할 크기(MB). [데몬 로그](#daemon-logs) 참고 |
+| `daemon_log_max_backups` | `5` | 보관할 순환 파일의 최대 개수 |
+| `daemon_log_max_age_days` | `30` | 순환 파일을 보관할 일수 |
값에는 다음 규칙이 적용됩니다.
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 60a7a485df..5025d107ad 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -296,13 +296,13 @@ The daemon logs at `debug` by default. Set `LOG_LEVEL` (`debug`, `info`, `warn`
When the daemon runs in the background (not attached to a terminal), it writes logs to `~/.multica/daemon.log`, or `~/.multica/profiles/<name>/daemon.log` for a named profile, rotating by size and compressing rotated files with gzip.
-| Variable | Default | Description |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | Size in MB at which `daemon.log` rotates |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | Maximum number of rotated files kept |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | Days rotated files are kept |
+| Variable | Profile key | Default | Description |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | Size in MB at which `daemon.log` rotates |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | Maximum number of rotated files kept |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | Days rotated files are kept |
-All three take a positive integer; `0`, a negative number, or an unparsable value falls back to the default rather than meaning "unlimited". A rotated file is deleted as soon as either the count or the age limit is reached. Crash output goes to `daemon.err.log` in the same directory, which is renamed to `daemon.err.log.1` at startup once it exceeds 5 MB.
+All three accept positive integers. Set the profile keys with `multica --profile dev config set <key> <value>`; `config show` displays the saved values. Pass `""` to clear a key. Changes apply on the next daemon start or restart. Valid environment values override the saved profile; unset, blank, zero, negative, malformed or overflowing values fall back to a valid profile value, then the defaults above. Size and age values must also fit their byte and duration conversions; `config set` rejects invalid values. Retention cannot be disabled with zero. A rotated file is deleted as soon as either the count or the age limit is reached. Crash output goes to `daemon.err.log` in the same directory, which is renamed to `daemon.err.log.1` at startup once it exceeds 5 MB.
### Per-tool paths, models, and arguments
@@ -405,6 +405,9 @@ Supported keys:
| `disable_auto_update` | follows environment | `true` turns auto-update off; `false` clears the local override and returns to the env var or default |
| `auto_update_check_interval` | `6h` | Update check interval |
| `disable_auto_reload` | follows environment | `true` stops the daemon following a binary replaced on disk; `false` clears the local override. Resolved separately from `disable_auto_update` |
+| `daemon_log_max_size_mb` | `20` | Size in MB at which `daemon.log` rotates; see [Daemon logs](#daemon-logs) |
+| `daemon_log_max_backups` | `5` | Maximum number of rotated log files kept |
+| `daemon_log_max_age_days` | `30` | Days rotated log files are kept |
A few value rules:
diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
index c14f9669dd..295139bc2f 100644
--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx
+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx
@@ -286,13 +286,13 @@ API key 與 base URL 都為空時,這一層關閉,不會發出任何上游
守護程序在後臺執行(不連著終端)時,日誌寫入 `~/.multica/daemon.log`,命名 profile 為 `~/.multica/profiles/<name>/daemon.log`,並按大小輪轉,輪轉出的檔案用 gzip 壓縮。
-| 變數 | 預設值 | 說明 |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | `daemon.log` 達到多少 MB 時輪轉 |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | 最多保留幾個輪轉檔案 |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | 輪轉檔案保留的天數 |
+| 變數 | Profile 設定鍵 | 預設值 | 說明 |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | `daemon.log` 達到多少 MB 時輪轉 |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | 最多保留幾個輪轉檔案 |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | 輪轉檔案保留的天數 |
-三個變數都要求正整數;`0`、負數或無法解析的值按預設值處理,不會變成"不限制"。保留數量和天數哪個先到就按哪個刪除。崩潰輸出寫在同目錄的 `daemon.err.log`,啟動時超過 5 MB 就改名為 `daemon.err.log.1`。
+三個參數都要求正整數。用 `multica --profile dev config set <key> <value>` 儲存,`config show` 查看已儲存值,傳入 `""` 清除對應設定。修改在下次守護行程啟動或重新啟動時生效。有效環境變數優先於 profile;未設定、空白、零、負數、格式錯誤或溢出的環境值會回退到有效 profile 值,再回退到表中預設值。大小和天數還必須能安全轉換為位元組和時長;`config set` 會拒絕無效值。零不能關閉保留限制。保留數量和天數哪個先到就按哪個刪除。崩潰輸出寫在同目錄的 `daemon.err.log`,啟動時超過 5 MB 就改名為 `daemon.err.log.1`。
### 各 AI 程式設計工具的路徑、模型與引數
@@ -395,6 +395,9 @@ multica config show
| `disable_auto_update` | 跟隨環境 | `true` 關閉自動更新;`false` 清除本地覆蓋,回到環境變數或預設 |
| `auto_update_check_interval` | `6h` | 檢查更新的間隔 |
| `disable_auto_reload` | 跟隨環境 | `true` 讓守護程序不再跟隨磁碟上被替換的二進位制;`false` 清除本地覆蓋。與 `disable_auto_update` 分開解析 |
+| `daemon_log_max_size_mb` | `20` | `daemon.log` 達到多少 MB 時輪轉,見[守護程序日誌](#daemon-logs) |
+| `daemon_log_max_backups` | `5` | 最多保留幾個輪轉檔案 |
+| `daemon_log_max_age_days` | `30` | 輪轉檔案保留的天數 |
幾條取值規則:
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 45296ed438..e40cce7123 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -290,13 +290,13 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游
守护进程在后台运行(不连着终端)时,日志写入 `~/.multica/daemon.log`,命名 profile 为 `~/.multica/profiles/<name>/daemon.log`,并按大小轮转,轮转出的文件用 gzip 压缩。
-| 变量 | 默认值 | 说明 |
-|---|---|---|
-| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `20` | `daemon.log` 达到多少 MB 时轮转 |
-| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `5` | 最多保留几个轮转文件 |
-| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `30` | 轮转文件保留的天数 |
+| 变量 | Profile 配置键 | 默认值 | 说明 |
+|---|---|---|---|
+| `MULTICA_DAEMON_LOG_MAX_SIZE_MB` | `daemon_log_max_size_mb` | `20` | `daemon.log` 达到多少 MB 时轮转 |
+| `MULTICA_DAEMON_LOG_MAX_BACKUPS` | `daemon_log_max_backups` | `5` | 最多保留几个轮转文件 |
+| `MULTICA_DAEMON_LOG_MAX_AGE_DAYS` | `daemon_log_max_age_days` | `30` | 轮转文件保留的天数 |
-三个变量都要求正整数;`0`、负数或无法解析的值按默认值处理,不会变成"不限制"。保留数量和天数哪个先到就按哪个删除。崩溃输出写在同目录的 `daemon.err.log`,启动时超过 5 MB 就改名为 `daemon.err.log.1`。
+三个参数都要求正整数。用 `multica --profile dev config set <key> <value>` 保存,`config show` 查看已保存值,传入 `""` 清除对应配置。修改在下次守护进程启动或重启时生效。有效环境变量优先于 profile;未设置、空白、零、负数、格式错误或溢出的环境值回退到有效 profile 值,再回退到表中默认值。大小和天数还必须能安全转换为字节和时长;`config set` 会拒绝无效值。零不能关闭保留限制。保留数量和天数哪个先到就按哪个删除。崩溃输出写在同目录的 `daemon.err.log`,启动时超过 5 MB 就改名为 `daemon.err.log.1`。
### 各 AI 编程工具的路径、模型与参数
@@ -399,6 +399,9 @@ multica config show
| `disable_auto_update` | 跟随环境 | `true` 关闭自动更新;`false` 清除本地覆盖,回到环境变量或默认 |
| `auto_update_check_interval` | `6h` | 检查更新的间隔 |
| `disable_auto_reload` | 跟随环境 | `true` 让守护进程不再跟随磁盘上被替换的二进制;`false` 清除本地覆盖。与 `disable_auto_update` 分开解析 |
+| `daemon_log_max_size_mb` | `20` | `daemon.log` 达到多少 MB 时轮转,见[守护进程日志](#daemon-logs) |
+| `daemon_log_max_backups` | `5` | 最多保留几个轮转文件 |
+| `daemon_log_max_age_days` | `30` | 轮转文件保留的天数 |
几条取值规则:
diff --git a/server/cmd/multica/cmd_config.go b/server/cmd/multica/cmd_config.go
index e11c103577..4a7280461e 100644
--- a/server/cmd/multica/cmd_config.go
+++ b/server/cmd/multica/cmd_config.go
@@ -36,6 +36,9 @@ var configSetSupportedKeys = []string{
"runtime_name",
"workspaces_root",
"max_concurrent_tasks",
+ "daemon_log_max_size_mb",
+ "daemon_log_max_backups",
+ "daemon_log_max_age_days",
"poll_interval",
"ws_claim_poll_interval",
"heartbeat_interval",
@@ -56,6 +59,7 @@ var configSetCmd = &cobra.Command{
Long: "Supported keys: " +
"server_url, app_url, workspace_id, " +
"device_name, runtime_name, workspaces_root, max_concurrent_tasks, poll_interval, ws_claim_poll_interval, " +
+ "daemon_log_max_size_mb, daemon_log_max_backups, daemon_log_max_age_days, " +
"heartbeat_interval, agent_timeout, agent_idle_watchdog, agent_tool_watchdog, " +
"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +
"disable_auto_update, auto_update_check_interval, disable_auto_reload, log_level.\n\n" +
@@ -66,6 +70,9 @@ var configSetCmd = &cobra.Command{
"--flag / env counterparts and are read by `daemon start` when " +
"neither the flag nor the env var is set. " +
"Precedence: --flag > MULTICA_… env > config.json > built-in default. " +
+ "The daemon_log_max_size_mb, daemon_log_max_backups, and daemon_log_max_age_days keys " +
+ "take positive integers (MB, files, and days). Valid MULTICA_DAEMON_LOG_MAX_* env values " +
+ "override them; invalid env values fall back to config.json, then defaults (20 MB, 5 files, 30 days). " +
"Duration keys take a Go duration (e.g. '10s', '500ms', '1m30s'); " +
"most keys require a positive value, while agent_timeout, agent_idle_watchdog, " +
"and agent_tool_watchdog also accept '0s' to disable their limit. " +
@@ -106,6 +113,9 @@ func runConfigShow(cmd *cobra.Command, _ []string) error {
fmt.Fprintf(os.Stdout, "%-34s %s\n", "runtime_name:", valueOrDefault(cfg.RuntimeName, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "workspaces_root:", valueOrDefault(cfg.WorkspacesRoot, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "max_concurrent_tasks:", intOrDefault(cfg.MaxConcurrentTasks, "(not set)"))
+ fmt.Fprintf(os.Stdout, "%-34s %s\n", "daemon_log_max_size_mb:", intOrDefault(cfg.DaemonLogMaxSizeMB, "(not set)"))
+ fmt.Fprintf(os.Stdout, "%-34s %s\n", "daemon_log_max_backups:", intOrDefault(cfg.DaemonLogMaxBackups, "(not set)"))
+ fmt.Fprintf(os.Stdout, "%-34s %s\n", "daemon_log_max_age_days:", intOrDefault(cfg.DaemonLogMaxAgeDays, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "poll_interval:", valueOrDefault(cfg.PollInterval, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "ws_claim_poll_interval:", valueOrDefault(cfg.WSClaimPollInterval, "(not set)"))
fmt.Fprintf(os.Stdout, "%-34s %s\n", "heartbeat_interval:", valueOrDefault(cfg.HeartbeatInterval, "(not set)"))
@@ -163,6 +173,12 @@ func applyConfigSet(cfg *cli.CLIConfig, key, value string) error {
switch key {
case "server_url":
cfg.ServerURL = value
+ case "daemon_log_max_size_mb":
+ return assignDaemonLogInt(&cfg.DaemonLogMaxSizeMB, key, value, maxDaemonLogSizeMB)
+ case "daemon_log_max_backups":
+ return assignDaemonLogInt(&cfg.DaemonLogMaxBackups, key, value, maxDaemonLogBackups)
+ case "daemon_log_max_age_days":
+ return assignDaemonLogInt(&cfg.DaemonLogMaxAgeDays, key, value, maxDaemonLogAgeDays)
case "app_url":
cfg.AppURL = value
case "workspace_id":
@@ -284,6 +300,22 @@ func applyConfigSet(cfg *cli.CLIConfig, key, value string) error {
return nil
}
+func assignDaemonLogInt(dst *int, key, value string, max int64) error {
+ if value == "" {
+ *dst = 0
+ return nil
+ }
+ n, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil || n <= 0 {
+ return fmt.Errorf("%s must be a positive integer; use `config set %s \"\"` to clear it", key, key)
+ }
+ if int64(n) > max {
+ return fmt.Errorf("%s must be at most %d", key, max)
+ }
+ *dst = n
+ return nil
+}
+
// assignBool parses value as a strict bool into dst. Shared by the
// disable_* toggles. Empty string clears the field (false).
func assignBool(dst *bool, key, value string) error {
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 808d54ab8a..ce96e7f8fe 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -8,6 +8,7 @@ import (
"io"
"io/fs"
"log/slog"
+ "math"
"net"
"net/http"
"os"
@@ -230,6 +231,11 @@ const (
defaultDaemonLogMaxSizeMB = 20 // rotate the active daemon.log once it reaches this size
defaultDaemonLogMaxBackups = 5 // how many rotated files to keep
defaultDaemonLogMaxAgeDays = 30 // drop rotated files older than this
+ // lumberjack converts MB to int64 bytes and days to time.Duration.
+ // Bound both conversions before passing user-provided values to it.
+ maxDaemonLogSizeMB = math.MaxInt64 / (1024 * 1024)
+ maxDaemonLogBackups = math.MaxInt64
+ maxDaemonLogAgeDays = math.MaxInt64 / int64(24*time.Hour)
// errLogMaxBytes bounds daemon.err.log (raw crash/panic sink). It is
// enforced by rolling the file to a single ".1" backup at open time, so a
// crash loop that repeatedly appends panic output can't reintroduce the
@@ -242,28 +248,37 @@ const (
// bulk of daemon.log volume is the daemon's own slog output plus agent
// subprocess stderr (all forwarded through slog), so bounding this writer
// bounds essentially all growth.
-func newDaemonLogRotator(logPath string) *lumberjack.Logger {
+func newDaemonLogRotator(logPath string, cfg cli.CLIConfig) *lumberjack.Logger {
return &lumberjack.Logger{
Filename: logPath,
- MaxSize: envPositiveIntOrDefault("MULTICA_DAEMON_LOG_MAX_SIZE_MB", defaultDaemonLogMaxSizeMB),
- MaxBackups: envPositiveIntOrDefault("MULTICA_DAEMON_LOG_MAX_BACKUPS", defaultDaemonLogMaxBackups),
- MaxAge: envPositiveIntOrDefault("MULTICA_DAEMON_LOG_MAX_AGE_DAYS", defaultDaemonLogMaxAgeDays),
+ MaxSize: daemonLogInt("MULTICA_DAEMON_LOG_MAX_SIZE_MB", cfg.DaemonLogMaxSizeMB, defaultDaemonLogMaxSizeMB, maxDaemonLogSizeMB),
+ MaxBackups: daemonLogInt("MULTICA_DAEMON_LOG_MAX_BACKUPS", cfg.DaemonLogMaxBackups, defaultDaemonLogMaxBackups, maxDaemonLogBackups),
+ MaxAge: daemonLogInt("MULTICA_DAEMON_LOG_MAX_AGE_DAYS", cfg.DaemonLogMaxAgeDays, defaultDaemonLogMaxAgeDays, maxDaemonLogAgeDays),
Compress: true,
}
}
+// Ignore invalid persisted values too: hand-edited config must not disable
+// retention or overflow lumberjack's size/age conversions.
+func daemonLogInt(key string, saved, def int, max int64) int {
+ if saved > 0 && int64(saved) <= max {
+ def = saved
+ }
+ return envPositiveIntOrDefault(key, def, max)
+}
+
// envPositiveIntOrDefault reads a strictly positive integer env var, falling
-// back to def when unset, blank, malformed, zero, or negative. Zero is treated
+// back to def when unset, blank, malformed, zero, negative, or over max. Zero is treated
// as "use default" on purpose: lumberjack reads MaxSize=0 as 100MB and
// MaxBackups=0 / MaxAge=0 as "keep everything", so honoring a literal 0 would
// silently disable retention and reintroduce unbounded growth.
-func envPositiveIntOrDefault(key string, def int) int {
+func envPositiveIntOrDefault(key string, def int, max int64) int {
v := strings.TrimSpace(os.Getenv(key))
if v == "" {
return def
}
n, err := strconv.Atoi(v)
- if err != nil || n <= 0 {
+ if err != nil || n <= 0 || int64(n) > max {
return def
}
return n
@@ -994,7 +1009,7 @@ func runDaemonForeground(cmd *cobra.Command) error {
// daemon.log solely owned by the rotator. No-op on Unix, where an open
// fd never blocks rename.
repointStdioToErrLog(daemonStderrLogPathForProfile(profile))
- logRotator = newDaemonLogRotator(daemonLogPathForProfile(profile))
+ logRotator = newDaemonLogRotator(daemonLogPathForProfile(profile), fileCfg)
defer logRotator.Close()
// Route both this process's structured logger and the package-global
// slog default through the rotator, so every log line — including
diff --git a/server/cmd/multica/cmd_daemon_log_policy_test.go b/server/cmd/multica/cmd_daemon_log_policy_test.go
new file mode 100644
index 0000000000..7c0f2630b2
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_log_policy_test.go
@@ -0,0 +1,242 @@
+package main
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+ "github.com/spf13/cobra"
+)
+
+func clearDaemonLogEnv(t *testing.T) {
+ t.Helper()
+ for _, key := range []string{"MULTICA_DAEMON_LOG_MAX_SIZE_MB", "MULTICA_DAEMON_LOG_MAX_BACKUPS", "MULTICA_DAEMON_LOG_MAX_AGE_DAYS"} {
+ t.Setenv(key, "")
+ }
+}
+
+func TestDaemonLogPolicyPrecedence(t *testing.T) {
+ clearDaemonLogEnv(t)
+ for _, tc := range []struct {
+ key string
+ fallback int
+ max int64
+ config func(int) cli.CLIConfig
+ read func(cli.CLIConfig) int
+ }{
+ {"MULTICA_DAEMON_LOG_MAX_SIZE_MB", 20, maxDaemonLogSizeMB, func(n int) cli.CLIConfig { return cli.CLIConfig{DaemonLogMaxSizeMB: n} }, func(c cli.CLIConfig) int { return newDaemonLogRotator("unused", c).MaxSize }},
+ {"MULTICA_DAEMON_LOG_MAX_BACKUPS", 5, maxDaemonLogBackups, func(n int) cli.CLIConfig { return cli.CLIConfig{DaemonLogMaxBackups: n} }, func(c cli.CLIConfig) int { return newDaemonLogRotator("unused", c).MaxBackups }},
+ {"MULTICA_DAEMON_LOG_MAX_AGE_DAYS", 30, maxDaemonLogAgeDays, func(n int) cli.CLIConfig { return cli.CLIConfig{DaemonLogMaxAgeDays: n} }, func(c cli.CLIConfig) int { return newDaemonLogRotator("unused", c).MaxAge }},
+ } {
+ t.Run(tc.key, func(t *testing.T) {
+ envValues := []string{"", " ", "0", "-1", "bad", strings.Repeat("9", 50), "7", " 8 "}
+ if tc.max < maxDaemonLogBackups {
+ envValues = append(envValues, strconv.FormatInt(tc.max+1, 10))
+ }
+ for _, saved := range []int{0, 3, -1} {
+ for _, value := range envValues {
+ t.Run(fmt.Sprintf("saved=%d/env=%q", saved, value), func(t *testing.T) {
+ t.Setenv(tc.key, value)
+ want := tc.fallback
+ if saved > 0 {
+ want = saved
+ }
+ if value == "7" {
+ want = 7
+ } else if value == " 8 " {
+ want = 8
+ }
+ if got := tc.read(tc.config(saved)); got != want {
+ t.Fatalf("got %d, want %d", got, want)
+ }
+ })
+ }
+ }
+ if tc.max < maxDaemonLogBackups && strconv.IntSize == 64 {
+ t.Setenv(tc.key, "")
+ if got := tc.read(tc.config(int(tc.max + 1))); got != tc.fallback {
+ t.Fatalf("overflowing saved value: got %d, want %d", got, tc.fallback)
+ }
+ }
+ })
+ }
+}
+
+func TestDaemonLogConfigValidation(t *testing.T) {
+ for _, key := range []string{"daemon_log_max_size_mb", "daemon_log_max_backups", "daemon_log_max_age_days"} {
+ t.Run(key, func(t *testing.T) {
+ for _, invalid := range []string{"0", "-1", "bad", " ", "1.5", strings.Repeat("9", 50)} {
+ cfg := cli.CLIConfig{DaemonLogMaxSizeMB: 3, DaemonLogMaxBackups: 3, DaemonLogMaxAgeDays: 3}
+ before := cfg
+ if err := applyConfigSet(&cfg, key, invalid); err == nil {
+ t.Fatalf("accepted %q", invalid)
+ }
+ if !reflect.DeepEqual(cfg, before) {
+ t.Fatalf("rejected value mutated config: %#v", cfg)
+ }
+ }
+ })
+ }
+ for key, max := range map[string]int64{"daemon_log_max_size_mb": maxDaemonLogSizeMB, "daemon_log_max_age_days": maxDaemonLogAgeDays} {
+ cfg := cli.CLIConfig{}
+ if err := applyConfigSet(&cfg, key, strconv.FormatInt(max+1, 10)); err == nil {
+ t.Fatalf("%s accepted conversion overflow", key)
+ }
+ }
+}
+
+func TestDaemonLogProfilePersistenceAndWriter(t *testing.T) {
+ clearDaemonLogEnv(t)
+ t.Setenv(cli.TaskConfigRootEnv, t.TempDir())
+ command := func(profile string) *cobra.Command {
+ c := &cobra.Command{}
+ c.Flags().String("profile", profile, "")
+ return c
+ }
+ for _, kv := range [][2]string{{"daemon_log_max_size_mb", "1"}, {"daemon_log_max_backups", "2"}, {"daemon_log_max_age_days", "7"}} {
+ if err := runConfigSet(command("small"), kv[:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := runConfigSet(command("other"), []string{kv[0], "9"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cfg, err := cli.LoadCLIConfigForProfile("small")
+ if err != nil {
+ t.Fatal(err)
+ }
+ other, err := cli.LoadCLIConfigForProfile("other")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if other.DaemonLogMaxSizeMB != 9 || other.DaemonLogMaxBackups != 9 || other.DaemonLogMaxAgeDays != 9 {
+ t.Fatalf("other profile changed: %#v", other)
+ }
+ path := filepath.Join(t.TempDir(), "daemon.log")
+ r := newDaemonLogRotator(path, cfg)
+ defer r.Close()
+ if r.MaxSize != 1 || r.MaxBackups != 2 || r.MaxAge != 7 || !r.Compress {
+ t.Fatalf("profile did not reach actual writer: %#v", r)
+ }
+ payload := bytes.Repeat([]byte("x"), 700*1024)
+ // Each write after the first rotates (700 KiB + 700 KiB > 1 MiB), so four
+ // writes produce three backups and MaxBackups=2 must prune one.
+ for range 4 {
+ // lumberjack uses millisecond archive names. Separate real writes so
+ // this test exercises retention rather than same-timestamp replacement.
+ time.Sleep(2 * time.Millisecond)
+ if _, err := r.Write(payload); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := r.Close(); err != nil {
+ t.Fatal(err)
+ }
+ waitForLogFiles(t, func() bool {
+ gz, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "daemon-*.log.gz"))
+ raw, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "daemon-*.log"))
+ return len(gz) == 2 && len(raw) == 0
+ })
+ gz, _ := filepath.Glob(filepath.Join(filepath.Dir(path), "daemon-*.log.gz"))
+ for _, p := range gz {
+ if got := readGzipLog(t, p); !bytes.Equal(got, payload) {
+ t.Fatalf("archive %s contents changed: %d bytes", p, len(got))
+ }
+ }
+ active, err := os.ReadFile(path)
+ if err != nil || !bytes.Equal(active, payload) {
+ t.Fatalf("active log not bounded/intact: %d bytes, %v", len(active), err)
+ }
+ for _, key := range []string{"daemon_log_max_size_mb", "daemon_log_max_backups", "daemon_log_max_age_days"} {
+ if err := runConfigSet(command("small"), []string{key, ""}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ cleared, err := cli.LoadCLIConfigForProfile("small")
+ if err != nil {
+ t.Fatal(err)
+ }
+ r = newDaemonLogRotator(path, cleared)
+ if r.MaxSize != 20 || r.MaxBackups != 5 || r.MaxAge != 30 {
+ t.Fatalf("clear did not restore defaults: %#v", r)
+ }
+}
+
+func TestDaemonLogProfileAgeRetention(t *testing.T) {
+ clearDaemonLogEnv(t)
+ dir := t.TempDir()
+ name := func(age time.Duration) string {
+ return filepath.Join(dir, "daemon-"+time.Now().UTC().Add(-age).Format("2006-01-02T15-04-05.000")+".log")
+ }
+ old, recent := name(72*time.Hour), name(12*time.Hour)
+ for _, p := range []string{old, recent} {
+ if err := os.WriteFile(p, []byte("synthetic retained log"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ r := newDaemonLogRotator(filepath.Join(dir, "daemon.log"), cli.CLIConfig{DaemonLogMaxSizeMB: 1, DaemonLogMaxBackups: 5, DaemonLogMaxAgeDays: 1})
+ defer r.Close()
+ if _, err := r.Write([]byte("current")); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Rotate(); err != nil {
+ t.Fatal(err)
+ }
+ waitForLogFiles(t, func() bool {
+ _, oldErr := os.Stat(old)
+ _, recentErr := os.Stat(recent)
+ _, gzErr := os.Stat(recent + ".gz")
+ return os.IsNotExist(oldErr) && os.IsNotExist(recentErr) && gzErr == nil
+ })
+ if _, err := os.Stat(old + ".gz"); !os.IsNotExist(err) {
+ t.Fatalf("expired backup was compressed/retained: %v", err)
+ }
+ if got := readGzipLog(t, recent+".gz"); string(got) != "synthetic retained log" {
+ t.Fatalf("recent backup changed: %q", got)
+ }
+}
+
+func waitForLogFiles(t *testing.T, ready func() bool) {
+ t.Helper()
+ deadline := time.NewTimer(5 * time.Second)
+ defer deadline.Stop()
+ tick := time.NewTicker(10 * time.Millisecond)
+ defer tick.Stop()
+ for !ready() {
+ select {
+ case <-deadline.C:
+ t.Fatal("lumberjack did not finish asynchronous retention/compression")
+ case <-tick.C:
+ }
+ }
+}
+
+func readGzipLog(t *testing.T, path string) []byte {
+ t.Helper()
+ f, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ r, err := gzip.NewReader(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, err := io.ReadAll(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
diff --git a/server/cmd/multica/cmd_daemon_log_test.go b/server/cmd/multica/cmd_daemon_log_test.go
index a544bfe5bf..cfd34a1664 100644
--- a/server/cmd/multica/cmd_daemon_log_test.go
+++ b/server/cmd/multica/cmd_daemon_log_test.go
@@ -5,6 +5,8 @@ import (
"path/filepath"
"strings"
"testing"
+
+ "github.com/multica-ai/multica/server/internal/cli"
)
// TestEnvPositiveIntOrDefault locks in the parse-or-fallback behaviour the log
@@ -35,7 +37,7 @@ func TestEnvPositiveIntOrDefault(t *testing.T) {
if c.set {
t.Setenv(key, c.val)
}
- if got := envPositiveIntOrDefault(key, c.def); got != c.want {
+ if got := envPositiveIntOrDefault(key, c.def, maxDaemonLogBackups); got != c.want {
t.Errorf("envPositiveIntOrDefault(%q, %d) = %d, want %d", c.val, c.def, got, c.want)
}
})
@@ -103,7 +105,7 @@ func TestNewDaemonLogRotatorEnvOverride(t *testing.T) {
t.Setenv("MULTICA_DAEMON_LOG_MAX_BACKUPS", "2")
t.Setenv("MULTICA_DAEMON_LOG_MAX_AGE_DAYS", "7")
- r := newDaemonLogRotator(filepath.Join(t.TempDir(), "daemon.log"))
+ r := newDaemonLogRotator(filepath.Join(t.TempDir(), "daemon.log"), cli.CLIConfig{})
if r.MaxSize != 5 || r.MaxBackups != 2 || r.MaxAge != 7 {
t.Errorf("rotator = {MaxSize:%d MaxBackups:%d MaxAge:%d}, want {5 2 7}", r.MaxSize, r.MaxBackups, r.MaxAge)
}
@@ -119,7 +121,7 @@ func TestDaemonLogRotatorRotates(t *testing.T) {
// racing lumberjack's async gzip of the rotated file.
dir := t.TempDir()
path := filepath.Join(dir, "daemon.log")
- r := newDaemonLogRotator(path)
+ r := newDaemonLogRotator(path, cli.CLIConfig{})
r.Compress = false
// Write ~1.5 MB in chunks; at least one rotation must happen.
diff --git a/server/internal/cli/config.go b/server/internal/cli/config.go
index 9ff38a1b1f..81f78115d3 100644
--- a/server/internal/cli/config.go
+++ b/server/internal/cli/config.go
@@ -63,6 +63,12 @@ type CLIConfig struct {
// MULTICA_DAEMON_MAX_CONCURRENT_TASKS env, this field, default.
MaxConcurrentTasks int `json:"max_concurrent_tasks,omitempty"`
+ // Daemon log rotation overrides. Zero means unset; valid environment values
+ // take precedence, followed by these fields, then the 20 MB / 5 / 30 defaults.
+ DaemonLogMaxSizeMB int `json:"daemon_log_max_size_mb,omitempty"`
+ DaemonLogMaxBackups int `json:"daemon_log_max_backups,omitempty"`
+ DaemonLogMaxAgeDays int `json:"daemon_log_max_age_days,omitempty"`
+
// PollInterval is how often the daemon polls the server for new tasks
// (Go duration string, e.g. "10s", "500ms"). Same persist-once
// motivation as MaxConcurrentTasks. Empty ("") means "not set — use