Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(daemon): add periodic GC for workspace isolation directories
yushenff206baa6fb5
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex e9bc9ecd1c..56fea3cabc 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -141,6 +141,8 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Router.Post("/tasks/{taskId}/usage", h.ReportTaskUsage)r.Post("/tasks/{taskId}/messages", h.ReportTaskMessages)r.Get("/tasks/{taskId}/messages", h.ListTaskMessages)++ r.Get("/issues/{issueId}/gc-check", h.GetIssueGCCheck)})// Protected API routesdiff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 6351cb78ff..5f93bb306c 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -198,6 +198,21 @@ func (c *Client) ListWorkspaces(ctx context.Context) ([]WorkspaceInfo, error) {return workspaces, nil}+// IssueGCStatus holds the minimal issue info returned by the GC check endpoint.+type IssueGCStatus struct {+ Status string `json:"status"`+ UpdatedAt time.Time `json:"updated_at"`+}++// GetIssueGCCheck returns the status and updated_at of an issue for GC decisions.+func (c *Client) GetIssueGCCheck(ctx context.Context, issueID string) (*IssueGCStatus, error) {+ var resp IssueGCStatus+ if err := c.getJSON(ctx, fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), &resp); err != nil {+ return nil, err+ }+ return &resp, nil+}+func (c *Client) Deregister(ctx context.Context, runtimeIDs []string) error {return c.postJSON(ctx, "/api/daemon/deregister", map[string]any{"runtime_ids": runtimeIDs,diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex fc0fcad7bd..1d8ed6dbc6 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -20,6 +20,9 @@ const (DefaultWorkspaceSyncInterval = 30 * time.SecondDefaultHealthPort = 19514DefaultMaxConcurrentTasks = 20+ DefaultGCInterval = 1 * time.Hour+ DefaultGCTTL = 5 * 24 * time.Hour // 5 days+ DefaultGCOrphanTTL = 30 * 24 * time.Hour // 30 days)// Config holds all daemon configuration.@@ -35,6 +38,10 @@ type Config struct {KeepEnvAfterTask bool // preserve env after task for debuggingHealthPort int // local HTTP port for health checks (default: 19514)MaxConcurrentTasks int // max tasks running in parallel (default: 20)+ GCEnabled bool // enable periodic workspace garbage collection (default: true)+ GCInterval time.Duration // how often the GC loop runs (default: 1h)+ GCTTL time.Duration // clean dirs whose issue is done/canceled and updated_at < now()-TTL (default: 5d)+ GCOrphanTTL time.Duration // clean orphan dirs (no meta or unknown issue) older than this (default: 30d)PollInterval time.DurationHeartbeatInterval time.DurationAgentTimeout time.Duration@@ -203,6 +210,24 @@ func LoadConfig(overrides Overrides) (Config, error) {// Keep env after task: env > default (false)keepEnv := os.Getenv("MULTICA_KEEP_ENV_AFTER_TASK") == "true" || os.Getenv("MULTICA_KEEP_ENV_AFTER_TASK") == "1"+ // GC config: env > defaults+ gcEnabled := true+ if v := os.Getenv("MULTICA_GC_ENABLED"); v == "false" || v == "0" {+ gcEnabled = false+ }+ gcInterval, err := durationFromEnv("MULTICA_GC_INTERVAL", DefaultGCInterval)+ if err != nil {+ return Config{}, err+ }+ gcTTL, err := durationFromEnv("MULTICA_GC_TTL", DefaultGCTTL)+ if err != nil {+ return Config{}, err+ }+ gcOrphanTTL, err := durationFromEnv("MULTICA_GC_ORPHAN_TTL", DefaultGCOrphanTTL)+ if err != nil {+ return Config{}, err+ }+return Config{ServerBaseURL: serverBaseURL,DaemonID: daemonID,@@ -212,6 +237,10 @@ func LoadConfig(overrides Overrides) (Config, error) {Agents: agents,WorkspacesRoot: workspacesRoot,KeepEnvAfterTask: keepEnv,+ GCEnabled: gcEnabled,+ GCInterval: gcInterval,+ GCTTL: gcTTL,+ GCOrphanTTL: gcOrphanTTL,HealthPort: healthPort,MaxConcurrentTasks: maxConcurrentTasks,PollInterval: pollInterval,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 42da52d116..7c1acfeb45 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -102,6 +102,7 @@ func (d *Daemon) Run(ctx context.Context) error {go d.heartbeatLoop(ctx)go d.usageScanLoop(ctx)+ go d.gcLoop(ctx)go d.serveHealth(ctx, healthLn, time.Now())return d.pollLoop(ctx)}@@ -928,6 +929,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo// the same (agent, issue) pair. The work_dir path is stored in DB on// task completion and passed back via PriorWorkDir on the next claim.+ // Write GC metadata so the periodic GC loop can look up the issue later.+ if err := env.WriteGCMeta(task.IssueID, task.WorkspaceID); err != nil {+ taskLog.Warn("write gc meta failed (non-fatal)", "error", err)+ }+prompt := BuildPrompt(task)// Pass the daemon's auth credentials and context so the spawned agent CLIdiff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 87ace616a9..8fbee24dd4 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -4,10 +4,12 @@package execenvimport (+ "encoding/json""fmt""log/slog""os""path/filepath"+ "time")// RepoContextForEnv describes a workspace repo available for checkout.@@ -156,6 +158,46 @@ func Reuse(workDir, provider string, task TaskContextForEnv, logger *slog.Loggerreturn env}+// GCMeta is persisted to .gc_meta.json inside the env root so the GC loop+// can determine which issue this directory belongs to.+type GCMeta struct {+ IssueID string `json:"issue_id"`+ WorkspaceID string `json:"workspace_id"`+ CompletedAt time.Time `json:"completed_at"`+}++const gcMetaFile = ".gc_meta.json"++// WriteGCMeta writes GC metadata into the environment root directory.+func (env *Environment) WriteGCMeta(issueID, workspaceID string) error {+ if env == nil {+ return nil+ }+ meta := GCMeta{+ IssueID: issueID,+ WorkspaceID: workspaceID,+ CompletedAt: time.Now().UTC(),+ }+ data, err := json.Marshal(meta)+ if err != nil {+ return fmt.Errorf("marshal gc meta: %w", err)+ }+ return os.WriteFile(filepath.Join(env.RootDir, gcMetaFile), data, 0o644)+}++// ReadGCMeta reads GC metadata from a task directory root.+func ReadGCMeta(envRoot string) (*GCMeta, error) {+ data, err := os.ReadFile(filepath.Join(envRoot, gcMetaFile))+ if err != nil {+ return nil, err+ }+ var meta GCMeta+ if err := json.Unmarshal(data, &meta); err != nil {+ return nil, err+ }+ return &meta, nil+}+// Cleanup tears down the execution environment.// If removeAll is true, the entire env root is deleted. Otherwise, workdir is// removed but output/ and logs/ are preserved for debugging.diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.gonew file mode 100644index 0000000000..be32c8d94a--- /dev/null+++ b/server/internal/daemon/gc.go@@ -0,0 +1,213 @@+package daemon++import (+ "context"+ "errors"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// gcLoop periodically scans local workspace directories and removes those+// whose issue is done/canceled and hasn't been updated within the configured TTL.+func (d *Daemon) gcLoop(ctx context.Context) {+ if !d.cfg.GCEnabled {+ d.logger.Info("gc: disabled")+ return+ }+ d.logger.Info("gc: started", "interval", d.cfg.GCInterval, "ttl", d.cfg.GCTTL, "orphan_ttl", d.cfg.GCOrphanTTL)++ // Run once at startup after a short delay (let the daemon finish initializing).+ if err := sleepWithContext(ctx, 30*time.Second); err != nil {+ return+ }+ d.runGC(ctx)++ ticker := time.NewTicker(d.cfg.GCInterval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ d.runGC(ctx)+ }+ }+}++// runGC performs a single GC scan across all workspace directories.+func (d *Daemon) runGC(ctx context.Context) {+ root := d.cfg.WorkspacesRoot+ entries, err := os.ReadDir(root)+ if err != nil {+ if os.IsNotExist(err) {+ return+ }+ d.logger.Warn("gc: read workspaces root failed", "error", err)+ return+ }++ var cleaned, skipped, orphaned int+ for _, wsEntry := range entries {+ if !wsEntry.IsDir() || wsEntry.Name() == ".repos" {+ continue+ }+ wsDir := filepath.Join(root, wsEntry.Name())+ c, s, o := d.gcWorkspace(ctx, wsDir)+ cleaned += c+ skipped += s+ orphaned += o+ }++ // Prune stale worktree references from all bare repo caches.+ d.pruneRepoWorktrees(root)++ if cleaned > 0 || orphaned > 0 {+ d.logger.Info("gc: cycle complete", "cleaned", cleaned, "orphaned", orphaned, "skipped", skipped)+ }+}++// gcWorkspace scans task directories inside a single workspace directory.+func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string) (cleaned, skipped, orphaned int) {+ taskEntries, err := os.ReadDir(wsDir)+ if err != nil {+ d.logger.Warn("gc: read workspace dir failed", "dir", wsDir, "error", err)+ return+ }++ for _, entry := range taskEntries {+ if ctx.Err() != nil {+ return+ }+ if !entry.IsDir() {+ continue+ }+ taskDir := filepath.Join(wsDir, entry.Name())+ action := d.shouldCleanTaskDir(ctx, taskDir)+ switch action {+ case gcActionClean:+ d.cleanTaskDir(taskDir)+ cleaned+++ case gcActionOrphan:+ d.cleanTaskDir(taskDir)+ orphaned+++ default:+ skipped+++ }+ }+ return+}++type gcAction int++const (+ gcActionSkip gcAction = iota+ gcActionClean // issue is done/canceled and stale+ gcActionOrphan // no meta or unknown issue and dir is old+)++// shouldCleanTaskDir decides whether a task directory should be removed.+func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcAction {+ meta, err := execenv.ReadGCMeta(taskDir)+ if err != nil {+ // No .gc_meta.json — check mtime for orphan cleanup.+ info, statErr := os.Stat(taskDir)+ if statErr != nil {+ return gcActionSkip+ }+ if time.Since(info.ModTime()) > d.cfg.GCOrphanTTL {+ d.logger.Info("gc: orphan directory (no meta)", "dir", taskDir, "age", time.Since(info.ModTime()).Round(time.Hour))+ return gcActionOrphan+ }+ return gcActionSkip+ }++ status, err := d.client.GetIssueGCCheck(ctx, meta.IssueID)+ if err != nil {+ var reqErr *requestError+ if errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusNotFound {+ // Issue deleted — check mtime for orphan cleanup.+ info, statErr := os.Stat(taskDir)+ if statErr != nil {+ return gcActionSkip+ }+ if time.Since(info.ModTime()) > d.cfg.GCOrphanTTL {+ d.logger.Info("gc: orphan directory (issue deleted)", "dir", taskDir, "issue", meta.IssueID)+ return gcActionOrphan+ }+ }+ // API error (network, auth, etc.) — skip and retry next cycle.+ return gcActionSkip+ }++ if (status.Status == "done" || status.Status == "canceled") &&+ time.Since(status.UpdatedAt) > d.cfg.GCTTL {+ d.logger.Info("gc: eligible for cleanup",+ "dir", filepath.Base(taskDir),+ "issue", meta.IssueID,+ "status", status.Status,+ "updated_at", status.UpdatedAt.Format(time.RFC3339),+ )+ return gcActionClean+ }++ return gcActionSkip+}++// cleanTaskDir removes a task directory and logs the result.+func (d *Daemon) cleanTaskDir(taskDir string) {+ if err := os.RemoveAll(taskDir); err != nil {+ d.logger.Warn("gc: remove task dir failed", "dir", taskDir, "error", err)+ } else {+ d.logger.Info("gc: removed", "dir", taskDir)+ }+}++// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache.+func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {+ reposRoot := filepath.Join(workspacesRoot, ".repos")+ wsEntries, err := os.ReadDir(reposRoot)+ if err != nil {+ return+ }++ for _, wsEntry := range wsEntries {+ if !wsEntry.IsDir() {+ continue+ }+ wsRepoDir := filepath.Join(reposRoot, wsEntry.Name())+ repoEntries, err := os.ReadDir(wsRepoDir)+ if err != nil {+ continue+ }+ for _, repoEntry := range repoEntries {+ if !repoEntry.IsDir() {+ continue+ }+ barePath := filepath.Join(wsRepoDir, repoEntry.Name())+ if !isBareRepo(barePath) {+ continue+ }+ cmd := exec.Command("git", "-C", barePath, "worktree", "prune")+ if out, err := cmd.CombinedOutput(); err != nil {+ d.logger.Warn("gc: worktree prune failed",+ "repo", barePath,+ "output", strings.TrimSpace(string(out)),+ "error", err,+ )+ }+ }+ }+}++// isBareRepo checks if a path looks like a bare git repository.+func isBareRepo(path string) bool {+ _, err := os.Stat(filepath.Join(path, "HEAD"))+ return err == nil+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 58b5ba600b..0f066390b0 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -842,3 +842,17 @@ func (h *Handler) GetIssueUsage(w http.ResponseWriter, r *http.Request) {"task_count": row.TaskCount,})}++// GetIssueGCCheck returns minimal issue info needed by the daemon GC loop.+func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {+ issueID := chi.URLParam(r, "issueId")+ issue, err := h.Queries.GetIssue(r.Context(), parseUUID(issueID))+ if err != nil {+ writeError(w, http.StatusNotFound, "issue not found")+ return+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "status": issue.Status,+ "updated_at": issue.UpdatedAt.Time,+ })+}