Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(gc): batch issue reconciliation (#5534)
Multica Eve18d41151eb16
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 6ac9e6dd45..2a305c0993 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -180,7 +180,7 @@ Daemon behavior is configured via flags or environment variables:| Runtime name | `--runtime-name` | `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` || Workspaces root | — | `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` || GC enabled | — | `MULTICA_GC_ENABLED` | `true` (set `false`/`0` to disable) |-| GC scan interval | — | `MULTICA_GC_INTERVAL` | `1h` |+| GC scan interval | — | `MULTICA_GC_INTERVAL` | `2h` || GC TTL (done/cancelled issues) | — | `MULTICA_GC_TTL` | `24h` || GC orphan TTL (no `.gc_meta.json`) | — | `MULTICA_GC_ORPHAN_TTL` | `72h` || GC artifact TTL (open issues) | — | `MULTICA_GC_ARTIFACT_TTL` | `12h` (set `0` to disable) |diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 9b1eb3e7d5..6cb4d95e6c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -799,6 +799,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/tasks/{taskId}/messages", h.ListTaskMessages)r.Post("/tasks/{taskId}/cancel-ack", h.AckTaskCancelled)+ r.Post("/workspaces/{workspaceId}/issues/gc-check", h.BatchIssueGCCheck)r.Get("/issues/{issueId}/gc-check", h.GetIssueGCCheck)r.Get("/chat-sessions/{sessionId}/gc-check", h.GetChatSessionGCCheck)r.Get("/autopilot-runs/{runId}/gc-check", h.GetAutopilotRunGCCheck)diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 196866f65c..eb82f73f61 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -111,6 +111,8 @@ type Client struct {workspaceCache []WorkspaceInfoworkspaceCacheValid boollegacyWorkspaceEndpointEnabled bool+ issueGCBatchMu sync.Mutex+ legacyIssueGCBatchEnabled bool}// NewClient creates a new daemon API client.@@ -590,6 +592,88 @@ type IssueGCStatus struct {UpdatedAt time.Time `json:"updated_at"`}+// IssueGCCheckResult is one explicit issue result from the workspace batch+// endpoint. Found=false deliberately covers both a deleted issue and an ID+// outside the requested workspace, preserving the server's anti-enumeration+// contract. Err is only populated by the legacy per-issue fallback.+type IssueGCCheckResult struct {+ ID string `json:"id"`+ Found bool `json:"found"`+ Status string `json:"status,omitempty"`+ UpdatedAt time.Time `json:"updated_at,omitempty"`+ Err error `json:"-"`+}++type issueGCBatchResponse struct {+ Issues []IssueGCCheckResult `json:"issues"`+}++// isIssueGCBatchUnsupported distinguishes chi's unmatched-route response on an+// older server from the JSON 404 returned by a current server when the caller+// cannot access the requested workspace. Only the former is a compatibility+// signal; falling back on an authorization 404 would turn one denied request+// into hundreds of legacy probes.+func isIssueGCBatchUnsupported(err error) bool {+ var reqErr *requestError+ return errors.As(err, &reqErr) &&+ reqErr.StatusCode == http.StatusNotFound &&+ strings.TrimSpace(reqErr.Body) == "404 page not found"+}++// GetIssueGCChecks reconciles a workspace's issue IDs in one request. When a+// new daemon reaches an older server that does not have the batch route, the+// first 404 permanently switches this client process to the legacy per-issue+// endpoint. Other batch failures are returned without fan-out so a transient+// server problem cannot amplify request volume.+func (c *Client) GetIssueGCChecks(ctx context.Context, workspaceID string, issueIDs []string) (map[string]IssueGCCheckResult, error) {+ c.issueGCBatchMu.Lock()+ defer c.issueGCBatchMu.Unlock()++ if c.legacyIssueGCBatchEnabled {+ return c.getLegacyIssueGCChecks(ctx, issueIDs), nil+ }++ path := fmt.Sprintf("/api/daemon/workspaces/%s/issues/gc-check", workspaceID)+ var resp issueGCBatchResponse+ err := c.postJSON(ctx, path, map[string]any{"issue_ids": issueIDs}, &resp)+ if err != nil {+ if !isIssueGCBatchUnsupported(err) {+ return nil, err+ }+ c.legacyIssueGCBatchEnabled = true+ return c.getLegacyIssueGCChecks(ctx, issueIDs), nil+ }++ results := make(map[string]IssueGCCheckResult, len(resp.Issues))+ for _, result := range resp.Issues {+ results[result.ID] = result+ }+ return results, nil+}++func (c *Client) getLegacyIssueGCChecks(ctx context.Context, issueIDs []string) map[string]IssueGCCheckResult {+ results := make(map[string]IssueGCCheckResult, len(issueIDs))+ for _, issueID := range issueIDs {+ status, err := c.GetIssueGCCheck(ctx, issueID)+ if err != nil {+ var reqErr *requestError+ if errors.As(err, &reqErr) && reqErr.StatusCode == http.StatusNotFound {+ results[issueID] = IssueGCCheckResult{ID: issueID, Found: false}+ } else {+ results[issueID] = IssueGCCheckResult{ID: issueID, Err: err}+ }+ continue+ }+ results[issueID] = IssueGCCheckResult{+ ID: issueID,+ Found: true,+ Status: status.Status,+ UpdatedAt: status.UpdatedAt,+ }+ }+ return results+}+// 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 IssueGCStatusdiff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.goindex 936f1c0cad..e5e6a2d9c4 100644--- a/server/internal/daemon/client_test.go+++ b/server/internal/daemon/client_test.go@@ -214,6 +214,38 @@ func TestIsTransientError(t *testing.T) {}}+func TestIsIssueGCBatchUnsupported(t *testing.T) {+ tests := []struct {+ name string+ err error+ want bool+ }{+ {+ name: "old server unmatched route",+ err: &requestError{StatusCode: http.StatusNotFound, Body: "404 page not found"},+ want: true,+ },+ {+ name: "workspace access denied",+ err: &requestError{StatusCode: http.StatusNotFound, Body: `{"error":"not found"}`},+ want: false,+ },+ {+ name: "transient server error",+ err: &requestError{StatusCode: http.StatusInternalServerError, Body: "failure"},+ want: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := isIssueGCBatchUnsupported(tt.err); got != tt.want {+ t.Fatalf("isIssueGCBatchUnsupported() = %v, want %v", got, tt.want)+ }+ })+ }+}+func TestPostJSONWithRetry_TransientThenSuccess(t *testing.T) {defer noSleepRetry(t)()diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex cc16834739..1a05881ecf 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -65,7 +65,7 @@ const (DefaultWorkspaceSyncMaxBackoff = 30 * time.MinuteDefaultHealthPort = 19514DefaultMaxConcurrentTasks = 20- DefaultGCInterval = 1 * time.Hour+ DefaultGCInterval = 2 * time.HourDefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open longDefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues@@ -97,7 +97,7 @@ type Config struct {HealthPort 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)+ 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)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 // when a task has been completed for at least this long but its issue is still open, drop regenerable artifacts (default: 12h, set 0 to disable)diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex fd2202f262..c006dd85ce 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -28,6 +28,12 @@ func TestPatternsFromEnv_DefaultsWhenUnset(t *testing.T) {}}+func TestDefaultGCIntervalIsTwoHours(t *testing.T) {+ if DefaultGCInterval != 2*time.Hour {+ t.Fatalf("DefaultGCInterval = %s, want 2h", DefaultGCInterval)+ }+}+func TestPatternsFromEnv_DropsSeparatorBearingEntries(t *testing.T) {t.Setenv("MULTICA_GC_ARTIFACT_PATTERNS", "node_modules, .next ,foo/bar, ../etc, ,target")got := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", nil)diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex dc4470e9df..f80800788d 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -253,8 +253,10 @@ type Daemon struct {pauseClaims bool // when true, the batch poller skips claimingclaimsInFlight int // pollers that have decided to claim but haven't yet handed the task off to handleTask- activeEnvRootsMu sync.Mutex- activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)+ activeEnvRootsMu sync.Mutex+ activeEnvRootsCond *sync.Cond // signalled when an in-flight env-root GC mutation finishes+ activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)+ deletingEnvRoots map[string]bool // env roots reserved by GC; new tasks wait until the mutation finishesactiveCodexStoresMu sync.MutexactiveCodexStoresCond *sync.Cond // signalled when an in-flight store deletion finishes, so a blocked markActive can proceed@@ -311,6 +313,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {resolvedPaths: make(map[string]healedAgent),wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),+ deletingEnvRoots: make(map[string]bool),activeCodexStores: make(map[string]int),deletingCodexStores: make(map[string]bool),localPathLocks: NewLocalPathLocker(),@@ -322,6 +325,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {workspaceChanges: newWorkspaceChangeSignal(),wsRPC: newWSRPCClient(wsRPCResponseGrace),}+ d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)d.runner = taskRunnerFunc(d.runTask)d.runUpdateFn = d.runUpdate@@ -5088,6 +5092,10 @@ func (d *Daemon) markActiveEnvRoot(envRoot string) {}d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()+ d.ensureActiveEnvRootStateLocked()+ for d.deletingEnvRoots[envRoot] {+ d.activeEnvRootsCond.Wait()+ }d.activeEnvRoots[envRoot]++}@@ -5097,6 +5105,7 @@ func (d *Daemon) unmarkActiveEnvRoot(envRoot string) {}d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()+ d.ensureActiveEnvRootStateLocked()if d.activeEnvRoots[envRoot] <= 1 {delete(d.activeEnvRoots, envRoot)return@@ -5107,9 +5116,46 @@ func (d *Daemon) unmarkActiveEnvRoot(envRoot string) {func (d *Daemon) isActiveEnvRoot(envRoot string) bool {d.activeEnvRootsMu.Lock()defer d.activeEnvRootsMu.Unlock()+ d.ensureActiveEnvRootStateLocked()return d.activeEnvRoots[envRoot] > 0}+func (d *Daemon) ensureActiveEnvRootStateLocked() {+ if d.activeEnvRoots == nil {+ d.activeEnvRoots = make(map[string]int)+ }+ if d.deletingEnvRoots == nil {+ d.deletingEnvRoots = make(map[string]bool)+ }+ if d.activeEnvRootsCond == nil {+ d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)+ }+}++// reserveEnvRootForGC atomically confirms that no live task is using envRoot+// and prevents a new task from entering until release runs. This closes the+// check-then-remove race between the GC loop and task startup: either GC sees+// the active task and skips, or task startup waits for the mutation to finish+// and recreates/uses the post-GC environment.+func (d *Daemon) reserveEnvRootForGC(envRoot string) (release func(), ok bool) {+ if envRoot == "" {+ return nil, false+ }+ d.activeEnvRootsMu.Lock()+ defer d.activeEnvRootsMu.Unlock()+ d.ensureActiveEnvRootStateLocked()+ if d.activeEnvRoots[envRoot] > 0 || d.deletingEnvRoots[envRoot] {+ return nil, false+ }+ d.deletingEnvRoots[envRoot] = true+ return func() {+ d.activeEnvRootsMu.Lock()+ delete(d.deletingEnvRoots, envRoot)+ d.activeEnvRootsCond.Broadcast()+ d.activeEnvRootsMu.Unlock()+ }, true+}+// markActiveCodexStore records that a task is about to use the given per-issue// Codex session store, so the GC never reclaims it mid-task — the store lives// outside the env root, so isActiveEnvRoot does not cover it (MUL-4424). If a GCdiff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 0dd003c23f..1073ecec4e 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -114,6 +114,7 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)}cleanedHere := 0+ issueCandidates := make([]issueGCCandidate, 0, len(taskEntries))for _, entry := range taskEntries {if ctx.Err() != nil {return@@ -122,35 +123,19 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)continue}taskDir := filepath.Join(wsDir, entry.Name())- action := d.shouldCleanTaskDir(ctx, taskDir)- switch action {- case gcActionClean:- bytes := dirSize(taskDir)- d.cleanTaskDir(taskDir)- stats.cleaned++- stats.bytesReclaimed += bytes- cleanedHere++- case gcActionOrphan:- bytes := dirSize(taskDir)- d.cleanTaskDir(taskDir)- stats.orphaned++- stats.bytesReclaimed += bytes- cleanedHere++- case gcActionCleanArtifacts:- removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, d.cfg.GCArtifactPatterns)- if removed > 0 {- stats.artifactDirs++- stats.artifactRemoved += removed- stats.bytesReclaimed += bytes- for k, v := range perPattern {- stats.byPattern[k] += v- }- }- stats.skipped++ // task dir itself preserved- default:+ if d.isActiveEnvRoot(taskDir) {stats.skipped+++ continue+ }+ meta, metaErr := execenv.ReadGCMeta(taskDir)+ if metaErr == nil && meta.Kind == execenv.GCKindIssue && strings.TrimSpace(meta.IssueID) != "" {+ issueCandidates = append(issueCandidates, issueGCCandidate{taskDir: taskDir, meta: meta})+ continue}+ action := d.shouldCleanTaskDir(ctx, taskDir)+ cleanedHere += d.applyGCAction(taskDir, action, stats)}+ cleanedHere += d.gcWorkspaceIssues(ctx, filepath.Base(wsDir), issueCandidates, stats)// Remove the workspace directory itself if it's now empty.if cleanedHere > 0 {@@ -161,6 +146,114 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)}}+const issueGCBatchSize = 500++type issueGCCandidate struct {+ taskDir string+ meta *execenv.GCMeta+}++// gcWorkspaceIssues resolves all issue-backed task dirs with a bounded number+// of workspace-level requests. Multiple task dirs for the same issue share one+// result. The client transparently falls back to the legacy per-issue endpoint+// when it is connected to an older server.+func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, candidates []issueGCCandidate, stats *gcStats) int {+ if len(candidates) == 0 {+ return 0+ }++ issueIDs := make([]string, 0, len(candidates))+ seen := make(map[string]struct{}, len(candidates))+ for _, candidate := range candidates {+ issueID := strings.TrimSpace(candidate.meta.IssueID)+ if _, ok := seen[issueID]; ok {+ continue+ }+ seen[issueID] = struct{}{}+ issueIDs = append(issueIDs, issueID)+ }++ results := make(map[string]IssueGCCheckResult, len(issueIDs))+ for start := 0; start < len(issueIDs); start += issueGCBatchSize {+ if ctx.Err() != nil {+ break+ }+ end := min(start+issueGCBatchSize, len(issueIDs))+ chunkResults, err := d.client.GetIssueGCChecks(ctx, workspaceID, issueIDs[start:end])+ if err != nil {+ d.logger.Warn("gc: batch issue check failed",+ "workspace", workspaceID,+ "count", end-start,+ "error", err,+ )+ continue+ }+ for issueID, result := range chunkResults {+ results[issueID] = result+ }+ }++ cleaned := 0+ for i, candidate := range candidates {+ if ctx.Err() != nil {+ stats.skipped += len(candidates) - i+ break+ }+ issueID := strings.TrimSpace(candidate.meta.IssueID)+ result, ok := results[issueID]+ if !ok || result.Err != nil {+ stats.skipped+++ continue+ }+ action := d.gcDecisionIssueResult(candidate.taskDir, candidate.meta, result)+ action = applyLocalDirectoryGCOverride(candidate.meta, action)+ cleaned += d.applyGCAction(candidate.taskDir, action, stats)+ }+ return cleaned+}++// applyGCAction performs one decision and updates cycle stats. Each mutation+// atomically reserves the env root because a task can start while the server+// reconciliation request is in flight.+func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats) int {+ if action != gcActionSkip {+ release, ok := d.reserveEnvRootForGC(taskDir)+ if !ok {+ stats.skipped+++ return 0+ }+ defer release()+ }+ switch action {+ case gcActionClean:+ bytes := dirSize(taskDir)+ d.cleanTaskDir(taskDir)+ stats.cleaned+++ stats.bytesReclaimed += bytes+ return 1+ case gcActionOrphan:+ bytes := dirSize(taskDir)+ d.cleanTaskDir(taskDir)+ stats.orphaned+++ stats.bytesReclaimed += bytes+ return 1+ case gcActionCleanArtifacts:+ removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, d.cfg.GCArtifactPatterns)+ if removed > 0 {+ stats.artifactDirs+++ stats.artifactRemoved += removed+ stats.bytesReclaimed += bytes+ for k, v := range perPattern {+ stats.byPattern[k] += v+ }+ }+ stats.skipped++ // task dir itself preserved+ default:+ stats.skipped+++ }+ return 0+}+type gcAction intconst (@@ -189,6 +282,10 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActio}action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)+ return applyLocalDirectoryGCOverride(meta, action)+}++func applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAction) gcAction {if !meta.LocalDirectory {return action}@@ -279,14 +376,27 @@ func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *execreturn gcActionSkip}- if (status.Status == "done" || status.Status == "cancelled") &&- time.Since(status.UpdatedAt) > d.cfg.GCTTL {+ return d.gcDecisionIssueResult(taskDir, meta, IssueGCCheckResult{+ ID: meta.IssueID,+ Found: true,+ Status: status.Status,+ UpdatedAt: status.UpdatedAt,+ })+}++func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, result IssueGCCheckResult) gcAction {+ if !result.Found {+ return d.orphanByMTime(taskDir, "issue not accessible")+ }++ if (result.Status == "done" || result.Status == "cancelled") &&+ time.Since(result.UpdatedAt) > d.cfg.GCTTL {d.logger.Info("gc: eligible for cleanup","dir", filepath.Base(taskDir),"kind", "issue","issue", meta.IssueID,- "status", status.Status,- "updated_at", status.UpdatedAt.Format(time.RFC3339),+ "status", result.Status,+ "updated_at", result.UpdatedAt.Format(time.RFC3339),)return gcActionClean}@@ -297,7 +407,7 @@ func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *exec"dir", filepath.Base(taskDir),"kind", "issue","issue", meta.IssueID,- "status", status.Status,+ "status", result.Status,"completed_at", meta.CompletedAt.Format(time.RFC3339),)return gcActionCleanArtifactsdiff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex 4259a65313..d506a52cb8 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -304,6 +304,142 @@ func TestGcWorkspace_CleansEmptyWorkspaceDir(t *testing.T) {}}+func TestGCWorkspace_BatchesAndDeduplicatesIssueChecks(t *testing.T) {+ doneID := "77777777-7777-7777-7777-777777777771"+ openID := "77777777-7777-7777-7777-777777777772"+ var batchRequests, legacyRequests int++ mux := http.NewServeMux()+ mux.HandleFunc("/api/daemon/workspaces/ws-batch/issues/gc-check", func(w http.ResponseWriter, r *http.Request) {+ batchRequests+++ if r.Method != http.MethodPost {+ t.Fatalf("batch method = %s, want POST", r.Method)+ }+ var body struct {+ IssueIDs []string `json:"issue_ids"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatalf("decode batch request: %v", err)+ }+ if got, want := strings.Join(body.IssueIDs, ","), doneID+","+openID; got != want {+ t.Fatalf("batch issue_ids = %q, want %q", got, want)+ }+ json.NewEncoder(w).Encode(map[string]any{"issues": []map[string]any{+ {"id": doneID, "found": true, "status": "done", "updated_at": time.Now().Add(-10 * 24 * time.Hour)},+ {"id": openID, "found": true, "status": "in_progress", "updated_at": time.Now()},+ }})+ })+ mux.HandleFunc("/api/daemon/issues/", func(w http.ResponseWriter, r *http.Request) {+ legacyRequests+++ http.Error(w, "legacy endpoint must not be called", http.StatusInternalServerError)+ })++ d := newGCTestDaemon(t, mux)+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-batch")+ doneA := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-batch", "done-a", &execenv.GCMeta{+ IssueID: doneID, WorkspaceID: "ws-batch", CompletedAt: time.Now().Add(-10 * 24 * time.Hour),+ })+ doneB := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-batch", "done-b", &execenv.GCMeta{+ IssueID: doneID, WorkspaceID: "ws-batch", CompletedAt: time.Now().Add(-10 * 24 * time.Hour),+ })+ open := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-batch", "open", &execenv.GCMeta{+ IssueID: openID, WorkspaceID: "ws-batch", CompletedAt: time.Now(),+ })++ stats := &gcStats{byPattern: map[string]int{}}+ d.gcWorkspace(context.Background(), wsDir, stats)++ if batchRequests != 1 || legacyRequests != 0 {+ t.Fatalf("requests: batch=%d legacy=%d, want batch=1 legacy=0", batchRequests, legacyRequests)+ }+ for _, dir := range []string{doneA, doneB} {+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("done task dir %s was not removed", dir)+ }+ }+ if _, err := os.Stat(open); err != nil {+ t.Fatalf("open task dir should remain: %v", err)+ }+ if stats.cleaned != 2 || stats.skipped != 1 {+ t.Fatalf("stats = cleaned:%d skipped:%d, want 2/1", stats.cleaned, stats.skipped)+ }+}++func TestGCWorkspace_OldServerFallbackIsCached(t *testing.T) {+ issueA := "77777777-7777-7777-7777-777777777773"+ issueB := "77777777-7777-7777-7777-777777777774"+ var batchRequests, legacyRequests int++ mux := http.NewServeMux()+ mux.HandleFunc("/api/daemon/workspaces/", func(w http.ResponseWriter, r *http.Request) {+ batchRequests+++ http.NotFound(w, r)+ })+ mux.HandleFunc("/api/daemon/issues/", func(w http.ResponseWriter, r *http.Request) {+ legacyRequests+++ json.NewEncoder(w).Encode(map[string]any{+ "status": "done", "updated_at": time.Now().Add(-10 * 24 * time.Hour),+ })+ })++ d := newGCTestDaemon(t, mux)+ for i, tc := range []struct {+ workspace string+ issueID string+ }{{"ws-legacy-a", issueA}, {"ws-legacy-b", issueB}} {+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, tc.workspace)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, tc.workspace, fmt.Sprintf("task-%d", i), &execenv.GCMeta{+ IssueID: tc.issueID, WorkspaceID: tc.workspace, CompletedAt: time.Now().Add(-10 * 24 * time.Hour),+ })+ d.gcWorkspace(context.Background(), wsDir, &gcStats{byPattern: map[string]int{}})+ if _, err := os.Stat(taskDir); !os.IsNotExist(err) {+ t.Fatalf("legacy fallback did not clean %s", taskDir)+ }+ }++ if batchRequests != 1 {+ t.Fatalf("batch requests = %d, want 1 capability probe", batchRequests)+ }+ if legacyRequests != 2 {+ t.Fatalf("legacy requests = %d, want 2", legacyRequests)+ }+}++func TestGCWorkspace_BatchFailureDoesNotFanOutOrClean(t *testing.T) {+ issueID := "77777777-7777-7777-7777-777777777775"+ var batchRequests, legacyRequests int++ mux := http.NewServeMux()+ mux.HandleFunc("/api/daemon/workspaces/ws-fail/issues/gc-check", func(w http.ResponseWriter, r *http.Request) {+ batchRequests+++ http.Error(w, "temporary failure", http.StatusInternalServerError)+ })+ mux.HandleFunc("/api/daemon/issues/", func(w http.ResponseWriter, r *http.Request) {+ legacyRequests+++ json.NewEncoder(w).Encode(map[string]any{+ "status": "done", "updated_at": time.Now().Add(-10 * 24 * time.Hour),+ })+ })++ d := newGCTestDaemon(t, mux)+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-fail")+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-fail", "task", &execenv.GCMeta{+ IssueID: issueID, WorkspaceID: "ws-fail", CompletedAt: time.Now().Add(-10 * 24 * time.Hour),+ })+ stats := &gcStats{byPattern: map[string]int{}}+ d.gcWorkspace(context.Background(), wsDir, stats)++ if batchRequests != 1 || legacyRequests != 0 {+ t.Fatalf("requests: batch=%d legacy=%d, want batch=1 legacy=0", batchRequests, legacyRequests)+ }+ if _, err := os.Stat(taskDir); err != nil {+ t.Fatalf("task dir must remain on batch failure: %v", err)+ }+ if stats.cleaned != 0 || stats.orphaned != 0 || stats.skipped != 1 {+ t.Fatalf("unexpected stats after failure: %+v", stats)+ }+}+func TestShouldCleanTaskDir_OpenIssueArtifactCleanup(t *testing.T) {t.Parallel()issueID := "88888888-8888-8888-8888-888888888888"@@ -629,6 +765,34 @@ func TestActiveEnvRootRefcount(t *testing.T) {}}+func TestReserveEnvRootForGCIsExclusive(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ root := "/tmp/fake/gc-reservation"++ d.markActiveEnvRoot(root)+ if _, ok := d.reserveEnvRootForGC(root); ok {+ t.Fatal("GC reservation must fail while a task is active")+ }+ d.unmarkActiveEnvRoot(root)++ release, ok := d.reserveEnvRootForGC(root)+ if !ok {+ t.Fatal("expected GC reservation for inactive env root")+ }+ if _, ok := d.reserveEnvRootForGC(root); ok {+ t.Fatal("second GC reservation must fail while the first is held")+ }+ release()++ release, ok = d.reserveEnvRootForGC(root)+ if !ok {+ t.Fatal("expected GC reservation after release")+ }+ release()+}+func TestIsBareRepo(t *testing.T) {t.Parallel()diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f3996499fb..15a2628452 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -3763,7 +3763,91 @@ func (h *Handler) GetIssueUsage(w http.ResponseWriter, r *http.Request) {})}-// GetIssueGCCheck returns minimal issue info needed by the daemon GC loop.+const (+ maxIssueGCBatchSize = 500+ maxIssueGCBatchBodyBytes = 64 << 10+)++type batchIssueGCCheckRequest struct {+ IssueIDs []string `json:"issue_ids"`+}++type batchIssueGCCheckItem struct {+ ID string `json:"id"`+ Found bool `json:"found"`+ Status string `json:"status,omitempty"`+ UpdatedAt *time.Time `json:"updated_at,omitempty"`+}++// BatchIssueGCCheck returns one explicit result for every requested issue ID.+// The query is workspace-scoped at the SQL layer; missing rows and IDs owned by+// another workspace both become found=false so the endpoint is not an+// enumeration oracle. Requests are capped because installed daemons run this+// endpoint periodically and must not be able to produce unbounded DB work.+func (h *Handler) BatchIssueGCCheck(w http.ResponseWriter, r *http.Request) {+ workspaceID := chi.URLParam(r, "workspaceId")+ workspaceUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace_id")+ if !ok {+ return+ }+ if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, maxIssueGCBatchBodyBytes)+ var req batchIssueGCCheckRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if len(req.IssueIDs) > maxIssueGCBatchSize {+ writeError(w, http.StatusBadRequest, "too many issue_ids")+ return+ }++ parsedIDs := make([]pgtype.UUID, 0, len(req.IssueIDs))+ canonicalIDs := make([]string, 0, len(req.IssueIDs))+ for _, issueID := range req.IssueIDs {+ parsedID, err := util.ParseUUID(issueID)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid issue_id")+ return+ }+ parsedIDs = append(parsedIDs, parsedID)+ canonicalIDs = append(canonicalIDs, uuidToString(parsedID))+ }++ rows := make(map[string]db.ListIssueGCStatusesRow, len(parsedIDs))+ if len(parsedIDs) > 0 {+ result, err := h.Queries.ListIssueGCStatuses(r.Context(), db.ListIssueGCStatusesParams{+ WorkspaceID: workspaceUUID,+ IssueIds: parsedIDs,+ })+ if err != nil {+ slog.Warn("list issue GC statuses failed", "workspace_id", workspaceID, "count", len(parsedIDs), "error", err)+ writeError(w, http.StatusInternalServerError, "failed to check issues")+ return+ }+ for _, row := range result {+ rows[uuidToString(row.ID)] = row+ }+ }++ items := make([]batchIssueGCCheckItem, 0, len(req.IssueIDs))+ for i, issueID := range req.IssueIDs {+ row, found := rows[canonicalIDs[i]]+ item := batchIssueGCCheckItem{ID: issueID, Found: found}+ if found {+ item.Status = row.Status+ updatedAt := row.UpdatedAt.Time+ item.UpdatedAt = &updatedAt+ }+ items = append(items, item)+ }+ writeJSON(w, http.StatusOK, map[string]any{"issues": items})+}++// GetIssueGCCheck returns minimal issue info needed by older daemon GC loops.// Gated on workspace access so a daemon token scoped to workspace A cannot// read issue metadata from workspace B via UUID enumeration.func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {@@ -3772,7 +3856,7 @@ func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {if !ok {return}- issue, err := h.Queries.GetIssue(r.Context(), issueUUID)+ issue, err := h.Queries.GetIssueGCStatus(r.Context(), issueUUID)if err != nil {writeError(w, http.StatusNotFound, "issue not found")returndiff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 8842ce23c0..4b26ff2d25 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -1383,6 +1383,66 @@ func TestGetIssueGCCheck_WithDaemonToken_CrossWorkspace(t *testing.T) {}}+func TestBatchIssueGCCheck_WithDaemonToken(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ var issueID string+ err := testPool.QueryRow(context.Background(), `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type)+ VALUES ($1, 'batch-gc-check-auth-test-issue', 'done', 'medium', $2, 'member')+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID)+ if err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ defer testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)++ missingID := "00000000-0000-0000-0000-000000000099"+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{+ "issue_ids": []string{issueID, missingID},+ }, testWorkspaceID, "legit-daemon")+ req = withURLParam(req, "workspaceId", testWorkspaceID)++ testHandler.BatchIssueGCCheck(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("BatchIssueGCCheck: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Issues []struct {+ ID string `json:"id"`+ Found bool `json:"found"`+ Status string `json:"status"`+ UpdatedAt string `json:"updated_at"`+ } `json:"issues"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(resp.Issues) != 2 {+ t.Fatalf("issues length = %d, want 2", len(resp.Issues))+ }+ if got := resp.Issues[0]; got.ID != issueID || !got.Found || got.Status != "done" || got.UpdatedAt == "" {+ t.Fatalf("found issue result = %+v", got)+ }+ if got := resp.Issues[1]; got.ID != missingID || got.Found || got.Status != "" || got.UpdatedAt != "" {+ t.Fatalf("missing issue result = %+v", got)+ }++ // A token for another workspace is rejected before any issue lookup.+ w = httptest.NewRecorder()+ req = newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{+ "issue_ids": []string{issueID},+ }, "00000000-0000-0000-0000-000000000000", "attacker-daemon")+ req = withURLParam(req, "workspaceId", testWorkspaceID)+ testHandler.BatchIssueGCCheck(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("cross-workspace batch: expected 404, got %d: %s", w.Code, w.Body.String())+ }+}+// withURLParams merges the given chi URL parameters into the request context.// Unlike calling withURLParam twice (which replaces the whole chi.RouteContext// and loses earlier params), this preserves previously-added params.diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.goindex aea8919f87..6c5784df09 100644--- a/server/internal/handler/handler_test.go+++ b/server/internal/handler/handler_test.go@@ -2146,6 +2146,38 @@ func TestGetIssueGCCheckRejectsMalformedIssueID(t *testing.T) {}}+func TestBatchIssueGCCheckRejectsInvalidRequests(t *testing.T) {+ h := &Handler{}+ workspaceID := "00000000-0000-0000-0000-000000000001"+ tooMany := make([]string, maxIssueGCBatchSize+1)+ for i := range tooMany {+ tooMany[i] = "00000000-0000-0000-0000-000000000002"+ }++ tests := []struct {+ name string+ workspaceID string+ body any+ }{+ {name: "malformed workspace", workspaceID: "not-a-uuid", body: map[string]any{"issue_ids": []string{}}},+ {name: "malformed issue", workspaceID: workspaceID, body: map[string]any{"issue_ids": []string{"not-a-uuid"}}},+ {name: "too many issues", workspaceID: workspaceID, body: map[string]any{"issue_ids": tooMany}},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+tt.workspaceID+"/issues/gc-check", tt.body,+ tt.workspaceID, "test-daemon")+ req = withURLParam(req, "workspaceId", tt.workspaceID)+ h.BatchIssueGCCheck(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}+func TestSetAgentSkillsRejectsMalformedSkillID(t *testing.T) {agentID := createHandlerTestAgent(t, "Handler Malformed Skill Assignment", nil)diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 2c94c82b14..64c626c60a 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -668,6 +668,25 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginParareturn i, err}+const getIssueGCStatus = `-- name: GetIssueGCStatus :one+SELECT workspace_id, status, updated_at+FROM issue+WHERE id = $1+`++type GetIssueGCStatusRow struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Status string `json:"status"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++func (q *Queries) GetIssueGCStatus(ctx context.Context, id pgtype.UUID) (GetIssueGCStatusRow, error) {+ row := q.db.QueryRow(ctx, getIssueGCStatus, id)+ var i GetIssueGCStatusRow+ err := row.Scan(&i.WorkspaceID, &i.Status, &i.UpdatedAt)+ return i, err+}+const getIssueInWorkspace = `-- name: GetIssueInWorkspace :oneSELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issueWHERE id = $1 AND workspace_id = $2@@ -837,6 +856,44 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByPreturn items, nil}+const listIssueGCStatuses = `-- name: ListIssueGCStatuses :many+SELECT id, status, updated_at+FROM issue+WHERE workspace_id = $1+ AND id = ANY($2::uuid[])+`++type ListIssueGCStatusesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ IssueIds []pgtype.UUID `json:"issue_ids"`+}++type ListIssueGCStatusesRow struct {+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++func (q *Queries) ListIssueGCStatuses(ctx context.Context, arg ListIssueGCStatusesParams) ([]ListIssueGCStatusesRow, error) {+ rows, err := q.db.Query(ctx, listIssueGCStatuses, arg.WorkspaceID, arg.IssueIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListIssueGCStatusesRow{}+ for rows.Next() {+ var i ListIssueGCStatusesRow+ if err := rows.Scan(&i.ID, &i.Status, &i.UpdatedAt); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listIssues = `-- name: ListIssues :manySELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 0d60346320..1e977ac3ae 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -65,6 +65,17 @@ LIMIT $2 OFFSET $3;SELECT * FROM issueWHERE id = $1;+-- name: GetIssueGCStatus :one+SELECT workspace_id, status, updated_at+FROM issue+WHERE id = $1;++-- name: ListIssueGCStatuses :many+SELECT id, status, updated_at+FROM issue+WHERE workspace_id = sqlc.arg('workspace_id')+ AND id = ANY(sqlc.arg('issue_ids')::uuid[]);+-- name: GetIssueInWorkspace :oneSELECT * FROM issueWHERE id = $1 AND workspace_id = $2;