Skip to content

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

Go

feat(skills): reject stale skill writes with --base-revision (MUL-9874) (#11210)

Jiayuan Zhangfc2be2b4a8dd
diff --git a/server/cmd/multica/cmd_skill.go b/server/cmd/multica/cmd_skill.go
index a6e94d245f..c6aa0d9d6c 100644
--- a/server/cmd/multica/cmd_skill.go
+++ b/server/cmd/multica/cmd_skill.go
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "strconv"
"strings"
"time"
"unicode/utf8"
@@ -47,8 +48,11 @@ var skillCreateCmd = &cobra.Command{
var skillUpdateCmd = &cobra.Command{
Use: "update <id>",
Short: "Update a skill",
- Args: exactArgs(1),
- RunE: runSkillUpdate,
+ Long: "Update a skill. Content and description are replaced whole, so pass --base-revision " +
+ "(the revision from `multica skill get`): if anyone saved the skill since, nothing is written " +
+ "and you get a conflict instead of silently overwriting their change.",
+ Args: exactArgs(1),
+ RunE: runSkillUpdate,
}
var skillDeleteCmd = &cobra.Command{
@@ -144,6 +148,7 @@ func init() {
skillUpdateCmd.Flags().Bool("content-stdin", false, "Read new content from stdin. Mutually exclusive with --content and --content-file.")
skillUpdateCmd.Flags().String("content-file", "", "Read new content from a UTF-8 file. Mutually exclusive with --content and --content-stdin.")
skillUpdateCmd.Flags().String("config", "", "New config as JSON string")
+ skillUpdateCmd.Flags().Int64("base-revision", 0, "Revision from skill get; the update fails instead of overwriting if the skill changed since")
skillUpdateCmd.Flags().String("output", "json", "Output format: table or json")
// skill delete
@@ -170,7 +175,36 @@ func init() {
skillFilesUpsertCmd.Flags().String("content", "", "File content (required)")
skillFilesUpsertCmd.Flags().Bool("content-stdin", false, "Read file content from stdin. Mutually exclusive with --content and --content-file.")
skillFilesUpsertCmd.Flags().String("content-file", "", "Read file content from a UTF-8 file. Mutually exclusive with --content and --content-stdin.")
+ skillFilesUpsertCmd.Flags().Int64("base-revision", 0, "Skill revision from skill get; the write fails instead of overwriting if the skill changed since")
skillFilesUpsertCmd.Flags().String("output", "json", "Output format: table or json")
+
+ // skill files delete
+ skillFilesDeleteCmd.Flags().Int64("base-revision", 0, "Skill revision from skill get; the delete fails if the skill changed since")
+}
+
+// skillBaseRevision reads --base-revision. Unset means "no precondition", which
+// keeps last-write-wins for scripts written before skill revisions existed.
+func skillBaseRevision(cmd *cobra.Command) (int64, bool, error) {
+ if !cmd.Flags().Changed("base-revision") {
+ return 0, false, nil
+ }
+ base, _ := cmd.Flags().GetInt64("base-revision")
+ if base <= 0 {
+ return 0, false, fmt.Errorf("--base-revision must be a positive revision from `multica skill get`")
+ }
+ return base, true, nil
+}
+
+// skillWriteError turns a stale-revision 409 into instructions an agent can act on.
+func skillWriteError(action string, base int64, err error) error {
+ var httpErr *cli.HTTPError
+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusConflict &&
+ strings.Contains(httpErr.Body, "revision_conflict") {
+ return fmt.Errorf("%s: the skill changed since revision %d, so nothing was written. "+
+ "Run `multica skill get --with-content` for the latest content and revision, merge your change into it, and retry with the new --base-revision (%s)",
+ action, base, httpErr.Body)
+ }
+ return fmt.Errorf("%s: %w", action, err)
}
// Skill commands
@@ -326,11 +360,12 @@ func runSkillGet(cmd *cobra.Command, args []string) error {
return cli.PrintJSON(os.Stdout, skill)
}
- headers := []string{"ID", "NAME", "DESCRIPTION", "CREATED_AT"}
+ headers := []string{"ID", "NAME", "DESCRIPTION", "REVISION", "CREATED_AT"}
rows := [][]string{{
strVal(skill, "id"),
strVal(skill, "name"),
strVal(skill, "description"),
+ strVal(skill, "revision"),
strVal(skill, "created_at"),
}}
cli.PrintTable(os.Stdout, headers, rows)
@@ -421,13 +456,20 @@ func runSkillUpdate(cmd *cobra.Command, args []string) error {
if len(body) == 0 {
return fmt.Errorf("no fields to update; use --name, --description, --content, or --config")
}
+ base, hasBase, err := skillBaseRevision(cmd)
+ if err != nil {
+ return err
+ }
+ if hasBase {
+ body["base_revision"] = base
+ }
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
var result map[string]any
if err := client.PutJSON(ctx, "/api/skills/"+args[0], body, &result); err != nil {
- return fmt.Errorf("update skill: %w", err)
+ return skillWriteError("update skill", base, err)
}
output, _ := cmd.Flags().GetString("output")
@@ -768,13 +810,20 @@ func runSkillFilesUpsert(cmd *cobra.Command, args []string) error {
"path": filePath,
"content": content,
}
+ base, hasBase, err := skillBaseRevision(cmd)
+ if err != nil {
+ return err
+ }
+ if hasBase {
+ body["base_revision"] = base
+ }
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
var result map[string]any
if err := client.PutJSON(ctx, "/api/skills/"+args[0]+"/files", body, &result); err != nil {
- return fmt.Errorf("upsert skill file: %w", err)
+ return skillWriteError("upsert skill file", base, err)
}
output, _ := cmd.Flags().GetString("output")
@@ -792,11 +841,20 @@ func runSkillFilesDelete(cmd *cobra.Command, args []string) error {
return err
}
+ path := "/api/skills/" + args[0] + "/files/" + args[1]
+ base, hasBase, err := skillBaseRevision(cmd)
+ if err != nil {
+ return err
+ }
+ if hasBase {
+ path += "?base_revision=" + strconv.FormatInt(base, 10)
+ }
+
ctx, cancel := cli.APIContext(context.Background())
defer cancel()
- if err := client.DeleteJSON(ctx, "/api/skills/"+args[0]+"/files/"+args[1]); err != nil {
- return fmt.Errorf("delete skill file: %w", err)
+ if err := client.DeleteJSON(ctx, path); err != nil {
+ return skillWriteError("delete skill file", base, err)
}
fmt.Printf("Skill file deleted: %s\n", args[1])
diff --git a/server/cmd/multica/cmd_skill_test.go b/server/cmd/multica/cmd_skill_test.go
index 6b4e155da7..e96a7d6297 100644
--- a/server/cmd/multica/cmd_skill_test.go
+++ b/server/cmd/multica/cmd_skill_test.go
@@ -355,6 +355,7 @@ func newSkillUpdateTestCmd() *cobra.Command {
cmd.Flags().Bool("content-stdin", false, "")
cmd.Flags().String("content-file", "", "")
cmd.Flags().String("config", "", "")
+ cmd.Flags().Int64("base-revision", 0, "")
cmd.Flags().String("output", "json", "")
return cmd
}
@@ -368,6 +369,7 @@ func newSkillFilesUpsertTestCmd() *cobra.Command {
cmd.Flags().String("content", "", "")
cmd.Flags().Bool("content-stdin", false, "")
cmd.Flags().String("content-file", "", "")
+ cmd.Flags().Int64("base-revision", 0, "")
cmd.Flags().String("output", "json", "")
return cmd
}
@@ -907,3 +909,95 @@ func TestRunSkillLabelCommands(t *testing.T) {
t.Fatalf("remove follow-up request: method=%s, path=%s", lastMethod, lastPath)
}
}
+
+func TestRunSkillUpdateSendsBaseRevisionOnlyWhenSet(t *testing.T) {
+ var body map[string]any
+ srv := newSkillBodyCaptureServer(t, http.MethodPut, "/api/skills/skill-123", &body)
+ defer srv.Close()
+ setSkillServerEnv(t, srv.URL)
+
+ cmd := newSkillUpdateTestCmd()
+ _ = cmd.Flags().Set("content", "new body")
+ _ = cmd.Flags().Set("base-revision", "7")
+ if _, err := captureStdout(t, func() error { return runSkillUpdate(cmd, []string{"skill-123"}) }); err != nil {
+ t.Fatalf("runSkillUpdate: %v", err)
+ }
+ if body["base_revision"] != float64(7) {
+ t.Fatalf("base_revision = %v, want 7", body["base_revision"])
+ }
+
+ body = nil
+ cmd = newSkillUpdateTestCmd()
+ _ = cmd.Flags().Set("content", "new body")
+ if _, err := captureStdout(t, func() error { return runSkillUpdate(cmd, []string{"skill-123"}) }); err != nil {
+ t.Fatalf("runSkillUpdate without base revision: %v", err)
+ }
+ if _, sent := body["base_revision"]; sent {
+ t.Fatalf("base_revision must be omitted when --base-revision is unset, body: %v", body)
+ }
+}
+
+func TestRunSkillUpdateRejectsNonPositiveBaseRevision(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatalf("no request expected, got %s %s", r.Method, r.URL.Path)
+ }))
+ defer srv.Close()
+ setSkillServerEnv(t, srv.URL)
+
+ cmd := newSkillUpdateTestCmd()
+ _ = cmd.Flags().Set("content", "new body")
+ _ = cmd.Flags().Set("base-revision", "0")
+ err := runSkillUpdate(cmd, []string{"skill-123"})
+ if err == nil || !strings.Contains(err.Error(), "--base-revision must be a positive revision") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestSkillWritesExplainRevisionConflict(t *testing.T) {
+ var gotPath, gotQuery string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusConflict)
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "error": "resource changed since it was loaded", "code": "revision_conflict",
+ "resource_type": "skill", "expected_revision": 3, "actual_revision": 4,
+ })
+ }))
+ defer srv.Close()
+ setSkillServerEnv(t, srv.URL)
+
+ wantGuidance := func(t *testing.T, err error) {
+ t.Helper()
+ if err == nil {
+ t.Fatal("expected a conflict error")
+ }
+ for _, want := range []string{"changed since revision 3", "nothing was written", "multica skill get", "--base-revision"} {
+ if !strings.Contains(err.Error(), want) {
+ t.Fatalf("error %q missing %q", err.Error(), want)
+ }
+ }
+ }
+
+ update := newSkillUpdateTestCmd()
+ _ = update.Flags().Set("content", "new body")
+ _ = update.Flags().Set("base-revision", "3")
+ wantGuidance(t, runSkillUpdate(update, []string{"skill-123"}))
+
+ upsert := newSkillFilesUpsertTestCmd()
+ _ = upsert.Flags().Set("path", "notes.md")
+ _ = upsert.Flags().Set("content", "notes")
+ _ = upsert.Flags().Set("base-revision", "3")
+ wantGuidance(t, runSkillFilesUpsert(upsert, []string{"skill-123"}))
+
+ del := &cobra.Command{Use: "delete"}
+ del.Flags().String("server-url", "", "")
+ del.Flags().String("workspace-id", "", "")
+ del.Flags().String("profile", "", "")
+ del.Flags().Int64("base-revision", 0, "")
+ _ = del.Flags().Set("base-revision", "3")
+ wantGuidance(t, runSkillFilesDelete(del, []string{"skill-123", "file-1"}))
+ if gotPath != "/api/skills/skill-123/files/file-1" || gotQuery != "base_revision=3" {
+ t.Fatalf("delete request: path=%q query=%q", gotPath, gotQuery)
+ }
+}
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index 40e2b8c29d..ee7284dca7 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -14,6 +14,7 @@ import (
"os"
"path/filepath"
"sort"
+ "strconv"
"strings"
"time"
@@ -60,6 +61,7 @@ type SkillResponse struct {
Description string `json:"description"`
Content string `json:"content"`
Config any `json:"config"`
+ Revision int64 `json:"revision"`
CreatedBy *string `json:"created_by"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
@@ -151,6 +153,7 @@ type SkillWithFilesResponse struct {
// how large the skill is and which part of it is large.
type SkillWithFileMetadataResponse struct {
SkillSummaryResponse
+ Revision int64 `json:"revision"`
// ContentSize / ContentHash describe the SKILL.md body that `content`
// would have carried.
ContentSize int64 `json:"content_size"`
@@ -187,6 +190,7 @@ func skillToResponse(s db.Skill) SkillResponse {
Description: s.Description,
Content: s.Content,
Config: decodeSkillConfig(s.Config),
+ Revision: s.Revision,
CreatedBy: uuidToPtr(s.CreatedBy),
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
@@ -303,6 +307,15 @@ type UpdateSkillRequest struct {
Content *string `json:"content"`
Config any `json:"config"`
Files []CreateSkillFileRequest `json:"files,omitempty"`
+ // BaseRevision is the skill revision the client edited; the write is
+ // refused with 409 if anyone saved since. Optional: omitted keeps
+ // last-write-wins for clients that predate skill revisions.
+ BaseRevision *int64 `json:"base_revision,omitempty"`
+}
+
+type UpsertSkillFileRequest struct {
+ CreateSkillFileRequest
+ BaseRevision *int64 `json:"base_revision,omitempty"`
}
type SetAgentSkillsRequest struct {
@@ -518,6 +531,7 @@ func (h *Handler) writeSkillMetadata(w http.ResponseWriter, r *http.Request, ski
skill.ID, skill.WorkspaceID, skill.Name, skill.Description,
skill.Config, skill.CreatedBy, skill.CreatedAt, skill.UpdatedAt,
),
+ Revision: skill.Revision,
ContentSize: int64(len(skill.Content)),
ContentHash: contentHash(skill.Content),
Files: fileResps,
@@ -608,6 +622,41 @@ func canOverwriteSkillByLocalImport(userID string, skill db.Skill) bool {
return skill.CreatedBy.Valid && uuidToString(skill.CreatedBy) == userID
}
+// validSkillBaseRevision rejects a base_revision no skill can have. Revisions
+// start at 1, so 0 is a client bug (an unset field sent anyway), not "skip
+// the check".
+func validSkillBaseRevision(w http.ResponseWriter, base *int64) bool {
+ if base != nil && *base <= 0 {
+ writeError(w, http.StatusBadRequest, "base_revision must be a positive revision from GET /api/skills/{id}")
+ return false
+ }
+ return true
+}
+
+// checkSkillBaseRevision must run inside the write transaction, before the
+// write. It locks the skill row and answers 409 when the caller named the
+// revision it edited and someone has saved since. With no base revision it is
+// a no-op, so clients that predate skill revisions keep last-write-wins.
+func checkSkillBaseRevision(w http.ResponseWriter, r *http.Request, qtx *db.Queries, skillID pgtype.UUID, base *int64) bool {
+ if base == nil {
+ return true
+ }
+ current, err := qtx.LockSkillForVersioning(r.Context(), skillID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "skill not found")
+ } else {
+ writeError(w, http.StatusInternalServerError, "failed to load skill")
+ }
+ return false
+ }
+ if current.Revision != *base {
+ writeRevisionConflict(w, "skill", current.ID, *base, current.Revision)
+ return false
+ }
+ return true
+}
+
func (h *Handler) UpdateSkill(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
skill, ok := h.loadSkillForUser(w, r, id)
@@ -630,6 +679,9 @@ func (h *Handler) UpdateSkill(w http.ResponseWriter, r *http.Request) {
return
}
}
+ if !validSkillBaseRevision(w, req.BaseRevision) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -640,6 +692,9 @@ func (h *Handler) UpdateSkill(w http.ResponseWriter, r *http.Request) {
qtx := h.Queries.WithTx(tx)
+ if !checkSkillBaseRevision(w, r, qtx, skill.ID, req.BaseRevision) {
+ return
+ }
if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {
slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to update skill")
@@ -2542,7 +2597,7 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {
return
}
- var req CreateSkillFileRequest
+ var req UpsertSkillFileRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
@@ -2556,10 +2611,13 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "SKILL.md is reserved for the primary skill content")
return
}
- if err := validateSkillWriteBudget("", []CreateSkillFileRequest{req}); err != nil {
+ if err := validateSkillWriteBudget("", []CreateSkillFileRequest{req.CreateSkillFileRequest}); err != nil {
writeError(w, http.StatusRequestEntityTooLarge, err.Error())
return
}
+ if !validSkillBaseRevision(w, req.BaseRevision) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -2569,6 +2627,9 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ if !checkSkillBaseRevision(w, r, qtx, skill.ID, req.BaseRevision) {
+ return
+ }
// The baseline runs before TouchSkill: it locks the skill row (the same
// lock TouchSkill and UpdateSkill take, so lock order is unchanged) and
// stamps a pre-versioning skill's baseline with its real updated_at.
@@ -2649,6 +2710,19 @@ func (h *Handler) DeleteSkillFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "skill file not found")
return
}
+ // DELETE carries no body, so the precondition travels as a query param.
+ var baseRevision *int64
+ if raw := strings.TrimSpace(r.URL.Query().Get("base_revision")); raw != "" {
+ n, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid base_revision")
+ return
+ }
+ baseRevision = &n
+ }
+ if !validSkillBaseRevision(w, baseRevision) {
+ return
+ }
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
@@ -2658,6 +2732,9 @@ func (h *Handler) DeleteSkillFile(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ if !checkSkillBaseRevision(w, r, qtx, skill.ID, baseRevision) {
+ return
+ }
if err := ensureSkillVersionBaseline(r.Context(), qtx, skill.ID); err != nil {
slog.Warn("skill version baseline failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to delete skill file")
diff --git a/server/internal/handler/skill_revision_test.go b/server/internal/handler/skill_revision_test.go
new file mode 100644
index 0000000000..41437305b8
--- /dev/null
+++ b/server/internal/handler/skill_revision_test.go
@@ -0,0 +1,223 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "strconv"
+ "sync"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func int64Ptr(v int64) *int64 { return &v }
+
+func updateSkillRequest(skillID string, body UpdateSkillRequest) *http.Request {
+ return withURLParam(newRequest(http.MethodPut, "/api/skills/"+skillID, body), "id", skillID)
+}
+
+func skillRevisionFromDB(t *testing.T, skillID string) (int64, string) {
+ t.Helper()
+ var revision int64
+ var content string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT revision, content FROM skill WHERE id = $1`, skillID).Scan(&revision, &content); err != nil {
+ t.Fatal(err)
+ }
+ return revision, content
+}
+
+func wantSkillRevisionConflict(t *testing.T, resp *testutil.Response, expected, actual int64) {
+ t.Helper()
+ body := resp.Want(http.StatusConflict).Map()
+ if body["code"] != "revision_conflict" || body["resource_type"] != "skill" ||
+ body["expected_revision"] != float64(expected) || body["actual_revision"] != float64(actual) {
+ t.Fatalf("conflict body: %+v", body)
+ }
+}
+
+// Two writers that read the same revision: the second is refused and the
+// first one's content survives, instead of being silently overwritten.
+func TestSkillUpdateBaseRevisionConflict(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ skill := createVersionTestSkill(t, "test-skill-revision-conflict", nil)
+ if skill.Revision != 1 {
+ t.Fatalf("new skill revision: want 1, got %d", skill.Revision)
+ }
+
+ var first SkillWithFilesResponse
+ testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("first writer"), BaseRevision: int64Ptr(1),
+ })).Want(http.StatusOK).JSON(&first)
+ if first.Revision != 2 {
+ t.Fatalf("revision after first write: want 2, got %d", first.Revision)
+ }
+
+ wantSkillRevisionConflict(t, testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("second writer"), BaseRevision: int64Ptr(1),
+ })), 1, 2)
+
+ if revision, content := skillRevisionFromDB(t, skill.ID); revision != 2 || content != "first writer" {
+ t.Fatalf("conflicting write must change nothing: revision %d, content %q", revision, content)
+ }
+
+ // Retrying from the revision the conflict reported succeeds.
+ var retried SkillWithFilesResponse
+ testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("second writer, merged"), BaseRevision: int64Ptr(2),
+ })).Want(http.StatusOK).JSON(&retried)
+ if retried.Revision != 3 || retried.Content != "second writer, merged" {
+ t.Fatalf("retry: revision %d, content %q", retried.Revision, retried.Content)
+ }
+}
+
+// The check and the write share the row lock, so writers racing from the same
+// revision cannot both pass the check.
+func TestSkillUpdateBaseRevisionConcurrentWriters(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ skill := createVersionTestSkill(t, "test-skill-revision-race", nil)
+
+ const writers = 4
+ codes := make([]int, writers)
+ var wg sync.WaitGroup
+ for i := 0; i < writers; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ resp := testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("writer " + strconv.Itoa(i)), BaseRevision: int64Ptr(1),
+ }))
+ codes[i] = resp.Code
+ }(i)
+ }
+ wg.Wait()
+
+ ok, conflicts := 0, 0
+ for _, code := range codes {
+ switch code {
+ case http.StatusOK:
+ ok++
+ case http.StatusConflict:
+ conflicts++
+ }
+ }
+ if ok != 1 || conflicts != writers-1 {
+ t.Fatalf("want exactly one winner and %d conflicts, got codes %v", writers-1, codes)
+ }
+ if revision, _ := skillRevisionFromDB(t, skill.ID); revision != 2 {
+ t.Fatalf("one successful write must leave revision 2, got %d", revision)
+ }
+}
+
+// Clients that predate skill revisions send no base_revision and keep
+// last-write-wins, while still advancing the revision for clients that do.
+func TestSkillUpdateWithoutBaseRevisionStillWrites(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ skill := createVersionTestSkill(t, "test-skill-revision-legacy", nil)
+ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{Content: strPtr("legacy one")})
+ updateSkillForVersionTest(t, skill.ID, UpdateSkillRequest{Content: strPtr("legacy two")})
+
+ if revision, content := skillRevisionFromDB(t, skill.ID); revision != 3 || content != "legacy two" {
+ t.Fatalf("legacy writes: revision %d, content %q", revision, content)
+ }
+
+ // A revision-aware writer that read before those saves is refused.
+ wantSkillRevisionConflict(t, testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("stale"), BaseRevision: int64Ptr(1),
+ })), 1, 3)
+}
+
+func TestSkillUpdateRejectsNonPositiveBaseRevision(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ skill := createVersionTestSkill(t, "test-skill-revision-invalid", nil)
+ testutil.Call(t, testHandler.UpdateSkill, updateSkillRequest(skill.ID, UpdateSkillRequest{
+ Content: strPtr("x"), BaseRevision: int64Ptr(0),
+ })).Want(http.StatusBadRequest)
+ if revision, _ := skillRevisionFromDB(t, skill.ID); revision != 1 {
+ t.Fatalf("rejected write must not bump revision, got %d", revision)
+ }
+}
+
+// Supporting-file writes replace a file's whole body, so they take the same
+// precondition, and they advance the skill revision like any other write.
+func TestSkillFileWritesBaseRevision(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database available")
+ }
+
+ skill := createVersionTestSkill(t, "test-skill-revision-files", []CreateSkillFileRequest{
+ {Path: "notes.md", Content: "original notes"},
+ })
+ upsert := func(body UpsertSkillFileRequest) *testutil.Response {
+ req := withURLParam(newRequest(http.MethodPut, "/api/skills/"+skill.ID+"/files", body), "id", skill.ID)
+ return testutil.Call(t, testHandler.UpsertSkillFile, req)
+ }
+ notes := func() string {
+ var content string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT content FROM skill_file WHERE skill_id = $1 AND path = 'notes.md'`, skill.ID).Scan(&content); err != nil {
+ t.Fatal(err)
+ }
+ return content
+ }
+
+ upsert(UpsertSkillFileRequest{
+ CreateSkillFileRequest: CreateSkillFileRequest{Path: "notes.md", Content: "first notes"},
+ BaseRevision: int64Ptr(1),
+ }).Want(http.StatusOK)
+
+ wantSkillRevisionConflict(t, upsert(UpsertSkillFileRequest{
+ CreateSkillFileRequest: CreateSkillFileRequest{Path: "notes.md", Content: "stale notes"},
+ BaseRevision: int64Ptr(1),
+ }), 1, 2)
+ if got := notes(); got != "first notes" {
+ t.Fatalf("conflicting file write must change nothing, got %q", got)
+ }
+
+ // Without base_revision the upsert behaves as before.
+ upsert(UpsertSkillFileRequest{
+ CreateSkillFileRequest: CreateSkillFileRequest{Path: "notes.md", Content: "legacy notes"},
+ }).Want(http.StatusOK)
+ if got := notes(); got != "legacy notes" {
+ t.Fatalf("legacy upsert: got %q", got)
+ }
+
+ var meta SkillWithFileMetadataResponse
+ getReq := withURLParam(newRequest(http.MethodGet, "/api/skills/"+skill.ID+"?include=metadata", nil), "id", skill.ID)
+ testutil.Call(t, testHandler.GetSkill, getReq).Want(http.StatusOK).JSON(&meta)
+ if meta.Revision != 3 {
+ t.Fatalf("metadata revision: want 3, got %d", meta.Revision)
+ }
+
+ var fileID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT id::text FROM skill_file WHERE skill_id = $1 AND path = 'notes.md'`, skill.ID).Scan(&fileID); err != nil {
+ t.Fatal(err)
+ }
+ deleteFile := func(query string) *testutil.Response {
+ req := withURLParams(newRequest(http.MethodDelete, "/api/skills/"+skill.ID+"/files/"+fileID+query, nil),
+ "id", skill.ID, "fileId", fileID)
+ return testutil.Call(t, testHandler.DeleteSkillFile, req)
+ }
+ wantSkillRevisionConflict(t, deleteFile("?base_revision=2"), 2, 3)
+ if got := notes(); got != "legacy notes" {
+ t.Fatalf("conflicting delete must keep the file, got %q", got)
+ }
+ deleteFile("?base_revision=abc").Want(http.StatusBadRequest)
+ deleteFile("?base_revision=3").Want(http.StatusNoContent)
+ if revision, _ := skillRevisionFromDB(t, skill.ID); revision != 4 {
+ t.Fatalf("file delete must bump revision to 4, got %d", revision)
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-platform/SKILL.md b/server/internal/service/builtin_skills/multica-platform/SKILL.md
index d922d300bf..ba0e2ec0c3 100644
--- a/server/internal/service/builtin_skills/multica-platform/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-platform/SKILL.md
@@ -29,7 +29,7 @@ Read the invariants below, then open the reference(s) your task actually needs
| `references/projects.md` | Projects and their durable resources (`github_repo`, `local_directory`, worktree mode); project workflows — status columns, handoffs, a `[Project workflow]` block in your prompt, reading or changing a workflow (`multica workflow`, `multica project workflow`) |
| `references/runtimes.md` | Runtimes, daemons, `repo checkout`, and the task CLI boundary |
| `references/environments.md` | Local environments in the issue sidebar: writing `.multica/environments.toml`, `multica env start` / `stop` / `list`, detected servers |
-| `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive |
+| `references/skill-import.md` | Importing a skill into this workspace from a URL or a local archive; editing a workspace skill's content without overwriting someone else's save (`--base-revision`) |
| `references/themes.md` | Building or changing a Multica app theme: the format, the checker, delivering to Desktop's themes folder or as a `.zip` |
| `references/inbox.md` | Going through the runtime owner's inbox for them: listing unread notifications, marking read or unread, archiving, snoozing, bulk clean-up (`multica inbox`) |
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.md
index 0b712930a4..90c87f386c 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
@@ -1,7 +1,8 @@
-# Importing skills
+# Importing and editing skills
Use this when the user already provided a skill URL, slug, or a clear intent to
-import a specific skill into the current Multica workspace. It does not help you
+import a specific skill into the current Multica workspace, or when you are
+changing the content of a skill that is already there. It does not help you
decide WHICH skill the user needs — if they only described a capability and no
URL is known, external search may produce candidates, but importing starts only
once a URL or concrete target exists.
@@ -14,6 +15,7 @@ once a URL or concrete target exists.
- [Reserved SKILL.md supporting file](#reserved-skillmd-supporting-file)
- [Same-name conflicts: --on-conflict](#same-name-conflicts---on-conflict)
- [Updating an already-imported skill](#updating-an-already-imported-skill)
+- [Editing a skill's content](#editing-a-skills-content)
- [Reading a skill back](#reading-a-skill-back)
- [Incorrect to correct](#incorrect-to-correct)
@@ -270,6 +272,35 @@ modes to report 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.
+## Editing a skill's content
+
+`multica skill update --content-file` and `multica skill files upsert` replace
+the whole SKILL.md body or the whole file. Workspace skills are shared, and
+another agent may be editing the same one: an update based on what you read a
+minute ago silently erases whatever they saved in between. Always edit from a
+revision:
+
+```bash
+multica skill get <skill-id> --with-content --output json # note "revision"
+# edit the content you just read, then:
+multica skill update <skill-id> --content-file ./SKILL.md --base-revision <revision> --output json
+multica skill files upsert <skill-id> --path notes.md --content-file ./notes.md --base-revision <revision> --output json
+multica skill files delete <skill-id> <file-id> --base-revision <revision>
+```
+
+Every successful write to the skill or any of its files moves `revision` up by
+exactly one, so when you make several writes in a row, pass your previous
+`--base-revision` plus one to the next. If someone else saved in between, that
+next write conflicts, as it should. When the skill changed since `--base-revision`, the server
+answers `409` with `"code": "revision_conflict"` and the current
+`actual_revision`, and nothing is written. Run `multica skill get --with-content`
+again, merge your change into the latest content, and retry with the new
+revision. Do not drop `--base-revision` to force the write through: that is the
+overwrite the check exists to stop.
+
+Without `--base-revision` the commands keep their old last-write-wins behavior,
+for scripts written before skill revisions existed.
+
## Reading a skill back
`multica skill get` and `multica skill files list` return **metadata only** —
diff --git a/server/internal/service/builtin_skills_test.go b/server/internal/service/builtin_skills_test.go
index 525d999381..4a962ac8e5 100644
--- a/server/internal/service/builtin_skills_test.go
+++ b/server/internal/service/builtin_skills_test.go
@@ -776,6 +776,11 @@ func TestPlatformSkillCoversPlatformContracts(t *testing.T) {
"multica agent skills list <agent-id> --output json",
"replace-all",
"`set` is the replacement path",
+ // MUL-9874: shared skills are edited from a revision so one
+ // agent's save cannot silently erase another's.
+ "multica skill update <skill-id> --content-file ./SKILL.md --base-revision <revision>",
+ "revision_conflict",
+ "Do not drop `--base-revision` to force the write through",
},
notWant: []string{
"multica agent skills set <agent-id> --skill-ids <skill-id>",
diff --git a/server/internal/service/task_agent_skills_test.go b/server/internal/service/task_agent_skills_test.go
index 18be631fdd..6bc4d8031b 100644
--- a/server/internal/service/task_agent_skills_test.go
+++ b/server/internal/service/task_agent_skills_test.go
@@ -109,7 +109,7 @@ func (d *skillReadDBTX) Query(_ context.Context, sql string, _ ...any) (pgx.Rows
func skillRow(id pgtype.UUID, name, description, content string) []any {
return []any{
id, testUUID(0xF0), name, description, content,
- []byte(nil), pgtype.UUID{}, pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{},
+ []byte(nil), pgtype.UUID{}, pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{}, int64(1),
}
}
diff --git a/server/migrations/731_skill_revision.down.sql b/server/migrations/731_skill_revision.down.sql
new file mode 100644
index 0000000000..36592bcc45
--- /dev/null
+++ b/server/migrations/731_skill_revision.down.sql
@@ -0,0 +1 @@
+ALTER TABLE skill DROP COLUMN IF EXISTS revision;
diff --git a/server/migrations/731_skill_revision.up.sql b/server/migrations/731_skill_revision.up.sql
new file mode 100644
index 0000000000..6d4b9da81b
--- /dev/null
+++ b/server/migrations/731_skill_revision.up.sql
@@ -0,0 +1,12 @@
+-- Optimistic-concurrency counter for workspace skills (MUL-9874).
+--
+-- Every write to a skill's name, description, content, config or supporting
+-- files bumps it in the same statement that takes the row lock (UpdateSkill /
+-- TouchSkill). A writer that names the revision it read (`base_revision`) is
+-- refused with 409 when the counter has moved, so two clients editing the same
+-- skill can no longer silently overwrite each other. Writers that omit
+-- base_revision keep the old last-write-wins behaviour.
+--
+-- A constant default makes this a catalog-only change: no table rewrite and no
+-- backfill. Existing rows start at 1, the same starting point as doc.revision.
+ALTER TABLE skill ADD COLUMN IF NOT EXISTS revision BIGINT NOT NULL DEFAULT 1;
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index f7face36d6..ff27b0c709 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1905,6 +1905,7 @@ type Skill struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
PluginInstallationID pgtype.UUID `json:"plugin_installation_id"`
+ Revision int64 `json:"revision"`
}
type SkillFile struct {
diff --git a/server/pkg/db/generated/plugin.sql.go b/server/pkg/db/generated/plugin.sql.go
index 2576710391..2ce0fb950f 100644
--- a/server/pkg/db/generated/plugin.sql.go
+++ b/server/pkg/db/generated/plugin.sql.go
@@ -1066,7 +1066,7 @@ func (q *Queries) ListPluginSecretKeys(ctx context.Context, installationID pgtyp
}
const listPluginSkills = `-- name: ListPluginSkills :many
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill WHERE plugin_installation_id = $1 ORDER BY name ASC
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill WHERE plugin_installation_id = $1 ORDER BY name ASC
`
func (q *Queries) ListPluginSkills(ctx context.Context, pluginInstallationID pgtype.UUID) ([]Skill, error) {
@@ -1089,6 +1089,7 @@ func (q *Queries) ListPluginSkills(ctx context.Context, pluginInstallationID pgt
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -1577,7 +1578,7 @@ ON CONFLICT (workspace_id, name) DO UPDATE SET
content = EXCLUDED.content,
updated_at = now()
WHERE skill.plugin_installation_id = EXCLUDED.plugin_installation_id
-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id
+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision
`
type UpsertPluginSkillParams struct {
@@ -1617,6 +1618,7 @@ func (q *Queries) UpsertPluginSkill(ctx context.Context, arg UpsertPluginSkillPa
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index ea219b034b..ef0e543613 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -30,7 +30,7 @@ func (q *Queries) AddAgentSkill(ctx context.Context, arg AddAgentSkillParams) er
const createSkill = `-- name: CreateSkill :one
INSERT INTO skill (workspace_id, name, description, content, config, created_by)
VALUES ($1, $2, $3, $4, $5, $6)
-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id
+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision
`
type CreateSkillParams struct {
@@ -63,6 +63,7 @@ func (q *Queries) CreateSkill(ctx context.Context, arg CreateSkillParams) (Skill
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
@@ -196,7 +197,7 @@ func (q *Queries) GetLatestSkillVersion(ctx context.Context, skillID pgtype.UUID
}
const getSkill = `-- name: GetSkill :one
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill
WHERE id = $1
`
@@ -214,12 +215,13 @@ func (q *Queries) GetSkill(ctx context.Context, id pgtype.UUID) (Skill, error) {
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
const getSkillByWorkspaceAndName = `-- name: GetSkillByWorkspaceAndName :one
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill
WHERE workspace_id = $1 AND name = $2
`
@@ -244,6 +246,7 @@ func (q *Queries) GetSkillByWorkspaceAndName(ctx context.Context, arg GetSkillBy
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
@@ -268,7 +271,7 @@ func (q *Queries) GetSkillFile(ctx context.Context, id pgtype.UUID) (SkillFile,
}
const getSkillInWorkspace = `-- name: GetSkillInWorkspace :one
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill
WHERE id = $1 AND workspace_id = $2
`
@@ -291,6 +294,7 @@ func (q *Queries) GetSkillInWorkspace(ctx context.Context, arg GetSkillInWorkspa
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
@@ -415,7 +419,7 @@ func (q *Queries) ListAgentSkillSummaries(ctx context.Context, agentID pgtype.UU
const listAgentSkills = `-- name: ListAgentSkills :many
-SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id FROM skill s
+SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id, s.revision FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
WHERE ask.agent_id = $1 AND ask.enabled = TRUE
ORDER BY s.name ASC
@@ -442,6 +446,7 @@ func (q *Queries) ListAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]S
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -454,7 +459,7 @@ func (q *Queries) ListAgentSkills(ctx context.Context, agentID pgtype.UUID) ([]S
}
const listAgentSkillsByIDs = `-- name: ListAgentSkillsByIDs :many
-SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id FROM skill s
+SELECT s.id, s.workspace_id, s.name, s.description, s.content, s.config, s.created_by, s.created_at, s.updated_at, s.plugin_installation_id, s.revision FROM skill s
JOIN agent_skill ask ON ask.skill_id = s.id
WHERE ask.agent_id = $1
AND ask.enabled = TRUE
@@ -493,6 +498,7 @@ func (q *Queries) ListAgentSkillsByIDs(ctx context.Context, arg ListAgentSkillsB
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -789,7 +795,7 @@ func (q *Queries) ListSkillVersions(ctx context.Context, arg ListSkillVersionsPa
const listSkillsByWorkspace = `-- name: ListSkillsByWorkspace :many
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill
WHERE workspace_id = $1
ORDER BY name ASC
`
@@ -815,6 +821,7 @@ func (q *Queries) ListSkillsByWorkspace(ctx context.Context, workspaceID pgtype.
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
); err != nil {
return nil, err
}
@@ -828,13 +835,14 @@ func (q *Queries) ListSkillsByWorkspace(ctx context.Context, workspaceID pgtype.
const lockSkillForVersioning = `-- name: LockSkillForVersioning :one
-SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id FROM skill WHERE id = $1 FOR UPDATE
+SELECT id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision FROM skill WHERE id = $1 FOR UPDATE
`
// Skill versions
// Serializes version-number allocation for one skill. Every content write
// takes this row lock inside its transaction before reading the latest
-// version, so concurrent writers cannot allocate the same number.
+// version, so concurrent writers cannot allocate the same number. The same
+// lock makes the base_revision check and the write that follows atomic.
func (q *Queries) LockSkillForVersioning(ctx context.Context, id pgtype.UUID) (Skill, error) {
row := q.db.QueryRow(ctx, lockSkillForVersioning, id)
var i Skill
@@ -849,6 +857,7 @@ func (q *Queries) LockSkillForVersioning(ctx context.Context, id pgtype.UUID) (S
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
@@ -898,9 +907,9 @@ func (q *Queries) SetAgentSkillEnabled(ctx context.Context, arg SetAgentSkillEna
}
const touchSkill = `-- name: TouchSkill :one
-UPDATE skill SET updated_at = now()
+UPDATE skill SET updated_at = now(), revision = revision + 1
WHERE id = $1 AND workspace_id = $2
-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id
+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision
`
type TouchSkillParams struct {
@@ -909,8 +918,9 @@ type TouchSkillParams struct {
}
// Supporting-file writes change the skill as a whole, so they bump the parent's
-// updated_at in the same transaction. Updating the row also takes its lock,
-// which serializes concurrent file writes on one skill with UpdateSkill.
+// updated_at and revision in the same transaction. Updating the row also takes
+// its lock, which serializes concurrent file writes on one skill with
+// UpdateSkill.
func (q *Queries) TouchSkill(ctx context.Context, arg TouchSkillParams) (Skill, error) {
row := q.db.QueryRow(ctx, touchSkill, arg.ID, arg.WorkspaceID)
var i Skill
@@ -925,6 +935,7 @@ func (q *Queries) TouchSkill(ctx context.Context, arg TouchSkillParams) (Skill,
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
@@ -935,9 +946,10 @@ UPDATE skill SET
description = COALESCE($3, description),
content = COALESCE($4, content),
config = COALESCE($5, config),
+ revision = revision + 1,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id
+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id, revision
`
type UpdateSkillParams struct {
@@ -968,6 +980,7 @@ func (q *Queries) UpdateSkill(ctx context.Context, arg UpdateSkillParams) (Skill
&i.CreatedAt,
&i.UpdatedAt,
&i.PluginInstallationID,
+ &i.Revision,
)
return i, err
}
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index 3ed58c14d7..decdeda8fe 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -40,15 +40,17 @@ UPDATE skill SET
description = COALESCE(sqlc.narg('description'), description),
content = COALESCE(sqlc.narg('content'), content),
config = COALESCE(sqlc.narg('config'), config),
+ revision = revision + 1,
updated_at = now()
WHERE id = $1
RETURNING *;
-- name: TouchSkill :one
-- Supporting-file writes change the skill as a whole, so they bump the parent's
--- updated_at in the same transaction. Updating the row also takes its lock,
--- which serializes concurrent file writes on one skill with UpdateSkill.
-UPDATE skill SET updated_at = now()
+-- updated_at and revision in the same transaction. Updating the row also takes
+-- its lock, which serializes concurrent file writes on one skill with
+-- UpdateSkill.
+UPDATE skill SET updated_at = now(), revision = revision + 1
WHERE id = $1 AND workspace_id = $2
RETURNING *;
@@ -188,7 +190,8 @@ ORDER BY s.name ASC;
-- name: LockSkillForVersioning :one
-- Serializes version-number allocation for one skill. Every content write
-- takes this row lock inside its transaction before reading the latest
--- version, so concurrent writers cannot allocate the same number.
+-- version, so concurrent writers cannot allocate the same number. The same
+-- lock makes the base_revision check and the write that follows atomic.
SELECT * FROM skill WHERE id = $1 FOR UPDATE;
-- name: GetLatestSkillVersion :one