Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4066: feat(skills): skill version history and restore (#9632)
Multica Eve3faf996d92cb
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex cd77e7b40b..fe65ed34f1 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -2571,6 +2571,66 @@ describe("ApiClient refreshSkill response schema", () => {});});+describe("ApiClient skill version response schemas", () => {+ function stubJSON(body: unknown) {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+ }++ const summary = {+ id: "ver-2",+ skill_id: "skill-1",+ version: 2,+ name: "review-helper",+ source: "restore",+ restored_from_version: 1,+ created_by: "user-1",+ created_at: "2026-01-02T00:00:00Z",+ };++ it("parses the version list and maps unknown sources to update", async () => {+ stubJSON([summary, { ...summary, id: "ver-1", version: 1, source: "future-kind" }]);+ const result = await new ApiClient("https://api.example.test").listSkillVersions("skill-1");+ expect(result.map((v) => [v.version, v.source])).toEqual([+ [2, "restore"],+ [1, "update"],+ ]);+ });++ it("falls back to an empty list when the response is malformed", async () => {+ stubJSON({ versions: 42 });+ const result = await new ApiClient("https://api.example.test").listSkillVersions("skill-1");+ expect(result).toEqual([]);+ });++ it("parses a version snapshot and defaults omitted fields", async () => {+ const fetchMock = stubJSON({ ...summary, content: "# v2", files: [{ path: "a.md" }] });+ const result = await new ApiClient("https://api.example.test").getSkillVersion("skill-1", 2);+ expect(String(fetchMock.mock.calls[0]?.[0])).toContain("/api/skills/skill-1/versions/2");+ expect(result).toMatchObject({+ version: 2,+ description: "",+ content: "# v2",+ files: [{ path: "a.md", content: "" }],+ });+ });++ it("restores through POST and falls back to the empty skill on a malformed body", async () => {+ const fetchMock = stubJSON({ skill: 42 });+ const result = await new ApiClient("https://api.example.test").restoreSkillVersion("skill-1", 1);+ const [url, init] = fetchMock.mock.calls[0] ?? [];+ expect(String(url)).toContain("/api/skills/skill-1/versions/1/restore");+ expect((init as RequestInit | undefined)?.method).toBe("POST");+ expect(result).toMatchObject({ id: "", files: [] });+ });+});+describe("ApiClient workspace MCP servers", () => {function stubJSON(body: unknown) {const fetchMock = vi.fn().mockResolvedValue(diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 71efde625e..0961eb8a79 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -69,6 +69,8 @@ import type {User,Skill,SkillSummary,+ SkillVersion,+ SkillVersionSummary,CreateSkillRequest,UpdateSkillRequest,SetAgentSkillsRequest,@@ -471,6 +473,10 @@ import {EMPTY_SKILL,SkillSummaryListSchema,EMPTY_SKILL_SUMMARY_LIST,+ SkillVersionSchema,+ EMPTY_SKILL_VERSION,+ SkillVersionSummaryListSchema,+ EMPTY_SKILL_VERSION_SUMMARY_LIST,SkillImportResultSchema,EMPTY_SKILL_IMPORT_RESULT,IssueViewSchema,@@ -3684,6 +3690,39 @@ export class ApiClient {});}+ // Content history, newest first. Metadata only; fetch one version for its+ // snapshot.+ async listSkillVersions(skillId: string): Promise<SkillVersionSummary[]> {+ const raw = await this.fetch<unknown>(`/api/skills/${skillId}/versions`);+ return parseWithFallback(+ raw,+ SkillVersionSummaryListSchema,+ EMPTY_SKILL_VERSION_SUMMARY_LIST,+ { endpoint: "GET /api/skills/:id/versions" },+ );+ }++ async getSkillVersion(skillId: string, version: number): Promise<SkillVersion> {+ const raw = await this.fetch<unknown>(+ `/api/skills/${skillId}/versions/${version}`,+ );+ return parseWithFallback(raw, SkillVersionSchema, EMPTY_SKILL_VERSION, {+ endpoint: "GET /api/skills/:id/versions/:version",+ });+ }++ // Writes the version's snapshot back to the skill. The server records the+ // result as a new latest version.+ async restoreSkillVersion(skillId: string, version: number): Promise<Skill> {+ const raw = await this.fetch<unknown>(+ `/api/skills/${skillId}/versions/${version}/restore`,+ { method: "POST" },+ );+ return parseWithFallback(raw, SkillSchema, EMPTY_SKILL, {+ endpoint: "POST /api/skills/:id/versions/:version/restore",+ });+ }+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 05ff2bde3e..2f2f967a5f 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -92,6 +92,8 @@ import type {Skill,SkillImportResult,SkillSummary,+ SkillVersion,+ SkillVersionSummary,Squad,TimelineEntry,User,@@ -3684,6 +3686,55 @@ export const EMPTY_SKILL: Skill = {export const SkillSummaryListSchema = z.array(SkillSummarySchema).default([]);+const SKILL_VERSION_SOURCES = [+ "baseline",+ "create",+ "update",+ "import",+ "refresh",+ "restore",+] as const;++export const SkillVersionSummarySchema = z.object({+ id: z.string(),+ skill_id: z.string(),+ version: z.number(),+ name: z.string().optional().default(""),+ source: z.enum(SKILL_VERSION_SOURCES).catch("update"),+ restored_from_version: z.number().nullable().optional().default(null),+ created_by: z.string().nullable().optional().default(null),+ created_at: z.string().optional().default(""),+}).loose();++export const SkillVersionSummaryListSchema = z+ .array(SkillVersionSummarySchema)+ .default([]);++export const EMPTY_SKILL_VERSION_SUMMARY_LIST: SkillVersionSummary[] = [];++export const SkillVersionSchema = SkillVersionSummarySchema.extend({+ description: z.string().optional().default(""),+ content: z.string().optional().default(""),+ files: z+ .array(z.object({ path: z.string(), content: z.string().optional().default("") }).loose())+ .optional()+ .default([]),+}).loose();++export const EMPTY_SKILL_VERSION: SkillVersion = {+ id: "",+ skill_id: "",+ version: 0,+ name: "",+ source: "update",+ restored_from_version: null,+ created_by: null,+ created_at: "",+ description: "",+ content: "",+ files: [],+};+export const EMPTY_SKILL_SUMMARY_LIST: SkillSummary[] = [];export const SkillImportExistingSkillSchema = z.object({diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex a569f8b2ea..0565b051ad 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -906,6 +906,32 @@ export interface SkillFile {updated_at: string;}+/** How a skill reached a version. Unknown server values fall back to "update". */+export type SkillVersionSource =+ | "baseline"+ | "create"+ | "update"+ | "import"+ | "refresh"+ | "restore";++export interface SkillVersionSummary {+ id: string;+ skill_id: string;+ version: number;+ name: string;+ source: SkillVersionSource;+ restored_from_version: number | null;+ created_by: string | null;+ created_at: string;+}++export interface SkillVersion extends SkillVersionSummary {+ description: string;+ content: string;+ files: { path: string; content: string }[];+}+export interface CreateSkillRequest {name: string;description?: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex cc2d90d352..8fef55fb63 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -72,6 +72,9 @@ export type {DisabledRuntimeSkill,SetAgentRuntimeSkillEnabledRequest,SkillFile,+ SkillVersion,+ SkillVersionSource,+ SkillVersionSummary,CreateSkillRequest,SkillImportResult,UpdateSkillRequest,diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex fac21d06f8..b539f89ec9 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -134,6 +134,30 @@ export function skillDetailOptions(wsId: string, skillId: string) {});}+// Nested under the skill detail key so skill realtime events, which+// invalidate the workspace skills prefix, refresh history too.+export function skillVersionsOptions(wsId: string, skillId: string) {+ return queryOptions({+ queryKey: [...workspaceKeys.skills(wsId), skillId, "versions"] as const,+ queryFn: () => api.listSkillVersions(skillId),+ enabled: !!skillId,+ });+}++// A version never changes once written.+export function skillVersionDetailOptions(+ wsId: string,+ skillId: string,+ version: number | null,+) {+ return queryOptions({+ queryKey: [...workspaceKeys.skills(wsId), skillId, "versions", version] as const,+ queryFn: () => api.getSkillVersion(skillId, version as number),+ enabled: !!skillId && version !== null,+ staleTime: Infinity,+ });+}+/*** Builds a `Map<skillId, Agent[]>` from the cached agent list. The server* already returns each agent with its full skill list inline, so no extradiff --git a/packages/views/locales/en/skills.json b/packages/views/locales/en/skills.jsonindex 1340f1e94f..e3eb0aa2f3 100644--- a/packages/views/locales/en/skills.json+++ b/packages/views/locales/en/skills.json@@ -134,6 +134,8 @@},"toast_saved": "Skill saved","toast_save_failed": "Failed to save skill",+ "toast_saved_version": "Saved as v{{version}}",+ "toast_view_history": "View history","toast_deleted": "Skill deleted","toast_delete_failed": "Failed to delete skill","refresh": {@@ -203,20 +205,51 @@"mode_edit": "Edit","mode_raw": "Plain text"},+ "versions": {+ "list_aria": "Skill versions",+ "version_label": "v{{version}}",+ "current": "Current",+ "unknown_author": "Unknown",+ "empty": "No versions yet. The next change to this skill records its current content as the first version.",+ "load_failed": "Failed to load versions.",+ "restore": "Restore",+ "toast_restored": "Restored v{{version}}",+ "toast_restore_failed": "Failed to restore version",+ "source": {+ "baseline": "Earlier content",+ "create": "Created",+ "update": "Edited",+ "import": "Imported",+ "refresh": "Updated from source",+ "restore": "Restored from v{{version}}"+ },+ "dialog": {+ "title": "Restore v{{version}}?",+ "description": "The content of v{{version}} becomes a new version. Agents use it from their next run. Newer versions stay in the history.",+ "unsaved_warning": "Your unsaved changes will be discarded.",+ "cancel": "Cancel",+ "confirm": "Restore",+ "restoring": "Restoring..."+ }+ },"sections": {"content": "Content","files": "Files","edit": "Edit","open": "Open",- "add": "Add"+ "add": "Add",+ "history": "History"},"menu": {"copy_link": "Copy link","link_copied": "Link copied",- "delete": "Delete skill"+ "delete": "Delete skill",+ "version_history": "Version history"},"panel": {- "add_description": "Add description"+ "add_description": "Add description",+ "version": "Version",+ "no_versions": "No versions yet"}},"create": {diff --git a/packages/views/locales/fr/skills.json b/packages/views/locales/fr/skills.jsonindex 4e09efae60..c8b804931f 100644--- a/packages/views/locales/fr/skills.json+++ b/packages/views/locales/fr/skills.json@@ -134,6 +134,8 @@},"toast_saved": "Skill enregistré","toast_save_failed": "Échec de l'enregistrement du skill",+ "toast_saved_version": "Enregistré en v{{version}}",+ "toast_view_history": "Voir l'historique","toast_deleted": "Skill supprimé","toast_delete_failed": "Échec de la suppression du skill","refresh": {@@ -203,20 +205,51 @@"mode_edit": "Modifier","mode_raw": "Texte brut"},+ "versions": {+ "list_aria": "Versions du skill",+ "version_label": "v{{version}}",+ "current": "Actuelle",+ "unknown_author": "Inconnu",+ "empty": "Aucune version pour l'instant. À la prochaine modification de ce skill, son contenu actuel sera enregistré comme première version.",+ "load_failed": "Impossible de charger les versions.",+ "restore": "Restaurer",+ "toast_restored": "v{{version}} restaurée",+ "toast_restore_failed": "Impossible de restaurer la version",+ "source": {+ "baseline": "Contenu antérieur",+ "create": "Création",+ "update": "Modification",+ "import": "Import",+ "refresh": "Mis à jour depuis la source",+ "restore": "Restaurée depuis v{{version}}"+ },+ "dialog": {+ "title": "Restaurer v{{version}} ?",+ "description": "Le contenu de v{{version}} devient une nouvelle version. Les agents l'utilisent dès leur prochaine exécution. Les versions plus récentes restent dans l'historique.",+ "unsaved_warning": "Vos modifications non enregistrées seront perdues.",+ "cancel": "Annuler",+ "confirm": "Restaurer",+ "restoring": "Restauration..."+ }+ },"sections": {"content": "Contenu","files": "Fichiers","edit": "Modifier","open": "Ouvrir",- "add": "Ajouter"+ "add": "Ajouter",+ "history": "Historique"},"menu": {"copy_link": "Copier le lien","link_copied": "Lien copié",- "delete": "Supprimer le skill"+ "delete": "Supprimer le skill",+ "version_history": "Historique des versions"},"panel": {- "add_description": "Ajouter une description"+ "add_description": "Ajouter une description",+ "version": "Version",+ "no_versions": "Aucune version"}},"create": {diff --git a/packages/views/locales/ja/skills.json b/packages/views/locales/ja/skills.jsonindex 3123c4cc94..2ea617c5e4 100644--- a/packages/views/locales/ja/skills.json+++ b/packages/views/locales/ja/skills.json@@ -126,6 +126,8 @@},"toast_saved": "スキルを保存しました","toast_save_failed": "スキルを保存できませんでした",+ "toast_saved_version": "v{{version}} として保存しました",+ "toast_view_history": "履歴を表示","toast_deleted": "スキルを削除しました","toast_delete_failed": "スキルを削除できませんでした","refresh": {@@ -192,20 +194,51 @@"mode_edit": "編集","mode_raw": "プレーンテキスト"},+ "versions": {+ "list_aria": "スキルのバージョン",+ "version_label": "v{{version}}",+ "current": "現在",+ "unknown_author": "不明",+ "empty": "まだバージョンはありません。次にこのスキルを変更したとき、現在の内容が最初のバージョンとして記録されます。",+ "load_failed": "バージョンを読み込めませんでした。",+ "restore": "復元",+ "toast_restored": "v{{version}} を復元しました",+ "toast_restore_failed": "バージョンを復元できませんでした",+ "source": {+ "baseline": "以前の内容",+ "create": "作成",+ "update": "編集",+ "import": "インポート",+ "refresh": "ソースから更新",+ "restore": "v{{version}} から復元"+ },+ "dialog": {+ "title": "v{{version}} を復元しますか?",+ "description": "v{{version}} の内容が新しいバージョンになり、エージェントは次回の実行からそれを使います。新しいバージョンも履歴に残ります。",+ "unsaved_warning": "保存していない変更は破棄されます。",+ "cancel": "キャンセル",+ "confirm": "復元",+ "restoring": "復元中…"+ }+ },"sections": {"content": "内容","files": "ファイル","edit": "編集","open": "開く",- "add": "追加"+ "add": "追加",+ "history": "履歴"},"menu": {"copy_link": "リンクをコピー","link_copied": "リンクをコピーしました",- "delete": "スキルを削除"+ "delete": "スキルを削除",+ "version_history": "バージョン履歴"},"panel": {- "add_description": "説明を追加"+ "add_description": "説明を追加",+ "version": "バージョン",+ "no_versions": "バージョンなし"}},"create": {diff --git a/packages/views/locales/ko/skills.json b/packages/views/locales/ko/skills.jsonindex 1a961bb174..600b05b2f5 100644--- a/packages/views/locales/ko/skills.json+++ b/packages/views/locales/ko/skills.json@@ -126,6 +126,8 @@},"toast_saved": "스킬을 저장했습니다","toast_save_failed": "스킬을 저장하지 못했습니다",+ "toast_saved_version": "v{{version}}(으)로 저장했습니다",+ "toast_view_history": "기록 보기","toast_deleted": "스킬을 삭제했습니다","toast_delete_failed": "스킬을 삭제하지 못했습니다","refresh": {@@ -192,20 +194,51 @@"mode_edit": "편집","mode_raw": "일반 텍스트"},+ "versions": {+ "list_aria": "스킬 버전",+ "version_label": "v{{version}}",+ "current": "현재",+ "unknown_author": "알 수 없음",+ "empty": "아직 버전이 없습니다. 다음에 이 스킬을 변경하면 현재 내용이 첫 번째 버전으로 기록됩니다.",+ "load_failed": "버전을 불러오지 못했습니다.",+ "restore": "복원",+ "toast_restored": "v{{version}}을(를) 복원했습니다",+ "toast_restore_failed": "버전을 복원하지 못했습니다",+ "source": {+ "baseline": "이전 내용",+ "create": "생성",+ "update": "편집",+ "import": "가져오기",+ "refresh": "소스에서 업데이트",+ "restore": "v{{version}}에서 복원"+ },+ "dialog": {+ "title": "v{{version}}(으)로 복원할까요?",+ "description": "v{{version}}의 내용이 새 버전이 되며, 에이전트는 다음 실행부터 이를 사용합니다. 이후 버전도 기록에 남습니다.",+ "unsaved_warning": "저장하지 않은 변경 사항은 삭제됩니다.",+ "cancel": "취소",+ "confirm": "복원",+ "restoring": "복원하는 중..."+ }+ },"sections": {"content": "내용","files": "파일","edit": "편집","open": "열기",- "add": "추가"+ "add": "추가",+ "history": "기록"},"menu": {"copy_link": "링크 복사","link_copied": "링크를 복사했습니다",- "delete": "스킬 삭제"+ "delete": "스킬 삭제",+ "version_history": "버전 기록"},"panel": {- "add_description": "설명 추가"+ "add_description": "설명 추가",+ "version": "버전",+ "no_versions": "아직 버전 없음"}},"create": {diff --git a/packages/views/locales/zh-Hans/skills.json b/packages/views/locales/zh-Hans/skills.jsonindex f9636d4034..490a085c8a 100644--- a/packages/views/locales/zh-Hans/skills.json+++ b/packages/views/locales/zh-Hans/skills.json@@ -126,6 +126,8 @@},"toast_saved": "已保存 skill","toast_save_failed": "保存 skill 失败",+ "toast_saved_version": "已保存为 v{{version}}",+ "toast_view_history": "查看历史","toast_deleted": "已删除 skill","toast_delete_failed": "删除 skill 失败","refresh": {@@ -192,20 +194,51 @@"mode_edit": "编辑","mode_raw": "纯文本"},+ "versions": {+ "list_aria": "skill 版本",+ "version_label": "v{{version}}",+ "current": "当前",+ "unknown_author": "未知",+ "empty": "还没有版本。这个 skill 下次被修改时,会先把当前内容记录为第一个版本。",+ "load_failed": "版本加载失败。",+ "restore": "恢复",+ "toast_restored": "已恢复 v{{version}}",+ "toast_restore_failed": "版本恢复失败",+ "source": {+ "baseline": "早期内容",+ "create": "创建",+ "update": "编辑",+ "import": "导入",+ "refresh": "从来源更新",+ "restore": "恢复自 v{{version}}"+ },+ "dialog": {+ "title": "恢复到 v{{version}}?",+ "description": "v{{version}} 的内容会成为一个新版本,智能体从下一次运行起使用它。更新的版本仍保留在历史里。",+ "unsaved_warning": "未保存的修改会被丢弃。",+ "cancel": "取消",+ "confirm": "恢复",+ "restoring": "恢复中..."+ }+ },"sections": {"content": "内容","files": "文件","edit": "编辑","open": "打开",- "add": "添加"+ "add": "添加",+ "history": "历史"},"menu": {"copy_link": "复制链接","link_copied": "已复制链接",- "delete": "删除 skill"+ "delete": "删除 skill",+ "version_history": "版本历史"},"panel": {- "add_description": "添加描述"+ "add_description": "添加描述",+ "version": "版本",+ "no_versions": "暂无版本"}},"create": {diff --git a/packages/views/locales/zh-Hant/skills.json b/packages/views/locales/zh-Hant/skills.jsonindex b7adb6a7d9..7b37d0ff6b 100644--- a/packages/views/locales/zh-Hant/skills.json+++ b/packages/views/locales/zh-Hant/skills.json@@ -126,6 +126,8 @@},"toast_saved": "已儲存 skill","toast_save_failed": "儲存 skill 失敗",+ "toast_saved_version": "已儲存為 v{{version}}",+ "toast_view_history": "查看歷史","toast_deleted": "已刪除 skill","toast_delete_failed": "刪除 skill 失敗","refresh": {@@ -192,20 +194,51 @@"mode_edit": "編輯","mode_raw": "純文字"},+ "versions": {+ "list_aria": "skill 版本",+ "version_label": "v{{version}}",+ "current": "目前",+ "unknown_author": "未知",+ "empty": "還沒有版本。這個 skill 下次被修改時,會先把目前內容記錄為第一個版本。",+ "load_failed": "版本載入失敗。",+ "restore": "還原",+ "toast_restored": "已還原 v{{version}}",+ "toast_restore_failed": "版本還原失敗",+ "source": {+ "baseline": "早期內容",+ "create": "建立",+ "update": "編輯",+ "import": "匯入",+ "refresh": "從來源更新",+ "restore": "還原自 v{{version}}"+ },+ "dialog": {+ "title": "還原到 v{{version}}?",+ "description": "v{{version}} 的內容會成為一個新版本,智慧體從下一次執行起使用它。較新的版本仍保留在歷史中。",+ "unsaved_warning": "未儲存的修改會被捨棄。",+ "cancel": "取消",+ "confirm": "還原",+ "restoring": "還原中..."+ }+ },"sections": {"content": "內容","files": "檔案","edit": "編輯","open": "開啟",- "add": "新增"+ "add": "新增",+ "history": "歷史"},"menu": {"copy_link": "複製連結","link_copied": "已複製連結",- "delete": "刪除 skill"+ "delete": "刪除 skill",+ "version_history": "版本歷史"},"panel": {- "add_description": "新增描述"+ "add_description": "新增描述",+ "version": "版本",+ "no_versions": "暫無版本"}},"create": {diff --git a/packages/views/skills/components/skill-detail-page.test.tsx b/packages/views/skills/components/skill-detail-page.test.tsxindex 945091232f..5bfef11a34 100644--- a/packages/views/skills/components/skill-detail-page.test.tsx+++ b/packages/views/skills/components/skill-detail-page.test.tsx@@ -13,6 +13,7 @@ const skillRef = vi.hoisted(() => ({ current: null as unknown }));const agentsRef = vi.hoisted(() => ({ current: [] as unknown[] }));const membersRef = vi.hoisted(() => ({ current: [] as unknown[] }));const canEditRef = vi.hoisted(() => ({ current: true }));+const versionsRef = vi.hoisted(() => ({ current: [] as unknown[] }));const copyTextMock = vi.hoisted(() => vi.fn(() => Promise.resolve(true)));vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));@@ -29,6 +30,15 @@ vi.mock("@multica/core/workspace/queries", () => ({queryKey: ["members", wsId],queryFn: () => Promise.resolve(membersRef.current),}),+ skillVersionsOptions: (wsId: string, id: string) => ({+ queryKey: ["skill-versions", wsId, id],+ queryFn: () => Promise.resolve(versionsRef.current),+ }),+ skillVersionDetailOptions: (wsId: string, id: string, version: number | null) => ({+ queryKey: ["skill-version", wsId, id, version],+ queryFn: () => Promise.resolve(null),+ enabled: false,+ }),selectSkillAssignments: () => new Map(),workspaceKeys: {skills: (wsId: string) => ["skills", wsId],@@ -111,6 +121,7 @@ vi.mock("@multica/ui/components/common/actor-avatar", () => ({}));import { SkillDetailPage } from "./skill-detail-page";+import { api } from "@multica/core/api";const LONG_DESCRIPTION ="Animation for product interfaces — when to animate and when not to. " +@@ -191,6 +202,7 @@ beforeEach(() => {{ user_id: "user-1", role: "member", name: "Ada Lovelace", avatar_url: null },];canEditRef.current = true;+ versionsRef.current = [];});describe("SkillDetailPage header", () => {@@ -208,7 +220,7 @@ describe("SkillDetailPage header", () => {expect(screen.getByTestId("add-to-agent-dialog")).toBeInTheDocument();});- it("keeps copy link, update from source and delete in the ⋯ menu", async () => {+ it("keeps copy link, version history, update from source and delete in the ⋯ menu", async () => {skillRef.current = {...baseSkill,config: { origin: { type: "github", source_url: SOURCE_URL } },@@ -217,7 +229,7 @@ describe("SkillDetailPage header", () => {const menu = await openMoreActions();expect(within(menu).getAllByRole("menuitem").map((item) => item.textContent),- ).toEqual(["Copy link", "Update from source", "Delete skill"]);+ ).toEqual(["Copy link", "Version history", "Update from source", "Delete skill"]);});it("copies the skill's shareable link", async () => {@@ -241,7 +253,7 @@ describe("SkillDetailPage header", () => {const menu = await openMoreActions();expect(within(menu).getAllByRole("menuitem").map((item) => item.textContent),- ).toEqual(["Copy link"]);+ ).toEqual(["Copy link", "Version history"]);});});@@ -343,6 +355,134 @@ describe("SkillDetailPage files view", () => {});});+describe("SkillDetailPage versions view", () => {+ it("opens version history from the ⋯ menu", async () => {+ const { push } = renderPage();+ const menu = await openMoreActions();+ await userEvent.click(within(menu).getByRole("menuitem", { name: "Version history" }));++ expect(push).toHaveBeenCalledWith("/acme/skills/skill-1?view=versions");+ expect(+ await screen.findByText(/next change to this skill/),+ ).toBeInTheDocument();+ expect(screen.queryByRole("heading", { name: "Content", level: 2 })).toBeNull();+ });++ it("restores the versions view from ?view=versions, with the skill as a breadcrumb link", async () => {+ renderPage(new URLSearchParams("view=versions"));+ expect(await screen.findByText(/next change to this skill/)).toBeInTheDocument();+ const header = screen.getByRole("banner");+ expect(+ within(header).getByRole("link", { name: "aiforui-animations" }),+ ).toHaveAttribute("href", "/acme/skills/skill-1");+ expect(within(header).getByText("Version history")).toBeInTheDocument();+ });+});++function versionSummary(version: number, source = "update") {+ return {+ id: `version-${version}`,+ skill_id: "skill-1",+ version,+ name: "aiforui-animations",+ source,+ restored_from_version: null,+ created_by: "user-1",+ created_at: "2026-07-28T18:14:40Z",+ };+}++describe("SkillDetailPage version entry points", () => {+ it("shows the current version in the panel and beside SKILL.md", async () => {+ versionsRef.current = [versionSummary(3), versionSummary(2), versionSummary(1, "create")];+ renderPage();+ expect(+ await screen.findByRole("button", { name: "Version history: v3" }),+ ).toBeInTheDocument();+ expect(within(section("Content")).getByTestId("skill-version-chip")).toHaveTextContent("v3");+ });++ it("says a skill without history has no versions yet, and shows no chip", async () => {+ renderPage();+ expect(+ await screen.findByRole("button", { name: "Version history: No versions yet" }),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("skill-version-chip")).toBeNull();+ });++ it("opens the history from the panel's Version and Updated rows", async () => {+ versionsRef.current = [versionSummary(1, "create")];+ const { push } = renderPage();+ await userEvent.click(await screen.findByRole("button", { name: "Version history: v1" }));+ expect(push).toHaveBeenLastCalledWith("/acme/skills/skill-1?view=versions");+ expect(await screen.findByText("Version history", { selector: "span" })).toBeInTheDocument();++ push.mockClear();+ const rows = screen.getAllByRole("button", { name: /^Version history: / });+ expect(rows).toHaveLength(2);+ await userEvent.click(rows[1]!);+ expect(push).toHaveBeenLastCalledWith("/acme/skills/skill-1?view=versions");+ });++ it("offers Content › History to read-only viewers too", async () => {+ canEditRef.current = false;+ const { push } = renderPage();+ await screen.findByRole("heading", { name: "Content", level: 2 });+ await userEvent.click(within(section("Content")).getByRole("button", { name: "History" }));+ expect(push).toHaveBeenCalledWith("/acme/skills/skill-1?view=versions");+ });++ it("names the version a save became, with a link to the history", async () => {+ versionsRef.current = [versionSummary(1, "create")];+ vi.mocked(api.updateSkill).mockImplementationOnce(async () => {+ versionsRef.current = [versionSummary(2), versionSummary(1, "create")];+ return { ...baseSkill, name: "renamed-skill", updated_at: "2026-07-29T10:00:00Z" };+ });+ const { push } = renderPage();+ await screen.findByRole("button", { name: "Version history: v1" });+ fireEvent.change(await screen.findByLabelText("Name"), {+ target: { value: "renamed-skill" },+ });+ await userEvent.click(screen.getByRole("button", { name: /Save changes/ }));++ await vi.waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith(+ "Saved as v2",+ expect.objectContaining({+ action: expect.objectContaining({ label: "View history" }),+ }),+ ),+ );+ const options = vi.mocked(toast.success).mock.calls.at(-1)?.[1] as unknown as {+ action: { onClick: () => void };+ };+ options.action.onClick();+ expect(push).toHaveBeenLastCalledWith("/acme/skills/skill-1?view=versions");+ });++ it("does not claim a new version when the save recorded none", async () => {+ versionsRef.current = [versionSummary(2), versionSummary(1, "create")];+ vi.mocked(api.updateSkill).mockImplementationOnce(async () => ({+ ...baseSkill,+ updated_at: "2026-07-29T10:00:00Z",+ }));+ renderPage();+ await screen.findByRole("button", { name: "Version history: v2" });+ fireEvent.change(await openDescription(), { target: { value: "changed" } });+ await userEvent.click(screen.getByRole("button", { name: /Save changes/ }));++ await vi.waitFor(() =>+ expect(toast.success).toHaveBeenCalledWith(+ "Skill saved",+ expect.objectContaining({+ action: expect.objectContaining({ label: "View history" }),+ }),+ ),+ );+ expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/^Saved as/), expect.anything());+ });+});+describe("SkillDetailPage file mode", () => {it("keeps plain-text mode when switching files", async () => {renderPage(new URLSearchParams("view=files"));diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsxindex 21d7a55bc6..cee6fea7cd 100644--- a/packages/views/skills/components/skill-detail-page.tsx+++ b/packages/views/skills/components/skill-detail-page.tsx@@ -15,6 +15,7 @@ import {ChevronRight,File,FileText,+ History,Link2,Loader2,Lock,@@ -45,6 +46,7 @@ import {memberListOptions,selectSkillAssignments,skillDetailOptions,+ skillVersionsOptions,workspaceKeys,} from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";@@ -97,6 +99,7 @@ import {type SkillActionsContext,} from "./skill-list-actions";import { RefreshSkillDialog } from "./refresh-skill-dialog";+import { SkillVersionsTab } from "./skill-versions-tab";import { useT } from "../../i18n";type DraftFile = { id?: string; path: string; content: string };@@ -168,15 +171,16 @@ function hasLocalEdits(draft: SkillDraft, baseline: SkillDraft | null): boolean}/**- * The page body: the skill's sections, or its files beside an editor. The- * files need more width than the reading column, so they take the body over- * instead of being a section of it. `?view=files` is also what the retired- * Files tab wrote, so its links still land on the files.+ * The page body: the skill's sections, its files beside an editor, or its+ * version history. Files and versions need more width than the reading+ * column, so they take the body over instead of being a section of it.+ * `?view=files` is also what the retired Files tab wrote, so its links still+ * land on the files.*/-type DetailView = "overview" | "files";+type DetailView = "overview" | "files" | "versions";function readView(value: string | null): DetailView {- return value === "files" ? "files" : "overview";+ return value === "files" || value === "versions" ? value : "overview";}const SKILL_DETAIL_LAYOUT_ID = "multica_skill_detail_layout";@@ -367,6 +371,14 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {const { data: runtimes = [], error: runtimesError } = useQuery(runtimeListOptions(wsId),);+ // Same cache entry as the versions view. Drives the version shown in the+ // properties panel and the Content header, and the save toast.+ const { data: versions } = useQuery(skillVersionsOptions(wsId, skillId));+ // `null`: no history yet (a skill that predates versioning and has not+ // changed since). `undefined`: still loading, or the load failed.+ const latestVersion: number | null | undefined = versions+ ? (versions[0]?.version ?? null)+ : undefined;const assignments = useMemo(() => selectSkillAssignments(agents), [agents]);@@ -587,6 +599,11 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {navigation.push(viewHref("files"));};+ const openVersions = () => {+ setActiveView("versions");+ navigation.push(viewHref("versions"));+ };+const handleSave = async () => {if (!skill || !canEdit) return;const trimmedName = name.trim();@@ -607,7 +624,34 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {exact: true,});qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });- toast.success(t(($) => $.detail.toast_saved));+ // Read the history back so the toast can name the version this save+ // became. The save already succeeded, so a failed read only costs the+ // version number in the toast.+ let savedVersion: number | null = null;+ try {+ const list = await qc.fetchQuery({+ ...skillVersionsOptions(wsId, skill.id),+ staleTime: 0,+ });+ savedVersion = list[0]?.version ?? null;+ } catch {+ savedVersion = null;+ }+ const viewHistory = {+ label: t(($) => $.detail.toast_view_history),+ onClick: openVersions,+ };+ if (savedVersion === null) {+ toast.success(t(($) => $.detail.toast_saved));+ } else if (savedVersion !== latestVersion) {+ toast.success(+ t(($) => $.detail.toast_saved_version, { version: savedVersion }),+ { action: viewHistory },+ );+ } else {+ // Content-identical saves record no version; don't claim one.+ toast.success(t(($) => $.detail.toast_saved), { action: viewHistory });+ }} catch (err) {toast.error(err instanceof Error ? err.message : t(($) => $.detail.toast_save_failed));} finally {@@ -815,6 +859,10 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {<Link2 />{t(($) => $.detail.menu.copy_link)}</DropdownMenuItem>+ <DropdownMenuItem onClick={openVersions}>+ <History />+ {t(($) => $.detail.menu.version_history)}+ </DropdownMenuItem>{canRefresh && (<DropdownMenuItem onClick={() => setConfirmRefresh(true)}><RotateCw />@@ -847,8 +895,10 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {origin={origin}originRuntime={originRuntime}creator={creator}+ latestVersion={latestVersion}onNameChange={setName}onDescriptionChange={setDescription}+ onOpenVersions={openVersions}/>);@@ -880,23 +930,40 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {<ObjectSectiontitle={t(($) => $.detail.sections.content)}- count={<span className="font-mono">{SKILL_MD}</span>}+ count={+ <span className="inline-flex items-center gap-1.5">+ <span className="font-mono">{SKILL_MD}</span>+ {typeof latestVersion === "number" && (+ <span+ data-testid="skill-version-chip"+ className="rounded-full border px-1.5 font-mono text-micro leading-4 text-muted-foreground"+ >+ {t(($) => $.detail.versions.version_label, { version: latestVersion })}+ </span>+ )}+ </span>+ }action={- canEdit ? (- <ObjectSectionAction- icon={Pencil}- onClick={() => openFiles(SKILL_MD, { edit: true })}- >- {t(($) => $.detail.sections.edit)}- </ObjectSectionAction>- ) : (- <ObjectSectionAction- icon={FileText}- onClick={() => openFiles(SKILL_MD)}- >- {t(($) => $.detail.sections.open)}+ <>+ <ObjectSectionAction icon={History} onClick={openVersions}>+ {t(($) => $.detail.sections.history)}</ObjectSectionAction>- )+ {canEdit ? (+ <ObjectSectionAction+ icon={Pencil}+ onClick={() => openFiles(SKILL_MD, { edit: true })}+ >+ {t(($) => $.detail.sections.edit)}+ </ObjectSectionAction>+ ) : (+ <ObjectSectionAction+ icon={FileText}+ onClick={() => openFiles(SKILL_MD)}+ >+ {t(($) => $.detail.sections.open)}+ </ObjectSectionAction>+ )}+ </>}><SkillContentPreview content={content} />@@ -964,6 +1031,32 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {</div>);+ const versionsView = (+ <div className="flex min-h-full flex-col md:h-full">+ {notices.length > 0 && (+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "space-y-2 pt-3")}>+ {notices}+ </div>+ )}+ <div className="flex min-h-0 flex-1 flex-col">+ <SkillVersionsTab+ skill={skill}+ wsId={wsId}+ canEdit={canEdit}+ hasUnsavedChanges={isDirty}+ members={members}+ // Adopt explicitly: the user confirmed the restore, so a dirty+ // draft is replaced instead of tripping the conflict banner.+ onRestored={(updated) => adoptServerVersion(updated)}+ />+ </div>+ </div>+ );++ // Files and versions take the body over, so the breadcrumb gains the skill+ // as a link back to its overview.+ const subView = activeView !== "overview";+return (// relative: positioning anchor for the floating save pill (page-centered,// same rule as the skills list batch toolbar).@@ -971,7 +1064,7 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {<ObjectPagelayoutId={SKILL_DETAIL_LAYOUT_ID}segments={- activeView === "files"+ subView? [listSegment,{@@ -987,6 +1080,10 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {<span className="truncate font-mono text-caption text-foreground">{selectedPath}</span>+ ) : activeView === "versions" ? (+ <span className="truncate text-foreground">+ {t(($) => $.detail.menu.version_history)}+ </span>) : (skillLeaf)@@ -994,7 +1091,11 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {actions={headerActions}panel={panel}>- {activeView === "files" ? filesView : overview}+ {activeView === "files"+ ? filesView+ : activeView === "versions"+ ? versionsView+ : overview}</ObjectPage>{/* Dirty-only and floating, matching the skills list batch toolbar;@@ -1112,7 +1213,13 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {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)}+ onRefreshed={(updated) => {+ adoptServerVersion(updated);+ qc.invalidateQueries({+ queryKey: skillVersionsOptions(wsId, updated.id).queryKey,+ exact: true,+ });+ }}/></div>);diff --git a/packages/views/skills/components/skill-properties-panel.tsx b/packages/views/skills/components/skill-properties-panel.tsxindex dc1e618a9f..fb990aea54 100644--- a/packages/views/skills/components/skill-properties-panel.tsx+++ b/packages/views/skills/components/skill-properties-panel.tsx@@ -1,6 +1,6 @@"use client";-import { Download, HardDrive, Pencil } from "@multica/ui/icons";+import { ChevronRight, Download, HardDrive, History, Pencil } from "@multica/ui/icons";import type { AgentRuntime, MemberWithUser, Skill } from "@multica/core/types";import { runtimeDisplayLabel } from "@multica/core/runtimes";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";@@ -137,9 +137,58 @@ function DescriptionValue({);}+/**+ * A panel value that opens the version history, so the row reads as a link.+ * The accessible name keeps the visible value and says where it leads.+ */+function HistoryLinkValue({+ label,+ value,+ muted = false,+ mono = false,+ icon,+ onClick,+}: {+ label: string;+ value: string;+ muted?: boolean;+ mono?: boolean;+ icon?: React.ReactNode;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-label={`${label}: ${value}`}+ title={label}+ className="group/history flex min-w-0 flex-1 items-center gap-1.5 rounded-sm text-left transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ {icon}+ <span+ className={cn(+ "truncate",+ muted && "text-muted-foreground",+ mono && "font-mono tabular-nums",+ )}+ >+ {value}+ </span>+ <ChevronRight+ className="ml-auto size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/history:opacity-100 group-focus-visible/history:opacity-100"+ aria-hidden="true"+ />+ </button>+ );+}+/*** The skill's properties. Name and description edit the page's draft, so* they save with the files through the same Save pill; labels save on pick.+ *+ * `latestVersion` is the current version number, `null` when the skill has no+ * history yet (it predates versioning and has not changed since), and+ * `undefined` while the history is loading or failed to load.*/export function SkillPropertiesPanel({skill,@@ -149,8 +198,10 @@ export function SkillPropertiesPanel({origin,originRuntime,creator,+ latestVersion,onNameChange,onDescriptionChange,+ onOpenVersions,}: {skill: Skill;name: string;@@ -159,11 +210,14 @@ export function SkillPropertiesPanel({origin: OriginInfo;originRuntime: AgentRuntime | null;creator: MemberWithUser | null;+ latestVersion: number | null | undefined;onNameChange: (value: string) => void;onDescriptionChange: (value: string) => void;+ onOpenVersions: () => void;}) {const { t } = useT("skills");const timeAgo = useTimeAgo();+ const historyLabel = t(($) => $.detail.menu.version_history);return (<div className="space-y-5">@@ -214,8 +268,31 @@ export function SkillPropertiesPanel({<span className="text-muted-foreground">—</span>)}</ObjectProperty>+ <ObjectProperty label={t(($) => $.detail.panel.version)}>+ <HistoryLinkValue+ label={historyLabel}+ icon={+ <History className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />+ }+ value={+ latestVersion === undefined+ ? "—"+ : latestVersion === null+ ? t(($) => $.detail.panel.no_versions)+ : t(($) => $.detail.versions.version_label, { version: latestVersion })+ }+ muted={latestVersion == null}+ mono={typeof latestVersion === "number"}+ onClick={onOpenVersions}+ />+ </ObjectProperty><ObjectProperty label={t(($) => $.table.updated)}>- {timeAgo(skill.updated_at)}+ {/* "Who changed what just now" is the usual reason to open history. */}+ <HistoryLinkValue+ label={historyLabel}+ value={timeAgo(skill.updated_at)}+ onClick={onOpenVersions}+ /></ObjectProperty><ObjectProperty label={t(($) => $.table.created)}>{timeAgo(skill.created_at)}diff --git a/packages/views/skills/components/skill-versions-tab.test.tsx b/packages/views/skills/components/skill-versions-tab.test.tsxnew file mode 100644index 0000000000..e2e42abd0e--- /dev/null+++ b/packages/views/skills/components/skill-versions-tab.test.tsx@@ -0,0 +1,141 @@+// @vitest-environment jsdom++import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { MemberWithUser, Skill, SkillVersion, SkillVersionSummary } 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";++const TEST_RESOURCES = { en: { common: enCommon, skills: enSkills } };++const apiMock = vi.hoisted(() => ({+ listSkillVersions: vi.fn(),+ getSkillVersion: vi.fn(),+ restoreSkillVersion: vi.fn(),+}));+vi.mock("@multica/core/api", () => ({ api: apiMock }));+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { SkillVersionsTab } from "./skill-versions-tab";++const skill: Skill = {+ id: "skill-1",+ workspace_id: "ws-1",+ name: "pr-review",+ description: "",+ config: {},+ created_by: "user-1",+ created_at: "2026-10-01T00:00:00Z",+ updated_at: "2026-10-02T00:00:00Z",+ content: "current body",+ files: [],+};++const members = [{ user_id: "user-1", name: "Bohan" }] as MemberWithUser[];++function summary(version: number, extra: Partial<SkillVersionSummary> = {}): SkillVersionSummary {+ return {+ id: `v-${version}`,+ skill_id: skill.id,+ version,+ name: skill.name,+ source: "update",+ restored_from_version: null,+ created_by: "user-1",+ created_at: "2026-10-02T00:00:00Z",+ ...extra,+ };+}++function snapshot(version: number, content: string): SkillVersion {+ return {+ ...summary(version),+ description: "",+ content,+ files: [{ path: "notes.md", content: `notes ${version}` }],+ };+}++function renderTab(props: { canEdit?: boolean; hasUnsavedChanges?: boolean; onRestored?: (s: Skill) => void } = {}) {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={queryClient}>+ <SkillVersionsTab+ skill={skill}+ wsId="ws-1"+ canEdit={props.canEdit ?? true}+ hasUnsavedChanges={props.hasUnsavedChanges ?? false}+ members={members}+ onRestored={props.onRestored ?? (() => {})}+ />+ </QueryClientProvider>+ </I18nProvider>,+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ apiMock.listSkillVersions.mockResolvedValue([+ summary(2),+ summary(1, { source: "create" }),+ ]);+ apiMock.getSkillVersion.mockImplementation(async (_id: string, v: number) =>+ snapshot(v, `body ${v}`),+ );+});++describe("SkillVersionsTab", () => {+ it("lists versions newest first and opens the current one", async () => {+ renderTab();+ const tabs = await screen.findAllByRole("tab", { name: /^v\d/ });+ expect(tabs.map((t) => t.textContent)).toEqual([+ expect.stringContaining("v2"),+ expect.stringContaining("v1"),+ ]);+ expect(tabs[0]?.textContent).toContain("Current");+ expect(tabs[1]?.textContent).toContain("Created · Bohan");+ await waitFor(() => expect(apiMock.getSkillVersion).toHaveBeenCalledWith("skill-1", 2));+ // The current version cannot be restored onto itself.+ expect(screen.queryByRole("button", { name: "Restore" })).toBeNull();+ });++ it("restores an older version after confirmation", async () => {+ const user = userEvent.setup();+ const restored = { ...skill, content: "body 1" };+ apiMock.restoreSkillVersion.mockResolvedValue(restored);+ const onRestored = vi.fn();+ renderTab({ hasUnsavedChanges: true, onRestored });++ await user.click(await screen.findByRole("tab", { name: /^v1/ }));+ await waitFor(() => expect(apiMock.getSkillVersion).toHaveBeenCalledWith("skill-1", 1));+ await user.click(await screen.findByRole("button", { name: "Restore" }));++ expect(await screen.findByText("Restore v1?")).toBeTruthy();+ expect(screen.getByText("Your unsaved changes will be discarded.")).toBeTruthy();+ const dialogRestore = screen+ .getAllByRole("button", { name: "Restore" })+ .find((b) => b.closest("[role='dialog']"));+ await user.click(dialogRestore!);++ await waitFor(() => expect(apiMock.restoreSkillVersion).toHaveBeenCalledWith("skill-1", 1));+ await waitFor(() => expect(onRestored).toHaveBeenCalledWith(restored));+ });++ it("offers no restore to read-only viewers", async () => {+ const user = userEvent.setup();+ renderTab({ canEdit: false });+ await user.click(await screen.findByRole("tab", { name: /^v1/ }));+ await waitFor(() => expect(apiMock.getSkillVersion).toHaveBeenCalledWith("skill-1", 1));+ expect(screen.queryByRole("button", { name: "Restore" })).toBeNull();+ });++ it("explains an empty history", async () => {+ apiMock.listSkillVersions.mockResolvedValue([]);+ renderTab();+ expect(await screen.findByText(/No versions yet/)).toBeTruthy();+ });+});diff --git a/packages/views/skills/components/skill-versions-tab.tsx b/packages/views/skills/components/skill-versions-tab.tsxnew file mode 100644index 0000000000..d1f88ffabf--- /dev/null+++ b/packages/views/skills/components/skill-versions-tab.tsx@@ -0,0 +1,380 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { History, Loader2, RotateCcw } from "@multica/ui/icons";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import type {+ MemberWithUser,+ Skill,+ SkillVersionSummary,+} from "@multica/core/types";+import { api } from "@multica/core/api";+import {+ skillDetailOptions,+ skillVersionDetailOptions,+ skillVersionsOptions,+ 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 { Skeleton } from "@multica/ui/components/ui/skeleton";+import { cn } from "@multica/ui/lib/utils";+import { PAGE_GUTTER, PAGE_RAIL } from "../../layout/page-header";+import { useT, useTimeAgo } from "../../i18n";+import { FileViewer, type FileMode } from "./file-viewer";++const SKILL_MD = "SKILL.md";++function useSourceLabel() {+ const { t } = useT("skills");+ return (v: SkillVersionSummary): string => {+ switch (v.source) {+ case "baseline":+ return t(($) => $.detail.versions.source.baseline);+ case "create":+ return t(($) => $.detail.versions.source.create);+ case "import":+ return t(($) => $.detail.versions.source.import);+ case "refresh":+ return t(($) => $.detail.versions.source.refresh);+ case "restore":+ return v.restored_from_version !== null+ ? t(($) => $.detail.versions.source.restore, {+ version: v.restored_from_version,+ })+ : t(($) => $.detail.versions.source.update);+ default:+ return t(($) => $.detail.versions.source.update);+ }+ };+}++/**+ * Read-only content history. Every save already records a version, so the+ * only action here is Restore, which the server turns into a new latest+ * version: history only moves forward and a restore can itself be restored.+ */+export function SkillVersionsTab({+ skill,+ wsId,+ canEdit,+ hasUnsavedChanges,+ members,+ onRestored,+}: {+ skill: Skill;+ wsId: string;+ canEdit: boolean;+ hasUnsavedChanges: boolean;+ members: MemberWithUser[];+ /** Fired after caches are updated; the detail page adopts the result. */+ onRestored: (updated: Skill) => void;+}) {+ const { t } = useT("skills");+ const timeAgo = useTimeAgo();+ const qc = useQueryClient();+ const sourceLabel = useSourceLabel();++ const {+ data: versions = [],+ isLoading,+ error,+ } = useQuery(skillVersionsOptions(wsId, skill.id));+ const latest = versions[0]?.version ?? null;++ const [selected, setSelected] = useState<number | null>(null);+ // Follow the newest version until the user picks one, and drop a selection+ // that no longer exists.+ const selectedVersion =+ selected !== null && versions.some((v) => v.version === selected)+ ? selected+ : latest;++ const { data: detail, isLoading: detailLoading } = useQuery(+ skillVersionDetailOptions(wsId, skill.id, selectedVersion),+ );++ const [selectedPath, setSelectedPath] = useState(SKILL_MD);+ const [mode, setMode] = useState<FileMode>("preview");+ const filePaths = useMemo(+ () => [SKILL_MD, ...(detail?.files ?? []).map((f) => f.path)],+ [detail],+ );+ useEffect(() => {+ if (!filePaths.includes(selectedPath)) setSelectedPath(SKILL_MD);+ }, [filePaths, selectedPath]);+ const selectedContent =+ selectedPath === SKILL_MD+ ? (detail?.content ?? "")+ : (detail?.files.find((f) => f.path === selectedPath)?.content ?? "");++ const [confirmOpen, setConfirmOpen] = useState(false);+ const [restoring, setRestoring] = useState(false);++ const memberName = (userId: string | null) =>+ (userId && members.find((m) => m.user_id === userId)?.name) ||+ t(($) => $.detail.versions.unknown_author);++ const handleRestore = async () => {+ if (selectedVersion === null) return;+ setRestoring(true);+ try {+ const updated = await api.restoreSkillVersion(skill.id, selectedVersion);+ if (updated.id === skill.id) {+ qc.setQueryData(skillDetailOptions(wsId, skill.id).queryKey, updated);+ } else {+ // Schema fallback (malformed response): refetch instead of seeding+ // the cache with the empty placeholder.+ qc.invalidateQueries({+ queryKey: skillDetailOptions(wsId, skill.id).queryKey,+ exact: true,+ });+ }+ qc.invalidateQueries({+ queryKey: skillVersionsOptions(wsId, skill.id).queryKey,+ exact: true,+ });+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId), exact: true });+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ toast.success(+ t(($) => $.detail.versions.toast_restored, { version: selectedVersion }),+ );+ setConfirmOpen(false);+ setSelected(null);+ if (updated.id === skill.id) onRestored(updated);+ } catch (e) {+ toast.error(+ e instanceof Error && e.message+ ? e.message+ : t(($) => $.detail.versions.toast_restore_failed),+ );+ } finally {+ setRestoring(false);+ }+ };++ if (isLoading) {+ return (+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "space-y-3 py-6")}>+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-5/6" />+ </div>+ );+ }++ if (error) {+ return (+ <div className={cn(PAGE_RAIL, PAGE_GUTTER, "py-6 text-caption text-muted-foreground")}>+ {t(($) => $.detail.versions.load_failed)}+ </div>+ );+ }++ if (versions.length === 0) {+ return (+ <div className="flex flex-col items-center justify-center gap-2 py-16 text-center">+ <History className="h-6 w-6 text-faint-foreground" />+ <p className="max-w-sm text-caption text-muted-foreground">+ {t(($) => $.detail.versions.empty)}+ </p>+ </div>+ );+ }++ const selectedSummary = versions.find((v) => v.version === selectedVersion);+ const isLatest = selectedVersion === latest;++ return (+ <div className={cn(PAGE_RAIL, "flex min-h-full flex-col md:h-full md:flex-row")}>+ <aside+ className={cn(+ "shrink-0 border-b border-surface-border py-3 md:w-64 md:overflow-y-auto md:border-b-0 md:border-r md:py-4",+ PAGE_GUTTER,+ )}+ >+ <div+ role="tablist"+ aria-orientation="vertical"+ aria-label={t(($) => $.detail.versions.list_aria)}+ className="flex flex-col gap-0.5"+ >+ {versions.map((v) => {+ const active = v.version === selectedVersion;+ return (+ <button+ key={v.id}+ type="button"+ role="tab"+ aria-selected={active}+ onClick={() => setSelected(v.version)}+ className={cn(+ "flex flex-col gap-0.5 rounded-md px-2.5 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ active ? "bg-accent text-accent-foreground" : "hover:bg-accent/60",+ )}+ >+ <span className="flex items-center gap-2">+ <span className="font-mono text-caption font-medium">+ {t(($) => $.detail.versions.version_label, { version: v.version })}+ </span>+ {v.version === latest && (+ <span className="rounded-full border px-1.5 text-micro text-muted-foreground">+ {t(($) => $.detail.versions.current)}+ </span>+ )}+ <span className="ml-auto shrink-0 text-micro text-muted-foreground">+ {timeAgo(v.created_at)}+ </span>+ </span>+ <span className="truncate text-caption text-muted-foreground">+ {sourceLabel(v)} · {memberName(v.created_by)}+ </span>+ </button>+ );+ })}+ </div>+ </aside>++ <section className="flex min-h-[32rem] min-w-0 flex-1 flex-col md:min-h-0">+ <div className="flex h-10 shrink-0 items-center gap-3 border-b px-3 sm:px-4">+ <div+ role="tablist"+ aria-label={t(($) => $.detail.files.list_aria)}+ className="flex min-w-0 items-center gap-1 overflow-x-auto"+ >+ {filePaths.map((p) => (+ <button+ key={p}+ type="button"+ role="tab"+ aria-selected={p === selectedPath}+ onClick={() => setSelectedPath(p)}+ className={cn(+ "h-6 shrink-0 rounded-xs px-2 font-mono text-caption transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ p === selectedPath+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {p}+ </button>+ ))}+ </div>+ <div className="ml-auto flex shrink-0 items-center gap-1">+ <div+ role="group"+ aria-label={t(($) => $.detail.files.mode_aria)}+ className="flex items-center gap-0.5 rounded-md bg-muted p-0.5"+ >+ {(["preview", "raw"] as const).map((value) => (+ <button+ key={value}+ type="button"+ aria-pressed={mode === value}+ onClick={() => setMode(value)}+ className={cn(+ "h-6 rounded-xs px-2 text-caption font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ mode === value+ ? "bg-surface text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {value === "preview"+ ? t(($) => $.detail.files.mode_preview)+ : t(($) => $.detail.files.mode_raw)}+ </button>+ ))}+ </div>+ {canEdit && !isLatest && (+ <Button+ type="button"+ variant="outline"+ size="xs"+ className="gap-1"+ onClick={() => setConfirmOpen(true)}+ >+ <RotateCcw className="h-3 w-3" />+ {t(($) => $.detail.versions.restore)}+ </Button>+ )}+ </div>+ </div>++ <div className="min-h-0 flex-1">+ {detailLoading || !detail ? (+ <div className="space-y-3 p-4">+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-3/4" />+ </div>+ ) : (+ <FileViewer+ key={`${selectedVersion}:${selectedPath}`}+ path={selectedPath}+ content={selectedContent}+ mode={mode}+ readOnly+ onChange={() => {}}+ />+ )}+ </div>+ </section>++ <Dialog+ open={confirmOpen}+ onOpenChange={(v) => {+ if (!restoring) setConfirmOpen(v);+ }}+ >+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>+ {t(($) => $.detail.versions.dialog.title, {+ version: selectedSummary?.version ?? 0,+ })}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.detail.versions.dialog.description, {+ version: selectedSummary?.version ?? 0,+ })}+ </DialogDescription>+ </DialogHeader>+ {hasUnsavedChanges && (+ <div className="rounded-md bg-warning/10 px-3 py-2 text-caption text-muted-foreground">+ {t(($) => $.detail.versions.dialog.unsaved_warning)}+ </div>+ )}+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={() => setConfirmOpen(false)}+ disabled={restoring}+ >+ {t(($) => $.detail.versions.dialog.cancel)}+ </Button>+ <Button type="button" onClick={handleRestore} disabled={restoring}>+ {restoring ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ {t(($) => $.detail.versions.dialog.restoring)}+ </>+ ) : (+ <>+ <RotateCcw className="h-3 w-3" />+ {t(($) => $.detail.versions.dialog.confirm)}+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 421212601b..fcdb4f67cf 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "613_skill_version_index": "idx_skill_version_skill_version","606_agent_task_queue_runtime_active_index": "idx_agent_task_queue_runtime_active","604_wecom_install_session_begin_rate_idx": "idx_wecom_install_session_begin_rate","603_wecom_install_session_agent_pending_idx": "idx_wecom_install_session_agent_pending",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 745df92b88..ec1058da51 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2418,6 +2418,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/files", h.ListSkillFiles)r.Put("/files", h.UpsertSkillFile)r.Delete("/files/{fileId}", h.DeleteSkillFile)+ r.Get("/versions", h.ListSkillVersions)+ r.Get("/versions/{version}", h.GetSkillVersion)+ r.Post("/versions/{version}/restore", h.RestoreSkillVersion)})})diff --git a/server/internal/handler/runtime_local_skills.go b/server/internal/handler/runtime_local_skills.goindex e38d5befff..ee690c0e09 100644--- a/server/internal/handler/runtime_local_skills.go+++ b/server/internal/handler/runtime_local_skills.go@@ -932,13 +932,14 @@ func (h *Handler) ReportLocalSkillImportResult(w http.ResponseWriter, r *http.Re}resp, err := h.createSkillWithFiles(r.Context(), skillCreateInput{- WorkspaceID: rt.WorkspaceID,- CreatorID: creatorUUID,- Name: name,- Description: description,- Content: body.Skill.Content,- Config: config,- Files: files,+ VersionSource: skillVersionSourceImport,+ WorkspaceID: rt.WorkspaceID,+ CreatorID: creatorUUID,+ Name: name,+ Description: description,+ Content: body.Skill.Content,+ Config: config,+ Files: files,})if err != nil {// A unique-violation here means another import won the race between ourdiff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex b0ab2410fe..cd2259d609 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -627,8 +627,14 @@ func (h *Handler) UpdateSkill(w http.ResponseWriter, r *http.Request) {qtx := h.Queries.WithTx(tx)+ if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {+ slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to update skill")+ return+ }+params := db.UpdateSkillParams{- ID: parseUUID(id),+ ID: skill.ID,}if req.Name != nil {params.Name = pgtype.Text{String: sanitizeNullBytes(*req.Name), Valid: true}@@ -688,6 +694,15 @@ func (h *Handler) UpdateSkill(w http.ResponseWriter, r *http.Request) {}}+ if _, err := recordSkillVersion(r.Context(), qtx, skill.ID, skillVersionRecord{+ Source: skillVersionSourceUpdate,+ CreatedBy: parseUUID(requestUserID(r)),+ }); err != nil {+ slog.Warn("record skill version failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to update skill")+ return+ }+if err := tx.Commit(r.Context()); err != nil {writeError(w, http.StatusInternalServerError, "failed to commit")return@@ -2173,13 +2188,14 @@ func skillImportConflictReason() string {func (h *Handler) createImportedSkillWithName(ctx context.Context, workspaceID, creatorID pgtype.UUID, name string, imported *importedSkill, config map[string]any, files []CreateSkillFileRequest) (SkillWithFilesResponse, error) {return h.createSkillWithFiles(ctx, skillCreateInput{- WorkspaceID: workspaceID,- CreatorID: creatorID,- Name: name,- Description: imported.description,- Content: imported.content,- Config: config,- Files: files,+ VersionSource: skillVersionSourceImport,+ WorkspaceID: workspaceID,+ CreatorID: creatorID,+ Name: name,+ Description: imported.description,+ Content: imported.content,+ Config: config,+ Files: files,})}@@ -2524,6 +2540,14 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ // The baseline runs before TouchSkill: it locks the skill row (the same+ // lock TouchSkill and UpdateSkill take, so lock order is unchanged) and+ // stamps a pre-versioning skill's baseline with its real updated_at.+ if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {+ slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to upsert skill file")+ return+ }// Touch the parent first so its row lock is taken before the file write,// in the same order UpdateSkill takes them.skill, err = qtx.TouchSkill(r.Context(), db.TouchSkillParams{@@ -2548,6 +2572,14 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to upsert skill file")return}+ if _, err := recordSkillVersion(r.Context(), qtx, skill.ID, skillVersionRecord{+ Source: skillVersionSourceUpdate,+ CreatedBy: parseUUID(requestUserID(r)),+ }); err != nil {+ slog.Warn("record skill version failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to upsert skill file")+ return+ }resp, err := skillWithFilesInTx(r.Context(), qtx, skill)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list skill files")@@ -2593,6 +2625,11 @@ func (h *Handler) DeleteSkillFile(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {+ slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to delete skill file")+ return+ }skill, err = qtx.TouchSkill(r.Context(), db.TouchSkillParams{ID: skill.ID,WorkspaceID: skill.WorkspaceID,@@ -2609,6 +2646,14 @@ func (h *Handler) DeleteSkillFile(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete skill file")return}+ if _, err := recordSkillVersion(r.Context(), qtx, skill.ID, skillVersionRecord{+ Source: skillVersionSourceUpdate,+ CreatedBy: parseUUID(requestUserID(r)),+ }); err != nil {+ slog.Warn("record skill version failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to delete skill file")+ return+ }resp, err := skillWithFilesInTx(r.Context(), qtx, skill)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list skill files")diff --git a/server/internal/handler/skill_create.go b/server/internal/handler/skill_create.goindex dc5cda5646..8d416bd3d5 100644--- a/server/internal/handler/skill_create.go+++ b/server/internal/handler/skill_create.go@@ -8,6 +8,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"skillpkg "github.com/multica-ai/multica/server/internal/skill"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -19,6 +20,9 @@ type skillCreateInput struct {Content stringConfig anyFiles []CreateSkillFileRequest+ // VersionSource labels the skill's first version. Empty means+ // skillVersionSourceCreate.+ VersionSource string}// createSkillWithFilesInTx writes a skill plus its supporting files using the@@ -65,6 +69,17 @@ func createSkillWithFilesInTx(ctx context.Context, qtx *db.Queries, input skillCfileResps = append(fileResps, skillFileToResponse(sf))}+ source := input.VersionSource+ if source == "" {+ source = skillVersionSourceCreate+ }+ if _, err := recordSkillVersion(ctx, qtx, skill.ID, skillVersionRecord{+ Source: source,+ CreatedBy: input.CreatorID,+ }); err != nil {+ return SkillWithFilesResponse{}, err+ }+return SkillWithFilesResponse{SkillResponse: skillToResponse(skill),Files: fileResps,@@ -124,6 +139,9 @@ type skillOverwriteInput struct {Content stringConfig anyFiles []CreateSkillFileRequest+ // VersionSource labels the version this overwrite records. Empty means+ // skillVersionSourceImport.+ VersionSource string}// overwriteSkillWithFiles re-imports a bundle onto an existing skill in a single@@ -180,6 +198,10 @@ func (h *Handler) overwriteSkillWithFiles(ctx context.Context, input skillOverwrreturn SkillWithFilesResponse{}, errSkillOverwriteNameMismatch}+ if err := ensureSkillVersionBaseline(ctx, qtx, existing.ID); err != nil {+ return SkillWithFilesResponse{}, err+ }+// 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@@ -226,6 +248,21 @@ func (h *Handler) overwriteSkillWithFiles(ctx context.Context, input skillOverwrfileResps = append(fileResps, skillFileToResponse(sf))}+ source := input.VersionSource+ if source == "" {+ source = skillVersionSourceImport+ }+ var versionAuthor pgtype.UUID+ if u, err := util.ParseUUID(input.UserID); err == nil {+ versionAuthor = u+ }+ if _, err := recordSkillVersion(ctx, qtx, skill.ID, skillVersionRecord{+ Source: source,+ CreatedBy: versionAuthor,+ }); err != nil {+ return SkillWithFilesResponse{}, err+ }+if err := tx.Commit(ctx); err != nil {return SkillWithFilesResponse{}, err}diff --git a/server/internal/handler/skill_refresh.go b/server/internal/handler/skill_refresh.goindex f1e1017f61..69ab4984bf 100644--- a/server/internal/handler/skill_refresh.go+++ b/server/internal/handler/skill_refresh.go@@ -171,6 +171,7 @@ func (h *Handler) RefreshSkill(w http.ResponseWriter, r *http.Request) {}resp, err := h.overwriteSkillWithFiles(r.Context(), skillOverwriteInput{+ VersionSource: skillVersionSourceRefresh,WorkspaceID: skill.WorkspaceID,TargetSkillID: skill.ID,UserID: userID,diff --git a/server/internal/handler/skill_version.go b/server/internal/handler/skill_version.gonew file mode 100644index 0000000000..78e7928649--- /dev/null+++ b/server/internal/handler/skill_version.go@@ -0,0 +1,369 @@+package handler++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "strconv"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/logger"+ skillpkg "github.com/multica-ai/multica/server/internal/skill"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Skill version sources. A version records how the skill reached that state.+const (+ // skillVersionSourceBaseline is the pre-write snapshot of a skill that had+ // no history yet (it predates skill versioning).+ skillVersionSourceBaseline = "baseline"+ skillVersionSourceCreate = "create"+ skillVersionSourceUpdate = "update"+ skillVersionSourceImport = "import"+ skillVersionSourceRefresh = "refresh"+ skillVersionSourceRestore = "restore"+)++type skillVersionFile struct {+ Path string `json:"path"`+ Content string `json:"content"`+}++type SkillVersionSummaryResponse struct {+ ID string `json:"id"`+ SkillID string `json:"skill_id"`+ Version int32 `json:"version"`+ Name string `json:"name"`+ Source string `json:"source"`+ RestoredFromVersion *int32 `json:"restored_from_version"`+ CreatedBy *string `json:"created_by"`+ CreatedAt string `json:"created_at"`+}++type SkillVersionResponse struct {+ SkillVersionSummaryResponse+ Description string `json:"description"`+ Content string `json:"content"`+ Files []skillVersionFile `json:"files"`+}++type skillVersionRecord struct {+ Source string+ CreatedBy pgtype.UUID+ RestoredFrom pgtype.Int4+ // CreatedAt overrides the row timestamp. Baselines use the skill's last+ // update time so the list shows when that content was actually written.+ CreatedAt pgtype.Timestamptz+}++// isVersionedSkill reports whether a skill keeps content history. Plugin+// skills are owned by their plugin package, which carries its own version.+func isVersionedSkill(skill db.Skill) bool {+ return !skill.PluginInstallationID.Valid+}++// ensureSkillVersionBaseline must run inside the write transaction, before+// the write. It locks the skill row (serializing version allocation for this+// skill until the transaction ends) and, when the skill has no history yet,+// snapshots its current state so the upcoming write can be reverted.+func ensureSkillVersionBaseline(ctx context.Context, qtx *db.Queries, skillID pgtype.UUID) error {+ skill, err := qtx.LockSkillForVersioning(ctx, skillID)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ return err+ }+ if !isVersionedSkill(skill) {+ return nil+ }+ if _, err := qtx.GetLatestSkillVersion(ctx, skill.ID); err == nil {+ return nil+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return err+ }+ _, err = appendSkillVersion(ctx, qtx, skill, skillVersionRecord{+ Source: skillVersionSourceBaseline,+ CreatedBy: skill.CreatedBy,+ CreatedAt: skill.UpdatedAt,+ })+ return err+}++// recordSkillVersion must run inside the write transaction, after the write.+// It snapshots the skill's current state and appends a version unless the+// content is identical to the latest version (no-op saves, config-only edits).+func recordSkillVersion(ctx context.Context, qtx *db.Queries, skillID pgtype.UUID, rec skillVersionRecord) (bool, error) {+ skill, err := qtx.LockSkillForVersioning(ctx, skillID)+ if err != nil {+ return false, err+ }+ if !isVersionedSkill(skill) {+ return false, nil+ }+ return appendSkillVersion(ctx, qtx, skill, rec)+}++func appendSkillVersion(ctx context.Context, qtx *db.Queries, skill db.Skill, rec skillVersionRecord) (bool, error) {+ files, err := qtx.ListSkillFiles(ctx, skill.ID)+ if err != nil {+ return false, err+ }+ snapshot := make([]skillVersionFile, len(files))+ for i, f := range files {+ snapshot[i] = skillVersionFile{Path: f.Path, Content: f.Content}+ }+ hash, err := skillVersionHash(skill.Name, skill.Description, skill.Content, snapshot)+ if err != nil {+ return false, err+ }++ next := int32(1)+ latest, err := qtx.GetLatestSkillVersion(ctx, skill.ID)+ switch {+ case err == nil:+ if latest.ContentHash == hash {+ return false, nil+ }+ next = latest.Version + 1+ case !errors.Is(err, pgx.ErrNoRows):+ return false, err+ }++ filesJSON, err := json.Marshal(snapshot)+ if err != nil {+ return false, err+ }+ _, err = qtx.CreateSkillVersion(ctx, db.CreateSkillVersionParams{+ WorkspaceID: skill.WorkspaceID,+ SkillID: skill.ID,+ Version: next,+ Name: skill.Name,+ Description: skill.Description,+ Content: skill.Content,+ Files: filesJSON,+ ContentHash: hash,+ Source: rec.Source,+ RestoredFromVersion: rec.RestoredFrom,+ CreatedBy: rec.CreatedBy,+ CreatedAt: rec.CreatedAt,+ })+ if err != nil {+ return false, err+ }+ return true, nil+}++// skillVersionHash fingerprints the versioned fields. Files come from+// ListSkillFiles, which orders by path, so the encoding is deterministic.+func skillVersionHash(name, description, content string, files []skillVersionFile) (string, error) {+ payload, err := json.Marshal(struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ Files []skillVersionFile `json:"files"`+ }{name, description, content, files})+ if err != nil {+ return "", err+ }+ sum := sha256.Sum256(payload)+ return hex.EncodeToString(sum[:]), nil+}++func skillVersionSummaryToResponse(id, skillID pgtype.UUID, version int32, name, source string, restoredFrom pgtype.Int4, createdBy pgtype.UUID, createdAt pgtype.Timestamptz) SkillVersionSummaryResponse {+ return SkillVersionSummaryResponse{+ ID: uuidToString(id),+ SkillID: uuidToString(skillID),+ Version: version,+ Name: name,+ Source: source,+ RestoredFromVersion: int4ToPtr(restoredFrom),+ CreatedBy: uuidToPtr(createdBy),+ CreatedAt: timestampToString(createdAt),+ }+}++func decodeSkillVersionFiles(raw []byte) ([]skillVersionFile, error) {+ files := []skillVersionFile{}+ if len(raw) == 0 {+ return files, nil+ }+ if err := json.Unmarshal(raw, &files); err != nil {+ return nil, err+ }+ return files, nil+}++func (h *Handler) ListSkillVersions(w http.ResponseWriter, r *http.Request) {+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ rows, err := h.Queries.ListSkillVersions(r.Context(), db.ListSkillVersionsParams{+ SkillID: skill.ID,+ WorkspaceID: skill.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list skill versions")+ return+ }+ resp := make([]SkillVersionSummaryResponse, len(rows))+ for i, v := range rows {+ resp[i] = skillVersionSummaryToResponse(v.ID, v.SkillID, v.Version, v.Name, v.Source, v.RestoredFromVersion, v.CreatedBy, v.CreatedAt)+ }+ writeJSON(w, http.StatusOK, resp)+}++// loadSkillVersion resolves the {version} URL param against an already+// authorized skill.+func (h *Handler) loadSkillVersion(w http.ResponseWriter, r *http.Request, q *db.Queries, skill db.Skill) (db.SkillVersion, bool) {+ n, err := strconv.ParseInt(chi.URLParam(r, "version"), 10, 32)+ if err != nil || n < 1 {+ writeError(w, http.StatusBadRequest, "invalid version")+ return db.SkillVersion{}, false+ }+ v, err := q.GetSkillVersion(r.Context(), db.GetSkillVersionParams{+ SkillID: skill.ID,+ WorkspaceID: skill.WorkspaceID,+ Version: int32(n),+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "skill version not found")+ } else {+ writeError(w, http.StatusInternalServerError, "failed to load skill version")+ }+ return db.SkillVersion{}, false+ }+ return v, true+}++func (h *Handler) GetSkillVersion(w http.ResponseWriter, r *http.Request) {+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ v, ok := h.loadSkillVersion(w, r, h.Queries, skill)+ if !ok {+ return+ }+ files, err := decodeSkillVersionFiles(v.Files)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decode skill version")+ return+ }+ writeJSON(w, http.StatusOK, SkillVersionResponse{+ SkillVersionSummaryResponse: skillVersionSummaryToResponse(v.ID, v.SkillID, v.Version, v.Name, v.Source, v.RestoredFromVersion, v.CreatedBy, v.CreatedAt),+ Description: v.Description,+ Content: v.Content,+ Files: files,+ })+}++// RestoreSkillVersion writes an old version's snapshot back to the skill and+// records the result as a new latest version. History is never rewritten.+func (h *Handler) RestoreSkillVersion(w http.ResponseWriter, r *http.Request) {+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ if !h.canManageSkill(w, r, skill) {+ return+ }+ if !isVersionedSkill(skill) {+ writeError(w, http.StatusUnprocessableEntity, "plugin skills do not keep version history")+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to start transaction")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {+ slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to restore skill version")+ return+ }+ v, ok := h.loadSkillVersion(w, r, qtx, skill)+ if !ok {+ return+ }+ files, err := decodeSkillVersionFiles(v.Files)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decode skill version")+ return+ }++ updated, err := qtx.UpdateSkill(r.Context(), db.UpdateSkillParams{+ ID: skill.ID,+ Name: pgtype.Text{String: v.Name, Valid: true},+ Description: pgtype.Text{String: v.Description, Valid: true},+ Content: pgtype.Text{String: v.Content, Valid: true},+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusNotFound, "skill not found")+ return+ }+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "another skill in this workspace already uses the name \""+v.Name+"\"")+ return+ }+ slog.Warn("restore skill version failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to restore skill version")+ return+ }+ if err := qtx.DeleteSkillFilesBySkill(r.Context(), skill.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to restore skill files")+ return+ }+ fileResps := make([]SkillFileResponse, 0, len(files))+ for _, f := range files {+ if !validateFilePath(f.Path) || skillpkg.IsReservedContentPath(f.Path) {+ continue+ }+ sf, err := qtx.UpsertSkillFile(r.Context(), db.UpsertSkillFileParams{+ SkillID: skill.ID,+ Path: f.Path,+ Content: f.Content,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to restore skill files")+ return+ }+ fileResps = append(fileResps, skillFileToResponse(sf))+ }+ if _, err := recordSkillVersion(r.Context(), qtx, skill.ID, skillVersionRecord{+ Source: skillVersionSourceRestore,+ CreatedBy: parseUUID(requestUserID(r)),+ RestoredFrom: pgtype.Int4{Int32: v.Version, Valid: true},+ }); err != nil {+ slog.Warn("record skill version failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to restore skill version")+ return+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to commit")+ return+ }++ resp := SkillWithFilesResponse{+ SkillResponse: skillToResponse(updated),+ Files: fileResps,+ }+ wsID := uuidToString(skill.WorkspaceID)+ actorType, actorID := h.resolveActor(r, requestUserID(r), wsID)+ h.publish(protocol.EventSkillUpdated, wsID, actorType, actorID, map[string]any{"skill": resp})+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/skill_version_test.go b/server/internal/handler/skill_version_test.gonew file mode 100644index 0000000000..3ceccd9e3f--- /dev/null+++ b/server/internal/handler/skill_version_test.go@@ -0,0 +1,243 @@+package handler++import (+ "context"+ "net/http"+ "strconv"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func createVersionTestSkill(t *testing.T, name string, files []CreateSkillFileRequest) SkillWithFilesResponse {+ t.Helper()+ var skill SkillWithFilesResponse+ testutil.Call(t, testHandler.CreateSkill, newRequest(http.MethodPost, "/api/skills", CreateSkillRequest{+ Name: name,+ Content: "v1 body",+ Files: files,+ })).Want(http.StatusCreated).JSON(&skill)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM skill_version WHERE skill_id = $1`, skill.ID)+ testPool.Exec(context.Background(), `DELETE FROM skill WHERE id = $1`, skill.ID)+ })+ return skill+}++func listVersions(t *testing.T, skillID string) []SkillVersionSummaryResponse {+ t.Helper()+ var versions []SkillVersionSummaryResponse+ req := withURLParam(newRequest(http.MethodGet, "/api/skills/"+skillID+"/versions", nil), "id", skillID)+ testutil.Call(t, testHandler.ListSkillVersions, req).Want(http.StatusOK).JSON(&versions)+ return versions+}++func updateSkillForVersionTest(t *testing.T, skillID string, body UpdateSkillRequest) {+ t.Helper()+ req := withURLParam(newRequest(http.MethodPut, "/api/skills/"+skillID, body), "id", skillID)+ testutil.Call(t, testHandler.UpdateSkill, req).Want(http.StatusOK)+}++func skillVersionRequest(method, skillID string, version string, suffix string) *http.Request {+ req := newRequest(method, "/api/skills/"+skillID+"/versions/"+version+suffix, nil)+ return withURLParams(req, "id", skillID, "version", version)+}++func TestSkillVersionLifecycle(t *testing.T) {+ if testPool == nil {+ t.Skip("no database available")+ }++ skill := createVersionTestSkill(t, "test-skill-version-lifecycle", []CreateSkillFileRequest{+ {Path: "notes.md", Content: "v1 notes"},+ })++ versions := listVersions(t, skill.ID)+ if len(versions) != 1 || versions[0].Version != 1 || versions[0].Source != skillVersionSourceCreate {+ t.Fatalf("after create: want [v1 create], got %+v", versions)+ }++ // One save with content and files produces exactly one version.+ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{+ Content: strPtr("v2 body"),+ Files: []CreateSkillFileRequest{+ {Path: "notes.md", Content: "v2 notes"},+ {Path: "extra.md", Content: "v2 extra"},+ },+ })+ // Saving identical content records nothing.+ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{Content: strPtr("v2 body")})++ // Single-file endpoint edits are versioned too.+ fileReq := withURLParam(newRequest(http.MethodPut, "/api/skills/"+skill.ID+"/files", CreateSkillFileRequest{+ Path: "extra.md", Content: "v3 extra",+ }), "id", skill.ID)+ testutil.Call(t, testHandler.UpsertSkillFile, fileReq).Want(http.StatusOK)++ versions = listVersions(t, skill.ID)+ if len(versions) != 3 {+ t.Fatalf("want 3 versions, got %+v", versions)+ }+ for i, want := range []int32{3, 2, 1} {+ if versions[i].Version != want {+ t.Fatalf("versions not newest-first: %+v", versions)+ }+ }+ if versions[0].Source != skillVersionSourceUpdate || versions[0].CreatedBy == nil || *versions[0].CreatedBy != testUserID {+ t.Fatalf("v3 metadata: %+v", versions[0])+ }++ var v1 SkillVersionResponse+ testutil.Call(t, testHandler.GetSkillVersion, skillVersionRequest(http.MethodGet, skill.ID, "1", "")).+ Want(http.StatusOK).JSON(&v1)+ if v1.Content != "v1 body" || len(v1.Files) != 1 || v1.Files[0].Path != "notes.md" || v1.Files[0].Content != "v1 notes" {+ t.Fatalf("v1 snapshot: %+v", v1)+ }++ var restored SkillWithFilesResponse+ testutil.Call(t, testHandler.RestoreSkillVersion, skillVersionRequest(http.MethodPost, skill.ID, "1", "/restore")).+ Want(http.StatusOK).JSON(&restored)+ if restored.Content != "v1 body" || len(restored.Files) != 1 || restored.Files[0].Content != "v1 notes" {+ t.Fatalf("restore response: %+v", restored)+ }+ var fileCount int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM skill_file WHERE skill_id = $1`, skill.ID).Scan(&fileCount); err != nil {+ t.Fatal(err)+ }+ if fileCount != 1 {+ t.Fatalf("restore must drop files added after v1, got %d files", fileCount)+ }++ versions = listVersions(t, skill.ID)+ if len(versions) != 4 || versions[0].Version != 4 || versions[0].Source != skillVersionSourceRestore ||+ versions[0].RestoredFromVersion == nil || *versions[0].RestoredFromVersion != 1 {+ t.Fatalf("after restore: %+v", versions)+ }++ // Restore can itself be undone by restoring the version before it.+ testutil.Call(t, testHandler.RestoreSkillVersion, skillVersionRequest(http.MethodPost, skill.ID, "3", "/restore")).+ Want(http.StatusOK).JSON(&restored)+ if restored.Content != "v2 body" || len(restored.Files) != 2 {+ t.Fatalf("restore v3: %+v", restored)+ }++ testutil.Call(t, testHandler.GetSkillVersion, skillVersionRequest(http.MethodGet, skill.ID, "99", "")).Want(http.StatusNotFound)+ testutil.Call(t, testHandler.RestoreSkillVersion, skillVersionRequest(http.MethodPost, skill.ID, "abc", "/restore")).Want(http.StatusBadRequest)++ delReq := withURLParam(newRequest(http.MethodDelete, "/api/skills/"+skill.ID, nil), "id", skill.ID)+ testutil.Call(t, testHandler.DeleteSkill, delReq).Want(http.StatusNoContent)+ var remaining int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM skill_version WHERE skill_id = $1`, skill.ID).Scan(&remaining); err != nil {+ t.Fatal(err)+ }+ if remaining != 0 {+ t.Fatalf("delete skill must remove its versions, %d left", remaining)+ }+}++// Skills created before versioning have no history. The first write snapshots+// the pre-write state so that write can be reverted.+func TestSkillVersionBaselineForUnversionedSkill(t *testing.T) {+ if testPool == nil {+ t.Skip("no database available")+ }++ skill := createVersionTestSkill(t, "test-skill-version-baseline", nil)+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `DELETE FROM skill_version WHERE skill_id = $1`, skill.ID); err != nil {+ t.Fatal(err)+ }+ if _, err := testPool.Exec(ctx, `UPDATE skill SET content = 'legacy body' WHERE id = $1`, skill.ID); err != nil {+ t.Fatal(err)+ }++ if got := listVersions(t, skill.ID); len(got) != 0 {+ t.Fatalf("unversioned skill should list no versions, got %+v", got)+ }++ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{Content: strPtr("new body")})++ versions := listVersions(t, skill.ID)+ if len(versions) != 2 || versions[1].Source != skillVersionSourceBaseline || versions[0].Source != skillVersionSourceUpdate {+ t.Fatalf("want [v2 update, v1 baseline], got %+v", versions)+ }+ var baseline SkillVersionResponse+ testutil.Call(t, testHandler.GetSkillVersion, skillVersionRequest(http.MethodGet, skill.ID, strconv.Itoa(int(versions[1].Version)), "")).+ Want(http.StatusOK).JSON(&baseline)+ if baseline.Content != "legacy body" {+ t.Fatalf("baseline must hold the pre-write content, got %q", baseline.Content)+ }+}++// The single-file endpoints also bump the skill's updated_at (TouchSkill). The+// baseline must be taken before that bump, so it keeps the time the legacy+// content was actually written and holds none of the incoming file write.+func TestSkillVersionBaselineForUnversionedSkillFileWrites(t *testing.T) {+ if testPool == nil {+ t.Skip("no database available")+ }++ skill := createVersionTestSkill(t, "test-skill-version-baseline-files", []CreateSkillFileRequest{+ {Path: "notes.md", Content: "legacy notes"},+ })+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `DELETE FROM skill_version WHERE skill_id = $1`, skill.ID); err != nil {+ t.Fatal(err)+ }+ legacyUpdatedAt := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)+ if _, err := testPool.Exec(ctx, `UPDATE skill SET updated_at = $2 WHERE id = $1`, skill.ID, legacyUpdatedAt); err != nil {+ t.Fatal(err)+ }++ fileReq := withURLParam(newRequest(http.MethodPut, "/api/skills/"+skill.ID+"/files", CreateSkillFileRequest{+ Path: "extra.md", Content: "new extra",+ }), "id", skill.ID)+ testutil.Call(t, testHandler.UpsertSkillFile, fileReq).Want(http.StatusOK)++ versions := listVersions(t, skill.ID)+ if len(versions) != 2 || versions[1].Source != skillVersionSourceBaseline || versions[0].Source != skillVersionSourceUpdate {+ t.Fatalf("want [v2 update, v1 baseline], got %+v", versions)+ }+ if got, err := time.Parse(time.RFC3339, versions[1].CreatedAt); err != nil || !got.Equal(legacyUpdatedAt) {+ t.Fatalf("baseline must keep the legacy updated_at %s, got %q (err %v)", legacyUpdatedAt, versions[1].CreatedAt, err)+ }+ var baseline SkillVersionResponse+ testutil.Call(t, testHandler.GetSkillVersion, skillVersionRequest(http.MethodGet, skill.ID, strconv.Itoa(int(versions[1].Version)), "")).+ Want(http.StatusOK).JSON(&baseline)+ if len(baseline.Files) != 1 || baseline.Files[0].Path != "notes.md" {+ t.Fatalf("baseline must hold the pre-write files, got %+v", baseline.Files)+ }++ // Deleting a file is one more version, not a second baseline.+ var fileID string+ if err := testPool.QueryRow(ctx, `SELECT id::text FROM skill_file WHERE skill_id = $1 AND path = 'extra.md'`, skill.ID).Scan(&fileID); err != nil {+ t.Fatal(err)+ }+ delReq := withURLParams(newRequest(http.MethodDelete, "/api/skills/"+skill.ID+"/files/"+fileID, nil), "id", skill.ID, "fileId", fileID)+ testutil.Call(t, testHandler.DeleteSkillFile, delReq).Want(http.StatusNoContent)+ versions = listVersions(t, skill.ID)+ if len(versions) != 3 || versions[0].Version != 3 || versions[0].Source != skillVersionSourceUpdate {+ t.Fatalf("after file delete: want v3 update on top, got %+v", versions)+ }+}++func TestSkillVersionSkipsPluginSkills(t *testing.T) {+ if testPool == nil {+ t.Skip("no database available")+ }++ skill := createVersionTestSkill(t, "test-skill-version-plugin", nil)+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `DELETE FROM skill_version WHERE skill_id = $1`, skill.ID); err != nil {+ t.Fatal(err)+ }+ if _, err := testPool.Exec(ctx, `UPDATE skill SET plugin_installation_id = gen_random_uuid() WHERE id = $1`, skill.ID); err != nil {+ t.Fatal(err)+ }++ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{Content: strPtr("plugin edit")})+ if got := listVersions(t, skill.ID); len(got) != 0 {+ t.Fatalf("plugin skills keep no history, got %+v", got)+ }+}diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 582bdfed33..562a8b8cd9 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -127,6 +127,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"skill": workspaceDelete,"skill_file": workspaceDelete,"skill_to_label": workspaceDelete,+ "skill_version": workspaceDelete,"squad": workspaceDelete,"squad_member": workspaceDelete,"sys_cron_executions": workspaceDeleteKeep,diff --git a/server/migrations/612_skill_version.down.sql b/server/migrations/612_skill_version.down.sqlnew file mode 100644index 0000000000..51cdfab6f6--- /dev/null+++ b/server/migrations/612_skill_version.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS skill_version;diff --git a/server/migrations/612_skill_version.up.sql b/server/migrations/612_skill_version.up.sqlnew file mode 100644index 0000000000..54f481b105--- /dev/null+++ b/server/migrations/612_skill_version.up.sql@@ -0,0 +1,30 @@+-- Append-only content history for workspace skills (MUL-4066).+--+-- Every write that changes a skill's name, description, SKILL.md content, or+-- supporting files appends one immutable row holding a full snapshot of those+-- fields. The live skill / skill_file rows stay the source of truth for task+-- execution; this table only powers the version list and restore. Restoring+-- an old version writes its snapshot back to skill / skill_file and appends a+-- new row, so history only moves forward.+--+-- Skills that predate this table get their first row lazily: the first write+-- after deploy snapshots the pre-write state as a 'baseline' version before+-- applying the change. No backfill runs at migration time.+--+-- No FK, no cascade (workspace DB rules): DeleteSkill and workspace teardown+-- remove a skill's versions explicitly.+CREATE TABLE IF NOT EXISTS skill_version (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ skill_id UUID NOT NULL,+ version INTEGER NOT NULL,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ content TEXT NOT NULL DEFAULT '',+ files JSONB NOT NULL DEFAULT '[]'::jsonb,+ content_hash TEXT NOT NULL,+ source TEXT NOT NULL,+ restored_from_version INTEGER NULL,+ created_by UUID NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);diff --git a/server/migrations/613_skill_version_index.down.sql b/server/migrations/613_skill_version_index.down.sqlnew file mode 100644index 0000000000..34147107d1--- /dev/null+++ b/server/migrations/613_skill_version_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_skill_version_skill_version;diff --git a/server/migrations/613_skill_version_index.up.sql b/server/migrations/613_skill_version_index.up.sqlnew file mode 100644index 0000000000..6706dda2d9--- /dev/null+++ b/server/migrations/613_skill_version_index.up.sql@@ -0,0 +1,7 @@+-- Single-statement migration: CREATE INDEX CONCURRENTLY cannot run inside a+-- transaction or a multi-command string.+--+-- One version number per skill. Serves the version list, latest-version+-- lookup, and per-skill cleanup on delete.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_skill_version_skill_version+ ON skill_version (skill_id, version);diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 808d9e1142..9eea0a6655 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1491,6 +1491,22 @@ type SkillToLabel struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type SkillVersion struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SkillID pgtype.UUID `json:"skill_id"`+ Version int32 `json:"version"`+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ Files []byte `json:"files"`+ ContentHash string `json:"content_hash"`+ Source string `json:"source"`+ RestoredFromVersion pgtype.Int4 `json:"restored_from_version"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type Squad struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.goindex b2a94b1015..ea219b034b 100644--- a/server/pkg/db/generated/skill.sql.go+++ b/server/pkg/db/generated/skill.sql.go@@ -67,8 +67,82 @@ func (q *Queries) CreateSkill(ctx context.Context, arg CreateSkillParams) (Skillreturn i, err}+const createSkillVersion = `-- name: CreateSkillVersion :one+INSERT INTO skill_version (+ workspace_id, skill_id, version, name, description, content, files,+ content_hash, source, restored_from_version, created_by, created_at+)+VALUES (+ $1, $2, $3, $4, $5, $6, $7,+ $8, $9, $10, $11,+ COALESCE($12::timestamptz, now())+)+RETURNING id, workspace_id, skill_id, version, name, source, restored_from_version, created_by, created_at+`++type CreateSkillVersionParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SkillID pgtype.UUID `json:"skill_id"`+ Version int32 `json:"version"`+ Name string `json:"name"`+ Description string `json:"description"`+ Content string `json:"content"`+ Files []byte `json:"files"`+ ContentHash string `json:"content_hash"`+ Source string `json:"source"`+ RestoredFromVersion pgtype.Int4 `json:"restored_from_version"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++type CreateSkillVersionRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SkillID pgtype.UUID `json:"skill_id"`+ Version int32 `json:"version"`+ Name string `json:"name"`+ Source string `json:"source"`+ RestoredFromVersion pgtype.Int4 `json:"restored_from_version"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++func (q *Queries) CreateSkillVersion(ctx context.Context, arg CreateSkillVersionParams) (CreateSkillVersionRow, error) {+ row := q.db.QueryRow(ctx, createSkillVersion,+ arg.WorkspaceID,+ arg.SkillID,+ arg.Version,+ arg.Name,+ arg.Description,+ arg.Content,+ arg.Files,+ arg.ContentHash,+ arg.Source,+ arg.RestoredFromVersion,+ arg.CreatedBy,+ arg.CreatedAt,+ )+ var i CreateSkillVersionRow+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.SkillID,+ &i.Version,+ &i.Name,+ &i.Source,+ &i.RestoredFromVersion,+ &i.CreatedBy,+ &i.CreatedAt,+ )+ return i, err+}+const deleteSkill = `-- name: DeleteSkill :exec-DELETE FROM skill WHERE id = $1 AND workspace_id = $2+WITH deleted_versions AS (+ DELETE FROM skill_version+ WHERE skill_version.skill_id = $1 AND skill_version.workspace_id = $2+)+DELETE FROM skill WHERE skill.id = $1 AND skill.workspace_id = $2`type DeleteSkillParams struct {@@ -77,6 +151,8 @@ type DeleteSkillParams struct {}// Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.+// skill_version has no FK, so the skill's history is removed in the same+// statement.func (q *Queries) DeleteSkill(ctx context.Context, arg DeleteSkillParams) error {_, err := q.db.Exec(ctx, deleteSkill, arg.ID, arg.WorkspaceID)return err@@ -100,6 +176,25 @@ func (q *Queries) DeleteSkillFilesBySkill(ctx context.Context, skillID pgtype.UUreturn err}+const getLatestSkillVersion = `-- name: GetLatestSkillVersion :one+SELECT version, content_hash FROM skill_version+WHERE skill_id = $1+ORDER BY version DESC+LIMIT 1+`++type GetLatestSkillVersionRow struct {+ Version int32 `json:"version"`+ ContentHash string `json:"content_hash"`+}++func (q *Queries) GetLatestSkillVersion(ctx context.Context, skillID pgtype.UUID) (GetLatestSkillVersionRow, error) {+ row := q.db.QueryRow(ctx, getLatestSkillVersion, skillID)+ var i GetLatestSkillVersionRow+ err := row.Scan(&i.Version, &i.ContentHash)+ return i, err+}+const getSkill = `-- name: GetSkill :oneSELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skillWHERE id = $1@@ -200,6 +295,38 @@ func (q *Queries) GetSkillInWorkspace(ctx context.Context, arg GetSkillInWorkspareturn i, err}+const getSkillVersion = `-- name: GetSkillVersion :one+SELECT id, workspace_id, skill_id, version, name, description, content, files, content_hash, source, restored_from_version, created_by, created_at FROM skill_version+WHERE skill_id = $1 AND workspace_id = $2 AND version = $3+`++type GetSkillVersionParams struct {+ SkillID pgtype.UUID `json:"skill_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Version int32 `json:"version"`+}++func (q *Queries) GetSkillVersion(ctx context.Context, arg GetSkillVersionParams) (SkillVersion, error) {+ row := q.db.QueryRow(ctx, getSkillVersion, arg.SkillID, arg.WorkspaceID, arg.Version)+ var i SkillVersion+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.SkillID,+ &i.Version,+ &i.Name,+ &i.Description,+ &i.Content,+ &i.Files,+ &i.ContentHash,+ &i.Source,+ &i.RestoredFromVersion,+ &i.CreatedBy,+ &i.CreatedAt,+ )+ return i, err+}+const listAgentSkillNamesByAgentIDs = `-- name: ListAgentSkillNamesByAgentIDs :manySELECT ask.agent_id, s.nameFROM agent_skill ask@@ -605,6 +732,61 @@ func (q *Queries) ListSkillSummariesByWorkspace(ctx context.Context, workspaceIDreturn items, nil}+const listSkillVersions = `-- name: ListSkillVersions :many+SELECT id, workspace_id, skill_id, version, name, source, restored_from_version, created_by, created_at+FROM skill_version+WHERE skill_id = $1 AND workspace_id = $2+ORDER BY version DESC+`++type ListSkillVersionsParams struct {+ SkillID pgtype.UUID `json:"skill_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++type ListSkillVersionsRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ SkillID pgtype.UUID `json:"skill_id"`+ Version int32 `json:"version"`+ Name string `json:"name"`+ Source string `json:"source"`+ RestoredFromVersion pgtype.Int4 `json:"restored_from_version"`+ CreatedBy pgtype.UUID `json:"created_by"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}++// Metadata only: snapshots can be large, and the list never shows bodies.+func (q *Queries) ListSkillVersions(ctx context.Context, arg ListSkillVersionsParams) ([]ListSkillVersionsRow, error) {+ rows, err := q.db.Query(ctx, listSkillVersions, arg.SkillID, arg.WorkspaceID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListSkillVersionsRow{}+ for rows.Next() {+ var i ListSkillVersionsRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.SkillID,+ &i.Version,+ &i.Name,+ &i.Source,+ &i.RestoredFromVersion,+ &i.CreatedBy,+ &i.CreatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listSkillsByWorkspace = `-- name: ListSkillsByWorkspace :manySELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill@@ -644,6 +826,33 @@ func (q *Queries) ListSkillsByWorkspace(ctx context.Context, workspaceID pgtype.return items, nil}+const lockSkillForVersioning = `-- name: LockSkillForVersioning :one++SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill WHERE id = $1 FOR UPDATE+`++// Skill versions+// Serializes version-number allocation for one skill. Every content write+// takes this row lock inside its transaction before reading the latest+// version, so concurrent writers cannot allocate the same number.+func (q *Queries) LockSkillForVersioning(ctx context.Context, id pgtype.UUID) (Skill, error) {+ row := q.db.QueryRow(ctx, lockSkillForVersioning, id)+ var i Skill+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.Description,+ &i.Content,+ &i.Config,+ &i.CreatedBy,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.PluginInstallationID,+ )+ return i, err+}+const removeAgentSkill = `-- name: RemoveAgentSkill :execDELETE FROM agent_skillWHERE agent_id = $1 AND skill_id = $2diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex adf9b0e7b6..648a6fd268 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -623,6 +623,11 @@ func (q *Queries) DeleteWorkspaceRuntimesAndProjects(ctx context.Context, workspconst deleteWorkspaceSquadsAndSkills = `-- name: DeleteWorkspaceSquadsAndSkills :execWITH deleted_squads AS (DELETE FROM squad WHERE squad.workspace_id = $1+),+deleted_skill_versions AS (+ -- Keyed by skill_id so the delete uses idx_skill_version_skill_version.+ DELETE FROM skill_version+ WHERE skill_version.skill_id IN (SELECT skill.id FROM skill WHERE skill.workspace_id = $1))DELETE FROM skill WHERE skill.workspace_id = $1`diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sqlindex 68f72fb5a5..3ed58c14d7 100644--- a/server/pkg/db/queries/skill.sql+++ b/server/pkg/db/queries/skill.sql@@ -54,7 +54,13 @@ RETURNING *;-- name: DeleteSkill :exec-- Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.-DELETE FROM skill WHERE id = $1 AND workspace_id = $2;+-- skill_version has no FK, so the skill's history is removed in the same+-- statement.+WITH deleted_versions AS (+ DELETE FROM skill_version+ WHERE skill_version.skill_id = $1 AND skill_version.workspace_id = $2+)+DELETE FROM skill WHERE skill.id = $1 AND skill.workspace_id = $2;-- Skill File CRUD@@ -176,3 +182,40 @@ FROM agent_skill askJOIN skill s ON s.id = ask.skill_idWHERE s.workspace_id = $1ORDER BY s.name ASC;++-- Skill versions++-- name: LockSkillForVersioning :one+-- Serializes version-number allocation for one skill. Every content write+-- takes this row lock inside its transaction before reading the latest+-- version, so concurrent writers cannot allocate the same number.+SELECT * FROM skill WHERE id = $1 FOR UPDATE;++-- name: GetLatestSkillVersion :one+SELECT version, content_hash FROM skill_version+WHERE skill_id = $1+ORDER BY version DESC+LIMIT 1;++-- name: CreateSkillVersion :one+INSERT INTO skill_version (+ workspace_id, skill_id, version, name, description, content, files,+ content_hash, source, restored_from_version, created_by, created_at+)+VALUES (+ @workspace_id, @skill_id, @version, @name, @description, @content, @files,+ @content_hash, @source, sqlc.narg('restored_from_version'), sqlc.narg('created_by'),+ COALESCE(sqlc.narg('created_at')::timestamptz, now())+)+RETURNING id, workspace_id, skill_id, version, name, source, restored_from_version, created_by, created_at;++-- name: ListSkillVersions :many+-- Metadata only: snapshots can be large, and the list never shows bodies.+SELECT id, workspace_id, skill_id, version, name, source, restored_from_version, created_by, created_at+FROM skill_version+WHERE skill_id = $1 AND workspace_id = $2+ORDER BY version DESC;++-- name: GetSkillVersion :one+SELECT * FROM skill_version+WHERE skill_id = $1 AND workspace_id = $2 AND version = $3;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex d32e2c6b4f..a6c3c0079d 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -628,6 +628,11 @@ DELETE FROM vcs_connection WHERE vcs_connection.workspace_id = $1;-- name: DeleteWorkspaceSquadsAndSkills :execWITH deleted_squads AS (DELETE FROM squad WHERE squad.workspace_id = $1+),+deleted_skill_versions AS (+ -- Keyed by skill_id so the delete uses idx_skill_version_skill_version.+ DELETE FROM skill_version+ WHERE skill_version.skill_id IN (SELECT skill.id FROM skill WHERE skill.workspace_id = $1))DELETE FROM skill WHERE skill.workspace_id = $1;