| 1 | package library |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "unicode/utf8" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/icons" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 13 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 14 | "gorm.io/gorm" |
| 15 | "gorm.io/gorm/clause" |
| 16 | ) |
| 17 | |
| 18 | type ModelRef struct{ Provider, Family, Model string } |
| 19 | type SpecialistInput struct { |
| 20 | Key, Name, Icon, Instructions string |
| 21 | AllowedModels []ModelRef |
| 22 | Tools []string |
| 23 | ProjectIDs []int64 |
| 24 | MaxConcurrent int |
| 25 | } |
| 26 | type Specialist struct { |
| 27 | Key string `gorm:"primaryKey"` |
| 28 | ModelSelection, Provider, ModelFamily, Model, StandingInstructions string |
| 29 | MaxConcurrent int |
| 30 | Revision int64 |
| 31 | TeamID string `gorm:"not null;default:''"` |
| 32 | Creator string `gorm:"not null;default:''"` |
| 33 | Name string `gorm:"not null;default:''"` |
| 34 | Icon string `gorm:"not null;default:''"` |
| 35 | Role string `gorm:"not null;default:''"` |
| 36 | Required bool `gorm:"not null;default:false"` |
| 37 | Archived bool `gorm:"not null;default:false"` |
| 38 | AllowedModels []ModelRef `gorm:"serializer:json;not null;default:'[]'"` |
| 39 | Tools []string `gorm:"serializer:json;not null;default:'[]'"` |
| 40 | ProjectIDs []int64 `gorm:"serializer:json;not null;default:'[]'"` |
| 41 | TemplateID string `gorm:"not null;default:''"` |
| 42 | TemplateVersion int64 `gorm:"not null;default:0"` |
| 43 | TemplateBase string `gorm:"not null;default:'{}'"` |
| 44 | } |
| 45 | type request struct { |
| 46 | TeamID, Principal, Operation, Resource, RequestID string `gorm:"primaryKey"` |
| 47 | InputHash, Result string |
| 48 | } |
| 49 | |
| 50 | func (request) TableName() string { return "specialist_requests" } |
| 51 | |
| 52 | var Models = []any{&Specialist{}, &request{}, &Playbook{}, &PlaybookRevision{}, &PlaybookDefault{}, &PlaybookSnapshot{}, &playbookRequest{}, &PlaybookSuggestion{}} |
| 53 | var DefaultKeys = []string{"product", "design", "copy", "engineering", "review"} |
| 54 | var DefaultIcons = []string{"lightbulb", "pencil", "type", "code", "check-circle"} |
| 55 | |
| 56 | type Access struct { |
| 57 | TeamID string |
| 58 | Owner bool |
| 59 | } |
| 60 | type Dependencies struct { |
| 61 | Authorize func(*gorm.DB, kernel.Actor) (Access, error) |
| 62 | Audit func(*gorm.DB, kernel.Actor, string, string) error |
| 63 | Referenced func(*gorm.DB, string) (bool, error) |
| 64 | Copy func(string) string |
| 65 | Catalog func() []Template |
| 66 | PlaybookCatalog func() []Template |
| 67 | TaskAccess func(*gorm.DB, kernel.Actor, int64) error |
| 68 | Invalid, Forbidden, NotFound, Conflict error |
| 69 | } |
| 70 | type Store struct { |
| 71 | tx *gorm.DB |
| 72 | deps Dependencies |
| 73 | } |
| 74 | |
| 75 | func New(tx *gorm.DB, d Dependencies) *Store { return &Store{tx: tx, deps: d} } |
| 76 | func Seed(tx *gorm.DB, teamID string) (int64, error) { |
| 77 | rows := []Specialist{} |
| 78 | for i, key := range DefaultKeys { |
| 79 | rows = append(rows, Specialist{Key: key, TeamID: teamID, Role: key, Icon: DefaultIcons[i], Required: key == "engineering" || key == "review", ModelSelection: "best_fit", MaxConcurrent: 1, Revision: 1, AllowedModels: []ModelRef{}, Tools: []string{}, ProjectIDs: []int64{}}) |
| 80 | } |
| 81 | r := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}}, DoNothing: true}).Create(&rows) |
| 82 | return r.RowsAffected, r.Error |
| 83 | } |
| 84 | func Input(s Specialist) SpecialistInput { |
| 85 | return SpecialistInput{Key: s.Key, Name: s.Name, Icon: s.Icon, Instructions: s.StandingInstructions, AllowedModels: slices.Clone(s.AllowedModels), Tools: slices.Clone(s.Tools), ProjectIDs: slices.Clone(s.ProjectIDs), MaxConcurrent: s.MaxConcurrent} |
| 86 | } |
| 87 | func (s *Store) Get(actor kernel.Actor, key string) (Specialist, error) { |
| 88 | a, err := s.deps.Authorize(s.tx, actor) |
| 89 | if err != nil { |
| 90 | return Specialist{}, err |
| 91 | } |
| 92 | return s.get(a, key) |
| 93 | } |
| 94 | func (s *Store) get(a Access, key string) (Specialist, error) { |
| 95 | var row Specialist |
| 96 | err := s.tx.Where("key=? AND team_id=?", key, a.TeamID).First(&row).Error |
| 97 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 98 | err = s.deps.NotFound |
| 99 | } |
| 100 | return row, err |
| 101 | } |
| 102 | func (s *Store) List(actor kernel.Actor) ([]Specialist, error) { |
| 103 | a, err := s.deps.Authorize(s.tx, actor) |
| 104 | if err != nil { |
| 105 | return nil, err |
| 106 | } |
| 107 | var rows []Specialist |
| 108 | err = s.tx.Where("team_id=? AND archived=?", a.TeamID, false).Order("key").Find(&rows).Error |
| 109 | return rows, err |
| 110 | } |
| 111 | func (s *Store) editor(actor kernel.Actor, key string) (Access, Specialist, error) { |
| 112 | a, err := s.deps.Authorize(s.tx, actor) |
| 113 | if err != nil { |
| 114 | return a, Specialist{}, err |
| 115 | } |
| 116 | row, err := s.get(a, key) |
| 117 | if err != nil { |
| 118 | return a, row, err |
| 119 | } |
| 120 | if !a.Owner && row.Creator != actor.Address { |
| 121 | return a, row, s.deps.Forbidden |
| 122 | } |
| 123 | return a, row, nil |
| 124 | } |
| 125 | func (s *Store) validate(in SpecialistInput) error { |
| 126 | if (strings.TrimSpace(in.Name) == "" && !slices.Contains(DefaultKeys, in.Key)) || len(in.Name) > 120 || !utf8.ValidString(in.Name) || len(in.Instructions) > 16384 || !utf8.ValidString(in.Instructions) || in.MaxConcurrent < 1 || in.MaxConcurrent > 100 || len(in.AllowedModels) > 100 || len(in.Tools) > 32 || len(in.ProjectIDs) > 100 { |
| 127 | return s.deps.Invalid |
| 128 | } |
| 129 | seen := map[ModelRef]bool{} |
| 130 | for _, m := range in.AllowedModels { |
| 131 | if (m.Provider != "codex" || m.Family != "gpt") && (m.Provider != "claude" || m.Family != "claude") || strings.TrimSpace(m.Model) == "" || len(m.Model) > 128 || !utf8.ValidString(m.Model) || seen[m] { |
| 132 | return s.deps.Invalid |
| 133 | } |
| 134 | seen[m] = true |
| 135 | } |
| 136 | ids := map[int64]bool{} |
| 137 | for _, id := range in.ProjectIDs { |
| 138 | if id <= 0 || ids[id] { |
| 139 | return s.deps.Invalid |
| 140 | } |
| 141 | ids[id] = true |
| 142 | } |
| 143 | if icons.Icon(in.Icon) == "" { |
| 144 | return s.deps.Invalid |
| 145 | } |
| 146 | // Custom executable profiles have no owner grants or certificates in this release. |
| 147 | if provider.ValidateSpecialistTools(in.Tools, nil, nil, nil) != nil { |
| 148 | return s.deps.Forbidden |
| 149 | } |
| 150 | for _, id := range in.ProjectIDs { |
| 151 | var p kernel.Project |
| 152 | if err := s.tx.First(&p, id).Error; err != nil { |
| 153 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 154 | return s.deps.NotFound |
| 155 | } |
| 156 | return err |
| 157 | } |
| 158 | } |
| 159 | return nil |
| 160 | } |
| 161 | func (s *Store) replay(a Access, actor kernel.Actor, op, key string, m kernel.Mutation, input any) (request, Specialist, bool, error) { |
| 162 | var result Specialist |
| 163 | if !m.Valid() { |
| 164 | return request{}, result, false, s.deps.Invalid |
| 165 | } |
| 166 | hash, err := kernel.InputHash(struct { |
| 167 | Input any |
| 168 | Revision int64 |
| 169 | }{input, m.Revision}) |
| 170 | if err != nil { |
| 171 | return request{}, result, false, err |
| 172 | } |
| 173 | q := request{TeamID: a.TeamID, Principal: actor.Address, Operation: op, Resource: key, RequestID: m.RequestID, InputHash: hash} |
| 174 | var old request |
| 175 | err = s.tx.Where("team_id=? AND principal=? AND operation=? AND resource=? AND request_id=?", q.TeamID, q.Principal, op, key, m.RequestID).First(&old).Error |
| 176 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 177 | return q, result, false, nil |
| 178 | } |
| 179 | if err != nil { |
| 180 | return q, result, false, err |
| 181 | } |
| 182 | if old.InputHash != hash { |
| 183 | return q, result, true, s.deps.Conflict |
| 184 | } |
| 185 | err = json.Unmarshal([]byte(old.Result), &result) |
| 186 | return q, result, true, err |
| 187 | } |
| 188 | func (s *Store) save(actor kernel.Actor, q request, row Specialist) (Specialist, error) { |
| 189 | if err := s.deps.Audit(s.tx, actor, q.Operation, row.Key); err != nil { |
| 190 | return Specialist{}, err |
| 191 | } |
| 192 | raw, err := json.Marshal(row) |
| 193 | if err != nil { |
| 194 | return Specialist{}, err |
| 195 | } |
| 196 | q.Result = string(raw) |
| 197 | return row, s.tx.Create(&q).Error |
| 198 | } |
| 199 | func (s *Store) Create(actor kernel.Actor, in SpecialistInput, m kernel.Mutation) (Specialist, error) { |
| 200 | return s.create(actor, in, TemplateRef{}, m) |
| 201 | } |
| 202 | func (s *Store) create(actor kernel.Actor, in SpecialistInput, ref TemplateRef, m kernel.Mutation) (Specialist, error) { |
| 203 | a, err := s.deps.Authorize(s.tx, actor) |
| 204 | if err != nil { |
| 205 | return Specialist{}, err |
| 206 | } |
| 207 | q, old, replay, err := s.replay(a, actor, "specialist.create", "", m, struct { |
| 208 | Input SpecialistInput |
| 209 | Template TemplateRef |
| 210 | }{in, ref}) |
| 211 | if err != nil || replay { |
| 212 | return old, err |
| 213 | } |
| 214 | if in.Key != "" || m.Revision != 0 { |
| 215 | return Specialist{}, s.deps.Invalid |
| 216 | } |
| 217 | return s.insert(a, actor, in, ref, q) |
| 218 | } |
| 219 | func (s *Store) insert(a Access, actor kernel.Actor, in SpecialistInput, ref TemplateRef, q request) (Specialist, error) { |
| 220 | if err := s.validate(in); err != nil { |
| 221 | return Specialist{}, err |
| 222 | } |
| 223 | row := Specialist{Key: rand.Text(), TeamID: a.TeamID, Creator: actor.Address, ModelSelection: "best_fit", Revision: 1, TemplateID: ref.ID, TemplateVersion: ref.Version, TemplateBase: "{}"} |
| 224 | assign(&row, in) |
| 225 | if ref.ID != "" { |
| 226 | raw, _ := json.Marshal(fields(row)) |
| 227 | row.TemplateBase = string(raw) |
| 228 | } |
| 229 | if err := s.tx.Create(&row).Error; err != nil { |
| 230 | return Specialist{}, err |
| 231 | } |
| 232 | return s.save(actor, q, row) |
| 233 | } |
| 234 | func assign(row *Specialist, in SpecialistInput) { |
| 235 | row.Name = in.Name |
| 236 | row.Icon = in.Icon |
| 237 | row.StandingInstructions = in.Instructions |
| 238 | row.MaxConcurrent = in.MaxConcurrent |
| 239 | row.AllowedModels = append([]ModelRef{}, in.AllowedModels...) |
| 240 | row.Tools = append([]string{}, in.Tools...) |
| 241 | row.ProjectIDs = append([]int64{}, in.ProjectIDs...) |
| 242 | } |
| 243 | func (s *Store) Update(actor kernel.Actor, in SpecialistInput, m kernel.Mutation) (Specialist, error) { |
| 244 | a, row, err := s.editor(actor, in.Key) |
| 245 | if err != nil { |
| 246 | return Specialist{}, err |
| 247 | } |
| 248 | q, old, replay, err := s.replay(a, actor, "specialist.update", in.Key, m, in) |
| 249 | if err != nil || replay { |
| 250 | return old, err |
| 251 | } |
| 252 | return s.update(actor, row, in, m, q) |
| 253 | } |
| 254 | func (s *Store) update(actor kernel.Actor, row Specialist, in SpecialistInput, m kernel.Mutation, q request) (Specialist, error) { |
| 255 | if row.Archived || m.Revision != row.Revision { |
| 256 | return Specialist{}, s.deps.Conflict |
| 257 | } |
| 258 | // Required categories keep their server-owned role and identity. Instructions |
| 259 | // cannot change the action profile, independent review or final person. |
| 260 | if row.Required && (in.Name != row.Name || in.Icon != row.Icon || len(in.Tools) != 0 || len(in.ProjectIDs) != 0) { |
| 261 | return Specialist{}, s.deps.Forbidden |
| 262 | } |
| 263 | if err := s.validate(in); err != nil { |
| 264 | return Specialist{}, err |
| 265 | } |
| 266 | assign(&row, in) |
| 267 | row.Revision++ |
| 268 | r := s.tx.Model(&Specialist{}).Where("key=? AND team_id=? AND revision=?", row.Key, row.TeamID, m.Revision).Select("Name", "Icon", "StandingInstructions", "MaxConcurrent", "AllowedModels", "Tools", "ProjectIDs", "Revision", "TemplateID", "TemplateVersion", "TemplateBase").Updates(&row) |
| 269 | if r.Error != nil { |
| 270 | return Specialist{}, r.Error |
| 271 | } |
| 272 | if r.RowsAffected != 1 { |
| 273 | return Specialist{}, s.deps.Conflict |
| 274 | } |
| 275 | return s.save(actor, q, row) |
| 276 | } |
| 277 | func (s *Store) Delete(actor kernel.Actor, key string, m kernel.Mutation) error { |
| 278 | a, row, err := s.editor(actor, key) |
| 279 | if err != nil { |
| 280 | return err |
| 281 | } |
| 282 | if row.Required { |
| 283 | return s.deps.Forbidden |
| 284 | } |
| 285 | q, _, replay, err := s.replay(a, actor, "specialist.archive", key, m, key) |
| 286 | if err != nil || replay { |
| 287 | return err |
| 288 | } |
| 289 | if row.Archived || row.Revision != m.Revision { |
| 290 | return s.deps.Conflict |
| 291 | } |
| 292 | used, err := s.deps.Referenced(s.tx, key) |
| 293 | if err != nil { |
| 294 | return err |
| 295 | } |
| 296 | if used { |
| 297 | return s.deps.Conflict |
| 298 | } |
| 299 | row.Archived = true |
| 300 | row.Revision++ |
| 301 | r := s.tx.Model(&Specialist{}).Where("key=? AND team_id=? AND revision=?", key, a.TeamID, m.Revision).Select("Archived", "Revision").Updates(&row) |
| 302 | if r.Error != nil { |
| 303 | return r.Error |
| 304 | } |
| 305 | if r.RowsAffected != 1 { |
| 306 | return s.deps.Conflict |
| 307 | } |
| 308 | _, err = s.save(actor, q, row) |
| 309 | return err |
| 310 | } |
| 311 | |
| 312 | func ListInstance(tx *gorm.DB) ([]Specialist, error) { |
| 313 | var rows []Specialist |
| 314 | if err := tx.Where("archived=? AND team_id=(SELECT id FROM teams LIMIT 1)", false).Find(&rows).Error; err != nil { |
| 315 | return nil, err |
| 316 | } |
| 317 | slices.SortFunc(rows, func(a, b Specialist) int { |
| 318 | ai, bi := slices.Index(DefaultKeys, a.Key), slices.Index(DefaultKeys, b.Key) |
| 319 | if ai < 0 { |
| 320 | ai = len(DefaultKeys) |
| 321 | } |
| 322 | if bi < 0 { |
| 323 | bi = len(DefaultKeys) |
| 324 | } |
| 325 | if ai != bi { |
| 326 | return ai - bi |
| 327 | } |
| 328 | return strings.Compare(a.Key, b.Key) |
| 329 | }) |
| 330 | return rows, nil |
| 331 | } |
| 332 | |