| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/specialist" |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | "gorm.io/gorm" |
| 14 | ) |
| 15 | |
| 16 | // Specialists as data (Research spec §6, slice R0). The coordinator |
| 17 | // proposes a specialist from the closed menu (internal/specialist); one |
| 18 | // card asks the proposing owner; only an owner's Add, in one transaction, |
| 19 | // makes it active and writes its grants and audit row. Every later use |
| 20 | // checks the grant again (grantFor, grants.go). The table is the team's: a |
| 21 | // specialist is not any one person's. |
| 22 | |
| 23 | // specialistRecord is one data-defined specialist. Only Name, Brief and |
| 24 | // ModelPreference come from the row; the profile fixes the rest. |
| 25 | type specialistRecord struct { |
| 26 | ID string `gorm:"primaryKey"` |
| 27 | Profile string `gorm:"index:chat_specialist_profile;uniqueIndex:chat_specialist_open,priority:1,where:state = 'proposed';uniqueIndex:chat_specialist_active,priority:1,where:state = 'active'"` |
| 28 | // ProjectID is the specialist's scope: "" is the team, else one |
| 29 | // project. One open proposal and one active row per profile and |
| 30 | // scope (migration 0121). |
| 31 | ProjectID string `gorm:"not null;default:'';uniqueIndex:chat_specialist_open,priority:2,where:state = 'proposed';uniqueIndex:chat_specialist_active,priority:2,where:state = 'active'"` |
| 32 | Name string |
| 33 | Brief string |
| 34 | ModelPreference string |
| 35 | // State is wire.SpecialistProposed, Active, Declined or Revoked; |
| 36 | // Revision moves on every change, and a grant holds at one revision. |
| 37 | State string |
| 38 | Revision int64 |
| 39 | ProposedBy string |
| 40 | ProposedTurn string |
| 41 | // CardID is the specialist card that asks about the proposal. |
| 42 | CardID string `gorm:"index:chat_specialist_card"` |
| 43 | Approver string |
| 44 | ApprovedAt *time.Time |
| 45 | DecidedBy string |
| 46 | DecidedAt *time.Time |
| 47 | RevokedBy string |
| 48 | RevokedAt *time.Time |
| 49 | CreatedAt time.Time |
| 50 | UpdatedAt time.Time |
| 51 | } |
| 52 | |
| 53 | func (specialistRecord) TableName() string { return "chat_specialists" } |
| 54 | |
| 55 | // grantRecord is one capability granted to a specialist by an owner's |
| 56 | // Add, at the specialist's revision then. Revoked rows stay. |
| 57 | type grantRecord struct { |
| 58 | ID string `gorm:"primaryKey"` |
| 59 | SpecialistID string `gorm:"index:chat_capability_grant_specialist"` |
| 60 | Capability string |
| 61 | Revision int64 |
| 62 | GrantedBy string |
| 63 | GrantedAt time.Time |
| 64 | RevokedBy string |
| 65 | RevokedAt *time.Time |
| 66 | } |
| 67 | |
| 68 | func (grantRecord) TableName() string { return "chat_capability_grants" } |
| 69 | |
| 70 | // specialistAuditRecord is one change to a specialist, written in the |
| 71 | // transaction of the change. Detail never holds a credential. Append only. |
| 72 | type specialistAuditRecord struct { |
| 73 | ID string `gorm:"primaryKey"` |
| 74 | SpecialistID string `gorm:"index:chat_specialist_audit_specialist"` |
| 75 | Action string |
| 76 | Actor string |
| 77 | Revision int64 |
| 78 | Detail string |
| 79 | At time.Time |
| 80 | } |
| 81 | |
| 82 | func (specialistAuditRecord) TableName() string { return "chat_specialist_audit" } |
| 83 | |
| 84 | // Specialist audit actions. |
| 85 | const ( |
| 86 | auditProposed = "proposed" |
| 87 | auditApproved = "approved" |
| 88 | auditDeclined = "declined" |
| 89 | auditRevoked = "revoked" |
| 90 | ) |
| 91 | |
| 92 | // ErrNoGrant: there is no usable grant (none, revoked, at another |
| 93 | // revision, beside another capability, or its approver is no longer an |
| 94 | // owner). |
| 95 | var ErrNoGrant = errors.New("chat: no usable grant") |
| 96 | |
| 97 | // ErrNotActive: the specialist is not active, so there is nothing to |
| 98 | // revoke. |
| 99 | var ErrNotActive = errors.New("chat: specialist not active") |
| 100 | |
| 101 | // Tool results for propose_specialist, read by the model. |
| 102 | const ( |
| 103 | toolSpecialistAsked = "Nothing is added yet: the person sees a card with what this specialist can do and its brief, with Add and Not now. Do not ask again in your reply; say in one line why you asked." |
| 104 | // toolSpecialistAskedProject: a proposal for one project, whose Add |
| 105 | // queues the continuation (specialist_added.go). |
| 106 | toolSpecialistAskedProject = "Nothing is added yet: the person sees a card with what this specialist can do, for this project only, and its brief, with Add and Not now. Do not record or start the work in this reply: if an owner taps Add, Equipo gives you a new turn to record it in that project and start it with this specialist. Do not ask again in your reply; say in one line why you asked." |
| 107 | toolSpecialistActive = "Already approved: this specialist is on the team for that scope. Do not propose it again." |
| 108 | toolSpecialistOpen = "Already proposed: a card for this specialist and scope is waiting for an owner's answer. Do not propose it again." |
| 109 | toolSpecialistOwner = "Only a team owner can add a specialist. Nothing was proposed." |
| 110 | toolSpecialistUnknown = "Refused: unknown profile. The profiles are research-v1 and design-v1." |
| 111 | toolSpecialistMenu = "Refused: capabilities and tools must be exactly the profile's. research-v1 is capabilities [\"web.research\"] and tools [\"submit_findings\", \"keep_image\"]; design-v1 is capabilities [\"branch.edit\", \"page.render\"] and tools [\"render_page\", \"submit_candidate\", \"ask_person\"]; nothing else." |
| 112 | toolSpecialistAlone = "Refused: web.research is never combined with any other capability or tool." |
| 113 | toolSpecialistName = "Refused: name is 1 to 40 letters, digits, spaces, hyphens or apostrophes, starting with a letter or digit, and not a built-in specialist's name (Engineering, Review, Checks)." |
| 114 | toolSpecialistBrief = "Refused: brief is required, plain text, and at most 2,048 bytes." |
| 115 | toolSpecialistOutdated = "Equipo needs an update before it can research." |
| 116 | // toolSpecialistTeamOnly: a scope for a profile that is the team's |
| 117 | // only (scopedProfiles). |
| 118 | toolSpecialistTeamOnly = "Refused: research-v1 is added for the whole team only; pass project \"\" or leave it out. Nothing was proposed." |
| 119 | toolSpecialistProject = "Refused: project must name one of the team's projects, as the project list shows it, or be \"\" for the whole team. Nothing was proposed." |
| 120 | toolSpecialistDeclined = "Refused: an owner said Not now to this specialist for this scope in the last 7 days. Do not propose it again; an owner can still add it themselves." |
| 121 | toolSpecialistNotTurn = "Refused: only the person's own message can lead to a specialist proposal. Nothing was proposed." |
| 122 | ) |
| 123 | |
| 124 | // scopedProfiles may be proposed for one project as well as the whole |
| 125 | // team. Any other profile is the team's only: research-v1. Its grant |
| 126 | // resolves per project now (researchGrant through grantFor), but a |
| 127 | // project-scoped Add queues the specialist_added continuation, which |
| 128 | // starts a task with that specialist as its maker, and Research is no |
| 129 | // maker; it stays team-wide until that continuation checks the profile. |
| 130 | var scopedProfiles = []string{specialist.ProfileDesign} |
| 131 | |
| 132 | // declineWindow is how long an owner's Not now holds a profile and scope |
| 133 | // back from the coordinator (spec section 4, No self-grant). |
| 134 | const declineWindow = 7 * 24 * time.Hour |
| 135 | |
| 136 | // toolProposeSpecialist runs propose_specialist for the person's turn |
| 137 | // (runTool has checked the turn is theirs and live): only in a person |
| 138 | // turn, on a connection at wire.ProtocolResearch, strictly decoded, |
| 139 | // against the closed menu, only for an owner, read in this transaction, |
| 140 | // and for a scope the profile allows (proposalScope). |
| 141 | func (t *txn) toolProposeSpecialist(l Lease, r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 142 | if l.Protocol < wire.ProtocolResearch { |
| 143 | return refused("research_unsupported", toolSpecialistOutdated), nil |
| 144 | } |
| 145 | if r.Kind != wire.TurnPerson { |
| 146 | return refused("not_person_turn", toolSpecialistNotTurn), nil |
| 147 | } |
| 148 | var in struct { |
| 149 | Profile string `json:"profile"` |
| 150 | Name string `json:"name"` |
| 151 | Brief string `json:"brief"` |
| 152 | Capabilities []string `json:"capabilities"` |
| 153 | Tools []string `json:"tools"` |
| 154 | // Project (protocol 38) is the scope: "" the team, else one of |
| 155 | // the team's projects (proposalScope), never read as the team's. |
| 156 | Project string `json:"project"` |
| 157 | } |
| 158 | if wire.Strict(v.Args, &in) != nil { |
| 159 | return refused("invalid", toolBadInput), nil |
| 160 | } |
| 161 | p, err := specialist.Validate(specialist.Proposal{Profile: in.Profile, Name: in.Name, Brief: in.Brief, Capabilities: in.Capabilities, Tools: in.Tools}) |
| 162 | switch { |
| 163 | case errors.Is(err, specialist.ErrUnknownProfile): |
| 164 | return refused("unknown_profile", toolSpecialistUnknown), nil |
| 165 | case errors.Is(err, specialist.ErrExclusive): |
| 166 | return refused("exclusive", toolSpecialistAlone), nil |
| 167 | case errors.Is(err, specialist.ErrNotOnMenu): |
| 168 | return refused("not_on_menu", toolSpecialistMenu), nil |
| 169 | case errors.Is(err, specialist.ErrName): |
| 170 | return refused("name", toolSpecialistName), nil |
| 171 | case errors.Is(err, specialist.ErrBrief): |
| 172 | return refused("brief", toolSpecialistBrief), nil |
| 173 | case err != nil: |
| 174 | return refused("invalid", toolBadInput), nil |
| 175 | } |
| 176 | if err := t.isOwner(r.Person); errors.Is(err, ErrForbidden) { |
| 177 | return refused("not_owner", toolSpecialistOwner), nil |
| 178 | } else if err != nil { |
| 179 | return wire.ToolResult{}, err |
| 180 | } |
| 181 | project, res, err := t.proposalScope(r.Person, p.Profile, in.Project) |
| 182 | if res != nil || err != nil { |
| 183 | return deref(res), err |
| 184 | } |
| 185 | return t.proposeSpecialist(r, p, project) |
| 186 | } |
| 187 | |
| 188 | // proposalScope is the project a proposal is for: none (the team's) for |
| 189 | // "", else the one active team project the text names (its id, or a name |
| 190 | // record_task would read as it), for a profile that may be scoped. A |
| 191 | // project that names nothing, or more than one, is refused, never read |
| 192 | // as the team's. |
| 193 | func (t *txn) proposalScope(person, profile, project string) (projectRecord, *wire.ToolResult, error) { |
| 194 | if project == "" { |
| 195 | return projectRecord{}, nil, nil |
| 196 | } |
| 197 | if !slices.Contains(scopedProfiles, profile) { |
| 198 | res := refused("team_only", toolSpecialistTeamOnly) |
| 199 | return projectRecord{}, &res, nil |
| 200 | } |
| 201 | name := strings.TrimSpace(project) |
| 202 | var byID []projectRecord |
| 203 | if err := t.db.Where("id = ? AND state = ?", name, wire.ProjectActive).Limit(1).Find(&byID).Error; err != nil { |
| 204 | return projectRecord{}, nil, err |
| 205 | } |
| 206 | if len(byID) == 1 { |
| 207 | return byID[0], nil, nil |
| 208 | } |
| 209 | p, err := t.namedProject(person, name) |
| 210 | if err != nil { |
| 211 | return projectRecord{}, nil, err |
| 212 | } |
| 213 | if p == nil || p.ID == "" || p.State != wire.ProjectActive { |
| 214 | res := refused("unknown_project", toolSpecialistProject) |
| 215 | return projectRecord{}, &res, nil |
| 216 | } |
| 217 | return *p, nil, nil |
| 218 | } |
| 219 | |
| 220 | // proposeSpecialist records a validated proposal for scope (project; the |
| 221 | // zero record is the team) and raises its card in the person's |
| 222 | // conversation: at most one open proposal per profile and scope, none |
| 223 | // for a profile already active in that scope, and none in the |
| 224 | // declineWindow after an owner's Not now on that profile and scope. A |
| 225 | // project's row and the team's are separate scopes. These checks answer |
| 226 | // first; the unique indexes (migration 0121) are only a backstop. |
| 227 | func (t *txn) proposeSpecialist(r turnRecord, p specialist.Proposal, project projectRecord) (wire.ToolResult, error) { |
| 228 | var rows []specialistRecord |
| 229 | if err := t.db.Where("profile = ? AND project_id = ? AND state IN ?", p.Profile, project.ID, []string{wire.SpecialistProposed, wire.SpecialistActive, wire.SpecialistDeclined}).Find(&rows).Error; err != nil { |
| 230 | return wire.ToolResult{}, err |
| 231 | } |
| 232 | now := t.now() |
| 233 | open := false |
| 234 | for _, s := range rows { |
| 235 | switch s.State { |
| 236 | case wire.SpecialistActive: |
| 237 | return refused("already_active", toolSpecialistActive), nil |
| 238 | case wire.SpecialistProposed: |
| 239 | open = true |
| 240 | } |
| 241 | } |
| 242 | if open { |
| 243 | return refused("already_proposed", toolSpecialistOpen), nil |
| 244 | } |
| 245 | for _, s := range rows { |
| 246 | // An answer with no time on it counts as recent: it denies. |
| 247 | if s.State == wire.SpecialistDeclined && (s.DecidedAt == nil || now.Sub(*s.DecidedAt) < declineWindow) { |
| 248 | return refused("declined_recently", toolSpecialistDeclined), nil |
| 249 | } |
| 250 | } |
| 251 | sp := specialistRecord{ID: newID("sp_"), Profile: p.Profile, ProjectID: project.ID, Name: p.Name, Brief: p.Brief, State: wire.SpecialistProposed, Revision: 1, ProposedBy: r.Person, ProposedTurn: r.ID, CardID: newID("c_"), CreatedAt: now, UpdatedAt: now} |
| 252 | if err := t.db.Create(&sp).Error; err != nil { |
| 253 | return wire.ToolResult{}, err |
| 254 | } |
| 255 | if err := t.specialistAudit(sp, auditProposed, r.Person); err != nil { |
| 256 | return wire.ToolResult{}, err |
| 257 | } |
| 258 | question := t.words("chat.card.specialist", p.Name) |
| 259 | if project.ID != "" { |
| 260 | question = t.words("chat.card.specialist_project", p.Name, project.shownTitle()) |
| 261 | } |
| 262 | if question == "" { |
| 263 | question = p.Name |
| 264 | } |
| 265 | options, _ := json.Marshal([]string{wire.ChoiceAdd, wire.ChoiceNotNow}) |
| 266 | c := cardRecord{ID: sp.CardID, Person: r.Person, Kind: wire.CardSpecialist, State: wire.CardOpen, TurnID: r.ID, Question: question, Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane} |
| 267 | if err := t.db.Create(&c).Error; err != nil { |
| 268 | return wire.ToolResult{}, err |
| 269 | } |
| 270 | if err := t.cardEvent(c); err != nil { |
| 271 | return wire.ToolResult{}, err |
| 272 | } |
| 273 | if project.ID != "" { |
| 274 | return wire.ToolResult{Code: "proposed", Text: toolSpecialistAskedProject}, nil |
| 275 | } |
| 276 | return wire.ToolResult{Code: "proposed", Text: toolSpecialistAsked}, nil |
| 277 | } |
| 278 | |
| 279 | // answerSpecialist is the answer on a specialist card: open and at its |
| 280 | // current revision, else a conflict with the card as it stands; the |
| 281 | // card's person, still an owner now (read in this transaction). Add makes |
| 282 | // the specialist active (none other active in its profile and scope) and |
| 283 | // writes one grant per profile capability at the new revision with its |
| 284 | // audit row, and for one project's specialist queues the continuation |
| 285 | // (queueSpecialistAdded); Not now declines it. All in this one |
| 286 | // transaction, with the card. |
| 287 | func (t *txn) answerSpecialist(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 288 | v, err := t.cardView(c) |
| 289 | if err != nil { |
| 290 | return wire.Card{}, wire.Card{}, err |
| 291 | } |
| 292 | if in.Choice != wire.ChoiceAdd && in.Choice != wire.ChoiceNotNow { |
| 293 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 294 | } |
| 295 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 296 | return wire.Card{}, v, ErrCardConflict |
| 297 | } |
| 298 | if c.Person != person { |
| 299 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 300 | } |
| 301 | if err := t.isOwner(person); err != nil { |
| 302 | return wire.Card{}, wire.Card{}, err |
| 303 | } |
| 304 | var sp specialistRecord |
| 305 | if err := t.db.Where("card_id = ?", c.ID).First(&sp).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 306 | return wire.Card{}, wire.Card{}, ErrNotFound |
| 307 | } else if err != nil { |
| 308 | return wire.Card{}, wire.Card{}, err |
| 309 | } |
| 310 | if sp.State != wire.SpecialistProposed { |
| 311 | return wire.Card{}, v, ErrCardConflict |
| 312 | } |
| 313 | profile, ok := specialist.Lookup(sp.Profile) |
| 314 | if !ok { |
| 315 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 316 | } |
| 317 | now := t.now() |
| 318 | sp.DecidedBy, sp.DecidedAt, sp.Revision, sp.UpdatedAt = person, &now, sp.Revision+1, now |
| 319 | action := auditDeclined |
| 320 | sp.State = wire.SpecialistDeclined |
| 321 | if in.Choice == wire.ChoiceAdd { |
| 322 | var active int64 |
| 323 | if err := t.db.Model(&specialistRecord{}).Where("profile = ? AND project_id = ? AND state = ?", sp.Profile, sp.ProjectID, wire.SpecialistActive).Count(&active).Error; err != nil { |
| 324 | return wire.Card{}, wire.Card{}, err |
| 325 | } |
| 326 | if active != 0 { |
| 327 | return wire.Card{}, v, ErrCardConflict |
| 328 | } |
| 329 | action = auditApproved |
| 330 | sp.State, sp.Approver, sp.ApprovedAt = wire.SpecialistActive, person, &now |
| 331 | } |
| 332 | if err := t.saveSpecialist(&sp); err != nil { |
| 333 | return wire.Card{}, wire.Card{}, err |
| 334 | } |
| 335 | if sp.State == wire.SpecialistActive { |
| 336 | for _, capability := range profile.Capabilities { |
| 337 | g := grantRecord{ID: newID("g_"), SpecialistID: sp.ID, Capability: capability, Revision: sp.Revision, GrantedBy: person, GrantedAt: now} |
| 338 | if err := t.db.Create(&g).Error; err != nil { |
| 339 | return wire.Card{}, wire.Card{}, err |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | if err := t.specialistAudit(sp, action, person); err != nil { |
| 344 | return wire.Card{}, wire.Card{}, err |
| 345 | } |
| 346 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 347 | if err := t.saveCard(&c); err != nil { |
| 348 | return wire.Card{}, wire.Card{}, err |
| 349 | } |
| 350 | if sp.State == wire.SpecialistActive { |
| 351 | if err := t.queueSpecialistAdded(c, sp, person); err != nil { |
| 352 | return wire.Card{}, wire.Card{}, err |
| 353 | } |
| 354 | } |
| 355 | out, err := t.cardView(c) |
| 356 | return out, wire.Card{}, err |
| 357 | } |
| 358 | |
| 359 | func (t *txn) saveSpecialist(sp *specialistRecord) error { |
| 360 | return t.db.Model(&specialistRecord{}).Where("id = ?", sp.ID).Select("state", "revision", "approver", "approved_at", "decided_by", "decided_at", "revoked_by", "revoked_at", "updated_at").Updates(sp).Error |
| 361 | } |
| 362 | |
| 363 | // specialistAudit appends one audit row for the specialist at its |
| 364 | // revision, here and in the instance's audit log, in this transaction. |
| 365 | // The detail is the profile and what it holds, never a credential. |
| 366 | func (t *txn) specialistAudit(sp specialistRecord, action, actor string) error { |
| 367 | detail := "profile=" + sp.Profile |
| 368 | if sp.ProjectID != "" { |
| 369 | detail += " project=" + sp.ProjectID |
| 370 | } |
| 371 | if p, ok := specialist.Lookup(sp.Profile); ok { |
| 372 | detail += " capabilities=" + strings.Join(p.Capabilities, ",") + " tools=" + strings.Join(p.Tools, ",") |
| 373 | } |
| 374 | a := specialistAuditRecord{ID: newID("sa_"), SpecialistID: sp.ID, Action: action, Actor: actor, Revision: sp.Revision, Detail: detail, At: t.now()} |
| 375 | if err := t.db.Create(&a).Error; err != nil { |
| 376 | return err |
| 377 | } |
| 378 | if t.s.authority.Audit == nil { |
| 379 | return nil |
| 380 | } |
| 381 | return t.s.authority.Audit(t.db, actor, "specialist."+action, sp.ID+"@"+sp.Profile) |
| 382 | } |
| 383 | |
| 384 | // researchGrant is the grant a Research step of a task in project runs |
| 385 | // under (checked at dispatch and before each start): the research-v1 |
| 386 | // specialist grantFor finds for that project (its own row, else the |
| 387 | // team's), whose one grant is web.research and nothing beside it, at its |
| 388 | // revision, given by its approver, an owner now (usableGrant). Anything |
| 389 | // else is ErrNoGrant; a lookup error is returned, and denies too. |
| 390 | func (t *txn) researchGrant(project string) (specialistRecord, grantRecord, error) { |
| 391 | sp, grants, err := t.usableGrant(specialist.ProfileResearch, project) |
| 392 | if err != nil { |
| 393 | return specialistRecord{}, grantRecord{}, err |
| 394 | } |
| 395 | // usableGrant has checked the grants are exactly the profile's, |
| 396 | // web.research alone; the length check only guards the index. |
| 397 | if sp == nil || len(grants) != 1 { |
| 398 | return specialistRecord{}, grantRecord{}, ErrNoGrant |
| 399 | } |
| 400 | return *sp, grants[0], nil |
| 401 | } |
| 402 | |
| 403 | // cancelResearch cancels every unfinished Research step that runs under |
| 404 | // sp, in the revoke's transaction: one bound to it at dispatch; one from |
| 405 | // before bindings (task 16) dispatched under one of its grants; and one |
| 406 | // not yet dispatched whose task's project resolves to it |
| 407 | // (researchResolvesTo). One that is queued (waiting for its fixed point, |
| 408 | // its card, the inventory or a runner; dispatched; or authorized and |
| 409 | // deferred on its runner) ends cancelled at once: its card is withdrawn, |
| 410 | // its dispatch retired, a runner that may hold it is asked to cancel it, |
| 411 | // and the Engineering it held is released. A running one gets the |
| 412 | // ordinary cancel: its runner is asked to stop it and reports its end, |
| 413 | // and its start authorization is refused from now on |
| 414 | // (authorizeResearch). |
| 415 | func (t *txn) cancelResearch(sp specialistRecord) error { |
| 416 | if sp.Profile != specialist.ProfileResearch { |
| 417 | return nil |
| 418 | } |
| 419 | var grants []string |
| 420 | if err := t.db.Model(&grantRecord{}).Where("specialist_id = ?", sp.ID).Pluck("id", &grants).Error; err != nil { |
| 421 | return err |
| 422 | } |
| 423 | var rows []stepRecord |
| 424 | if err := t.db.Where("specialist = ? AND state IN ?", wire.SpecialistResearch, []string{wire.StepQueued, wire.StepRunning}).Order("created_at, id").Find(&rows).Error; err != nil { |
| 425 | return err |
| 426 | } |
| 427 | for i := range rows { |
| 428 | s := &rows[i] |
| 429 | k, err := t.loadTask(s.TaskID) |
| 430 | if err != nil { |
| 431 | return err |
| 432 | } |
| 433 | mine := s.SpecialistID == sp.ID |
| 434 | switch { |
| 435 | case s.SpecialistID != "": |
| 436 | case s.ResearchGrant != "": |
| 437 | mine = slices.Contains(grants, s.ResearchGrant) |
| 438 | default: |
| 439 | if mine, err = t.researchResolvesTo(sp, k.ProjectID); err != nil { |
| 440 | return err |
| 441 | } |
| 442 | } |
| 443 | if !mine { |
| 444 | continue |
| 445 | } |
| 446 | if err := t.retireResearch(*s); err != nil { |
| 447 | return err |
| 448 | } |
| 449 | if err := t.withdrawSources(*s); err != nil { |
| 450 | return err |
| 451 | } |
| 452 | if s.State == wire.StepRunning { |
| 453 | continue |
| 454 | } |
| 455 | now := t.now() |
| 456 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, wire.ReasonResearchNoGrant, true, &now, "", nil |
| 457 | if err := t.saveStep(s, &k); err != nil { |
| 458 | return err |
| 459 | } |
| 460 | } |
| 461 | return nil |
| 462 | } |
| 463 | |
| 464 | // RevokeSpecialist is POST /api/v1/specialists/{id}/revoke: an owner, |
| 465 | // read in this transaction, revokes an active specialist at its current |
| 466 | // revision. Its grants are revoked with an audit row, and the steps |
| 467 | // bound to it cancelled and their pending publications withdrawn |
| 468 | // (cancelSpecialist), in one transaction. |
| 469 | func (s *Store) RevokeSpecialist(ctx context.Context, person, id string, in wire.RevokeSpecialist) (out wire.Specialist, err error) { |
| 470 | err = s.tx(ctx, func(t *txn) error { |
| 471 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 472 | return err |
| 473 | } |
| 474 | if err := t.isOwner(person); err != nil { |
| 475 | return err |
| 476 | } |
| 477 | var sp specialistRecord |
| 478 | if err := t.db.Where("id = ?", id).First(&sp).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 479 | return ErrNotFound |
| 480 | } else if err != nil { |
| 481 | return err |
| 482 | } |
| 483 | if sp.Revision != in.Revision { |
| 484 | return ErrRevision |
| 485 | } |
| 486 | if sp.State != wire.SpecialistActive { |
| 487 | return ErrNotActive |
| 488 | } |
| 489 | now := t.now() |
| 490 | sp.State, sp.RevokedBy, sp.RevokedAt, sp.Revision, sp.UpdatedAt = wire.SpecialistRevoked, person, &now, sp.Revision+1, now |
| 491 | if err := t.saveSpecialist(&sp); err != nil { |
| 492 | return err |
| 493 | } |
| 494 | if err := t.db.Model(&grantRecord{}).Where("specialist_id = ? AND revoked_at IS NULL", sp.ID).Select("revoked_by", "revoked_at").Updates(grantRecord{RevokedBy: person, RevokedAt: &now}).Error; err != nil { |
| 495 | return err |
| 496 | } |
| 497 | if err := t.specialistAudit(sp, auditRevoked, person); err != nil { |
| 498 | return err |
| 499 | } |
| 500 | if err := t.cancelSpecialist(sp); err != nil { |
| 501 | return err |
| 502 | } |
| 503 | out = specialistView(sp) |
| 504 | return nil |
| 505 | }) |
| 506 | return out, err |
| 507 | } |
| 508 | |
| 509 | // Specialists is GET /api/v1/specialists: the team's data-defined |
| 510 | // specialists, newest first, for any current member to read. |
| 511 | func (s *Store) Specialists(ctx context.Context, person string) (out wire.SpecialistList, err error) { |
| 512 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 513 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 514 | return err |
| 515 | } |
| 516 | var rows []specialistRecord |
| 517 | if err := tx.Order("created_at DESC, id").Find(&rows).Error; err != nil { |
| 518 | return err |
| 519 | } |
| 520 | out.Items = make([]wire.Specialist, 0, len(rows)) |
| 521 | for _, sp := range rows { |
| 522 | out.Items = append(out.Items, specialistView(sp)) |
| 523 | } |
| 524 | return nil |
| 525 | }) |
| 526 | return out, err |
| 527 | } |
| 528 | |
| 529 | func specialistView(sp specialistRecord) wire.Specialist { |
| 530 | v := wire.Specialist{ID: sp.ID, Revision: sp.Revision, Profile: sp.Profile, Project: sp.ProjectID, Name: sp.Name, Brief: sp.Brief, Model: sp.ModelPreference, State: sp.State, Capabilities: []string{}, Tools: []string{}, ProposedBy: sp.ProposedBy, Approver: sp.Approver, ApprovedAt: sp.ApprovedAt, RevokedBy: sp.RevokedBy, RevokedAt: sp.RevokedAt, CreatedAt: sp.CreatedAt, UpdatedAt: sp.UpdatedAt} |
| 531 | if p, ok := specialist.Lookup(sp.Profile); ok { |
| 532 | v.Capabilities, v.Tools = p.Capabilities, p.Tools |
| 533 | } |
| 534 | return v |
| 535 | } |
| 536 | |
| 537 | // specialistCard is what a specialist card shows: its proposal and each |
| 538 | // capability in the instance's words. |
| 539 | func (t *txn) specialistCard(cardID string) (wire.CardSpecialistView, error) { |
| 540 | var sp specialistRecord |
| 541 | if err := t.db.Where("card_id = ?", cardID).First(&sp).Error; err != nil { |
| 542 | return wire.CardSpecialistView{}, err |
| 543 | } |
| 544 | v := wire.CardSpecialistView{ID: sp.ID, Profile: sp.Profile, Name: sp.Name, Brief: sp.Brief, State: sp.State, Capabilities: []wire.SpecialistCapability{}} |
| 545 | if p, ok := specialist.Lookup(sp.Profile); ok { |
| 546 | for _, c := range p.Capabilities { |
| 547 | v.Capabilities = append(v.Capabilities, wire.SpecialistCapability{ID: c, Words: t.words(specialist.Describe(c))}) |
| 548 | } |
| 549 | } |
| 550 | return v, nil |
| 551 | } |
| 552 | |