Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(daemon): bound daemon.log size with rotation (MUL-4330) (#5170)
Bohan Jiang6c3b79db190d
diff --git a/apps/docs/content/docs/troubleshooting.ja.mdx b/apps/docs/content/docs/troubleshooting.ja.mdxindex 98d95c91e4..2abb6a822c 100644--- a/apps/docs/content/docs/troubleshooting.ja.mdx+++ b/apps/docs/content/docs/troubleshooting.ja.mdx@@ -279,9 +279,12 @@ netstat -ano | findstr :8080 # Windows| 構成要素 | 場所 | コマンド ||---|---|---|| **デーモン** | `~/.multica/daemon.log`(バックグラウンドモード)またはフォアグラウンドの stdout | `multica daemon logs -f --lines 100` |+| **デーモン(クラッシュ)** | `~/.multica/daemon.err.log` | 直接開く——パニックや起動初期のエラーはここに記録されます || **サーバー(Docker)** | コンテナの stdout | `docker logs -f <container>` || **サーバー(systemd)** | journal | `journalctl -u multica-server -f` || **フロントエンド(dev)** | `pnpm dev` を実行中のターミナル | 直接確認 || **フロントエンド(ブラウザ)** | DevTools → Console | `F12` を押す |-より詳細なデーモンログが必要な場合は、デーモンをバックグラウンドからフォアグラウンドに移してください: `multica daemon stop && multica daemon start --foreground`。+バックグラウンドモードでは `daemon.log` はサイズでローテーションされ(デフォルトは 20MB × gzip バックアップ 5 世代。`MULTICA_DAEMON_LOG_MAX_SIZE_MB` / `_MAX_BACKUPS` / `_MAX_AGE_DAYS` で調整可能)、開けないほど大きくなることはありません。Go ランタイムのパニックや logger 初期化前のエラーは、独立した上限付きの `daemon.err.log` に出力されます。++より詳細なデーモンログが必要な場合は、デーモンをバックグラウンドからフォアグラウンドに移してください: `multica daemon stop && multica daemon start --foreground`。フォアグラウンドで実行すると、ログはローテーションファイルではなくターミナルにリアルタイムで出力されます。diff --git a/apps/docs/content/docs/troubleshooting.ko.mdx b/apps/docs/content/docs/troubleshooting.ko.mdxindex e089db49c6..dbd20d77eb 100644--- a/apps/docs/content/docs/troubleshooting.ko.mdx+++ b/apps/docs/content/docs/troubleshooting.ko.mdx@@ -279,9 +279,12 @@ netstat -ano | findstr :8080 # Windows| 구성 요소 | 위치 | 명령 ||---|---|---|| **데몬** | `~/.multica/daemon.log`(백그라운드 모드) 또는 포그라운드 stdout | `multica daemon logs -f --lines 100` |+| **데몬(크래시)** | `~/.multica/daemon.err.log` | 직접 열기 — 패닉/초기 시작 오류가 여기에 기록됩니다 || **서버(Docker)** | 컨테이너 stdout | `docker logs -f <container>` || **서버(systemd)** | journal | `journalctl -u multica-server -f` || **프런트엔드(dev)** | `pnpm dev`를 실행 중인 터미널 | 직접 확인 || **프런트엔드(브라우저)** | DevTools → Console | `F12`를 누르세요 |-더 자세한 데몬 로그가 필요하면, 데몬을 백그라운드에서 포그라운드로 옮기세요: `multica daemon stop && multica daemon start --foreground`.+백그라운드 모드에서 `daemon.log`는 크기 기준으로 로테이션되므로(기본값 20MB × gzip 백업 5개; `MULTICA_DAEMON_LOG_MAX_SIZE_MB` / `_MAX_BACKUPS` / `_MAX_AGE_DAYS`로 조정 가능) 열 수 없을 만큼 커지지 않습니다. Go 런타임 패닉과 logger 초기화 이전 오류는 별도의 상한이 있는 `daemon.err.log`에 기록됩니다.++더 자세한 데몬 로그가 필요하면, 데몬을 백그라운드에서 포그라운드로 옮기세요: `multica daemon stop && multica daemon start --foreground`. 포그라운드로 실행하면 로그가 로테이션 파일이 아니라 터미널에 실시간으로 출력됩니다.diff --git a/apps/docs/content/docs/troubleshooting.mdx b/apps/docs/content/docs/troubleshooting.mdxindex d20be1d4da..f7f76111a3 100644--- a/apps/docs/content/docs/troubleshooting.mdx+++ b/apps/docs/content/docs/troubleshooting.mdx@@ -279,9 +279,12 @@ netstat -ano | findstr :8080 # Windows| Component | Location | Command ||---|---|---|| **Daemon** | `~/.multica/daemon.log` (background mode) or foreground stdout | `multica daemon logs -f --lines 100` |+| **Daemon (crashes)** | `~/.multica/daemon.err.log` | Open directly — panics / early-startup errors land here || **Server (Docker)** | Container stdout | `docker logs -f <container>` || **Server (systemd)** | journal | `journalctl -u multica-server -f` || **Frontend (dev)** | Terminal running `pnpm dev` | Read directly || **Frontend (browser)** | DevTools → Console | Press `F12` |-For more detailed daemon logs, move it from background to foreground: `multica daemon stop && multica daemon start --foreground`.+In background mode `daemon.log` is size-rotated (20MB × 5 gzip backups by default; tune with `MULTICA_DAEMON_LOG_MAX_SIZE_MB` / `_MAX_BACKUPS` / `_MAX_AGE_DAYS`), so it stays small enough to open. Go runtime panics and pre-logger errors go to the separate, bounded `daemon.err.log`.++For more detailed daemon logs, move it from background to foreground: `multica daemon stop && multica daemon start --foreground`. Running in the foreground streams logs live to your terminal instead of the rotated file.diff --git a/apps/docs/content/docs/troubleshooting.zh.mdx b/apps/docs/content/docs/troubleshooting.zh.mdxindex 22b929b82f..423f5d6b40 100644--- a/apps/docs/content/docs/troubleshooting.zh.mdx+++ b/apps/docs/content/docs/troubleshooting.zh.mdx@@ -278,9 +278,12 @@ netstat -ano | findstr :8080 # Windows| 组件 | 位置 | 命令 ||---|---|---|| **守护进程** | `~/.multica/daemon.log`(后台模式)或前台 stdout | `multica daemon logs -f --lines 100` |+| **守护进程(崩溃)** | `~/.multica/daemon.err.log` | 直接打开——panic / 启动早期错误会写到这里 || **服务器(Docker)** | container stdout | `docker logs -f <container>` || **服务器(systemd)** | journal | `journalctl -u multica-server -f` || **前端(dev)** | `pnpm dev` 所在终端 | 直接看 || **前端(browser)** | DevTools → Console | 按 `F12` |-需要更详细的 daemon 日志,把它从后台挪到前台跑:`multica daemon stop && multica daemon start --foreground`。+后台模式下 `daemon.log` 会按大小轮转(默认 20MB × 5 份 gzip 备份;可用 `MULTICA_DAEMON_LOG_MAX_SIZE_MB` / `_MAX_BACKUPS` / `_MAX_AGE_DAYS` 调整),所以文件不会大到打不开。Go 运行时 panic 和 logger 建立前的错误会写到独立且有上限的 `daemon.err.log`。++需要更详细的 daemon 日志,把它从后台挪到前台跑:`multica daemon stop && multica daemon start --foreground`。前台运行会把日志实时打到终端,而不是写入轮转文件。diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 0e5caf8783..1ccaa22afb 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -6,6 +6,7 @@ import ("errors""fmt""io"+ "log/slog""net/http""os""os/exec"@@ -16,6 +17,7 @@ import ("time""github.com/spf13/cobra"+ lumberjack "gopkg.in/natefinch/lumberjack.v2""github.com/multica-ai/multica/server/internal/cli""github.com/multica-ai/multica/server/internal/daemon"@@ -142,6 +144,78 @@ func daemonLogPathForProfile(profile string) string {return filepath.Join(daemonDirForProfile(profile), "daemon.log")}+// daemonStderrLogPathForProfile is the sink for the foreground daemon's raw+// stdout/stderr — Go runtime panics, fatal aborts, and any pre-logger output.+// It is deliberately separate from daemon.log: the foreground daemon owns+// daemon.log through a rotating writer (newDaemonLogRotator), and letting the+// child also hold daemon.log open via inherited fds would block rotation's+// rename on Windows. Because every structured log line already flows through+// slog into the rotating daemon.log, this file only receives rare crash output+// and stays near-empty for a healthy daemon.+func daemonStderrLogPathForProfile(profile string) string {+ return filepath.Join(daemonDirForProfile(profile), "daemon.err.log")+}++// Daemon log rotation policy. Defaults keep the active daemon.log small enough+// to open in an editor while retaining recent history; each is overridable via+// env so operators can tune retention without a rebuild. Whichever of backups+// / age is hit first prunes a rotated file.+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+ // 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+ // unbounded-growth problem on a different file.+ errLogMaxBytes = 5 * 1024 * 1024+)++// newDaemonLogRotator builds the size-based rotating writer backing daemon.log.+// Rotated files are gzip-compressed to keep the on-disk footprint small. The+// 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 {+ 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),+ Compress: true,+ }+}++// envPositiveIntOrDefault reads a strictly positive integer env var, falling+// back to def when unset, blank, malformed, zero, or negative. 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 {+ v := strings.TrimSpace(os.Getenv(key))+ if v == "" {+ return def+ }+ n, err := strconv.Atoi(v)+ if err != nil || n <= 0 {+ return def+ }+ return n+}++// openBoundedErrLog rolls daemon.err.log to a single ".1" backup when it has+// grown past errLogMaxBytes, then opens it for appending. This keeps the raw+// crash sink bounded across restarts (see errLogMaxBytes) without pulling in a+// second rotating writer — the file is only ever written by inherited fds.+func openBoundedErrLog(path string) (*os.File, error) {+ if fi, err := os.Stat(path); err == nil && fi.Size() >= errLogMaxBytes {+ // Best-effort roll; ignore errors and fall through to append so a+ // rename failure never blocks daemon startup.+ _ = os.Rename(path, path+".1")+ }+ return os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)+}+// healthPortForProfile returns the health check port for the given profile.// Default profile uses the standard port (19514). Named profiles get a// deterministic offset derived from the profile name.@@ -199,11 +273,18 @@ func runDaemonBackground(cmd *cobra.Command) error {return fmt.Errorf("create daemon directory: %w", err)}- logPath := daemonLogPathForProfile(profile)- logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)+ // The child (foreground daemon) writes daemon.log itself through a+ // rotating writer; its inherited stdout/stderr only need to catch raw+ // crash output, which goes to a separate, non-rotated sink so it never+ // holds daemon.log open (see daemonStderrLogPathForProfile).+ errLogPath := daemonStderrLogPathForProfile(profile)+ logFile, err := openBoundedErrLog(errLogPath)if err != nil {- return fmt.Errorf("open log file %s: %w", logPath, err)+ return fmt.Errorf("open log file %s: %w", errLogPath, err)}+ // Where the daemon's structured logs actually land (rotated), for the+ // user-facing hints below.+ logPath := daemonLogPathForProfile(profile)child := exec.Command(exePath, args...)child.Stdout = logFile@@ -269,7 +350,7 @@ func runDaemonBackground(cmd *cobra.Command) error {if lastStatus == "starting" {fmt.Fprintf(os.Stderr, "Daemon is still starting after %s (agent detection / workspace sync is taking longer than expected). Check logs:\n %s\n", startupTimeout, logPath)} else {- fmt.Fprintf(os.Stderr, "Daemon may not have started successfully. Check logs:\n %s\n", logPath)+ fmt.Fprintf(os.Stderr, "Daemon may not have started successfully. Check logs:\n %s\n %s (crash output)\n", logPath, errLogPath)}return nil}@@ -337,6 +418,34 @@ func runDaemonForeground(cmd *cobra.Command) error {profile := resolveProfile(cmd)+ // Pick the log sink. A user who runs `daemon start --foreground` in a shell+ // keeps live, colored logging on their terminal (a documented debugging+ // path — see docs troubleshooting). A detached/background child, whose+ // stderr the launcher redirected to a file, instead routes structured logs+ // into the size-bounded, rotating daemon.log so the file can't grow without+ // limit. We distinguish the two by whether stderr is a terminal.+ var (+ logger *slog.Logger+ logRotator *lumberjack.Logger+ )+ if logger_pkg.StderrIsTerminal() {+ logger = logger_pkg.NewLogger("daemon")+ } else {+ // An older self-update launcher may have handed this process daemon.log+ // itself as stdout/stderr. On Windows that inherited handle lacks+ // FILE_SHARE_DELETE and would block the rotator's rename, so re-point+ // our standard handles at the bounded crash sink first, leaving+ // 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))+ defer logRotator.Close()+ // Route both this process's structured logger and the package-global+ // slog default through the rotator, so every log line — including+ // LoadConfig's slog.Warn below — is captured and rotated.+ logger = logger_pkg.NewWriterLoggerDefault("daemon", logRotator)+ }+serverURL := cli.FlagOrEnv(cmd, "server-url", "MULTICA_SERVER_URL", "")if serverURL == "" {if c, err := cli.LoadCLIConfigForProfile(profile); err == nil && c.ServerURL != "" {@@ -388,8 +497,6 @@ func runDaemonForeground(cmd *cobra.Command) error {ctx, stop := notifyShutdownContext(context.Background())defer stop()- logger := logger_pkg.NewLogger("daemon")-d := daemon.New(cfg, logger)// Write PID file so "daemon stop" can find us.@@ -407,17 +514,31 @@ func runDaemonForeground(cmd *cobra.Command) error {if restartBin := d.RestartBinary(); restartBin != "" {logger.Info("restarting daemon with updated binary", "path", restartBin)+ // The successor will open daemon.log through its own rotating writer,+ // and lumberjack does not support two writers managing one file. Stop+ // writing to our rotator before the successor starts: close it and move+ // this process's remaining handoff logs to the crash sink (stderr),+ // including the package-global slog default (which would otherwise+ // reopen daemon.log on its next write).+ if logRotator != nil {+ logger = logger_pkg.NewWriterLoggerDefault("daemon", os.Stderr)+ _ = logRotator.Close()+ }+args := buildDaemonStartArgs(cmd)child := exec.Command(restartBin, args...)- logPath := daemonLogPathForProfile(profile)- logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)+ // The successor is a fresh foreground daemon that will open daemon.log+ // through its own rotating writer; hand it the raw-stderr sink so its+ // inherited fds don't hold daemon.log open (see runDaemonBackground).+ errLogPath := daemonStderrLogPathForProfile(profile)+ logFile, err := openBoundedErrLog(errLogPath)if err != nil {logger.Error("failed to open log file for restart", "error", err)// Runtimes were already deregistered by triggerRestart() before handoff.// The supervisor-spawned successor re-registers on startup; do not// duplicate cleanup here.- return fmt.Errorf("failed to open daemon log file %s for restart: %w", logPath, err)+ return fmt.Errorf("failed to open daemon log file %s for restart: %w", errLogPath, err)}child.Stdout = logFilechild.Stderr = logFilediff --git a/server/cmd/multica/cmd_daemon_log_test.go b/server/cmd/multica/cmd_daemon_log_test.gonew file mode 100644index 0000000000..846f6e6396--- /dev/null+++ b/server/cmd/multica/cmd_daemon_log_test.go@@ -0,0 +1,205 @@+package main++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++// TestEnvPositiveIntOrDefault locks in the parse-or-fallback behaviour the log+// rotation knobs rely on. Critically, an explicit 0 falls back to the default+// (not through to lumberjack, where 0 means 100MB / keep-everything), so the+// retention footguns can't be tripped from the environment.+func TestEnvPositiveIntOrDefault(t *testing.T) {+ const key = "MULTICA_TEST_ENV_INT"+ cases := []struct {+ name string+ set bool+ val string+ def int+ want int+ }{+ {"unset", false, "", 20, 20},+ {"blank", true, "", 20, 20},+ {"whitespace", true, " ", 20, 20},+ {"valid", true, "50", 20, 50},+ {"zero_falls_back", true, "0", 20, 20},+ {"negative", true, "-1", 20, 20},+ {"malformed", true, "abc", 20, 20},+ {"padded", true, " 7 ", 20, 7},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ os.Unsetenv(key)+ if c.set {+ t.Setenv(key, c.val)+ }+ if got := envPositiveIntOrDefault(key, c.def); got != c.want {+ t.Errorf("envPositiveIntOrDefault(%q, %d) = %d, want %d", c.val, c.def, got, c.want)+ }+ })+ }+}++// TestOpenBoundedErrLogRolls verifies the raw crash sink is bounded: once it is+// at/over the cap, opening it rolls the old contents to a single ".1" backup+// and starts fresh, so a crash loop can't grow daemon.err.log without limit.+func TestOpenBoundedErrLogRolls(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "daemon.err.log")++ // Seed an over-cap file.+ big := make([]byte, errLogMaxBytes+1024)+ if err := os.WriteFile(path, big, 0o644); err != nil {+ t.Fatalf("seed: %v", err)+ }+ f, err := openBoundedErrLog(path)+ if err != nil {+ t.Fatalf("openBoundedErrLog: %v", err)+ }+ f.Close()++ if _, err := os.Stat(path + ".1"); err != nil {+ t.Errorf("expected rolled backup %s.1: %v", path, err)+ }+ fi, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat active: %v", err)+ }+ if fi.Size() != 0 {+ t.Errorf("active err log = %d bytes after roll, want 0", fi.Size())+ }+}++// TestOpenBoundedErrLogKeepsSmall confirms a below-cap file is appended to, not+// rolled — the common healthy-daemon case.+func TestOpenBoundedErrLogKeepsSmall(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "daemon.err.log")+ if err := os.WriteFile(path, []byte("prior crash\n"), 0o644); err != nil {+ t.Fatalf("seed: %v", err)+ }+ f, err := openBoundedErrLog(path)+ if err != nil {+ t.Fatalf("openBoundedErrLog: %v", err)+ }+ f.WriteString("next line\n")+ f.Close()++ if _, err := os.Stat(path + ".1"); !os.IsNotExist(err) {+ t.Errorf("did not expect a rolled backup for a small file")+ }+ data, _ := os.ReadFile(path)+ if !strings.Contains(string(data), "prior crash") || !strings.Contains(string(data), "next line") {+ t.Errorf("expected append, got %q", data)+ }+}++// TestNewDaemonLogRotatorDefaults asserts the rotator is wired to the intended+// policy when no env overrides are set: the configured path, the default+// size/backups/age, and gzip compression so rotated files stay small.+func TestNewDaemonLogRotatorDefaults(t *testing.T) {+ os.Unsetenv("MULTICA_DAEMON_LOG_MAX_SIZE_MB")+ os.Unsetenv("MULTICA_DAEMON_LOG_MAX_BACKUPS")+ os.Unsetenv("MULTICA_DAEMON_LOG_MAX_AGE_DAYS")++ path := filepath.Join(t.TempDir(), "daemon.log")+ r := newDaemonLogRotator(path)+ if r.Filename != path {+ t.Errorf("Filename = %q, want %q", r.Filename, path)+ }+ if r.MaxSize != defaultDaemonLogMaxSizeMB {+ t.Errorf("MaxSize = %d, want %d", r.MaxSize, defaultDaemonLogMaxSizeMB)+ }+ if r.MaxBackups != defaultDaemonLogMaxBackups {+ t.Errorf("MaxBackups = %d, want %d", r.MaxBackups, defaultDaemonLogMaxBackups)+ }+ if r.MaxAge != defaultDaemonLogMaxAgeDays {+ t.Errorf("MaxAge = %d, want %d", r.MaxAge, defaultDaemonLogMaxAgeDays)+ }+ if !r.Compress {+ t.Error("Compress = false, want true")+ }+}++// TestNewDaemonLogRotatorEnvOverride confirms operators can tune retention via+// env without a rebuild.+func TestNewDaemonLogRotatorEnvOverride(t *testing.T) {+ t.Setenv("MULTICA_DAEMON_LOG_MAX_SIZE_MB", "5")+ 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"))+ 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)+ }+}++// TestDaemonLogRotatorRotates is the end-to-end guarantee: once the active file+// crosses MaxSize the writer rotates instead of appending forever, so daemon.log+// stays bounded (the core of MUL-4330). Uses the 1 MB floor lumberjack enforces.+func TestDaemonLogRotatorRotates(t *testing.T) {+ t.Setenv("MULTICA_DAEMON_LOG_MAX_SIZE_MB", "1")+ t.Setenv("MULTICA_DAEMON_LOG_MAX_BACKUPS", "3")+ // Disable compression here so the assertion on the active file size is not+ // racing lumberjack's async gzip of the rotated file.+ dir := t.TempDir()+ path := filepath.Join(dir, "daemon.log")+ r := newDaemonLogRotator(path)+ r.Compress = false++ // Write ~1.5 MB in chunks; at least one rotation must happen.+ line := strings.Repeat("x", 1024) + "\n"+ for written := 0; written < 3*1024*1024; written += len(line) {+ if _, err := r.Write([]byte(line)); err != nil {+ t.Fatalf("write: %v", err)+ }+ }+ if err := r.Close(); err != nil {+ t.Fatalf("close: %v", err)+ }++ entries, err := os.ReadDir(dir)+ if err != nil {+ t.Fatalf("read dir: %v", err)+ }+ var logFiles int+ for _, e := range entries {+ if strings.HasPrefix(e.Name(), "daemon") && strings.Contains(e.Name(), ".log") {+ logFiles+++ }+ }+ if logFiles < 2 {+ t.Fatalf("expected at least 2 log files after rotation, got %d (%v)", logFiles, entries)+ }++ // The active file must be bounded well under the total bytes written.+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat active log: %v", err)+ }+ if info.Size() > 2*1024*1024 {+ t.Errorf("active daemon.log = %d bytes, expected bounded (<2MB)", info.Size())+ }+}++// TestDaemonStderrLogPathIsSeparate guards the invariant that the raw crash+// sink is a distinct file from the rotating log, so the child's inherited fds+// never hold daemon.log open (which would block rotation's rename on Windows).+func TestDaemonStderrLogPathIsSeparate(t *testing.T) {+ logPath := daemonLogPathForProfile("")+ errPath := daemonStderrLogPathForProfile("")+ if logPath == "" || errPath == "" {+ t.Skip("profile dir unavailable in this environment")+ }+ if logPath == errPath {+ t.Fatalf("stderr sink %q must differ from daemon.log %q", errPath, logPath)+ }+ if filepath.Base(errPath) != "daemon.err.log" {+ t.Errorf("stderr sink base = %q, want daemon.err.log", filepath.Base(errPath))+ }+ if filepath.Dir(logPath) != filepath.Dir(errPath) {+ t.Errorf("sinks should share a directory: %q vs %q", filepath.Dir(logPath), filepath.Dir(errPath))+ }+}diff --git a/server/cmd/multica/cmd_daemon_unix.go b/server/cmd/multica/cmd_daemon_unix.goindex 5c2a99c231..6c765eb69d 100644--- a/server/cmd/multica/cmd_daemon_unix.go+++ b/server/cmd/multica/cmd_daemon_unix.go@@ -30,10 +30,23 @@ func notifyShutdownContext(parent context.Context) (context.Context, context.Canreturn signal.NotifyContext(parent, syscall.SIGINT, syscall.SIGTERM)}+// repointStdioToErrLog is a no-op on Unix. The rotating daemon.log writer+// renames the active file on rotation, and on POSIX an open file descriptor —+// including one an older self-update launcher inherited onto this process's+// stdout/stderr — never blocks a rename or unlink, so the rotator works without+// re-pointing our standard handles. Only Windows needs to release the inherited+// handle (see the windows build for the rationale).+func repointStdioToErrLog(_ string) {}+func tailLogFile(logPath string, lines int, follow bool) error {args := []string{"-n", strconv.Itoa(lines)}if follow {- args = append(args, "-f")+ // -F (follow by name), not -f (follow by descriptor): after the rotator+ // renames daemon.log out from under us and opens a fresh one, -F reopens+ // the new file by path, whereas -f would stay glued to the rotated-away+ // inode and silently stop showing new output. Both GNU and BSD/macOS+ // tail support -F.+ args = append(args, "-F")}args = append(args, logPath)diff --git a/server/cmd/multica/cmd_daemon_windows.go b/server/cmd/multica/cmd_daemon_windows.goindex c90bbc865c..72834f3bce 100644--- a/server/cmd/multica/cmd_daemon_windows.go+++ b/server/cmd/multica/cmd_daemon_windows.go@@ -10,6 +10,8 @@ import ("os/signal""syscall""time"++ "golang.org/x/sys/windows")const (@@ -68,12 +70,58 @@ func notifyShutdownContext(parent context.Context) (context.Context, context.Canreturn signal.NotifyContext(parent, os.Interrupt, sigBreak)}+// repointStdioToErrLog releases the daemon.log handle that an older self-update+// launcher may have inherited onto this process's stdout/stderr, then makes the+// bounded crash sink the process's standard output/error. Go opens files+// without FILE_SHARE_DELETE, so while that inherited handle stays open the+// rotating writer's rename-on-rotate fails — permanently, until the next clean+// restart. Closing os.Stdout/os.Stderr drops the inherited handle; SetStdHandle+// then rebinds the standard handles so panics and any raw writes still land in+// daemon.err.log. Best-effort: on any failure we leave stdio as inherited.+func repointStdioToErrLog(errLogPath string) {+ f, err := openBoundedErrLog(errLogPath)+ if err != nil {+ return+ }+ _ = os.Stdout.Close()+ _ = os.Stderr.Close()+ h := windows.Handle(f.Fd())+ _ = windows.SetStdHandle(windows.STD_OUTPUT_HANDLE, h)+ _ = windows.SetStdHandle(windows.STD_ERROR_HANDLE, h)+ os.Stdout = f+ os.Stderr = f+}++// openLogForTail opens the log for reading with FILE_SHARE_DELETE (which Go's+// os.Open omits). Without delete-sharing, a long-lived reader — `daemon logs+// -f` — would block the rotator's rename and silently freeze rotation on+// Windows.+func openLogForTail(path string) (*os.File, error) {+ p, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return nil, err+ }+ h, err := windows.CreateFile(+ p,+ windows.GENERIC_READ,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil,+ windows.OPEN_EXISTING,+ windows.FILE_ATTRIBUTE_NORMAL,+ 0,+ )+ if err != nil {+ return nil, err+ }+ return os.NewFile(uintptr(h), path), nil+}+func tailLogFile(logPath string, lines int, follow bool) error {- f, err := os.Open(logPath)+ f, err := openLogForTail(logPath)if err != nil {return err}- defer f.Close()+ defer func() { f.Close() }()fi, err := f.Stat()if err != nil {@@ -118,12 +166,26 @@ func tailLogFile(logPath string, lines int, follow bool) error {return nil}+ offset, _ := f.Seek(0, io.SeekCurrent)buf := make([]byte, 4096)for {time.Sleep(500 * time.Millisecond)+ // Detect rotation: the rotator renamed our file away and created a+ // fresh, smaller one at the same path. Our handle still points at the+ // rotated-away file (EOF forever), so reopen by path and start over —+ // mirrors the Unix `tail -F` behaviour and the Desktop tail's+ // size-shrink reset.+ if fi, statErr := os.Stat(logPath); statErr == nil && fi.Size() < offset {+ if nf, reopenErr := openLogForTail(logPath); reopenErr == nil {+ f.Close()+ f = nf+ offset = 0+ }+ }n, readErr := f.Read(buf)if n > 0 {os.Stdout.Write(buf[:n])+ offset += int64(n)}if readErr != nil && readErr != io.EOF {return readErrdiff --git a/server/go.mod b/server/go.modindex 082461c5fd..9f2e8c9192 100644--- a/server/go.mod+++ b/server/go.mod@@ -30,7 +30,9 @@ require (github.com/spf13/cobra v1.10.2github.com/spf13/pflag v1.0.9golang.org/x/sync v0.20.0+ golang.org/x/sys v0.35.0google.golang.org/protobuf v1.36.8+ gopkg.in/natefinch/lumberjack.v2 v2.2.1gopkg.in/yaml.v3 v3.0.1)@@ -69,6 +71,5 @@ require (go.uber.org/atomic v1.11.0 // indirectgo.yaml.in/yaml/v2 v2.4.2 // indirectgolang.org/x/net v0.43.0 // indirect- golang.org/x/sys v0.35.0 // indirectgolang.org/x/text v0.35.0 // indirect)diff --git a/server/go.sum b/server/go.sumindex b30a6629d7..b880426295 100644--- a/server/go.sum+++ b/server/go.sum@@ -176,6 +176,8 @@ google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=+gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/server/internal/handler/quick_create_parent_test.go b/server/internal/handler/quick_create_parent_test.goindex 07a3fe6af8..d9f6999b02 100644--- a/server/internal/handler/quick_create_parent_test.go+++ b/server/internal/handler/quick_create_parent_test.go@@ -33,23 +33,27 @@ func TestQuickCreateIssueParentTrustBoundary(t *testing.T) {}ctx := context.Background()- // Resolve the seeded runtime + agent for this workspace, then bump the- // runtime metadata to a CLI version that clears MinQuickCreateCLIVersion.- // The seed runtime uses metadata '{}'::jsonb which would otherwise trip- // the daemon-version gate before we ever reach the parent_issue_id check.+ // Resolve the agent this request targets, then bump the CLI version on the+ // runtime BOUND TO that agent — that is the runtime the version gate checks+ // (the handler uses agent.RuntimeID). Picking an arbitrary `LIMIT 1`+ // agent_runtime is wrong when the shared test workspace holds more than one+ // runtime (other handler tests register their own): the LIMIT 1 row need+ // not be the agent's runtime, so the agent's real runtime stays on the+ // seed's empty '{}' metadata and trips the daemon-version gate before we+ // ever reach the parent_issue_id check.var runtimeID, agentID string- if err := testPool.QueryRow(ctx,- `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`,- testWorkspaceID,- ).Scan(&runtimeID); err != nil {- t.Fatalf("fetch runtime: %v", err)- }if err := testPool.QueryRow(ctx,`SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`,testWorkspaceID,).Scan(&agentID); err != nil {t.Fatalf("fetch agent: %v", err)}+ if err := testPool.QueryRow(ctx,+ `SELECT runtime_id FROM agent WHERE id = $1`,+ agentID,+ ).Scan(&runtimeID); err != nil {+ t.Fatalf("fetch agent runtime: %v", err)+ }if _, err := testPool.Exec(ctx,`UPDATE agent_runtime SET metadata = jsonb_build_object('cli_version', $1::text) WHERE id = $2`,agent.MinQuickCreateCLIVersion, runtimeID,diff --git a/server/internal/logger/logger.go b/server/internal/logger/logger.goindex ba183f3083..3b9c86c8ab 100644--- a/server/internal/logger/logger.go+++ b/server/internal/logger/logger.go@@ -1,6 +1,7 @@package loggerimport (+ "io""log/slog""net/http""os"@@ -49,6 +50,34 @@ func NewLogger(component string) *slog.Logger {return slog.New(handler).With("component", component)}+// StderrIsTerminal reports whether this process's stderr is attached to a+// terminal. The daemon uses it to distinguish a user running+// `daemon start --foreground` in a shell (log live to the terminal) from a+// detached/background child whose stderr is redirected to a file (rotate into+// daemon.log instead).+func StderrIsTerminal() bool {+ return isTerminal(os.Stderr)+}++// NewWriterLoggerDefault builds a named slog logger that writes structured,+// color-free output to w, and installs the same handler as the global slog+// default so bare slog.Info/Warn/... calls (e.g. from LoadConfig) land in the+// same sink. Intended for standalone processes that log to a file or rotating+// writer instead of a terminal (the daemon), where ANSI color is never wanted+// and every log line — injected-logger and package-global alike — must end up+// in the one managed file. Reads LOG_LEVEL like NewLogger/Init.+func NewWriterLoggerDefault(component string, w io.Writer) *slog.Logger {+ level := parseLevel(os.Getenv("LOG_LEVEL"))+ handler := tint.NewHandler(w, &tint.Options{+ Level: level,+ TimeFormat: "15:04:05.000",+ NoColor: true,+ })+ base := slog.New(handler)+ slog.SetDefault(base)+ return base.With("component", component)+}+// RequestAttrs extracts request_id, user_id, and X-Client-* metadata from// an HTTP request for use in handler-level structured logging. Mirrors the// global request logger so handler logs end up with the same observabilitydiff --git a/server/internal/logger/logger_test.go b/server/internal/logger/logger_test.gonew file mode 100644index 0000000000..c6466ccd54--- /dev/null+++ b/server/internal/logger/logger_test.go@@ -0,0 +1,39 @@+package logger++import (+ "bytes"+ "log/slog"+ "strings"+ "testing"+)++// TestNewWriterLoggerDefault verifies that both the returned component logger+// and bare slog.* calls write to the supplied writer (not os.Stderr), with the+// component tag attached and color escapes disabled. This is the contract the+// daemon relies on to funnel every log line into its rotating daemon.log.+func TestNewWriterLoggerDefault(t *testing.T) {+ // slog.SetDefault mutates global state, so this test cannot run in parallel+ // with others touching the default logger; restore it afterwards.+ prev := slog.Default()+ t.Cleanup(func() { slog.SetDefault(prev) })++ var buf bytes.Buffer+ log := NewWriterLoggerDefault("daemon", &buf)++ log.Error("boom", "code", 42)+ slog.Warn("global-line")++ out := buf.String()+ if !strings.Contains(out, "boom") {+ t.Errorf("component logger output missing message: %q", out)+ }+ if !strings.Contains(out, "component=daemon") {+ t.Errorf("output missing component tag: %q", out)+ }+ if !strings.Contains(out, "global-line") {+ t.Errorf("global slog.Warn did not reach the writer: %q", out)+ }+ if strings.Contains(out, "\x1b[") {+ t.Errorf("output contains ANSI color escapes, want NoColor: %q", out)+ }+}