Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(projects): project github_repo resources override workspace repos (#1929)
Bohan Jiang2129aa3dee4a
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdxindex c74db07e15..bff15d27bf 100644--- a/apps/docs/content/docs/project-resources.mdx+++ b/apps/docs/content/docs/project-resources.mdx@@ -124,11 +124,21 @@ There is **no schema migration**, no new sqlc query, no new endpoint, **and no CThe same `project_resource` table and the same three CRUD calls handle every type.+## Workspace repos vs. project repos++The repo list shown to the agent (`## Repositories` block in `CLAUDE.md` / `AGENTS.md`) is chosen by the daemon claim handler with this precedence:++- **Project has at least one `github_repo` resource** → only those repos are surfaced to the agent. Workspace-bound repos are intentionally hidden so the agent doesn't have to guess which one belongs to this issue.+- **Project has no `github_repo` resources (or the issue isn't in a project)** → fall back to the workspace's repo list as before.++This keeps the agent's working set tight: when a project is explicit about its repos, that's the authoritative answer. The structured resource list at `.multica/project/resources.json` always carries the full set, so a skill that wants to inspect everything still can.++The daemon mirrors this on the checkout side: when a task arrives with project-scoped `github_repo` URLs, those URLs are merged into the per-workspace allowlist *and* synced into the local repo cache before the agent spawns. So a project repo URL that isn't bound at the workspace level is still a valid argument to `multica repo checkout` — the daemon won't reject it as "not configured." The allowlist split is internal: workspace-bound URLs and task-scoped URLs are tracked separately, so a workspace-repos refresh doesn't accidentally revoke a project URL mid-run.+## What's intentionally **not** in scope here- **Cross-project sharing.** Each resource lives on exactly one project today.- **Per-skill resource scoping.** All resources are visible to every skill on the agent's run; type-aware filtering is a follow-up.- **Caching / sync.** `github_repo` is just metadata — checkout still happens via `multica repo checkout` on demand. Cached document text for Notion / Google Docs will arrive with those types.-- **Workspace defaults.** Workspace-level repos remain a separate, broader concept. When a project resource and a workspace repo overlap, the project resource takes priority for issues in that project (see *workflow notes* in the [issues](/issues) doc).These are deliberate omissions — the goal of the first cut is to validate the abstraction with the smallest set of moving parts.diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 12c2685565..37617d61b4 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -26,11 +26,18 @@ import (var ErrRepoNotConfigured = errors.New("repo is not configured for this workspace")// workspaceState tracks registered runtimes for a single workspace.+//+// allowedRepoURLs covers the workspace-level repo bindings; it gets rebuilt on+// every refresh from the server. taskRepoURLs covers repos that the server+// surfaced through a per-task claim (project github_repo resources today,+// possibly other typed sources later) — those don't show up in+// GetWorkspaceRepos, so they would be wiped on refresh if we shared one map.type workspaceState struct {workspaceID stringruntimeIDs []stringreposVersion string // stored for future use: skip refresh when version unchangedallowedRepoURLs map[string]struct{}+ taskRepoURLs map[string]struct{}settings json.RawMessage // workspace settings (JSONB)lastRepoSyncErr stringrepoRefreshMu sync.Mutex@@ -359,8 +366,13 @@ func (d *Daemon) workspaceRepoAllowed(workspaceID, repoURL string) bool {if !ok {return false}- _, allowed := ws.allowedRepoURLs[repoURL]- return allowed+ if _, allowed := ws.allowedRepoURLs[repoURL]; allowed {+ return true+ }+ if _, allowed := ws.taskRepoURLs[repoURL]; allowed {+ return true+ }+ return false}func (d *Daemon) workspaceLastRepoSyncErr(workspaceID string) string {@@ -392,6 +404,56 @@ func (d *Daemon) workspaceCoAuthoredByEnabled(workspaceID string) bool {return *s.CoAuthoredByEnabled}+// registerTaskRepos merges task-scoped repos (e.g. project github_repo+// resources lifted into resp.Repos by the claim handler) into the workspace's+// allowlist and kicks off a cache sync for any URLs that aren't yet cached.+//+// It's safe to call with the workspace's own repos — duplicates are+// idempotent. Called from runTask before the agent spawns so+// `multica repo checkout` accepts project-only URLs without an extra round+// trip back to GetWorkspaceRepos (which doesn't carry project resources).+func (d *Daemon) registerTaskRepos(workspaceID string, repos []RepoData) {+ if len(repos) == 0 {+ return+ }++ d.mu.Lock()+ ws, ok := d.workspaces[workspaceID]+ if !ok {+ d.mu.Unlock()+ return+ }+ if ws.taskRepoURLs == nil {+ ws.taskRepoURLs = make(map[string]struct{}, len(repos))+ }+ toSync := make([]RepoData, 0, len(repos))+ for _, repo := range repos {+ url := strings.TrimSpace(repo.URL)+ if url == "" {+ continue+ }+ // Don't re-sync if the URL is already tracked (workspace or task-scoped)+ // AND the cache already has it.+ _, inWorkspace := ws.allowedRepoURLs[url]+ _, inTask := ws.taskRepoURLs[url]+ if (inWorkspace || inTask) && d.repoCache != nil && d.repoCache.Lookup(workspaceID, url) != "" {+ ws.taskRepoURLs[url] = struct{}{}+ continue+ }+ ws.taskRepoURLs[url] = struct{}{}+ toSync = append(toSync, RepoData{URL: url, Description: repo.Description})+ }+ d.mu.Unlock()++ if d.repoCache != nil && len(toSync) > 0 {+ // Sync in the background — same shape used at workspace registration.+ // `ensureRepoReady` reports a meaningful error if the cache isn't ready+ // yet, so the agent's first checkout will surface a sync failure+ // without silently treating it as a config bug.+ go d.syncWorkspaceRepos(workspaceID, toSync)+ }+}+func (d *Daemon) syncWorkspaceRepos(workspaceID string, repos []RepoData) {if d.repoCache == nil {return@@ -1141,6 +1203,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireturn TaskResult{}, fmt.Errorf("refusing to spawn agent: task has no workspace_id (task_id=%s)", task.ID)}+ // task.Repos is the authoritative repo list for this task — when the+ // claimed task belongs to a project with github_repo resources the server+ // has already narrowed it to project repos only. Make sure those URLs are+ // in the per-workspace allowlist and the local cache, otherwise+ // `multica repo checkout` would reject project-only URLs that aren't also+ // bound at the workspace level.+ d.registerTaskRepos(task.WorkspaceID, task.Repos)+entry, ok := d.cfg.Agents[provider]if !ok {return TaskResult{}, fmt.Errorf("no agent configured for provider %q", provider)diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 0e3840f2e7..0e49a0340d 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -654,6 +654,89 @@ func TestEnsureRepoReadyRefreshesOnMiss(t *testing.T) {}}+// A project github_repo URL that the workspace itself does not bind must still+// be allowed for `multica repo checkout` after registerTaskRepos runs. Without+// this, the new project-repos-override-workspace-repos behavior would surface+// repos in the meta-skill that the agent then can't actually clone.+func TestRegisterTaskReposAllowsProjectOnlyURL(t *testing.T) {+ t.Parallel()++ sourceRepo := createDaemonTestRepo(t)+ var refreshCalls atomic.Int32+ d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ refreshCalls.Add(1)+ // If the workspace endpoint is hit it returns an empty list — the+ // project-only URL must NOT depend on this for allowlist membership.+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: "ws-1",+ Repos: []RepoData{},+ ReposVersion: "v1",+ })+ })+ // Workspace has zero workspace-bound repos; the project resource gives us+ // the only repo URL the agent should be able to check out.+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)++ d.registerTaskRepos("ws-1", []RepoData{{URL: sourceRepo, Description: "project repo"}})++ // The async clone goroutine in registerTaskRepos may not have finished;+ // poll briefly until the cache is populated so the test isn't racy.+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ if d.repoCache.Lookup("ws-1", sourceRepo) != "" {+ break+ }+ time.Sleep(20 * time.Millisecond)+ }+ if d.repoCache.Lookup("ws-1", sourceRepo) == "" {+ t.Fatalf("expected repo to be cached after registerTaskRepos, but Lookup returned empty")+ }++ if !d.workspaceRepoAllowed("ws-1", sourceRepo) {+ t.Fatal("expected project repo to pass workspaceRepoAllowed")+ }++ if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {+ t.Fatalf("ensureRepoReady: %v", err)+ }+ if got := refreshCalls.Load(); got != 0 {+ t.Fatalf("expected zero workspace-repos refreshes (URL came from project), got %d", got)+ }+}++// Confirms that a workspace refresh wiping allowedRepoURLs does not also wipe+// task-scoped URLs (project repos). Without the separate taskRepoURLs map a+// concurrent refresh would silently revoke project-only URLs and the next+// checkout would fail.+func TestRegisterTaskReposSurvivesWorkspaceRefresh(t *testing.T) {+ t.Parallel()++ sourceRepo := createDaemonTestRepo(t)+ d := newRepoReadyTestDaemon(t, func(w http.ResponseWriter, r *http.Request) {+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: "ws-1",+ Repos: []RepoData{},+ ReposVersion: "v2",+ })+ })+ d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)+ d.registerTaskRepos("ws-1", []RepoData{{URL: sourceRepo}})++ // Wait for the registration to populate the cache.+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) && d.repoCache.Lookup("ws-1", sourceRepo) == "" {+ time.Sleep(20 * time.Millisecond)+ }++ if _, err := d.refreshWorkspaceRepos(context.Background(), "ws-1"); err != nil {+ t.Fatalf("refreshWorkspaceRepos: %v", err)+ }++ if !d.workspaceRepoAllowed("ws-1", sourceRepo) {+ t.Fatal("project repo URL was wiped by workspace refresh")+ }+}+func TestEnsureRepoReadyReturnsNotConfigured(t *testing.T) {t.Parallel()diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 3cefdb8ca2..7e2d90bf81 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -201,6 +201,48 @@ func TestPrepareWithProjectResources(t *testing.T) {}}+// When the issue's project has its own github_repo resources, those should be+// the only repos rendered in the meta-skill — workspace-level repos must not+// leak into the agent prompt to avoid confusing it about which repo to use.+//+// The handler-side override is exercised in handler tests; this test confirms+// the rendering side: given a TaskContextForEnv where Repos was already+// narrowed by the server to project repos only, the meta skill renders just+// those.+func TestProjectReposReplaceWorkspaceReposInMetaSkill(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ ctx := TaskContextForEnv{+ IssueID: "11111111-2222-3333-4444-555555555555",+ ProjectID: "22222222-3333-4444-5555-666666666666",+ ProjectTitle: "Project A",+ Repos: []RepoContextForEnv{+ {URL: "https://github.com/org/project-repo", Description: ""},+ },+ ProjectResources: []ProjectResourceForEnv{+ {+ ID: "33333333-4444-5555-6666-777777777777",+ ResourceType: "github_repo",+ ResourceRef: []byte(`{"url":"https://github.com/org/project-repo"}`),+ },+ },+ }+ if err := InjectRuntimeConfig(dir, "claude", ctx); err != nil {+ t.Fatalf("InjectRuntimeConfig: %v", err)+ }+ content, err := os.ReadFile(filepath.Join(dir, "CLAUDE.md"))+ if err != nil {+ t.Fatalf("read CLAUDE.md: %v", err)+ }+ s := string(content)+ if !strings.Contains(s, "https://github.com/org/project-repo") {+ t.Errorf("CLAUDE.md missing project repo URL")+ }+ if strings.Contains(s, "https://github.com/org/workspace-repo") {+ t.Errorf("CLAUDE.md should not contain workspace repo when project has its own")+ }+}+func TestWriteProjectResourcesSkippedWhenNone(t *testing.T) {t.Parallel()dir := t.TempDir()diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 8b6424965c..679daf5610 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -873,18 +873,17 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {}// Include workspace ID and repos so the daemon can set up worktrees.+ //+ // Repo precedence: project-bound github_repo resources override workspace+ // repos when present. Mixing both would just confuse the agent — if a+ // project explicitly attached its repos, those are the authoritative set+ // for issues inside that project. When the project has no github_repo+ // resources (or no project at all), we fall back to the workspace repos.if task.IssueID.Valid {if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {resp.WorkspaceID = uuidToString(issue.WorkspaceID)- if ws, err := h.Queries.GetWorkspace(r.Context(), issue.WorkspaceID); err == nil && ws.Repos != nil {- var repos []RepoData- if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {- resp.Repos = repos- }- }- // Attach project context (id, title, resources) when the issue- // belongs to a project. Resource fetch failures degrade gracefully- // — the agent simply runs without project context, never blocked.++ var projectRepos []RepoDataif issue.ProjectID.Valid {resp.ProjectID = uuidToString(issue.ProjectID)if proj, err := h.Queries.GetProject(r.Context(), issue.ProjectID); err == nil {@@ -907,10 +906,34 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {ResourceRef: ref,Label: label,})+ // Lift github_repo resources into the daemon's repo list+ // so `multica repo checkout` and the meta-skill render+ // them as the issue's repos.+ if row.ResourceType == "github_repo" {+ var payload struct {+ URL string `json:"url"`+ }+ if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {+ desc := ""+ if row.Label.Valid {+ desc = row.Label.String+ }+ projectRepos = append(projectRepos, RepoData{URL: payload.URL, Description: desc})+ }+ }}resp.ProjectResources = out}}++ if len(projectRepos) > 0 {+ resp.Repos = projectRepos+ } else if ws, err := h.Queries.GetWorkspace(r.Context(), issue.WorkspaceID); err == nil && ws.Repos != nil {+ var repos []RepoData+ if json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {+ resp.Repos = repos+ }+ }}// Fetch the triggering comment content so the daemon can embed itdiff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 511de4a93a..1d62e1d11c 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -1262,6 +1262,185 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {}}+// ClaimTaskByRuntime must surface the issue's project github_repo resources+// as resp.Repos and hide the workspace-bound repos. Without this the agent+// would see two repo lists in the meta-skill and have no signal about which+// belongs to the current issue.+func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()++ // Workspace repos: two of them, neither matches the project repo URL.+ setHandlerTestWorkspaceRepos(t, []map[string]string{+ {"url": "https://github.com/example/workspace-repo-a", "description": "ws a"},+ {"url": "https://github.com/example/workspace-repo-b", "description": "ws b"},+ })++ // Project + project_resource(github_repo) with a URL that is NOT in the+ // workspace's repos list.+ var projectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id+ `, testWorkspaceID, "Claim project repo override").Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })++ const projectRepoURL = "https://github.com/example/project-only-repo"+ if _, err := testPool.Exec(ctx, `+ INSERT INTO project_resource (+ project_id, workspace_id, resource_type, resource_ref, position+ ) VALUES ($1, $2, 'github_repo', $3::jsonb, 0)+ `, projectID, testWorkspaceID, `{"url":"`+projectRepoURL+`"}`); err != nil {+ t.Fatalf("create project_resource: %v", err)+ }++ // Agent + runtime + queued task in this project.+ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("get agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position+ ) VALUES ($1, $2, 'project repo override', 'todo', 'medium', $3, 'member', 88001, 0)+ RETURNING id+ `, testWorkspaceID, projectID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority+ ) VALUES ($1, $2, $3, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {+ t.Fatalf("create task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-project-repos")+ req = withURLParam(req, "runtimeId", runtimeID)+ testHandler.ClaimTaskByRuntime(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime: %d %s", w.Code, w.Body.String())+ }++ var resp struct {+ Task *struct {+ Repos []RepoData `json:"repos"`+ ProjectID string `json:"project_id"`+ ProjectResources []ProjectResourceData `json:"project_resources"`+ } `json:"task"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.Task == nil {+ t.Fatal("expected task in response")+ }+ if resp.Task.ProjectID != projectID {+ t.Errorf("project_id = %q, want %q", resp.Task.ProjectID, projectID)+ }+ if len(resp.Task.Repos) != 1 || resp.Task.Repos[0].URL != projectRepoURL {+ t.Fatalf("expected resp.Repos to contain only the project repo URL, got %+v", resp.Task.Repos)+ }+ for _, r := range resp.Task.Repos {+ if strings.HasSuffix(r.URL, "workspace-repo-a") || strings.HasSuffix(r.URL, "workspace-repo-b") {+ t.Errorf("workspace repo %q leaked into resp.Repos despite project override", r.URL)+ }+ }+ if len(resp.Task.ProjectResources) != 1 {+ t.Errorf("expected 1 project_resources entry, got %d", len(resp.Task.ProjectResources))+ }+}++// When the issue's project has no github_repo resources, the claim handler+// must fall back to workspace repos (the pre-override behavior).+func TestClaimTask_ProjectWithoutRepos_FallsBackToWorkspaceRepos(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()++ setHandlerTestWorkspaceRepos(t, []map[string]string{+ {"url": "https://github.com/example/workspace-fallback", "description": "ws"},+ })++ var projectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id+ `, testWorkspaceID, "Claim project without repos").Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 LIMIT 1`,+ testWorkspaceID,+ ).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("get agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, project_id, title, status, priority, creator_id, creator_type, number, position+ ) VALUES ($1, $2, 'no project repos', 'todo', 'medium', $3, 'member', 88002, 0)+ RETURNING id+ `, testWorkspaceID, projectID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority+ ) VALUES ($1, $2, $3, 'queued', 0)+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {+ t.Fatalf("create task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-fallback")+ req = withURLParam(req, "runtimeId", runtimeID)+ testHandler.ClaimTaskByRuntime(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ClaimTaskByRuntime: %d %s", w.Code, w.Body.String())+ }++ var resp struct {+ Task *struct {+ Repos []RepoData `json:"repos"`+ } `json:"task"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp.Task == nil {+ t.Fatal("expected task in response")+ }+ if len(resp.Task.Repos) != 1 || !strings.HasSuffix(resp.Task.Repos[0].URL, "workspace-fallback") {+ t.Fatalf("expected workspace fallback repo, got %+v", resp.Task.Repos)+ }+}+// Regression test for #1276: ClaimTaskByRuntime must populate workspace_id in// the response for run_only autopilot tasks. Before the fix, resp.WorkspaceID// stayed empty because ClaimTaskByRuntime only handled IssueID and