Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8238: fix(skills): preserve complete bundles when source fetching fails (#9518)
Frezcbcf44eed37df
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.goindex 63360b5d8b..2c2d66fa03 100644--- a/server/internal/handler/skill.go+++ b/server/internal/handler/skill.go@@ -899,9 +899,19 @@ type githubContentEntry struct {Path string `json:"path"`Type string `json:"type"` // "file" or "dir"URL string `json:"url"`+ GitURL string `json:"git_url"`DownloadURL string `json:"download_url"`}+// isSubmodule reports whether a directory-listing entry is a Git submodule.+// For backwards compatibility the contents API lists submodules inside a+// directory as type "file" with a null download_url; their git_url points at+// the submodule repository's tree rather than a blob. The recursive tree path+// skips submodules (type "commit"), so the crawl fallback must skip them too.+func (e githubContentEntry) isSubmodule() bool {+ return e.Type == "submodule" || (e.DownloadURL == "" && strings.Contains(e.GitURL, "/git/trees/"))+}+type githubRepoInfo struct {DefaultBranch string `json:"default_branch"`}@@ -1153,26 +1163,16 @@ func fetchFromClawHub(ctx context.Context, httpClient *http.Client, rawURL strin}for _, fp := range filePaths {+ if skillpkg.IsLikelyBinaryFilePath(fp) {+ continue+ }fileURL := fmt.Sprintf("%s/skills/%s/file?path=%s", apiBase, url.PathEscape(slug), url.QueryEscape(fp))if latestVersion != "" {fileURL += "&version=" + url.QueryEscape(latestVersion)}body, err := fetchRawFile(ctx, httpClient, fileURL)if err != nil {- // Cap violations must abort: silently dropping a file would- // produce an incomplete bundle that looks valid. SKILL.md is- // load-bearing, so any failure on it is fatal too.- if isCapError(err) || fp == "SKILL.md" {- return nil, fmt.Errorf("clawhub import: %s: %w", fp, err)- }- // A cancelled context (overall deadline / client disconnect) is- // fatal for the same reason: skipping every remaining file would- // persist a half-populated bundle as a success.- if ctx.Err() != nil {- return nil, fmt.Errorf("clawhub import: fetch aborted at %s: %w", fp, ctx.Err())- }- slog.Warn("clawhub import: file download failed", "path", fp, "error", err)- continue+ return nil, fmt.Errorf("clawhub import: %s: %w", fp, err)}if fp == "SKILL.md" {result.content = string(body)@@ -1283,13 +1283,9 @@ func newSkillsShImportedSkill(skillMdBody []byte, skillName, rawURL, owner, repo}// addSupportingFilesViaCrawl is the legacy per-directory enumeration path, used-// as a fallback only for a truncated recursive tree (and by the github.com-// importer). A tree-fetch failure no longer routes here — it returns a retryable-// error instead. It lists skillDir via the contents API, recurses-// subdirectories, and downloads each file. It stays lenient on a genuine listing-// failure (returns with only SKILL.md, matching prior behavior under GitHub API-// rate limiting) but treats a cancelled context as fatal so a mid-crawl deadline-// or disconnect can't persist an incomplete bundle as a success.+// for a truncated tree, or an unavailable tree for github.com imports. Every+// directory and eligible file must be read before a bundle can replace local+// content; an unavailable listing does not prove that a directory is empty.func addSupportingFilesViaCrawl(ctx context.Context, httpClient *http.Client, result *importedSkill, owner, repo, ref, skillDir string) error {apiURL := buildGitHubContentsURL(owner, repo, skillDir, ref)dirResp, err := doGitHubAPIGet(ctx, httpClient, apiURL)@@ -1303,7 +1299,10 @@ func addSupportingFilesViaCrawl(ctx context.Context, httpClient *http.Client, reif ctx.Err() != nil {return fmt.Errorf("github import: directory listing aborted: %w", ctx.Err())}- return nil+ if err != nil {+ return fmt.Errorf("%w: listing %s: %w", errImportSourceUnavailable, apiURL, err)+ }+ return fmt.Errorf("%w: listing %s: HTTP %d", errImportSourceUnavailable, apiURL, dirResp.StatusCode)}defer dirResp.Body.Close()@@ -1316,16 +1315,15 @@ func addSupportingFilesViaCrawl(ctx context.Context, httpClient *http.Client, reif ctx.Err() != nil {return fmt.Errorf("github import: directory listing read aborted: %w", ctx.Err())}- slog.Warn("github import: failed to decode top-level directory listing", "url", apiURL, "error", err)- return nil+ return fmt.Errorf("%w: decoding directory %s: %w", errImportSourceUnavailable, apiURL, err)+ }+ if entries == nil {+ return fmt.Errorf("%w: directory %s is not a file list", errImportSourceUnavailable, apiURL)}var allFiles []githubContentEntry- collectGitHubFiles(ctx, httpClient, entries, &allFiles, apiURL)- // collectGitHubFiles is lenient on a failed subdirectory listing; if the- // context was cancelled mid-crawl the collected set is incomplete, so abort.- if ctx.Err() != nil {- return fmt.Errorf("github import: directory crawl aborted: %w", ctx.Err())+ if err := collectGitHubFiles(ctx, httpClient, entries, &allFiles, apiURL); err != nil {+ return err}basePath := ""@@ -1334,18 +1332,11 @@ func addSupportingFilesViaCrawl(ctx context.Context, httpClient *http.Client, re}for _, entry := range allFiles {if entry.DownloadURL == "" {- continue+ return fmt.Errorf("%w: no download URL for %s", errImportSourceUnavailable, entry.Path)}body, err := fetchRawFile(ctx, httpClient, entry.DownloadURL)if err != nil {- if isCapError(err) {- return fmt.Errorf("github import: %s: %w", entry.Path, err)- }- if ctx.Err() != nil {- return fmt.Errorf("github import: fetch aborted at %s: %w", entry.Path, ctx.Err())- }- slog.Warn("github import: file download failed", "path", entry.Path, "error", err)- continue+ return fmt.Errorf("github import: %s: %w", entry.Path, err)}relPath := strings.TrimPrefix(entry.Path, basePath)if err := result.addFile(relPath, string(body)); err != nil {@@ -1376,6 +1367,9 @@ func fetchGitHubTree(ctx context.Context, httpClient *http.Client, owner, repo,if err := json.NewDecoder(resp.Body).Decode(&tree); err != nil {return nil, false, err}+ if tree.Tree == nil {+ return nil, false, fmt.Errorf("GitHub tree response has no entries")+ }return tree.Tree, tree.Truncated, nil}@@ -1547,7 +1541,6 @@ func addSupportingFilesFromTree(ctx context.Context, httpClient *http.Client, re// Download concurrently, then append in the pre-sorted order.contents := make([]string, len(eligible))- fetched := make([]bool, len(eligible))g, gctx := errgroup.WithContext(ctx)g.SetLimit(treeDownloadConcurrency)for i, f := range eligible {@@ -1555,26 +1548,9 @@ func addSupportingFilesFromTree(ctx context.Context, httpClient *http.Client, reg.Go(func() error {body, err := fetchRawFile(gctx, httpClient, buildRawGitHubURL(rawPrefix, f.repoPath))if err != nil {- if isCapError(err) {- return fmt.Errorf("github import: %s: %w", f.repoPath, err)- }- // A cancelled context (overall import deadline exceeded, or the- // client disconnecting) must abort, not be swallowed as a- // per-file skip: otherwise every remaining download fails the- // same way, g.Wait returns nil, and the user gets a bundle that- // looks complete but is silently missing files. Let it surface- // so importFetchErrorResponse maps the deadline to a readable- // 504.- if gctx.Err() != nil {- return fmt.Errorf("github import: fetch aborted at %s: %w", f.repoPath, gctx.Err())- }- // Otherwise match the legacy loop's leniency: a single failed- // supporting file is logged and skipped, not fatal.- slog.Warn("github import: file download failed", "path", f.repoPath, "error", err)- return nil+ return fmt.Errorf("github import: %s: %w", f.repoPath, err)}contents[i] = string(body)- fetched[i] = truereturn nil})}@@ -1583,9 +1559,6 @@ func addSupportingFilesFromTree(ctx context.Context, httpClient *http.Client, re}for i, f := range eligible {- if !fetched[i] {- continue- }if err := result.addFile(f.relPath, contents[i]); err != nil {return err}@@ -1603,18 +1576,22 @@ func (e githubTreeEntry) size() int64 {}// collectGitHubFiles recursively collects file entries from a GitHub directory listing.-func collectGitHubFiles(ctx context.Context, httpClient *http.Client, entries []githubContentEntry, out *[]githubContentEntry, parentURL string) {+func collectGitHubFiles(ctx context.Context, httpClient *http.Client, entries []githubContentEntry, out *[]githubContentEntry, parentURL string) error {for _, entry := range entries {- // Stop descending once the context is cancelled; the caller checks- // ctx.Err() afterwards and aborts rather than importing a partial crawl.if ctx.Err() != nil {- return+ return fmt.Errorf("github import: directory crawl aborted: %w", ctx.Err())}lower := strings.ToLower(entry.Name)if lower == "skill.md" || lower == "license" || lower == "license.txt" || lower == "license.md" {continue}+ if entry.isSubmodule() {+ continue+ }if entry.Type == "file" {+ if skillpkg.IsLikelyBinaryFilePath(entry.Path) {+ continue+ }*out = append(*out, entry)} else if entry.Type == "dir" {// Fetch subdirectory contents@@ -1622,35 +1599,36 @@ func collectGitHubFiles(ctx context.Context, httpClient *http.Client, entries []if subURL == "" {parsed, err := url.Parse(parentURL)if err != nil {- slog.Warn("github import: invalid parent directory url", "url", parentURL, "error", err)- continue+ return fmt.Errorf("%w: invalid directory URL: %w", errImportSourceUnavailable, err)}parsed.Path = strings.TrimSuffix(parsed.Path, "/") + "/" + entry.NamesubURL = parsed.String()}subResp, err := doGitHubAPIGet(ctx, httpClient, subURL)if err != nil || subResp.StatusCode != http.StatusOK {- attrs := []any{"url", subURL}if subResp != nil {- attrs = append(attrs, "status", subResp.StatusCode)subResp.Body.Close()}if err != nil {- attrs = append(attrs, "error", err)+ return fmt.Errorf("%w: listing %s: %w", errImportSourceUnavailable, subURL, err)}- slog.Warn("github import: failed to list subdirectory", attrs...)- continue+ return fmt.Errorf("%w: listing %s: HTTP %d", errImportSourceUnavailable, subURL, subResp.StatusCode)}var subEntries []githubContentEntryif err := json.NewDecoder(subResp.Body).Decode(&subEntries); err != nil {subResp.Body.Close()- slog.Warn("github import: failed to decode subdirectory listing", "url", subURL, "error", err)- continue+ return fmt.Errorf("%w: decoding directory %s: %w", errImportSourceUnavailable, subURL, err)}subResp.Body.Close()- collectGitHubFiles(ctx, httpClient, subEntries, out, subURL)+ if subEntries == nil {+ return fmt.Errorf("%w: directory %s is not a file list", errImportSourceUnavailable, subURL)+ }+ if err := collectGitHubFiles(ctx, httpClient, subEntries, out, subURL); err != nil {+ return err+ }}}+ return nil}func findSkillDirFromConventionalPrefixes(ctx context.Context, httpClient *http.Client, owner, repo, defaultBranch, rawPrefix, skillName string) (string, []byte, bool) {@@ -2087,9 +2065,8 @@ func fetchFromGitHub(ctx context.Context, httpClient *http.Client, rawURL string// Enumerate supporting files from a single recursive tree, checking the// import caps against the tree metadata before downloading anything. Fall- // back to the per-directory contents crawl when the tree is unavailable or- // truncated (kept lenient so a rate-limited listing doesn't fail an import- // that already produced a valid SKILL.md).+ // back to a complete per-directory contents crawl when the tree is unavailable+ // or truncated. Neither path may publish a partially fetched bundle.tree, truncated, treeErr := fetchGitHubTree(ctx, httpClient, spec.owner, spec.repo, spec.ref)if treeErr == nil && !truncated {if err := addSupportingFilesFromTree(ctx, httpClient, result, tree, rawPrefix, spec.skillDir); err != nil {diff --git a/server/internal/handler/skill_refresh_atomic_test.go b/server/internal/handler/skill_refresh_atomic_test.gonew file mode 100644index 0000000000..5e941f8814--- /dev/null+++ b/server/internal/handler/skill_refresh_atomic_test.go@@ -0,0 +1,208 @@+package handler++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestRefreshSkill_GitHubBundleIsAtomic(t *testing.T) {+ for _, tc := range []struct {+ name string+ treeStatus int+ crawl bool+ listingError string+ fileStatus int+ shortBody bool+ submodule bool+ want int+ }{+ {name: "complete tree", want: 200},+ {name: "complete crawl", crawl: true, want: 200},+ {name: "tree skips submodule", submodule: true, want: 200},+ {name: "crawl skips submodule", crawl: true, submodule: true, want: 200},+ {name: "tree unavailable complete crawl", treeStatus: 403, crawl: true, want: 200},+ {name: "tree and crawl unavailable", treeStatus: 403, listingError: "root status", want: 503},+ {name: "root listing unavailable", crawl: true, listingError: "root status", want: 503},+ {name: "root listing malformed", crawl: true, listingError: "root json", want: 503},+ {name: "root listing null", crawl: true, listingError: "root null", want: 503},+ {name: "nested listing unavailable", crawl: true, listingError: "nested status", want: 503},+ {name: "nested listing malformed", crawl: true, listingError: "nested json", want: 503},+ {name: "nested listing null", crawl: true, listingError: "nested null", want: 503},+ {name: "missing download url", crawl: true, listingError: "download url", want: 503},+ {name: "tree file unavailable", fileStatus: 503, want: 502},+ {name: "tree file missing", fileStatus: 404, want: 502},+ {name: "tree file body interrupted", shortBody: true, want: 502},+ {name: "crawl file unavailable", crawl: true, fileStatus: 503, want: 502},+ {name: "crawl file body interrupted", crawl: true, shortBody: true, want: 502},+ } {+ t.Run(tc.name, func(t *testing.T) {+ userID := dbfx.User(t, "Refresh member", fmt.Sprintf("refresh-%[email protected]", time.Now().UnixNano()))+ dbfx.Member(t, testWorkspaceID, userID, "member")+ skill := dbfx.Insert(t, "skill", testutil.Cols{+ "workspace_id": testWorkspaceID, "created_by": userID, "name": "foo", "description": "old description", "content": "# Original",+ "config": `{"keep":"original","origin":{"type":"github","source_url":"https://github.com/acme/skills/tree/main/skills/foo"}}`,+ })+ dbfx.Insert(t, "skill_file", testutil.Cols{"skill_id": skill, "path": "old.md", "content": "old auxiliary content"})+ agent := dbfx.Agent(t, "Bound refresh agent", testRuntimeID, testutil.Cols{"workspace_id": testWorkspaceID, "owner_id": userID})+ dbfx.InsertNoID(t, "agent_skill", testutil.Cols{"agent_id": agent, "skill_id": skill}, "agent_id=$1 AND skill_id=$2", agent, skill)+ snapshot := func() string {+ var state string+ dbfx.QueryRow(t, `SELECT jsonb_build_object('skill',to_jsonb(s),+ 'files',(SELECT jsonb_agg(to_jsonb(f) ORDER BY f.path) FROM skill_file f WHERE f.skill_id=s.id),+ 'bindings',(SELECT jsonb_agg(to_jsonb(b) ORDER BY b.agent_id) FROM agent_skill b WHERE b.skill_id=s.id))::text+ FROM skill s WHERE s.id=$1`, skill).Scan(&state)+ return state+ }+ before := snapshot()+ client, requests := newGitHubFixtureClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.Contains(r.URL.Path, "/commits/"):+ if strings.HasSuffix(r.URL.Path, "/commits/main") {+ w.WriteHeader(http.StatusOK)+ } else {+ http.NotFound(w, r)+ }+ case strings.Contains(r.URL.Path, "/git/trees/"):+ if tc.treeStatus != 0 {+ w.WriteHeader(tc.treeStatus)+ return+ }+ tree := []githubTreeEntry{+ {Path: "skills/foo/SKILL.md", Type: "blob"},+ {Path: "skills/foo/refs/guide.md", Type: "blob", Size: 11},+ {Path: "skills/foo/image.png", Type: "blob"},+ }+ if tc.submodule {+ tree = append(tree, githubTreeEntry{Path: "skills/foo/vendor", Type: "commit"})+ }+ writeJSON(w, 200, githubTreeResponse{Truncated: tc.crawl, Tree: tree})+ case strings.HasSuffix(r.URL.Path, "/contents/skills/foo"):+ switch tc.listingError {+ case "root status":+ w.WriteHeader(403)+ case "root json":+ fmt.Fprint(w, "{invalid")+ case "root null":+ fmt.Fprint(w, "null")+ default:+ entries := []githubContentEntry{{Name: "refs", Path: "skills/foo/refs", Type: "dir"}, {Name: "image.png", Path: "skills/foo/image.png", Type: "file"}}+ if tc.submodule {+ // Directory listings report submodules as type "file" with a+ // null download_url and a git_url pointing at a tree.+ entries = append(entries, githubContentEntry{Name: "vendor", Path: "skills/foo/vendor", Type: "file",+ GitURL: "https://api.github.com/repos/acme/vendor/git/trees/855827c583bc30645ba427885caa40c5b81764d2"})+ }+ writeJSON(w, 200, entries)+ }+ case strings.HasSuffix(r.URL.Path, "/contents/skills/foo/refs"):+ switch tc.listingError {+ case "nested status":+ w.WriteHeader(503)+ case "nested json":+ fmt.Fprint(w, "{invalid")+ case "nested null":+ fmt.Fprint(w, "null")+ default:+ fileURL := "https://raw.githubusercontent.com/acme/skills/main/skills/foo/refs/guide.md"+ if tc.listingError == "download url" {+ fileURL = ""+ }+ writeJSON(w, 200, []githubContentEntry{{Name: "guide.md", Path: "skills/foo/refs/guide.md", Type: "file", DownloadURL: fileURL}})+ }+ case strings.HasSuffix(r.URL.Path, "/SKILL.md"):+ fmt.Fprint(w, "---\nname: foo\ndescription: refreshed\n---\n# Refreshed")+ case strings.HasSuffix(r.URL.Path, "/refs/guide.md"):+ if tc.fileStatus != 0 {+ w.WriteHeader(tc.fileStatus)+ return+ }+ if tc.shortBody {+ w.Header().Set("Content-Length", "100")+ }+ fmt.Fprint(w, "fresh guide")+ default:+ t.Errorf("unexpected upstream request: %s", r.URL.Path)+ http.NotFound(w, r)+ }+ })+ previous := http.DefaultTransport+ http.DefaultTransport = client.Transport+ t.Cleanup(func() { http.DefaultTransport = previous })+ request := func(id string) *http.Request {+ return testutil.WithURLParams(newRequestAsUser(userID, "POST", "/api/skills/"+id+"/refresh", nil), "id", id)+ }+ if tc.want != http.StatusOK {+ testutil.Call(t, testHandler.RefreshSkill, request(skill)).Want(tc.want)+ if after := snapshot(); after != before {+ t.Fatalf("failed refresh changed skill, files or bindings:\nbefore=%s\nafter=%s", before, after)+ }+ } else {+ var response SkillWithFilesResponse+ testutil.Call(t, testHandler.RefreshSkill, request(skill)).Want(200).JSON(&response)+ if response.CreatedBy == nil || *response.CreatedBy != userID || response.Content != "---\nname: foo\ndescription: refreshed\n---\n# Refreshed" || len(response.Files) != 1 || response.Files[0].Path != "refs/guide.md" || response.Files[0].Content != "fresh guide" {+ t.Fatalf("incomplete or incorrectly authorized refresh: %+v", response)+ }+ var bound bool+ dbfx.QueryRow(t, "SELECT EXISTS(SELECT 1 FROM agent_skill WHERE agent_id=$1 AND skill_id=$2)", agent, skill).Scan(&bound)+ if !bound || skillFilePaths(t, skill)["old.md"] {+ t.Fatal("successful refresh lost binding or retained obsolete file")+ }+ }+ foreign := dbfx.Insert(t, "skill", testutil.Cols{"workspace_id": testWorkspaceID, "created_by": testUserID, "name": "foreign", "content": "foreign original"})+ requestCount := len(*requests)+ testutil.Call(t, testHandler.RefreshSkill, request(foreign)).Want(403)+ if len(*requests) != requestCount {+ t.Fatal("unauthorized refresh contacted upstream")+ }+ })+ }+}++func TestRefreshSkill_ClawHubDownloadFailurePreservesBundle(t *testing.T) {+ for _, failure := range []string{"unavailable", "missing", "interrupted body"} {+ t.Run(failure, func(t *testing.T) {+ userID := dbfx.User(t, "Refresh member", fmt.Sprintf("refresh-%[email protected]", time.Now().UnixNano()))+ dbfx.Member(t, testWorkspaceID, userID, "member")+ skill := dbfx.Insert(t, "skill", testutil.Cols{"workspace_id": testWorkspaceID, "created_by": userID, "name": "old name", "content": "# Original", "config": clawhubOriginConfig("atomic")})+ dbfx.Insert(t, "skill_file", testutil.Cols{"skill_id": skill, "path": "old.md", "content": "old guide"})+ var before string+ dbfx.QueryRow(t, "SELECT to_jsonb(s)::text FROM skill s WHERE id=$1", skill).Scan(&before)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/versions/1.0.0"):+ fmt.Fprint(w, `{"version":{"files":[{"path":"SKILL.md"},{"path":"guide.md"}]}}`)+ case strings.HasSuffix(r.URL.Path, "/file"):+ if r.URL.Query().Get("path") == "SKILL.md" {+ fmt.Fprint(w, "# Fresh")+ } else if failure == "interrupted body" {+ w.Header().Set("Content-Length", "100")+ fmt.Fprint(w, "short")+ } else if failure == "missing" {+ w.WriteHeader(404)+ } else {+ w.WriteHeader(503)+ }+ default:+ fmt.Fprint(w, `{"skill":{"displayName":"new name","tags":{"latest":"1.0.0"}}}`)+ }+ }))+ t.Cleanup(srv.Close)+ previous := clawHubAPIBase+ clawHubAPIBase = srv.URL+ t.Cleanup(func() { clawHubAPIBase = previous })+ testutil.Call(t, testHandler.RefreshSkill, testutil.WithURLParams(newRequestAsUser(userID, "POST", "/api/skills/"+skill+"/refresh", nil), "id", skill)).Want(502)+ var after, guide string+ dbfx.QueryRow(t, "SELECT to_jsonb(s)::text FROM skill s WHERE id=$1", skill).Scan(&after)+ dbfx.QueryRow(t, "SELECT content FROM skill_file WHERE skill_id=$1 AND path='old.md'", skill).Scan(&guide)+ if after != before || guide != "old guide" {+ t.Fatal("failed ClawHub download changed the existing bundle")+ }+ })+ }+}diff --git a/server/internal/handler/skill_test.go b/server/internal/handler/skill_test.goindex 3159f97430..f2865f2e66 100644--- a/server/internal/handler/skill_test.go+++ b/server/internal/handler/skill_test.go@@ -5,7 +5,6 @@ import ("context""errors""fmt"- "log/slog""net/http""net/http/httptest""net/url"@@ -188,7 +187,7 @@ func TestFetchFromSkillsSh_FallbackDoesNotDoubleEscapeDirectoryNames(t *testing.}}-func TestFetchFromSkillsSh_LogsSubdirectoryFailures(t *testing.T) {+func TestFetchFromSkillsSh_RejectsSubdirectoryFailures(t *testing.T) {client, _ := newGitHubFixtureClient(t, func(w http.ResponseWriter, r *http.Request) {switch r.Header.Get("X-Test-Original-Host") {case "api.github.com":@@ -226,30 +225,12 @@ func TestFetchFromSkillsSh_LogsSubdirectoryFailures(t *testing.T) {}})- var logs bytes.Buffer- prev := slog.Default()- slog.SetDefault(slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelInfo})))- t.Cleanup(func() {- slog.SetDefault(prev)- })-result, err := fetchFromSkillsSh(t.Context(), client, "https://skills.sh/acme/skills/pptx")- if err != nil {- t.Fatalf("fetchFromSkillsSh: %v", err)+ if result != nil || !errors.Is(err, errImportSourceUnavailable) {+ t.Fatalf("expected incomplete listing to fail, got result=%+v error=%v", result, err)}- if len(result.files) != 0 {- t.Fatalf("expected no files when subdirectory listing fails, got %v", importedFilePaths(result.files))- }-- logOutput := logs.String()- if !strings.Contains(logOutput, "github import: failed to list subdirectory") {- t.Fatalf("expected warning log, got %q", logOutput)- }- if !strings.Contains(logOutput, "status=404") {- t.Fatalf("expected status in warning log, got %q", logOutput)- }- if !strings.Contains(logOutput, "skills/pptx/scripts?ref=main") {- t.Fatalf("expected subdirectory URL in warning log, got %q", logOutput)+ if !strings.Contains(err.Error(), "HTTP 404") || !strings.Contains(err.Error(), "skills/pptx/scripts?ref=main") {+ t.Fatalf("error must identify the failed subdirectory and status: %v", err)}}@@ -1570,49 +1551,41 @@ func TestFetchFromGitHub_UnresolvableRefFailsLoudly(t *testing.T) {}}-// When the GitHub API responds 403 (rate-limited or auth-blocked) on the-// ref-resolution probe, the import should NOT fail outright. The optimistic-// single-segment split (ref = first segment, rest = path) is correct for-// the overwhelming majority of URLs, so we fall back to it and let the raw-// SKILL.md fetch be the source of truth. This covers the common case of-// self-hosted servers hitting GitHub's 60-req/hour unauthenticated limit.+// Ref resolution may use the optimistic split, but supporting-file enumeration+// must still succeed before that bundle can be published.func TestFetchFromGitHub_FallsBackOnAPIBlocked(t *testing.T) {- client, _ := newGitHubFixtureClient(t, func(w http.ResponseWriter, r *http.Request) {- switch r.Header.Get("X-Test-Original-Host") {- case "api.github.com":- // Simulate rate-limit on every commits probe and on contents.- if strings.HasPrefix(r.URL.Path, "/repos/anthropics/skills/commits/") {- http.Error(w, "rate limit", http.StatusForbidden)+ for _, enumerationBlocked := range []bool{false, true} {+ t.Run(fmt.Sprintf("enumeration_blocked_%t", enumerationBlocked), func(t *testing.T) {+ client, _ := newGitHubFixtureClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.Header.Get("X-Test-Original-Host") {+ case "api.github.com":+ if strings.Contains(r.URL.Path, "/contents/") && !enumerationBlocked {+ writeJSON(w, 200, []githubContentEntry{})+ return+ }+ http.Error(w, "rate limit", http.StatusForbidden)+ case "raw.githubusercontent.com":+ if r.URL.Path == "/anthropics/skills/main/skills/pptx/SKILL.md" {+ fmt.Fprint(w, "---\nname: pptx\ndescription: PowerPoint skill\n---\nbody")+ return+ }+ http.NotFound(w, r)+ }+ })+ result, err := fetchFromGitHub(t.Context(), client, "https://github.com/anthropics/skills/tree/main/skills/pptx")+ if enumerationBlocked {+ if result != nil || !errors.Is(err, errImportSourceUnavailable) {+ t.Fatalf("expected blocked enumeration to fail, got result=%+v error=%v", result, err)+ }return}- if strings.HasPrefix(r.URL.Path, "/repos/anthropics/skills/contents/") {- http.Error(w, "rate limit", http.StatusForbidden)- return+ if err != nil {+ t.Fatal(err)}- http.NotFound(w, r)- case "raw.githubusercontent.com":- switch r.URL.Path {- case "/anthropics/skills/main/skills/pptx/SKILL.md":- w.Write([]byte("---\nname: pptx\ndescription: PowerPoint skill\n---\nbody"))- default:- http.NotFound(w, r)+ if result.name != "pptx" || result.origin["ref"] != "main" || result.origin["path"] != "skills/pptx" {+ t.Fatalf("unexpected optimistic ref fallback: %+v", result)}- default:- http.NotFound(w, r)- }- })- result, err := fetchFromGitHub(t.Context(), client, "https://github.com/anthropics/skills/tree/main/skills/pptx")- if err != nil {- t.Fatalf("fetchFromGitHub: %v", err)- }- if result.origin["ref"] != "main" {- t.Fatalf("origin ref = %v, want main (optimistic fallback)", result.origin["ref"])- }- if result.origin["path"] != "skills/pptx" {- t.Fatalf("origin path = %v, want skills/pptx (optimistic fallback)", result.origin["path"])- }- if result.name != "pptx" {- t.Fatalf("name = %q, want pptx", result.name)+ })}}diff --git a/server/internal/service/builtin_skills/multica-platform/references/skill-import.md b/server/internal/service/builtin_skills/multica-platform/references/skill-import.mdindex de16f2c32f..58fa69d0ee 100644--- a/server/internal/service/builtin_skills/multica-platform/references/skill-import.md+++ b/server/internal/service/builtin_skills/multica-platform/references/skill-import.md@@ -63,6 +63,11 @@ multica skill import --url github.com/owner/repo/blob/main/path/to/SKILL.md --ou- A bare ClawHub slug (no host) is accepted and routed to ClawHub.- Any other host is rejected with a 400 naming the supported sources.+URL imports and refreshes require every directory listing and eligible+supporting-file download to succeed before saving the bundle. A failed refresh+leaves the existing content, supporting files, and agent-skill bindings unchanged;+a failed listing is not treated as an empty directory.+## Local archive import`multica skill import --file <path> --output json` imports a skill from a local