Skip to content

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

Go

feat(daemon): disk-usage cross-root aggregation + migration FK/readiness fixes (MUL-3404) (#4290)

Bohan Jiange3a829f05e67
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 15498ea4a1..05955fb6a5 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -65,6 +65,10 @@ var daemonDiskUsageCmd = &cobra.Command{
Long: "Walks the daemon's workspaces root and reports per-task or per-workspace disk usage.\n" +
"Default view is per-task, sorted by size descending. --by-workspace switches to a per-workspace summary;\n" +
"--top N keeps only the largest N entries.\n\n" +
+ "By default only the current profile's root is scanned. --all-profiles aggregates across every workspace\n" +
+ "root — the default root plus each ~/.multica/profiles/* root, including the Desktop app's dedicated\n" +
+ "`desktop-<host>` root — and prints a per-root breakdown with a combined grand total. In that mode --top\n" +
+ "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.",
@@ -107,9 +111,10 @@ func init() {
df := daemonDiskUsageCmd.Flags()
df.Bool("by-workspace", false, "Aggregate output by workspace instead of by task")
df.Bool("by-task", false, "Per-task view (default; mutually exclusive with --by-workspace)")
- df.Int("top", 0, "Keep only the largest N entries (across all workspaces)")
+ df.Int("top", 0, "Keep only the largest N entries (per root in --all-profiles mode)")
df.String("output", "table", "Output format: table or json")
df.String("workspaces-root", "", "Override the workspaces root path (default: same as the daemon)")
+ df.Bool("all-profiles", false, "Scan every workspace root (default root + all ~/.multica/profiles/* roots, incl. the Desktop app's) and report a combined total")
daemonCmd.AddCommand(daemonStartCmd)
daemonCmd.AddCommand(daemonStopCmd)
@@ -702,6 +707,7 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
byTask, _ := cmd.Flags().GetBool("by-task")
top, _ := cmd.Flags().GetInt("top")
output, _ := cmd.Flags().GetString("output")
+ allProfiles, _ := cmd.Flags().GetBool("all-profiles")
if byWorkspace && byTask {
return fmt.Errorf("--by-workspace and --by-task are mutually exclusive")
@@ -709,6 +715,13 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
if top < 0 {
return fmt.Errorf("--top must be a non-negative integer")
}
+ if allProfiles && rootOverride != "" {
+ return fmt.Errorf("--all-profiles and --workspaces-root are mutually exclusive")
+ }
+
+ if allProfiles {
+ return runDaemonDiskUsageAggregate(byWorkspace, top, output)
+ }
workspacesRoot, err := daemon.ResolveWorkspacesRoot(profile, rootOverride)
if err != nil {
@@ -736,14 +749,116 @@ func runDaemonDiskUsage(cmd *cobra.Command, _ []string) error {
if byWorkspace {
printDiskUsageWorkspaceTable(os.Stdout, report)
- printDiskUsageEmptyHint(os.Stdout, report, profile, rootOverride)
+ printDiskUsageOtherRootsHint(os.Stdout, report, profile, rootOverride)
return nil
}
printDiskUsageTaskTable(os.Stdout, report)
- printDiskUsageEmptyHint(os.Stdout, report, profile, rootOverride)
+ printDiskUsageOtherRootsHint(os.Stdout, report, profile, rootOverride)
+ return 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 {
+ roots, err := enumerateDiskUsageRoots()
+ if err != nil {
+ return err
+ }
+ agg, err := daemon.ScanDiskUsageRoots(roots, daemon.ArtifactPatternsFromEnv())
+ if err != nil {
+ return err
+ }
+
+ // --top trims each root's table independently — the grand total in the
+ // report stays anchored to the full scan, mirroring single-root --top.
+ if top > 0 {
+ for i := range agg.Roots {
+ r := &agg.Roots[i].Report
+ if byWorkspace {
+ if top < len(r.Workspaces) {
+ r.Workspaces = r.Workspaces[:top]
+ }
+ } else if top < len(r.Tasks) {
+ r.Tasks = r.Tasks[:top]
+ }
+ }
+ }
+
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, agg)
+ }
+ printAggregateDiskUsage(os.Stdout, agg, byWorkspace)
return nil
}
+// enumerateDiskUsageRoots returns the ordered, de-duplicated set of workspace
+// roots to scan in --all-profiles mode: the default root first (always, for
+// orientation even when empty), then each ~/.multica/profiles/* root that
+// exists on disk, sorted by profile name. Roots that resolve to the same path
+// (e.g. when MULTICA_WORKSPACES_ROOT pins every profile to one directory) are
+// collapsed to a single entry.
+func enumerateDiskUsageRoots() ([]daemon.DiskUsageRoot, error) {
+ seen := map[string]bool{}
+ out := make([]daemon.DiskUsageRoot, 0)
+
+ if root, err := daemon.ResolveWorkspacesRoot("", ""); err == nil {
+ out = append(out, daemon.DiskUsageRoot{Profile: "", Root: root})
+ seen[root] = true
+ }
+
+ profilesRoot, err := profilesRootDir()
+ if err != nil {
+ return out, nil
+ }
+ entries, err := os.ReadDir(profilesRoot)
+ if err != nil {
+ return out, nil
+ }
+ names := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ if entry.IsDir() {
+ names = append(names, entry.Name())
+ }
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ root, err := daemon.ResolveWorkspacesRoot(name, "")
+ if err != nil || seen[root] {
+ continue
+ }
+ // Skip profile roots that were never created on disk — a configured
+ // profile whose daemon never ran has nothing to report.
+ if info, statErr := os.Stat(root); statErr != nil || !info.IsDir() {
+ continue
+ }
+ seen[root] = true
+ out = append(out, daemon.DiskUsageRoot{Profile: name, Root: root})
+ }
+ return out, nil
+}
+
+func printAggregateDiskUsage(w io.Writer, agg daemon.AggregateDiskUsageReport, byWorkspace bool) {
+ fmt.Fprintf(w, "Scanned %d workspace root(s).\n", len(agg.Roots))
+ for _, root := range agg.Roots {
+ fmt.Fprintln(w)
+ label := "default"
+ if root.Profile != "" {
+ label = root.Profile
+ }
+ fmt.Fprintf(w, "[%s]\n", label)
+ if byWorkspace {
+ printDiskUsageWorkspaceTable(w, root.Report)
+ } else {
+ printDiskUsageTaskTable(w, root.Report)
+ }
+ }
+ fmt.Fprintf(w, "\nGrand total: %s across %d task(s) in %d root(s); %s reclaimable as artifacts (%.1f%%).\n",
+ formatBytes(agg.TotalSizeBytes), agg.TotalTaskCount, len(agg.Roots),
+ formatBytes(agg.TotalArtifactSizeBytes), agg.TotalArtifactRatio*100)
+}
+
func printDiskUsageTaskTable(w io.Writer, report daemon.DiskUsageReport) {
fmt.Fprintf(w, "Workspaces root: %s\n", report.WorkspacesRoot)
if report.TotalTaskCount == 0 {
@@ -817,8 +932,13 @@ func printDiskUsageWorkspaceTable(w io.Writer, report daemon.DiskUsageReport) {
formatBytes(report.TotalArtifactSizeBytes), report.TotalArtifactRatio*100)
}
-func printDiskUsageEmptyHint(w io.Writer, report daemon.DiskUsageReport, profile, rootOverride string) {
- if report.TotalTaskCount != 0 || rootOverride != "" {
+// printDiskUsageOtherRootsHint warns that workspace roots OTHER than the one
+// just scanned also hold task directories — the case that hides the Desktop
+// app's `desktop-<host>` root behind a non-empty default root. It fires
+// whenever such roots exist (empty current root or not); the only opt-out is an
+// explicit --workspaces-root, where the user already chose exactly what to scan.
+func printDiskUsageOtherRootsHint(w io.Writer, report daemon.DiskUsageReport, profile, rootOverride string) {
+ if rootOverride != "" {
return
}
suggestions := diskUsageProfileSuggestions(profile, report.WorkspacesRoot)
@@ -831,6 +951,7 @@ func printDiskUsageEmptyHint(w io.Writer, report daemon.DiskUsageReport, profile
fmt.Fprintf(w, " %s # %s (%d task%s)\n",
s.Command, s.Root, s.TaskCount, pluralS(s.TaskCount))
}
+ fmt.Fprintln(w, "Run 'multica daemon disk-usage --all-profiles' for a combined total across all roots.")
}
type diskUsageProfileSuggestion struct {
diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.go
index 4e412e3440..d25c450099 100644
--- a/server/cmd/multica/cmd_daemon_test.go
+++ b/server/cmd/multica/cmd_daemon_test.go
@@ -131,7 +131,7 @@ func TestPrintDaemonStatusAlignsValuesWithProfileLabel(t *testing.T) {
}
}
-func TestPrintDiskUsageEmptyHintSuggestsProfilesWithTasks(t *testing.T) {
+func TestPrintDiskUsageOtherRootsHintSuggestsProfilesWithTasks(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
@@ -147,7 +147,7 @@ func TestPrintDiskUsageEmptyHintSuggestsProfilesWithTasks(t *testing.T) {
writeDiskUsageTaskFile(t, home, "two-tasks", "ws2", "task2", "workdir/main.go")
var out bytes.Buffer
- printDiskUsageEmptyHint(&out, daemon.DiskUsageReport{
+ printDiskUsageOtherRootsHint(&out, daemon.DiskUsageReport{
WorkspacesRoot: filepath.Join(home, "multica_workspaces"),
}, "", "")
@@ -164,7 +164,10 @@ func TestPrintDiskUsageEmptyHintSuggestsProfilesWithTasks(t *testing.T) {
if !strings.Contains(got, "multica --profile 'space profile' daemon disk-usage") {
t.Fatalf("hint output = %q, want shell-quoted profile command", got)
}
- if strings.Contains(got, "empty") {
+ if !strings.Contains(got, "multica daemon disk-usage --all-profiles") {
+ t.Fatalf("hint output = %q, want --all-profiles tip", got)
+ }
+ if strings.Contains(got, "(0 task") {
t.Fatalf("hint output = %q, want empty profile omitted", got)
}
if strings.Index(got, "two-tasks") > strings.Index(got, "one-task") {
@@ -172,7 +175,31 @@ func TestPrintDiskUsageEmptyHintSuggestsProfilesWithTasks(t *testing.T) {
}
}
-func TestPrintDiskUsageEmptyHintSuggestsDefaultFromNamedProfile(t *testing.T) {
+// TestPrintDiskUsageOtherRootsHintFiresWhenCurrentRootNonEmpty is the core
+// MUL-3404 behavior: the hint must surface other roots even when the scanned
+// root already has tasks, otherwise the Desktop app's root stays hidden behind
+// a non-empty default root.
+func TestPrintDiskUsageOtherRootsHintFiresWhenCurrentRootNonEmpty(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+
+ mkdirProfile(t, home, "desktop-host")
+ writeDiskUsageTaskFile(t, home, "desktop-host", "ws1", "task1", "workdir/main.go")
+
+ var out bytes.Buffer
+ printDiskUsageOtherRootsHint(&out, daemon.DiskUsageReport{
+ WorkspacesRoot: filepath.Join(home, "multica_workspaces"),
+ TotalTaskCount: 7, // current root is NOT empty
+ }, "", "")
+
+ got := out.String()
+ if !strings.Contains(got, "multica --profile desktop-host daemon disk-usage") {
+ t.Fatalf("hint output = %q, want desktop-host suggestion even with a non-empty current root", got)
+ }
+}
+
+func TestPrintDiskUsageOtherRootsHintSuggestsDefaultFromNamedProfile(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
@@ -180,20 +207,17 @@ func TestPrintDiskUsageEmptyHintSuggestsDefaultFromNamedProfile(t *testing.T) {
writeDefaultDiskUsageTaskFile(t, home, "ws0", "task0", "workdir/main.go")
var out bytes.Buffer
- printDiskUsageEmptyHint(&out, daemon.DiskUsageReport{
+ printDiskUsageOtherRootsHint(&out, daemon.DiskUsageReport{
WorkspacesRoot: filepath.Join(home, "multica_workspaces_named"),
}, "named", "")
got := out.String()
- if !strings.Contains(got, "multica daemon disk-usage") {
+ if !strings.Contains(got, "multica daemon disk-usage #") {
t.Fatalf("hint output = %q, want default profile command", got)
}
- if strings.Contains(got, "--profile") {
- t.Fatalf("hint output = %q, want default profile command without --profile", got)
- }
}
-func TestPrintDiskUsageEmptyHintSkipsExplicitRootOverride(t *testing.T) {
+func TestPrintDiskUsageOtherRootsHintSkipsExplicitRootOverride(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("MULTICA_WORKSPACES_ROOT", "")
@@ -202,7 +226,7 @@ func TestPrintDiskUsageEmptyHintSkipsExplicitRootOverride(t *testing.T) {
writeDiskUsageTaskFile(t, home, "has-task", "ws1", "task1", "workdir/main.go")
var out bytes.Buffer
- printDiskUsageEmptyHint(&out, daemon.DiskUsageReport{
+ printDiskUsageOtherRootsHint(&out, daemon.DiskUsageReport{
WorkspacesRoot: filepath.Join(home, "custom-root"),
}, "", filepath.Join(home, "custom-root"))
@@ -211,6 +235,72 @@ func TestPrintDiskUsageEmptyHintSkipsExplicitRootOverride(t *testing.T) {
}
}
+func TestEnumerateDiskUsageRoots(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("MULTICA_WORKSPACES_ROOT", "")
+
+ // Two profiles configured under ~/.multica/profiles, but only one has its
+ // workspaces root created on disk; the other (never-run) profile is skipped.
+ mkdirProfile(t, home, "desktop-host")
+ mkdirProfile(t, home, "never-ran")
+ writeDiskUsageTaskFile(t, home, "desktop-host", "ws1", "task1", "workdir/main.go")
+ writeDefaultDiskUsageTaskFile(t, home, "ws0", "task0", "workdir/main.go")
+
+ roots, err := enumerateDiskUsageRoots()
+ if err != nil {
+ t.Fatalf("enumerateDiskUsageRoots: %v", err)
+ }
+
+ if len(roots) != 2 {
+ t.Fatalf("roots = %+v, want default + desktop-host only", roots)
+ }
+ if roots[0].Profile != "" || roots[0].Root != filepath.Join(home, "multica_workspaces") {
+ t.Fatalf("roots[0] = %+v, want default root first", roots[0])
+ }
+ if roots[1].Profile != "desktop-host" || roots[1].Root != filepath.Join(home, "multica_workspaces_desktop-host") {
+ t.Fatalf("roots[1] = %+v, want desktop-host root", roots[1])
+ }
+}
+
+func TestPrintAggregateDiskUsageShowsRootsAndGrandTotal(t *testing.T) {
+ agg := daemon.AggregateDiskUsageReport{
+ Roots: []daemon.RootDiskUsage{
+ {Profile: "", Report: daemon.DiskUsageReport{
+ WorkspacesRoot: "/home/u/multica_workspaces",
+ Tasks: []daemon.TaskDiskUsage{{WorkspaceShort: "ws0", TaskShort: "t0", SizeBytes: 100}},
+ TotalTaskCount: 1,
+ TotalSizeBytes: 100,
+ }},
+ {Profile: "desktop-host", Report: daemon.DiskUsageReport{
+ WorkspacesRoot: "/home/u/multica_workspaces_desktop-host",
+ Tasks: []daemon.TaskDiskUsage{{WorkspaceShort: "ws1", TaskShort: "t1", SizeBytes: 900}},
+ TotalTaskCount: 1,
+ TotalSizeBytes: 900,
+ }},
+ },
+ TotalTaskCount: 2,
+ TotalSizeBytes: 1000,
+ }
+
+ var out bytes.Buffer
+ printAggregateDiskUsage(&out, agg, false)
+ got := out.String()
+
+ if !strings.Contains(got, "Scanned 2 workspace root(s).") {
+ t.Fatalf("output = %q, want scanned-roots header", got)
+ }
+ if !strings.Contains(got, "[default]") || !strings.Contains(got, "[desktop-host]") {
+ t.Fatalf("output = %q, want per-root section labels", got)
+ }
+ if !strings.Contains(got, "/home/u/multica_workspaces_desktop-host") {
+ t.Fatalf("output = %q, want desktop root path", got)
+ }
+ if !strings.Contains(got, "Grand total:") || !strings.Contains(got, "across 2 task(s) in 2 root(s)") {
+ t.Fatalf("output = %q, want grand total line", got)
+ }
+}
+
func valueColumn(t *testing.T, line string) int {
t.Helper()
colon := strings.Index(line, ":")
diff --git a/server/cmd/server/health.go b/server/cmd/server/health.go
index 18610ee730..798dc50cb8 100644
--- a/server/cmd/server/health.go
+++ b/server/cmd/server/health.go
@@ -14,7 +14,12 @@ import (
"github.com/multica-ai/multica/server/internal/migrations"
)
-const readinessQuery = `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`
+// readinessQuery counts how many of the binary's required migration versions
+// are recorded as applied. We compare the count to the number of required
+// versions rather than checking a single "latest" row, so a missing
+// out-of-order migration (numbered below an already-applied later one) is
+// detected instead of being masked by the later version's presence.
+const readinessQuery = `SELECT COUNT(*) FROM schema_migrations WHERE version = ANY($1)`
const readinessCacheTTL = 3 * time.Second
@@ -24,12 +29,12 @@ type readinessDB interface {
}
type serverHealth struct {
- db readinessDB
- latestMigration string
- initErr error
- cacheTTL time.Duration
- refreshMu sync.Mutex
- cache atomic.Pointer[cachedReadiness]
+ db readinessDB
+ requiredMigrations []string
+ initErr error
+ cacheTTL time.Duration
+ refreshMu sync.Mutex
+ cache atomic.Pointer[cachedReadiness]
}
type cachedReadiness struct {
@@ -53,12 +58,12 @@ type readinessChecks struct {
}
func newServerHealth(pool *pgxpool.Pool) *serverHealth {
- latestMigration, err := migrations.LatestVersion()
+ requiredMigrations, err := migrations.AllVersions()
return &serverHealth{
- db: pool,
- latestMigration: latestMigration,
- initErr: err,
- cacheTTL: readinessCacheTTL,
+ db: pool,
+ requiredMigrations: requiredMigrations,
+ initErr: err,
+ cacheTTL: readinessCacheTTL,
}
}
@@ -132,20 +137,23 @@ func (h *serverHealth) computeReadiness(parent context.Context) (readinessRespon
return resp, http.StatusServiceUnavailable
}
- if h.initErr != nil || h.latestMigration == "" {
+ if h.initErr != nil || len(h.requiredMigrations) == 0 {
resp.Status = "not_ready"
resp.Checks.Migrations = "error"
return resp, http.StatusServiceUnavailable
}
- var applied bool
- if err := h.db.QueryRow(ctx, readinessQuery, h.latestMigration).Scan(&applied); err != nil {
+ var appliedCount int
+ if err := h.db.QueryRow(ctx, readinessQuery, h.requiredMigrations).Scan(&appliedCount); err != nil {
resp.Status = "not_ready"
resp.Checks.Migrations = "error"
return resp, http.StatusServiceUnavailable
}
- if !applied {
+ // version is the schema_migrations PK, so each required version matches at
+ // most one row; a count below the required total means at least one
+ // migration this binary needs has not been applied.
+ if appliedCount < len(h.requiredMigrations) {
resp.Status = "not_ready"
resp.Checks.Migrations = "out_of_date"
return resp, http.StatusServiceUnavailable
diff --git a/server/cmd/server/health_test.go b/server/cmd/server/health_test.go
index 01b9bea74b..004f1dea0c 100644
--- a/server/cmd/server/health_test.go
+++ b/server/cmd/server/health_test.go
@@ -14,11 +14,11 @@ import (
)
type stubReadinessDB struct {
- pingErr error
- queryErr error
- applied bool
- pingCalls atomic.Int32
- queryCalls atomic.Int32
+ pingErr error
+ queryErr error
+ appliedCount int
+ pingCalls atomic.Int32
+ queryCalls atomic.Int32
}
func (s *stubReadinessDB) Ping(context.Context) error {
@@ -28,27 +28,27 @@ func (s *stubReadinessDB) Ping(context.Context) error {
func (s *stubReadinessDB) QueryRow(context.Context, string, ...any) pgx.Row {
s.queryCalls.Add(1)
- return stubRow{applied: s.applied, err: s.queryErr}
+ return stubRow{appliedCount: s.appliedCount, err: s.queryErr}
}
type stubRow struct {
- applied bool
- err error
+ appliedCount int
+ err error
}
func (r stubRow) Scan(dest ...any) error {
if r.err != nil {
return r.err
}
- *(dest[0].(*bool)) = r.applied
+ *(dest[0].(*int)) = r.appliedCount
return nil
}
func TestServerHealthReadyHandlerDBPingFailure(t *testing.T) {
db := &stubReadinessDB{pingErr: errors.New("db unavailable")}
h := &serverHealth{
- db: db,
- latestMigration: "056_example",
+ db: db,
+ requiredMigrations: []string{"056_example"},
}
rec := httptest.NewRecorder()
@@ -76,10 +76,10 @@ func TestServerHealthReadyHandlerDBPingFailure(t *testing.T) {
}
func TestServerHealthReadyHandlerMigrationOutOfDate(t *testing.T) {
- db := &stubReadinessDB{applied: false}
+ db := &stubReadinessDB{appliedCount: 0}
h := &serverHealth{
- db: db,
- latestMigration: "056_example",
+ db: db,
+ requiredMigrations: []string{"056_example"},
}
rec := httptest.NewRecorder()
@@ -106,12 +106,42 @@ func TestServerHealthReadyHandlerMigrationOutOfDate(t *testing.T) {
}
}
+func TestServerHealthReadyHandlerMigrationPartiallyApplied(t *testing.T) {
+ // Three migrations required but only two recorded — the out-of-order case
+ // the old "is the latest version applied?" check used to mask. Readiness
+ // must report not_ready, not ok.
+ db := &stubReadinessDB{appliedCount: 2}
+ h := &serverHealth{
+ db: db,
+ requiredMigrations: []string{"120_a", "120_b", "121_c"},
+ }
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
+ h.readyHandler(rec, req)
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503, got %d", rec.Code)
+ }
+
+ var resp readinessResponse
+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if resp.Status != "not_ready" {
+ t.Fatalf("status = %q, want %q", resp.Status, "not_ready")
+ }
+ if resp.Checks.Migrations != "out_of_date" {
+ t.Fatalf("migrations check = %q, want %q", resp.Checks.Migrations, "out_of_date")
+ }
+}
+
func TestServerHealthReadinessCachesResult(t *testing.T) {
- db := &stubReadinessDB{applied: true}
+ db := &stubReadinessDB{appliedCount: 1}
h := &serverHealth{
- db: db,
- latestMigration: "056_example",
- cacheTTL: time.Minute,
+ db: db,
+ requiredMigrations: []string{"056_example"},
+ cacheTTL: time.Minute,
}
resp1, status1 := h.readiness(context.Background())
diff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.go
index 8d4c9d5e75..f29a49f37f 100644
--- a/server/internal/daemon/diskusage.go
+++ b/server/internal/daemon/diskusage.go
@@ -55,6 +55,60 @@ type DiskUsageReport struct {
TotalArtifactRatio float64 `json:"total_artifact_ratio"`
}
+// DiskUsageRoot pairs a workspaces root with the profile it was derived from
+// ("" = the default root). ScanDiskUsageRoots scans each one and labels its
+// report with the profile so the cross-root view can attribute footprint back
+// to a profile (e.g. the Desktop app's `desktop-<host>` root).
+type DiskUsageRoot struct {
+ Profile string
+ Root string
+}
+
+// RootDiskUsage is one root's report inside an AggregateDiskUsageReport.
+type RootDiskUsage struct {
+ Profile string `json:"profile"`
+ Report DiskUsageReport `json:"report"`
+}
+
+// AggregateDiskUsageReport is the result of scanning several workspace roots in
+// one pass. Total* fields are the grand totals across every root's full scan
+// (never the post-`--top` truncated view) so the combined footprint stays
+// accurate even when each root's table is trimmed for display.
+type AggregateDiskUsageReport struct {
+ GeneratedAt time.Time `json:"generated_at"`
+ ArtifactPatterns []string `json:"artifact_patterns"`
+ Roots []RootDiskUsage `json:"roots"`
+ TotalTaskCount int `json:"total_task_count"`
+ TotalWorkspaceCount int `json:"total_workspace_count"`
+ TotalSizeBytes int64 `json:"total_size_bytes"`
+ TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`
+ TotalArtifactRatio float64 `json:"total_artifact_ratio"`
+}
+
+// ScanDiskUsageRoots scans every root in order and returns the combined report.
+// It reuses ScanDiskUsage per root — a missing root yields an empty per-root
+// report (not an error), matching the single-root command, so a never-used
+// profile root simply contributes zero. A genuinely unreadable root (e.g. a
+// permission error on the root directory itself) aborts the whole scan.
+func ScanDiskUsageRoots(roots []DiskUsageRoot, artifactPatterns []string) (AggregateDiskUsageReport, error) {
+ agg := AggregateDiskUsageReport{GeneratedAt: time.Now().UTC()}
+ agg.ArtifactPatterns = sortedKeys(buildPatternSet(artifactPatterns))
+
+ for _, r := range roots {
+ report, err := ScanDiskUsage(r.Root, artifactPatterns)
+ if err != nil {
+ return agg, err
+ }
+ agg.Roots = append(agg.Roots, RootDiskUsage{Profile: r.Profile, Report: report})
+ agg.TotalTaskCount += report.TotalTaskCount
+ agg.TotalWorkspaceCount += report.TotalWorkspaceCount
+ agg.TotalSizeBytes += report.TotalSizeBytes
+ agg.TotalArtifactSizeBytes += report.TotalArtifactSizeBytes
+ }
+ agg.TotalArtifactRatio = ratio(agg.TotalArtifactSizeBytes, agg.TotalSizeBytes)
+ return agg, nil
+}
+
// DiskUsageKindUnknown is the kind reported for task directories whose
// .gc_meta.json is missing or unreadable. Mirrors how the GC orphan path
// treats them — present on disk, but no parent record we can lock onto.
diff --git a/server/internal/daemon/diskusage_test.go b/server/internal/daemon/diskusage_test.go
index a9890d556f..5f2d45f56a 100644
--- a/server/internal/daemon/diskusage_test.go
+++ b/server/internal/daemon/diskusage_test.go
@@ -343,6 +343,51 @@ func TestScanDiskUsage_RejectsPatternsWithSeparators(t *testing.T) {
}
}
+// TestScanDiskUsageRoots_SumsAcrossRoots verifies the cross-root aggregate:
+// each root keeps its own labeled report and the grand totals are the sum of
+// every root's full scan. A missing root contributes an empty report, not an
+// error, so a never-used profile root doesn't break the aggregate.
+func TestScanDiskUsageRoots_SumsAcrossRoots(t *testing.T) {
+ t.Parallel()
+
+ rootA := t.TempDir()
+ writeFile(t, filepath.Join(rootA, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "t1", "workdir/main.go"), 100)
+
+ rootB := t.TempDir()
+ writeFile(t, filepath.Join(rootB, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "t1", "workdir/big"), 300)
+ writeFile(t, filepath.Join(rootB, "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "t2", "workdir/main.go"), 50)
+
+ missing := filepath.Join(t.TempDir(), "never-ran")
+
+ agg, err := ScanDiskUsageRoots([]DiskUsageRoot{
+ {Profile: "", Root: rootA},
+ {Profile: "desktop-host", Root: rootB},
+ {Profile: "never-ran", Root: missing},
+ }, []string{"node_modules"})
+ if err != nil {
+ t.Fatalf("ScanDiskUsageRoots: %v", err)
+ }
+
+ if len(agg.Roots) != 3 {
+ t.Fatalf("Roots len = %d, want 3 (missing root still listed, empty)", len(agg.Roots))
+ }
+ if agg.Roots[0].Profile != "" || agg.Roots[1].Profile != "desktop-host" {
+ t.Fatalf("root profiles not preserved in order: %+v", agg.Roots)
+ }
+ if agg.Roots[2].Report.TotalTaskCount != 0 {
+ t.Fatalf("missing root TotalTaskCount = %d, want 0", agg.Roots[2].Report.TotalTaskCount)
+ }
+ if agg.TotalTaskCount != 3 {
+ t.Fatalf("TotalTaskCount = %d, want 3 across roots", agg.TotalTaskCount)
+ }
+ if agg.TotalSizeBytes != 450 {
+ t.Fatalf("TotalSizeBytes = %d, want 450 (100 + 300 + 50)", agg.TotalSizeBytes)
+ }
+ if agg.TotalWorkspaceCount != 2 {
+ t.Fatalf("TotalWorkspaceCount = %d, want 2", agg.TotalWorkspaceCount)
+ }
+}
+
func mustWriteMeta(t *testing.T, taskDir string, meta execenv.GCMeta) {
t.Helper()
data, err := json.Marshal(meta)
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index f046e506b7..e531501310 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -812,7 +812,27 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.Queries.DeleteAutopilot(r.Context(), idUUID); err != nil {
+ // autopilot_subscriber carries no DB-level foreign key/cascade (repo rule:
+ // referential cleanup lives in the application layer), so delete the
+ // subscriber template alongside the autopilot in one transaction. Without
+ // this, deleting an autopilot would orphan its subscriber rows.
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ if err := qtx.DeleteAutopilotSubscribersForAutopilot(r.Context(), idUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ if err := qtx.DeleteAutopilot(r.Context(), idUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete autopilot")
return
}
diff --git a/server/internal/handler/autopilot_subscriber_test.go b/server/internal/handler/autopilot_subscriber_test.go
index 962f279739..11aa3c0d72 100644
--- a/server/internal/handler/autopilot_subscriber_test.go
+++ b/server/internal/handler/autopilot_subscriber_test.go
@@ -596,3 +596,74 @@ func TestAutopilotDispatchSkipsInboxWhenNoSubscribers(t *testing.T) {
t.Fatalf("issue_subscribed inbox rows = %d, want 0 (no subscribers)", inboxCount)
}
}
+
+// TestDeleteAutopilotRemovesSubscribers guards the app-layer cleanup that
+// replaced the dropped autopilot_subscriber → autopilot ON DELETE CASCADE:
+// deleting an autopilot must also delete its subscriber template rows in the
+// same transaction, leaving no orphans behind.
+func TestDeleteAutopilotRemovesSubscribers(t *testing.T) {
+ ctx := context.Background()
+ var autopilotID string
+ defer func() {
+ if autopilotID != "" {
+ testPool.Exec(ctx, `DELETE FROM autopilot_subscriber WHERE autopilot_id = $1`, autopilotID)
+ testPool.Exec(ctx, `DELETE FROM autopilot WHERE id = $1`, autopilotID)
+ }
+ }()
+
+ var agentID string
+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("load test agent: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Delete-with-subscribers autopilot",
+ "assignee_id": agentID,
+ "execution_mode": "create_issue",
+ "subscribers": []map[string]any{
+ {"user_type": "member", "user_id": testUserID},
+ },
+ })
+ testHandler.CreateAutopilot(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAutopilot: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created AutopilotResponse
+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
+ t.Fatalf("decode created: %v", err)
+ }
+ autopilotID = created.ID
+
+ var before int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM autopilot_subscriber WHERE autopilot_id = $1`, autopilotID).Scan(&before); err != nil {
+ t.Fatalf("count subscribers before delete: %v", err)
+ }
+ if before != 1 {
+ t.Fatalf("subscriber rows before delete = %d, want 1", before)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("DELETE", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, nil)
+ req = withURLParam(req, "id", autopilotID)
+ testHandler.DeleteAutopilot(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteAutopilot: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var after int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM autopilot_subscriber WHERE autopilot_id = $1`, autopilotID).Scan(&after); err != nil {
+ t.Fatalf("count subscribers after delete: %v", err)
+ }
+ if after != 0 {
+ t.Fatalf("subscriber rows after delete = %d, want 0 (app-layer cleanup)", after)
+ }
+
+ var autopilotRows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM autopilot WHERE id = $1`, autopilotID).Scan(&autopilotRows); err != nil {
+ t.Fatalf("count autopilot after delete: %v", err)
+ }
+ if autopilotRows != 0 {
+ t.Fatalf("autopilot rows after delete = %d, want 0", autopilotRows)
+ }
+}
diff --git a/server/internal/migrations/migrations.go b/server/internal/migrations/migrations.go
index e91b74ac1e..17e6e9e765 100644
--- a/server/internal/migrations/migrations.go
+++ b/server/internal/migrations/migrations.go
@@ -69,16 +69,24 @@ func Files(direction string) ([]string, error) {
return files, nil
}
-// LatestVersion returns the latest "up" migration version found on disk.
-func LatestVersion() (string, error) {
+// AllVersions returns every "up" migration version found on disk, in apply
+// order. The readiness check verifies that all of them are recorded in
+// schema_migrations — checking only the lexically-last version would miss an
+// out-of-order migration (one numbered below an already-applied later one),
+// letting a server report ready while running against a schema that lacks it.
+func AllVersions() ([]string, error) {
files, err := Files("up")
if err != nil {
- return "", err
+ return nil, err
}
if len(files) == 0 {
- return "", fmt.Errorf("no up migrations found")
+ return nil, fmt.Errorf("no up migrations found")
+ }
+ versions := make([]string, len(files))
+ for i, f := range files {
+ versions[i] = ExtractVersion(f)
}
- return ExtractVersion(files[len(files)-1]), nil
+ return versions, nil
}
// ExtractVersion strips the .up.sql / .down.sql suffix from a migration file.
diff --git a/server/migrations/120_autopilot_subscriber.down.sql b/server/migrations/120_autopilot_subscriber.down.sql
index 5f6aaa9065..e742d46c93 100644
--- a/server/migrations/120_autopilot_subscriber.down.sql
+++ b/server/migrations/120_autopilot_subscriber.down.sql
@@ -1,7 +1,10 @@
-- Rows still carrying reason='autopilot' would violate the restored CHECK
--- constraint, so drop them first. Operators wanting an audit trail should
--- backfill reason='manual' before rolling this back.
-DELETE FROM issue_subscriber WHERE reason = 'autopilot';
+-- constraint. Relabel them to 'manual' (a value the restored CHECK still
+-- allows) instead of deleting them, so rolling back narrows the reason taxonomy
+-- without silently dropping who is subscribed. The reason column is not part of
+-- issue_subscriber's PK (issue_id, user_type, user_id), so this UPDATE can never
+-- collide with an existing row for the same subscriber.
+UPDATE issue_subscriber SET reason = 'manual' WHERE reason = 'autopilot';
ALTER TABLE issue_subscriber DROP CONSTRAINT issue_subscriber_reason_check;
ALTER TABLE issue_subscriber ADD CONSTRAINT issue_subscriber_reason_check
diff --git a/server/migrations/120_autopilot_subscriber.up.sql b/server/migrations/120_autopilot_subscriber.up.sql
index 1593bec0c0..320b44470f 100644
--- a/server/migrations/120_autopilot_subscriber.up.sql
+++ b/server/migrations/120_autopilot_subscriber.up.sql
@@ -1,9 +1,12 @@
-- Template list of workspace members auto-subscribed to every issue spawned
-- by the autopilot. Members-only for now (broaden the CHECK to expand).
--- No FK on user_id — workspace membership is enforced at the API boundary
--- (isWorkspaceEntity in the handler), matching issue_subscriber.
+-- No foreign keys or cascades — autopilot existence and workspace membership
+-- are both enforced in the application layer (the autopilot delete handler
+-- removes these rows in the same transaction; membership is checked at the API
+-- boundary via isWorkspaceEntity), per the repo rule. Mirrors issue_subscriber's
+-- app-level user_id handling.
CREATE TABLE autopilot_subscriber (
- autopilot_id UUID NOT NULL REFERENCES autopilot(id) ON DELETE CASCADE,
+ autopilot_id UUID NOT NULL,
user_type TEXT NOT NULL CHECK (user_type IN ('member')),
user_id UUID NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
diff --git a/server/migrations/120_comment_source_task_id.up.sql b/server/migrations/120_comment_source_task_id.up.sql
index 3dced6569e..cac13eb18c 100644
--- a/server/migrations/120_comment_source_task_id.up.sql
+++ b/server/migrations/120_comment_source_task_id.up.sql
@@ -1,2 +1,8 @@
+-- Trace pointer to the agent_task_queue row that produced this comment, used by
+-- the "retry failed agent comment" affordance. No FK on source_task_id: the
+-- referenced task can be GC'd independently of the comment it produced, and the
+-- relationship is resolved in the application layer (a missing task simply means
+-- the source is no longer retryable). Matches the repo rule that foreign keys
+-- and cascades are handled by the app, not the database.
ALTER TABLE comment
- ADD COLUMN source_task_id UUID REFERENCES agent_task_queue(id) ON DELETE SET NULL;
+ ADD COLUMN source_task_id UUID;