Skip to content

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

Go

MUL-6639: fix(skills): metadata-only skill listings and stall-based timeouts (#7574)

Bohan Jiang54027ba763fa
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 8d448e81fb..0ae7d0985b 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -988,3 +988,47 @@ always at least this value, so raising it takes effect across all commands.
```bash
MULTICA_HTTP_TIMEOUT=60s multica issue list
```
+
+### Stall detection (skill commands)
+
+A total-elapsed timeout punishes the transfer that is working: a large skill
+arriving steadily over a slow link is cut off mid-body, while a dead connection
+is held open for the full budget. The `skill` commands therefore fail on a lack
+of *progress* instead:
+
+- A read that receives no bytes for **15 seconds** fails immediately, reported
+ as a stalled transfer rather than a timeout.
+- A transfer that keeps producing bytes runs to completion, however long it
+ takes, behind a loose **10 minute** whole-request ceiling.
+
+Override the no-progress budget with `MULTICA_HTTP_STALL_TIMEOUT` (same format
+as `MULTICA_HTTP_TIMEOUT`). If only `MULTICA_HTTP_TIMEOUT` is set it applies on
+this path too, as the no-progress budget — it keeps meaning "the longest I will
+wait for this server", not "the longest this download may take".
+
+```bash
+MULTICA_HTTP_STALL_TIMEOUT=45s multica skill get <id>
+```
+
+Every other command still uses the total-elapsed timeout above. Stall detection
+starts here because skill payloads are the largest responses the CLI reads; the
+mechanism itself is not skill-specific.
+
+### Skill payload size
+
+`multica skill get` and `multica skill files list` return **metadata only** by
+default — path, byte size and content hash for each file, plus the size and
+hash of the SKILL.md body. Sizes are what tell you which file makes a skill
+large, and they stay available no matter how large it gets.
+
+Pass `--with-content` when you actually need the bodies:
+
+```bash
+multica skill files list <id> # paths and sizes
+multica skill files list <id> --with-content # bodies inlined
+```
+
+On the API, both endpoints accept `?include=content` and `?include=metadata`.
+A request that sends neither still gets `content`, on both endpoints, so a
+server upgrade never changes what an un-upgraded client receives — it is the
+CLI that asks for the smaller shape.
diff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.go
index 953ff1eb27..dd4c134c1b 100644
--- a/server/cmd/multica/cmd_skill.go
+++ b/server/cmd/multica/cmd_skill.go
@@ -32,7 +32,7 @@ var skillListCmd = &cobra.Command{
var skillGetCmd = &cobra.Command{
Use: "get <id>",
- Short: "Get skill details (includes files)",
+ Short: "Get skill details and its file list (use --with-content for the bodies)",
Args: exactArgs(1),
RunE: runSkillGet,
}
@@ -125,6 +125,7 @@ func init() {
// skill get
skillGetCmd.Flags().String("output", "json", "Output format: table or json")
+ skillGetCmd.Flags().Bool("with-content", false, "Include the SKILL.md body and every file body. Off by default: the response grows with the skill and large skills cannot be fetched this way over slow links.")
// skill create
skillCreateCmd.Flags().String("name", "", "Skill name (required)")
@@ -161,6 +162,7 @@ func init() {
// skill files list
skillFilesListCmd.Flags().String("output", "table", "Output format: table or json")
+ skillFilesListCmd.Flags().Bool("with-content", false, "Include each file's body. Off by default: use it to read a file, not to list them.")
// skill files upsert
skillFilesUpsertCmd.Flags().String("path", "", "File path within the skill (required)")
@@ -174,6 +176,51 @@ func init() {
// Skill commands
// ---------------------------------------------------------------------------
+// newSkillAPIClient is newAPIClient with the transport swapped for the
+// stall-aware one (see internal/cli/stall.go). Skill payloads are the largest
+// responses the CLI reads, so they are where a total-elapsed deadline breaks
+// first — a 599KB skill could not be fetched at all over a link that was
+// delivering it perfectly well, just not within 30s (GH #7498).
+//
+// It reuses newAPIClient rather than duplicating credential and header
+// resolution: this is a pilot of which commands adopt the mechanism, not a
+// second CLI client. Graduating it means moving the transport into
+// cli.NewAPIClient and deleting this function.
+func newSkillAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return nil, err
+ }
+ client.HTTPClient = cli.NewStallAwareHTTPClient()
+ return client, nil
+}
+
+// skillFileSizeCell renders the `size` field of a file-metadata response.
+//
+// It cannot go through strVal: JSON numbers decode as float64, and strVal's
+// %v prints a 1.2MB file as "1.234567e+06" — unreadable exactly when the file
+// is big enough to be the one you are looking for. formatBytes is the same
+// renderer the daemon table uses.
+func skillFileSizeCell(m map[string]any) string {
+ size, ok := m["size"].(float64)
+ if !ok {
+ return strVal(m, "size")
+ }
+ return formatBytes(int64(size))
+}
+
+// skillIncludeQuery renders the ?include= parameter the skill endpoints take.
+// The CLI asks for metadata by default: `skill get`'s table view prints four
+// columns, and `skill files list` prints none of the file bodies, so pulling
+// every byte of content to render them was pure cost — and, past a few hundred
+// KB, the reason neither command completed.
+func skillIncludeQuery(cmd *cobra.Command) string {
+ if withContent, _ := cmd.Flags().GetBool("with-content"); withContent {
+ return "?include=content"
+ }
+ return "?include=metadata"
+}
+
// resolveSkillContentFlag intentionally stays separate from resolveTextFlag.
// Skill bodies are Markdown documents where byte-level preservation matters:
// inline --content is not backslash-unescaped, and stdin/file input is not
@@ -262,16 +309,16 @@ func runSkillList(cmd *cobra.Command, _ []string) error {
}
func runSkillGet(cmd *cobra.Command, args []string) error {
- client, err := newAPIClient(cmd)
+ client, err := newSkillAPIClient(cmd)
if err != nil {
return err
}
- ctx, cancel := cli.APIContext(context.Background())
+ ctx, cancel := cli.StallAwareContext(context.Background())
defer cancel()
var skill map[string]any
- if err := client.GetJSON(ctx, "/api/skills/"+args[0], &skill); err != nil {
+ if err := client.GetJSON(ctx, "/api/skills/"+args[0]+skillIncludeQuery(cmd), &skill); err != nil {
return fmt.Errorf("get skill: %w", err)
}
@@ -637,16 +684,16 @@ func runSkillSearch(cmd *cobra.Command, args []string) error {
// ---------------------------------------------------------------------------
func runSkillFilesList(cmd *cobra.Command, args []string) error {
- client, err := newAPIClient(cmd)
+ client, err := newSkillAPIClient(cmd)
if err != nil {
return err
}
- ctx, cancel := cli.APIContext(context.Background())
+ ctx, cancel := cli.StallAwareContext(context.Background())
defer cancel()
var files []map[string]any
- if err := client.GetJSON(ctx, "/api/skills/"+args[0]+"/files", &files); err != nil {
+ if err := client.GetJSON(ctx, "/api/skills/"+args[0]+"/files"+skillIncludeQuery(cmd), &files); err != nil {
return fmt.Errorf("list skill files: %w", err)
}
@@ -655,15 +702,23 @@ func runSkillFilesList(cmd *cobra.Command, args []string) error {
return cli.PrintJSON(os.Stdout, files)
}
- headers := []string{"ID", "PATH", "CREATED_AT", "UPDATED_AT"}
+ // SIZE is what makes an oversized skill diagnosable: it names the file to
+ // look at without downloading any of them. The content shape carries no
+ // size field, so the column is dropped under --with-content rather than
+ // rendered empty.
+ withContent, _ := cmd.Flags().GetBool("with-content")
+ headers := []string{"ID", "PATH", "SIZE", "CREATED_AT", "UPDATED_AT"}
+ if withContent {
+ headers = []string{"ID", "PATH", "CREATED_AT", "UPDATED_AT"}
+ }
rows := make([][]string, 0, len(files))
for _, f := range files {
- rows = append(rows, []string{
- strVal(f, "id"),
- strVal(f, "path"),
- strVal(f, "created_at"),
- strVal(f, "updated_at"),
- })
+ row := []string{strVal(f, "id"), strVal(f, "path")}
+ if !withContent {
+ row = append(row, skillFileSizeCell(f))
+ }
+ row = append(row, strVal(f, "created_at"), strVal(f, "updated_at"))
+ rows = append(rows, row)
}
cli.PrintTable(os.Stdout, headers, rows)
return nil
diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.go
index b0e0e4855e..a5c335d08e 100644
--- a/server/cmd/multica/cmd_skill_test.go
+++ b/server/cmd/multica/cmd_skill_test.go
@@ -542,3 +542,130 @@ func TestRunSkillRefreshJsonPrintsSkill(t *testing.T) {
t.Fatalf("got = %#v", got)
}
}
+
+func newSkillGetTestCmd(withContent bool) *cobra.Command {
+ cmd := &cobra.Command{Use: "get"}
+ cmd.Flags().String("server-url", "", "")
+ cmd.Flags().String("workspace-id", "", "")
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().String("output", "json", "")
+ cmd.Flags().Bool("with-content", withContent, "")
+ return cmd
+}
+
+func newSkillFilesListTestCmd(withContent bool) *cobra.Command {
+ cmd := &cobra.Command{Use: "list"}
+ cmd.Flags().String("server-url", "", "")
+ cmd.Flags().String("workspace-id", "", "")
+ cmd.Flags().String("profile", "", "")
+ cmd.Flags().String("output", "table", "")
+ cmd.Flags().Bool("with-content", withContent, "")
+ return cmd
+}
+
+// newSkillQueryCaptureServer records the query string the CLI sent and answers
+// with an empty payload of the right shape.
+func newSkillQueryCaptureServer(t *testing.T, wantPath string, gotQuery *string, payload any) *httptest.Server {
+ t.Helper()
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != wantPath {
+ t.Errorf("path = %q, want %q", r.URL.Path, wantPath)
+ }
+ *gotQuery = r.URL.RawQuery
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(payload)
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+// `skill get`'s table view prints four columns; asking for every file body to
+// render them is what made a large skill unfetchable (GH #7498).
+func TestRunSkillGetAsksForMetadataUnlessContentRequested(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ withContent bool
+ wantQuery string
+ }{
+ {"default", false, "include=metadata"},
+ {"--with-content", true, "include=content"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ var gotQuery string
+ srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123", &gotQuery, map[string]any{
+ "id": "skill-123",
+ "name": "review-helper",
+ })
+ setSkillServerEnv(t, srv.URL)
+
+ if _, err := captureStdout(t, func() error {
+ return runSkillGet(newSkillGetTestCmd(tc.withContent), []string{"skill-123"})
+ }); err != nil {
+ t.Fatalf("runSkillGet: %v", err)
+ }
+ if gotQuery != tc.wantQuery {
+ t.Errorf("query = %q, want %q", gotQuery, tc.wantQuery)
+ }
+ })
+ }
+}
+
+func TestRunSkillFilesListAsksForMetadataUnlessContentRequested(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ withContent bool
+ wantQuery string
+ }{
+ {"default", false, "include=metadata"},
+ {"--with-content", true, "include=content"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ var gotQuery string
+ srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123/files", &gotQuery, []any{})
+ setSkillServerEnv(t, srv.URL)
+
+ if _, err := captureStdout(t, func() error {
+ return runSkillFilesList(newSkillFilesListTestCmd(tc.withContent), []string{"skill-123"})
+ }); err != nil {
+ t.Fatalf("runSkillFilesList: %v", err)
+ }
+ if gotQuery != tc.wantQuery {
+ t.Errorf("query = %q, want %q", gotQuery, tc.wantQuery)
+ }
+ })
+ }
+}
+
+// The size column exists to name the oversized file. Rendering it through
+// strVal would print a 1.2MB file as "1.234567e+06" — JSON numbers decode as
+// float64 — which is unreadable at exactly the sizes that matter.
+func TestRunSkillFilesListRendersReadableSizes(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ var gotQuery string
+ srv := newSkillQueryCaptureServer(t, "/api/skills/skill-123/files", &gotQuery, []any{
+ map[string]any{"id": "f1", "path": "reference.md", "size": 1234567, "content_hash": "abc"},
+ map[string]any{"id": "f2", "path": "small.md", "size": 128, "content_hash": "def"},
+ })
+ setSkillServerEnv(t, srv.URL)
+
+ out, err := captureStdout(t, func() error {
+ return runSkillFilesList(newSkillFilesListTestCmd(false), []string{"skill-123"})
+ })
+ if err != nil {
+ t.Fatalf("runSkillFilesList: %v", err)
+ }
+ if !strings.Contains(out, "SIZE") {
+ t.Errorf("table has no SIZE column: %q", out)
+ }
+ if strings.Contains(out, "e+06") {
+ t.Errorf("size rendered in scientific notation: %q", out)
+ }
+ if !strings.Contains(out, "1.2 MiB") {
+ t.Errorf("expected a human-readable size for the large file, got %q", out)
+ }
+ if !strings.Contains(out, "128 B") {
+ t.Errorf("expected an exact byte count for the small file, got %q", out)
+ }
+}
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index 209fd0c930..06ccf283bf 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -273,7 +273,7 @@ func (c *APIClient) GetJSON(ctx context.Context, path string, out any) error {
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// GetJSONWithHeaders performs a GET request, decodes the JSON response, and
@@ -298,7 +298,7 @@ func (c *APIClient) GetJSONWithHeaders(ctx context.Context, path string, out any
}
if out != nil {
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
- return resp.Header, err
+ return resp.Header, wrapBodyRead(req, err)
}
}
return resp.Header, nil
@@ -328,7 +328,7 @@ func (c *APIClient) DeleteJSONResponse(ctx context.Context, path string, out any
return newHTTPError(http.MethodDelete, path, resp)
}
if out != nil {
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
return nil
}
@@ -386,7 +386,7 @@ func (c *APIClient) PostJSON(ctx context.Context, path string, body any, out any
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// PutJSON performs a PUT request with a JSON body.
@@ -416,7 +416,7 @@ func (c *APIClient) PutJSON(ctx context.Context, path string, body any, out any)
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// PatchJSON performs a PATCH request with a JSON body.
@@ -446,7 +446,7 @@ func (c *APIClient) PatchJSON(ctx context.Context, path string, body any, out an
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// AttachmentResponse mirrors the server's upload-file response.
@@ -698,7 +698,7 @@ func (c *APIClient) ImportSkillFile(ctx context.Context, fileData []byte, filena
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// UploadPrivatePlugin installs workspace-private Plugin archive bytes. The
@@ -736,7 +736,7 @@ func (c *APIClient) UploadPrivatePlugin(ctx context.Context, path string, archiv
if out == nil {
return nil
}
- return json.NewDecoder(resp.Body).Decode(out)
+ return wrapBodyRead(req, json.NewDecoder(resp.Body).Decode(out))
}
// DownloadFile downloads a file from the given URL and returns the response body.
diff --git a/server/internal/cli/errors.go b/server/internal/cli/errors.go
index c162b13caf..0116a31367 100644
--- a/server/internal/cli/errors.go
+++ b/server/internal/cli/errors.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net"
"net/http"
"os"
@@ -30,6 +31,11 @@ const (
KindNetworkRefused // connection refused
KindNetworkTLS // x509 / tls handshake failures
KindNetworkOffline // catch-all: host unreachable, reset, etc.
+ // KindNetworkStalled is a transfer that stopped producing bytes (see
+ // StallError). Distinct from KindNetworkTimeout because the remedy is
+ // different: a timeout says "this took too long", a stall says "this went
+ // quiet", and only the latter is unaffected by raising a time limit.
+ KindNetworkStalled
// HTTP status layer.
KindAuthRequired // 401
@@ -61,7 +67,7 @@ const (
// IsNetwork reports whether the kind is a transport-layer failure.
func (k ErrorKind) IsNetwork() bool {
switch k {
- case KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline:
+ case KindNetworkTimeout, KindNetworkDNS, KindNetworkRefused, KindNetworkTLS, KindNetworkOffline, KindNetworkStalled:
return true
default:
return false
@@ -83,6 +89,8 @@ func (k ErrorKind) String() string {
return "network_tls"
case KindNetworkOffline:
return "network_offline"
+ case KindNetworkStalled:
+ return "network_stalled"
case KindAuthRequired:
return "auth_required"
case KindTaskTokenRejected:
@@ -190,6 +198,14 @@ func classifyNetworkError(err error) ErrorKind {
return KindUnknown
}
+ // A stalled transfer is checked first: the guard implements it by
+ // canceling the request context, so the underlying error would otherwise
+ // read as a generic cancellation and lose the reason.
+ var stalled *StallError
+ if errors.As(err, &stalled) {
+ return KindNetworkStalled
+ }
+
// Timeouts (context deadline or socket i/o timeout).
if errors.Is(err, context.DeadlineExceeded) {
return KindNetworkTimeout
@@ -261,6 +277,41 @@ func wrapTransport(req *http.Request, err error) error {
return &NetworkError{Kind: classifyNetworkError(err), Op: op, Err: err}
}
+// wrapBodyRead classifies an error raised while reading or decoding a
+// response body.
+//
+// wrapTransport only sees errors from http.Client.Do, which returns as soon as
+// the response headers arrive. Everything that goes wrong afterwards — the
+// case #7498 actually reports, a body that never finishes arriving — surfaces
+// out of the JSON decoder instead, and used to reach the user as a raw
+// "context deadline exceeded ... while reading body". A transport failure is
+// still a transport failure when the decoder is the one that notices it; a
+// genuine malformed-JSON error is returned unchanged.
+//
+// io.ErrUnexpectedEOF is deliberately on the network side of that line. It is
+// what the decoder reports for a body that simply stops — a dropped
+// connection, a proxy cutting the response — which is vastly the more common
+// cause than a server that emits syntactically truncated JSON. Well-formed
+// nonsense (the ordinary server bug) raises *json.SyntaxError and is left
+// alone.
+func wrapBodyRead(req *http.Request, err error) error {
+ if err == nil {
+ return nil
+ }
+ var stalled *StallError
+ if errors.As(err, &stalled) {
+ return wrapTransport(req, err)
+ }
+ var netErr net.Error
+ if errors.As(err, &netErr) ||
+ errors.Is(err, context.DeadlineExceeded) ||
+ errors.Is(err, context.Canceled) ||
+ errors.Is(err, io.ErrUnexpectedEOF) {
+ return wrapTransport(req, err)
+ }
+ return err
+}
+
// Language is the language FormatError renders messages in.
type Language int
@@ -294,6 +345,10 @@ var kindMessages = map[ErrorKind][2]string{
"Request timed out: the server did not respond in time. Check your network connection or try again later. You can raise the limit with MULTICA_HTTP_TIMEOUT.",
"请求超时:服务器未在规定时间内响应。请检查网络连接或稍后重试。可通过 MULTICA_HTTP_TIMEOUT 调高超时时间。",
},
+ KindNetworkStalled: {
+ "Transfer stalled: the connection stopped sending data before the response was complete. Check your network connection or try again. You can raise the no-progress budget with MULTICA_HTTP_STALL_TIMEOUT.",
+ "传输中断:响应尚未接收完毕,连接就停止发送数据。请检查网络连接或重试。可通过 MULTICA_HTTP_STALL_TIMEOUT 调高无进展等待时间。",
+ },
KindNetworkDNS: {
"Could not resolve the Multica server address. Check your network connection or the --server-url setting.",
"无法解析 Multica 服务器地址。请检查网络连接或 --server-url 配置。",
diff --git a/server/internal/cli/stall.go b/server/internal/cli/stall.go
new file mode 100644
index 0000000000..8e98b4fc0a
--- /dev/null
+++ b/server/internal/cli/stall.go
@@ -0,0 +1,272 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Transfer-stall detection.
+//
+// http.Client.Timeout is a wall clock on the whole request, body included, so
+// it punishes exactly the transfer that is working: a 599KB skill bundle
+// arriving steadily over a slow link is killed at 30s mid-body, while a
+// genuinely dead connection is held open for the same 30s (GH #7498). The
+// honest question is not "has this taken too long?" but "is it still making
+// progress?".
+//
+// So the client below demotes the wall clock to a backstop and makes progress
+// the primary test: bounded connect and response-header phases, a body read
+// that must keep producing bytes, and a ceiling loose enough that no healthy
+// transfer reaches it. Slow-but-alive transfers finish; dead ones fail sooner
+// than they used to.
+//
+// The mechanism is general and lives here for any caller. Adoption starts with
+// the skill commands (see newSkillAPIClient) because that is where the failure
+// was reported. Graduation is deliberately one edit: point NewAPIClient at
+// NewStallAwareHTTPClient, fold StallAwareContext into APIContext, and delete
+// the skill-local constructor. A permanent second HTTP client would leave the
+// CLI with two timeout personalities, which is worse than either one alone.
+
+const (
+ // defaultStallTimeout is how long a transfer may produce no bytes at all
+ // before it is considered dead. Tighter than the 30s total timeout it
+ // replaces: with progress as the test, there is no reason to wait as long
+ // as a whole slow download might legitimately take.
+ defaultStallTimeout = 15 * time.Second
+
+ // defaultTransferCeiling bounds a command that keeps making progress
+ // forever (a server trickling bytes indefinitely). It is a backstop, not
+ // the primary failure test, so it is loose enough that no healthy transfer
+ // reaches it — but it is never absent.
+ defaultTransferCeiling = 10 * time.Minute
+)
+
+// StallTimeout returns the no-progress budget for a single read.
+//
+// MULTICA_HTTP_STALL_TIMEOUT sets it directly. Failing that, an explicitly set
+// MULTICA_HTTP_TIMEOUT is honored: on this path it keeps its plain-language
+// meaning — the longest the user is willing to wait with nothing arriving —
+// rather than silently becoming a total-elapsed limit again. With neither set,
+// defaultStallTimeout applies.
+func StallTimeout() time.Duration {
+ if d, ok := durationFromEnv("MULTICA_HTTP_STALL_TIMEOUT"); ok {
+ return d
+ }
+ if _, ok := durationFromEnv("MULTICA_HTTP_TIMEOUT"); ok {
+ return httpTimeout()
+ }
+ return defaultStallTimeout
+}
+
+// TransferCeiling returns the hard upper bound for a stall-aware command. It
+// never drops below a multiple of the stall budget, so raising the stall
+// threshold cannot produce a ceiling that fires first and hides it.
+func TransferCeiling() time.Duration {
+ ceiling := defaultTransferCeiling
+ if floor := 4 * StallTimeout(); floor > ceiling {
+ ceiling = floor
+ }
+ return ceiling
+}
+
+// durationFromEnv parses a duration env var, accepting either a Go duration
+// string ("45s", "2m") or a plain integer number of seconds ("45"), matching
+// httpTimeout. It reports false for unset, empty, invalid, or non-positive
+// values so callers can distinguish "user chose this" from "fall back".
+func durationFromEnv(name string) (time.Duration, bool) {
+ v := strings.TrimSpace(os.Getenv(name))
+ if v == "" {
+ return 0, false
+ }
+ if d, err := time.ParseDuration(v); err == nil && d > 0 {
+ return d, true
+ }
+ if secs, err := strconv.Atoi(v); err == nil && secs > 0 {
+ return time.Duration(secs) * time.Second, true
+ }
+ return 0, false
+}
+
+// StallError reports a transfer that stopped producing bytes. It is distinct
+// from a deadline error on purpose: "no data for 15s after 200KB" and "the
+// whole command hit its ceiling" point at different causes and different
+// fixes, and collapsing them into one "request timed out" is what made #7498
+// hard to diagnose from the client side.
+type StallError struct {
+ // Idle is the no-progress budget that was exceeded.
+ Idle time.Duration
+ // BytesRead is how much of the body had arrived before it stalled. Zero
+ // means the body never started, which usually means the connection or the
+ // server died rather than the link being slow.
+ BytesRead int64
+ Op string // e.g. "GET /api/skills/abc" — shown only in --debug
+ Err error // the underlying cancellation, for --debug
+}
+
+func (e *StallError) Error() string {
+ msg := fmt.Sprintf("transfer stalled: no data received for %s after %d bytes", e.Idle, e.BytesRead)
+ if e.Op != "" {
+ return e.Op + ": " + msg
+ }
+ return msg
+}
+
+func (e *StallError) Unwrap() error { return e.Err }
+
+// NewStallAwareHTTPClient builds the HTTP client described at the top of this
+// file: bounded connect/TLS/header phases, a response body that fails when it
+// stops making progress, and a loose whole-request ceiling behind both.
+func NewStallAwareHTTPClient() *http.Client {
+ idle := StallTimeout()
+ base := &http.Transport{
+ // ProxyFromEnvironment matches http.DefaultTransport. Dropping it
+ // would silently break every user behind a corporate proxy, which is
+ // a population that overlaps heavily with the slow links this change
+ // exists for.
+ Proxy: http.ProxyFromEnvironment,
+ DialContext: (&net.Dialer{Timeout: idle, KeepAlive: 30 * time.Second}).DialContext,
+ ForceAttemptHTTP2: true,
+ MaxIdleConns: 100,
+ IdleConnTimeout: 90 * time.Second,
+ TLSHandshakeTimeout: idle,
+ ExpectContinueTimeout: 1 * time.Second,
+ // Covers the phase the body guard cannot see: connected, request
+ // sent, server never replies.
+ ResponseHeaderTimeout: idle,
+ }
+ return &http.Client{
+ Transport: &stallGuardTransport{base: base, idle: idle},
+ // The wall clock stays, but demoted from primary failure test to
+ // backstop, and set loose enough that no healthy transfer reaches it.
+ // Dropping it to 0 would have left a stalled request *upload* — which
+ // the response-body guard cannot see — with no deadline at all, so
+ // removing one wall clock would have quietly removed two.
+ Timeout: TransferCeiling(),
+ }
+}
+
+// StallAwareContext derives a command context for a client built by
+// NewStallAwareHTTPClient. Like APIContext it leaves the transport's own
+// deadline the one that fires, so the failure arrives as a classifiable
+// network error rather than a bare context cancellation.
+func StallAwareContext(parent context.Context) (context.Context, context.CancelFunc) {
+ if parent == nil {
+ parent = context.Background()
+ }
+ return context.WithTimeout(parent, TransferCeiling()+apiContextGrace)
+}
+
+// stallGuardTransport wraps every response body in a progress check.
+type stallGuardTransport struct {
+ base http.RoundTripper
+ idle time.Duration
+}
+
+func (t *stallGuardTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ // Canceling this context is what actually interrupts a blocked body read;
+ // closing the body from another goroutine would race with the reader.
+ // req.WithContext copies the request, so the caller's is untouched as the
+ // RoundTripper contract requires.
+ ctx, cancel := context.WithCancel(req.Context())
+ resp, err := t.base.RoundTrip(req.WithContext(ctx))
+ if err != nil {
+ cancel()
+ return nil, err
+ }
+ op := ""
+ if req.URL != nil {
+ op = req.Method + " " + req.URL.Path
+ }
+ resp.Body = newStallGuardBody(resp.Body, t.idle, cancel, op)
+ return resp, nil
+}
+
+// stallGuardBody fails a read that has produced no bytes for idle.
+//
+// The timer re-checks rather than being reset on every Read: a Reset on the
+// hot path races with the timer firing, and could kill a transfer that just
+// delivered data. Here the timer wakes up, re-reads progress under the same
+// lock that Read writes it, and either re-arms for the remaining time or
+// trips. Cost is at most one extra wakeup per idle window.
+type stallGuardBody struct {
+ rc io.ReadCloser
+ idle time.Duration
+ cancel context.CancelFunc
+ op string
+ timer *time.Timer
+
+ mu sync.Mutex
+ last time.Time
+ read int64
+ tripped bool
+ closed bool
+}
+
+func newStallGuardBody(rc io.ReadCloser, idle time.Duration, cancel context.CancelFunc, op string) *stallGuardBody {
+ b := &stallGuardBody{rc: rc, idle: idle, cancel: cancel, op: op, last: time.Now()}
+ b.timer = time.AfterFunc(idle, b.check)
+ return b
+}
+
+func (b *stallGuardBody) check() {
+ b.mu.Lock()
+ if b.closed || b.tripped {
+ b.mu.Unlock()
+ return
+ }
+ if remaining := b.idle - time.Since(b.last); remaining > 0 {
+ b.timer.Reset(remaining)
+ b.mu.Unlock()
+ return
+ }
+ b.tripped = true
+ b.mu.Unlock()
+ b.cancel()
+}
+
+func (b *stallGuardBody) Read(p []byte) (int, error) {
+ n, err := b.rc.Read(p)
+ if n > 0 {
+ b.mu.Lock()
+ b.read += int64(n)
+ b.last = time.Now()
+ b.mu.Unlock()
+ }
+ if err != nil && err != io.EOF {
+ if stalled := b.stallError(err); stalled != nil {
+ return n, stalled
+ }
+ }
+ return n, err
+}
+
+func (b *stallGuardBody) Close() error {
+ b.mu.Lock()
+ b.closed = true
+ b.mu.Unlock()
+ b.timer.Stop()
+ err := b.rc.Close()
+ // Release the derived context only after the body is done with it;
+ // canceling earlier would abort the read this guard is protecting.
+ b.cancel()
+ return err
+}
+
+// stallError translates the cancellation the guard caused into the reason for
+// it. Errors from any other cause pass through untouched.
+func (b *stallGuardBody) stallError(cause error) *StallError {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if !b.tripped {
+ return nil
+ }
+ return &StallError{Idle: b.idle, BytesRead: b.read, Op: b.op, Err: cause}
+}
diff --git a/server/internal/cli/stall_test.go b/server/internal/cli/stall_test.go
new file mode 100644
index 0000000000..09adcbe10d
--- /dev/null
+++ b/server/internal/cli/stall_test.go
@@ -0,0 +1,320 @@
+package cli
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// trickleServer streams a JSON array in chunks, pausing between them, then
+// optionally goes silent forever mid-body. It stands in for the link in GH
+// #7498: bytes keep arriving, just not fast enough for a wall clock.
+func trickleServer(t *testing.T, chunks int, pause time.Duration, stallAfter int) *httptest.Server {
+ t.Helper()
+ blocked := make(chan struct{})
+ t.Cleanup(func() { close(blocked) })
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ t.Error("ResponseWriter is not a Flusher")
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{"items":[`)
+ flusher.Flush()
+
+ for i := range chunks {
+ if stallAfter >= 0 && i == stallAfter {
+ // Hold the response open without writing: the transfer is
+ // alive at the socket level and producing nothing.
+ select {
+ case <-blocked:
+ case <-r.Context().Done():
+ }
+ return
+ }
+ if i > 0 {
+ fmt.Fprint(w, ",")
+ }
+ fmt.Fprintf(w, `"%s"`, strings.Repeat("x", 512))
+ flusher.Flush()
+ time.Sleep(pause)
+ }
+ fmt.Fprint(w, `]}`)
+ flusher.Flush()
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+type trickleBody struct {
+ Items []string `json:"items"`
+}
+
+// The regression #7498 reports: a transfer that is working the whole time,
+// killed for taking too long in total. The stall-aware client completes the
+// same download the total-elapsed client cannot.
+func TestStallAwareClientCompletesSlowButSteadyTransfer(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "400ms")
+ const (
+ chunks = 12
+ pause = 40 * time.Millisecond
+ )
+
+ t.Run("total-elapsed deadline kills a healthy transfer", func(t *testing.T) {
+ srv := trickleServer(t, chunks, pause, -1)
+ client := &APIClient{
+ BaseURL: srv.URL,
+ HTTPClient: &http.Client{Timeout: 200 * time.Millisecond},
+ }
+ var out trickleBody
+ err := client.GetJSON(context.Background(), "/slow", &out)
+ if err == nil {
+ t.Fatal("expected the total-elapsed client to fail; the fixture is not slow enough to be meaningful")
+ }
+ })
+
+ t.Run("stall detection lets it finish", func(t *testing.T) {
+ srv := trickleServer(t, chunks, pause, -1)
+ client := &APIClient{BaseURL: srv.URL, HTTPClient: NewStallAwareHTTPClient()}
+
+ var out trickleBody
+ if err := client.GetJSON(context.Background(), "/slow", &out); err != nil {
+ t.Fatalf("GetJSON: %v", err)
+ }
+ if len(out.Items) != chunks {
+ t.Fatalf("got %d items, want %d", len(out.Items), chunks)
+ }
+ })
+}
+
+func TestStallAwareClientFailsOnStalledBody(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "150ms")
+ srv := trickleServer(t, 20, 10*time.Millisecond, 4)
+
+ client := &APIClient{BaseURL: srv.URL, HTTPClient: NewStallAwareHTTPClient()}
+
+ start := time.Now()
+ var out trickleBody
+ err := client.GetJSON(context.Background(), "/stalls", &out)
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Fatal("expected a stalled transfer to fail")
+ }
+
+ var stalled *StallError
+ if !errors.As(err, &stalled) {
+ t.Fatalf("error is not a *StallError: %#v", err)
+ }
+ // Bytes did arrive before the silence — this is the signal that separates
+ // "slow link" from "server never answered", and the diagnostic #7498 asks
+ // for.
+ if stalled.BytesRead <= 0 {
+ t.Errorf("BytesRead = %d, want > 0 (some of the body arrived)", stalled.BytesRead)
+ }
+ if stalled.Op != "GET /stalls" {
+ t.Errorf("Op = %q, want %q", stalled.Op, "GET /stalls")
+ }
+ // It must fail on the stall budget, not on the whole-request ceiling.
+ if elapsed > 3*time.Second {
+ t.Errorf("took %s to notice a stall with a 150ms budget", elapsed)
+ }
+}
+
+// A stall must reach the user as a stall. It used to surface as a raw
+// "context deadline exceeded ... while reading body" out of the JSON decoder,
+// because only errors from http.Client.Do were ever classified.
+func TestStalledTransferIsClassifiedAsNetworkError(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "150ms")
+ srv := trickleServer(t, 20, 10*time.Millisecond, 4)
+
+ client := &APIClient{BaseURL: srv.URL, HTTPClient: NewStallAwareHTTPClient()}
+ var out trickleBody
+ err := client.GetJSON(context.Background(), "/stalls", &out)
+ if err == nil {
+ t.Fatal("expected a stalled transfer to fail")
+ }
+
+ var netErr *NetworkError
+ if !errors.As(err, &netErr) {
+ t.Fatalf("error is not a *NetworkError: %#v", err)
+ }
+ if netErr.Kind != KindNetworkStalled {
+ t.Errorf("Kind = %v, want KindNetworkStalled", netErr.Kind)
+ }
+ if got := ExitCodeFor(err); got != ExitNetwork {
+ t.Errorf("ExitCodeFor = %d, want %d", got, ExitNetwork)
+ }
+ msg := FormatError(err, false)
+ if !strings.Contains(msg, "MULTICA_HTTP_STALL_TIMEOUT") {
+ t.Errorf("user message does not name the knob that fixes it: %q", msg)
+ }
+ if strings.Contains(msg, "context deadline exceeded") {
+ t.Errorf("user message leaked the raw transport error: %q", msg)
+ }
+}
+
+// wrapBodyRead must not turn every decode failure into a network error: a
+// server that answers 200 with malformed JSON is a server bug, and calling it
+// a connection problem sends the user to look at their network.
+func TestMalformedJSONIsNotReportedAsNetworkFailure(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"items": [ not json`)
+ }))
+ t.Cleanup(srv.Close)
+
+ client := &APIClient{BaseURL: srv.URL, HTTPClient: NewStallAwareHTTPClient()}
+ var out trickleBody
+ err := client.GetJSON(context.Background(), "/broken", &out)
+ if err == nil {
+ t.Fatal("expected a decode failure")
+ }
+
+ var netErr *NetworkError
+ if errors.As(err, &netErr) {
+ t.Fatalf("malformed JSON was classified as a network error: %v", netErr)
+ }
+ var syntaxErr *json.SyntaxError
+ if !errors.As(err, &syntaxErr) {
+ t.Fatalf("expected a *json.SyntaxError, got %#v", err)
+ }
+}
+
+func TestStallTimeoutEnvPrecedence(t *testing.T) {
+ t.Run("default when nothing is set", func(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "")
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")
+ if got := StallTimeout(); got != defaultStallTimeout {
+ t.Errorf("StallTimeout = %v, want %v", got, defaultStallTimeout)
+ }
+ })
+
+ // An explicitly set MULTICA_HTTP_TIMEOUT keeps meaning "how long am I
+ // willing to wait for this server" on the stall-aware path, rather than
+ // silently reverting to a total-elapsed limit.
+ t.Run("legacy timeout var still has effect", func(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "")
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "90s")
+ if got, want := StallTimeout(), 90*time.Second; got != want {
+ t.Errorf("StallTimeout = %v, want %v", got, want)
+ }
+ })
+
+ t.Run("dedicated var wins", func(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "5s")
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "90s")
+ if got, want := StallTimeout(), 5*time.Second; got != want {
+ t.Errorf("StallTimeout = %v, want %v", got, want)
+ }
+ })
+
+ t.Run("bare seconds and invalid values", func(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "45")
+ if got, want := StallTimeout(), 45*time.Second; got != want {
+ t.Errorf("StallTimeout = %v, want %v", got, want)
+ }
+ for _, bad := range []string{"nonsense", "0", "-5s"} {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", bad)
+ if got := StallTimeout(); got != defaultStallTimeout {
+ t.Errorf("StallTimeout with %q = %v, want the default %v", bad, got, defaultStallTimeout)
+ }
+ }
+ })
+}
+
+// The ceiling is a backstop, so it must never be the thing that fires first —
+// including when someone sets a very generous stall budget.
+func TestTransferCeilingStaysAboveStallBudget(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")
+
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "")
+ if got := TransferCeiling(); got != defaultTransferCeiling {
+ t.Errorf("TransferCeiling = %v, want %v", got, defaultTransferCeiling)
+ }
+
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "20m")
+ if got, want := TransferCeiling(), 80*time.Minute; got != want {
+ t.Errorf("TransferCeiling = %v, want %v", got, want)
+ }
+
+ // And it is never absent: an unbounded command is not an improvement over
+ // one that gives up too early.
+ if TransferCeiling() <= 0 {
+ t.Error("TransferCeiling must always be positive")
+ }
+}
+
+func TestStallAwareContextLeavesTransportDeadlineFirst(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "")
+ t.Setenv("MULTICA_HTTP_TIMEOUT", "")
+
+ ctx, cancel := StallAwareContext(context.Background())
+ defer cancel()
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ t.Fatal("StallAwareContext must set a deadline")
+ }
+ if budget := time.Until(deadline); budget <= TransferCeiling() {
+ t.Errorf("context budget %v must exceed the transport ceiling %v", budget, TransferCeiling())
+ }
+}
+
+// Closing a body early must not leave the guard's timer or context alive.
+func TestStallGuardBodyCloseReleasesGuard(t *testing.T) {
+ t.Setenv("MULTICA_HTTP_STALL_TIMEOUT", "50ms")
+ srv := trickleServer(t, 20, 10*time.Millisecond, 4)
+
+ client := NewStallAwareHTTPClient()
+ req, err := http.NewRequest(http.MethodGet, srv.URL+"/stalls", nil)
+ if err != nil {
+ t.Fatalf("NewRequest: %v", err)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("Do: %v", err)
+ }
+ if err := resp.Body.Close(); err != nil {
+ t.Errorf("Close: %v", err)
+ }
+ // Closing twice must not panic on the already-stopped timer.
+ _ = resp.Body.Close()
+}
+
+// A body that simply stops mid-JSON is a dropped connection far more often
+// than it is a server emitting truncated JSON, so it is classified as a
+// network failure. This test pins that choice rather than leaving it to
+// whichever error the decoder happens to return.
+func TestTruncatedBodyIsReportedAsNetworkFailure(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Length", "64")
+ fmt.Fprint(w, `{"items": ["abc`)
+ }))
+ t.Cleanup(srv.Close)
+
+ client := &APIClient{BaseURL: srv.URL, HTTPClient: NewStallAwareHTTPClient()}
+ var out trickleBody
+ err := client.GetJSON(context.Background(), "/truncated", &out)
+ if err == nil {
+ t.Fatal("expected a truncated body to fail")
+ }
+
+ var netErr *NetworkError
+ if !errors.As(err, &netErr) {
+ t.Fatalf("truncated body was not classified as a network error: %#v", err)
+ }
+ if got := ExitCodeFor(err); got != ExitNetwork {
+ t.Errorf("ExitCodeFor = %d, want %d", got, ExitNetwork)
+ }
+}
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 3f2a75d208..572c6523bb 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -2,6 +2,8 @@ package handler
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -93,6 +95,26 @@ type SkillFileResponse struct {
UpdatedAt string `json:"updated_at"`
}
+// SkillFileMetadataResponse is the file-listing shape: everything
+// SkillFileResponse has except `content`, plus the size and hash that answer
+// "which file makes this skill big?" without downloading any of it.
+//
+// A ~600KB skill could not be listed at all while every row carried its full
+// body, so the one command that would have diagnosed the problem was itself a
+// casualty of it (GH multica-ai/multica#7498). A list endpoint lists.
+type SkillFileMetadataResponse struct {
+ ID string `json:"id"`
+ SkillID string `json:"skill_id"`
+ Path string `json:"path"`
+ // Size is the byte length of the file body, computed in Postgres.
+ Size int64 `json:"size"`
+ // ContentHash is the hex SHA-256 of the file body. Callers that cache
+ // skill files can use it to skip an unchanged download.
+ ContentHash string `json:"content_hash"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
type SkillSearchCandidateResponse struct {
Name string `json:"name"`
URL string `json:"url"`
@@ -108,6 +130,19 @@ type SkillWithFilesResponse struct {
Files []SkillFileResponse `json:"files"`
}
+// SkillWithFileMetadataResponse is `GET /api/skills/{id}?include=metadata`:
+// the skill without its SKILL.md body, and its files without theirs. Sizes and
+// hashes stand in for the content that was dropped, so a caller can still see
+// how large the skill is and which part of it is large.
+type SkillWithFileMetadataResponse struct {
+ SkillSummaryResponse
+ // ContentSize / ContentHash describe the SKILL.md body that `content`
+ // would have carried.
+ ContentSize int64 `json:"content_size"`
+ ContentHash string `json:"content_hash"`
+ Files []SkillFileMetadataResponse `json:"files"`
+}
+
type SkillImportResult struct {
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
@@ -212,6 +247,26 @@ func skillFileToResponse(f db.SkillFile) SkillFileResponse {
}
}
+func skillFileMetadataToResponse(f db.ListSkillFileMetadataRow) SkillFileMetadataResponse {
+ return SkillFileMetadataResponse{
+ ID: uuidToString(f.ID),
+ SkillID: uuidToString(f.SkillID),
+ Path: f.Path,
+ Size: f.Size,
+ ContentHash: f.ContentHash,
+ CreatedAt: timestampToString(f.CreatedAt),
+ UpdatedAt: timestampToString(f.UpdatedAt),
+ }
+}
+
+// contentHash is the hex SHA-256 the metadata shapes report in place of a
+// body. It matches Postgres `encode(sha256(content::bytea), 'hex')`, so a
+// SKILL.md hash computed here and a file hash computed in SQL are comparable.
+func contentHash(content string) string {
+ sum := sha256.Sum256([]byte(content))
+ return hex.EncodeToString(sum[:])
+}
+
// --- Request structs ---
type CreateSkillRequest struct {
@@ -324,13 +379,58 @@ func (h *Handler) SearchSkills(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, candidates)
}
+// Values for the `include` query parameter shared by the skill detail and
+// skill-file list endpoints.
+const (
+ skillIncludeContent = "content"
+ skillIncludeMetadata = "metadata"
+)
+
+// resolveSkillInclude reads `?include=`. `content` inlines the SKILL.md body
+// and every file body; `metadata` returns path/size/hash only.
+//
+// A request that says nothing keeps getting content, on both endpoints. The
+// clients that call them are installed software — desktop builds for the skill
+// editor, older CLI versions whose `skill files list --output json` scripts
+// read `content` — and none of them can be asked retroactively to send a query
+// parameter. Flipping a default here would make a server deploy silently
+// change what an un-upgraded client receives, which no client-side change can
+// prevent.
+//
+// So the shrink is opt-in and travels with the caller: the CLI sends
+// `include=metadata` itself, which fixes GH #7498 without requiring the server
+// and every client to ship together. The default can flip once clients that
+// send `include=content` have aged in.
+func resolveSkillInclude(w http.ResponseWriter, r *http.Request) (bool, bool) {
+ switch strings.TrimSpace(r.URL.Query().Get("include")) {
+ case "":
+ return true, true
+ case skillIncludeContent:
+ return true, true
+ case skillIncludeMetadata:
+ return false, true
+ default:
+ writeError(w, http.StatusBadRequest, `invalid include: expected "content" or "metadata"`)
+ return false, false
+ }
+}
+
func (h *Handler) GetSkill(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
+ includeContent, ok := resolveSkillInclude(w, r)
+ if !ok {
+ return
+ }
skill, ok := h.loadSkillForUser(w, r, id)
if !ok {
return
}
+ if !includeContent {
+ h.writeSkillMetadata(w, r, skill)
+ return
+ }
+
files, err := h.Queries.ListSkillFiles(r.Context(), skill.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list skill files")
@@ -348,6 +448,33 @@ func (h *Handler) GetSkill(w http.ResponseWriter, r *http.Request) {
})
}
+// writeSkillMetadata answers GET /api/skills/{id}?include=metadata. The skill
+// row is already loaded (loadSkillForUser needs it for the tenant check), so
+// the SKILL.md size and hash cost nothing extra; only the file bodies are
+// worth a separate metadata query.
+func (h *Handler) writeSkillMetadata(w http.ResponseWriter, r *http.Request, skill db.Skill) {
+ files, err := h.Queries.ListSkillFileMetadata(r.Context(), skill.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list skill files")
+ return
+ }
+
+ fileResps := make([]SkillFileMetadataResponse, len(files))
+ for i, f := range files {
+ fileResps[i] = skillFileMetadataToResponse(f)
+ }
+
+ writeJSON(w, http.StatusOK, SkillWithFileMetadataResponse{
+ SkillSummaryResponse: skillSummaryToResponse(
+ skill.ID, skill.WorkspaceID, skill.Name, skill.Description,
+ skill.Config, skill.CreatedBy, skill.CreatedAt, skill.UpdatedAt,
+ ),
+ ContentSize: int64(len(skill.Content)),
+ ContentHash: contentHash(skill.Content),
+ Files: fileResps,
+ })
+}
+
func (h *Handler) CreateSkill(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
@@ -2302,11 +2429,29 @@ func (h *Handler) finishSkillImport(w http.ResponseWriter, r *http.Request, work
func (h *Handler) ListSkillFiles(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
+ includeContent, ok := resolveSkillInclude(w, r)
+ if !ok {
+ return
+ }
skill, ok := h.loadSkillForUser(w, r, id)
if !ok {
return
}
+ if !includeContent {
+ metadata, err := h.Queries.ListSkillFileMetadata(r.Context(), skill.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list skill files")
+ return
+ }
+ resp := make([]SkillFileMetadataResponse, len(metadata))
+ for i, f := range metadata {
+ resp[i] = skillFileMetadataToResponse(f)
+ }
+ writeJSON(w, http.StatusOK, resp)
+ return
+ }
+
files, err := h.Queries.ListSkillFiles(r.Context(), skill.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list skill files")
diff --git a/server/internal/handler/skill_metadata_test.go b/server/internal/handler/skill_metadata_test.go
new file mode 100644
index 0000000000..01efe3a9aa
--- /dev/null
+++ b/server/internal/handler/skill_metadata_test.go
@@ -0,0 +1,284 @@
+package handler
+
+import (
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// newLargeSkillFixture builds a skill whose file bodies dwarf its metadata,
+// which is the condition GH #7498 reports: the response was large because it
+// inlined every body, and the command that would have said so was the one that
+// could not finish.
+func newLargeSkillFixture(t *testing.T) (skillID string, bodies map[string]string) {
+ t.Helper()
+
+ skillID = dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "name": "skill-metadata-fixture",
+ "description": "fixture for include= tests",
+ "content": strings.Repeat("s", 4096),
+ "created_by": testUserID,
+ })
+
+ bodies = map[string]string{
+ "reference.md": strings.Repeat("r", 60_000),
+ "scripts/setup.sh": strings.Repeat("x", 128),
+ }
+ for path, body := range bodies {
+ dbfx.Insert(t, "skill_file", testutil.Cols{
+ "skill_id": skillID,
+ "path": path,
+ "content": body,
+ })
+ }
+ return skillID, bodies
+}
+
+func skillRequest(t *testing.T, skillID, path string) *http.Request {
+ t.Helper()
+ return withURLParam(newRequest(http.MethodGet, path, nil), "id", skillID)
+}
+
+func TestListSkillFilesMetadataOmitsBodies(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, bodies := newLargeSkillFixture(t)
+
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"/files?include=metadata")
+ var resp []SkillFileMetadataResponse
+ res := testutil.Call(t, testHandler.ListSkillFiles, req).Want(http.StatusOK).JSON(&resp)
+
+ if len(resp) != len(bodies) {
+ t.Fatalf("got %d files, want %d", len(resp), len(bodies))
+ }
+ for _, f := range resp {
+ want, ok := bodies[f.Path]
+ if !ok {
+ t.Fatalf("unexpected file %q in response", f.Path)
+ }
+ if f.Size != int64(len(want)) {
+ t.Errorf("%s: size = %d, want %d", f.Path, f.Size, len(want))
+ }
+ if expect := contentHash(want); f.ContentHash != expect {
+ t.Errorf("%s: content_hash = %q, want %q", f.Path, f.ContentHash, expect)
+ }
+ }
+
+ // Asserting on the response bytes rather than on a missing struct field is
+ // deliberate: a body that reappeared under a different key would satisfy a
+ // field-name check and still reproduce the bug.
+ if strings.Contains(res.Text(), strings.Repeat("r", 1000)) {
+ t.Error("response inlined a file body")
+ }
+ if got, limit := res.Body.Len(), 4096; got > limit {
+ t.Errorf("metadata listing is %d bytes, want <= %d", got, limit)
+ }
+}
+
+func TestListSkillFilesIncludeContentReturnsBodies(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, bodies := newLargeSkillFixture(t)
+
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"/files?include=content")
+ resp := testutil.Decode[[]SkillFileResponse](t, testHandler.ListSkillFiles, req, http.StatusOK)
+
+ if len(resp) != len(bodies) {
+ t.Fatalf("got %d files, want %d", len(resp), len(bodies))
+ }
+ for _, f := range resp {
+ if want := bodies[f.Path]; f.Content != want {
+ t.Errorf("%s: content length = %d, want %d", f.Path, len(f.Content), len(want))
+ }
+ }
+}
+
+// Neither endpoint may change what a request without `?include=` receives.
+// Their callers are installed software — desktop builds, and older CLI
+// versions whose `skill files list --output json` scripts read `content` — so
+// a server deploy that flipped a default would silently take content away from
+// clients that have no way to ask for it back.
+func TestSkillEndpointsWithoutIncludeStillReturnContent(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, bodies := newLargeSkillFixture(t)
+
+ t.Run("files listing", func(t *testing.T) {
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"/files")
+ resp := testutil.Decode[[]SkillFileResponse](t, testHandler.ListSkillFiles, req, http.StatusOK)
+ if len(resp) != len(bodies) {
+ t.Fatalf("got %d files, want %d", len(resp), len(bodies))
+ }
+ for _, f := range resp {
+ if want := bodies[f.Path]; f.Content != want {
+ t.Errorf("%s: content length = %d, want %d", f.Path, len(f.Content), len(want))
+ }
+ }
+ })
+
+ t.Run("skill detail", func(t *testing.T) {
+ req := skillRequest(t, skillID, "/api/skills/"+skillID)
+ resp := testutil.Decode[SkillWithFilesResponse](t, testHandler.GetSkill, req, http.StatusOK)
+ if len(resp.Content) != 4096 {
+ t.Errorf("content length = %d, want 4096", len(resp.Content))
+ }
+ for _, f := range resp.Files {
+ if want := bodies[f.Path]; f.Content != want {
+ t.Errorf("%s: content length = %d, want %d", f.Path, len(f.Content), len(want))
+ }
+ }
+ })
+}
+
+func TestGetSkillIncludeMetadataDropsBodies(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, bodies := newLargeSkillFixture(t)
+
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"?include=metadata")
+ var resp SkillWithFileMetadataResponse
+ res := testutil.Call(t, testHandler.GetSkill, req).Want(http.StatusOK).JSON(&resp)
+
+ if resp.ID != skillID {
+ t.Errorf("id = %q, want %q", resp.ID, skillID)
+ }
+ if resp.Name != "skill-metadata-fixture" {
+ t.Errorf("name = %q, want the fixture name", resp.Name)
+ }
+ if resp.ContentSize != 4096 {
+ t.Errorf("content_size = %d, want 4096", resp.ContentSize)
+ }
+ if want := contentHash(strings.Repeat("s", 4096)); resp.ContentHash != want {
+ t.Errorf("content_hash = %q, want %q", resp.ContentHash, want)
+ }
+ if len(resp.Files) != len(bodies) {
+ t.Fatalf("got %d files, want %d", len(resp.Files), len(bodies))
+ }
+
+ if strings.Contains(res.Text(), strings.Repeat("s", 1000)) {
+ t.Error("response inlined the SKILL.md body")
+ }
+ if strings.Contains(res.Text(), strings.Repeat("r", 1000)) {
+ t.Error("response inlined a file body")
+ }
+ if got, limit := res.Body.Len(), 4096; got > limit {
+ t.Errorf("metadata response is %d bytes, want <= %d", got, limit)
+ }
+}
+
+// A metadata response must stay small no matter how big the skill gets — that
+// is the property the fix is actually about. Ten more files of 60KB each add
+// rows, not megabytes.
+func TestSkillMetadataSizeDoesNotTrackContentSize(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, _ := newLargeSkillFixture(t)
+
+ measure := func() int {
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"/files?include=metadata")
+ return testutil.Call(t, testHandler.ListSkillFiles, req).Want(http.StatusOK).Body.Len()
+ }
+
+ before := measure()
+ for i := range 10 {
+ dbfx.Insert(t, "skill_file", testutil.Cols{
+ "skill_id": skillID,
+ "path": "bulk/" + string(rune('a'+i)) + ".md",
+ "content": strings.Repeat("b", 60_000),
+ })
+ }
+ after := measure()
+
+ // 600KB of new content; the listing may only grow by its 10 new rows.
+ if grew := after - before; grew > 3000 {
+ t.Errorf("listing grew by %d bytes after adding 600KB of content, want a per-row increase", grew)
+ }
+}
+
+// The size and hash are computed in SQL, so they must agree with Go's view of
+// the same bytes for every body a skill can legally hold.
+//
+// `sha256(content::bytea)` did not: that cast runs the bytea *input* parser
+// over the text, so `\x41` hashed as the single byte `A`, and any bare
+// backslash — a regex, a Windows path — failed the whole request with "invalid
+// input syntax for type bytea". Skill files are full of both.
+func TestSkillFileHashCoversRawUTF8Bytes(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ const skillBody = `SKILL.md with \x41 and C:\path`
+ bodies := map[string]string{
+ "hex-escape.md": `\x41`,
+ "invalid-hex.md": `\xzz`,
+ "bare-backslash.md": `C:\Users\skill`,
+ "regex.md": `^\d+\s*$`,
+ "unicode.md": "héllo 世界 🌍",
+ "empty.md": "",
+ }
+
+ skillID := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "name": "skill-hash-fixture",
+ "description": "bodies that break a bytea cast",
+ "content": skillBody,
+ "created_by": testUserID,
+ })
+ for path, body := range bodies {
+ dbfx.Insert(t, "skill_file", testutil.Cols{
+ "skill_id": skillID,
+ "path": path,
+ "content": body,
+ })
+ }
+
+ req := skillRequest(t, skillID, "/api/skills/"+skillID+"/files?include=metadata")
+ resp := testutil.Decode[[]SkillFileMetadataResponse](t, testHandler.ListSkillFiles, req, http.StatusOK)
+
+ if len(resp) != len(bodies) {
+ t.Fatalf("got %d files, want %d", len(resp), len(bodies))
+ }
+ for _, f := range resp {
+ want := bodies[f.Path]
+ if f.Size != int64(len(want)) {
+ t.Errorf("%s: size = %d, want %d", f.Path, f.Size, len(want))
+ }
+ if expect := contentHash(want); f.ContentHash != expect {
+ t.Errorf("%s (%q): content_hash = %q, want %q", f.Path, want, f.ContentHash, expect)
+ }
+ }
+
+ // Same bytes, same rule, for the SKILL.md body — that one is hashed in Go,
+ // so this pins the SQL and Go implementations to each other.
+ detail := testutil.Decode[SkillWithFileMetadataResponse](t,
+ testHandler.GetSkill, skillRequest(t, skillID, "/api/skills/"+skillID+"?include=metadata"), http.StatusOK)
+ if detail.ContentSize != int64(len(skillBody)) {
+ t.Errorf("content_size = %d, want %d", detail.ContentSize, len(skillBody))
+ }
+ if want := contentHash(skillBody); detail.ContentHash != want {
+ t.Errorf("content_hash = %q, want %q", detail.ContentHash, want)
+ }
+}
+
+func TestSkillIncludeRejectsUnknownValue(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+ skillID, _ := newLargeSkillFixture(t)
+
+ testutil.Call(t, testHandler.GetSkill,
+ skillRequest(t, skillID, "/api/skills/"+skillID+"?include=everything")).
+ Want(http.StatusBadRequest)
+
+ testutil.Call(t, testHandler.ListSkillFiles,
+ skillRequest(t, skillID, "/api/skills/"+skillID+"/files?include=everything")).
+ Want(http.StatusBadRequest)
+}
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
index 436f8a9ffa..7938d8ddc3 100644
--- a/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-skill-importing/SKILL.md
@@ -256,7 +256,7 @@ skill in place:
`import --on-conflict overwrite`, which stays creator-only.
The success response is the plain `SkillWithFilesResponse` (same shape as
-`multica skill get`), not the import result envelope. Failure modes to report
+`multica skill get --with-content`), not the import result envelope. Failure modes to report
instead of retrying in a loop:
- `422`: the skill has no refreshable provenance (created manually, imported
@@ -267,6 +267,24 @@ instead of retrying in a loop:
- `502` / `503` / `504` / `413`: upstream fetch failed (gone, unavailable,
timed out, or now exceeds import caps); the skill is left untouched.
+## Reading a skill back: metadata by default
+
+`multica skill get` and `multica skill files list` return **metadata only** —
+path, byte size and content hash per file, plus the size and hash of the
+SKILL.md body. That is what the conflict and verification steps above need, and
+it is what keeps a large skill inspectable at all: inlining every body made a
+~600KB skill impossible to fetch over a slow link (GH #7498).
+
+```bash
+multica skill get <skill-id> --output json # metadata
+multica skill get <skill-id> --with-content --output json # bodies inlined
+multica skill files list <skill-id> # paths and sizes
+```
+
+Reach for `--with-content` only when you are going to read the content. To find
+out why a skill is large, the default output already answers it: the `size`
+column names the file.
+
## Incorrect → correct
Incorrect (bypasses Multica):
diff --git a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
index ac0e0de4d3..f95351e508 100644
--- a/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
+++ b/server/internal/service/builtin_skills/multica-skill-importing/references/skill-importing-source-map.md
@@ -156,3 +156,17 @@ Behavior is path-shape-dependent. On **import or create** a manifest's `SKILL.md
supporting file is dropped (it will not appear in the returned `files`), so the
import still succeeds — it does not 400. The hard 400 rejection fires only on the
dedicated single-file endpoint `PUT /api/skills/{id}/files`.
+
+## Reading a skill back (`?include=`)
+
+| Behavior | File:line |
+|---|---|
+| `resolveSkillInclude` parses `?include=content\|metadata`, 400 on anything else | `server/internal/handler/skill.go`, grep `func resolveSkillInclude` |
+| Both endpoints default to `content` when `?include=` is absent — installed desktop builds and older CLIs cannot be asked to send it | `resolveSkillInclude`, `server/internal/handler/skill.go` |
+| Compatibility test for that default | `TestSkillEndpointsWithoutIncludeStillReturnContent`, `server/internal/handler/skill_metadata_test.go` |
+| Metadata shapes (`size`, `content_hash`, `content_size`) | `SkillFileMetadataResponse` / `SkillWithFileMetadataResponse` in `server/internal/handler/skill.go` |
+| Size + hash of file bodies computed in Postgres, so those bodies never leave it | `ListSkillFileMetadata`, `server/pkg/db/queries/skill.sql` |
+| Hash is over raw UTF-8 (`convert_to`, never `content::bytea` — the cast reads backslash escapes and rejects a bare `\`) | `server/pkg/db/queries/skill.sql`, test `TestSkillFileHashCoversRawUTF8Bytes` |
+| CLI sends `include=metadata` unless `--with-content` | `skillIncludeQuery`, `server/cmd/multica/cmd_skill.go` |
+| Handler tests | `server/internal/handler/skill_metadata_test.go` |
+| CLI tests | `server/cmd/multica/cmd_skill_test.go`, grep `AsksForMetadataUnlessContentRequested` |
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index b9ab06cb4b..c56153341c 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -368,6 +368,67 @@ func (q *Queries) ListAgentSkillsByWorkspace(ctx context.Context, workspaceID pg
return items, nil
}
+const listSkillFileMetadata = `-- name: ListSkillFileMetadata :many
+SELECT id, skill_id, path,
+ octet_length(content)::bigint AS size,
+ encode(sha256(convert_to(content, 'UTF8')), 'hex') AS content_hash,
+ created_at, updated_at
+FROM skill_file
+WHERE skill_id = $1
+ORDER BY path ASC
+`
+
+type ListSkillFileMetadataRow struct {
+ ID pgtype.UUID `json:"id"`
+ SkillID pgtype.UUID `json:"skill_id"`
+ Path string `json:"path"`
+ Size int64 `json:"size"`
+ ContentHash string `json:"content_hash"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+// Metadata-only variant of ListSkillFiles: path, byte size and content hash
+// without the body. Same reason as ListSkillSummariesByWorkspace — a skill
+// whose supporting files total ~600KB cannot be listed at all when every row
+// carries its full content, and the one command that would show which file is
+// oversized was the command that timed out (GH multica-ai/multica#7498).
+// size/hash are computed in Postgres so the file bodies never leave it.
+//
+// convert_to(content, 'UTF8'), never content::bytea: the cast runs the bytea
+// INPUT parser over the text, so it reads backslash escapes instead of taking
+// the bytes. A file containing `\x41` would hash as the single byte `A`, and
+// one containing a bare backslash — a regex `\d+`, a Windows path, a LaTeX
+// snippet — fails outright with "invalid input syntax for type bytea",
+// turning an ordinary skill into a 500 on this endpoint.
+func (q *Queries) ListSkillFileMetadata(ctx context.Context, skillID pgtype.UUID) ([]ListSkillFileMetadataRow, error) {
+ rows, err := q.db.Query(ctx, listSkillFileMetadata, skillID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListSkillFileMetadataRow{}
+ for rows.Next() {
+ var i ListSkillFileMetadataRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.SkillID,
+ &i.Path,
+ &i.Size,
+ &i.ContentHash,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listSkillFiles = `-- name: ListSkillFiles :many
SELECT id, skill_id, path, content, created_at, updated_at FROM skill_file
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index 0d95a5e9ed..103b0d39c2 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -55,6 +55,28 @@ SELECT * FROM skill_file
WHERE skill_id = $1
ORDER BY path ASC;
+-- name: ListSkillFileMetadata :many
+-- Metadata-only variant of ListSkillFiles: path, byte size and content hash
+-- without the body. Same reason as ListSkillSummariesByWorkspace — a skill
+-- whose supporting files total ~600KB cannot be listed at all when every row
+-- carries its full content, and the one command that would show which file is
+-- oversized was the command that timed out (GH multica-ai/multica#7498).
+-- size/hash are computed in Postgres so the file bodies never leave it.
+--
+-- convert_to(content, 'UTF8'), never content::bytea: the cast runs the bytea
+-- INPUT parser over the text, so it reads backslash escapes instead of taking
+-- the bytes. A file containing `\x41` would hash as the single byte `A`, and
+-- one containing a bare backslash — a regex `\d+`, a Windows path, a LaTeX
+-- snippet — fails outright with "invalid input syntax for type bytea",
+-- turning an ordinary skill into a 500 on this endpoint.
+SELECT id, skill_id, path,
+ octet_length(content)::bigint AS size,
+ encode(sha256(convert_to(content, 'UTF8')), 'hex') AS content_hash,
+ created_at, updated_at
+FROM skill_file
+WHERE skill_id = $1
+ORDER BY path ASC;
+
-- name: GetSkillFile :one
SELECT * FROM skill_file
WHERE id = $1;