Skip to content

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

Go

feat: add additive agent skill assignment (#3642)

Naiyuan Qinge36f874c86e7
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.go
index 3eb9c5559d..bde468ba03 100644
--- a/server/cmd/multica/cmd_agent.go
+++ b/server/cmd/multica/cmd_agent.go
@@ -122,6 +122,13 @@ var agentSkillsSetCmd = &cobra.Command{
RunE: runAgentSkillsSet,
}
+var agentSkillsAddCmd = &cobra.Command{
+ Use: "add <agent-id>",
+ Short: "Add skills to an agent without replacing existing assignments",
+ Args: exactArgs(1),
+ RunE: runAgentSkillsAdd,
+}
+
func init() {
agentCmd.AddCommand(agentListCmd)
agentCmd.AddCommand(agentGetCmd)
@@ -136,6 +143,7 @@ func init() {
agentSkillsCmd.AddCommand(agentSkillsListCmd)
agentSkillsCmd.AddCommand(agentSkillsSetCmd)
+ agentSkillsCmd.AddCommand(agentSkillsAddCmd)
agentEnvCmd.AddCommand(agentEnvGetCmd)
agentEnvCmd.AddCommand(agentEnvSetCmd)
@@ -204,6 +212,10 @@ func init() {
agentSkillsSetCmd.Flags().StringSlice("skill-ids", nil, "Skill IDs to assign (comma-separated)")
agentSkillsSetCmd.Flags().String("output", "json", "Output format: table or json")
+ // agent skills add
+ agentSkillsAddCmd.Flags().StringSlice("skill-ids", nil, "Skill IDs to add (comma-separated)")
+ agentSkillsAddCmd.Flags().String("output", "json", "Output format: table or json")
+
// agent env get
agentEnvGetCmd.Flags().String("output", "json", "Output format: json or table")
@@ -808,16 +820,7 @@ func runAgentSkillsSet(cmd *cobra.Command, args []string) error {
if !cmd.Flags().Changed("skill-ids") {
return fmt.Errorf("--skill-ids is required (comma-separated skill IDs; use --skill-ids '' to clear all)")
}
- skillIDs, _ := cmd.Flags().GetStringSlice("skill-ids")
- // Allow passing empty string to clear all skills.
- cleanIDs := make([]string, 0, len(skillIDs))
- for _, id := range skillIDs {
- id = strings.TrimSpace(id)
- if id != "" {
- cleanIDs = append(cleanIDs, id)
- }
- }
-
+ cleanIDs := cleanSkillIDsFlag(cmd)
body := map[string]any{
"skill_ids": cleanIDs,
}
@@ -830,6 +833,50 @@ func runAgentSkillsSet(cmd *cobra.Command, args []string) error {
return fmt.Errorf("set agent skills: %w", err)
}
+ return printAgentSkillsMutationResult(cmd, args[0], result)
+}
+
+func runAgentSkillsAdd(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ if !cmd.Flags().Changed("skill-ids") {
+ return fmt.Errorf("--skill-ids is required (comma-separated skill IDs)")
+ }
+ cleanIDs := cleanSkillIDsFlag(cmd)
+ if len(cleanIDs) == 0 {
+ return fmt.Errorf("--skill-ids must include at least one skill ID")
+ }
+ body := map[string]any{
+ "skill_ids": cleanIDs,
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ var result json.RawMessage
+ if err := client.PostJSON(ctx, "/api/agents/"+args[0]+"/skills/add", body, &result); err != nil {
+ return fmt.Errorf("add agent skills: %w", err)
+ }
+
+ return printAgentSkillsMutationResult(cmd, args[0], result)
+}
+
+func cleanSkillIDsFlag(cmd *cobra.Command) []string {
+ skillIDs, _ := cmd.Flags().GetStringSlice("skill-ids")
+ cleanIDs := make([]string, 0, len(skillIDs))
+ for _, id := range skillIDs {
+ id = strings.TrimSpace(id)
+ if id != "" {
+ cleanIDs = append(cleanIDs, id)
+ }
+ }
+ return cleanIDs
+}
+
+func printAgentSkillsMutationResult(cmd *cobra.Command, agentID string, result json.RawMessage) error {
output, _ := cmd.Flags().GetString("output")
if output == "json" {
var pretty any
@@ -837,7 +884,24 @@ func runAgentSkillsSet(cmd *cobra.Command, args []string) error {
return cli.PrintJSON(os.Stdout, pretty)
}
- fmt.Printf("Skills updated for agent %s\n", args[0])
+ var skills []map[string]any
+ if err := json.Unmarshal(result, &skills); err != nil {
+ return fmt.Errorf("decode agent skills response: %w", err)
+ }
+ if len(skills) == 0 {
+ fmt.Printf("No skills assigned to agent %s\n", agentID)
+ return nil
+ }
+ headers := []string{"ID", "NAME", "DESCRIPTION"}
+ rows := make([][]string, 0, len(skills))
+ for _, s := range skills {
+ rows = append(rows, []string{
+ strVal(s, "id"),
+ strVal(s, "name"),
+ strVal(s, "description"),
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
return nil
}
diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.go
index 3f14c204fd..fe16d4f4fa 100644
--- a/server/cmd/multica/cmd_agent_test.go
+++ b/server/cmd/multica/cmd_agent_test.go
@@ -500,6 +500,65 @@ func TestResolveCustomEnv(t *testing.T) {
})
}
+func TestAgentSkillsAddCallsAdditiveEndpoint(t *testing.T) {
+ var gotMethod string
+ var gotPath string
+ var gotBody map[string][]string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotMethod = r.Method
+ gotPath = r.URL.Path
+ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
+ t.Errorf("decode request body: %v", err)
+ }
+ json.NewEncoder(w).Encode([]map[string]any{
+ {"id": "skill-a", "name": "Skill A", "description": ""},
+ {"id": "skill-b", "name": "Skill B", "description": ""},
+ })
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := &cobra.Command{Use: "add"}
+ cmd.Flags().StringSlice("skill-ids", nil, "")
+ cmd.Flags().String("output", "json", "")
+ cmd.Flags().String("profile", "", "")
+ if err := cmd.Flags().Set("skill-ids", "skill-a,skill-b"); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := runAgentSkillsAdd(cmd, []string{"agent-123"}); err != nil {
+ t.Fatalf("runAgentSkillsAdd: %v", err)
+ }
+ if gotMethod != http.MethodPost {
+ t.Fatalf("method = %s, want POST", gotMethod)
+ }
+ if gotPath != "/api/agents/agent-123/skills/add" {
+ t.Fatalf("path = %q, want additive endpoint", gotPath)
+ }
+ if !reflect.DeepEqual(gotBody["skill_ids"], []string{"skill-a", "skill-b"}) {
+ t.Fatalf("skill_ids body = %v", gotBody["skill_ids"])
+ }
+}
+
+func TestAgentSkillsAddRequiresSkillIDs(t *testing.T) {
+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := &cobra.Command{Use: "add"}
+ cmd.Flags().StringSlice("skill-ids", nil, "")
+ cmd.Flags().String("output", "json", "")
+ cmd.Flags().String("profile", "", "")
+
+ err := runAgentSkillsAdd(cmd, []string{"agent-123"})
+ if err == nil || !strings.Contains(err.Error(), "--skill-ids is required") {
+ t.Fatalf("expected required --skill-ids error, got %v", err)
+ }
+}
+
// TestAgentAvatarHappyPath verifies the full flow: agent pre-check, file upload,
// and avatar update all succeed.
func TestAgentAvatarHappyPath(t *testing.T) {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index ab601a4c05..88bb31329c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -595,6 +595,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/tasks", h.ListAgentTasks)
r.Get("/skills", h.ListAgentSkills)
r.Put("/skills", h.SetAgentSkills)
+ r.Post("/skills/add", h.AddAgentSkills)
// Dedicated env-management endpoint. Owner/admin only;
// agent actors are denied. Every reveal / write is
// audited to activity_log. See MUL-2600 and
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index e81f503ae9..69e48d1026 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -1844,6 +1844,145 @@ func TestSetAgentSkillsRejectsMalformedSkillID(t *testing.T) {
}
}
+func TestAddAgentSkillsPreservesExistingAssignments(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Add Skill Preserves Existing", nil)
+ existingSkillID := insertHandlerTestSkill(t, "add-preserve-existing", "existing body")
+ newSkillID := insertHandlerTestSkill(t, "add-preserve-new", "new body")
+
+ if _, err := testPool.Exec(context.Background(),
+ `INSERT INTO agent_skill (agent_id, skill_id) VALUES ($1, $2)`,
+ agentID, existingSkillID,
+ ); err != nil {
+ t.Fatalf("seed existing skill assignment: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{
+ "skill_ids": []string{newSkillID},
+ })
+ req = withURLParam(req, "id", agentID)
+ testHandler.AddAgentSkills(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("AddAgentSkills: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var resp []SkillSummaryResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ assertSkillIDsPresent(t, resp, existingSkillID, newSkillID)
+ assertAgentSkillRowCount(t, agentID, 2)
+}
+
+func TestAddAgentSkillsAddsMultipleAndIsIdempotent(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Add Multiple Skills", nil)
+ skillA := insertHandlerTestSkill(t, "add-multiple-a", "a body")
+ skillB := insertHandlerTestSkill(t, "add-multiple-b", "b body")
+
+ for attempt := 0; attempt < 2; attempt++ {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{
+ "skill_ids": []string{skillA, skillB},
+ })
+ req = withURLParam(req, "id", agentID)
+ testHandler.AddAgentSkills(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("AddAgentSkills attempt %d: expected 200, got %d: %s", attempt+1, w.Code, w.Body.String())
+ }
+ }
+
+ assertAgentSkillRowCount(t, agentID, 2)
+}
+
+func TestAddAgentSkillsRejectsMalformedSkillID(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Add Malformed Skill Assignment", nil)
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{
+ "skill_ids": []string{"not-a-uuid"},
+ })
+ req = withURLParam(req, "id", agentID)
+ testHandler.AddAgentSkills(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("AddAgentSkills: expected 400 for malformed skill_ids, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestAddAgentSkillsRejectsCrossWorkspaceSkillID(t *testing.T) {
+ agentID := createHandlerTestAgent(t, "Handler Add Cross Workspace Skill", nil)
+ foreignSkillID := insertHandlerTestSkillInForeignWorkspace(t, "add-cross-workspace", "foreign body")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/agents/"+agentID+"/skills/add", map[string]any{
+ "skill_ids": []string{foreignSkillID},
+ })
+ req = withURLParam(req, "id", agentID)
+ testHandler.AddAgentSkills(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("AddAgentSkills: expected 404 for cross-workspace skill_id, got %d: %s", w.Code, w.Body.String())
+ }
+ assertAgentSkillRowCount(t, agentID, 0)
+}
+
+func insertHandlerTestSkillInForeignWorkspace(t *testing.T, namePrefix, content string) string {
+ t.Helper()
+ ctx := context.Background()
+ slug := "foreign-skill-" + strings.ToLower(strings.ReplaceAll(t.Name(), "_", "-"))
+
+ var workspaceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, "Foreign Skill Workspace "+t.Name(), slug, "", "FSW").Scan(&workspaceID); err != nil {
+ t.Fatalf("insert foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)
+ })
+
+ name := namePrefix + "-" + t.Name()
+ var skillID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO skill (workspace_id, name, description, content, config, created_by)
+ VALUES ($1, $2, $3, $4, '{}'::jsonb, $5)
+ RETURNING id
+ `, workspaceID, name, "fixture", content, testUserID).Scan(&skillID); err != nil {
+ t.Fatalf("insert foreign skill: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, skillID)
+ })
+ return skillID
+}
+
+func assertSkillIDsPresent(t *testing.T, skills []SkillSummaryResponse, wantIDs ...string) {
+ t.Helper()
+ got := make(map[string]bool, len(skills))
+ for _, s := range skills {
+ got[s.ID] = true
+ }
+ for _, want := range wantIDs {
+ if !got[want] {
+ t.Fatalf("response missing skill %s; got %+v", want, skills)
+ }
+ }
+}
+
+func assertAgentSkillRowCount(t *testing.T, agentID string, want int) {
+ t.Helper()
+ var got int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT COUNT(*) FROM agent_skill WHERE agent_id = $1`,
+ agentID,
+ ).Scan(&got); err != nil {
+ t.Fatalf("count agent_skill: %v", err)
+ }
+ if got != want {
+ t.Fatalf("agent_skill row count: got %d, want %d", got, want)
+ }
+}
+
func TestAgentCRUD(t *testing.T) {
// List agents
w := httptest.NewRecorder()
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 6689074193..fd925af7e5 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -211,6 +211,10 @@ type SetAgentSkillsRequest struct {
SkillIDs []string `json:"skill_ids"`
}
+type AddAgentSkillsRequest struct {
+ SkillIDs []string `json:"skill_ids"`
+}
+
// --- Helpers ---
// validateFilePath checks that a file path is safe (no traversal, no absolute paths).
@@ -1927,6 +1931,9 @@ func (h *Handler) SetAgentSkills(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ if !h.validateAgentSkillIDsInWorkspace(w, r, agent, skillUUIDs) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -1957,7 +1964,78 @@ func (h *Handler) SetAgentSkills(w http.ResponseWriter, r *http.Request) {
return
}
- // Return the updated skills list.
+ h.writeUpdatedAgentSkills(w, r, agent)
+}
+
+func (h *Handler) AddAgentSkills(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ agent, ok := h.loadAgentForUser(w, r, id)
+ if !ok {
+ return
+ }
+ if !h.canManageAgent(w, r, agent) {
+ return
+ }
+
+ var req AddAgentSkillsRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ skillUUIDs, ok := parseUUIDSliceOrBadRequest(w, req.SkillIDs, "skill_ids")
+ if !ok {
+ return
+ }
+ if !h.validateAgentSkillIDsInWorkspace(w, r, agent, skillUUIDs) {
+ return
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+
+ qtx := h.Queries.WithTx(tx)
+ for _, skillID := range skillUUIDs {
+ if err := qtx.AddAgentSkill(r.Context(), db.AddAgentSkillParams{
+ AgentID: agent.ID,
+ SkillID: skillID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to add agent skill: "+err.Error())
+ return
+ }
+ }
+
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit")
+ return
+ }
+
+ h.writeUpdatedAgentSkills(w, r, agent)
+}
+
+func (h *Handler) validateAgentSkillIDsInWorkspace(w http.ResponseWriter, r *http.Request, agent db.Agent, skillUUIDs []pgtype.UUID) bool {
+ seen := map[string]struct{}{}
+ for _, skillID := range skillUUIDs {
+ key := uuidToString(skillID)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ if _, err := h.Queries.GetSkillInWorkspace(r.Context(), db.GetSkillInWorkspaceParams{
+ ID: skillID,
+ WorkspaceID: agent.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusNotFound, "skill not found")
+ return false
+ }
+ }
+ return true
+}
+
+func (h *Handler) writeUpdatedAgentSkills(w http.ResponseWriter, r *http.Request, agent db.Agent) {
skills, err := h.Queries.ListAgentSkillSummaries(r.Context(), agent.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list agent skills")