Skip to content

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

Go

fix(skills): publish skill:updated for supporting-file writes (MUL-8447) (#9767)

MartinPLarsen6a60658e85b4
diff --git a/server/internal/handler/skill.go b/server/internal/handler/skill.go
index e8fce3c62f..0d03b38cc4 100644
--- a/server/internal/handler/skill.go
+++ b/server/internal/handler/skill.go
@@ -2516,7 +2516,29 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {
return
}
- sf, err := h.Queries.UpsertSkillFile(r.Context(), db.UpsertSkillFileParams{
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // Touch the parent first so its row lock is taken before the file write,
+ // in the same order UpdateSkill takes them.
+ skill, err = qtx.TouchSkill(r.Context(), db.TouchSkillParams{
+ ID: skill.ID,
+ WorkspaceID: skill.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "skill not found")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update skill")
+ return
+ }
+ sf, err := qtx.UpsertSkillFile(r.Context(), db.UpsertSkillFileParams{
SkillID: skill.ID,
Path: sanitizeNullBytes(req.Path),
Content: sanitizeNullBytes(req.Content),
@@ -2526,7 +2548,17 @@ func (h *Handler) UpsertSkillFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to upsert skill file")
return
}
+ resp, err := skillWithFilesInTx(r.Context(), qtx, skill)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list skill files")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit")
+ return
+ }
+ h.publishSkillFilesChanged(r, resp)
writeJSON(w, http.StatusOK, skillFileToResponse(sf))
}
@@ -2552,13 +2584,71 @@ func (h *Handler) DeleteSkillFile(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "skill file not found")
return
}
- if err := h.Queries.DeleteSkillFile(r.Context(), file.ID); err != nil {
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to start transaction")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ skill, err = qtx.TouchSkill(r.Context(), db.TouchSkillParams{
+ ID: skill.ID,
+ WorkspaceID: skill.WorkspaceID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "skill not found")
+ return
+ }
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update skill")
+ return
+ }
+ if err := qtx.DeleteSkillFile(r.Context(), file.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete skill file")
return
}
+ resp, err := skillWithFilesInTx(r.Context(), qtx, skill)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list skill files")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to commit")
+ return
+ }
+
+ h.publishSkillFilesChanged(r, resp)
w.WriteHeader(http.StatusNoContent)
}
+// skillWithFilesInTx builds the skill:updated payload from reads inside the
+// writing transaction, so the event carries exactly the state it committed.
+func skillWithFilesInTx(ctx context.Context, qtx *db.Queries, skill db.Skill) (SkillWithFilesResponse, error) {
+ files, err := qtx.ListSkillFiles(ctx, skill.ID)
+ if err != nil {
+ return SkillWithFilesResponse{}, err
+ }
+ fileResps := make([]SkillFileResponse, len(files))
+ for i, f := range files {
+ fileResps[i] = skillFileToResponse(f)
+ }
+ return SkillWithFilesResponse{
+ SkillResponse: skillToResponse(skill),
+ Files: fileResps,
+ }, nil
+}
+
+// publishSkillFilesChanged announces a supporting-file write the same way
+// UpdateSkill announces an edit: a file change is a change to the skill, and
+// clients holding the skill (detail page, agent skill lists) must refetch it.
+func (h *Handler) publishSkillFilesChanged(r *http.Request, resp SkillWithFilesResponse) {
+ wsID := h.resolveWorkspaceID(r)
+ actorType, actorID := h.resolveActor(r, requestUserID(r), wsID)
+ h.publish(protocol.EventSkillUpdated, wsID, actorType, actorID, map[string]any{"skill": resp})
+}
+
// --- Agent-Skill junction ---
func (h *Handler) ListAgentSkills(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/handler/skill_file_events_test.go b/server/internal/handler/skill_file_events_test.go
new file mode 100644
index 0000000000..b5dae2d074
--- /dev/null
+++ b/server/internal/handler/skill_file_events_test.go
@@ -0,0 +1,188 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// A supporting-file write is a change to the skill: it must bump the skill's
+// updated_at and announce skill:updated with the full file set, exactly like
+// PUT /api/skills/{id} does. Before this, clients holding the skill never
+// learned that a file had changed.
+func TestSkillFileWritesPublishSkillUpdated(t *testing.T) {
+ skillID := insertHandlerTestSkill(t, "skill-file-events", "body")
+
+ var mu sync.Mutex
+ var updates []SkillWithFilesResponse
+ testHandler.Bus.Subscribe(protocol.EventSkillUpdated, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ skill, ok := payload["skill"].(SkillWithFilesResponse)
+ if !ok || skill.ID != skillID {
+ return
+ }
+ mu.Lock()
+ updates = append(updates, skill)
+ mu.Unlock()
+ })
+ lastUpdate := func() (SkillWithFilesResponse, int) {
+ mu.Lock()
+ defer mu.Unlock()
+ if len(updates) == 0 {
+ return SkillWithFilesResponse{}, 0
+ }
+ return updates[len(updates)-1], len(updates)
+ }
+ updatedAt := func() time.Time {
+ var ts time.Time
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT updated_at FROM skill WHERE id = $1`, skillID).Scan(&ts); err != nil {
+ t.Fatalf("read updated_at: %v", err)
+ }
+ return ts
+ }
+
+ before := updatedAt()
+
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", "/api/skills/"+skillID+"/files", map[string]any{
+ "path": "notes/a.md",
+ "content": "alpha",
+ })
+ req = withURLParam(req, "id", skillID)
+ testHandler.UpsertSkillFile(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpsertSkillFile: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ got, n := lastUpdate()
+ if n != 1 {
+ t.Fatalf("expected 1 skill:updated after upsert, got %d", n)
+ }
+ if len(got.Files) != 1 || got.Files[0].Path != "notes/a.md" || got.Files[0].Content != "alpha" {
+ t.Fatalf("upsert event files = %+v, want the one upserted file", got.Files)
+ }
+ afterUpsert := updatedAt()
+ if !afterUpsert.After(before) {
+ t.Fatalf("upsert did not bump skill.updated_at: before %v, after %v", before, afterUpsert)
+ }
+
+ fileID := got.Files[0].ID
+ w = httptest.NewRecorder()
+ req = newRequest("DELETE", "/api/skills/"+skillID+"/files/"+fileID, nil)
+ req = withURLParams(req, "id", skillID, "fileId", fileID)
+ testHandler.DeleteSkillFile(w, req)
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteSkillFile: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+
+ got, n = lastUpdate()
+ if n != 2 {
+ t.Fatalf("expected 2 skill:updated after delete, got %d", n)
+ }
+ if len(got.Files) != 0 {
+ t.Fatalf("delete event files = %+v, want none", got.Files)
+ }
+ if !updatedAt().After(afterUpsert) {
+ t.Fatal("delete did not bump skill.updated_at")
+ }
+}
+
+func TestTouchSkillWorkspaceScope(t *testing.T) {
+ ctx := context.Background()
+ skillID := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "created_by": testUserID,
+ "name": "touch-skill-workspace-scope",
+ "updated_at": testutil.Raw("now() - interval '1 hour'"),
+ })
+ otherWorkspaceID := dbfx.Workspace(t, "Other skill workspace", "touch-skill-other-"+skillID)
+ original, err := testHandler.Queries.GetSkill(ctx, parseUUID(skillID))
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = testHandler.Queries.TouchSkill(ctx, db.TouchSkillParams{
+ ID: original.ID,
+ WorkspaceID: parseUUID(otherWorkspaceID),
+ })
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("touch from another workspace: got %v, want no rows", err)
+ }
+ unchanged, err := testHandler.Queries.GetSkill(ctx, original.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !unchanged.UpdatedAt.Time.Equal(original.UpdatedAt.Time) {
+ t.Fatal("touch from another workspace changed the skill timestamp")
+ }
+
+ updated, err := testHandler.Queries.TouchSkill(ctx, db.TouchSkillParams{
+ ID: original.ID,
+ WorkspaceID: original.WorkspaceID,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !updated.UpdatedAt.Time.After(original.UpdatedAt.Time) {
+ t.Fatal("touch from the owning workspace did not update the skill timestamp")
+ }
+}
+
+func TestSkillFileWritesReturnNotFoundAfterSkillDeleted(t *testing.T) {
+ for _, method := range []string{http.MethodPut, http.MethodDelete} {
+ t.Run(method, func(t *testing.T) {
+ skillID := dbfx.Insert(t, "skill", testutil.Cols{
+ "workspace_id": testWorkspaceID,
+ "created_by": testUserID,
+ "name": "deleted-before-file-write-" + method,
+ })
+ fileID := dbfx.Insert(t, "skill_file", testutil.Cols{
+ "skill_id": skillID,
+ "path": "notes.md",
+ "content": "original",
+ })
+
+ h := *testHandler
+ h.Bus = events.New()
+ updates := 0
+ h.Bus.Subscribe(protocol.EventSkillUpdated, func(events.Event) { updates++ })
+ deleted := false
+ h.TxStarter = hookedTxStarter{base: testHandler.TxStarter, hook: func() error {
+ dbfx.Exec(t, `DELETE FROM skill_file WHERE skill_id = $1`, skillID)
+ dbfx.Exec(t, `DELETE FROM skill WHERE id = $1 AND workspace_id = $2`, skillID, testWorkspaceID)
+ deleted = true
+ return nil
+ }}
+
+ handler := h.UpsertSkillFile
+ path := "/api/skills/" + skillID + "/files"
+ if method == http.MethodDelete {
+ handler = h.DeleteSkillFile
+ path += "/" + fileID
+ }
+ req := newRequest(method, path, map[string]any{"path": "notes.md", "content": "changed"})
+ req = testutil.WithURLParams(req, "id", skillID, "fileId", fileID)
+ testutil.Call(t, handler, req).Want(http.StatusNotFound)
+ if !deleted {
+ t.Fatal("request did not reach the post-authorization deletion hook")
+ }
+ if updates != 0 {
+ t.Fatalf("deleted skill published %d updates, want none", updates)
+ }
+ })
+ }
+}
diff --git a/server/pkg/db/generated/skill.sql.go b/server/pkg/db/generated/skill.sql.go
index 45d7bfec05..b2a94b1015 100644
--- a/server/pkg/db/generated/skill.sql.go
+++ b/server/pkg/db/generated/skill.sql.go
@@ -688,6 +688,38 @@ func (q *Queries) SetAgentSkillEnabled(ctx context.Context, arg SetAgentSkillEna
return result.RowsAffected(), nil
}
+const touchSkill = `-- name: TouchSkill :one
+UPDATE skill SET updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING id, workspace_id, name, description, content, config, created_by, created_at, updated_at, plugin_installation_id
+`
+
+type TouchSkillParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// 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.
+func (q *Queries) TouchSkill(ctx context.Context, arg TouchSkillParams) (Skill, error) {
+ row := q.db.QueryRow(ctx, touchSkill, arg.ID, arg.WorkspaceID)
+ var i Skill
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Description,
+ &i.Content,
+ &i.Config,
+ &i.CreatedBy,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.PluginInstallationID,
+ )
+ return i, err
+}
+
const updateSkill = `-- name: UpdateSkill :one
UPDATE skill SET
name = COALESCE($2, name),
diff --git a/server/pkg/db/queries/skill.sql b/server/pkg/db/queries/skill.sql
index a4d795073e..68f72fb5a5 100644
--- a/server/pkg/db/queries/skill.sql
+++ b/server/pkg/db/queries/skill.sql
@@ -44,6 +44,14 @@ UPDATE skill SET
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()
+WHERE id = $1 AND workspace_id = $2
+RETURNING *;
+
-- name: DeleteSkill :exec
-- Defense-in-depth: workspace_id is a SQL-layer tenant guard. See DeleteIssue.
DELETE FROM skill WHERE id = $1 AND workspace_id = $2;