Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(daemon): account for and evict the bare repo cache (#6297)
Bohan Jianga735e4808d5f
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex bd9c48d23f..685dfacf94 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -187,17 +187,22 @@ Daemon behavior is configured via flags or environment variables:| 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) || GC artifact patterns | — | `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` |+| GC repo cache TTL (`.repos`) | — | `MULTICA_GC_REPO_TTL` | `720h` (30d; set `0` to disable) |#### Workspace garbage collection-The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space in three modes:+The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space in four modes:- **Full task cleanup** — when an issue's status is `done` or `cancelled` and has been idle for `MULTICA_GC_TTL`, the entire task directory is removed.- **Orphan cleanup** — task directories with no `.gc_meta.json` (e.g. left over from a daemon crash) are removed once they exceed `MULTICA_GC_ORPHAN_TTL`.- **Artifact-only cleanup** — when a task has been completed for at least `MULTICA_GC_ARTIFACT_TTL` but the issue is still open, regenerable build outputs whose directory basename matches `MULTICA_GC_ARTIFACT_PATTERNS` are removed. The daemon also reclaims the exact managed path `codex-home/.sandbox-bin`; old task metadata without `completed_at` becomes eligible for this managed-only cleanup after its `.gc_meta.json` file has been idle for `MULTICA_GC_ORPHAN_TTL`. The rest of the task (source, `.git`, `output/`, `logs/`, `.gc_meta.json`, Codex auth/config/session state) is preserved so the agent can resume it.+- **Repo cache eviction** — the bare git clones under `.repos/` are shared object stores: each task workdir is a `git worktree` off one of them rather than its own clone, so a task's `.git` is only a pointer file. They are evicted only when all of the following hold: the repo is no longer attached to any workspace this daemon watches, it has no worktrees left, and no task has created a worktree from it for `MULTICA_GC_REPO_TTL`. A cache created before this stamp existed is not treated as ancient — its clock starts at the first GC cycle that sees it, so upgrading does not wipe every cache. Evicting is safe by construction: the next task that needs the repo re-clones it on demand, so a wrong eviction costs a clone, not a failure.+Configured patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The managed Codex cache is matched by its exact relative path, so a repository's own `.sandbox-bin` is not removed unless an operator explicitly adds that basename to `MULTICA_GC_ARTIFACT_PATTERNS`. The default list (`node_modules`, `.next`, `.turbo`) is intentionally narrow; extend it per deployment if your repos consistently produce other regenerable directories (for example, `MULTICA_GC_ARTIFACT_PATTERNS=node_modules,.next,.turbo,target,__pycache__`). To disable artifact cleanup entirely, including the managed Codex cache, set `MULTICA_GC_ARTIFACT_TTL=0`.+`multica daemon disk-usage` reports the `.repos` footprint on its own line rather than folding it into the per-task totals — every task in a workspace checks out from that shared cache, so attributing it to individual task directories would double-count it. Note that the repo cache is reclaimed on the schedule above and not by any per-issue status change, so it is normal for it to persist after every task directory is gone.+Agent-specific overrides:| Variable | Description |diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex b0d4187cb3..9bf070bb59 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -1558,12 +1558,17 @@ func printAggregateDiskUsage(w io.Writer, agg daemon.AggregateDiskUsageReport, bfmt.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)+ if agg.TotalRepoCacheCount > 0 || agg.TotalRepoCacheSizeBytes > 0 {+ fmt.Fprintf(w, "Repo cache (.repos): %s across %d repo(s) in all roots, not included above.\n",+ formatBytes(agg.TotalRepoCacheSizeBytes), agg.TotalRepoCacheCount)+ }}func printDiskUsageTaskTable(w io.Writer, report daemon.DiskUsageReport) {fmt.Fprintf(w, "Workspaces root: %s\n", report.WorkspacesRoot)if report.TotalTaskCount == 0 {fmt.Fprintln(w, "(no task directories)")+ printRepoCacheLine(w, report)return}rows := make([][]string, 0, len(report.Tasks))@@ -1591,17 +1596,32 @@ func printDiskUsageTaskTable(w io.Writer, report daemon.DiskUsageReport) {formatBytes(displayedSize), formatBytes(displayedArtifact),formatBytes(report.TotalSizeBytes), formatBytes(report.TotalArtifactSizeBytes),report.TotalArtifactRatio*100)+ } else {+ fmt.Fprintf(w, "\nTotal: %s across %d task(s); %s reclaimable as artifacts (%.1f%%).\n",+ formatBytes(report.TotalSizeBytes), report.TotalTaskCount,+ formatBytes(report.TotalArtifactSizeBytes), report.TotalArtifactRatio*100)+ }+ printRepoCacheLine(w, report)+}++// printRepoCacheLine reports the bare-repo cache on its own line. Every task+// directory in a workspace checks out from this shared cache, so folding it+// into the task totals would attribute it to directories that do not contain+// it. Omitting it entirely — the previous behaviour — is what made the+// reported total silently disagree with the user's file manager.+func printRepoCacheLine(w io.Writer, report daemon.DiskUsageReport) {+ if report.RepoCacheCount == 0 && report.RepoCacheSizeBytes == 0 {return}- fmt.Fprintf(w, "\nTotal: %s across %d task(s); %s reclaimable as artifacts (%.1f%%).\n",- formatBytes(report.TotalSizeBytes), report.TotalTaskCount,- formatBytes(report.TotalArtifactSizeBytes), report.TotalArtifactRatio*100)+ fmt.Fprintf(w, "Repo cache (.repos): %s across %d repo(s), not included above. Evicted once a repo is unused for MULTICA_GC_REPO_TTL and no longer attached to a workspace.\n",+ formatBytes(report.RepoCacheSizeBytes), report.RepoCacheCount)}func printDiskUsageWorkspaceTable(w io.Writer, report daemon.DiskUsageReport) {fmt.Fprintf(w, "Workspaces root: %s\n", report.WorkspacesRoot)if report.TotalWorkspaceCount == 0 {fmt.Fprintln(w, "(no workspaces)")+ printRepoCacheLine(w, report)return}rows := make([][]string, 0, len(report.Workspaces))@@ -1626,11 +1646,12 @@ func printDiskUsageWorkspaceTable(w io.Writer, report daemon.DiskUsageReport) {formatBytes(displayedSize), formatBytes(displayedArtifact),formatBytes(report.TotalSizeBytes), formatBytes(report.TotalArtifactSizeBytes),report.TotalArtifactRatio*100)- return+ } else {+ fmt.Fprintf(w, "\nTotal: %s across %d workspace(s); %s reclaimable as artifacts (%.1f%%).\n",+ formatBytes(report.TotalSizeBytes), report.TotalWorkspaceCount,+ formatBytes(report.TotalArtifactSizeBytes), report.TotalArtifactRatio*100)}- fmt.Fprintf(w, "\nTotal: %s across %d workspace(s); %s reclaimable as artifacts (%.1f%%).\n",- formatBytes(report.TotalSizeBytes), report.TotalWorkspaceCount,- formatBytes(report.TotalArtifactSizeBytes), report.TotalArtifactRatio*100)+ printRepoCacheLine(w, report)}// printDiskUsageOtherRootsHint warns that workspace roots OTHER than the onediff --git a/server/cmd/multica/cmd_daemon_diskusage_status_test.go b/server/cmd/multica/cmd_daemon_diskusage_status_test.goindex b1f6cfbce3..132dc658ae 100644--- a/server/cmd/multica/cmd_daemon_diskusage_status_test.go+++ b/server/cmd/multica/cmd_daemon_diskusage_status_test.go@@ -1,7 +1,9 @@package mainimport (+ "bytes""encoding/json"+ "io""net/http""net/http/httptest""os"@@ -12,6 +14,7 @@ import ("time""github.com/multica-ai/multica/server/internal/cli"+ "github.com/multica-ai/multica/server/internal/daemon""github.com/spf13/cobra")@@ -290,3 +293,65 @@ func TestRunDaemonDiskUsageAllProfilesUsesPerProfileToken(t *testing.T) {t.Errorf("second profile root resolved with token %q, want token-second", got)}}++// TestPrintRepoCacheLineAppearsInEveryView guards the branch this first shipped+// wrong: both table renderers have a truncated (--top) path that returns early+// and a full-total path, and the repo cache line has to survive all of them.+// Otherwise the footprint that motivated the whole accounting change stays+// invisible in exactly the view users run most.+func TestPrintRepoCacheLineAppearsInEveryView(t *testing.T) {+ t.Parallel()++ const wantLine = "Repo cache (.repos): 4.0 KiB across 2 repo(s)"+ report := daemon.DiskUsageReport{+ WorkspacesRoot: "/root",+ Tasks: []daemon.TaskDiskUsage{{WorkspaceShort: "ws0", TaskShort: "t0", SizeBytes: 100}},+ Workspaces: []daemon.WorkspaceDiskUsage{{WorkspaceShort: "ws0", TaskCount: 1, SizeBytes: 100}},+ RepoCacheSizeBytes: 4096,+ RepoCacheCount: 2,+ }++ cases := []struct {+ name string+ print func(io.Writer, daemon.DiskUsageReport)+ // truncated makes len(slice) < Total*Count, taking the --top branch.+ truncated bool+ }{+ {"task table, full totals", printDiskUsageTaskTable, false},+ {"task table, --top truncated", printDiskUsageTaskTable, true},+ {"workspace table, full totals", printDiskUsageWorkspaceTable, false},+ {"workspace table, --top truncated", printDiskUsageWorkspaceTable, true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ r := report+ r.TotalTaskCount = 1+ r.TotalWorkspaceCount = 1+ if tc.truncated {+ r.TotalTaskCount = 50+ r.TotalWorkspaceCount = 50+ }+ var buf bytes.Buffer+ tc.print(&buf, r)+ if !strings.Contains(buf.String(), wantLine) {+ t.Errorf("missing %q in:\n%s", wantLine, buf.String())+ }+ })+ }+}++// TestPrintRepoCacheLineSilentWhenEmpty keeps the line out of reports from+// machines that have never cached a repo.+func TestPrintRepoCacheLineSilentWhenEmpty(t *testing.T) {+ t.Parallel()++ var buf bytes.Buffer+ printDiskUsageTaskTable(&buf, daemon.DiskUsageReport{+ WorkspacesRoot: "/root",+ Tasks: []daemon.TaskDiskUsage{{WorkspaceShort: "ws0", TaskShort: "t0", SizeBytes: 100}},+ TotalTaskCount: 1,+ })+ if strings.Contains(buf.String(), "Repo cache") {+ t.Errorf("empty repo cache must not print a line:\n%s", buf.String())+ }+}diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 19ceda4fe1..57c6116f8a 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -69,6 +69,7 @@ const (DefaultGCOrphanTTL = 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 issuesDefaultGCCodexSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-issue Codex session stores untouched this long+ DefaultGCRepoTTL = 30 * 24 * time.Hour // 30 days — evict a bare repo cache no task has checked out this longDefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release)@@ -101,6 +102,7 @@ type Config struct {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)GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)+ GCRepoTTL time.Duration // evict a cached bare repo under .repos once no task has created a worktree from it for this long, it has no worktrees left, and it is no longer attached to any watched workspace (default: 30d, set 0 to disable)GCCodexSessionTTL time.Duration // reclaim a per-issue Codex session store (~/.codex/multica-sessions/<agent>/<issue>) untouched for at least this long, so a done/abandoned issue's conversation history does not accumulate forever (default: 14d, set 0 to disable)AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true on Multica Cloud, false on self-host)AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)@@ -407,6 +409,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcRepoTTL, err := durationFromEnv("MULTICA_GC_REPO_TTL", DefaultGCRepoTTL)+ if err != nil {+ return Config{}, err+ }gcArtifactPatterns := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", DefaultGCArtifactPatterns)// Auto-update config: default -> env override -> CLI override.@@ -454,6 +460,7 @@ func LoadConfig(overrides Overrides) (Config, error) {GCOrphanTTL: gcOrphanTTL,GCArtifactTTL: gcArtifactTTL,GCArtifactPatterns: gcArtifactPatterns,+ GCRepoTTL: gcRepoTTL,GCCodexSessionTTL: gcCodexSessionTTL,AutoUpdateEnabled: autoUpdateEnabled,AutoUpdateCheckInterval: autoUpdateInterval,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 47610072ea..33f6d60990 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -243,6 +243,7 @@ type workspaceState struct {type repoCacheBackend interface {Lookup(workspaceID, url string) string+ BarePath(workspaceID, url string) stringSync(workspaceID string, repos []repocache.RepoInfo) errorWithRepoLock(barePath string, fn func() error) errorCreateWorktree(params repocache.WorktreeParams) (*repocache.WorktreeResult, error)@@ -1913,6 +1914,37 @@ func (d *Daemon) workspaceRepoAllowed(workspaceID, repoURL string) bool {return false}+// liveRepoBarePaths returns the bare cache directories that some watched+// workspace still claims, so the GC can refuse to evict them.+//+// It mirrors workspaceRepoAllowed by unioning both sources: allowedRepoURLs+// (workspace-level bindings) and taskRepoURLs (project repos the server+// surfaced through a task claim, which never appear in GetWorkspaceRepos).+// Missing the second set would make the GC evict repos that tasks actively+// check out.+//+// Read from in-memory state on purpose. The alternative — asking the server+// for each workspace's repo list during GC — would make a transient API+// failure look like "nothing is attached", and this set is what protects+// caches from deletion.+func (d *Daemon) liveRepoBarePaths() map[string]struct{} {+ live := map[string]struct{}{}+ if d.repoCache == nil {+ return live+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ for workspaceID, ws := range d.workspaces {+ for url := range ws.allowedRepoURLs {+ live[d.repoCache.BarePath(workspaceID, url)] = struct{}{}+ }+ for url := range ws.taskRepoURLs {+ live[d.repoCache.BarePath(workspaceID, url)] = struct{}{}+ }+ }+ return live+}+func (d *Daemon) workspaceLastRepoSyncErr(workspaceID string) string {d.mu.Lock()defer d.mu.Unlock()diff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.goindex 9f15f2c26e..fcc966685d 100644--- a/server/internal/daemon/diskusage.go+++ b/server/internal/daemon/diskusage.go@@ -62,6 +62,13 @@ type DiskUsageReport struct {TotalSizeBytes int64 `json:"total_size_bytes"`TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`TotalArtifactRatio float64 `json:"total_artifact_ratio"`+ // RepoCacheSizeBytes is the bare-repo cache (.repos) footprint. It is a+ // sibling of the task directories, not one of them, so it is reported+ // separately and deliberately excluded from Total*: those totals describe+ // task dirs, and folding a shared cache into them would double-count it+ // against per-task numbers that do not contain it.+ RepoCacheSizeBytes int64 `json:"repo_cache_size_bytes"`+ RepoCacheCount int `json:"repo_cache_count"`}// DiskUsageRoot pairs a workspaces root with the profile it was derived from@@ -93,6 +100,8 @@ type AggregateDiskUsageReport struct {TotalSizeBytes int64 `json:"total_size_bytes"`TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`TotalArtifactRatio float64 `json:"total_artifact_ratio"`+ TotalRepoCacheSizeBytes int64 `json:"total_repo_cache_size_bytes"`+ TotalRepoCacheCount int `json:"total_repo_cache_count"`}// ScanDiskUsageRoots scans every root in order and returns the combined report.@@ -116,6 +125,8 @@ func ScanDiskUsageRoots(roots []DiskUsageRoot, artifactPatterns []string) (Aggreagg.TotalWorkspaceCount += report.TotalWorkspaceCountagg.TotalSizeBytes += report.TotalSizeBytesagg.TotalArtifactSizeBytes += report.TotalArtifactSizeBytes+ agg.TotalRepoCacheSizeBytes += report.RepoCacheSizeBytes+ agg.TotalRepoCacheCount += report.RepoCacheCount}agg.TotalArtifactRatio = ratio(agg.TotalArtifactSizeBytes, agg.TotalSizeBytes)return agg, nil@@ -162,10 +173,21 @@ func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageRwsAgg := map[string]*WorkspaceDiskUsage{}for _, wsEntry := range wsEntries {- // Skip the bare-repo cache and any non-directory entries; the GC loop- // applies the same exclusions, so the disk-usage report stays in sync- // with what the GC actually walks.- if !wsEntry.IsDir() || wsEntry.Name() == ".repos" {+ if !wsEntry.IsDir() {+ continue+ }+ // The bare-repo cache is not a workspace. Measure it separately rather+ // than skipping it outright: it is reclaimed on its own schedule+ // (GCRepoTTL) and used to be invisible here, which made the reported+ // total disagree with the user's file manager for no stated reason.+ if wsEntry.Name() == reposDirName {+ report.RepoCacheSizeBytes, report.RepoCacheCount = repoCacheSize(filepath.Join(workspacesRoot, wsEntry.Name()))+ continue+ }+ // Other dot-directories are daemon-internal caches (skill bundles and+ // friends), never workspaces. Counting them as workspaces put rows like+ // ".skillca" in the per-workspace table.+ if strings.HasPrefix(wsEntry.Name(), ".") {continue}wsID := wsEntry.Name()@@ -222,6 +244,34 @@ func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageRreturn report, nil}+// repoCacheSize measures the bare-repo cache and counts the repos in it.+// Layout is .repos/<workspace-id>/<repo-dir>, so the count is the number of+// second-level directories — the unit the GC evicts.+func repoCacheSize(reposRoot string) (sizeBytes int64, repoCount int) {+ wsEntries, err := os.ReadDir(reposRoot)+ if err != nil {+ return 0, 0+ }+ for _, wsEntry := range wsEntries {+ if !wsEntry.IsDir() {+ continue+ }+ wsDir := filepath.Join(reposRoot, wsEntry.Name())+ repoEntries, err := os.ReadDir(wsDir)+ if err != nil {+ continue+ }+ for _, repoEntry := range repoEntries {+ if !repoEntry.IsDir() {+ continue+ }+ repoCount+++ sizeBytes += dirSize(filepath.Join(wsDir, repoEntry.Name()))+ }+ }+ return sizeBytes, repoCount+}+// ratio returns numerator / denominator, mapping 0/0 (and any 0 denominator)// to 0 instead of NaN. Callers render the result as a percentage so a NaN// would surface as "NaN%" in the table — guard at the source.diff --git a/server/internal/daemon/diskusage_test.go b/server/internal/daemon/diskusage_test.goindex 6d6c35d41a..f2d3a33bc4 100644--- a/server/internal/daemon/diskusage_test.go+++ b/server/internal/daemon/diskusage_test.go@@ -658,3 +658,66 @@ func TestResolveParentStatuses_NoFetcherIsNoOp(t *testing.T) {t.Fatalf("nil report should be a no-op, got %v", err)}}++// TestScanDiskUsage_ReportsRepoCacheSeparately pins the accounting split: the+// bare-repo cache is measured (it used to be invisible, which made the reported+// total silently disagree with the user's file manager) but kept out of the+// task totals, since every task checks out from it and none contains it.+func TestScanDiskUsage_ReportsRepoCacheSeparately(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ wsID := "11111111-1111-1111-1111-111111111111"+ writeFile(t, filepath.Join(root, wsID, "aaaaaaaa", "workdir/main.go"), 1000)++ // .repos/<workspace>/<repo>/... — the repo dir is the unit the GC evicts.+ writeFile(t, filepath.Join(root, ".repos", wsID, "widgets.git", "objects/pack/x"), 4000)+ writeFile(t, filepath.Join(root, ".repos", wsID, "gadgets.git", "objects/pack/y"), 2000)++ report, err := ScanDiskUsage(root, nil)+ if err != nil {+ t.Fatalf("ScanDiskUsage: %v", err)+ }++ if report.RepoCacheSizeBytes != 6000 {+ t.Errorf("repo_cache_size_bytes = %d, want 6000", report.RepoCacheSizeBytes)+ }+ if report.RepoCacheCount != 2 {+ t.Errorf("repo_cache_count = %d, want 2", report.RepoCacheCount)+ }+ if report.TotalSizeBytes != 1000 {+ t.Errorf("total_size_bytes = %d, want 1000 (task dirs only, cache excluded)", report.TotalSizeBytes)+ }+ if report.TotalWorkspaceCount != 1 {+ t.Errorf("total_workspace_count = %d, want 1 (.repos is not a workspace)", report.TotalWorkspaceCount)+ }+}++// TestScanDiskUsage_SkipsDaemonInternalDotDirs keeps caches like .skill-cache+// out of the per-workspace table, where they used to surface as bogus+// workspace rows alongside the real ones.+func TestScanDiskUsage_SkipsDaemonInternalDotDirs(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ wsID := "11111111-1111-1111-1111-111111111111"+ writeFile(t, filepath.Join(root, wsID, "aaaaaaaa", "workdir/main.go"), 1000)+ writeFile(t, filepath.Join(root, ".skill-cache", "v1", "bundle", "skill.md"), 500)++ report, err := ScanDiskUsage(root, nil)+ if err != nil {+ t.Fatalf("ScanDiskUsage: %v", err)+ }++ if report.TotalWorkspaceCount != 1 {+ t.Fatalf("total_workspace_count = %d, want 1", report.TotalWorkspaceCount)+ }+ for _, ws := range report.Workspaces {+ if strings.HasPrefix(ws.WorkspaceID, ".") {+ t.Errorf("dot-directory %q reported as a workspace", ws.WorkspaceID)+ }+ }+ if report.TotalSizeBytes != 1000 {+ t.Errorf("total_size_bytes = %d, want 1000 (skill cache excluded)", report.TotalSizeBytes)+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 374973233a..01d9f8b986 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -11,8 +11,14 @@ import ("time""github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/daemon/repocache")+// reposDirName is the bare-repo cache directory inside the workspaces root.+// It is a sibling of the per-workspace task directories rather than one of+// them, so every walk over the root has to decide explicitly what to do with it.+const reposDirName = ".repos"+// gcLoop periodically scans local workspace directories and removes those// whose issue is done/cancelled and hasn't been updated within the configured TTL.func (d *Daemon) gcLoop(ctx context.Context) {@@ -25,6 +31,7 @@ func (d *Daemon) gcLoop(ctx context.Context) {"ttl", d.cfg.GCTTL,"orphan_ttl", d.cfg.GCOrphanTTL,"artifact_ttl", d.cfg.GCArtifactTTL,+ "repo_ttl", d.cfg.GCRepoTTL,"artifact_patterns", d.cfg.GCArtifactPatterns,"managed_artifact_subpaths", execenv.ManagedReclaimableArtifactSubpaths(),)@@ -50,14 +57,15 @@ func (d *Daemon) gcLoop(ctx context.Context) {// gcStats accumulates byte counts and per-pattern hit counts for one GC cycle.type gcStats struct {- cleaned int // whole task dirs removed (issue done/cancelled)- orphaned int // whole task dirs removed (no meta / unreachable issue)- skipped int // task dirs left untouched- artifactDirs int // task dirs that had at least one artifact reclaimed- artifactRemoved int // count of removed artifact subdirs- storesReclaimed int // per-issue Codex session stores reclaimed past their TTL- bytesReclaimed int64 // total bytes freed in this cycle- byPattern map[string]int // configured basename or managed path label -> reclaim count+ cleaned int // whole task dirs removed (issue done/cancelled)+ orphaned int // whole task dirs removed (no meta / unreachable issue)+ skipped int // task dirs left untouched+ artifactDirs int // task dirs that had at least one artifact reclaimed+ artifactRemoved int // count of removed artifact subdirs+ storesReclaimed int // per-issue Codex session stores reclaimed past their TTL+ repoCachesReclaimed int // bare repo caches under .repos evicted past their TTL+ bytesReclaimed int64 // total bytes freed in this cycle+ byPattern map[string]int // configured basename or managed path label -> reclaim count}// runGC performs a single GC scan across all workspace directories.@@ -74,15 +82,17 @@ func (d *Daemon) runGC(ctx context.Context) {stats := &gcStats{byPattern: map[string]int{}}for _, wsEntry := range entries {- if !wsEntry.IsDir() || wsEntry.Name() == ".repos" {+ if !wsEntry.IsDir() || wsEntry.Name() == reposDirName {continue}wsDir := filepath.Join(root, wsEntry.Name())d.gcWorkspace(ctx, wsDir, stats)}- // Prune stale worktree references from all bare repo caches.- d.pruneRepoWorktrees(root)+ // Prune stale worktree references from all bare repo caches, then evict the+ // caches nothing needs anymore. These live outside any workspace directory+ // and are never reclaimed by the task walk above.+ d.pruneRepoWorktrees(root, stats)// Reclaim per-issue Codex session stores idle past their TTL. These live// under the shared ~/.codex home (outside WorkspacesRoot) so resume survives@@ -92,7 +102,7 @@ func (d *Daemon) runGC(ctx context.Context) {stats.bytesReclaimed += storeBytes}- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 {+ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.repoCachesReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,@@ -100,6 +110,7 @@ func (d *Daemon) runGC(ctx context.Context) {"artifact_dirs", stats.artifactDirs,"artifact_removed", stats.artifactRemoved,"codex_session_stores_reclaimed", stats.storesReclaimed,+ "repo_caches_reclaimed", stats.repoCachesReclaimed,"bytes_reclaimed", stats.bytesReclaimed,"by_pattern", stats.byPattern,)@@ -726,14 +737,16 @@ const (gitMaintenanceTimeout = 10 * time.Minute)-// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache.-func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {- reposRoot := filepath.Join(workspacesRoot, ".repos")+// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache,+// then evicts the ones nothing needs anymore.+func (d *Daemon) pruneRepoWorktrees(workspacesRoot string, stats *gcStats) {+ reposRoot := filepath.Join(workspacesRoot, reposDirName)wsEntries, err := os.ReadDir(reposRoot)if err != nil {return}+ live := d.liveRepoBarePaths()for _, wsEntry := range wsEntries {if !wsEntry.IsDir() {continue@@ -751,24 +764,152 @@ func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {if !isBareRepo(barePath) {continue}- d.pruneWorktree(barePath)+ d.maintainRepoCache(barePath, live, stats)+ }+ // Drop the per-workspace directory once its last repo is gone.+ if remaining, err := os.ReadDir(wsRepoDir); err == nil && len(remaining) == 0 {+ os.Remove(wsRepoDir)}}}+func (d *Daemon) maintainRepoCache(barePath string, live map[string]struct{}, stats *gcStats) {+ d.withRepoLock(barePath, func() {+ d.pruneWorktreeLocked(barePath)+ d.evictRepoCacheLocked(barePath, live, stats)+ })+}++// pruneWorktree runs only the maintenance half — prune stale worktrees and+// agent branches — without considering eviction.func (d *Daemon) pruneWorktree(barePath string) {- if d.repoCache != nil {- if err := d.repoCache.WithRepoLock(barePath, func() error {- d.pruneWorktreeLocked(barePath)- return nil- }); err != nil {- d.logger.Warn("gc: repo lock failed", "repo", barePath, "error", err)- return- }+ d.withRepoLock(barePath, func() { d.pruneWorktreeLocked(barePath) })+}++// withRepoLock serializes a mutation against Sync / CreateWorktree on the same+// bare repo. A daemon built without a repo cache (tests, degraded startup) has+// no lock to take and runs the work directly.+func (d *Daemon) withRepoLock(barePath string, fn func()) {+ if d.repoCache == nil {+ fn()+ return+ }+ if err := d.repoCache.WithRepoLock(barePath, func() error {+ fn()+ return nil+ }); err != nil {+ d.logger.Warn("gc: repo lock failed", "repo", barePath, "error", err)+ }+}++// evictRepoCacheLocked removes a bare repo cache that nothing needs anymore.+// The caller must hold the repo lock, so this cannot race a Sync or a+// CreateWorktree on the same repo.+//+// All four conditions are required:+//+// 1. GCRepoTTL > 0 — eviction is opt-out.+//+// 2. No watched workspace still claims the repo. This is a RETAIN predicate,+// not a delete predicate, and the direction matters: Sync re-clones every+// listed repo that is missing whenever a workspace registers, which happens+// on every daemon start. Evicting a still-attached repo therefore just buys+// a full re-clone on the next restart — that is not reclaiming space, it is+// moving it. Because the set only ever *prevents* deletion, a stale or+// empty one cannot widen what we delete; it can only drop a layer of+// protection that conditions 3 and 4 still enforce.+//+// 3. No worktrees are left, checked after `git worktree prune` has dropped the+// entries whose task dirs the GC already removed. A live worktree's .git+// points into this directory, so removing it would break that checkout.+//+// 4. No task has created a worktree from it within GCRepoTTL. An unknown+// stamp is stamped and skipped, never treated as ancient — see+// repocache.LastUsed.+//+// Evicting wrongly costs time, not correctness: the next task that needs the+// repo takes the cache-miss path in ensureRepoReady, which re-syncs and+// re-clones on demand.+func (d *Daemon) evictRepoCacheLocked(barePath string, live map[string]struct{}, stats *gcStats) {+ if d.cfg.GCRepoTTL <= 0 {+ return+ }+ if _, attached := live[barePath]; attached {return}- d.pruneWorktreeLocked(barePath)+ worktrees, err := linkedWorktreeCount(barePath)+ if err != nil {+ d.logger.Warn("gc: worktree count failed", "repo", barePath, "error", err)+ return+ }+ if worktrees > 0 {+ return+ }++ lastUsed, ok := repocache.LastUsed(barePath)+ if !ok {+ // A cache created before the stamp existed. Start its clock now; the+ // alternative reading of "unknown" would evict every pre-upgrade cache+ // on the machine in the first cycle after an upgrade.+ repocache.MarkUsed(barePath, d.logger)+ return+ }+ idle := time.Since(lastUsed)+ if idle <= d.cfg.GCRepoTTL {+ return+ }++ bytes := dirSize(barePath)+ if err := os.RemoveAll(barePath); err != nil {+ d.logger.Warn("gc: repo cache remove failed", "repo", barePath, "error", err)+ return+ }+ stats.repoCachesReclaimed+++ stats.bytesReclaimed += bytes+ d.logger.Info("gc: repo cache evicted",+ "repo", filepath.Base(barePath),+ "workspace", filepath.Base(filepath.Dir(barePath)),+ "last_used", lastUsed.UTC().Format(time.RFC3339),+ "idle", idle.Round(time.Hour),+ "bytes_reclaimed", bytes,+ )+}++// linkedWorktreeCount returns how many linked worktrees a bare repo still has.+// `git worktree list --porcelain` emits one blank-line-separated block per+// worktree and marks the bare repo's own block with a `bare` line; only the+// linked blocks represent checkouts that would break if the repo went away.+func linkedWorktreeCount(barePath string) (int, error) {+ out, err := runGitGCCommand(barePath, "worktree", "list", "--porcelain")+ if err != nil {+ return 0, err+ }++ count := 0+ inBlock := false+ isBare := false+ flush := func() {+ if inBlock && !isBare {+ count+++ }+ inBlock = false+ isBare = false+ }+ for _, line := range strings.Split(out, "\n") {+ line = strings.TrimSpace(line)+ switch {+ case line == "":+ flush()+ case strings.HasPrefix(line, "worktree "):+ flush()+ inBlock = true+ case line == "bare":+ isBare = true+ }+ }+ flush()+ return count, nil}func (d *Daemon) pruneWorktreeLocked(barePath string) {diff --git a/server/internal/daemon/gc_repo_evict_test.go b/server/internal/daemon/gc_repo_evict_test.gonew file mode 100644index 0000000000..a9ee13085e--- /dev/null+++ b/server/internal/daemon/gc_repo_evict_test.go@@ -0,0 +1,224 @@+package daemon++import (+ "net/http"+ "os"+ "path/filepath"+ "testing"+ "time"+)++const testRepoURL = "https://example.com/acme/widgets.git"++// newEvictTestRepo clones a bare repo into the exact cache path the daemon+// would use for repoURL, so the live-set lookup (which is keyed on that path)+// lines up with what is on disk.+func newEvictTestRepo(t *testing.T, d *Daemon, workspaceID, repoURL string) string {+ t.Helper()+ source := createGCGitRepo(t)+ barePath := d.repoCache.BarePath(workspaceID, repoURL)+ if err := os.MkdirAll(filepath.Dir(barePath), 0o755); err != nil {+ t.Fatal(err)+ }+ runGitForGC(t, "", "clone", "--bare", source, barePath)+ return barePath+}++// writeLastUsed pins the on-disk stamp format that repocache.LastUsed reads.+func writeLastUsed(t *testing.T, barePath string, at time.Time) {+ t.Helper()+ path := filepath.Join(barePath, ".multica_last_used")+ if err := os.WriteFile(path, []byte(at.UTC().Format(time.RFC3339Nano)), 0o644); err != nil {+ t.Fatal(err)+ }+}++// attachRepo registers a workspace that claims repoURL, which is what makes the+// repo "live" and therefore ineligible for eviction.+func attachRepo(d *Daemon, workspaceID, repoURL string) {+ d.mu.Lock()+ defer d.mu.Unlock()+ d.workspaces[workspaceID] = &workspaceState{+ workspaceID: workspaceID,+ allowedRepoURLs: map[string]struct{}{repoURL: {}},+ }+}++func runRepoGC(d *Daemon) *gcStats {+ stats := &gcStats{byPattern: map[string]int{}}+ d.pruneRepoWorktrees(d.cfg.WorkspacesRoot, stats)+ return stats+}++// TestEvictRepoCache_RemovesIdleDetachedRepo is the happy path: a cache no+// workspace claims, with no worktrees, untouched past the TTL.+func TestEvictRepoCache_RemovesIdleDetachedRepo(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 24 * time.Hour++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)+ writeLastUsed(t, barePath, time.Now().Add(-48*time.Hour))++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); !os.IsNotExist(err) {+ t.Fatalf("expected bare repo to be evicted, stat err = %v", err)+ }+ if stats.repoCachesReclaimed != 1 {+ t.Errorf("repo_caches_reclaimed = %d, want 1", stats.repoCachesReclaimed)+ }+ if stats.bytesReclaimed <= 0 {+ t.Errorf("bytes_reclaimed = %d, want > 0", stats.bytesReclaimed)+ }+ // The per-workspace directory is now empty and should go with it.+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, reposDirName, wsID)+ if _, err := os.Stat(wsDir); !os.IsNotExist(err) {+ t.Errorf("expected empty workspace cache dir to be removed, stat err = %v", err)+ }+}++// TestEvictRepoCache_KeepsRepoStillAttachedToWorkspace is the load-bearing+// guard. Sync re-clones every listed repo that is missing whenever a workspace+// registers, which happens on every daemon start — so evicting a repo the+// workspace still claims would just pay a full re-clone on the next restart.+func TestEvictRepoCache_KeepsRepoStillAttachedToWorkspace(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 24 * time.Hour++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)+ writeLastUsed(t, barePath, time.Now().Add(-90*24*time.Hour))+ attachRepo(d, wsID, testRepoURL)++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); err != nil {+ t.Fatalf("attached repo must survive eviction however idle: %v", err)+ }+ if stats.repoCachesReclaimed != 0 {+ t.Errorf("repo_caches_reclaimed = %d, want 0", stats.repoCachesReclaimed)+ }+}++// TestEvictRepoCache_KeepsRepoWithLiveWorktree guards the checkout that would+// break: a linked worktree's .git points into this directory.+func TestEvictRepoCache_KeepsRepoWithLiveWorktree(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 24 * time.Hour++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)+ writeLastUsed(t, barePath, time.Now().Add(-90*24*time.Hour))++ worktree := filepath.Join(t.TempDir(), "checkout")+ runGitForGC(t, "", "-C", barePath, "worktree", "add", "-b", "agent/live/1234", worktree, "HEAD")++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); err != nil {+ t.Fatalf("repo with a live worktree must survive: %v", err)+ }+ if stats.repoCachesReclaimed != 0 {+ t.Errorf("repo_caches_reclaimed = %d, want 0", stats.repoCachesReclaimed)+ }+}++// TestEvictRepoCache_MissingStampIsBackfilledNotEvicted is the upgrade-safety+// case. Every cache that predates the stamp reports "unknown"; reading that as+// "infinitely old" would wipe every repo cache on the machine in the first+// cycle after an upgrade and force a full re-clone of each.+func TestEvictRepoCache_MissingStampIsBackfilledNotEvicted(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = time.Nanosecond // any real stamp would be past this++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); err != nil {+ t.Fatalf("a cache with no stamp must not be evicted on first sight: %v", err)+ }+ if stats.repoCachesReclaimed != 0 {+ t.Errorf("repo_caches_reclaimed = %d, want 0", stats.repoCachesReclaimed)+ }+ if _, err := os.Stat(filepath.Join(barePath, ".multica_last_used")); err != nil {+ t.Errorf("expected the missing stamp to be backfilled so the clock starts now: %v", err)+ }++ // Second cycle: the backfilled stamp is now older than the 1ns TTL, so the+ // repo becomes eligible — the grace period is one cycle, not permanent.+ time.Sleep(2 * time.Millisecond)+ if stats := runRepoGC(d); stats.repoCachesReclaimed != 1 {+ t.Errorf("second cycle repo_caches_reclaimed = %d, want 1", stats.repoCachesReclaimed)+ }+}++// TestEvictRepoCache_DisabledWhenTTLZero keeps the feature opt-out.+func TestEvictRepoCache_DisabledWhenTTLZero(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 0++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)+ writeLastUsed(t, barePath, time.Now().Add(-365*24*time.Hour))++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); err != nil {+ t.Fatalf("MULTICA_GC_REPO_TTL=0 must disable eviction entirely: %v", err)+ }+ if stats.repoCachesReclaimed != 0 {+ t.Errorf("repo_caches_reclaimed = %d, want 0", stats.repoCachesReclaimed)+ }+}++// TestEvictRepoCache_KeepsRecentlyUsedRepo covers the ordinary in-use case: a+// detached repo that a task checked out inside the TTL window.+func TestEvictRepoCache_KeepsRecentlyUsedRepo(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCRepoTTL = 24 * time.Hour++ wsID := "11111111-1111-1111-1111-111111111111"+ barePath := newEvictTestRepo(t, d, wsID, testRepoURL)+ writeLastUsed(t, barePath, time.Now().Add(-1*time.Hour))++ stats := runRepoGC(d)++ if _, err := os.Stat(barePath); err != nil {+ t.Fatalf("repo used within the TTL must survive: %v", err)+ }+ if stats.repoCachesReclaimed != 0 {+ t.Errorf("repo_caches_reclaimed = %d, want 0", stats.repoCachesReclaimed)+ }+}++// TestLinkedWorktreeCount checks the porcelain parsing directly: the bare+// repo's own block carries a `bare` marker and must not be counted, or every+// cache would look permanently in use.+func TestLinkedWorktreeCount(t *testing.T) {+ d := newGCTestDaemon(t, http.NewServeMux())+ barePath := newEvictTestRepo(t, d, "11111111-1111-1111-1111-111111111111", testRepoURL)++ count, err := linkedWorktreeCount(barePath)+ if err != nil {+ t.Fatalf("linkedWorktreeCount: %v", err)+ }+ if count != 0 {+ t.Fatalf("bare repo with no checkouts = %d, want 0 (its own block is marked bare)", count)+ }++ first := filepath.Join(t.TempDir(), "wt1")+ second := filepath.Join(t.TempDir(), "wt2")+ runGitForGC(t, "", "-C", barePath, "worktree", "add", "-b", "agent/a/1", first, "HEAD")+ runGitForGC(t, "", "-C", barePath, "worktree", "add", "-b", "agent/b/2", second, "HEAD")++ count, err = linkedWorktreeCount(barePath)+ if err != nil {+ t.Fatalf("linkedWorktreeCount: %v", err)+ }+ if count != 2 {+ t.Errorf("linked worktrees = %d, want 2", count)+ }+}diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex d594f8b3a0..785c9b34e2 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -1219,6 +1219,10 @@ func (c *blockingRepoCache) Lookup(workspaceID, url string) string {return c.inner.Lookup(workspaceID, url)}+func (c *blockingRepoCache) BarePath(workspaceID, url string) string {+ return c.inner.BarePath(workspaceID, url)+}+func (c *blockingRepoCache) Sync(workspaceID string, repos []repocache.RepoInfo) error {return c.inner.Sync(workspaceID, repos)}diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 5c5c31e6ed..49c3aa0906 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -350,6 +350,10 @@ func newBlockingLookupRepoCache(path string) *blockingLookupRepoCache {}}+func (c *blockingLookupRepoCache) BarePath(_, _ string) string {+ return ""+}+func (c *blockingLookupRepoCache) Lookup(_, _ string) string {select {case <-c.lookupSeen:@@ -382,6 +386,10 @@ func (c *recordingRepoCache) Lookup(_, _ string) string {return c.lookupPath}+func (c *recordingRepoCache) BarePath(_, _ string) string {+ return c.lookupPath+}+func (c *recordingRepoCache) Sync(string, []repocache.RepoInfo) error {return nil}diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 33e5278d9f..bf74cf5c26 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -208,13 +208,66 @@ func (c *Cache) Sync(workspaceID string, repos []RepoInfo) error {// Lookup returns the local bare clone path for a repo URL within a workspace.// Returns "" if not cached.func (c *Cache) Lookup(workspaceID, url string) string {- barePath := filepath.Join(c.root, workspaceID, bareDirName(url))+ barePath := c.BarePath(workspaceID, url)if isBareRepo(barePath) {return barePath}return ""}+// BarePath returns where a repo's bare cache lives, whether or not it exists+// yet. Lookup is the "is it cached?" question; this is the "where would it be?"+// question, which the GC needs to map a set of live repo URLs onto the+// directories it is about to consider evicting.+func (c *Cache) BarePath(workspaceID, url string) string {+ return filepath.Join(c.root, workspaceID, bareDirName(url))+}++// lastUsedFile records the last time a task asked for a worktree from this+// bare repo. It lives inside the bare repo so it is removed with it.+//+// Directory mtime cannot answer this question. Every daemon restart re-syncs+// each registered workspace's full repo list, and that path fetches every+// cached repo (see Sync), refreshing the mtime of repos no task has checked+// out in months. atime is worse: noatime is common on Linux and Windows+// disables it by default. So the signal has to be written explicitly, at the+// one place that means a repo was really used — CreateWorktree.+const lastUsedFile = ".multica_last_used"++// MarkUsed records that this bare repo was just used for a checkout. Callers+// must already hold the repo lock. Best-effort: a failed stamp only risks the+// repo looking idle later, and the GC's own missing-stamp grace period+// (see LastUsed) absorbs that.+func MarkUsed(barePath string, logger *slog.Logger) {+ if barePath == "" {+ return+ }+ stamp := time.Now().UTC().Format(time.RFC3339Nano)+ if err := os.WriteFile(filepath.Join(barePath, lastUsedFile), []byte(stamp), 0o644); err != nil && logger != nil {+ logger.Warn("repo cache: write last-used stamp failed", "repo", barePath, "error", err)+ }+}++// LastUsed reports when this bare repo was last used for a checkout, and+// whether a stamp existed at all.+//+// ok=false means "unknown", never "ancient". Every cache created before this+// stamp existed reports unknown, so treating it as infinitely old would make+// the first GC cycle after an upgrade wipe every repo cache on the machine and+// force a full re-clone of each. Callers must stamp an unknown repo and let it+// age from now.+func LastUsed(barePath string) (time.Time, bool) {+ data, err := os.ReadFile(filepath.Join(barePath, lastUsedFile))+ if err != nil {+ return time.Time{}, false+ }+ stamp, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(string(data)))+ if err != nil {+ return time.Time{}, false+ }+ return stamp, true+}+// WithRepoLock serializes caller-supplied mutations on a bare repo against all// other same-repo operations that use the cache's lock (Sync, Fetch,// CreateWorktree, and daemon GC maintenance).@@ -463,6 +516,12 @@ func (c *Cache) CreateWorktree(params WorktreeParams) (*WorktreeResult, error) {repoLock.Lock()defer repoLock.Unlock()+ // Stamp before doing the work, not after: a task asking for a worktree is+ // what "this cache is still wanted" means, whether or not the checkout+ // ultimately succeeds. Stamping only on success would let a repo whose+ // checkouts keep failing age out from under the tasks still trying to use it.+ MarkUsed(barePath, c.logger)+// Fetch latest from origin. This also migrates the bare cache's refspec// to the modern remote-tracking layout on first run, so subsequent fetches// never collide with the refs/heads/agent/* branches that worktree creationdiff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.goindex 0e6dc92b6a..cb4515c9fa 100644--- a/server/internal/daemon/repocache/cache_test.go+++ b/server/internal/daemon/repocache/cache_test.go@@ -9,6 +9,7 @@ import ("path/filepath""strings""testing"+ "time")func testLogger() *slog.Logger {@@ -1691,3 +1692,94 @@ func TestGetRemoteDefaultBranchAmbiguousOriginReturnsEmpty(t *testing.T) {t.Fatalf("getRemoteDefaultBranch = %q, want \"\" (ambiguous origin/* must not guess)", got)}}++// TestLastUsedMissingIsUnknownNotAncient pins the distinction the GC's+// upgrade safety depends on: a cache created before the stamp existed must+// report "unknown", never a zero time that reads as infinitely idle.+func TestLastUsedMissingIsUnknownNotAncient(t *testing.T) {+ t.Parallel()+ if _, ok := LastUsed(t.TempDir()); ok {+ t.Fatal("LastUsed on a repo with no stamp must report ok=false")+ }+}++// TestMarkUsedRoundTrip covers the stamp write/read pair on its own.+func TestMarkUsedRoundTrip(t *testing.T) {+ t.Parallel()+ barePath := t.TempDir()++ before := time.Now().Add(-time.Second)+ MarkUsed(barePath, testLogger())++ stamp, ok := LastUsed(barePath)+ if !ok {+ t.Fatal("expected a stamp after MarkUsed")+ }+ if stamp.Before(before) {+ t.Errorf("stamp %s is older than the call that wrote it (%s)", stamp, before)+ }+ if time.Since(stamp) > time.Hour {+ t.Errorf("stamp %s is implausibly old", stamp)+ }+}++// TestMarkUsedIgnoresUnwritableRepo keeps the stamp best-effort: a failure to+// record use must not break the checkout that triggered it.+func TestMarkUsedIgnoresUnwritableRepo(t *testing.T) {+ t.Parallel()+ MarkUsed(filepath.Join(t.TempDir(), "does-not-exist"), testLogger())+ MarkUsed("", testLogger())+}++// TestCreateWorktreeStampsLastUsed is the one that matters for eviction: the+// stamp has to be written where "a task really used this repo" happens, since+// directory mtime cannot distinguish that from a routine fetch.+func TestCreateWorktreeStampsLastUsed(t *testing.T) {+ t.Parallel()+ sourceRepo := createTestRepo(t)+ cacheRoot := t.TempDir()++ cache := New(cacheRoot, testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("sync failed: %v", err)+ }++ barePath := cache.Lookup("ws-1", sourceRepo)+ if barePath == "" {+ t.Fatal("expected cached repo")+ }+ // Sync alone must not look like use — only a checkout counts.+ if _, ok := LastUsed(barePath); ok {+ t.Fatal("Sync must not stamp last-used; only CreateWorktree does")+ }++ if _, err := cache.CreateWorktree(WorktreeParams{+ WorkspaceID: "ws-1",+ RepoURL: sourceRepo,+ WorkDir: t.TempDir(),+ AgentName: "Code Reviewer",+ TaskID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",+ }); err != nil {+ t.Fatalf("CreateWorktree failed: %v", err)+ }++ if _, ok := LastUsed(barePath); !ok {+ t.Error("CreateWorktree must stamp last-used on the bare repo")+ }+}++// TestBarePathIsIndependentOfExistence separates the two questions Lookup used+// to answer at once: Lookup means "is it cached?", BarePath means "where would+// it live?" — the GC needs the second to map live repo URLs onto directories.+func TestBarePathIsIndependentOfExistence(t *testing.T) {+ t.Parallel()+ cache := New(t.TempDir(), testLogger())++ path := cache.BarePath("ws-1", "https://example.com/acme/widgets.git")+ if path == "" {+ t.Fatal("BarePath must return a path even when nothing is cached")+ }+ if cache.Lookup("ws-1", "https://example.com/acme/widgets.git") != "" {+ t.Error("Lookup must still report an uncached repo as absent")+ }+}