Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(skills): update imported skills from their source (#6847)
Guillaume147cd8d84f4a
diff --git a/apps/docs/content/docs/skills.ja.mdx b/apps/docs/content/docs/skills.ja.mdxindex 1c48f5b387..b990a4464b 100644--- a/apps/docs/content/docs/skills.ja.mdx+++ b/apps/docs/content/docs/skills.ja.mdx@@ -35,7 +35,22 @@ CLI では、`.skill` や `.zip` ファイルからもインポートできまmultica skill import --file ./review-helper.skill```-インポート時にワークスペースへ同名のスキルがすでにある場合は、インポートの中止、既存内容の上書き、新しい名前での保存、スキップのいずれかを選べます。インポートによる上書きができるのは、そのスキルの作成者本人だけです。ワークスペースの `admin` は、アプリ内でスキルを編集できても、インポートで上書きすることはできません。+インポート時にワークスペースへ同名のスキルがすでにある場合は、インポートの中止、既存内容の上書き、新しい名前での保存、スキップのいずれかを選べます。インポートによる上書きができるのは、そのスキルの作成者本人だけです。ワークスペースの `admin` は、アプリ内でスキルを編集できても、インポートで上書きすることはできません。すでにワークスペースにあるスキルへ新しいバージョンを取り込むには、代わりに[インポート済みスキルの更新](#インポート済みスキルの更新)を使ってください。++## インポート済みスキルの更新++GitHub・ClawHub・Skills.sh からインポートしたスキルは、そのソースへの参照を保持しています。最新バージョンを取り込むには、スキルページの**更新**ボタン(または一覧の行メニューの「ソースから更新」)か、CLI を使います:++```bash+multica skill refresh <skill-id>+```++スキルはソースから再ダウンロードされ、その場で置き換えられます:++- **保持されるもの**:スキルの同一性 —— エージェントへの割り当て、ラベル、作成者、作成日時。エージェントが再追加する必要はありません。+- **置き換えられるもの**:名前(ソース側で改名された場合はそれに従います)、説明、`SKILL.md`、すべての補助ファイル。スキルへのローカル編集は上書きされます。++ソースから更新できるのは、スキルの作成者とワークスペースの `owner`・`admin` です。手動で作成したスキル、アーカイブファイルからインポートしたスキル、ランタイムからコピーしたスキルにはホストされたソースがないため、この方法では更新できません。再インポートしてください。## スキルの内容diff --git a/apps/docs/content/docs/skills.ko.mdx b/apps/docs/content/docs/skills.ko.mdxindex 4dcdd162bb..e8aa6e3534 100644--- a/apps/docs/content/docs/skills.ko.mdx+++ b/apps/docs/content/docs/skills.ko.mdx@@ -35,7 +35,22 @@ CLI에서는 `.skill` 또는 `.zip` 파일에서도 가져올 수 있습니다.multica skill import --file ./review-helper.skill```-가져올 때 워크스페이스에 같은 이름의 스킬이 이미 있으면 가져오기를 중단하거나, 기존 내용을 덮어쓰거나, 새 이름으로 저장하거나, 건너뛸 수 있습니다. 가져오기를 통한 덮어쓰기는 해당 스킬의 생성자만 할 수 있습니다. 워크스페이스 `admin`이 앱 안에서 수정할 수 있더라도 가져오기로는 덮어쓸 수 없습니다.+가져올 때 워크스페이스에 같은 이름의 스킬이 이미 있으면 가져오기를 중단하거나, 기존 내용을 덮어쓰거나, 새 이름으로 저장하거나, 건너뛸 수 있습니다. 가져오기를 통한 덮어쓰기는 해당 스킬의 생성자만 할 수 있습니다. 워크스페이스 `admin`이 앱 안에서 수정할 수 있더라도 가져오기로는 덮어쓸 수 없습니다. 워크스페이스에 이미 있는 스킬의 새 버전을 받으려면 [가져온 스킬 업데이트](#가져온-스킬-업데이트)를 사용하세요.++## 가져온 스킬 업데이트++GitHub, ClawHub, Skills.sh에서 가져온 스킬은 소스에 대한 참조를 유지합니다. 최신 버전을 받으려면 스킬 페이지의 **업데이트** 버튼(또는 목록 행 메뉴의 "소스에서 업데이트")을 사용하거나 CLI를 사용하세요:++```bash+multica skill refresh <skill-id>+```++스킬은 소스에서 다시 다운로드되어 그 자리에서 교체됩니다:++- **유지되는 것**: 스킬의 정체성 — 에이전트 할당, 라벨, 생성자, 생성 시각. 에이전트가 다시 추가할 필요가 없습니다.+- **교체되는 것**: 이름(소스에서 이름이 바뀌면 따라감), 설명, `SKILL.md`, 모든 지원 파일. 스킬에 대한 로컬 편집 내용은 덮어쓰기됩니다.++스킬의 생성자와 워크스페이스 `owner`, `admin`이 소스에서 업데이트할 수 있습니다. 수동으로 만들었거나, 압축 파일에서 가져왔거나, 런타임에서 복사한 스킬은 호스팅된 소스가 없어 이 방법으로 업데이트할 수 없습니다. 다시 가져오세요.## 스킬 내용diff --git a/apps/docs/content/docs/skills.mdx b/apps/docs/content/docs/skills.mdxindex 5ad9a0d999..5c958c55c3 100644--- a/apps/docs/content/docs/skills.mdx+++ b/apps/docs/content/docs/skills.mdx@@ -35,7 +35,22 @@ With the CLI, you can also import from a `.skill` or `.zip` file:multica skill import --file ./review-helper.skill```-If a skill with the same name already exists in the workspace, the import can stop, overwrite the existing content, save under a new name, or skip. Overwriting through import is limited to the skill's creator; a workspace `admin` who can edit the skill in the app still cannot overwrite it via import.+If a skill with the same name already exists in the workspace, the import can stop, overwrite the existing content, save under a new name, or skip. Overwriting through import is limited to the skill's creator; a workspace `admin` who can edit the skill in the app still cannot overwrite it via import. To pull a newer version of a skill that is already in the workspace, use [Updating an imported skill](#updating-an-imported-skill) instead.++## Updating an imported skill++A skill imported from GitHub, ClawHub, or Skills.sh keeps a reference to its source. To pull the latest version, use **Update** on the skill page (or "Update from source" in the list's row menu), or the CLI:++```bash+multica skill refresh <skill-id>+```++The skill is re-downloaded from its source and replaced in place:++- **Preserved**: the skill's identity — agent assignments, labels, creator, and creation date. Agents keep the skill without re-adding it.+- **Replaced**: name (if the source renamed it), description, `SKILL.md`, and all supporting files. Local edits to the skill are overwritten.++The skill's creator and workspace `owner`s / `admin`s can update from source. Skills created manually, imported from an archive file, or copied from a runtime have no hosted source and cannot be updated this way — re-import them instead.## Skill contentsdiff --git a/apps/docs/content/docs/skills.zh.mdx b/apps/docs/content/docs/skills.zh.mdxindex 86554b0b91..087cf506af 100644--- a/apps/docs/content/docs/skills.zh.mdx+++ b/apps/docs/content/docs/skills.zh.mdx@@ -35,7 +35,22 @@ Skill 是工作区中可以复用的一组工作方法。它以 `SKILL.md` 为multica skill import --file ./review-helper.skill```-导入时如果工作区已经存在同名 skill,可以停止导入、覆盖原内容、使用新名称保存,或跳过。通过导入覆盖仅限该 skill 的创建者本人;工作区 `admin` 即使可以在应用内编辑它,也不能用导入的方式覆盖。+导入时如果工作区已经存在同名 skill,可以停止导入、覆盖原内容、使用新名称保存,或跳过。通过导入覆盖仅限该 skill 的创建者本人;工作区 `admin` 即使可以在应用内编辑它,也不能用导入的方式覆盖。要为已在工作区里的 skill 拉取新版本,请改用[更新已导入的 skill](#更新已导入的-skill)。++## 更新已导入的 skill++从 GitHub、ClawHub 或 Skills.sh 导入的 skill 会记住它的来源。要拉取最新版本,在 skill 页面点击**更新**(或在列表行菜单里选「从来源更新」),也可以用 CLI:++```bash+multica skill refresh <skill-id>+```++Skill 会从来源重新下载并就地替换:++- **保留**:skill 的身份 —— 智能体分配、标签、创建者和创建时间。智能体无需重新添加。+- **替换**:名称(来源改名时跟随)、描述、`SKILL.md` 和全部支持文件。对 skill 的本地修改会被覆盖。++Skill 的创建者以及工作区 `owner`、`admin` 都可以从来源更新。手动创建、从压缩包导入、或从运行时复制的 skill 没有托管来源,无法这样更新 —— 请重新导入。## Skill 的内容diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 33c486be60..133130c523 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1989,3 +1989,82 @@ describe("ApiClient startMikaOnboarding", () => {).resolves.toEqual({ started: false });});});++describe("ApiClient refreshSkill response schema", () => {+ const validSkill = {+ id: "skill-1",+ workspace_id: "ws-1",+ name: "review-helper",+ description: "refreshed",+ content: "# refreshed",+ config: { origin: { type: "github", source_url: "https://github.com/acme/skills" } },+ created_by: "user-1",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-02T00:00:00Z",+ files: [+ {+ id: "file-1",+ skill_id: "skill-1",+ path: "ref.md",+ content: "ref",+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-02T00:00:00Z",+ },+ ],+ };++ it("parses a valid refreshed skill", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(validSkill), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ const result = await new ApiClient("https://api.example.test").refreshSkill("skill-1");+ expect(result).toMatchObject({+ id: "skill-1",+ name: "review-helper",+ files: [{ path: "ref.md" }],+ });+ });++ it("falls back to the empty skill when the response is malformed", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ skill: 42 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ const result = await new ApiClient("https://api.example.test").refreshSkill("skill-1");+ expect(result).toMatchObject({ id: "", name: "", files: [] });+ });++ it("defaults optional fields the server may omit", async () => {+ const { description, content, files, ...minimal } = validSkill;+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(minimal), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ const result = await new ApiClient("https://api.example.test").refreshSkill("skill-1");+ expect(result).toMatchObject({+ id: "skill-1",+ description: "",+ content: "",+ files: [],+ });+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 0d7eaca1d8..2a8e32556c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -338,6 +338,8 @@ import {EMPTY_LIST_GITHUB_REPOSITORIES_RESPONSE,RuntimeModelListRequestSchema,MALFORMED_RUNTIME_MODEL_LIST_REQUEST,+ SkillSchema,+ EMPTY_SKILL,IssueViewSchema,IssueViewListSchema,IssueViewPreferenceSchema,@@ -2225,6 +2227,18 @@ export class ApiClient {});}+ // Re-downloads the skill from its stored config.origin source, replacing+ // name/description/content/files in place while preserving the skill id and+ // its agent bindings.+ async refreshSkill(id: string): Promise<Skill> {+ const raw = await this.fetch<unknown>(`/api/skills/${id}/refresh`, {+ method: "POST",+ });+ return parseWithFallback(raw, SkillSchema, EMPTY_SKILL, {+ endpoint: "POST /api/skills/:id/refresh",+ });+ }+async listAgentSkills(agentId: string): Promise<SkillSummary[]> {return this.fetch(`/api/agents/${agentId}/skills`);}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 276613904e..0194432bf7 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -53,6 +53,7 @@ import type {RuntimeModelListRequest,SearchIssuesResponse,SearchProjectsResponse,+ Skill,Squad,TimelineEntry,User,@@ -2194,3 +2195,41 @@ export const EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE: RedeemWecomBindingTokenRinstallation_id: "",wecom_user_id: "",};++// Skills. Introduced for `POST /api/skills/:id/refresh` (update a skill from+// its imported source). `config` stays a loose record: the server owns the+// `origin` provenance shape and may extend it freely.+export const SkillFileSchema = z.object({+ id: z.string(),+ skill_id: z.string(),+ path: z.string(),+ content: z.string().optional().default(""),+ created_at: z.string().optional().default(""),+ updated_at: z.string().optional().default(""),+}).loose();++export const SkillSchema = 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([]),+}).loose();++export const EMPTY_SKILL: Skill = {+ id: "",+ workspace_id: "",+ name: "",+ description: "",+ content: "",+ config: {},+ created_by: null,+ created_at: "",+ updated_at: "",+ files: [],+};diff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex 65972377f4..da15a03d6c 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -67,6 +67,7 @@"actions": {"row_menu": "Actions","add_to_agent": "Add to agent",+ "refresh": "Update from source","my_agents": "My agents","other_agents": "Other agents","no_agents": "No agents available",@@ -145,6 +146,23 @@"toast_save_failed": "Failed to save skill","toast_deleted": "Skill deleted","toast_delete_failed": "Failed to delete skill",+ "refresh": {+ "button": "Update",+ "tooltip": "Re-download this skill from its source",+ "source_github": "GitHub",+ "source_skills_sh": "Skills.sh",+ "source_clawhub": "ClawHub",+ "toast_success": "Skill updated from {{source}}",+ "toast_failed": "Failed to update skill",+ "dialog": {+ "title": "Update from source?",+ "description": "This will re-download \"{{name}}\" from {{source}} and replace its name, description, SKILL.md, and files with the latest version.",+ "warning": "Local edits to this skill will be overwritten. Agent assignments, labels, and creator are preserved.",+ "cancel": "Cancel",+ "confirm": "Update",+ "refreshing": "Updating…"+ }+ },"delete_dialog": {"title": "Delete skill?","description_with_agents_one": "This will permanently delete \"{{name}}\" and remove it from {{count}} agent currently using it.",diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.jsonindex 4206a8ae8c..8d90c811dd 100644--- a/packages/views/locales/ja/skills.json+++ b/packages/views/locales/ja/skills.json@@ -67,6 +67,7 @@"actions": {"row_menu": "操作","add_to_agent": "エージェントに追加",+ "refresh": "ソースから更新","my_agents": "自分のエージェント","other_agents": "その他のエージェント","no_agents": "利用可能なエージェントがありません",@@ -139,6 +140,23 @@"toast_save_failed": "スキルを保存できませんでした","toast_deleted": "スキルを削除しました","toast_delete_failed": "スキルを削除できませんでした",+ "refresh": {+ "button": "更新",+ "tooltip": "ソースからスキルを再ダウンロードします",+ "source_github": "GitHub",+ "source_skills_sh": "Skills.sh",+ "source_clawhub": "ClawHub",+ "toast_success": "{{source}} からスキルを更新しました",+ "toast_failed": "スキルの更新に失敗しました",+ "dialog": {+ "title": "ソースから更新しますか?",+ "description": "「{{name}}」を {{source}} から再ダウンロードし、名前・説明・SKILL.md・ファイルを最新バージョンで置き換えます。",+ "warning": "このスキルへのローカル編集は上書きされます。エージェントへの割り当て、ラベル、作成者は保持されます。",+ "cancel": "キャンセル",+ "confirm": "更新",+ "refreshing": "更新中…"+ }+ },"delete_dialog": {"title": "スキルを削除しますか?","description_with_agents_other": "「{{name}}」を完全に削除し、現在使用中の {{count}} 個のエージェントから削除します。",diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.jsonindex e6f0ebdd4c..e5eacf7cd0 100644--- a/packages/views/locales/ko/skills.json+++ b/packages/views/locales/ko/skills.json@@ -67,6 +67,7 @@"actions": {"row_menu": "작업","add_to_agent": "에이전트에 추가",+ "refresh": "소스에서 업데이트","my_agents": "내 에이전트","other_agents": "다른 에이전트","no_agents": "사용 가능한 에이전트가 없습니다",@@ -139,6 +140,23 @@"toast_save_failed": "스킬을 저장하지 못했습니다","toast_deleted": "스킬을 삭제했습니다","toast_delete_failed": "스킬을 삭제하지 못했습니다",+ "refresh": {+ "button": "업데이트",+ "tooltip": "소스에서 스킬을 다시 다운로드합니다",+ "source_github": "GitHub",+ "source_skills_sh": "Skills.sh",+ "source_clawhub": "ClawHub",+ "toast_success": "{{source}}에서 스킬을 업데이트했습니다",+ "toast_failed": "스킬 업데이트에 실패했습니다",+ "dialog": {+ "title": "소스에서 업데이트할까요?",+ "description": "\"{{name}}\"을(를) {{source}}에서 다시 다운로드하여 이름, 설명, SKILL.md, 파일을 최신 버전으로 교체합니다.",+ "warning": "이 스킬에 대한 로컬 편집 내용은 덮어쓰기됩니다. 에이전트 할당, 라벨, 작성자는 유지됩니다.",+ "cancel": "취소",+ "confirm": "업데이트",+ "refreshing": "업데이트하는 중..."+ }+ },"delete_dialog": {"title": "스킬을 삭제할까요?","description_with_agents_other": "\"{{name}}\"을(를) 영구 삭제하고 현재 사용 중인 에이전트 {{count}}개에서 제거합니다.",diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex 911b480b90..f5d94cbee1 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -67,6 +67,7 @@"actions": {"row_menu": "操作","add_to_agent": "添加到智能体",+ "refresh": "从来源更新","my_agents": "我的智能体","other_agents": "其他智能体","no_agents": "暂无可用智能体",@@ -139,6 +140,23 @@"toast_save_failed": "保存 skill 失败","toast_deleted": "已删除 skill","toast_delete_failed": "删除 skill 失败",+ "refresh": {+ "button": "更新",+ "tooltip": "从来源重新下载这个 skill",+ "source_github": "GitHub",+ "source_skills_sh": "Skills.sh",+ "source_clawhub": "ClawHub",+ "toast_success": "已从 {{source}} 更新 skill",+ "toast_failed": "更新 skill 失败",+ "dialog": {+ "title": "从来源更新这个 skill?",+ "description": "将从 {{source}} 重新下载\"{{name}}\",并用最新版本替换它的名称、描述、SKILL.md 和文件。",+ "warning": "对这个 skill 的本地修改将被覆盖。智能体分配、标签和创建者保持不变。",+ "cancel": "取消",+ "confirm": "更新",+ "refreshing": "更新中..."+ }+ },"delete_dialog": {"title": "删除这个 skill?","description_with_agents_other": "将永久删除\"{{name}}\",并从当前正在使用它的 {{count}} 个智能体上移除。",diff --git a/packages/views/skills/components/refresh-skill-dialog.tsx b/packages/views/skills/components/refresh-skill-dialog.tsxnew file mode 100644index 0000000000..6defbc5fc8--- /dev/null+++ b/packages/views/skills/components/refresh-skill-dialog.tsx@@ -0,0 +1,135 @@+"use client";++import { useState } from "react";+import { Loader2, RotateCw } from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import type { Skill, SkillSummary } from "@multica/core/types";+import { api } from "@multica/core/api";+import {+ skillDetailOptions,+ workspaceKeys,+} from "@multica/core/workspace/queries";+import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { useT } from "../../i18n";+import type { OriginInfo } from "../lib/origin";++/** Human name of the hosted source a refresh re-downloads from. */+export function useRefreshSourceLabel(origin: OriginInfo | null): string {+ const { t } = useT("skills");+ if (origin?.type === "clawhub") return t(($) => $.detail.refresh.source_clawhub);+ if (origin?.type === "skills_sh") return t(($) => $.detail.refresh.source_skills_sh);+ return t(($) => $.detail.refresh.source_github);+}++/**+ * Confirm-and-run dialog for `POST /api/skills/:id/refresh`. The server+ * replaces name, description, SKILL.md, and the full file set with the fresh+ * upstream state while preserving the skill id — so agent assignments,+ * labels, and the creator survive. Local edits do not, hence the confirm.+ */+export function RefreshSkillDialog({+ skill,+ origin,+ wsId,+ open,+ onOpenChange,+ onRefreshed,+}: {+ skill: SkillSummary;+ origin: OriginInfo | null;+ wsId: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Fired after caches are updated; the detail page adopts the version here. */+ onRefreshed?: (updated: Skill) => void;+}) {+ const { t } = useT("skills");+ const qc = useQueryClient();+ const [refreshing, setRefreshing] = useState(false);+ const source = useRefreshSourceLabel(origin);++ const handleConfirm = async () => {+ setRefreshing(true);+ try {+ const updated = await api.refreshSkill(skill.id);+ if (updated.id === skill.id) {+ qc.setQueryData(skillDetailOptions(wsId, skill.id).queryKey, updated);+ } else {+ // Schema fallback (malformed response): drop the stale cache instead+ // of seeding it with the empty placeholder.+ qc.invalidateQueries({+ queryKey: skillDetailOptions(wsId, skill.id).queryKey,+ });+ }+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId), exact: true });+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ toast.success(t(($) => $.detail.refresh.toast_success, { source }));+ onOpenChange(false);+ if (updated.id === skill.id) onRefreshed?.(updated);+ } catch (e) {+ toast.error(+ e instanceof Error && e.message+ ? e.message+ : t(($) => $.detail.refresh.toast_failed),+ );+ } finally {+ setRefreshing(false);+ }+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(v) => {+ if (!refreshing) onOpenChange(v);+ }}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t(($) => $.detail.refresh.dialog.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.detail.refresh.dialog.description, {+ name: skill.name,+ source,+ })}+ </DialogDescription>+ </DialogHeader>+ <div className="rounded-md bg-warning/10 px-3 py-2 text-caption text-muted-foreground">+ {t(($) => $.detail.refresh.dialog.warning)}+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => onOpenChange(false)}+ disabled={refreshing}+ >+ {t(($) => $.detail.refresh.dialog.cancel)}+ </Button>+ <Button type="button" onClick={handleConfirm} disabled={refreshing}>+ {refreshing ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.detail.refresh.dialog.refreshing)}+ </>+ ) : (+ <>+ <RotateCw className="h-3 w-3" />+ {t(($) => $.detail.refresh.dialog.confirm)}+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsxindex 1fd390b81e..ff57162d52 100644--- a/packages/views/skills/components/skill-detail-page.tsx+++ b/packages/views/skills/components/skill-detail-page.tsx@@ -12,6 +12,7 @@ import {Lock,Pencil,Plus,+ RotateCw,Save,Trash2,UserPlus,@@ -69,13 +70,19 @@ import { BreadcrumbHeader } from "../../layout/breadcrumb-header";import { useCanEditSkill } from "../hooks/use-can-edit-skill";import { useSkillPermissions } from "@multica/core/permissions";import { CapabilityBanner } from "@multica/ui/components/common/capability-banner";-import { readOrigin, totalFileCount, type OriginInfo } from "../lib/origin";+import {+ isRefreshableOrigin,+ readOrigin,+ totalFileCount,+ type OriginInfo,+} from "../lib/origin";import { FileTree } from "./file-tree";import { FileViewer, isMarkdownPath, type FileMode } from "./file-viewer";import {AddToAgentDialog,type SkillActionsContext,} from "./skill-list-actions";+import { RefreshSkillDialog } from "./refresh-skill-dialog";import { useT } from "../../i18n";import { ResourceLabelPicker } from "../../labels/resource-label-picker";@@ -766,6 +773,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {const [saving, setSaving] = useState(false);const [deleting, setDeleting] = useState(false);const [confirmDelete, setConfirmDelete] = useState(false);+ const [confirmRefresh, setConfirmRefresh] = useState(false);const [showAddToAgents, setShowAddToAgents] = useState(false);const [addingFile, setAddingFile] = useState(false);const [conflictPending, setConflictPending] = useState(false);@@ -1138,6 +1146,26 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {{t(($) => $.detail.read_only)}</span>)}+ {canEdit && origin && isRefreshableOrigin(origin) && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="xs"+ className="gap-1"+ onClick={() => setConfirmRefresh(true)}+ >+ <RotateCw className="h-3 w-3" />+ {t(($) => $.detail.refresh.button)}+ </Button>+ }+ />+ <TooltipContent>+ {t(($) => $.detail.refresh.tooltip)}+ </TooltipContent>+ </Tooltip>+ )}<Buttonvariant="outline"size="xs"@@ -1389,6 +1417,17 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {open={showAddToAgents}onOpenChange={setShowAddToAgents}/>++ <RefreshSkillDialog+ skill={skill}+ origin={origin}+ wsId={wsId}+ open={confirmRefresh}+ onOpenChange={setConfirmRefresh}+ // Adopt explicitly: the user just confirmed the overwrite, so a dirty+ // draft must be replaced instead of tripping the conflict banner.+ onRefreshed={(updated) => adoptServerVersion(updated)}+ /></div>);}diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsxindex 1f2d3ab1d6..48fa828036 100644--- a/packages/views/skills/components/skill-list-actions.tsx+++ b/packages/views/skills/components/skill-list-actions.tsx@@ -8,6 +8,7 @@ import {Loader2,MoreHorizontal,Plus,+ RotateCw,Search,Trash2,X,@@ -51,6 +52,8 @@ import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { cn } from "@multica/ui/lib/utils";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";// Shared context the row kebab and the batch toolbar both need. Assembled@@ -527,8 +530,12 @@ export function SkillRowActions({const paths = useWorkspacePaths();const intentNavigate = useIntentNavigate();const [addOpen, setAddOpen] = useState(false);+ const [refreshOpen, setRefreshOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);+ const origin = readOrigin(row.skill);+ const canRefresh = row.canEdit && isRefreshableOrigin(origin);+return (<spanonClick={(e) => e.stopPropagation()}@@ -564,6 +571,12 @@ export function SkillRowActions({<Plus className="size-3.5" />{t(($) => $.actions.add_to_agent)}</DropdownMenuItem>+ {canRefresh && (+ <DropdownMenuItem onClick={() => setRefreshOpen(true)}>+ <RotateCw className="size-3.5" />+ {t(($) => $.actions.refresh)}+ </DropdownMenuItem>+ )}{row.canEdit && (<><DropdownMenuSeparator />@@ -584,6 +597,15 @@ export function SkillRowActions({open={addOpen}onOpenChange={setAddOpen}/>+ {canRefresh && (+ <RefreshSkillDialog+ skill={row.skill}+ origin={origin}+ wsId={ctx.wsId}+ open={refreshOpen}+ onOpenChange={setRefreshOpen}+ />+ )}<DeleteSkillsDialogrows={[row]}ctx={ctx}diff --git a/packages/views/skills/lib/origin.ts b/packages/views/skills/lib/origin.tsindex 46ca49b2bf..cbffcbd736 100644--- a/packages/views/skills/lib/origin.ts+++ b/packages/views/skills/lib/origin.ts@@ -12,6 +12,12 @@ export type OriginInfo = {runtime_id?: string;source_path?: string;source_url?: string;+ owner?: string;+ repo?: string;+ ref?: string;+ path?: string;+ skill?: string;+ slug?: string;};export function readOrigin(skill: SkillSummary): OriginInfo {@@ -25,6 +31,20 @@ export function readOrigin(skill: SkillSummary): OriginInfo {return { type: "manual" };}+/**+ * Whether the skill can be re-downloaded from where it was imported. Only+ * hosted sources qualify: runtime-local copies re-import through the daemon,+ * and manual / archive-uploaded skills have no upstream at all. The server+ * enforces the same rule on `POST /api/skills/:id/refresh`.+ */+export function isRefreshableOrigin(origin: OriginInfo): boolean {+ return (+ (origin.type === "github" || origin.type === "skills_sh" || origin.type === "clawhub") &&+ typeof origin.source_url === "string" &&+ origin.source_url.length > 0+ );+}+/*** SKILL.md is always present plus any additional attached files. Accepts a* `SkillSummary` because list endpoints don't return the `files` array — indiff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.goindex 0d62925fd3..953ff1eb27 100644--- a/server/cmd/multica/cmd_skill.go+++ b/server/cmd/multica/cmd_skill.go@@ -63,6 +63,13 @@ var skillImportCmd = &cobra.Command{RunE: runSkillImport,}+var skillRefreshCmd = &cobra.Command{+ Use: "refresh <id>",+ Short: "Re-download a skill from its imported source, preserving its id and agent assignments",+ Args: exactArgs(1),+ RunE: runSkillRefresh,+}+var skillSearchCmd = &cobra.Command{Use: "search <query>",Short: "Search for installable skills",@@ -105,6 +112,7 @@ func init() {skillCmd.AddCommand(skillUpdateCmd)skillCmd.AddCommand(skillDeleteCmd)skillCmd.AddCommand(skillImportCmd)+ skillCmd.AddCommand(skillRefreshCmd)skillCmd.AddCommand(skillSearchCmd)skillCmd.AddCommand(skillFilesCmd)@@ -145,6 +153,9 @@ func init() {skillImportCmd.Flags().String("on-conflict", "fail", "Conflict strategy when a skill with the same name exists: fail, overwrite, rename, or skip")skillImportCmd.Flags().String("output", "json", "Output format: table or json")+ // skill refresh+ skillRefreshCmd.Flags().String("output", "json", "Output format: table or json")+// skill searchskillSearchCmd.Flags().String("output", "json", "Output format: table or json")@@ -411,6 +422,31 @@ func runSkillDelete(cmd *cobra.Command, args []string) error {return nil}+func runSkillRefresh(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ // The server re-fetches the bundle from the upstream source before+ // answering; give it the same budget as an import (server-side cap: 45s).+ ctx, cancel := context.WithTimeout(context.Background(), cli.AtLeastAPITimeout(60*time.Second))+ defer cancel()++ var result map[string]any+ if err := client.PostJSON(ctx, "/api/skills/"+args[0]+"/refresh", map[string]any{}, &result); err != nil {+ return fmt.Errorf("refresh skill: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, result)+ }++ fmt.Printf("Skill updated from source: %s (%s)\n", strVal(result, "name"), strVal(result, "id"))+ return nil+}+func runSkillImport(cmd *cobra.Command, _ []string) error {client, err := newAPIClient(cmd)if err != nil {diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.goindex aedd39a74a..b0e0e4855e 100644--- a/server/cmd/multica/cmd_skill_test.go+++ b/server/cmd/multica/cmd_skill_test.go@@ -460,3 +460,85 @@ func TestRunSkillInlineEmptyContentKeepsExistingBehavior(t *testing.T) {t.Fatalf("upsert inline empty error = %v", err)}}++func TestRunSkillRefreshPostsToRefreshEndpointAndPrintsTable(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")++ 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/skills/skill-123/refresh" {+ t.Fatalf("path = %q, want /api/skills/skill-123/refresh", r.URL.Path)+ }+ if r.Header.Get("X-Workspace-ID") != "workspace-123" {+ t.Fatalf("X-Workspace-ID = %q, want workspace-123", r.Header.Get("X-Workspace-ID"))+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": "skill-123",+ "name": "review-helper",+ "description": "refreshed",+ "content": "# refreshed",+ "files": []any{},+ })+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := &cobra.Command{Use: "refresh"}+ cmd.Flags().String("server-url", "", "")+ cmd.Flags().String("workspace-id", "", "")+ cmd.Flags().String("profile", "", "")+ cmd.Flags().String("output", "table", "")++ out, err := captureStdout(t, func() error {+ return runSkillRefresh(cmd, []string{"skill-123"})+ })+ if err != nil {+ t.Fatalf("runSkillRefresh: %v", err)+ }+ if !strings.Contains(out, "review-helper") || !strings.Contains(out, "skill-123") {+ t.Fatalf("table output %q must contain skill name and id", out)+ }+}++func TestRunSkillRefreshJsonPrintsSkill(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "id": "skill-123",+ "name": "review-helper",+ })+ }))+ defer srv.Close()+ t.Setenv("MULTICA_SERVER_URL", srv.URL)++ cmd := &cobra.Command{Use: "refresh"}+ cmd.Flags().String("server-url", "", "")+ cmd.Flags().String("workspace-id", "", "")+ cmd.Flags().String("profile", "", "")+ cmd.Flags().String("output", "json", "")++ out, err := captureStdout(t, func() error {+ return runSkillRefresh(cmd, []string{"skill-123"})+ })+ if err != nil {+ t.Fatalf("runSkillRefresh: %v", err)+ }+ var got map[string]any+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("decode stdout JSON %q: %v", out, err)+ }+ if got["id"] != "skill-123" || got["name"] != "review-helper" {+ t.Fatalf("got = %#v", got)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f0969bf372..619a93ccf8 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1595,6 +1595,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/", h.GetSkill)r.Put("/", h.UpdateSkill)r.Delete("/", h.DeleteSkill)+ r.Post("/refresh", h.RefreshSkill)r.Get("/labels", h.ListLabelsForSkill)r.Post("/labels", h.AttachLabelToSkill)r.Delete("/labels/{labelId}", h.DetachLabelFromSkill)diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex 9f4119f9bd..312745e972 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -2252,12 +2252,9 @@ func importFetchErrorResponse(ctx context.Context, err error) (int, string) {return http.StatusBadGateway, err.Error()}-// finishSkillImport runs the shared tail of every skill import — whether the-// bundle came from a hosted URL or an uploaded archive (.skill / .zip). It maps-// the extracted files onto CreateSkillFileRequest, records provenance into-// config.origin, and creates the skill, routing same-name collisions through-// the on_conflict strategy.-func (h *Handler) finishSkillImport(w http.ResponseWriter, r *http.Request, workspaceID string, workspaceUUID, creatorUUID pgtype.UUID, creatorID, strategy string, structuredResult bool, imported *importedSkill) {+// importedSkillFileRequests maps a fetched bundle's supporting files onto+// CreateSkillFileRequest, dropping entries whose path fails validateFilePath.+func importedSkillFileRequests(imported *importedSkill) []CreateSkillFileRequest {files := make([]CreateSkillFileRequest, 0, len(imported.files))for _, f := range imported.files {if !validateFilePath(f.path) {@@ -2268,6 +2265,16 @@ func (h *Handler) finishSkillImport(w http.ResponseWriter, r *http.Request, workContent: f.content,})}+ return files+}++// finishSkillImport runs the shared tail of every skill import — whether the+// bundle came from a hosted URL or an uploaded archive (.skill / .zip). It maps+// the extracted files onto CreateSkillFileRequest, records provenance into+// config.origin, and creates the skill, routing same-name collisions through+// the on_conflict strategy.+func (h *Handler) finishSkillImport(w http.ResponseWriter, r *http.Request, workspaceID string, workspaceUUID, creatorUUID pgtype.UUID, creatorID, strategy string, structuredResult bool, imported *importedSkill) {+ files := importedSkillFileRequests(imported)// Persist provenance into skill.config.origin so list/detail UI can show// "Imported from GitHub / ClawHub / Skills.sh" and link back to the source.diff --git a/server/internal/handler/skill_create.go b/server/internal/handler/skill_create.goindex ab0c467869..dc5cda5646 100644--- a/server/internal/handler/skill_create.go+++ b/server/internal/handler/skill_create.go@@ -101,6 +101,7 @@ var (errSkillOverwriteNotFound = errors.New("target skill not found")errSkillOverwriteForbidden = errors.New("not permitted to overwrite target skill")errSkillOverwriteNameMismatch = errors.New("target skill name does not match the imported skill")+ errSkillOverwriteNameConflict = errors.New("another skill in the workspace already has the imported name"))type skillOverwriteInput struct {@@ -112,10 +113,17 @@ type skillOverwriteInput struct {// different skill than the one the conflict dialog showed the user. The// caller passes the sanitized effective import name.ExpectedName string- Description string- Content string- Config any- Files []CreateSkillFileRequest+ // NewName, when non-empty, renames the target to the imported skill's name.+ // A collision with another skill in the workspace (UNIQUE(workspace_id,+ // name)) fails the whole overwrite with errSkillOverwriteNameConflict.+ NewName string+ // AllowOverwrite overrides the in-tx permission recheck. Nil keeps the+ // default creator-only policy (canOverwriteSkillByLocalImport).+ AllowOverwrite func(userID string, skill db.Skill) bool+ Description string+ Content string+ Config any+ Files []CreateSkillFileRequest}// overwriteSkillWithFiles re-imports a bundle onto an existing skill in a single@@ -157,7 +165,11 @@ func (h *Handler) overwriteSkillWithFiles(ctx context.Context, input skillOverwr}return SkillWithFilesResponse{}, err}- if !canOverwriteSkillByLocalImport(input.UserID, existing) {+ allowOverwrite := input.AllowOverwrite+ if allowOverwrite == nil {+ allowOverwrite = canOverwriteSkillByLocalImport+ }+ if !allowOverwrite(input.UserID, existing) {return SkillWithFilesResponse{}, errSkillOverwriteForbidden}// The overwrite is keyed on target_skill_id, but the conflict the user@@ -168,11 +180,17 @@ func (h *Handler) overwriteSkillWithFiles(ctx context.Context, input skillOverwrreturn SkillWithFilesResponse{}, errSkillOverwriteNameMismatch}- // Name is intentionally left unset (COALESCE keeps the existing name): the- // overwrite targets the same-name skill, so preserving it avoids any- // unique-name churn.+ // Name stays unset by default (COALESCE keeps the existing name): the+ // import-conflict overwrite targets the same-name skill, so preserving it+ // avoids any unique-name churn. Refresh-from-source passes NewName to adopt+ // an upstream rename.+ var newName pgtype.Text+ if n := sanitizeNullBytes(input.NewName); n != "" && n != existing.Name {+ newName = pgtype.Text{String: n, Valid: true}+ }skill, err := qtx.UpdateSkill(ctx, db.UpdateSkillParams{ID: existing.ID,+ Name: newName,Description: pgtype.Text{String: sanitizeNullBytes(input.Description), Valid: true},Content: pgtype.Text{String: sanitizeNullBytes(input.Content), Valid: true},Config: config,@@ -184,6 +202,9 @@ func (h *Handler) overwriteSkillWithFiles(ctx context.Context, input skillOverwrif errors.Is(err, pgx.ErrNoRows) {return SkillWithFilesResponse{}, errSkillOverwriteNotFound}+ if newName.Valid && isUniqueViolation(err) {+ return SkillWithFilesResponse{}, errSkillOverwriteNameConflict+ }return SkillWithFilesResponse{}, err}diff --git a/server/internal/handler/skill_refresh.go b/server/internal/handler/skill_refresh.gonew file mode 100644index 0000000000..1e22ac3165--- /dev/null+++ b/server/internal/handler/skill_refresh.go@@ -0,0 +1,202 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "strings"+ "time"++ "github.com/go-chi/chi/v5"++ "github.com/multica-ai/multica/server/pkg/protocol"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// errSkillNotRefreshable marks a skill whose stored provenance cannot be+// re-fetched: manual skills, archive uploads (no origin), runtime-local+// copies, or a hand-edited origin whose source_url no longer matches its type.+var errSkillNotRefreshable = errors.New("this skill was not imported from a refreshable source (GitHub, skills.sh, or ClawHub)")++// skillOriginRef is the minimal provenance needed to re-run an import.+type skillOriginRef struct {+ Type string+ SourceURL string+}++// parseSkillOrigin extracts config.origin.{type,source_url} from a skill's+// JSONB config blob. ok is false when config has no decodable origin object.+func parseSkillOrigin(config []byte) (skillOriginRef, bool) {+ if len(config) == 0 {+ return skillOriginRef{}, false+ }+ var decoded struct {+ Origin struct {+ Type string `json:"type"`+ SourceURL string `json:"source_url"`+ } `json:"origin"`+ }+ if err := json.Unmarshal(config, &decoded); err != nil {+ return skillOriginRef{}, false+ }+ if decoded.Origin.Type == "" {+ return skillOriginRef{}, false+ }+ return skillOriginRef{+ Type: decoded.Origin.Type,+ SourceURL: strings.TrimSpace(decoded.Origin.SourceURL),+ }, true+}++// refreshableOriginSource maps a stored origin type onto the importSource its+// source_url must resolve to. ok is false for origins that cannot be+// re-fetched (manual, runtime_local, archive uploads).+func refreshableOriginSource(originType string) (importSource, bool) {+ switch originType {+ case "github":+ return sourceGitHub, true+ case "skills_sh":+ return sourceSkillsSh, true+ case "clawhub":+ return sourceClawHub, true+ default:+ return 0, false+ }+}++// fetchImportedSkillFromOrigin re-runs the import fetch for a skill's stored+// provenance. Eligibility is validated before any network call: a+// non-refreshable origin type, an empty source_url, or a source_url that does+// not resolve to the origin's own source (hand-edited config) all return+// errSkillNotRefreshable without contacting the upstream.+func fetchImportedSkillFromOrigin(ctx context.Context, httpClient *http.Client, origin skillOriginRef) (*importedSkill, error) {+ expected, ok := refreshableOriginSource(origin.Type)+ if !ok || origin.SourceURL == "" {+ return nil, errSkillNotRefreshable+ }+ source, normalized, err := detectImportSource(origin.SourceURL)+ if err != nil || source != expected {+ return nil, errSkillNotRefreshable+ }+ switch source {+ case sourceClawHub:+ return fetchFromClawHub(ctx, httpClient, normalized)+ case sourceSkillsSh:+ return fetchFromSkillsSh(ctx, httpClient, normalized)+ case sourceGitHub:+ return fetchFromGitHub(ctx, httpClient, normalized)+ }+ return nil, errSkillNotRefreshable+}++// mergeSkillConfigOrigin rewrites only the origin key of a skill's config,+// preserving any other keys a user may have set via the API or CLI. This is+// deliberately narrower than the import-overwrite path, which replaces config+// wholesale: refresh touches provenance, not user configuration.+func mergeSkillConfigOrigin(existingConfig []byte, origin map[string]any) map[string]any {+ config := map[string]any{}+ if len(existingConfig) > 0 {+ var decoded map[string]any+ if err := json.Unmarshal(existingConfig, &decoded); err == nil && decoded != nil {+ config = decoded+ }+ }+ if origin != nil {+ config["origin"] = origin+ }+ return config+}++// RefreshSkill re-downloads a skill from its stored config.origin source and+// overwrites the skill in place. Identity (id, created_by, created_at) and+// agent_skill bindings are preserved; name, description, content, files, and+// config.origin are replaced with the fresh upstream state. Unlike the+// creator-only import-overwrite path, refresh follows the canManageSkill+// policy (workspace owner/admin or creator): the source URL is pinned on the+// skill itself, so a refreshing admin cannot inject arbitrary content.+func (h *Handler) RefreshSkill(w http.ResponseWriter, r *http.Request) {+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ // Permission before any upstream fetch, so a forbidden caller cannot burn+ // the 45s fetch budget. Mirrors canManageSkill, keeping the member row to+ // re-check permission inside the overwrite transaction.+ workspaceID := uuidToString(skill.WorkspaceID)+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "skill not found", "owner", "admin", "member")+ if !ok {+ return+ }+ isAdmin := roleAllowed(member.Role, "owner", "admin")+ isCreator := skill.CreatedBy.Valid && uuidToString(skill.CreatedBy) == userID+ if !isAdmin && !isCreator {+ writeError(w, http.StatusForbidden, "only the skill creator or a workspace admin can update this skill from its source")+ return+ }++ origin, ok := parseSkillOrigin(skill.Config)+ if !ok {+ writeError(w, http.StatusUnprocessableEntity, errSkillNotRefreshable.Error())+ return+ }++ httpClient := &http.Client{Timeout: 30 * time.Second}+ ctx, cancel := context.WithTimeout(r.Context(), importFetchTimeout)+ defer cancel()++ imported, err := fetchImportedSkillFromOrigin(ctx, httpClient, origin)+ if err != nil {+ if errors.Is(err, errSkillNotRefreshable) {+ writeError(w, http.StatusUnprocessableEntity, err.Error())+ return+ }+ status, msg := importFetchErrorResponse(ctx, err)+ writeError(w, status, msg)+ return+ }++ newName := sanitizeNullBytes(imported.name)+ if newName != skill.Name {+ slog.Info("skill refresh: adopting upstream rename",+ "skill_id", uuidToString(skill.ID), "old_name", skill.Name, "new_name", newName)+ }++ resp, err := h.overwriteSkillWithFiles(r.Context(), skillOverwriteInput{+ WorkspaceID: skill.WorkspaceID,+ TargetSkillID: skill.ID,+ UserID: userID,+ NewName: newName,+ AllowOverwrite: func(uid string, s db.Skill) bool {+ return isAdmin || (s.CreatedBy.Valid && uuidToString(s.CreatedBy) == uid)+ },+ Description: imported.description,+ Content: imported.content,+ Config: mergeSkillConfigOrigin(skill.Config, imported.origin),+ Files: importedSkillFileRequests(imported),+ })+ if err != nil {+ switch {+ case errors.Is(err, errSkillOverwriteNotFound):+ writeError(w, http.StatusNotFound, "skill not found")+ case errors.Is(err, errSkillOverwriteForbidden):+ writeError(w, http.StatusForbidden, "only the skill creator or a workspace admin can update this skill from its source")+ case errors.Is(err, errSkillOverwriteNameConflict):+ writeError(w, http.StatusConflict, "a skill named \""+newName+"\" already exists in this workspace")+ default:+ writeError(w, http.StatusInternalServerError, "failed to update skill from source: "+err.Error())+ }+ return+ }++ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ h.publish(protocol.EventSkillUpdated, workspaceID, actorType, actorID, map[string]any{"skill": resp})+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/skill_refresh_test.go b/server/internal/handler/skill_refresh_test.gonew file mode 100644index 0000000000..a07a6ad227--- /dev/null+++ b/server/internal/handler/skill_refresh_test.go@@ -0,0 +1,468 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++// createImportTargetSkillWithConfig is createImportTargetSkill with an explicit+// config blob, used to seed provenance (config.origin) for refresh tests.+func createImportTargetSkillWithConfig(t *testing.T, name, ownerID, configJSON string, files map[string]string) string {+ t.Helper()++ var skillID string+ if err := testPool.QueryRow(context.Background(), `+ INSERT INTO skill (workspace_id, name, description, content, config, created_by)+ VALUES ($1, $2, 'original description', '# original', $3::jsonb, $4)+ RETURNING id+ `, testWorkspaceID, name, configJSON, ownerID).Scan(&skillID); err != nil {+ t.Fatalf("create target skill: %v", err)+ }+ for path, content := range files {+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO skill_file (skill_id, path, content) VALUES ($1, $2, $3)+ `, skillID, path, content); err != nil {+ t.Fatalf("create skill file: %v", err)+ }+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, skillID)+ })+ return skillID+}++// installClawHubFixture serves a complete successful ClawHub bundle for slug+// and swaps clawHubAPIBase to it. The returned counter tracks how many+// requests reached the fixture, letting tests assert that a rejected refresh+// never contacted the upstream.+func installClawHubFixture(t *testing.T, slug, displayName, summary string, files map[string]string) *int {+ t.Helper()++ requests := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests+++ switch {+ case r.URL.Path == "/api/v1/skills/"+slug:+ writeJSON(w, http.StatusOK, map[string]any{+ "skill": map[string]any{+ "slug": slug, "displayName": displayName, "summary": summary,+ "tags": map[string]string{"latest": "1.0.0"},+ },+ })+ case r.URL.Path == "/api/v1/skills/"+slug+"/versions/1.0.0":+ fileList := make([]map[string]any, 0, len(files))+ for p, c := range files {+ fileList = append(fileList, map[string]any{"path": p, "size": len(c)})+ }+ writeJSON(w, http.StatusOK, map[string]any{+ "version": map[string]any{"version": "1.0.0", "files": fileList},+ })+ case r.URL.Path == "/api/v1/skills/"+slug+"/file":+ if content, ok := files[r.URL.Query().Get("path")]; ok {+ w.Write([]byte(content))+ return+ }+ http.NotFound(w, r)+ default:+ http.NotFound(w, r)+ }+ }))+ prev := clawHubAPIBase+ clawHubAPIBase = srv.URL + "/api/v1"+ t.Cleanup(func() { clawHubAPIBase = prev; srv.Close() })+ return &requests+}++func clawhubOriginConfig(slug string) string {+ return fmt.Sprintf(`{"origin": {"type": "clawhub", "source_url": "https://clawhub.ai/acme/%s", "slug": "%s"}}`, slug, slug)+}++func doRefreshSkill(t *testing.T, userID, skillID string) *httptest.ResponseRecorder {+ t.Helper()++ w := httptest.NewRecorder()+ req := withURLParams(+ newRequestAsUser(userID, http.MethodPost, "/api/skills/"+skillID+"/refresh", nil),+ "id", skillID,+ )+ testHandler.RefreshSkill(w, req)+ return w+}++func skillCreatedAt(t *testing.T, skillID string) string {+ t.Helper()++ var createdAt string+ if err := testPool.QueryRow(context.Background(),+ `SELECT created_at::text FROM skill WHERE id = $1`, skillID).Scan(&createdAt); err != nil {+ t.Fatalf("get skill created_at: %v", err)+ }+ return createdAt+}++func skillFilePaths(t *testing.T, skillID string) map[string]bool {+ t.Helper()++ rows, err := testPool.Query(context.Background(),+ `SELECT path FROM skill_file WHERE skill_id = $1`, skillID)+ if err != nil {+ t.Fatalf("list skill files: %v", err)+ }+ defer rows.Close()+ paths := map[string]bool{}+ for rows.Next() {+ var p string+ if err := rows.Scan(&p); err != nil {+ t.Fatalf("scan skill file path: %v", err)+ }+ paths[p] = true+ }+ return paths+}++func TestRefreshSkill_UpdatesContentPreservingIdentityAndBindings(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ slug := fmt.Sprintf("refresh-keep-%d", time.Now().UnixNano())+ oldName := slug + "-old"+ newName := slug + "-renamed"+ // Custom config key alongside origin: refresh must preserve it (merge, not+ // wholesale replace).+ config := fmt.Sprintf(`{"custom_key": "keep-me", "origin": {"type": "clawhub", "source_url": "https://clawhub.ai/acme/%s", "slug": "%s"}}`, slug, slug)+ skillID := createImportTargetSkillWithConfig(t, oldName, testUserID, config, map[string]string{+ "prune.md": "should be removed",+ })+ bindAgentToSkill(t, skillID)+ createdAtBefore := skillCreatedAt(t, skillID)++ installClawHubFixture(t, slug, newName, "fresh summary", map[string]string{+ "SKILL.md": "# refreshed body",+ "new.md": "brand new file",+ })++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp SkillWithFilesResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }++ // Identity preserved.+ if resp.ID != skillID {+ t.Fatalf("refresh must preserve UUID: got %q, want %q", resp.ID, skillID)+ }+ if resp.CreatedBy == nil || *resp.CreatedBy != testUserID {+ t.Fatalf("created_by not preserved: %v", resp.CreatedBy)+ }+ if got := skillCreatedAt(t, skillID); got != createdAtBefore {+ t.Fatalf("created_at changed: %q -> %q", createdAtBefore, got)+ }+ if n := countAgentSkillBindings(t, skillID); n != 1 {+ t.Fatalf("expected agent binding to survive refresh, got %d", n)+ }++ // Upstream rename adopted; content and description replaced.+ if resp.Name != newName {+ t.Fatalf("name = %q, want upstream name %q", resp.Name, newName)+ }+ if n := countSkillsByName(t, oldName); n != 0 {+ t.Fatalf("old name must be gone after rename adoption, found %d", n)+ }+ if resp.Description != "fresh summary" {+ t.Fatalf("description = %q, want %q", resp.Description, "fresh summary")+ }+ if resp.Content != "# refreshed body" {+ t.Fatalf("content = %q, want refreshed body", resp.Content)+ }++ // Files fully replaced: prune.md gone, new.md present.+ paths := skillFilePaths(t, skillID)+ if paths["prune.md"] || !paths["new.md"] {+ t.Fatalf("files = %v, want new.md without prune.md", paths)+ }++ // Config merged: origin rewritten, custom key preserved.+ configMap, ok := resp.Config.(map[string]any)+ if !ok {+ t.Fatalf("config is not an object: %T", resp.Config)+ }+ if configMap["custom_key"] != "keep-me" {+ t.Fatalf("custom config key not preserved: %v", configMap)+ }+ origin, ok := configMap["origin"].(map[string]any)+ if !ok || origin["type"] != "clawhub" || origin["slug"] != slug {+ t.Fatalf("origin not rewritten from fresh fetch: %v", configMap["origin"])+ }+}++func TestRefreshSkill_UpstreamRenameCollisionReturns409(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ slug := fmt.Sprintf("refresh-collision-%d", time.Now().UnixNano())+ oldName := slug + "-old"+ takenName := slug + "-taken"+ skillID := createImportTargetSkillWithConfig(t, oldName, testUserID, clawhubOriginConfig(slug), nil)+ createImportTargetSkill(t, takenName, testUserID, nil)++ installClawHubFixture(t, slug, takenName, "incoming", map[string]string{"SKILL.md": "# incoming"})++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ }+ // Whole refresh rolled back: name, description, and content unchanged.+ name, desc, content, _ := getSkillRow(t, skillID)+ if name != oldName || desc != "original description" || content != "# original" {+ t.Fatalf("collision must not mutate the skill: name=%q desc=%q content=%q", name, desc, content)+ }+}++func TestRefreshSkill_AdminCanRefresh(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ // Skill created by a plain member; the caller (testUserID) is the+ // workspace owner. Refresh follows canManageSkill, so this must succeed —+ // unlike the creator-only import-overwrite path.+ creatorID := createRuntimeLocalSkillTestMember(t, "member")+ slug := fmt.Sprintf("refresh-admin-%d", time.Now().UnixNano())+ skillID := createImportTargetSkillWithConfig(t, slug, creatorID, clawhubOriginConfig(slug), nil)++ installClawHubFixture(t, slug, slug, "admin refreshed", map[string]string{"SKILL.md": "# refreshed"})++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ // Creator still preserved even when an admin refreshes.+ if _, desc, _, createdBy := getSkillRow(t, skillID); desc != "admin refreshed" || createdBy != creatorID {+ t.Fatalf("desc=%q createdBy=%q, want refreshed desc with original creator %q", desc, createdBy, creatorID)+ }+}++func TestRefreshSkill_PlainMemberNonCreatorForbidden(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ memberID := createRuntimeLocalSkillTestMember(t, "member")+ slug := fmt.Sprintf("refresh-forbidden-%d", time.Now().UnixNano())+ skillID := createImportTargetSkillWithConfig(t, slug, testUserID, clawhubOriginConfig(slug), nil)++ requests := installClawHubFixture(t, slug, slug, "incoming", map[string]string{"SKILL.md": "# incoming"})++ w := doRefreshSkill(t, memberID, skillID)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403, got %d: %s", w.Code, w.Body.String())+ }+ if _, desc, _, _ := getSkillRow(t, skillID); desc != "original description" {+ t.Fatalf("forbidden refresh must not mutate the skill, description = %q", desc)+ }+ // Permission is checked before the fetch: the upstream must never be hit.+ if *requests != 0 {+ t.Fatalf("forbidden refresh must not contact the upstream, got %d requests", *requests)+ }+}++func TestRefreshSkill_ManualSkillNotRefreshable(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ name := fmt.Sprintf("refresh-manual-%d", time.Now().UnixNano())+ skillID := createImportTargetSkill(t, name, testUserID, nil)++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusUnprocessableEntity {+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())+ }+ if _, desc, _, _ := getSkillRow(t, skillID); desc != "original description" {+ t.Fatalf("non-refreshable refresh must not mutate the skill, description = %q", desc)+ }+}++func TestRefreshSkill_RuntimeLocalOriginNotRefreshable(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ name := fmt.Sprintf("refresh-runtime-local-%d", time.Now().UnixNano())+ config := `{"origin": {"type": "runtime_local", "runtime_id": "r-1", "provider": "claude", "source_path": "~/.claude/skills/x"}}`+ skillID := createImportTargetSkillWithConfig(t, name, testUserID, config, nil)++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusUnprocessableEntity {+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())+ }+}++func TestRefreshSkill_OriginHostMismatchRejected(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ name := fmt.Sprintf("refresh-mismatch-%d", time.Now().UnixNano())+ // A hand-edited origin: claims github but points at clawhub. Must be+ // rejected without any fetch.+ config := `{"origin": {"type": "github", "source_url": "https://clawhub.ai/acme/x"}}`+ skillID := createImportTargetSkillWithConfig(t, name, testUserID, config, nil)++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusUnprocessableEntity {+ t.Fatalf("expected 422, got %d: %s", w.Code, w.Body.String())+ }+}++func TestRefreshSkill_UpstreamGoneReturns502(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ slug := fmt.Sprintf("refresh-gone-%d", time.Now().UnixNano())+ skillID := createImportTargetSkillWithConfig(t, slug, testUserID, clawhubOriginConfig(slug), nil)++ // Fixture knows no routes: the skill lookup 404s upstream.+ srv := httptest.NewServer(http.NotFoundHandler())+ prev := clawHubAPIBase+ clawHubAPIBase = srv.URL + "/api/v1"+ t.Cleanup(func() { clawHubAPIBase = prev; srv.Close() })++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusBadGateway {+ t.Fatalf("expected 502, got %d: %s", w.Code, w.Body.String())+ }+ if _, desc, _, _ := getSkillRow(t, skillID); desc != "original description" {+ t.Fatalf("failed refresh must not mutate the skill, description = %q", desc)+ }+}++func TestRefreshSkill_CapExceededReturns413(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ slug := fmt.Sprintf("refresh-cap-%d", time.Now().UnixNano())+ skillID := createImportTargetSkillWithConfig(t, slug, testUserID, clawhubOriginConfig(slug), nil)++ installClawHubFixture(t, slug, slug, "too big now", map[string]string{+ "SKILL.md": "# ok",+ "big.md": strings.Repeat("a", maxImportFileSize+1),+ })++ w := doRefreshSkill(t, testUserID, skillID)+ if w.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("expected 413, got %d: %s", w.Code, w.Body.String())+ }+ if _, desc, _, _ := getSkillRow(t, skillID); desc != "original description" {+ t.Fatalf("cap-exceeded refresh must not mutate the skill, description = %q", desc)+ }+}++func TestParseSkillOrigin(t *testing.T) {+ cases := []struct {+ name string+ config string+ wantOK bool+ want skillOriginRef+ }{+ {name: "nil config", config: "", wantOK: false},+ {name: "empty object", config: "{}", wantOK: false},+ {name: "origin not an object", config: `{"origin": "github"}`, wantOK: false},+ {name: "origin without type", config: `{"origin": {"source_url": "https://github.com/a/b"}}`, wantOK: false},+ {+ name: "origin without source_url",+ config: `{"origin": {"type": "github"}}`,+ wantOK: true,+ want: skillOriginRef{Type: "github", SourceURL: ""},+ },+ {+ name: "full origin with whitespace",+ config: `{"origin": {"type": "skills_sh", "source_url": " https://skills.sh/a/b/c "}}`,+ wantOK: true,+ want: skillOriginRef{Type: "skills_sh", SourceURL: "https://skills.sh/a/b/c"},+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ var raw []byte+ if tc.config != "" {+ raw = []byte(tc.config)+ }+ got, ok := parseSkillOrigin(raw)+ if ok != tc.wantOK {+ t.Fatalf("ok = %v, want %v", ok, tc.wantOK)+ }+ if ok && got != tc.want {+ t.Fatalf("origin = %+v, want %+v", got, tc.want)+ }+ })+ }+}++func TestFetchImportedSkillFromOrigin_RejectsNonRefreshable(t *testing.T) {+ client := &http.Client{}+ cases := []skillOriginRef{+ {Type: "manual", SourceURL: "https://github.com/a/b"},+ {Type: "runtime_local", SourceURL: ""},+ {Type: "github", SourceURL: ""},+ {Type: "github", SourceURL: "https://clawhub.ai/acme/x"}, // host mismatch+ {Type: "clawhub", SourceURL: "https://github.com/acme/x"}, // host mismatch+ {Type: "skills_sh", SourceURL: "https://example.com/a/b"}, // unsupported host+ }+ for _, origin := range cases {+ if _, err := fetchImportedSkillFromOrigin(t.Context(), client, origin); !errors.Is(err, errSkillNotRefreshable) {+ t.Fatalf("origin %+v: err = %v, want errSkillNotRefreshable", origin, err)+ }+ }+}++func TestFetchImportedSkillFromOrigin_GitHubDispatch(t *testing.T) {+ client, _ := newGitHubFixtureClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.Header.Get("X-Test-Original-Host") {+ case "api.github.com":+ switch r.URL.Path {+ case "/repos/acme/skills/commits/main":+ w.Write([]byte("deadbeef"))+ case "/repos/acme/skills/contents/foo":+ writeJSON(w, http.StatusOK, []githubContentEntry{})+ default:+ http.NotFound(w, r)+ }+ case "raw.githubusercontent.com":+ if r.URL.Path == "/acme/skills/main/foo/SKILL.md" {+ w.Write([]byte("---\nname: foo\ndescription: refreshed\n---\nbody"))+ return+ }+ http.NotFound(w, r)+ default:+ http.NotFound(w, r)+ }+ })++ origin := skillOriginRef{Type: "github", SourceURL: "https://github.com/acme/skills/tree/main/foo"}+ imported, err := fetchImportedSkillFromOrigin(t.Context(), client, origin)+ if err != nil {+ t.Fatalf("fetchImportedSkillFromOrigin: %v", err)+ }+ if imported.name != "foo" || imported.description != "refreshed" {+ t.Fatalf("imported = %q / %q, want foo / refreshed", imported.name, imported.description)+ }+ // The fresh origin re-records the re-resolved ref and path.+ if imported.origin["type"] != "github" || imported.origin["ref"] != "main" || imported.origin["path"] != "foo" {+ t.Fatalf("origin = %v, want github/main/foo", imported.origin)+ }+}diff --git a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.mdindex 14ae8492c4..436f8a9ffa 100644--- a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md+++ b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md@@ -234,6 +234,39 @@ Then report that the skill already exists and include its `id` / `name`. Do notretry in a loop, and do not create a second skill under a different name just tododge the conflict.+## Updating an already-imported skill: `multica skill refresh`++When the goal is to pull the latest version of a skill that is already in the+workspace, prefer `refresh` over re-typing the import URL:++```bash+multica skill refresh <skill-id> --output json+```++It sends `POST /api/skills/{id}/refresh` (empty body). The server re-downloads+the bundle from the provenance stored in the skill's `config.origin`+(`github`, `skills_sh`, or `clawhub` with its `source_url`) and overwrites the+skill in place:++- Preserved: skill ID, `created_by`, `created_at`, agent-skill bindings, and+ labels — agents keep the skill without re-adding it.+- Replaced: name (an upstream rename is adopted), description, `SKILL.md`+ content, provenance config, and the full supporting-file set.+- Permission: the skill's creator or a workspace `owner`/`admin` — broader than+ `import --on-conflict overwrite`, which stays creator-only.++The success response is the plain `SkillWithFilesResponse` (same shape as+`multica skill get`), not the import result envelope. Failure modes to report+instead of retrying in a loop:++- `422`: the skill has no refreshable provenance (created manually, imported+ from a local archive, or copied from a local runtime). Re-import instead.+- `409`: the upstream renamed the skill and another workspace skill already+ uses that name; nothing was changed.+- `403`: caller is neither the creator nor a workspace admin.+- `502` / `503` / `504` / `413`: upstream fetch failed (gone, unavailable,+ timed out, or now exceeds import caps); the skill is left untouched.+## Incorrect → correctIncorrect (bypasses Multica):diff --git a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.mdindex a475ed6e19..ac0e0de4d3 100644--- a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md+++ b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md@@ -120,6 +120,24 @@ that omit `on_conflict` still receive a bare `SkillWithFilesResponse`.| `runAgentSkillsSet` → `PUT .../skills` | `server/cmd/multica/cmd_agent.go:772`; PUT `:790` || CLI `agent skills list` | `server/cmd/multica/cmd_agent.go:740`; GET `:750` |+## Updating an imported skill (`POST /api/skills/{id}/refresh`)++| Behavior | File:line |+|---|---|+| `RefreshSkill` handler | `server/internal/handler/skill_refresh.go:120` |+| Route `r.Post("/refresh", h.RefreshSkill)` | `server/cmd/server/router.go:1594` |+| Reads stored provenance `config.origin.{type,source_url}` | `parseSkillOrigin`, `server/internal/handler/skill_refresh.go:32` |+| Refreshable origins are `github` / `skills_sh` / `clawhub` only | `refreshableOriginSource`, `server/internal/handler/skill_refresh.go:57` |+| Re-runs the matching import fetcher from the stored `source_url` | `fetchImportedSkillFromOrigin`, `server/internal/handler/skill_refresh.go:75` |+| Non-refreshable origin → 422 | `errSkillNotRefreshable`, `server/internal/handler/skill_refresh.go:22` |+| Permission: creator or workspace owner/admin, checked before the fetch | `server/internal/handler/skill_refresh.go:120` (body) — broader than import-overwrite's creator-only rule |+| Merges only `config.origin`, preserving other config keys | `mergeSkillConfigOrigin`, `server/internal/handler/skill_refresh.go:99` |+| In-place overwrite preserving id/creator/bindings, adopting upstream rename | `overwriteSkillWithFiles` with `NewName` + `AllowOverwrite`, `server/internal/handler/skill_create.go:119-122`, tx helper `:133` |+| Upstream rename colliding with another skill → 409 | `errSkillOverwriteNameConflict`, `server/internal/handler/skill_create.go:104` |+| Fetch failures map like import (413/502/503/504) | `importFetchErrorResponse` (grep in `server/internal/handler/skill.go`) |+| CLI `skill refresh <id>` def / runner | `server/cmd/multica/cmd_skill.go:66`, `runSkillRefresh` at `:425` |+| Handler tests | `server/internal/handler/skill_refresh_test.go` |+## Reserved primary-content filename (`SKILL.md`)| Behavior | File:line |