Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(projects): honor repo resource checkout refs (MUL-3593) (#4470)
beast20eecfb093f9
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdxindex 3eb7f61eb0..db86434a26 100644--- a/apps/docs/content/docs/project-resources.mdx+++ b/apps/docs/content/docs/project-resources.mdx@@ -28,12 +28,15 @@ The default resource type — checked out per task into an isolated worktree:"resource_type": "github_repo","resource_ref": {"url": "https://github.com/owner/repo",+ "ref": "release/v2","default_branch_hint": "main"}}```-`default_branch_hint` is optional — if present, the daemon surfaces it in the meta-skill so the agent knows which branch to base its work on.+`ref` is optional — if present, `multica repo checkout <url>` uses it as the default branch, tag, or commit for tasks in this project. An explicit `multica repo checkout <url> --ref <other-ref>` still wins for that one checkout.++`default_branch_hint` is optional prompt context. It is not used for checkout; use `ref` when the project should pin a branch, tag, or SHA.## Resource type: `local_directory`@@ -168,6 +171,7 @@ multica project create \# Manage resources latermultica project resource list <project-id>multica project resource add <project-id> --type github_repo --url <url>+multica project resource add <project-id> --type github_repo --url <url> --ref <branch-or-sha>multica project resource remove <project-id> <resource-id># Generic escape hatch for any resource_type the server understands —@@ -251,7 +255,7 @@ The repo list shown to the agent (`## Repositories` block in `CLAUDE.md` / `AGENThis 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.+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." If the project resource includes `ref`, that ref becomes the default for `multica repo checkout <url>` during that task; passing `--ref` to the checkout command overrides it. 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 herediff --git a/packages/core/types/project.ts b/packages/core/types/project.tsindex 6855f8e891..333d094826 100644--- a/packages/core/types/project.ts+++ b/packages/core/types/project.ts@@ -52,13 +52,14 @@ export interface ListProjectsResponse {// validateAndNormalizeResourceRef on the server and a renderer in the UI.//// Known types (UI must default-case unknown server-side additions):-// - github_repo: cloud-side git checkout, ref = { url, default_branch_hint? }+// - github_repo: cloud-side git checkout, ref = { url, ref?, default_branch_hint? }// - local_directory: in-place agent execution on a specific daemon,// ref = { local_path, daemon_id, label? }export type ProjectResourceType = "github_repo" | "local_directory";export interface GithubRepoResourceRef {url: string;+ ref?: string;default_branch_hint?: string;}diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsxindex 7e0074a6c7..a255db55bc 100644--- a/packages/views/projects/components/project-resources-section.tsx+++ b/packages/views/projects/components/project-resources-section.tsx@@ -408,6 +408,8 @@ function ResourceRow({const { t } = useT("projects");if (isGithubRef(resource)) {const ref = resource.resource_ref;+ const display = resource.label || (ref.ref ? `${ref.url} @ ${ref.ref}` : ref.url);+ const tooltip = ref.ref ? `${ref.url}\nref: ${ref.ref}` : ref.url;return (<div className="flex items-center gap-2 text-xs group"><FolderGit className="size-3.5 text-muted-foreground shrink-0" />@@ -420,11 +422,11 @@ function ResourceRow({rel="noopener noreferrer"className="truncate flex-1 hover:underline">- {resource.label || ref.url}+ {display}</a>}/>- <TooltipContent side="top">{ref.url}</TooltipContent>+ <TooltipContent side="top" className="whitespace-pre-line">{tooltip}</TooltipContent></Tooltip><buttontype="button"diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.goindex 5cfbc43bdb..a45d0c66ef 100644--- a/server/cmd/multica/cmd_project.go+++ b/server/cmd/multica/cmd_project.go@@ -142,16 +142,17 @@ func init() {projectResourceListCmd.Flags().String("output", "table", "Output format: table or json")projectResourceListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")- // project resource add — generic shape: any --type with a JSON --ref payload- // works without further CLI changes. github_repo is supported via the- // dedicated --url / --default-branch-hint shortcuts as a convenience.+ // project resource add — generic shape: any --type with a JSON --ref+ // payload works without further CLI changes. github_repo is supported via+ // dedicated shortcuts; for that type, a non-JSON --ref value is treated as+ // the default checkout ref.projectResourceAddCmd.Flags().String("type", "github_repo", "Resource type (e.g. github_repo, local_directory — see docs)")projectResourceAddCmd.Flags().String("url", "", "Shortcut: the repo URL (only used when --type github_repo)")projectResourceAddCmd.Flags().String("default-branch-hint", "", "Shortcut: optional default branch hint (only used when --type github_repo)")projectResourceAddCmd.Flags().String("local-path", "", "Shortcut: absolute path to the working directory (only used when --type local_directory)")projectResourceAddCmd.Flags().String("daemon-id", "", "Shortcut: id of the daemon that owns the local path (only used when --type local_directory)")projectResourceAddCmd.Flags().String("ref-label", "", "Shortcut: optional label embedded in resource_ref (only used when --type local_directory)")- projectResourceAddCmd.Flags().String("ref", "", "Generic JSON resource_ref payload — overrides the per-type shortcuts when set")+ projectResourceAddCmd.Flags().String("ref", "", "Generic JSON resource_ref payload, or a github_repo checkout ref when used with --url")projectResourceAddCmd.Flags().String("label", "", "Optional human-readable label")projectResourceAddCmd.Flags().String("output", "json", "Output format: table or json")@@ -162,7 +163,7 @@ func init() {projectResourceUpdateCmd.Flags().String("local-path", "", "Shortcut: new absolute local path (local_directory)")projectResourceUpdateCmd.Flags().String("daemon-id", "", "Shortcut: new daemon id (local_directory)")projectResourceUpdateCmd.Flags().String("ref-label", "", "Shortcut: new label embedded in resource_ref (local_directory)")- projectResourceUpdateCmd.Flags().String("ref", "", "Generic JSON resource_ref payload — overrides per-type shortcuts when set")+ projectResourceUpdateCmd.Flags().String("ref", "", "Generic JSON resource_ref payload, or a github_repo checkout ref")projectResourceUpdateCmd.Flags().String("label", "", "New human-readable label; pass an empty string to clear")projectResourceUpdateCmd.Flags().Bool("clear-label", false, "Clear the human-readable label")projectResourceUpdateCmd.Flags().Int32("position", 0, "New display position")@@ -556,26 +557,22 @@ func runProjectResourceAdd(cmd *cobra.Command, args []string) error {body := map[string]any{"resource_type": resourceType}- // --ref takes precedence: any new resource type works through this path- // without a CLI change. Per-type shortcuts (--url etc.) only apply when- // --ref is empty.- if rawRef, _ := cmd.Flags().GetString("ref"); strings.TrimSpace(rawRef) != "" {- var ref any- if err := json.Unmarshal([]byte(rawRef), &ref); err != nil {- return fmt.Errorf("--ref is not valid JSON: %w", err)- }+ // --ref takes precedence when it is JSON: any new resource type works+ // through that path without a CLI change. For github_repo only, a non-JSON+ // --ref is a checkout ref shortcut and merges with --url.+ if ref, ok, err := buildResourceRefFromRefFlag(cmd, resourceType, nil); err != nil {+ return err+ } else if ok {body["resource_ref"] = ref} else {switch resourceType {case "github_repo":- urlVal, _ := cmd.Flags().GetString("url")- urlVal = strings.TrimSpace(urlVal)- if urlVal == "" {- return fmt.Errorf("github_repo requires --url (or pass a JSON payload via --ref)")+ ref, has, err := buildResourceRefFromFlags(cmd, resourceType, nil)+ if err != nil {+ return err}- ref := map[string]any{"url": urlVal}- if hint, _ := cmd.Flags().GetString("default-branch-hint"); hint != "" {- ref["default_branch_hint"] = strings.TrimSpace(hint)+ if !has {+ return fmt.Errorf("github_repo requires --url (or pass a JSON payload via --ref)")}body["resource_ref"] = refcase "local_directory":@@ -679,11 +676,9 @@ func runProjectResourceUpdate(cmd *cobra.Command, args []string) error {body := map[string]any{}- if rawRef, _ := cmd.Flags().GetString("ref"); strings.TrimSpace(rawRef) != "" {- var ref any- if err := json.Unmarshal([]byte(rawRef), &ref); err != nil {- return fmt.Errorf("--ref is not valid JSON: %w", err)- }+ if ref, ok, err := buildResourceRefFromRefFlag(cmd, resourceType, existingRef); err != nil {+ return err+ } else if ok {body["resource_ref"] = ref} else {ref, has, err := buildResourceRefFromFlags(cmd, resourceType, existingRef)@@ -732,6 +727,41 @@ func runProjectResourceUpdate(cmd *cobra.Command, args []string) error {return cli.PrintJSON(os.Stdout, result)}+func buildResourceRefFromRefFlag(cmd *cobra.Command, resourceType string, existingRef map[string]any) (any, bool, error) {+ if !cmd.Flags().Changed("ref") {+ return nil, false, nil+ }+ rawRef, _ := cmd.Flags().GetString("ref")+ rawRef = strings.TrimSpace(rawRef)+ // --ref is the generic JSON resource_ref escape hatch. For github_repo it+ // does double duty: a JSON object/array ("{...}" / "[...]") is still the+ // escape hatch, but any other value — including bare scalars like a numeric+ // tag ("2024") or an all-digit short SHA ("1234567") — is a checkout-ref+ // shortcut that merges with --url. Only parse JSON when the value is+ // actually meant as JSON; otherwise json.Unmarshal would accept "2024" as a+ // number and silently swallow a legitimate checkout ref.+ if rawRef != "" && (resourceType != "github_repo" || looksLikeJSONPayload(rawRef)) {+ var ref any+ if err := json.Unmarshal([]byte(rawRef), &ref); err != nil {+ return nil, false, fmt.Errorf("--ref is not valid JSON: %w", err)+ }+ return ref, true, nil+ }+ if resourceType != "github_repo" {+ return nil, false, fmt.Errorf("--ref must be a JSON resource_ref payload for resource type %q", resourceType)+ }+ ref, has, err := buildResourceRefFromFlags(cmd, resourceType, existingRef)+ if err != nil {+ return nil, false, err+ }+ return ref, has, nil+}++func looksLikeJSONPayload(raw string) bool {+ raw = strings.TrimSpace(raw)+ return strings.HasPrefix(raw, "{") || strings.HasPrefix(raw, "[")+}+// buildResourceRefFromFlags collects the per-type shortcut flags into a// resource_ref payload, seeding from existingRef so partial edits (only// --default-branch-hint, only --ref-label) preserve the unmentioned fields.@@ -745,7 +775,8 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existingcase "github_repo":urlSet := cmd.Flags().Changed("url")hintSet := cmd.Flags().Changed("default-branch-hint")- if !urlSet && !hintSet {+ refSet := cmd.Flags().Changed("ref")+ if !urlSet && !hintSet && !refSet {return nil, false, nil}ref := map[string]any{}@@ -758,6 +789,9 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existingif h, ok := existingRef["default_branch_hint"].(string); ok && strings.TrimSpace(h) != "" {ref["default_branch_hint"] = strings.TrimSpace(h)}+ if checkoutRef, ok := existingRef["ref"].(string); ok && strings.TrimSpace(checkoutRef) != "" {+ ref["ref"] = strings.TrimSpace(checkoutRef)+ }}if urlSet {urlVal, _ := cmd.Flags().GetString("url")@@ -775,6 +809,14 @@ func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existingref["default_branch_hint"] = hint}}+ if refSet {+ checkoutRef := strings.TrimSpace(mustString(cmd, "ref"))+ if checkoutRef == "" {+ delete(ref, "ref")+ } else {+ ref["ref"] = checkoutRef+ }+ }if _, ok := ref["url"]; !ok {return nil, false, fmt.Errorf("github_repo: --url is required (no existing url to merge with)")}@@ -878,6 +920,9 @@ func summarizeResourceRef(raw any) string {return ""}if u, ok := m["url"].(string); ok && u != "" {+ if ref, ok := m["ref"].(string); ok && strings.TrimSpace(ref) != "" {+ return u + " @ " + strings.TrimSpace(ref)+ }return u}if p, ok := m["local_path"].(string); ok && p != "" {diff --git a/server/cmd/multica/cmd_project_test.go b/server/cmd/multica/cmd_project_test.goindex 8ae73f9dc3..6b925c97b9 100644--- a/server/cmd/multica/cmd_project_test.go+++ b/server/cmd/multica/cmd_project_test.go@@ -113,6 +113,53 @@ func TestBuildResourceRefFromFlagsGithubMergesHint(t *testing.T) {}})+ t.Run("checkout ref edit preserves existing url and hint", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("ref", "release/v2")+ existing := map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "default_branch_hint": "main",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if ref["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("expected merged url, got %v", ref["url"])+ }+ if ref["default_branch_hint"] != "main" {+ t.Errorf("expected merged hint to persist, got %v", ref["default_branch_hint"])+ }+ if ref["ref"] != "release/v2" {+ t.Errorf("expected checkout ref release/v2, got %v", ref["ref"])+ }+ })++ t.Run("empty checkout ref clears existing ref", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("ref", "")+ existing := map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": "stale",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if _, ok := ref["ref"]; ok {+ t.Errorf("expected checkout ref to be cleared, got %v", ref["ref"])+ }+ if ref["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("expected merged url, got %v", ref["url"])+ }+ })+t.Run("hint-only with no existing url fails fast", func(t *testing.T) {cmd := newProjectResourceUpdateTestCmd()_ = cmd.Flags().Set("default-branch-hint", "main")@@ -134,6 +181,92 @@ func TestBuildResourceRefFromFlagsGithubMergesHint(t *testing.T) {})}+func TestBuildResourceRefFromRefFlagKeepsJSONEscapeHatch(t *testing.T) {+ t.Run("json payload wins over github shortcuts", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("url", "https://github.com/multica-ai/ignored")+ _ = cmd.Flags().Set("ref", `{"url":"https://github.com/multica-ai/multica","ref":"release/v2"}`)++ ref, has, err := buildResourceRefFromRefFlag(cmd, "github_repo", nil)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ payload, ok := ref.(map[string]any)+ if !ok {+ t.Fatalf("expected JSON object payload, got %T", ref)+ }+ if payload["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("json payload url = %v", payload["url"])+ }+ if payload["ref"] != "release/v2" {+ t.Errorf("json payload ref = %v", payload["ref"])+ }+ })++ t.Run("broken json is still rejected", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("url", "https://github.com/multica-ai/multica")+ _ = cmd.Flags().Set("ref", `{"url":`)++ _, _, err := buildResourceRefFromRefFlag(cmd, "github_repo", nil)+ if err == nil {+ t.Fatalf("expected invalid JSON error")+ }+ if !strings.Contains(err.Error(), "not valid JSON") {+ t.Fatalf("error = %q, want JSON guidance", err)+ }+ })++ // A github_repo checkout ref that happens to be valid JSON as a bare scalar+ // (a numeric tag, an all-digit short SHA, true/false/null) must be treated+ // as a checkout ref, not silently parsed into the JSON escape hatch. Only+ // "{...}" / "[...]" shaped values are the escape hatch.+ t.Run("bare scalar github ref is a checkout ref, not JSON", func(t *testing.T) {+ for _, gitRef := range []string{"2024", "1234567", "true", "null"} {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("url", "https://github.com/multica-ai/multica")+ _ = cmd.Flags().Set("ref", gitRef)++ ref, has, err := buildResourceRefFromRefFlag(cmd, "github_repo", nil)+ if err != nil {+ t.Fatalf("ref %q: unexpected error: %v", gitRef, err)+ }+ if !has {+ t.Fatalf("ref %q: expected has=true", gitRef)+ }+ payload, ok := ref.(map[string]any)+ if !ok {+ t.Fatalf("ref %q: expected github_repo shortcut map, got %T", gitRef, ref)+ }+ if payload["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("ref %q: url = %v", gitRef, payload["url"])+ }+ if payload["ref"] != gitRef {+ t.Errorf("ref %q: checkout ref = %v, want %q", gitRef, payload["ref"], gitRef)+ }+ }+ })++ // The checkout-ref shortcut only applies to github_repo: every other+ // resource type must still reject a non-JSON --ref so the generic escape+ // hatch stays typed.+ t.Run("non-json ref rejected for non-github type", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("ref", "develop")++ _, _, err := buildResourceRefFromRefFlag(cmd, "local_directory", nil)+ if err == nil {+ t.Fatalf("expected error for non-JSON --ref on local_directory")+ }+ if !strings.Contains(err.Error(), "not valid JSON") {+ t.Fatalf("error = %q, want JSON guidance", err)+ }+ })+}+// TestBuildResourceRefFromFlagsLocalDirectoryMerges covers the same merge// behavior for local_directory: partial edits keep unmentioned fields from the// existing ref.diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 157c4b99ef..a66b62053c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -119,13 +119,17 @@ var (// 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.+// taskRepoRefs tracks optional checkout refs for the specific task that+// surfaced each project repo so two projects using the same URL don't leak refs+// into each other.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)+ taskRepoRefs map[string]map[string]string // taskID -> repo URL -> checkout ref+ settings json.RawMessage // workspace settings (JSONB)lastRepoSyncErr stringrepoRefreshMu sync.Mutex// profileSetSig is a content hash of the workspace's custom runtime@@ -1236,7 +1240,7 @@ func (d *Daemon) workspaceCoAuthoredByEnabled(workspaceID string) bool {// 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) {+func (d *Daemon) registerTaskRepos(workspaceID, taskID string, repos []RepoData) {if len(repos) == 0 {return}@@ -1255,6 +1259,9 @@ func (d *Daemon) registerTaskRepos(workspaceID string, repos []RepoData) {if ws.taskRepoURLs == nil {ws.taskRepoURLs = make(map[string]struct{}, len(repos))}+ if taskID != "" && ws.taskRepoRefs == nil {+ ws.taskRepoRefs = make(map[string]map[string]string)+ }candidates := make([]repoCandidate, 0, len(repos))for _, repo := range repos {url := strings.TrimSpace(repo.URL)@@ -1266,6 +1273,14 @@ func (d *Daemon) registerTaskRepos(workspaceID string, repos []RepoData) {_, inWorkspace := ws.allowedRepoURLs[url]_, inTask := ws.taskRepoURLs[url]ws.taskRepoURLs[url] = struct{}{}+ if taskID != "" {+ if ws.taskRepoRefs[taskID] == nil {+ ws.taskRepoRefs[taskID] = make(map[string]string, len(repos))+ }+ if _, exists := ws.taskRepoRefs[taskID][url]; !exists {+ ws.taskRepoRefs[taskID][url] = strings.TrimSpace(repo.Ref)+ }+ }candidates = append(candidates, repoCandidate{url: url,tracked: inWorkspace || inTask,@@ -1294,6 +1309,33 @@ func (d *Daemon) registerTaskRepos(workspaceID string, repos []RepoData) {}}+func (d *Daemon) taskRepoDefaultRef(workspaceID, taskID, repoURL string) string {+ taskID = strings.TrimSpace(taskID)+ repoURL = strings.TrimSpace(repoURL)+ if taskID == "" || repoURL == "" {+ return ""+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ ws, ok := d.workspaces[workspaceID]+ if !ok || ws.taskRepoRefs == nil {+ return ""+ }+ return strings.TrimSpace(ws.taskRepoRefs[taskID][repoURL])+}++func (d *Daemon) clearTaskRepoRefs(workspaceID, taskID string) {+ taskID = strings.TrimSpace(taskID)+ if taskID == "" {+ return+ }+ d.mu.Lock()+ defer d.mu.Unlock()+ if ws, ok := d.workspaces[workspaceID]; ok && ws.taskRepoRefs != nil {+ delete(ws.taskRepoRefs, taskID)+ }+}+// waitBackgroundSyncs blocks until every background sync started by// registerTaskRepos has finished. Intended for test teardown: tests that// hand the daemon a t.TempDir-backed repo cache must call this before@@ -3281,7 +3323,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// 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)+ d.registerTaskRepos(task.WorkspaceID, task.ID, task.Repos)+ defer d.clearTaskRepoRefs(task.WorkspaceID, task.ID)entry, ok := d.cfg.Agents[provider]// A custom runtime profile (MUL-3284) overrides the executable path: the@@ -4323,7 +4366,7 @@ func convertReposForEnv(repos []RepoData) []execenv.RepoContextForEnv {}result := make([]execenv.RepoContextForEnv, len(repos))for i, r := range repos {- result[i] = execenv.RepoContextForEnv{URL: r.URL, Description: r.Description}+ result[i] = execenv.RepoContextForEnv{URL: r.URL, Description: r.Description, Ref: r.Ref}}return result}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex da1bf8b469..fde3e042bf 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1644,7 +1644,7 @@ func TestRegisterTaskReposAllowsProjectOnlyURL(t *testing.T) {// 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}})+ d.registerTaskRepos("ws-1", "task-project-only", []RepoData{{URL: sourceRepo}})// The async clone goroutine in registerTaskRepos may not have finished;// poll briefly until the cache is populated so the test isn't racy.@@ -1691,7 +1691,7 @@ func TestRegisterTaskReposSurvivesWorkspaceRefresh(t *testing.T) {})})d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)- d.registerTaskRepos("ws-1", []RepoData{{URL: sourceRepo}})+ d.registerTaskRepos("ws-1", "task-refresh", []RepoData{{URL: sourceRepo}})// Wait for the registration to populate the cache.deadline := time.Now().Add(5 * time.Second)@@ -1708,6 +1708,39 @@ func TestRegisterTaskReposSurvivesWorkspaceRefresh(t *testing.T) {}}+func TestTaskRepoDefaultRefScopedByTask(t *testing.T) {+ t.Parallel()++ const repoURL = "https://github.com/example/shared"+ d := &Daemon{+ workspaces: map[string]*workspaceState{+ "ws-1": newWorkspaceState("ws-1", nil, "", nil, nil),+ },+ }++ d.registerTaskRepos("ws-1", "task-a", []RepoData{+ {URL: repoURL, Ref: "release/a"},+ {URL: repoURL, Ref: "late-duplicate"},+ })+ d.registerTaskRepos("ws-1", "task-b", []RepoData{{URL: repoURL, Ref: "release/b"}})++ if got := d.taskRepoDefaultRef("ws-1", "task-a", repoURL); got != "release/a" {+ t.Fatalf("task-a default ref = %q, want release/a", got)+ }+ if got := d.taskRepoDefaultRef("ws-1", "task-b", repoURL); got != "release/b" {+ t.Fatalf("task-b default ref = %q, want release/b", got)+ }++ d.clearTaskRepoRefs("ws-1", "task-a")++ if got := d.taskRepoDefaultRef("ws-1", "task-a", repoURL); got != "" {+ t.Fatalf("task-a default ref after cleanup = %q, want empty", got)+ }+ if got := d.taskRepoDefaultRef("ws-1", "task-b", repoURL); got != "release/b" {+ t.Fatalf("task-b default ref after task-a cleanup = %q, want release/b", got)+ }+}+func TestEnsureRepoReadyReturnsNotConfigured(t *testing.T) {t.Parallel()diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 4ace0f8947..20e1832ec8 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -16,6 +16,7 @@ import (type RepoContextForEnv struct {URL string // remote URLDescription string // optional repo description+ Ref string // optional default checkout ref for this task}// ProjectResourceForEnv describes a single resource attached to the issue'sdiff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 59b671d568..9a1f6833d0 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -157,7 +157,7 @@ func TestPrepareWithProjectResources(t *testing.T) {{ID: "33333333-4444-5555-6666-777777777777",ResourceType: "github_repo",- ResourceRef: json.RawMessage(`{"url":"https://github.com/multica-ai/multica","default_branch_hint":"main"}`),+ ResourceRef: json.RawMessage(`{"url":"https://github.com/multica-ai/multica","ref":"release/v2","default_branch_hint":"main"}`),},},}@@ -221,7 +221,8 @@ func TestPrepareWithProjectResources(t *testing.T) {"Always write copy in British English. Ship behind a feature flag.","GitHub repo","https://github.com/multica-ai/multica",- "default branch: `main`",+ "checkout ref: `release/v2`",+ "default branch hint: `main`",".multica/project/resources.json",} {if !strings.Contains(s, want) {@@ -290,7 +291,7 @@ func TestPrepareWithRepoContext(t *testing.T) {taskCtx := TaskContextForEnv{IssueID: "b2c3d4e5-f6a7-8901-bcde-f12345678901",Repos: []RepoContextForEnv{- {URL: "https://github.com/org/backend"},+ {URL: "https://github.com/org/backend", Ref: "release/v2"},{URL: "https://github.com/org/frontend"},},}@@ -333,6 +334,7 @@ func TestPrepareWithRepoContext(t *testing.T) {for _, want := range []string{"multica repo checkout","https://github.com/org/backend",+ "default ref: `release/v2`","https://github.com/org/frontend",} {if !strings.Contains(s, want) {diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex cf5efed9f2..76f232f1b4 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -122,11 +122,19 @@ func formatProjectResource(r ProjectResourceForEnv) string {var payload struct {URL string `json:"url"`DefaultBranchHint string `json:"default_branch_hint,omitempty"`+ Ref string `json:"ref,omitempty"`}_ = json.Unmarshal(r.ResourceRef, &payload)out := fmt.Sprintf("**GitHub repo**: %s", payload.URL)+ details := make([]string, 0, 2)+ if payload.Ref != "" {+ details = append(details, fmt.Sprintf("checkout ref: `%s`", payload.Ref))+ }if payload.DefaultBranchHint != "" {- out += fmt.Sprintf(" (default branch: `%s`)", payload.DefaultBranchHint)+ details = append(details, fmt.Sprintf("default branch hint: `%s`", payload.DefaultBranchHint))+ }+ if len(details) > 0 {+ out += " (" + strings.Join(details, ", ") + ")"}if label != "" {out += " — " + label@@ -565,10 +573,14 @@ func buildMetaSkillContent(provider string, ctx TaskContextForEnv) string {b.WriteString("The following code repositories are available in this workspace.\n")b.WriteString("Use `multica repo checkout <url>` to check out a repository into your working directory. Add `--ref <branch-or-sha>` when you need an exact branch, tag, or commit.\n\n")for _, repo := range ctx.Repos {+ refHint := ""+ if repo.Ref != "" {+ refHint = fmt.Sprintf(" (default ref: `%s`)", repo.Ref)+ }if repo.Description != "" {- fmt.Fprintf(&b, "- %s — %s\n", repo.URL, repo.Description)+ fmt.Fprintf(&b, "- %s%s — %s\n", repo.URL, refHint, repo.Description)} else {- fmt.Fprintf(&b, "- %s\n", repo.URL)+ fmt.Fprintf(&b, "- %s%s\n", repo.URL, refHint)}}b.WriteString("\nThe checkout command creates a git worktree with a dedicated branch. You can check out one or more repos as needed, and can pass `--ref` for review/QA on a non-default branch or commit.\n\n")diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.goindex c601005478..ff1b0e6624 100644--- a/server/internal/daemon/health.go+++ b/server/internal/daemon/health.go@@ -9,6 +9,7 @@ import ("net/http""os""runtime"+ "strings""time""github.com/multica-ai/multica/server/internal/daemon/repocache"@@ -138,8 +139,23 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timmux := http.NewServeMux()mux.HandleFunc("/health", d.healthHandler(startedAt))mux.HandleFunc("/shutdown", d.shutdownHandler())+ mux.HandleFunc("/repo/checkout", d.repoCheckoutHandler())- mux.HandleFunc("/repo/checkout", func(w http.ResponseWriter, r *http.Request) {+ srv := &http.Server{Handler: mux}++ go func() {+ <-ctx.Done()+ srv.Close()+ }()++ d.logger.Info("health server listening", "addr", ln.Addr().String())+ if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {+ d.logger.Warn("health server error", "error", err)+ }+}++func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {http.Error(w, "method not allowed", http.StatusMethodNotAllowed)return@@ -150,6 +166,7 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timhttp.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)return}+ req.URL = strings.TrimSpace(req.URL)if req.URL == "" {http.Error(w, "url is required", http.StatusBadRequest)return@@ -178,11 +195,16 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timreturn}+ checkoutRef := strings.TrimSpace(req.Ref)+ if checkoutRef == "" {+ checkoutRef = d.taskRepoDefaultRef(req.WorkspaceID, req.TaskID, req.URL)+ }+result, err := d.repoCache.CreateWorktree(repocache.WorktreeParams{WorkspaceID: req.WorkspaceID,RepoURL: req.URL,WorkDir: req.WorkDir,- Ref: req.Ref,+ Ref: checkoutRef,AgentName: req.AgentName,TaskID: req.TaskID,CoAuthoredByEnabled: d.workspaceCoAuthoredByEnabled(req.WorkspaceID),@@ -195,17 +217,5 @@ func (d *Daemon) serveHealth(ctx context.Context, ln net.Listener, startedAt timw.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(result)- })-- srv := &http.Server{Handler: mux}-- go func() {- <-ctx.Done()- srv.Close()- }()-- d.logger.Info("health server listening", "addr", ln.Addr().String())- if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {- d.logger.Warn("health server error", "error", err)}}diff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 1a6d366d23..620d8aec5f 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -7,6 +7,7 @@ import ("net/http""net/http/httptest""runtime"+ "strings""sync""testing""time"@@ -198,7 +199,7 @@ func TestHealthHandlerRespondsWhileTaskRepoLookupWaits(t *testing.T) {registerDone := make(chan struct{})go func() {- d.registerTaskRepos(workspaceID, []RepoData{{URL: repoURL}})+ d.registerTaskRepos(workspaceID, "task-health", []RepoData{{URL: repoURL}})close(registerDone)}()cache.waitForLookup(t)@@ -227,6 +228,73 @@ func TestHealthHandlerRespondsWhileTaskRepoLookupWaits(t *testing.T) {}}+func TestRepoCheckoutUsesTaskScopedProjectRefByDefault(t *testing.T) {+ t.Parallel()++ const workspaceID = "ws-checkout"+ const repoURL = "https://github.com/org/repo.git"+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)+ d.registerTaskRepos(workspaceID, "task-1", []RepoData{{URL: repoURL, Ref: "release/v2"}})++ rec := httptest.NewRecorder()+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1"}`)+ d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }+ if got := cache.lastCreateParams().Ref; got != "release/v2" {+ t.Fatalf("CreateWorktree Ref = %q, want release/v2", got)+ }+}++func TestRepoCheckoutExplicitRefOverridesProjectDefault(t *testing.T) {+ t.Parallel()++ const workspaceID = "ws-checkout"+ const repoURL = "https://github.com/org/repo.git"+ cache := &recordingRepoCache{lookupPath: "/cache/org/repo.git"}+ d := newRepoCheckoutTestDaemon(t, workspaceID, repoURL, cache)+ d.registerTaskRepos(workspaceID, "task-1", []RepoData{{URL: repoURL, Ref: "release/v2"}})++ rec := httptest.NewRecorder()+ body := strings.NewReader(`{"url":"` + repoURL + `","workspace_id":"` + workspaceID + `","workdir":"/tmp/work","task_id":"task-1","ref":"hotfix"}`)+ d.repoCheckoutHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/repo/checkout", body))++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }+ if got := cache.lastCreateParams().Ref; got != "hotfix" {+ t.Fatalf("CreateWorktree Ref = %q, want explicit hotfix", got)+ }+}++func newRepoCheckoutTestDaemon(t *testing.T, workspaceID, repoURL string, cache *recordingRepoCache) *Daemon {+ t.Helper()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/daemon/workspaces/"+workspaceID+"/repos" {+ http.NotFound(w, r)+ return+ }+ json.NewEncoder(w).Encode(WorkspaceReposResponse{+ WorkspaceID: workspaceID,+ Repos: []RepoData{{URL: repoURL}},+ ReposVersion: "v1",+ })+ }))+ t.Cleanup(srv.Close)+ return &Daemon{+ cfg: Config{CLIVersion: "v1.0.0"},+ client: NewClient(srv.URL),+ repoCache: cache,+ workspaces: map[string]*workspaceState{+ workspaceID: newWorkspaceState(workspaceID, nil, "", []RepoData{{URL: repoURL}}, nil),+ },+ logger: slog.Default(),+ }+}+type blockingLookupRepoCache struct {path stringlookupSeen chan struct{}@@ -264,6 +332,40 @@ func (c *blockingLookupRepoCache) CreateWorktree(repocache.WorktreeParams) (*repreturn nil, nil}+type recordingRepoCache struct {+ lookupPath string+ mu sync.Mutex+ params []repocache.WorktreeParams+}++func (c *recordingRepoCache) Lookup(_, _ string) string {+ return c.lookupPath+}++func (c *recordingRepoCache) Sync(string, []repocache.RepoInfo) error {+ return nil+}++func (c *recordingRepoCache) WithRepoLock(_ string, fn func() error) error {+ return fn()+}++func (c *recordingRepoCache) CreateWorktree(params repocache.WorktreeParams) (*repocache.WorktreeResult, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.params = append(c.params, params)+ return &repocache.WorktreeResult{Path: params.WorkDir, BranchName: "agent/test"}, nil+}++func (c *recordingRepoCache) lastCreateParams() repocache.WorktreeParams {+ c.mu.Lock()+ defer c.mu.Unlock()+ if len(c.params) == 0 {+ return repocache.WorktreeParams{}+ }+ return c.params[len(c.params)-1]+}+func (c *blockingLookupRepoCache) waitForLookup(t *testing.T) {t.Helper()select {diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex bb5bef94f0..a7b3ac22e8 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -26,6 +26,7 @@ type Runtime struct {type RepoData struct {URL string `json:"url"`Description string `json:"description,omitempty"`+ Ref string `json:"ref,omitempty"`}// ProjectResourceData mirrors handler.ProjectResourceData — a single projectdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex f01b823f03..e1432b8d42 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -206,6 +206,7 @@ func preserveMaskedGatewayToken(incoming any, persistedRuntimeConfig []byte) {type RepoData struct {URL string `json:"url"`Description string `json:"description,omitempty"`+ Ref string `json:"ref,omitempty"`}// ProjectResourceData is the wire shape for a project resource included in adiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 06b114cd81..cf66df2d9a 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1440,9 +1440,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if row.ResourceType == "github_repo" {var payload struct {URL string `json:"url"`+ Ref string `json:"ref,omitempty"`}if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {- projectRepos = append(projectRepos, RepoData{URL: payload.URL})+ projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})}}}@@ -1717,9 +1718,10 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if row.ResourceType == "github_repo" {var payload struct {URL string `json:"url"`+ Ref string `json:"ref,omitempty"`}if json.Unmarshal(row.ResourceRef, &payload) == nil && payload.URL != "" {- projectRepos = append(projectRepos, RepoData{URL: payload.URL})+ projectRepos = append(projectRepos, RepoData{URL: payload.URL, Ref: strings.TrimSpace(payload.Ref)})}}}diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 91c4c148a7..5b8286f53f 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -2149,11 +2149,12 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })const projectRepoURL = "https://github.com/example/project-only-repo"+ const projectRepoRef = "release/v2"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 {+ `, projectID, testWorkspaceID, `{"url":"`+projectRepoURL+`","ref":"`+projectRepoRef+`"}`); err != nil {t.Fatalf("create project_resource: %v", err)}@@ -2215,6 +2216,9 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {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)}+ if resp.Task.Repos[0].Ref != projectRepoRef {+ t.Fatalf("project repo ref = %q, want %q", resp.Task.Repos[0].Ref, projectRepoRef)+ }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)diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex 54a4d9968c..e6c9c2cea6 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -84,6 +84,7 @@ func validateAndNormalizeResourceRef(resourceType string, ref json.RawMessage) (type githubRepoRef struct {URL string `json:"url"`DefaultBranchHint string `json:"default_branch_hint,omitempty"`+ Ref string `json:"ref,omitempty"`}func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {@@ -99,6 +100,7 @@ func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {return nil, errors.New("github_repo: url must be a valid http(s) or ssh git URL")}payload.DefaultBranchHint = strings.TrimSpace(payload.DefaultBranchHint)+ payload.Ref = strings.TrimSpace(payload.Ref)out, err := json.Marshal(payload)if err != nil {return nil, errdiff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.goindex 38c59dd254..1c7530a78b 100644--- a/server/internal/handler/project_resource_test.go+++ b/server/internal/handler/project_resource_test.go@@ -32,7 +32,10 @@ func TestProjectResourceLifecycle(t *testing.T) {w = httptest.NewRecorder()req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{"resource_type": "github_repo",- "resource_ref": map[string]any{"url": "https://github.com/multica-ai/multica"},+ "resource_ref": map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": "release/v2",+ },})req = withURLParam(req, "id", project.ID)testHandler.CreateProjectResource(w, req)@@ -48,6 +51,7 @@ func TestProjectResourceLifecycle(t *testing.T) {}var ref struct {URL string `json:"url"`+ Ref string `json:"ref"`}if err := json.Unmarshal(created.ResourceRef, &ref); err != nil {t.Fatalf("decode resource_ref: %v", err)@@ -55,6 +59,9 @@ func TestProjectResourceLifecycle(t *testing.T) {if ref.URL != "https://github.com/multica-ai/multica" {t.Errorf("created.ResourceRef.url = %q", ref.URL)}+ if ref.Ref != "release/v2" {+ t.Errorf("created.ResourceRef.ref = %q, want release/v2", ref.Ref)+ }// Listing must include the new resource.w = httptest.NewRecorder()@@ -82,7 +89,10 @@ func TestProjectResourceLifecycle(t *testing.T) {w = httptest.NewRecorder()req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{"resource_type": "github_repo",- "resource_ref": map[string]any{"url": "https://github.com/multica-ai/multica"},+ "resource_ref": map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "ref": "release/v2",+ },})req = withURLParam(req, "id", project.ID)testHandler.CreateProjectResource(w, req)diff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.mdindex e7ee3c21fa..850f38b044 100644--- a/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md+++ b/server/internal/service/builtin_skills/multica-projects-and-resources/SKILL.md@@ -28,7 +28,7 @@ A project's `description` is also durable context: when an issue (or a quick-creCommon resource types:-- `github_repo` — durable GitHub repo context, with `resource_ref.url` and optional `default_branch_hint`;+- `github_repo` — durable GitHub repo context, with `resource_ref.url`, optional checkout `ref`, and optional prompt-only `default_branch_hint`;- `local_directory` — daemon-local path context, with `resource_ref.local_path`, `daemon_id`, and optional label.## CLI@@ -41,12 +41,14 @@ multica project update <project-id> --title "<title>" --output jsonmultica project status <project-id> in_progress --output jsonmultica project resource list <project-id> --output jsonmultica project resource add <project-id> --type github_repo --url <github-url> --output json+multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output jsonmultica project resource add <project-id> --type local_directory --local-path <abs-path> --daemon-id <daemon-id> --output jsonmultica project resource update <project-id> <resource-id> --url <new-github-url> --output json+multica project resource update <project-id> <resource-id> --ref <branch-or-sha> --output jsonmultica project resource remove <project-id> <resource-id> --output json```-Use `--ref '<json>'` only for resource types or payloads not covered by shortcuts.+For `github_repo`, non-JSON `--ref` sets `resource_ref.ref`, the default checkout branch/tag/SHA for future tasks in that project. JSON `--ref '<json>'` remains the escape hatch for full payloads or resource types not covered by shortcuts.## When to add a resource@@ -59,7 +61,7 @@ is task-local checkout state.1. `multica project get <project-id> --output json`.2. `multica project resource list <project-id> --output json`.-3. Check `github_repo.resource_ref.url`, `default_branch_hint`, and `local_directory.resource_ref.daemon_id`.+3. Check `github_repo.resource_ref.url`, optional `ref`, `default_branch_hint`, and `local_directory.resource_ref.daemon_id`.4. Updating resources is a durable mutation. After an update, listing theresource is the verification path.5. If resources match the expected task context, inspect runtime/repo checkoutdiff --git a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md b/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.mdindex d207dea773..0a90af2836 100644--- a/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md+++ b/server/internal/service/builtin_skills/multica-projects-and-resources/references/projects-and-resources-source-map.md@@ -3,9 +3,10 @@- `server/cmd/multica/cmd_project.go` registers project `list`, `get`, `create`, `update`, `delete`, and `status`.- The same file registers `project resource list/add/update/remove`.- `project create --repo` attaches `github_repo` resources during project creation.-- `project resource add` supports shortcuts for `github_repo` (`--url`, `--default-branch-hint`) and `local_directory` (`--local-path`, `--daemon-id`, `--ref-label`), or generic `--ref '<json>'`.-- `project resource update` merges shortcut edits with existing `resource_ref` so a partial edit does not clobber required fields.+- `project resource add` supports shortcuts for `github_repo` (`--url`, non-JSON `--ref` for checkout ref, `--default-branch-hint`) and `local_directory` (`--local-path`, `--daemon-id`, `--ref-label`), or generic JSON `--ref '<json>'`.+- `project resource update` merges shortcut edits with existing `resource_ref` so a partial edit does not clobber required fields; non-JSON `--ref` updates `github_repo.resource_ref.ref`.- `server/cmd/server/router.go` exposes `/api/projects` plus `/api/projects/{projectId}/resources` routes.- `server/pkg/db/queries/project_resource.sql` is the CRUD query surface for `project_resource` rows.- Project resources are written into `.multica/project/resources.json` for agent workdirs.+- `github_repo.resource_ref.ref` is lifted into daemon `RepoData.Ref` by `server/internal/handler/daemon.go`; `server/internal/daemon/daemon.go` stores it per task, and `server/internal/daemon/health.go` uses it as the default `/repo/checkout` ref when the checkout request does not explicitly pass one.- A project's `description` is injected as durable context for every task in the project. The claim handler (`server/internal/handler/daemon.go`) reads `proj.Description` onto the claim response (`ProjectDescription`, `server/internal/handler/agent.go`); the daemon carries it through `Task` (`server/internal/daemon/types.go`) and `TaskContextForEnv` (`server/internal/daemon/execenv/execenv.go`) into the brief's `## Project Context` section (`server/internal/daemon/execenv/runtime_config.go`) and into `.multica/project/resources.json` as `project_description` (`server/internal/daemon/execenv/context.go`).diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.mdindex 28addd542f..6ff3f60f35 100644--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/SKILL.md@@ -47,7 +47,7 @@ multica repo checkout <url> --ref <branch-or-sha>`runtime update` and `runtime delete` are writes. `runtime delete` removes a runtime registration; if active agents are still bound, it refuses unless the user explicitly passes `--cascade`, which archives those agents and cancels their queued/running tasks before deleting the runtime. `repo checkout` creates a git worktree in the task working directory.-`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path.+`repo checkout` requires `MULTICA_DAEMON_PORT`; it is intended to run inside a daemon task. If absent, you are not in the normal agent checkout path. When a project `github_repo` resource has `resource_ref.ref`, `repo checkout <url>` uses that ref by default for the current task; an explicit `repo checkout <url> --ref <branch-or-sha>` overrides it.## Debugging an agent that did not run@@ -69,7 +69,7 @@ The runtime brief lists repos available to this task. Treat that list as the autWorkspace repos and project resources are not the same thing:- workspace repo metadata can appear in workspace context;-- `github_repo` project resources are durable project context and can affect future tasks;+- `github_repo` project resources are durable project context and can affect future tasks; optional `resource_ref.ref` pins the default checkout ref for tasks in that project;- `local_directory` resources point at a path owned by a daemon and carry local-machine assumptions.Do not add a project resource just because `repo checkout` failed. First determine whether the user asked for durable project context or just a task checkout.diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.mdindex 054c3738e8..72be9fa273 100644--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md@@ -6,6 +6,7 @@- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/archive-agents-and-delete`.- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.- `repo checkout` requires `MULTICA_DAEMON_PORT`, sends `workspace_id`, `workdir`, `ref`, `agent_name`, and `task_id` to local daemon `/repo/checkout`, then prints the checked-out path.+- `server/internal/daemon/health.go` resolves the checkout ref: request `ref` wins; otherwise it asks `server/internal/daemon/daemon.go` for the current task's project repo default ref.- `server/cmd/server/router.go` registers daemon APIs under `/api/daemon`, including workspace repos and task claim.- `server/internal/daemon/daemon.go` claims tasks, prepares workdirs, launches provider CLIs, and reports completion.- `server/internal/daemon/execenv/runtime_config.go` injects task/project/repo context into agent workdirs.diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.goindex a72972d862..4787b824f8 100644--- a/server/internal/service/builtin_skills_test.go+++ b/server/internal/service/builtin_skills_test.go@@ -465,6 +465,7 @@ func TestRuntimesAndReposSkillCoversClaimAndCheckoutChain(t *testing.T) {"multica runtime list --output json","multica repo checkout <url>","MULTICA_DAEMON_PORT",+ "resource_ref.ref","github_repo","local_directory","Runtime and repo commands affect active agent execution",@@ -499,9 +500,11 @@ func TestProjectsAndResourcesSkillCoversDurableContext(t *testing.T) {".multica/project/resources.json","multica project resource list <project-id> --output json","multica project resource add <project-id> --type github_repo --url <github-url> --output json",+ "multica project resource add <project-id> --type github_repo --url <github-url> --ref <branch-or-sha> --output json","multica project resource add <project-id> --type local_directory","Project resources are durable and affect future tasks","github_repo.resource_ref.url",+ "resource_ref.ref","references/projects-and-resources-source-map.md",}for _, want := range mustContain {