Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7336: feat(labels): add skill label CLI commands and skills list label filtering (#8368)
klinsmaya904693bed94f
diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex dfea842fca..82d34c49be 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -247,7 +247,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| `project` | `list/get/create/update/delete` | プロジェクトを管理 | || | `status <id> <status>` | プロジェクトのステータスを変更 | || | `resource list/add/update/remove` | プロジェクトの追加リソースを管理 | `--type`、`--url`、`--local-path`、`--daemon-id`、`--execution-mode`(ローカルディレクトリの `in_place` / `worktree`) |-| `label` | `list/get/create/update/delete` | ワークスペースのラベルを管理 | |+| `label` | `list/get/create/update/delete` | ワークスペースのラベルを管理 | `list`: `--resource-type`(`issue` または `skill`)、`--full-id`;`create`: `--name`、`--color`、`--resource-type`(`issue` または `skill`)、`--description` || `property` | `list/get/create/update/archive/unarchive` | ワークスペースのカスタムプロパティを管理 | `create`: `--name`、`--type`(`text`、`number`、`select`、`multi_select`、`date`、`checkbox`、`url`、`actor`、`multi_actor`)、`--option`(繰り返し可、select 系のみ);`list`: `--include-archived`;タイプは作成後に変更できません || `agent` | `list/get/create/update/archive/restore` | エージェントを管理 | `--name`、`--runtime-id`(`create` では必須)、`--instructions`、`--conversation-starters`、`--model`、`--thinking-level`、`--mcp-config`、`--permission-mode`、`--max-concurrent-tasks` || | `copy <agent-id>` | 新しいエージェントとして複製。元のエージェントは変更されません | `--name`(デフォルトは元の名前 + ` (copy)`)、`--runtime-id`(別のランタイムへ複製する場合は `--model` の同時指定が必須)、`--no-skills`;`custom_env`、`mcp_config`、`runtime_config` などの機密設定は複製されないため、`create` と同じフラグで再指定してください |@@ -268,6 +268,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `import` | URL またはローカルファイルからスキルをインポート | `--url` / `--file`、`--on-conflict`(`fail`、`overwrite`、`rename`、`skip`。デフォルトは `fail`) || | `search <query>` | スキルを検索 | || | `files list/upsert/delete <skill-id>` | スキル内のファイルを管理 | |+| | `label list/add/remove <skill-id>` | スキルのラベルを管理 | `add` / `remove`: `<label-id>` は完全な UUID または短いプレフィックス || `squad` | `list/get/create/update/delete` | スクワッドを管理(`delete` はアーカイブ) | || | `member list/add/set-role/remove` | スクワッドのメンバーを管理 | || | `activity <issue-id> <outcome>` | リーダーの評価を記録 | |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 79e718d391..9640bac123 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -247,7 +247,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| `project` | `list/get/create/update/delete` | 프로젝트 관리 | || | `status <id> <status>` | 프로젝트 상태 변경 | || | `resource list/add/update/remove` | 프로젝트 추가 리소스 관리 | `--type`, `--url`, `--local-path`, `--daemon-id`, `--execution-mode`(로컬 디렉터리의 `in_place` / `worktree`) |-| `label` | `list/get/create/update/delete` | 워크스페이스 라벨 관리 | |+| `label` | `list/get/create/update/delete` | 워크스페이스 라벨 관리 | `list`: `--resource-type`(`issue` 또는 `skill`), `--full-id`; `create`: `--name`, `--color`, `--resource-type`(`issue` 또는 `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | 워크스페이스 사용자 지정 속성 관리 | `create`: `--name`, `--type`(`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`), `--option`(반복 가능, select 유형만). `list`: `--include-archived`. 유형은 생성 후 변경 불가 || `agent` | `list/get/create/update/archive/restore` | 에이전트 관리 | `--name`, `--runtime-id`(`create`에서 필수), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--mcp-config`, `--permission-mode`, `--max-concurrent-tasks` || | `copy <agent-id>` | 원래 에이전트에 영향 없이 새 에이전트로 복사 | `--name`(기본값은 원래 이름 + ` (copy)`), `--runtime-id`(다른 런타임으로 복사할 때 `--model`도 필수), `--no-skills`. `custom_env`, `mcp_config`, `runtime_config` 같은 기밀 설정은 복사되지 않으며 `create`와 같은 flag로 다시 제공해야 함 |@@ -268,6 +268,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `import` | URL 또는 로컬 파일에서 스킬 가져오기 | `--url` / `--file`, `--on-conflict`(`fail`, `overwrite`, `rename`, `skip`, 기본 `fail`) || | `search <query>` | 스킬 검색 | || | `files list/upsert/delete <skill-id>` | 스킬 내부 파일 관리 | |+| | `label list/add/remove <skill-id>` | 스킬 라벨 관리 | `add` / `remove`: `<label-id>`에 전체 UUID 또는 짧은 접두사 사용 가능 || `squad` | `list/get/create/update/delete` | 스쿼드 관리(`delete`는 보관) | || | `member list/add/set-role/remove` | 스쿼드 멤버 관리 | || | `activity <issue-id> <outcome>` | 리더 평가 기록 | |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex b705e4a0f0..63fa9867e6 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -255,7 +255,7 @@ The tables below cover every current top-level command, grouped the way the CLI| `project` | `list/get/create/update/delete` | Manage projects | || | `status <id> <status>` | Change project status | || | `resource list/add/update/remove` | Manage project resources | `--type`, `--url`, `--local-path`, `--daemon-id`, `--execution-mode` (`in_place` / `worktree` for a local directory) |-| `label` | `list/get/create/update/delete` | Manage workspace labels | |+| `label` | `list/get/create/update/delete` | Manage workspace labels | `list`: `--resource-type` (`issue` or `skill`), `--full-id`; `create`: `--name`, `--color`, `--resource-type` (`issue` or `skill`), `--description` || `property` | `list/get/create/update/archive/unarchive` | Manage workspace custom properties | `create`: `--name`, `--type` (`text`, `number`, `select`, `multi_select`, `date`, `checkbox`, `url`, `actor`, `multi_actor`), `--option` (repeatable, select types only); `list`: `--include-archived`; the type cannot be changed after creation || `agent` | `list/get/create/update/archive/restore` | Manage agents | `--name`, `--runtime-id` (required for `create`), `--instructions`, `--conversation-starters`, `--model`, `--thinking-level`, `--mcp-config`, `--permission-mode`, `--max-concurrent-tasks` || | `copy <agent-id>` | Copy into a new agent; the original is untouched | `--name` (defaults to the original name plus ` (copy)`), `--runtime-id` (copying to another runtime also requires `--model`), `--no-skills`; secret configuration such as `custom_env`, `mcp_config`, and `runtime_config` is not copied — re-provide it with the same flags as `create` |@@ -276,6 +276,7 @@ The tables below cover every current top-level command, grouped the way the CLI| | `import` | Import a skill from a URL or local file | `--url` / `--file`, `--on-conflict` (`fail`, `overwrite`, `rename`, `skip`; default `fail`) || | `search <query>` | Search skills | || | `files list/upsert/delete <skill-id>` | Manage the files inside a skill | |+| | `label list/add/remove <skill-id>` | Manage labels on a skill | `add` / `remove`: `<label-id>` accepts a full UUID or short prefix || `squad` | `list/get/create/update/delete` | Manage squads (`delete` archives) | || | `member list/add/set-role/remove` | Manage squad members | || | `activity <issue-id> <outcome>` | Record a leader evaluation | |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 0eaa21daec..fef72f5b40 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -247,7 +247,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| `project` | `list/get/create/update/delete` | 管理项目 | || | `status <id> <status>` | 修改项目状态 | || | `resource list/add/update/remove` | 管理项目附加资源 | `--type`、`--url`、`--local-path`、`--daemon-id`、`--execution-mode`(本地目录的 `in_place` / `worktree`) |-| `label` | `list/get/create/update/delete` | 管理工作区标签 | |+| `label` | `list/get/create/update/delete` | 管理工作区标签 | `list`:`--resource-type`(`issue` 或 `skill`)、`--full-id`;`create`:`--name`、`--color`、`--resource-type`(`issue` 或 `skill`)、`--description` || `property` | `list/get/create/update/archive/unarchive` | 管理工作区自定义属性 | `create`:`--name`、`--type`(`text`、`number`、`select`、`multi_select`、`date`、`checkbox`、`url`、`actor`、`multi_actor`)、`--option`(可重复,仅 select 类型);`list`:`--include-archived`;类型创建后不可修改 || `agent` | `list/get/create/update/archive/restore` | 管理智能体 | `--name`、`--runtime-id`(`create` 必填)、`--instructions`、`--conversation-starters`、`--model`、`--thinking-level`、`--mcp-config`、`--permission-mode`、`--max-concurrent-tasks` || | `copy <agent-id>` | 复制为新智能体,原智能体不受影响 | `--name`(默认为原名加 ` (copy)`)、`--runtime-id`(复制到其他运行时时必须同时指定 `--model`)、`--no-skills`;`custom_env`、`mcp_config`、`runtime_config` 等机密配置不会复制,需用与 `create` 相同的 flag 重新提供 |@@ -268,6 +268,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `import` | 从 URL 或本地文件导入 skill | `--url` / `--file`、`--on-conflict`(`fail`、`overwrite`、`rename`、`skip`,默认 `fail`) || | `search <query>` | 搜索 skill | || | `files list/upsert/delete <skill-id>` | 管理 skill 内的文件 | |+| | `label list/add/remove <skill-id>` | 管理 skill 上的标签 | `add` / `remove`:`<label-id>` 可使用完整 UUID 或短前缀 || `squad` | `list/get/create/update/delete` | 管理小队(`delete` 为归档) | || | `member list/add/set-role/remove` | 管理小队成员 | || | `activity <issue-id> <outcome>` | 记录队长评价 | |diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2779c8d5bd..fbc13b094e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -416,6 +416,8 @@ import {MALFORMED_RUNTIME_MODEL_LIST_REQUEST,SkillSchema,EMPTY_SKILL,+ SkillSummaryListSchema,+ EMPTY_SKILL_SUMMARY_LIST,SkillImportResultSchema,EMPTY_SKILL_IMPORT_RESULT,IssueViewSchema,@@ -3043,7 +3045,10 @@ export class ApiClient {// Skillsasync listSkills(): Promise<SkillSummary[]> {- return this.fetch("/api/skills");+ const raw = await this.fetch<unknown>("/api/skills");+ return parseWithFallback(raw, SkillSummaryListSchema, EMPTY_SKILL_SUMMARY_LIST, {+ endpoint: "GET /api/skills",+ });}async getSkill(id: string): Promise<Skill> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex abffe933ae..a70a2b4736 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -129,6 +129,64 @@ describe("ApiClient schema fallback", () => {});});+ describe("listSkills", () => {+ const baseSkill = {+ id: "skill-1",+ workspace_id: "ws-1",+ name: "review-helper",+ description: "",+ config: {},+ created_by: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+ const skillLabel = {+ id: "label-1",+ workspace_id: "ws-1",+ resource_type: "skill",+ name: "mattpocock",+ color: "#3b82f6",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };++ it("falls back to an empty list when the response is malformed", async () => {+ stubFetchJson({ skills: "not-an-array" });+ const client = new ApiClient("https://api.example.test");+ const res = await client.listSkills();+ expect(res).toEqual([]);+ });++ it("treats a missing labels field as an empty array (older backends)", async () => {+ stubFetchJson([baseSkill]);+ const client = new ApiClient("https://api.example.test");+ const res = await client.listSkills();+ expect(res).toHaveLength(1);+ expect(res[0]?.id).toBe("skill-1");+ expect(res[0]?.labels).toEqual([]);+ // List parsing must not invent detail-only fields (GH #2174).+ expect(res[0]).not.toHaveProperty("content");+ expect(res[0]).not.toHaveProperty("files");+ });++ it("keeps a well-formed labels array", async () => {+ stubFetchJson([{ ...baseSkill, labels: [skillLabel] }]);+ const client = new ApiClient("https://api.example.test");+ const res = await client.listSkills();+ expect(res[0]?.labels?.map((l) => l.id)).toEqual(["label-1"]);+ expect(res[0]?.labels?.[0]?.resource_type).toBe("skill");+ });++ it("catches malformed labels to [] without dropping the skill", async () => {+ stubFetchJson([{ ...baseSkill, labels: [{ nope: true }] }]);+ const client = new ApiClient("https://api.example.test");+ const res = await client.listSkills();+ expect(res).toHaveLength(1);+ expect(res[0]?.id).toBe("skill-1");+ expect(res[0]?.labels).toEqual([]);+ });+ });+describe("getIssue", () => {// Unlike a list, a single issue has no safe-empty shape, and the bare// identifier autolink caches this result for 5 minutes. A malformed 2xxdiff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 90cdae195f..a05ffdfc39 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -82,6 +82,7 @@ import type {ShareLinkInfo,Skill,SkillImportResult,+ SkillSummary,Squad,TimelineEntry,User,@@ -3231,32 +3232,52 @@ export const SkillFileSchema = z.object({updated_at: z.string().optional().default(""),}).loose();-export const SkillSchema = z.object({+// Workspace list shape (`GET /api/skills`). Intentionally no `content` /+// `files`: those belong on the detail endpoint. Defaulting them here used+// to invent empty bodies on every list row (GH #2174).+export const SkillSummarySchema = z.object({id: z.string(),workspace_id: z.string(),name: z.string(),description: z.string().optional().default(""),- content: z.string().optional().default(""),config: z.record(z.string(), z.unknown()).optional().default({}),created_by: z.string().nullable().optional().default(null),created_at: z.string().optional().default(""),updated_at: z.string().optional().default(""),- files: z.array(SkillFileSchema).optional().default([]),+ enabled: z.boolean().optional(),+ // Catch-to-empty so a missing/malformed labels field cannot fail the+ // whole skill (or the list it lives in). Older backends omit it; the+ // filter treats an empty array as "no labels".+ labels: z.array(LabelSchema).catch([]),}).loose();-export const EMPTY_SKILL: Skill = {+export const EMPTY_SKILL_SUMMARY: SkillSummary = {id: "",workspace_id: "",name: "",description: "",- content: "",config: {},created_by: null,created_at: "",updated_at: "",+ labels: [],+};++export const SkillSchema = SkillSummarySchema.extend({+ content: z.string().optional().default(""),+ files: z.array(SkillFileSchema).optional().default([]),+}).loose();++export const EMPTY_SKILL: Skill = {+ ...EMPTY_SKILL_SUMMARY,+ content: "",files: [],};+export const SkillSummaryListSchema = z.array(SkillSummarySchema).default([]);++export const EMPTY_SKILL_SUMMARY_LIST: SkillSummary[] = [];+export const SkillImportExistingSkillSchema = z.object({id: z.string(),name: z.string(),diff --git a/packages/core/labels/mutations.ts b/packages/core/labels/mutations.tsindex 6f87255d5f..d78a0bfc67 100644--- a/packages/core/labels/mutations.ts+++ b/packages/core/labels/mutations.ts@@ -3,6 +3,7 @@ import { api } from "../api";import { labelKeys } from "./queries";import { useWorkspaceId } from "../hooks";import { issueKeys } from "../issues/queries";+import { workspaceKeys } from "../workspace/queries";import {invalidateIssueLabelDerivatives,onIssueLabelsChanged,@@ -69,9 +70,10 @@ export function useUpdateLabel() {// stale copy of this label is refetched. The list cache is the source// of truth; byIssue views will re-render with the fresh data.qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });- // Issues now embed labels (denormalized snapshot), so a rename/recolor- // also has to refresh the issues caches that hold those snapshots.+ // Issues and workspace skill lists embed label snapshots, so a+ // rename/recolor also has to refresh those caches.qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });},});}@@ -100,9 +102,10 @@ export function useDeleteLabel() {},onSettled: () => {qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });- // A deleted label still lives in cached issue.labels arrays until we- // refetch — invalidate so list/board chips drop the orphan.+ // A deleted label still lives in cached issue/skill.labels arrays+ // until we refetch — invalidate so list chips drop the orphan.qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });},});}diff --git a/packages/core/skills/stores/view-store.test.ts b/packages/core/skills/stores/view-store.test.tsnew file mode 100644index 0000000000..dc577e6d56--- /dev/null+++ b/packages/core/skills/stores/view-store.test.ts@@ -0,0 +1,64 @@+// @vitest-environment jsdom+import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";+import {+ DEFAULT_HIDDEN_COLUMNS,+ EMPTY_SKILL_FILTERS,+ useSkillsViewStore,+} from "./view-store";+import { setCurrentWorkspace } from "../../platform/workspace-storage";++const flush = () => new Promise((resolve) => queueMicrotask(() => resolve(null)));++beforeAll(() => {+ if (typeof globalThis.localStorage?.clear !== "function") {+ const values = new Map<string, string>();+ const storage: Storage = {+ get length() { return values.size; },+ clear: () => values.clear(),+ getItem: (k) => values.get(k) ?? null,+ key: (i) => Array.from(values.keys())[i] ?? null,+ removeItem: (k) => { values.delete(k); },+ setItem: (k, v) => { values.set(k, v); },+ };+ Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });+ Object.defineProperty(window, "localStorage", { configurable: true, value: storage });+ }+});++beforeEach(() => {+ localStorage.clear();+ useSkillsViewStore.setState({+ sortField: "updated",+ sortDirection: "desc",+ hiddenColumns: DEFAULT_HIDDEN_COLUMNS,+ filters: EMPTY_SKILL_FILTERS,+ });+ setCurrentWorkspace(null, null);+});++afterEach(() => {+ setCurrentWorkspace(null, null);+});++describe("useSkillsViewStore", () => {+ it("backfills new filter dimensions when rehydrating a pre-labels payload", async () => {+ // A payload persisted before the `labels` filter existed must not drop+ // the key to undefined (the skills list filter predicate reads+ // `filters.labels.length` and would crash).+ localStorage.setItem(+ "multica_skills_view:acme",+ JSON.stringify({+ state: { filters: { usage: ["used"], origins: [], agents: [], creators: [] } },+ version: 0,+ }),+ );++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ await flush();++ const filters = useSkillsViewStore.getState().filters;+ expect(filters.labels).toEqual([]);+ expect(filters.usage).toEqual(["used"]);+ });+});diff --git a/packages/core/skills/stores/view-store.ts b/packages/core/skills/stores/view-store.tsindex 6b4b984d4f..5b6f6024ce 100644--- a/packages/core/skills/stores/view-store.ts+++ b/packages/core/skills/stores/view-store.ts@@ -42,6 +42,7 @@ export interface SkillListFilters {origins: SkillOriginType[];agents: string[];creators: string[];+ labels: string[];}export const EMPTY_SKILL_FILTERS: SkillListFilters = {@@ -49,6 +50,7 @@ export const EMPTY_SKILL_FILTERS: SkillListFilters = {origins: [],agents: [],creators: [],+ labels: [],};// User-hideable columns. Name and the structural columns (checkbox, kebab)diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 5c20cdeea1..8828c27cf7 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -1,4 +1,5 @@import type { ChatSession } from "./chat";+import type { Label } from "./label";export type AgentStatus = "idle" | "working" | "blocked" | "error" | "offline";@@ -849,8 +850,10 @@ export interface SkillSummary {created_by: string | null;created_at: string;updated_at: string;- /** Present only when returned from an agent-scoped assignment endpoint. */- enabled?: boolean;+ /** Present only when returned from an agent-scoped assignment endpoint. */+ enabled?: boolean;+ /** Present on workspace skill lists after a backend that bulk-attaches labels. */+ labels?: Label[];}export interface Skill extends SkillSummary {diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex 68828f64d2..961fec66d1 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -113,6 +113,10 @@"filter_active_count_other": "{{count}} filters","clear_filters": "Clear filters","section_usage": "Usage",+ "section_labels": "Labels",+ "filter_search_placeholder": "Filter...",+ "no_labels": "No labels yet",+ "no_results": "No results","display": "Display","sort_by": "Sort by","direction_asc": "Ascending",diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.jsonindex 197865edcc..80f3f35fcf 100644--- a/packages/views/locales/ja/skills.json+++ b/packages/views/locales/ja/skills.json@@ -105,6 +105,10 @@"filter_active_count_other": "{{count}} 件のフィルター","clear_filters": "フィルターを解除","section_usage": "使用状況",+ "section_labels": "ラベル",+ "filter_search_placeholder": "フィルター...",+ "no_labels": "まだラベルがありません",+ "no_results": "結果なし","display": "表示","sort_by": "並び替え","direction_asc": "昇順",diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.jsonindex fa1d86b6d8..95e2d045a8 100644--- a/packages/views/locales/ko/skills.json+++ b/packages/views/locales/ko/skills.json@@ -105,6 +105,10 @@"filter_active_count_other": "필터 {{count}}개","clear_filters": "필터 해제","section_usage": "사용 상태",+ "section_labels": "라벨",+ "filter_search_placeholder": "필터...",+ "no_labels": "아직 라벨이 없습니다",+ "no_results": "결과 없음","display": "표시","sort_by": "정렬","direction_asc": "오름차순",diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex 58a1c83ff1..2b92c8caa4 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -105,6 +105,10 @@"filter_active_count_other": "{{count}} 项筛选","clear_filters": "清除筛选","section_usage": "使用状态",+ "section_labels": "标签",+ "filter_search_placeholder": "筛选...",+ "no_labels": "还没有标签",+ "no_results": "无结果","display": "显示","sort_by": "排序","direction_asc": "升序",diff --git a/packages/views/skills/components/skill-list-actions.test.tsx b/packages/views/skills/components/skill-list-actions.test.tsxindex a550e081b2..0ec3572317 100644--- a/packages/views/skills/components/skill-list-actions.test.tsx+++ b/packages/views/skills/components/skill-list-actions.test.tsx@@ -8,7 +8,7 @@ import type { SkillSummary } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enSkills from "../../locales/en/skills.json";-import type { SkillRow } from "./skills-page";+import type { SkillRow } from "./skill-list-filter";import type { SkillActionsContext } from "./skill-list-actions";const TEST_RESOURCES = { en: { common: enCommon, skills: enSkills } };diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsxindex 4b2d582381..4f4e39749c 100644--- a/packages/views/skills/components/skill-list-actions.tsx+++ b/packages/views/skills/components/skill-list-actions.tsx@@ -54,7 +54,7 @@ import { useT } from "../../i18n";import { useIntentNavigate } from "../../navigation";import { isRefreshableOrigin, readOrigin } from "../lib/origin";import { RefreshSkillDialog } from "./refresh-skill-dialog";-import type { SkillRow } from "./skills-page";+import type { SkillRow } from "./skill-list-filter";// Shared context the row kebab and the batch toolbar both need. Assembled// once at the page level.diff --git a/packages/views/skills/components/skill-list-filter.ts b/packages/views/skills/components/skill-list-filter.tsnew file mode 100644index 0000000000..a36cebae40--- /dev/null+++ b/packages/views/skills/components/skill-list-filter.ts@@ -0,0 +1,55 @@+import type { Agent, AgentRuntime, MemberWithUser, SkillSummary } from "@multica/core/types";+import type { SkillListFilters } from "@multica/core/skills/stores";+import type { OriginInfo } from "../lib/origin";++export interface SkillRow {+ skill: SkillSummary;+ agents: Agent[];+ creator: MemberWithUser | null;+ runtime: AgentRuntime | null;+ originType: OriginInfo["type"];+ canEdit: boolean;+}++/**+ * Pure row-filter predicate: returns true if the row matches all active+ * filter dimensions plus name search. Empty arrays are inactive. Label+ * matching is OR-within-labels, matching Issue list semantics.+ */+export function rowMatchesFilters(+ row: SkillRow,+ filters: SkillListFilters,+ query: string,+): boolean {+ const q = query.trim().toLowerCase();+ if (q && !row.skill.name.toLowerCase().includes(q)) return false;+ if (filters.usage.length > 0) {+ const usage = row.agents.length > 0 ? "used" : "unused";+ if (!filters.usage.includes(usage)) return false;+ }+ if (+ filters.origins.length > 0 &&+ !filters.origins.includes(row.originType)+ ) {+ return false;+ }+ if (+ filters.agents.length > 0 &&+ !row.agents.some((a) => filters.agents.includes(a.id))+ ) {+ return false;+ }+ if (+ filters.creators.length > 0 &&+ (!row.skill.created_by ||+ !filters.creators.includes(row.skill.created_by))+ ) {+ return false;+ }+ if (filters.labels.length > 0) {+ const labels = row.skill.labels;+ if (!labels || labels.length === 0) return false;+ if (!labels.some((l) => filters.labels.includes(l.id))) return false;+ }+ return true;+}diff --git a/packages/views/skills/components/skill-list-toolbar.tsx b/packages/views/skills/components/skill-list-toolbar.tsxindex 5dc751adad..b2dc589521 100644--- a/packages/views/skills/components/skill-list-toolbar.tsx+++ b/packages/views/skills/components/skill-list-toolbar.tsx@@ -1,5 +1,6 @@"use client";+import { useState } from "react";import {ArrowDown,ArrowUp,@@ -11,7 +12,10 @@ import {Search,X,} from "lucide-react";-import type { Agent, MemberWithUser } from "@multica/core/types";+import { useQuery } from "@tanstack/react-query";+import { useWorkspaceId } from "@multica/core/hooks";+import { labelListOptions } from "@multica/core/labels/queries";+import type { Agent, Label, MemberWithUser } from "@multica/core/types";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { Button } from "@multica/ui/components/ui/button";import {@@ -46,8 +50,9 @@ import {type SkillSortDirection,type SkillSortField,} from "@multica/core/skills/stores";+import { LabelChip } from "../../labels/label-chip";import { useT } from "../../i18n";-import type { SkillRow } from "./skills-page";+import type { SkillRow } from "./skill-list-filter";import { PAGE_TOOLBAR } from "../../layout/page-header";export type OriginType = SkillOriginType;@@ -70,6 +75,7 @@ export function countActiveFilterDimensions(if (filters.origins.length > 0) count++;if (filters.agents.length > 0) count++;if (filters.creators.length > 0) count++;+ if (filters.labels.length > 0) count++;return count;}@@ -119,6 +125,9 @@ export function SkillListToolbar({visibleCount: number;}) {const { t } = useT("skills");+ const [labelSearch, setLabelSearch] = useState("");+ const wsId = useWorkspaceId();+ const { data: catalogLabels = [] } = useQuery(labelListOptions(wsId, "skill"));const activeCount = countActiveFilterDimensions(filters);const hasActiveFilters = activeCount > 0;@@ -134,6 +143,7 @@ export function SkillListToolbar({string,{ member: MemberWithUser; count: number }>();+ const labelCounts = new Map<string, number>();for (const row of allRows) {originCounts.set(row.originType, (originCounts.get(row.originType) ?? 0) + 1);for (const agent of row.agents) {@@ -146,8 +156,16 @@ export function SkillListToolbar({if (entry) entry.count += 1;else creatorOptions.set(row.creator.user_id, { member: row.creator, count: 1 });}+ for (const label of row.skill.labels ?? []) {+ labelCounts.set(label.id, (labelCounts.get(label.id) ?? 0) + 1);+ }}+ const labelQuery = labelSearch.trim().toLowerCase();+ const filteredLabels = catalogLabels.filter((label: Label) =>+ label.name.toLowerCase().includes(labelQuery),+ );+const ORIGIN_LABELS: Record<OriginType, string> = {manual: t(($) => $.table.source_manual),runtime_local: t(($) => $.table.source_runtime_unknown),@@ -382,6 +400,59 @@ export function SkillListToolbar({))}</DropdownMenuSubContent></DropdownMenuSub>++ {/* Labels — Skill-scoped catalog, OR-within-labels like Issues. */}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <span className="flex-1">+ {t(($) => $.toolbar.section_labels)}+ </span>+ {filters.labels.length > 0 && (+ <span className="text-caption font-medium text-primary">+ {filters.labels.length}+ </span>+ )}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-auto min-w-52 p-0">+ <div className="border-b border-foreground/5 px-2 py-1.5">+ <input+ type="text"+ value={labelSearch}+ onChange={(e) => setLabelSearch(e.target.value)}+ placeholder={t(($) => $.toolbar.filter_search_placeholder)}+ className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"+ autoFocus+ />+ </div>+ <div className="max-h-64 overflow-y-auto p-1">+ {filteredLabels.map((label) => {+ const checked = filters.labels.includes(label.id);+ const count = labelCounts.get(label.id) ?? 0;+ return (+ <DropdownMenuCheckboxItem+ key={label.id}+ checked={checked}+ onCheckedChange={() =>+ onToggleFilter("labels", label.id)+ }+ className={FILTER_ITEM_CLASS}+ >+ <HoverCheck checked={checked} />+ <LabelChip label={label} />+ {count > 0 && countBadge(count)}+ </DropdownMenuCheckboxItem>+ );+ })}+ {filteredLabels.length === 0 && (+ <div className="px-2 py-3 text-center text-body text-muted-foreground">+ {labelSearch+ ? t(($) => $.toolbar.no_results)+ : t(($) => $.toolbar.no_labels)}+ </div>+ )}+ </div>+ </DropdownMenuSubContent>+ </DropdownMenuSub></DropdownMenuContent></DropdownMenu>diff --git a/packages/views/skills/components/skills-page-filter-predicate.test.ts b/packages/views/skills/components/skills-page-filter-predicate.test.tsnew file mode 100644index 0000000000..f7743cfbf7--- /dev/null+++ b/packages/views/skills/components/skills-page-filter-predicate.test.ts@@ -0,0 +1,124 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import type { SkillListFilters } from "@multica/core/skills/stores";+import type { Agent, Label, SkillSummary } from "@multica/core/types";+import { rowMatchesFilters, type SkillRow } from "./skill-list-filter";++function makeSkill(overrides: Partial<SkillSummary> = {}): SkillSummary {+ return {+ id: "skill-1",+ workspace_id: "ws-1",+ name: "review-helper",+ description: "",+ config: {},+ created_by: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++function makeLabel(id: string, name = id): Label {+ return {+ id,+ workspace_id: "ws-1",+ resource_type: "skill",+ name,+ color: "#3b82f6",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+}++function makeRow(+ skillOverrides: Partial<SkillSummary> = {},+ rowOverrides: Partial<SkillRow> = {},+): SkillRow {+ return {+ skill: makeSkill(skillOverrides),+ agents: [],+ creator: null,+ runtime: null,+ originType: "manual",+ canEdit: true,+ ...rowOverrides,+ };+}++const EMPTY_FILTERS: SkillListFilters = {+ usage: [],+ origins: [],+ agents: [],+ creators: [],+ labels: [],+};++function withLabels(filters: SkillListFilters, ...ids: string[]): SkillListFilters {+ return { ...filters, labels: ids };+}++describe("rowMatchesFilters — labels dimension", () => {+ const noFilters = EMPTY_FILTERS;++ it("empty labels filter is inactive (all rows pass)", () => {+ const unlabeled = makeRow();+ const labeled = makeRow({ labels: [makeLabel("lab-1")] });+ const empty = makeRow({ labels: [] });+ expect(rowMatchesFilters(unlabeled, noFilters, "")).toBe(true);+ expect(rowMatchesFilters(labeled, noFilters, "")).toBe(true);+ expect(rowMatchesFilters(empty, noFilters, "")).toBe(true);+ });++ it("missing labels fail when a labels filter is on", () => {+ const unlabeled = makeRow();+ expect(rowMatchesFilters(unlabeled, withLabels(noFilters, "lab-1"), "")).toBe(+ false,+ );+ });++ it("empty labels fail when a labels filter is on", () => {+ const empty = makeRow({ labels: [] });+ expect(rowMatchesFilters(empty, withLabels(noFilters, "lab-1"), "")).toBe(+ false,+ );+ });++ it("multi-select labels filter is OR-combined", () => {+ const a = makeRow({ labels: [makeLabel("lab-a")] });+ const b = makeRow({ labels: [makeLabel("lab-b")] });+ const neither = makeRow({ labels: [makeLabel("lab-c")] });+ const filters = withLabels(noFilters, "lab-a", "lab-b");+ expect(rowMatchesFilters(a, filters, "")).toBe(true);+ expect(rowMatchesFilters(b, filters, "")).toBe(true);+ expect(rowMatchesFilters(neither, filters, "")).toBe(false);+ });++ it("labels + usage filter: both must pass (AND)", () => {+ const used = makeRow(+ { labels: [makeLabel("lab-1")] },+ { agents: [{ id: "agent-1" } as Agent] },+ );+ const unused = makeRow({ labels: [makeLabel("lab-1")] }, { agents: [] });+ const filters: SkillListFilters = {+ ...noFilters,+ labels: ["lab-1"],+ usage: ["used"],+ };+ expect(rowMatchesFilters(used, filters, "")).toBe(true);+ expect(rowMatchesFilters(unused, filters, "")).toBe(false);+ });++ it("labels + name search: both must pass (AND)", () => {+ const match = makeRow({+ name: "review-helper",+ labels: [makeLabel("lab-1")],+ });+ const miss = makeRow({+ name: "deploy-notes",+ labels: [makeLabel("lab-1")],+ });+ const filters = withLabels(noFilters, "lab-1");+ expect(rowMatchesFilters(match, filters, "review")).toBe(true);+ expect(rowMatchesFilters(miss, filters, "review")).toBe(false);+ });+});diff --git a/packages/views/skills/components/skills-page.source-link.test.tsx b/packages/views/skills/components/skills-page.source-link.test.tsxindex 2df399e06b..7979667e18 100644--- a/packages/views/skills/components/skills-page.source-link.test.tsx+++ b/packages/views/skills/components/skills-page.source-link.test.tsx@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({origins: [] as string[],agents: [] as string[],creators: [] as string[],+ labels: [] as string[],},toggleSort: vi.fn(),setSortField: vi.fn(),diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsxindex 487ec9c9ab..506a5cbd2e 100644--- a/packages/views/skills/components/skills-page.tsx+++ b/packages/views/skills/components/skills-page.tsx@@ -61,7 +61,8 @@ import {CollectionPageState,} from "../../layout/collection-page";import { canEditSkill } from "../hooks/use-can-edit-skill";-import { originSourceUrl, readOrigin, type OriginInfo } from "../lib/origin";+import { originSourceUrl, readOrigin } from "../lib/origin";+import { rowMatchesFilters, type SkillRow } from "./skill-list-filter";import { CreateSkillDialog } from "./create-skill-dialog";import {useSkillsViewStore,@@ -152,15 +153,7 @@ function columnTrackVars(// (@multica/core/skills/stores/view-store) so the persisted state and the// UI share one definition. Re-exported here for the toolbar's convenience.export type SortField = SkillSortField;--export interface SkillRow {- skill: SkillSummary;- agents: Agent[];- creator: MemberWithUser | null;- runtime: AgentRuntime | null;- originType: OriginInfo["type"];- canEdit: boolean;-}+export { rowMatchesFilters, type SkillRow } from "./skill-list-filter";// ---------------------------------------------------------------------------// Page header bar — uses shared PageHeader so the mobile sidebar trigger and@@ -689,34 +682,9 @@ export default function SkillsPage() {// Visible rows: name search + filters, then sort.const rows = useMemo<SkillRow[]>(() => {- const q = search.trim().toLowerCase();- const filtered = allRows.filter((row) => {- if (q && !row.skill.name.toLowerCase().includes(q)) return false;- if (filters.usage.length > 0) {- const usage = row.agents.length > 0 ? "used" : "unused";- if (!filters.usage.includes(usage)) return false;- }- if (- filters.origins.length > 0 &&- !filters.origins.includes(row.originType)- ) {- return false;- }- if (- filters.agents.length > 0 &&- !row.agents.some((a) => filters.agents.includes(a.id))- ) {- return false;- }- if (- filters.creators.length > 0 &&- (!row.skill.created_by ||- !filters.creators.includes(row.skill.created_by))- ) {- return false;- }- return true;- });+ const filtered = allRows.filter((row) =>+ rowMatchesFilters(row, filters, search),+ );const dir = sortDirection === "asc" ? 1 : -1;filtered.sort((a, b) => {diff --git a/server/cmd/multica/cmd_id_resolver.go b/server/cmd/multica/cmd_id_resolver.goindex c01be14c7a..44a9c30f17 100644--- a/server/cmd/multica/cmd_id_resolver.go+++ b/server/cmd/multica/cmd_id_resolver.go@@ -406,31 +406,39 @@ func resolveProjectResourceID(ctx context.Context, client *cli.APIClient, projecreturn resolveIDByPrefix(ctx, client, "project resource", input, fetch)}-func resolveLabelID(ctx context.Context, client *cli.APIClient, input string) (resolvedID, error) {- return resolveIDByPrefix(ctx, client, "label", input, fetchLabelCandidates)+func resolveLabelID(ctx context.Context, client *cli.APIClient, input, resourceType string) (resolvedID, error) {+ return resolveIDByPrefix(ctx, client, "label", input, func(ctx context.Context, client *cli.APIClient) ([]idCandidate, error) {+ return fetchLabelCandidates(ctx, client, resourceType)+ })}-func fetchLabelCandidates(ctx context.Context, client *cli.APIClient) ([]idCandidate, error) {+func fetchLabelCandidates(ctx context.Context, client *cli.APIClient, resourceType string) ([]idCandidate, error) {if client.WorkspaceID == "" {return nil, fmt.Errorf("workspace_id is required to resolve label id prefixes")}- params := url.Values{"workspace_id": {client.WorkspaceID}}- var result map[string]any- if err := client.GetJSON(ctx, "/api/labels?"+params.Encode(), &result); err != nil {- return nil, err+ resourceTypes := []string{resourceType}+ if resourceType == "" {+ resourceTypes = []string{"issue", "skill"}}- labelsRaw, _ := result["labels"].([]any)- candidates := make([]idCandidate, 0, len(labelsRaw))- for _, raw := range labelsRaw {- l, ok := raw.(map[string]any)- if !ok {- continue+ candidates := make([]idCandidate, 0)+ for _, candidateType := range resourceTypes {+ params := url.Values{"workspace_id": {client.WorkspaceID}, "resource_type": {candidateType}}+ var result map[string]any+ if err := client.GetJSON(ctx, "/api/labels?"+params.Encode(), &result); err != nil {+ return nil, err+ }+ labelsRaw, _ := result["labels"].([]any)+ for _, raw := range labelsRaw {+ l, ok := raw.(map[string]any)+ if !ok {+ continue+ }+ candidates = append(candidates, idCandidate{+ ID: strVal(l, "id"),+ Display: strVal(l, "name"),+ Detail: strVal(l, "color"),+ })}- candidates = append(candidates, idCandidate{- ID: strVal(l, "id"),- Display: strVal(l, "name"),- Detail: strVal(l, "color"),- })}return candidates, nil}diff --git a/server/cmd/multica/cmd_issue_label.go b/server/cmd/multica/cmd_issue_label.goindex edad673bc9..27180931cb 100644--- a/server/cmd/multica/cmd_issue_label.go+++ b/server/cmd/multica/cmd_issue_label.go@@ -95,7 +95,7 @@ func runIssueLabelAdd(cmd *cobra.Command, args []string) error {if err != nil {return fmt.Errorf("resolve issue: %w", err)}- labelRef, err := resolveLabelID(ctx, client, args[1])+ labelRef, err := resolveLabelID(ctx, client, args[1], "issue")if err != nil {return fmt.Errorf("resolve label: %w", err)}@@ -128,7 +128,7 @@ func runIssueLabelRemove(cmd *cobra.Command, args []string) error {if err != nil {return fmt.Errorf("resolve issue: %w", err)}- labelRef, err := resolveLabelID(ctx, client, args[1])+ labelRef, err := resolveLabelID(ctx, client, args[1], "issue")if err != nil {return fmt.Errorf("resolve label: %w", err)}diff --git a/server/cmd/multica/cmd_label.go b/server/cmd/multica/cmd_label.goindex a6dcb69a4e..23f770107e 100644--- a/server/cmd/multica/cmd_label.go+++ b/server/cmd/multica/cmd_label.go@@ -12,12 +12,12 @@ import ()// ----------------------------------------------------------------------------// Label commands — workspace-scoped CRUD for issue labels.+// Label commands — workspace-scoped CRUD for labels (issues and skills).// ---------------------------------------------------------------------------var labelCmd = &cobra.Command{Use: "label",- Short: "Work with issue labels",+ Short: "Work with labels",}var labelListCmd = &cobra.Command{@@ -53,6 +53,13 @@ var labelDeleteCmd = &cobra.Command{RunE: runLabelDelete,}+func validateLabelResourceType(value string) error {+ if value != "issue" && value != "skill" {+ return fmt.Errorf("resource type must be issue or skill")+ }+ return nil+}+func init() {labelCmd.AddCommand(labelListCmd)labelCmd.AddCommand(labelGetCmd)@@ -62,14 +69,18 @@ func init() {labelListCmd.Flags().String("output", "table", "Output format: table or json")labelListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")+ labelListCmd.Flags().String("resource-type", "", "Filter by resource type: issue or skill (default: issue)")labelGetCmd.Flags().String("output", "json", "Output format: table or json")labelCreateCmd.Flags().String("name", "", "Label name (required)")labelCreateCmd.Flags().String("color", "", "Hex color like #3b82f6 (required)")+ labelCreateCmd.Flags().String("resource-type", "issue", "Resource type: issue or skill")+ labelCreateCmd.Flags().String("description", "", "Label description")labelCreateCmd.Flags().String("output", "json", "Output format: table or json")labelUpdateCmd.Flags().String("name", "", "New name")labelUpdateCmd.Flags().String("color", "", "New hex color")+ labelUpdateCmd.Flags().String("description", "", "New description")labelUpdateCmd.Flags().String("output", "json", "Output format: table or json")labelDeleteCmd.Flags().String("output", "json", "Output format: table or json")@@ -87,6 +98,12 @@ func runLabelList(cmd *cobra.Command, _ []string) error {if client.WorkspaceID != "" {params.Set("workspace_id", client.WorkspaceID)}+ if v, _ := cmd.Flags().GetString("resource-type"); v != "" {+ if err := validateLabelResourceType(v); err != nil {+ return err+ }+ params.Set("resource_type", v)+ }path := "/api/labels"if len(params) > 0 {path += "?" + params.Encode()@@ -104,7 +121,7 @@ func runLabelList(cmd *cobra.Command, _ []string) error {}fullID, _ := cmd.Flags().GetBool("full-id")- headers := []string{"ID", "NAME", "COLOR", "CREATED"}+ headers := []string{"ID", "NAME", "RESOURCE TYPE", "COLOR", "CREATED"}rows := make([][]string, 0, len(labelsRaw))for _, raw := range labelsRaw {l, ok := raw.(map[string]any)@@ -118,6 +135,7 @@ func runLabelList(cmd *cobra.Command, _ []string) error {rows = append(rows, []string{displayID(strVal(l, "id"), fullID),strVal(l, "name"),+ strVal(l, "resource_type"),strVal(l, "color"),created,})@@ -134,7 +152,7 @@ func runLabelGet(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- labelRef, err := resolveLabelID(ctx, client, args[0])+ labelRef, err := resolveLabelID(ctx, client, args[0], "")if err != nil {return fmt.Errorf("resolve label: %w", err)}@@ -146,7 +164,7 @@ func runLabelGet(cmd *cobra.Command, args []string) error {output, _ := cmd.Flags().GetString("output")if output == "table" {- headers := []string{"ID", "NAME", "COLOR", "CREATED"}+ headers := []string{"ID", "NAME", "RESOURCE TYPE", "COLOR", "CREATED"}created := strVal(label, "created_at")if len(created) >= 10 {created = created[:10]@@ -154,6 +172,7 @@ func runLabelGet(cmd *cobra.Command, args []string) error {rows := [][]string{{strVal(label, "id"),strVal(label, "name"),+ strVal(label, "resource_type"),strVal(label, "color"),created,}}@@ -172,6 +191,10 @@ func runLabelCreate(cmd *cobra.Command, _ []string) error {if color == "" {return fmt.Errorf("--color is required (e.g. #3b82f6)")}+ resourceType, _ := cmd.Flags().GetString("resource-type")+ if err := validateLabelResourceType(resourceType); err != nil {+ return err+ }client, err := newAPIClient(cmd)if err != nil {@@ -181,6 +204,10 @@ func runLabelCreate(cmd *cobra.Command, _ []string) error {defer cancel()body := map[string]any{"name": name, "color": color}+ body["resource_type"] = resourceType+ if v, _ := cmd.Flags().GetString("description"); v != "" {+ body["description"] = v+ }var result map[string]anyif err := client.PostJSON(ctx, "/api/labels", body, &result); err != nil {return fmt.Errorf("create label: %w", err)@@ -188,10 +215,11 @@ func runLabelCreate(cmd *cobra.Command, _ []string) error {output, _ := cmd.Flags().GetString("output")if output == "table" {- headers := []string{"ID", "NAME", "COLOR"}+ headers := []string{"ID", "NAME", "RESOURCE TYPE", "COLOR"}rows := [][]string{{strVal(result, "id"),strVal(result, "name"),+ strVal(result, "resource_type"),strVal(result, "color"),}}cli.PrintTable(os.Stdout, headers, rows)@@ -208,7 +236,7 @@ func runLabelUpdate(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- labelRef, err := resolveLabelID(ctx, client, args[0])+ labelRef, err := resolveLabelID(ctx, client, args[0], "")if err != nil {return fmt.Errorf("resolve label: %w", err)}@@ -220,8 +248,12 @@ func runLabelUpdate(cmd *cobra.Command, args []string) error {if v, _ := cmd.Flags().GetString("color"); v != "" {body["color"] = v}+ if cmd.Flags().Changed("description") {+ v, _ := cmd.Flags().GetString("description")+ body["description"] = v+ }if len(body) == 0 {- return fmt.Errorf("nothing to update — provide --name and/or --color")+ return fmt.Errorf("nothing to update — provide --name, --color, and/or --description")}var result map[string]any@@ -231,10 +263,11 @@ func runLabelUpdate(cmd *cobra.Command, args []string) error {output, _ := cmd.Flags().GetString("output")if output == "table" {- headers := []string{"ID", "NAME", "COLOR"}+ headers := []string{"ID", "NAME", "RESOURCE TYPE", "COLOR"}rows := [][]string{{strVal(result, "id"),strVal(result, "name"),+ strVal(result, "resource_type"),strVal(result, "color"),}}cli.PrintTable(os.Stdout, headers, rows)@@ -251,7 +284,7 @@ func runLabelDelete(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- labelRef, err := resolveLabelID(ctx, client, args[0])+ labelRef, err := resolveLabelID(ctx, client, args[0], "")if err != nil {return fmt.Errorf("resolve label: %w", err)}diff --git a/server/cmd/multica/cmd_label_test.go b/server/cmd/multica/cmd_label_test.goindex 3ed67481dd..79e774bb85 100644--- a/server/cmd/multica/cmd_label_test.go+++ b/server/cmd/multica/cmd_label_test.go@@ -16,10 +16,20 @@ func newLabelCreateTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "create"}cmd.Flags().String("name", "", "")cmd.Flags().String("color", "", "")+ cmd.Flags().String("resource-type", "issue", "")+ cmd.Flags().String("description", "", "")cmd.Flags().String("output", "json", "")return cmd}+func newLabelListTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "list"}+ cmd.Flags().String("resource-type", "", "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().Bool("full-id", false, "")+ return cmd+}+func newLabelUpdateTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "update"}cmd.Flags().String("name", "", "")@@ -153,3 +163,89 @@ func TestRunLabelCreateRequiresNameAndColor(t *testing.T) {t.Fatalf("runLabelCreate error = %v, want missing color", err)}}++func TestRunLabelCreateWithResourceType(t *testing.T) {+ var body map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Fatalf("method = %s, want POST", r.Method)+ }+ if r.URL.Path != "/api/labels" {+ t.Fatalf("path = %q, want /api/labels", r.URL.Path)+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatalf("decode body: %v", err)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": testLabelUUID,+ "name": body["name"],+ "resource_type": body["resource_type"],+ "color": body["color"],+ })+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)++ cmd := newLabelCreateTestCmd()+ _ = cmd.Flags().Set("name", "mattpocock")+ _ = cmd.Flags().Set("color", "#3b82f6")+ _ = cmd.Flags().Set("resource-type", "skill")++ out, err := captureStdout(t, func() error { return runLabelCreate(cmd, nil) })+ if err != nil {+ t.Fatalf("runLabelCreate: %v", err)+ }+ if body["name"] != "mattpocock" || body["color"] != "#3b82f6" || body["resource_type"] != "skill" {+ t.Fatalf("body = %#v, want name/color/resource_type", body)+ }+ var got map[string]any+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("decode stdout JSON: %v\n%s", err, out)+ }+ if got["resource_type"] != "skill" || got["name"] != "mattpocock" {+ t.Fatalf("stdout = %#v, want created skill label", got)+ }+}++func TestRunLabelListWithResourceType(t *testing.T) {+ var queryResource string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ t.Fatalf("method = %s, want GET", r.Method)+ }+ if r.URL.Path != "/api/labels" {+ t.Fatalf("path = %q, want /api/labels", r.URL.Path)+ }+ queryResource = r.URL.Query().Get("resource_type")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "labels": []map[string]any{+ {+ "id": testLabelUUID,+ "name": "frontend",+ "resource_type": queryResource,+ "color": "#3b82f6",+ },+ },+ })+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)++ cmd := newLabelListTestCmd()+ _ = cmd.Flags().Set("resource-type", "skill")++ out, err := captureStdout(t, func() error { return runLabelList(cmd, nil) })+ if err != nil {+ t.Fatalf("runLabelList: %v", err)+ }+ if queryResource != "skill" {+ t.Fatalf("queryResource = %q, want skill", queryResource)+ }+ var got []map[string]any+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("decode stdout JSON: %v\n%s", err, out)+ }+ if len(got) != 1 || got[0]["resource_type"] != "skill" {+ t.Fatalf("stdout = %#v, want skill label list", got)+ }+}diff --git a/server/cmd/multica/cmd_skill_label.go b/server/cmd/multica/cmd_skill_label.gonew file mode 100644index 0000000000..006ff0f1d5--- /dev/null+++ b/server/cmd/multica/cmd_skill_label.go@@ -0,0 +1,144 @@+package main++import (+ "context"+ "fmt"+ "net/url"+ "os"++ "github.com/spf13/cobra"++ "github.com/multica-ai/multica/server/internal/cli"+)++// multica skill label {list|add|remove} — manages the labels attached to a+// specific skill. The label itself is managed via `multica label ...`.++var skillLabelCmd = &cobra.Command{+ Use: "label",+ Short: "Manage labels on a skill",+}++var skillLabelListCmd = &cobra.Command{+ Use: "list <skill-id>",+ Short: "List labels on a skill",+ Args: exactArgs(1),+ RunE: runSkillLabelList,+}++var skillLabelAddCmd = &cobra.Command{+ Use: "add <skill-id> <label-id>",+ Short: "Attach a label to a skill",+ Args: exactArgs(2),+ RunE: runSkillLabelAdd,+}++var skillLabelRemoveCmd = &cobra.Command{+ Use: "remove <skill-id> <label-id>",+ Short: "Remove a label from a skill",+ Args: exactArgs(2),+ RunE: runSkillLabelRemove,+}++func init() {+ skillLabelCmd.AddCommand(skillLabelListCmd)+ skillLabelCmd.AddCommand(skillLabelAddCmd)+ skillLabelCmd.AddCommand(skillLabelRemoveCmd)++ skillLabelListCmd.Flags().String("output", "table", "Output format: table or json")+ skillLabelAddCmd.Flags().String("output", "table", "Output format: table or json")+ skillLabelRemoveCmd.Flags().String("output", "table", "Output format: table or json")+ skillLabelListCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")+ skillLabelAddCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")+ skillLabelRemoveCmd.Flags().Bool("full-id", false, "Show full UUIDs in table output")++ // Register under the top-level `skill` command.+ skillCmd.AddCommand(skillLabelCmd)+}++func runSkillLabelList(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ var result map[string]any+ if err := client.GetJSON(ctx, "/api/skills/"+url.PathEscape(args[0])+"/labels", &result); err != nil {+ return fmt.Errorf("list skill labels: %w", err)+ }+ labelsRaw, _ := result["labels"].([]any)++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, labelsRaw)+ }+ fullID, _ := cmd.Flags().GetBool("full-id")+ printLabelTable(labelsRaw, fullID)+ return nil+}++func runSkillLabelAdd(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ labelRef, err := resolveLabelID(ctx, client, args[1], "skill")+ if err != nil {+ return fmt.Errorf("resolve label: %w", err)+ }++ body := map[string]any{"label_id": labelRef.ID}+ var result map[string]any+ if err := client.PostJSON(ctx, "/api/skills/"+url.PathEscape(args[0])+"/labels", body, &result); err != nil {+ return fmt.Errorf("attach label: %w", err)+ }+ labelsRaw, _ := result["labels"].([]any)++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, labelsRaw)+ }+ fullID, _ := cmd.Flags().GetBool("full-id")+ printLabelTable(labelsRaw, fullID)+ return nil+}++func runSkillLabelRemove(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }+ ctx, cancel := cli.APIContext(context.Background())+ defer cancel()++ labelRef, err := resolveLabelID(ctx, client, args[1], "skill")+ if err != nil {+ return fmt.Errorf("resolve label: %w", err)+ }++ if err := client.DeleteJSON(ctx, "/api/skills/"+url.PathEscape(args[0])+"/labels/"+labelRef.ID); err != nil {+ return fmt.Errorf("detach label: %w", err)+ }++ var result map[string]any+ output, _ := cmd.Flags().GetString("output")+ if err := client.GetJSON(ctx, "/api/skills/"+url.PathEscape(args[0])+"/labels", &result); err != nil {+ if output == "json" {+ return cli.PrintJSON(os.Stdout, map[string]any{"detached": true})+ }+ fmt.Fprintln(os.Stdout, "Label detached.")+ return nil+ }+ labelsRaw, _ := result["labels"].([]any)+ if output == "json" {+ return cli.PrintJSON(os.Stdout, labelsRaw)+ }+ fullID, _ := cmd.Flags().GetBool("full-id")+ printLabelTable(labelsRaw, fullID)+ return nil+}diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.goindex a5c335d08e..abf2a58f36 100644--- a/server/cmd/multica/cmd_skill_test.go+++ b/server/cmd/multica/cmd_skill_test.go@@ -669,3 +669,110 @@ func TestRunSkillFilesListRendersReadableSizes(t *testing.T) {t.Errorf("expected an exact byte count for the small file, got %q", out)}}++func newSkillLabelTestCmd(action string) *cobra.Command {+ cmd := &cobra.Command{Use: action}+ cmd.Flags().String("output", "json", "")+ cmd.Flags().Bool("full-id", false, "")+ return cmd+}++func TestRunSkillLabelCommands(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ var lastMethod, lastPath string+ var lastBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ lastMethod = r.Method+ lastPath = r.URL.Path+ w.Header().Set("Content-Type", "application/json")+ if r.Method == http.MethodGet && r.URL.Path == "/api/skills/skill-1/labels" {+ _ = json.NewEncoder(w).Encode(map[string]any{+ "labels": []map[string]any{+ {"id": testLabelUUID, "name": "mattpocock", "color": "#3b82f6"},+ },+ })+ return+ }+ if r.Method == http.MethodPost && r.URL.Path == "/api/skills/skill-1/labels" {+ _ = json.NewDecoder(r.Body).Decode(&lastBody)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "labels": []map[string]any{+ {"id": testLabelUUID, "name": "mattpocock", "color": "#3b82f6"},+ },+ })+ return+ }+ if r.Method == http.MethodDelete && r.URL.Path == "/api/skills/skill-1/labels/"+testLabelUUID {+ w.WriteHeader(http.StatusNoContent)+ return+ }+ if r.Method == http.MethodGet && r.URL.Path == "/api/labels" {+ if got := r.URL.Query().Get("resource_type"); got != "skill" {+ t.Fatalf("resource_type = %q, want skill", got)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "labels": []map[string]any{+ {"id": testLabelUUID, "name": "mattpocock", "color": "#3b82f6"},+ },+ })+ return+ }+ http.NotFound(w, r)+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ // 1. List labels on skill+ listCmd := newSkillLabelTestCmd("list")+ out, err := captureStdout(t, func() error {+ return runSkillLabelList(listCmd, []string{"skill-1"})+ })+ if err != nil {+ t.Fatalf("runSkillLabelList: %v", err)+ }+ var gotList []map[string]any+ if err := json.Unmarshal([]byte(out), &gotList); err != nil {+ t.Fatalf("decode JSON: %v", err)+ }+ if len(gotList) != 1 || gotList[0]["name"] != "mattpocock" {+ t.Fatalf("list output = %#v", gotList)+ }++ // 2. Add label to skill+ addCmd := newSkillLabelTestCmd("add")+ out, err = captureStdout(t, func() error {+ return runSkillLabelAdd(addCmd, []string{"skill-1", testLabelUUID})+ })+ if err != nil {+ t.Fatalf("runSkillLabelAdd: %v", err)+ }+ if lastMethod != http.MethodPost || lastPath != "/api/skills/skill-1/labels" {+ t.Fatalf("add request: method=%s, path=%s", lastMethod, lastPath)+ }+ if lastBody["label_id"] != testLabelUUID {+ t.Fatalf("add body: %#v, want label_id %s", lastBody, testLabelUUID)+ }++ // Short IDs from `label list --resource-type skill` resolve against skill labels.+ _, err = captureStdout(t, func() error {+ return runSkillLabelAdd(addCmd, []string{"skill-1", "1111"})+ })+ if err != nil {+ t.Fatalf("runSkillLabelAdd with short label ID: %v", err)+ }++ // 3. Remove label from skill+ removeCmd := newSkillLabelTestCmd("remove")+ out, err = captureStdout(t, func() error {+ return runSkillLabelRemove(removeCmd, []string{"skill-1", testLabelUUID})+ })+ if err != nil {+ t.Fatalf("runSkillLabelRemove: %v", err)+ }+ if lastMethod != http.MethodGet || lastPath != "/api/skills/skill-1/labels" {+ t.Fatalf("remove follow-up request: method=%s, path=%s", lastMethod, lastPath)+ }+}diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex 572c6523bb..c570a3c130 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -72,6 +72,11 @@ type SkillSummaryResponse struct {// Enabled is only populated for agent-scoped skill responses. Workspace// skill lists describe the skill itself, so they omit assignment state.Enabled *bool `json:"enabled,omitempty"`+ // Labels are bulk-attached by ListSkills so the client can filter+ // without an N+1 round-trip per row. Pointer + omitempty: ListSkills+ // always sets a non-nil slice (empty when none). Other summary+ // producers leave this nil so the field is omitted.+ Labels *[]LabelResponse `json:"labels,omitempty"`}// AgentSkillSummary is the still-narrower shape used for skills embedded in@@ -342,24 +347,68 @@ func (h *Handler) loadSkillForUser(w http.ResponseWriter, r *http.Request, id stfunc (h *Handler) ListSkills(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)+ wsUUID := parseUUID(workspaceID)- skills, err := h.Queries.ListSkillSummariesByWorkspace(r.Context(), parseUUID(workspaceID))+ skills, err := h.Queries.ListSkillSummariesByWorkspace(r.Context(), wsUUID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list skills")return}+ ids := make([]pgtype.UUID, len(skills))+ for i, s := range skills {+ ids[i] = s.ID+ }+ labelsMap := h.labelsBySkill(r.Context(), wsUUID, ids)+resp := make([]SkillSummaryResponse, len(skills))for i, s := range skills {resp[i] = skillSummaryToResponse(s.ID, s.WorkspaceID, s.Name, s.Description, s.Config,s.CreatedBy, s.CreatedAt, s.UpdatedAt,)+ // Own a non-nil slice so JSON is `labels: []` (not `null`/omitted).+ // append(nil, xs...) keeps a nil header when xs is empty.+ labels := append([]LabelResponse{}, labelsMap[resp[i].ID]...)+ resp[i].Labels = &labels}writeJSON(w, http.StatusOK, resp)}+// labelsBySkill bulk-loads labels for the given skill IDs and returns a map+// keyed by skill UUID string. On error or empty input, returns an empty map —+// label rendering is non-critical and we'd rather serve skills without labels+// than fail the whole list call.+func (h *Handler) labelsBySkill(ctx context.Context, wsUUID pgtype.UUID, skillIDs []pgtype.UUID) map[string][]LabelResponse {+ out := map[string][]LabelResponse{}+ if len(skillIDs) == 0 {+ return out+ }+ rows, err := h.Queries.ListLabelsForSkills(ctx, db.ListLabelsForSkillsParams{+ SkillIds: skillIDs,+ WorkspaceID: wsUUID,+ })+ if err != nil {+ slog.Warn("ListLabelsForSkills failed", "error", err)+ return out+ }+ for _, r := range rows {+ skillID := uuidToString(r.SkillID)+ out[skillID] = append(out[skillID], LabelResponse{+ ID: uuidToString(r.ID),+ WorkspaceID: uuidToString(r.WorkspaceID),+ ResourceType: r.ResourceType,+ Name: r.Name,+ Description: r.Description,+ Color: r.Color,+ CreatedAt: timestampToString(r.CreatedAt),+ UpdatedAt: timestampToString(r.UpdatedAt),+ })+ }+ return out+}+func (h *Handler) SearchSkills(w http.ResponseWriter, r *http.Request) {query := strings.TrimSpace(r.URL.Query().Get("q"))if query == "" {diff --git a/server/internal/handler/skill_list_test.go b/server/internal/handler/skill_list_test.goindex 5d3f5483b7..36114ec5e0 100644--- a/server/internal/handler/skill_list_test.go+++ b/server/internal/handler/skill_list_test.go@@ -261,3 +261,77 @@ func insertHandlerTestSkill(t *testing.T, namePrefix, content string) string {})return id}++func TestListSkills_IncludesAttachedLabelsAndOmitsContent(t *testing.T) {+ labeledID := insertHandlerTestSkill(t, "list-skill-with-label", strings.Repeat("c", 512))+ unlabeledID := insertHandlerTestSkill(t, "list-skill-no-label", strings.Repeat("d", 512))++ wCreate := httptest.NewRecorder()+ testHandler.CreateLabel(wCreate, newRequest("POST", "/api/labels", map[string]any{+ "resource_type": "skill",+ "name": "list-filter",+ "color": "#3b82f6",+ }))+ if wCreate.Code != 201 {+ t.Fatalf("CreateLabel: expected 201, got %d: %s", wCreate.Code, wCreate.Body.String())+ }+ var created LabelResponse+ if err := json.NewDecoder(wCreate.Body).Decode(&created); err != nil {+ t.Fatalf("decode created label: %v", err)+ }+ t.Cleanup(func() {+ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/labels/"+created.ID, nil)+ req = withURLParam(req, "id", created.ID)+ testHandler.DeleteLabel(w, req)+ })+ if _, err := testPool.Exec(context.Background(),+ `INSERT INTO skill_to_label (skill_id, label_id) VALUES ($1, $2)`,+ labeledID, created.ID,+ ); err != nil {+ t.Fatalf("attach skill label: %v", err)+ }++ w := httptest.NewRecorder()+ req := newRequest("GET", "/api/skills?workspace_id="+testWorkspaceID, nil)+ testHandler.ListSkills(w, req)+ if w.Code != 200 {+ t.Fatalf("ListSkills: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var rows []map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil {+ t.Fatalf("ListSkills: failed to decode body: %v", err)+ }++ byID := make(map[string]map[string]any, len(rows))+ for _, row := range rows {+ id, _ := row["id"].(string)+ byID[id] = row+ }++ labeled, ok := byID[labeledID]+ if !ok {+ t.Fatalf("ListSkills: labeled skill %s not in response", labeledID)+ }+ if _, hasContent := labeled["content"]; hasContent {+ t.Fatalf("ListSkills: labeled skill must still omit content, got: %v", labeled)+ }+ labels, ok := labeled["labels"].([]any)+ if !ok || len(labels) != 1 {+ t.Fatalf("ListSkills: labeled skill expected 1 label, got: %v", labeled["labels"])+ }+ label, _ := labels[0].(map[string]any)+ if label["id"] != created.ID || label["name"] != created.Name || label["resource_type"] != "skill" {+ t.Fatalf("ListSkills: unexpected attached label: %+v", label)+ }++ unlabeled, ok := byID[unlabeledID]+ if !ok {+ t.Fatalf("ListSkills: unlabeled skill %s not in response", unlabeledID)+ }+ empty, ok := unlabeled["labels"].([]any)+ if !ok || len(empty) != 0 {+ t.Fatalf("ListSkills: unlabeled skill expected labels: [], got: %v", unlabeled["labels"])+ }+}