Skip to content

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

Go

MUL-5620: fix(daemon): make disk-usage report what is actually on disk (#6270)

Bohan Jiangc037c134ad3e
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 724b033f4a..b0d4187cb3 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -81,7 +81,12 @@ var daemonDiskUsageCmd = &cobra.Command{
"applies within each root and --workspaces-root is not allowed.\n\n" +
"Bytes are split into total and the artifact-cleanable subset (node_modules, .next, .turbo by default,\n" +
"overridable via MULTICA_GC_ARTIFACT_PATTERNS) so the report stays in sync with what the GC reclaims.\n" +
- "The walk skips .git and never follows symlinks. The daemon does not need to be running.",
+ "A .git directory counts toward the total but never toward the artifact subset — the GC frees it only\n" +
+ "when it removes the whole task directory. Symlinks are never followed.\n\n" +
+ "The STATUS column shows the current status of the issue each directory belongs to, which requires\n" +
+ "contacting the server. When the machine is offline, logged out, or the request fails, the column is\n" +
+ "left blank and the rest of the report still prints. --by-workspace has no STATUS column and therefore\n" +
+ "makes no network request unless --output json is also set. The daemon does not need to be running.",
RunE: runDaemonDiskUsage,
}
@@ -1334,7 +1339,7 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
}
if allProfiles {
- return runDaemonDiskUsageAggregate(byWorkspace, top, output)
+ return runDaemonDiskUsageAggregate(cmd, byWorkspace, top, output)
}
workspacesRoot, err := daemon.ResolveWorkspacesRoot(profile, rootOverride)
@@ -1346,6 +1351,11 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
if err != nil {
return err
}
+ // Resolve before --top trims the slice: the batch endpoint costs the same
+ // either way, and the JSON consumer sees statuses for everything it gets.
+ if diskUsageNeedsParentStatus(byWorkspace, output) {
+ fillDiskUsageParentStatuses(cmd, profile, &report)
+ }
if top > 0 {
if byWorkspace {
@@ -1371,11 +1381,79 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
return nil
}
+// diskUsageNeedsParentStatus reports whether this invocation renders per-task
+// rows at all. The --by-workspace table has no STATUS column, so resolving
+// statuses for it would spend a network round trip — and, against an
+// unreachable server, a full timeout — on data nothing displays, turning a
+// local diagnostic into a command that hangs offline. JSON output always
+// carries the task array, so it still needs them even with --by-workspace.
+func diskUsageNeedsParentStatus(byWorkspace bool, output string) bool {
+ return !byWorkspace || output == "json"
+}
+
+// fillDiskUsageParentStatuses populates the report's STATUS column in place.
+//
+// This is best-effort and never fails the command: `disk-usage` is a local
+// diagnostic that has to keep working when the machine is offline or logged
+// out. When statuses can't be resolved the column simply stays blank, and the
+// reason goes to stderr so `--output json` stdout stays machine-readable.
+func fillDiskUsageParentStatuses(cmd *cobra.Command, profile string, report *daemon.DiskUsageReport) {
+ fetch := newParentStatusFetcher(cmd, profile)
+ if fetch == nil {
+ return
+ }
+ ctx, cancel := cli.APIContext(cmd.Context())
+ defer cancel()
+ if err := daemon.ResolveParentStatuses(ctx, report, fetch); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: could not resolve issue statuses, STATUS column may be blank: %v\n", err)
+ }
+}
+
+// newParentStatusFetcher builds a fetcher backed by the same batch gc-check
+// endpoint the daemon's GC loop uses, so the STATUS column reports exactly the
+// status the GC would act on. The daemon authenticates with the profile's CLI
+// token (see Daemon.resolveAuth), so reusing it here needs no extra API
+// surface. Returns nil when this profile has no usable credentials — the
+// caller then leaves the column blank rather than erroring.
+func newParentStatusFetcher(cmd *cobra.Command, profile string) daemon.ParentStatusFetcher {
+ cfg, err := cli.LoadCLIConfigForProfile(profile)
+ if err != nil || strings.TrimSpace(cfg.Token) == "" {
+ return nil
+ }
+ rawURL := resolveDaemonServerURL(cmd, profile)
+ if rawURL == "" {
+ rawURL = daemon.DefaultServerURL
+ }
+ baseURL, err := daemon.NormalizeServerBaseURL(rawURL)
+ if err != nil {
+ return nil
+ }
+
+ client := daemon.NewClient(baseURL)
+ client.SetToken(cfg.Token)
+ return func(ctx context.Context, workspaceID string, issueIDs []string) (map[string]string, error) {
+ results, err := client.GetIssueGCChecks(ctx, workspaceID, issueIDs)
+ if err != nil {
+ return nil, err
+ }
+ statuses := make(map[string]string, len(results))
+ for id, result := range results {
+ // Skip per-issue failures and 404s: an unresolved id must stay
+ // blank so it reads as "unknown", not as a status.
+ if result.Err != nil || !result.Found {
+ continue
+ }
+ statuses[id] = result.Status
+ }
+ return statuses, nil
+ }
+}
+
// runDaemonDiskUsageAggregate scans every workspace root (the default root plus
// each ~/.multica/profiles/* root) and renders a per-root breakdown with a
// combined grand total. This is the path that surfaces the Desktop app's
// `desktop-<host>` root, which the default single-root scan never sees.
-func runDaemonDiskUsageAggregate(byWorkspace bool, top int, output string) error {
+func runDaemonDiskUsageAggregate(cmd *cobra.Command, byWorkspace bool, top int, output string) error {
roots, err := enumerateDiskUsageRoots()
if err != nil {
return err
@@ -1384,6 +1462,15 @@ func runDaemonDiskUsageAggregate(byWorkspace bool, top int, output string) error
if err != nil {
return err
}
+ // Each root belongs to its own profile, so it needs that profile's token.
+ // Skipping the whole loop when nothing renders task rows matters most
+ // here: an unreachable server would otherwise burn one full timeout per
+ // root, serially.
+ if diskUsageNeedsParentStatus(byWorkspace, output) {
+ for i := range agg.Roots {
+ fillDiskUsageParentStatuses(cmd, agg.Roots[i].Profile, &agg.Roots[i].Report)
+ }
+ }
// --top trims each root's table independently — the grand total in the
// report stays anchored to the full scan, mirroring single-root --top.
diff --git a/server/cmd/multica/cmd_daemon_diskusage_status_test.go b/server/cmd/multica/cmd_daemon_diskusage_status_test.go
new file mode 100644
index 0000000000..b1f6cfbce3
--- /dev/null
+++ b/server/cmd/multica/cmd_daemon_diskusage_status_test.go
@@ -0,0 +1,292 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+ "github.com/spf13/cobra"
+)
+
+// newDiskUsageTestCmd mirrors the flag set registered on daemonDiskUsageCmd so
+// runDaemonDiskUsage can be driven directly without touching the global command.
+func newDiskUsageTestCmd(t *testing.T) *cobra.Command {
+ t.Helper()
+ cmd := &cobra.Command{}
+ f := cmd.Flags()
+ f.Bool("by-workspace", false, "")
+ f.Bool("by-task", false, "")
+ f.Int("top", 0, "")
+ f.String("output", "table", "")
+ f.String("workspaces-root", "", "")
+ f.Bool("all-profiles", false, "")
+ f.String("profile", "", "")
+ f.String("server-url", "", "")
+ return cmd
+}
+
+// gcCheckRecorder is a stand-in for the server's batch gc-check endpoint. It
+// records every request so tests can assert on both call count and the
+// credentials each call carried.
+type gcCheckRecorder struct {
+ mu sync.Mutex
+ // tokenByIssue maps a requested issue id to the bearer token it was
+ // requested with, so --all-profiles can be checked per profile.
+ tokenByIssue map[string]string
+ calls int
+ statusCode int
+}
+
+func newGCCheckServer(t *testing.T, rec *gcCheckRecorder) *httptest.Server {
+ t.Helper()
+ rec.tokenByIssue = map[string]string{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !strings.HasSuffix(r.URL.Path, "/issues/gc-check") {
+ http.NotFound(w, r)
+ return
+ }
+ var body struct {
+ IssueIDs []string `json:"issue_ids"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&body)
+
+ rec.mu.Lock()
+ rec.calls++
+ token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ for _, id := range body.IssueIDs {
+ rec.tokenByIssue[id] = token
+ }
+ code := rec.statusCode
+ rec.mu.Unlock()
+
+ if code != 0 && code != http.StatusOK {
+ w.WriteHeader(code)
+ return
+ }
+ issues := make([]map[string]any, 0, len(body.IssueIDs))
+ for _, id := range body.IssueIDs {
+ issues = append(issues, map[string]any{
+ "id": id, "found": true, "status": "in_review",
+ "updated_at": time.Now().UTC().Format(time.RFC3339Nano),
+ })
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"issues": issues})
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func (r *gcCheckRecorder) callCount() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.calls
+}
+
+// writeDiskUsageIssueTask creates a task dir carrying issue-kind GC metadata,
+// which is what makes it eligible for status resolution.
+func writeDiskUsageIssueTask(t *testing.T, root, wsID, taskShort, issueID string) {
+ t.Helper()
+ taskDir := filepath.Join(root, wsID, taskShort)
+ if err := os.MkdirAll(filepath.Join(taskDir, "workdir"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(taskDir, "workdir", "main.go"), []byte("package main"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ meta, err := json.Marshal(map[string]any{
+ "kind": "issue",
+ "issue_id": issueID,
+ "workspace_id": wsID,
+ "completed_at": time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339Nano),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(taskDir, ".gc_meta.json"), meta, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// setupDiskUsageProfile points a profile's CLI config at srv and seeds one
+// issue-kind task dir under that profile's workspaces root.
+func setupDiskUsageProfile(t *testing.T, home, profile, token, serverURL, wsID, taskShort, issueID string) {
+ t.Helper()
+ root := filepath.Join(home, "multica_workspaces")
+ if profile != "" {
+ root += "_" + profile
+ mkdirProfile(t, home, profile)
+ }
+ writeDiskUsageIssueTask(t, root, wsID, taskShort, issueID)
+ if err := cli.SaveCLIConfigForProfile(cli.CLIConfig{
+ ServerURL: serverURL,
+ Token: token,
+ }, profile); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestDiskUsageNeedsParentStatus pins the gate itself: the per-task table and
+// any JSON output need statuses; the --by-workspace table has no STATUS column
+// and must not trigger a request.
+func TestDiskUsageNeedsParentStatus(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ byWorkspace bool
+ output string
+ want bool
+ }{
+ {false, "table", true}, // per-task table renders STATUS
+ {false, "json", true},
+ {true, "json", true}, // JSON always carries the task array
+ {true, "table", false}, // per-workspace table has no STATUS column
+ }
+ for _, tc := range cases {
+ if got := diskUsageNeedsParentStatus(tc.byWorkspace, tc.output); got != tc.want {
+ t.Errorf("diskUsageNeedsParentStatus(byWorkspace=%v, output=%q) = %v, want %v",
+ tc.byWorkspace, tc.output, got, tc.want)
+ }
+ }
+}
+
+// TestRunDaemonDiskUsageByWorkspaceTableMakesNoRequest is the offline-regression
+// guard: with valid credentials on disk, the --by-workspace table must still
+// resolve nothing, so an unreachable server cannot make a local diagnostic hang.
+func TestRunDaemonDiskUsageByWorkspaceTableMakesNoRequest(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ rec := &gcCheckRecorder{}
+ srv := newGCCheckServer(t, rec)
+ setupDiskUsageProfile(t, home, "", "token-default", srv.URL,
+ "11111111-1111-1111-1111-111111111111", "aaaaaaaa", "issue-1")
+
+ cmd := newDiskUsageTestCmd(t)
+ if err := cmd.Flags().Set("by-workspace", "true"); err != nil {
+ t.Fatal(err)
+ }
+
+ out, err := captureStdout(t, func() error { return runDaemonDiskUsage(cmd, nil) })
+ if err != nil {
+ t.Fatalf("runDaemonDiskUsage: %v", err)
+ }
+ if rec.callCount() != 0 {
+ t.Errorf("made %d gc-check request(s); --by-workspace table must not go to the network", rec.callCount())
+ }
+ if !strings.Contains(out, "Workspaces root:") {
+ t.Errorf("expected a per-workspace table, got:\n%s", out)
+ }
+}
+
+// TestRunDaemonDiskUsageTaskTableResolvesStatus is the positive half: the
+// default per-task view does resolve, and the status reaches the rendered table.
+func TestRunDaemonDiskUsageTaskTableResolvesStatus(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ rec := &gcCheckRecorder{}
+ srv := newGCCheckServer(t, rec)
+ setupDiskUsageProfile(t, home, "", "token-default", srv.URL,
+ "11111111-1111-1111-1111-111111111111", "aaaaaaaa", "issue-1")
+
+ out, err := captureStdout(t, func() error { return runDaemonDiskUsage(newDiskUsageTestCmd(t), nil) })
+ if err != nil {
+ t.Fatalf("runDaemonDiskUsage: %v", err)
+ }
+ if rec.callCount() != 1 {
+ t.Errorf("gc-check calls = %d, want 1", rec.callCount())
+ }
+ if !strings.Contains(out, "in_review") {
+ t.Errorf("STATUS column missing the resolved status, got:\n%s", out)
+ }
+}
+
+// TestRunDaemonDiskUsageJSONSurvivesServerFailure pins the best-effort
+// contract: a failing server must not fail the command or corrupt stdout, so
+// scripts consuming --output json keep working when the API is down.
+func TestRunDaemonDiskUsageJSONSurvivesServerFailure(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ rec := &gcCheckRecorder{statusCode: http.StatusInternalServerError}
+ srv := newGCCheckServer(t, rec)
+ setupDiskUsageProfile(t, home, "", "token-default", srv.URL,
+ "11111111-1111-1111-1111-111111111111", "aaaaaaaa", "issue-1")
+
+ cmd := newDiskUsageTestCmd(t)
+ if err := cmd.Flags().Set("output", "json"); err != nil {
+ t.Fatal(err)
+ }
+
+ out, err := captureStdout(t, func() error { return runDaemonDiskUsage(cmd, nil) })
+ if err != nil {
+ t.Fatalf("a failing gc-check must not fail the command, got: %v", err)
+ }
+
+ var report struct {
+ Tasks []struct {
+ ParentID string `json:"parent_id"`
+ ParentStatus string `json:"parent_status"`
+ } `json:"tasks"`
+ }
+ if err := json.Unmarshal([]byte(out), &report); err != nil {
+ t.Fatalf("stdout must stay valid JSON when resolution fails: %v\n%s", err, out)
+ }
+ if len(report.Tasks) != 1 {
+ t.Fatalf("tasks = %d, want 1", len(report.Tasks))
+ }
+ if report.Tasks[0].ParentStatus != "" {
+ t.Errorf("parent_status = %q, want empty after a failed resolve", report.Tasks[0].ParentStatus)
+ }
+ if report.Tasks[0].ParentID != "issue-1" {
+ t.Errorf("parent_id = %q, want issue-1 (local scan data survives)", report.Tasks[0].ParentID)
+ }
+}
+
+// TestRunDaemonDiskUsageAllProfilesUsesPerProfileToken guards the credential
+// wiring in aggregate mode: each root must be resolved with its own profile's
+// token, not whichever one happened to be loaded first.
+func TestRunDaemonDiskUsageAllProfilesUsesPerProfileToken(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+ t.Setenv("MULTICA_SERVER_URL", "")
+
+ rec := &gcCheckRecorder{}
+ srv := newGCCheckServer(t, rec)
+ setupDiskUsageProfile(t, home, "", "token-default", srv.URL,
+ "11111111-1111-1111-1111-111111111111", "aaaaaaaa", "issue-default")
+ setupDiskUsageProfile(t, home, "second", "token-second", srv.URL,
+ "22222222-2222-2222-2222-222222222222", "bbbbbbbb", "issue-second")
+
+ cmd := newDiskUsageTestCmd(t)
+ if err := cmd.Flags().Set("all-profiles", "true"); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := captureStdout(t, func() error { return runDaemonDiskUsage(cmd, nil) }); err != nil {
+ t.Fatalf("runDaemonDiskUsage --all-profiles: %v", err)
+ }
+
+ rec.mu.Lock()
+ defer rec.mu.Unlock()
+ if got := rec.tokenByIssue["issue-default"]; got != "token-default" {
+ t.Errorf("default root resolved with token %q, want token-default", got)
+ }
+ if got := rec.tokenByIssue["issue-second"]; got != "token-second" {
+ t.Errorf("second profile root resolved with token %q, want token-second", got)
+ }
+}
diff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.go
index 2c83ca889d..9f15f2c26e 100644
--- a/server/internal/daemon/diskusage.go
+++ b/server/internal/daemon/diskusage.go
@@ -1,6 +1,7 @@
package daemon
import (
+ "context"
"fmt"
"os"
"path/filepath"
@@ -12,12 +13,19 @@ import (
)
// TaskDiskUsage describes one task workdir's footprint on disk.
+//
+// ParentID is the id of the record that governs this directory's lifecycle,
+// discriminated by Kind (issue id, chat session id, autopilot run id, or task
+// id). ParentStatus is that record's current status; it stays empty until
+// ResolveParentStatuses fills it in, because ScanDiskUsage itself is purely
+// local and .gc_meta.json does not persist a status.
type TaskDiskUsage struct {
WorkspaceID string `json:"workspace_id"`
WorkspaceShort string `json:"workspace_short"`
TaskShort string `json:"task_short"`
Path string `json:"path"`
Kind string `json:"kind"`
+ ParentID string `json:"parent_id,omitempty"`
ParentStatus string `json:"parent_status"`
AgeSeconds int64 `json:"age_seconds"`
SizeBytes int64 `json:"size_bytes"`
@@ -119,13 +127,16 @@ func ScanDiskUsageRoots(roots []DiskUsageRoot, artifactPatterns []string) (Aggre
const DiskUsageKindUnknown = "unknown"
// ScanDiskUsage walks workspacesRoot and returns the disk-usage report. The
-// walk is read-only and follows the same safety contract as the GC artifact
-// cleaner: it never enters .git, never follows symlinks, and counts only
-// regular files. artifactPatterns is filtered through the basename-only check
-// used by cleanTaskArtifacts, and exact daemon-managed artifact paths are
-// included, so the reported "artifact" footprint matches the bytes the GC
-// would actually reclaim. Missing roots return an empty report
+// walk is read-only, never follows symlinks, and counts only regular files.
+// artifactPatterns is filtered through the basename-only check used by
+// cleanTaskArtifacts, and exact daemon-managed artifact paths are included, so
+// the reported "artifact" footprint matches the bytes the GC would actually
+// reclaim. A .git subtree counts toward the total but never toward that
+// artifact footprint — see taskSize. Missing roots return an empty report
// (not an error) — a daemon that's never run yet has no directory to walk.
+//
+// The scan is purely local. ParentStatus is left empty; callers that want the
+// STATUS column populated run ResolveParentStatuses afterwards.
func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageReport, error) {
report := DiskUsageReport{
WorkspacesRoot: workspacesRoot,
@@ -255,6 +266,7 @@ func buildTaskUsage(taskDir, wsID, taskShort string, matcher artifactMatcher) Ta
if meta, err := execenv.ReadGCMeta(taskDir); err == nil && meta != nil {
metaPresent = true
usage.Kind = string(meta.Kind)
+ usage.ParentID = parentIDForMeta(meta)
if !meta.CompletedAt.IsZero() {
usage.AgeSeconds = int64(time.Since(meta.CompletedAt).Seconds())
} else if age, ok := gcMetaFileAge(taskDir); ok {
@@ -274,12 +286,116 @@ func buildTaskUsage(taskDir, wsID, taskShort string, matcher artifactMatcher) Ta
return usage
}
-// taskSize walks taskDir and returns (totalBytes, artifactBytes). Both honor
-// the GC safety contract: never descends into .git, never follows symlinks,
-// counts only regular files. A directory matched by matcher is treated as an
-// artifact subtree — its size is added to both totals and the walk does not
-// descend further so the size matches what os.RemoveAll would reclaim if the
-// GC ran cleanTaskArtifacts on it.
+// parentIDForMeta returns the id of the record that governs this task dir's
+// lifecycle. GCMeta is a discriminated union keyed on Kind, so only the field
+// matching Kind is meaningful.
+func parentIDForMeta(meta *execenv.GCMeta) string {
+ switch meta.Kind {
+ case execenv.GCKindIssue:
+ return strings.TrimSpace(meta.IssueID)
+ case execenv.GCKindChat:
+ return strings.TrimSpace(meta.ChatSessionID)
+ case execenv.GCKindAutopilotRun:
+ return strings.TrimSpace(meta.AutopilotRunID)
+ case execenv.GCKindQuickCreate:
+ return strings.TrimSpace(meta.TaskID)
+ default:
+ return ""
+ }
+}
+
+// ParentStatusFetcher resolves a batch of issue ids in one workspace to their
+// current status. Ids the server does not return (deleted, or invisible to
+// this token) must be omitted from the result rather than mapped to a
+// placeholder, so callers can tell "unresolved" from a real status.
+type ParentStatusFetcher func(ctx context.Context, workspaceID string, issueIDs []string) (map[string]string, error)
+
+// ResolveParentStatuses fills in ParentStatus on every issue-kind task in the
+// report. ScanDiskUsage is deliberately network-free — this is the opt-in
+// second pass that turns the STATUS column into real data.
+//
+// Only issue-kind tasks are resolved: they are the overwhelming majority of
+// task dirs and the only kind with a batch reconciliation endpoint. Chat,
+// autopilot-run, and quick-create dirs keep an empty ParentStatus rather than
+// costing one request each.
+//
+// Best-effort by design: a workspace whose fetch fails leaves its tasks
+// unresolved and the error is returned for the caller to surface, but every
+// other workspace is still filled in. Callers must not treat a non-nil error
+// as "the report is unusable".
+func ResolveParentStatuses(ctx context.Context, report *DiskUsageReport, fetch ParentStatusFetcher) error {
+ if report == nil || fetch == nil {
+ return nil
+ }
+
+ idsByWorkspace := map[string][]string{}
+ seen := map[string]map[string]bool{}
+ for _, task := range report.Tasks {
+ if task.Kind != string(execenv.GCKindIssue) || task.ParentID == "" {
+ continue
+ }
+ if seen[task.WorkspaceID] == nil {
+ seen[task.WorkspaceID] = map[string]bool{}
+ }
+ // Several task dirs can share one issue (a re-dispatched task reuses
+ // the prior workdir), so de-duplicate before asking the server.
+ if seen[task.WorkspaceID][task.ParentID] {
+ continue
+ }
+ seen[task.WorkspaceID][task.ParentID] = true
+ idsByWorkspace[task.WorkspaceID] = append(idsByWorkspace[task.WorkspaceID], task.ParentID)
+ }
+ if len(idsByWorkspace) == 0 {
+ return nil
+ }
+
+ var firstErr error
+ statuses := make(map[string]map[string]string, len(idsByWorkspace))
+ for workspaceID, ids := range idsByWorkspace {
+ resolved := make(map[string]string, len(ids))
+ // Same chunk size the GC loop uses, so one oversized root cannot trip
+ // the server's batch cap.
+ for start := 0; start < len(ids); start += issueGCBatchSize {
+ end := min(start+issueGCBatchSize, len(ids))
+ chunk, err := fetch(ctx, workspaceID, ids[start:end])
+ if err != nil {
+ if firstErr == nil {
+ firstErr = err
+ }
+ continue
+ }
+ for id, status := range chunk {
+ resolved[id] = status
+ }
+ }
+ statuses[workspaceID] = resolved
+ }
+
+ for i := range report.Tasks {
+ task := &report.Tasks[i]
+ if task.Kind != string(execenv.GCKindIssue) || task.ParentID == "" {
+ continue
+ }
+ if status, ok := statuses[task.WorkspaceID][task.ParentID]; ok {
+ task.ParentStatus = status
+ }
+ }
+ return firstErr
+}
+
+// taskSize walks taskDir and returns (totalBytes, artifactBytes). It never
+// follows symlinks and counts only regular files. A directory matched by
+// matcher is treated as an artifact subtree — its size is added to both totals
+// and the walk does not descend further so the size matches what os.RemoveAll
+// would reclaim if the GC ran cleanTaskArtifacts on it.
+//
+// A .git subtree is counted whole into totalBytes but never into artifactBytes.
+// It is real footprint the user sees in their file manager, and a full
+// gcActionClean removes it along with the rest of the task dir (dirSize, which
+// reports bytes_reclaimed there, counts it too) — so excluding it made SizeBytes
+// disagree with what the GC would actually free. The walk still refuses to
+// descend into it, which keeps the artifact accounting aligned with
+// cleanTaskArtifacts' refusal to reclaim anything inside .git.
func taskSize(taskDir string, matcher artifactMatcher) (totalBytes int64, artifactBytes int64) {
if taskDir == "" {
return
@@ -305,6 +421,7 @@ func taskSize(taskDir string, matcher artifactMatcher) (totalBytes int64, artifa
}
if entry.IsDir() {
if entry.Name() == ".git" {
+ totalBytes += dirSize(path)
return filepath.SkipDir
}
if _, ok := matcher.matchDirectory(absRoot, path, entry); ok {
diff --git a/server/internal/daemon/diskusage_test.go b/server/internal/daemon/diskusage_test.go
index 749b2defd0..6d6c35d41a 100644
--- a/server/internal/daemon/diskusage_test.go
+++ b/server/internal/daemon/diskusage_test.go
@@ -1,7 +1,10 @@
package daemon
import (
+ "context"
"encoding/json"
+ "errors"
+ "fmt"
"os"
"path/filepath"
"runtime"
@@ -293,11 +296,12 @@ func TestScanDiskUsage_EmptyWorkspaceArtifactRatio(t *testing.T) {
}
}
-// TestScanDiskUsage_DoesNotEnterGit guards the GC safety contract: anything
-// inside a .git directory must not be counted, even if it would otherwise
-// match an artifact basename. Reflects the same constraint cleanTaskArtifacts
-// enforces so the disk-usage report stays in sync with what GC reclaims.
-func TestScanDiskUsage_DoesNotEnterGit(t *testing.T) {
+// TestScanDiskUsage_CountsGitButNeverAsArtifact pins the two halves of the
+// .git rule. A .git subtree IS real footprint, so it counts toward size_bytes
+// (a full task-dir reclaim frees it, and dirSize reports it that way). But it
+// must never count as an artifact, even when something inside it matches an
+// artifact basename, because cleanTaskArtifacts refuses to reclaim in there.
+func TestScanDiskUsage_CountsGitButNeverAsArtifact(t *testing.T) {
t.Parallel()
root := t.TempDir()
@@ -317,11 +321,12 @@ func TestScanDiskUsage_DoesNotEnterGit(t *testing.T) {
t.Fatalf("expected 1 task, got %d", len(report.Tasks))
}
got := report.Tasks[0]
- if got.SizeBytes != 100 {
- t.Errorf("size_bytes = %d, want 100 (only main.go; .git tree skipped)", got.SizeBytes)
+ const wantSize = 100 + 9999 + 5555
+ if got.SizeBytes != wantSize {
+ t.Errorf("size_bytes = %d, want %d (main.go plus the whole .git tree)", got.SizeBytes, wantSize)
}
if got.ArtifactSizeBytes != 0 {
- t.Errorf("artifact_size_bytes = %d, want 0 (node_modules under .git is invisible)", got.ArtifactSizeBytes)
+ t.Errorf("artifact_size_bytes = %d, want 0 (node_modules under .git is not reclaimable)", got.ArtifactSizeBytes)
}
}
@@ -465,3 +470,191 @@ func mustWriteMeta(t *testing.T, taskDir string, meta execenv.GCMeta) {
t.Fatal(err)
}
}
+
+// issueTask builds a minimal issue-kind task row for ResolveParentStatuses.
+func issueTask(wsID, taskShort, issueID string) TaskDiskUsage {
+ return TaskDiskUsage{
+ WorkspaceID: wsID,
+ TaskShort: taskShort,
+ Kind: string(execenv.GCKindIssue),
+ ParentID: issueID,
+ }
+}
+
+// TestResolveParentStatuses_FillsIssueTasks covers the main path: statuses land
+// on the right rows, ids shared by several task dirs are asked for once, each
+// workspace is queried separately, and non-issue kinds are left alone.
+func TestResolveParentStatuses_FillsIssueTasks(t *testing.T) {
+ t.Parallel()
+
+ wsA := "11111111-1111-1111-1111-111111111111"
+ wsB := "22222222-2222-2222-2222-222222222222"
+ report := &DiskUsageReport{Tasks: []TaskDiskUsage{
+ issueTask(wsA, "aaaa1111", "issue-1"),
+ // Same issue, second workdir — must resolve without a second ask.
+ issueTask(wsA, "aaaa2222", "issue-1"),
+ issueTask(wsA, "aaaa3333", "issue-2"),
+ issueTask(wsB, "bbbb1111", "issue-3"),
+ {WorkspaceID: wsA, TaskShort: "cccc1111", Kind: string(execenv.GCKindChat), ParentID: "chat-1"},
+ {WorkspaceID: wsA, TaskShort: "dddd1111", Kind: DiskUsageKindUnknown},
+ }}
+
+ asked := map[string][]string{}
+ fetch := func(_ context.Context, workspaceID string, issueIDs []string) (map[string]string, error) {
+ asked[workspaceID] = append(asked[workspaceID], issueIDs...)
+ out := map[string]string{}
+ for _, id := range issueIDs {
+ switch id {
+ case "issue-1":
+ out[id] = "done"
+ case "issue-2":
+ out[id] = "in_progress"
+ case "issue-3":
+ out[id] = "cancelled"
+ }
+ }
+ return out, nil
+ }
+
+ if err := ResolveParentStatuses(context.Background(), report, fetch); err != nil {
+ t.Fatalf("ResolveParentStatuses: %v", err)
+ }
+
+ want := []string{"done", "done", "in_progress", "cancelled", "", ""}
+ for i, wantStatus := range want {
+ if got := report.Tasks[i].ParentStatus; got != wantStatus {
+ t.Errorf("task[%d] (%s) parent_status = %q, want %q",
+ i, report.Tasks[i].TaskShort, got, wantStatus)
+ }
+ }
+
+ if len(asked[wsA]) != 2 {
+ t.Errorf("workspace A asked for %v, want exactly 2 de-duplicated ids", asked[wsA])
+ }
+ if len(asked[wsB]) != 1 {
+ t.Errorf("workspace B asked for %v, want exactly 1 id", asked[wsB])
+ }
+}
+
+// TestResolveParentStatuses_UnresolvedStaysBlank ensures an id the server does
+// not return (deleted issue, or one this token cannot see) reads as unknown
+// rather than being filled with a placeholder that looks like a real status.
+func TestResolveParentStatuses_UnresolvedStaysBlank(t *testing.T) {
+ t.Parallel()
+
+ wsID := "11111111-1111-1111-1111-111111111111"
+ report := &DiskUsageReport{Tasks: []TaskDiskUsage{
+ issueTask(wsID, "aaaa1111", "issue-known"),
+ issueTask(wsID, "aaaa2222", "issue-missing"),
+ }}
+
+ fetch := func(_ context.Context, _ string, _ []string) (map[string]string, error) {
+ return map[string]string{"issue-known": "todo"}, nil
+ }
+
+ if err := ResolveParentStatuses(context.Background(), report, fetch); err != nil {
+ t.Fatalf("ResolveParentStatuses: %v", err)
+ }
+ if report.Tasks[0].ParentStatus != "todo" {
+ t.Errorf("known issue status = %q, want todo", report.Tasks[0].ParentStatus)
+ }
+ if report.Tasks[1].ParentStatus != "" {
+ t.Errorf("missing issue status = %q, want empty", report.Tasks[1].ParentStatus)
+ }
+}
+
+// TestResolveParentStatuses_ChunksLargeWorkspaces verifies a root with more
+// issues than the server's batch cap is split the same way the GC loop splits
+// it, instead of being sent as one oversized request.
+func TestResolveParentStatuses_ChunksLargeWorkspaces(t *testing.T) {
+ t.Parallel()
+
+ wsID := "11111111-1111-1111-1111-111111111111"
+ total := issueGCBatchSize + 1
+ tasks := make([]TaskDiskUsage, 0, total)
+ for i := range total {
+ tasks = append(tasks, issueTask(wsID, fmt.Sprintf("task%04d", i), fmt.Sprintf("issue-%04d", i)))
+ }
+ report := &DiskUsageReport{Tasks: tasks}
+
+ var chunkSizes []int
+ fetch := func(_ context.Context, _ string, issueIDs []string) (map[string]string, error) {
+ chunkSizes = append(chunkSizes, len(issueIDs))
+ out := make(map[string]string, len(issueIDs))
+ for _, id := range issueIDs {
+ out[id] = "done"
+ }
+ return out, nil
+ }
+
+ if err := ResolveParentStatuses(context.Background(), report, fetch); err != nil {
+ t.Fatalf("ResolveParentStatuses: %v", err)
+ }
+
+ if len(chunkSizes) != 2 {
+ t.Fatalf("chunk sizes = %v, want 2 chunks", chunkSizes)
+ }
+ if chunkSizes[0] != issueGCBatchSize || chunkSizes[1] != 1 {
+ t.Errorf("chunk sizes = %v, want [%d 1]", chunkSizes, issueGCBatchSize)
+ }
+ for i := range report.Tasks {
+ if report.Tasks[i].ParentStatus != "done" {
+ t.Fatalf("task[%d] parent_status = %q, want done", i, report.Tasks[i].ParentStatus)
+ }
+ }
+}
+
+// TestResolveParentStatuses_PartialFailureKeepsOtherWorkspaces pins the
+// best-effort contract: one workspace failing must not blank out the rest, and
+// the error still surfaces so the CLI can warn.
+func TestResolveParentStatuses_PartialFailureKeepsOtherWorkspaces(t *testing.T) {
+ t.Parallel()
+
+ wsGood := "11111111-1111-1111-1111-111111111111"
+ wsBad := "22222222-2222-2222-2222-222222222222"
+ report := &DiskUsageReport{Tasks: []TaskDiskUsage{
+ issueTask(wsGood, "aaaa1111", "issue-good"),
+ issueTask(wsBad, "bbbb1111", "issue-bad"),
+ }}
+
+ fetch := func(_ context.Context, workspaceID string, _ []string) (map[string]string, error) {
+ if workspaceID == wsBad {
+ return nil, errors.New("boom")
+ }
+ return map[string]string{"issue-good": "done"}, nil
+ }
+
+ err := ResolveParentStatuses(context.Background(), report, fetch)
+ if err == nil {
+ t.Fatal("expected the failing workspace's error to surface")
+ }
+ if report.Tasks[0].ParentStatus != "done" {
+ t.Errorf("healthy workspace status = %q, want done", report.Tasks[0].ParentStatus)
+ }
+ if report.Tasks[1].ParentStatus != "" {
+ t.Errorf("failed workspace status = %q, want empty", report.Tasks[1].ParentStatus)
+ }
+}
+
+// TestResolveParentStatuses_NoFetcherIsNoOp keeps `disk-usage` usable offline
+// or logged out: with no way to resolve, the scan result passes through
+// untouched instead of erroring.
+func TestResolveParentStatuses_NoFetcherIsNoOp(t *testing.T) {
+ t.Parallel()
+
+ report := &DiskUsageReport{Tasks: []TaskDiskUsage{
+ issueTask("11111111-1111-1111-1111-111111111111", "aaaa1111", "issue-1"),
+ }}
+ if err := ResolveParentStatuses(context.Background(), report, nil); err != nil {
+ t.Fatalf("nil fetcher should be a no-op, got %v", err)
+ }
+ if report.Tasks[0].ParentStatus != "" {
+ t.Errorf("parent_status = %q, want empty", report.Tasks[0].ParentStatus)
+ }
+ if err := ResolveParentStatuses(context.Background(), nil, func(context.Context, string, []string) (map[string]string, error) {
+ t.Fatal("fetcher must not run for a nil report")
+ return nil, nil
+ }); err != nil {
+ t.Fatalf("nil report should be a no-op, got %v", err)
+ }
+}