| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "slices" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/websource" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | "gorm.io/gorm" |
| 17 | ) |
| 18 | |
| 19 | // Research's sources, card and scheduling (Research spec §2, slice R2). |
| 20 | // |
| 21 | // The coordinator's research tool only requests a run: it records a |
| 22 | // Research step waiting for the task's next fixed point (Boundary), with |
| 23 | // its sources, and a card when it proposed URLs. Fixed points are the |
| 24 | // task's start ("start", before the first Engineering step) and the |
| 25 | // boundary before each later Engineering round ("round:<n>", after the |
| 26 | // Review or Checks result that sends it). At its fixed point the step |
| 27 | // starts; while any started Research step of the task has not ended, the |
| 28 | // Engineering step created there is held (wire.PlacementResearch), and |
| 29 | // it is dispatched when Research ends, however it ends (saveStep calls |
| 30 | // releaseResearch). Research steps are never judgements: progress skips |
| 31 | // them, and they are never a task's last word. |
| 32 | |
| 33 | // researchSourceRecord is one source of a Research step, in order: the |
| 34 | // person's own (approved from the start) then the coordinator's |
| 35 | // proposals (approved only by Allow on the step's card). URL is the |
| 36 | // canonical form (websource.URL.String), parsed once at the request. |
| 37 | type researchSourceRecord struct { |
| 38 | StepID string `gorm:"primaryKey"` |
| 39 | Idx int `gorm:"primaryKey"` |
| 40 | SourceID string |
| 41 | URL string |
| 42 | Origin string |
| 43 | Approved bool |
| 44 | CreatedAt time.Time |
| 45 | } |
| 46 | |
| 47 | func (researchSourceRecord) TableName() string { return "chat_research_sources" } |
| 48 | |
| 49 | // The fixed point a Research step waits for. |
| 50 | const boundaryStart = "start" |
| 51 | |
| 52 | func boundaryRound(round int) string { return "round:" + strconv.Itoa(round) } |
| 53 | |
| 54 | // Tool results for research, read by the model. |
| 55 | const ( |
| 56 | toolResearchStart = "Requested. Research reads the pages when the task starts: call start_task as usual, and Engineering begins once Research is done. Do not wait for its findings in your reply; say in one line that Research will look at the pages first." |
| 57 | toolResearchRound = "Requested. Research reads the pages after the task's current review, before Engineering's next round, and that round waits for it. If no further round comes, it does not run. Do not wait for its findings in your reply." |
| 58 | toolResearchCard = " The person sees a card with the URLs you proposed, in full, with Allow and Skip; do not ask about them again in your reply." |
| 59 | toolResearchNoGrant = "Refused: Research is not on the team. If the person wants web pages read for this, propose it with propose_specialist; an owner adds it." |
| 60 | toolResearchQuestion = "Refused: question is required, plain text, and at most 1,000 bytes." |
| 61 | toolResearchSecret = "Refused: the question looks like it holds a secret (a key, token or password). Say what to look for in plain words." |
| 62 | toolResearchTooMany = "Refused: at most 10 urls." |
| 63 | toolResearchURL = "Refused: a proposed URL is https or http on the standard port, with a public host name (no IP address, and no local, private or tailnet name), no user name, no query string, a path of at most 100 characters, and nothing that looks like a secret. Refused for: " |
| 64 | toolResearchLimit = "Refused: this task has had its 3 Research runs. Equipo does not run more." |
| 65 | toolResearchTaken = "Refused: Research is already requested for this point in the task (its start, or the next review round). One run per point." |
| 66 | toolResearchNoRound = "Refused: this task has no Engineering round ahead (it is ready to merge or merging), so there is no point at which Research could run." |
| 67 | toolResearchNoSources = "Refused: nothing to read. The person's words on the task name no page, and you proposed none. Propose the pages in urls." |
| 68 | ) |
| 69 | |
| 70 | // toolResearch runs research for the person's turn (runTool has checked |
| 71 | // the turn is theirs, live and a person turn): only on a connection at |
| 72 | // wire.ProtocolResearch, strictly decoded, for the person's own open |
| 73 | // task, an owner, a usable grant, a clean question and proposals that |
| 74 | // keep the rules; at most one per fixed point and MaxResearchRuns per |
| 75 | // task, and only when there is something to read. |
| 76 | func (t *txn) toolResearch(l Lease, r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 77 | if l.Protocol < wire.ProtocolResearch { |
| 78 | return refused("research_unsupported", toolSpecialistOutdated), nil |
| 79 | } |
| 80 | var in struct { |
| 81 | Task string `json:"task"` |
| 82 | Question string `json:"question"` |
| 83 | URLs []string `json:"urls"` |
| 84 | } |
| 85 | if wire.Strict(v.Args, &in) != nil { |
| 86 | return refused("invalid", toolBadInput), nil |
| 87 | } |
| 88 | k, res, err := t.ownTask(r.Person, in.Task) |
| 89 | if res != nil || err != nil { |
| 90 | return deref(res), err |
| 91 | } |
| 92 | if err := t.isOwner(r.Person); errors.Is(err, ErrForbidden) { |
| 93 | return refused("not_owner", toolNotOwner), nil |
| 94 | } else if err != nil { |
| 95 | return wire.ToolResult{}, err |
| 96 | } |
| 97 | // Research reads web pages for the person the job is for: they need |
| 98 | // web (spec 2026-11-26-assistant-abilities §6.2). |
| 99 | if ok, err := t.researchAllowed(k.ID); err != nil || !ok { |
| 100 | if err != nil { |
| 101 | return wire.ToolResult{}, err |
| 102 | } |
| 103 | return refused(wire.CodeResearchOff, toolResearchOff), nil |
| 104 | } |
| 105 | question, ok := cleanText(in.Question, wire.MaxResearchQuestion) |
| 106 | if !ok { |
| 107 | return refused("question", toolResearchQuestion), nil |
| 108 | } |
| 109 | if websource.LooksSecret(question) { |
| 110 | return refused("secret", toolResearchSecret), nil |
| 111 | } |
| 112 | if len(in.URLs) > wire.MaxResearchProposals { |
| 113 | return refused("too_many_urls", toolResearchTooMany), nil |
| 114 | } |
| 115 | var proposed []websource.URL |
| 116 | for _, raw := range in.URLs { |
| 117 | u, err := websource.Proposal(strings.TrimSpace(raw)) |
| 118 | if err != nil { |
| 119 | return refused(websource.Reason(err), toolResearchURL+websource.Reason(err)+"."), nil |
| 120 | } |
| 121 | proposed = append(proposed, u) |
| 122 | } |
| 123 | if _, _, err := t.researchGrant(k.ProjectID); errors.Is(err, ErrNoGrant) { |
| 124 | return refused("no_grant", toolResearchNoGrant), nil |
| 125 | } else if err != nil { |
| 126 | return wire.ToolResult{}, err |
| 127 | } |
| 128 | steps, err := t.steps(k.ID) |
| 129 | if err != nil { |
| 130 | return wire.ToolResult{}, err |
| 131 | } |
| 132 | // Every Research step counts, cancelled or not. |
| 133 | if runs := researchSteps(steps); len(runs) >= wire.MaxResearchRuns { |
| 134 | return refused("research_limit", toolResearchLimit), nil |
| 135 | } |
| 136 | if k.Stage == wire.StageReadyToMerge || k.Stage == wire.StageMerging { |
| 137 | return refused("no_round", toolResearchNoRound), nil |
| 138 | } |
| 139 | boundary := nextBoundary(steps) |
| 140 | if slices.ContainsFunc(researchSteps(steps), func(s stepRecord) bool { return s.Boundary == boundary }) { |
| 141 | return refused("boundary_taken", toolResearchTaken), nil |
| 142 | } |
| 143 | words, err := t.personWords(k, r.ID) |
| 144 | if err != nil { |
| 145 | return wire.ToolResult{}, err |
| 146 | } |
| 147 | var sources []researchSourceRecord |
| 148 | seen := map[string]bool{} |
| 149 | add := func(u websource.URL, origin string) { |
| 150 | if seen[u.String()] { |
| 151 | return |
| 152 | } |
| 153 | seen[u.String()] = true |
| 154 | sources = append(sources, researchSourceRecord{URL: u.String(), Origin: origin, Approved: origin == wire.ResearchOriginPerson}) |
| 155 | } |
| 156 | mine := 0 |
| 157 | for _, w := range words { |
| 158 | for _, u := range websource.Mentions(w) { |
| 159 | if mine < wire.MaxResearchPersonSources && !seen[u.String()] { |
| 160 | mine++ |
| 161 | add(u, wire.ResearchOriginPerson) |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | for _, u := range proposed { |
| 166 | add(u, wire.ResearchOriginProposed) |
| 167 | } |
| 168 | if len(sources) == 0 { |
| 169 | return refused("no_sources", toolResearchNoSources), nil |
| 170 | } |
| 171 | return t.requestResearch(r, k, steps, boundary, question, sources) |
| 172 | } |
| 173 | |
| 174 | // requestResearch records the Research step waiting for its fixed point, |
| 175 | // its sources in order, and the card about its proposals, if any. |
| 176 | func (t *txn) requestResearch(r turnRecord, k taskRecord, steps []stepRecord, boundary, question string, sources []researchSourceRecord) (wire.ToolResult, error) { |
| 177 | now := t.now() |
| 178 | s := stepRecord{ID: newID("s_"), TaskID: k.ID, Idx: nextIdx(steps), Specialist: wire.SpecialistResearch, Person: r.Person, State: wire.StepQueued, Attempt: 1, Kind: wire.NormalKind(k.Kind), Placement: wire.PlacementBoundary, Boundary: boundary, Question: question, RequestTurn: r.ID, CreatedAt: now, UpdatedAt: now} |
| 179 | var asked []string |
| 180 | for i := range sources { |
| 181 | sources[i].StepID, sources[i].Idx, sources[i].SourceID, sources[i].CreatedAt = s.ID, i+1, "s"+strconv.Itoa(i+1), now |
| 182 | if sources[i].Origin == wire.ResearchOriginProposed { |
| 183 | asked = append(asked, sources[i].URL) |
| 184 | } |
| 185 | } |
| 186 | if len(asked) > 0 { |
| 187 | s.SourcesCard, s.SourcesHash = newID("c_"), sourcesHash(s.ID, asked) |
| 188 | } |
| 189 | if err := t.db.Create(&s).Error; err != nil { |
| 190 | return wire.ToolResult{}, err |
| 191 | } |
| 192 | if err := t.db.Create(&sources).Error; err != nil { |
| 193 | return wire.ToolResult{}, err |
| 194 | } |
| 195 | text := toolResearchRound |
| 196 | if boundary == boundaryStart { |
| 197 | text = toolResearchStart |
| 198 | } |
| 199 | if s.SourcesCard != "" { |
| 200 | question := t.words("chat.card.research_sources") |
| 201 | if question == "" { |
| 202 | question = "Let Research read these pages?" |
| 203 | } |
| 204 | options, _ := json.Marshal([]string{wire.ChoiceAllow, wire.ChoiceSkip}) |
| 205 | c := cardRecord{ID: s.SourcesCard, Person: r.Person, Kind: wire.CardResearchSources, State: wire.CardOpen, TurnID: r.ID, ProjectID: k.ProjectID, TaskID: k.ID, Question: question, Options: string(options), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane} |
| 206 | if err := t.db.Create(&c).Error; err != nil { |
| 207 | return wire.ToolResult{}, err |
| 208 | } |
| 209 | if err := t.cardEvent(c); err != nil { |
| 210 | return wire.ToolResult{}, err |
| 211 | } |
| 212 | text += toolResearchCard |
| 213 | } |
| 214 | if err := t.saveStep(&s, &k); err != nil { |
| 215 | return wire.ToolResult{}, err |
| 216 | } |
| 217 | return wire.ToolResult{Code: "requested", Text: text}, nil |
| 218 | } |
| 219 | |
| 220 | func researchSteps(steps []stepRecord) []stepRecord { |
| 221 | var out []stepRecord |
| 222 | for _, s := range steps { |
| 223 | if s.Specialist == wire.SpecialistResearch { |
| 224 | out = append(out, s) |
| 225 | } |
| 226 | } |
| 227 | return out |
| 228 | } |
| 229 | |
| 230 | func nextIdx(steps []stepRecord) int { |
| 231 | n := 0 |
| 232 | for _, s := range steps { |
| 233 | n = max(n, s.Idx) |
| 234 | } |
| 235 | return n + 1 |
| 236 | } |
| 237 | |
| 238 | // nextBoundary is the task's next fixed point: its start until it has an |
| 239 | // Engineering step, then the round after its newest Engineering step's. |
| 240 | func nextBoundary(steps []stepRecord) string { |
| 241 | var eng *stepRecord |
| 242 | for i := range steps { |
| 243 | if steps[i].Specialist == wire.SpecialistEngineering && (eng == nil || steps[i].Idx > eng.Idx) { |
| 244 | eng = &steps[i] |
| 245 | } |
| 246 | } |
| 247 | if eng == nil { |
| 248 | return boundaryStart |
| 249 | } |
| 250 | return boundaryRound(eng.Round + 1) |
| 251 | } |
| 252 | |
| 253 | // sourcesHash binds a sources card to its step and the exact list of |
| 254 | // URLs it shows, in order. |
| 255 | func sourcesHash(stepID string, urls []string) string { |
| 256 | sum := sha256.Sum256([]byte(stepID + "\n" + strings.Join(urls, "\n"))) |
| 257 | return hex.EncodeToString(sum[:]) |
| 258 | } |
| 259 | |
| 260 | // personWords are the task creator's own words on the task, verbatim and |
| 261 | // oldest first. Only what the creator sent, authenticated as theirs, |
| 262 | // counts: composer-origin message rows (role person) in turns linked to the |
| 263 | // task (the turn that recorded it, the turn that requested this Research, |
| 264 | // the turns whose add_report joined it, and the same for every task of |
| 265 | // theirs folded into it, or cancelled as a duplicate of it), then the notes they posted |
| 266 | // on its page themselves (PostThread). For a handoff, read the original |
| 267 | // Assistant turn's composer messages, never the model-selected excerpt. |
| 268 | // Nothing the coordinator wrote ever |
| 269 | // counts: not add_report text, a title, a brief, a fold's copy of them, |
| 270 | // or a note Equipo wrote; a URL only there is a proposal, asked about on |
| 271 | // a card. |
| 272 | func (t *txn) personWords(k taskRecord, requestTurn string) ([]string, error) { |
| 273 | tasks := []string{k.ID} |
| 274 | turns := []string{} |
| 275 | if k.TurnID != "" { |
| 276 | turns = append(turns, k.TurnID) |
| 277 | } |
| 278 | if requestTurn != "" { |
| 279 | turns = append(turns, requestTurn) |
| 280 | } |
| 281 | seen := map[string]bool{k.ID: true} |
| 282 | for i := 0; i < len(tasks) && i < maxLinkedTasks; i++ { |
| 283 | var keys []string |
| 284 | if err := t.db.Model(&entryRecord{}).Where("task_id = ? AND kind = ? AND (folded_from IS NULL OR folded_from = '') AND substr(idempotency_key, 1, 7) = ?", tasks[i], entryReport, "report:").Pluck("idempotency_key", &keys).Error; err != nil { |
| 285 | return nil, err |
| 286 | } |
| 287 | for _, key := range keys { |
| 288 | if turn, _, ok := strings.Cut(strings.TrimPrefix(key, "report:"), ":"); ok && turn != "" { |
| 289 | turns = append(turns, turn) |
| 290 | } |
| 291 | } |
| 292 | var linked []taskRecord |
| 293 | if err := t.db.Select("id", "turn_id").Where("creator = ? AND (folded_into = ? OR duplicate_of = ? AND (stage = ? OR cancel_requested))", k.Creator, tasks[i], tasks[i], wire.StageCancelled).Order("created_at, id").Find(&linked).Error; err != nil { |
| 294 | return nil, err |
| 295 | } |
| 296 | for _, d := range linked { |
| 297 | if seen[d.ID] { |
| 298 | continue |
| 299 | } |
| 300 | seen[d.ID] = true |
| 301 | tasks = append(tasks, d.ID) |
| 302 | if d.TurnID != "" { |
| 303 | turns = append(turns, d.TurnID) |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | var out []string |
| 308 | if err := t.db.Model(&messageRecord{}).Where("turn_id IN ? AND person = ? AND role = ? AND origin = ?", turns, k.Creator, wire.RolePerson, originComposer).Order("seq").Pluck("text", &out).Error; err != nil { |
| 309 | return nil, err |
| 310 | } |
| 311 | var handoffs []handoffRecord |
| 312 | if err := t.db.Where("person = ? AND id IN (?)", k.Creator, t.db.Model(&handoffTurnRecord{}).Select("handoff_id").Where("turn_id IN ?", turns)).Find(&handoffs).Error; err != nil { |
| 313 | return nil, err |
| 314 | } |
| 315 | for _, h := range handoffs { |
| 316 | var handed messageRecord |
| 317 | if h.MessageID == "" { |
| 318 | continue |
| 319 | } |
| 320 | if err := t.db.First(&handed, "id = ? AND person = ?", h.MessageID, k.Creator).Error; err != nil { |
| 321 | return nil, err |
| 322 | } |
| 323 | var originals []string |
| 324 | if err := t.db.Model(&messageRecord{}).Where("turn_id = ? AND person = ? AND role = ? AND origin = ?", h.AssistantTurn, k.Creator, wire.RolePerson, originComposer).Order("seq").Pluck("text", &originals).Error; err != nil { |
| 325 | return nil, err |
| 326 | } |
| 327 | quote, _, _ := folded(handed.Text) |
| 328 | for _, original := range originals { |
| 329 | if _, ok := quoteIn(original, strings.TrimSpace(quote)); ok && strings.TrimSpace(quote) != "" { |
| 330 | out = append(out, original) |
| 331 | break |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | prefix := "note:" + k.Creator + ":" |
| 336 | var notes []string |
| 337 | if err := t.db.Model(&entryRecord{}).Where("task_id IN ? AND author = ? AND kind = ? AND (folded_from IS NULL OR folded_from = '') AND substr(idempotency_key, 1, ?) = ?", tasks, k.Creator, entryNote, len(prefix), prefix).Order("created_at, id").Pluck("text", ¬es).Error; err != nil { |
| 338 | return nil, err |
| 339 | } |
| 340 | return append(out, notes...), nil |
| 341 | } |
| 342 | |
| 343 | // maxLinkedTasks bounds the tasks personWords follows through folds and |
| 344 | // duplicates. |
| 345 | const maxLinkedTasks = 20 |
| 346 | |
| 347 | // Keep complete messages within the dispatch budget, newest first in |
| 348 | // selection but oldest first in the prompt. Never clip a person's words. |
| 349 | func boundedPersonWords(words []string) []string { |
| 350 | budget := wire.MaxMessageBytes |
| 351 | start := len(words) |
| 352 | for start > 0 && len(words[start-1]) <= budget { |
| 353 | start-- |
| 354 | budget -= len(words[start]) |
| 355 | } |
| 356 | return words[start:] |
| 357 | } |
| 358 | |
| 359 | // researchSources are the step's sources in order: all, or only those |
| 360 | // approved. |
| 361 | func (t *txn) researchSources(stepID string, approved bool) ([]researchSourceRecord, error) { |
| 362 | q := t.db.Where("step_id = ?", stepID) |
| 363 | if approved { |
| 364 | q = q.Where("approved = ?", true) |
| 365 | } |
| 366 | var rows []researchSourceRecord |
| 367 | return rows, q.Order("idx").Find(&rows).Error |
| 368 | } |
| 369 | |
| 370 | // proposedURLs are the URLs the step's card asks about, in order. |
| 371 | func (t *txn) proposedURLs(stepID string) ([]string, error) { |
| 372 | var urls []string |
| 373 | err := t.db.Model(&researchSourceRecord{}).Where("step_id = ? AND origin = ?", stepID, wire.ResearchOriginProposed).Order("idx").Pluck("url", &urls).Error |
| 374 | return urls, err |
| 375 | } |
| 376 | |
| 377 | // researchCard is what a sources card shows. |
| 378 | func (t *txn) researchCard(c cardRecord) (*wire.CardResearchView, error) { |
| 379 | var s stepRecord |
| 380 | if err := t.db.Where("sources_card = ?", c.ID).First(&s).Error; err != nil { |
| 381 | return nil, err |
| 382 | } |
| 383 | urls, err := t.proposedURLs(s.ID) |
| 384 | if err != nil { |
| 385 | return nil, err |
| 386 | } |
| 387 | if urls == nil { |
| 388 | urls = []string{} |
| 389 | } |
| 390 | return &wire.CardResearchView{StepID: s.ID, Question: s.Question, URLs: urls}, nil |
| 391 | } |
| 392 | |
| 393 | // answerResearchSources is the creator's answer on a sources card: open |
| 394 | // and at its current revision, else a conflict with the card as it |
| 395 | // stands; the card's person, its task's creator, an owner now (read in |
| 396 | // this transaction); the step not ended; and the list the card shows |
| 397 | // still exactly the one it was raised with. Allow approves those URLs, |
| 398 | // Skip drops them; a step already at its fixed point goes on at once. |
| 399 | func (t *txn) answerResearchSources(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) { |
| 400 | v, err := t.cardView(c) |
| 401 | if err != nil { |
| 402 | return wire.Card{}, wire.Card{}, err |
| 403 | } |
| 404 | if in.Choice != wire.ChoiceAllow && in.Choice != wire.ChoiceSkip { |
| 405 | return wire.Card{}, wire.Card{}, ErrInvalid |
| 406 | } |
| 407 | if c.State != wire.CardOpen || c.Revision != in.Revision { |
| 408 | return wire.Card{}, v, ErrCardConflict |
| 409 | } |
| 410 | if c.Person != person { |
| 411 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 412 | } |
| 413 | var s stepRecord |
| 414 | if err := t.db.Where("sources_card = ? AND specialist = ?", c.ID, wire.SpecialistResearch).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 415 | return wire.Card{}, wire.Card{}, ErrNotFound |
| 416 | } else if err != nil { |
| 417 | return wire.Card{}, wire.Card{}, err |
| 418 | } |
| 419 | k, err := t.loadTask(s.TaskID) |
| 420 | if err != nil { |
| 421 | return wire.Card{}, wire.Card{}, err |
| 422 | } |
| 423 | if k.Creator != person || s.Person != person { |
| 424 | return wire.Card{}, wire.Card{}, ErrForbidden |
| 425 | } |
| 426 | if err := t.isOwner(person); err != nil { |
| 427 | return wire.Card{}, wire.Card{}, err |
| 428 | } |
| 429 | if wire.StepTerminal(s.State) || wire.FinalStage(k.Stage) || k.CancelRequested { |
| 430 | return wire.Card{}, v, ErrCardConflict |
| 431 | } |
| 432 | urls, err := t.proposedURLs(s.ID) |
| 433 | if err != nil { |
| 434 | return wire.Card{}, wire.Card{}, err |
| 435 | } |
| 436 | if s.SourcesHash == "" || sourcesHash(s.ID, urls) != s.SourcesHash { |
| 437 | return wire.Card{}, v, ErrCardConflict |
| 438 | } |
| 439 | if in.Choice == wire.ChoiceAllow { |
| 440 | if err := t.db.Model(&researchSourceRecord{}).Where("step_id = ? AND origin = ?", s.ID, wire.ResearchOriginProposed).Update("approved", true).Error; err != nil { |
| 441 | return wire.Card{}, wire.Card{}, err |
| 442 | } |
| 443 | } |
| 444 | c.State, c.Choice = wire.CardAnswered, in.Choice |
| 445 | if err := t.saveCard(&c); err != nil { |
| 446 | return wire.Card{}, wire.Card{}, err |
| 447 | } |
| 448 | if s.Placement == wire.PlacementSources { |
| 449 | if err := t.dispatchStep(&k, &s); err != nil { |
| 450 | return wire.Card{}, wire.Card{}, err |
| 451 | } |
| 452 | if err := t.saveStep(&s, &k); err != nil { |
| 453 | return wire.Card{}, wire.Card{}, err |
| 454 | } |
| 455 | } |
| 456 | out, err := t.cardView(c) |
| 457 | return out, wire.Card{}, err |
| 458 | } |
| 459 | |
| 460 | // researchAt starts the task's Research requested for this fixed point, |
| 461 | // if any, and reports whether the Engineering step created here is held: |
| 462 | // some Research step of the task has started and not ended. A started |
| 463 | // step moves to the end of the task's steps, just before that |
| 464 | // Engineering step. |
| 465 | func (t *txn) researchAt(k *taskRecord, boundary string) (bool, error) { |
| 466 | var due []stepRecord |
| 467 | if err := t.db.Where("task_id = ? AND specialist = ? AND state = ? AND placement = ? AND boundary = ?", k.ID, wire.SpecialistResearch, wire.StepQueued, wire.PlacementBoundary, boundary).Find(&due).Error; err != nil { |
| 468 | return false, err |
| 469 | } |
| 470 | for i := range due { |
| 471 | s := &due[i] |
| 472 | steps, err := t.steps(k.ID) |
| 473 | if err != nil { |
| 474 | return false, err |
| 475 | } |
| 476 | if s.Idx != nextIdx(steps)-1 { |
| 477 | s.Idx = nextIdx(steps) |
| 478 | if err := t.db.Model(&stepRecord{}).Where("id = ?", s.ID).Update("idx", s.Idx).Error; err != nil { |
| 479 | return false, err |
| 480 | } |
| 481 | } |
| 482 | s.Placement = "" |
| 483 | if err := t.dispatchStep(k, s); err != nil { |
| 484 | return false, err |
| 485 | } |
| 486 | if err := t.saveStep(s, k); err != nil { |
| 487 | return false, err |
| 488 | } |
| 489 | } |
| 490 | return t.researchActive(k.ID) |
| 491 | } |
| 492 | |
| 493 | // researchActive reports whether a Research step of the task has started |
| 494 | // (it is past its fixed point) and not ended. |
| 495 | func (t *txn) researchActive(taskID string) (bool, error) { |
| 496 | var n int64 |
| 497 | err := t.db.Model(&stepRecord{}).Where("task_id = ? AND specialist = ? AND state IN ? AND placement <> ?", taskID, wire.SpecialistResearch, []string{wire.StepQueued, wire.StepRunning}, wire.PlacementBoundary).Count(&n).Error |
| 498 | return n > 0, err |
| 499 | } |
| 500 | |
| 501 | // releaseResearch dispatches the task's Engineering steps held for |
| 502 | // Research once no started Research step of it is left. Idempotent. |
| 503 | func (t *txn) releaseResearch(k *taskRecord) error { |
| 504 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 505 | return nil |
| 506 | } |
| 507 | if active, err := t.researchActive(k.ID); err != nil || active { |
| 508 | return err |
| 509 | } |
| 510 | var held []stepRecord |
| 511 | if err := t.db.Where("task_id = ? AND specialist = ? AND state = ? AND placement = ?", k.ID, wire.SpecialistEngineering, wire.StepQueued, wire.PlacementResearch).Order("idx").Find(&held).Error; err != nil { |
| 512 | return err |
| 513 | } |
| 514 | for i := range held { |
| 515 | if err := t.dispatchStep(k, &held[i]); err != nil { |
| 516 | return err |
| 517 | } |
| 518 | if err := t.saveStep(&held[i], k); err != nil { |
| 519 | return err |
| 520 | } |
| 521 | } |
| 522 | return nil |
| 523 | } |
| 524 | |
| 525 | // dispatchResearch is dispatchStep for a Research step at or past its |
| 526 | // fixed point (never before it). In order, it waits for the answer on |
| 527 | // its sources card; ends done with a gap when nothing is approved to |
| 528 | // read; ends cancelled without a usable grant; is placed on the primary |
| 529 | // only (never a worker), waiting for one when there is none; ends |
| 530 | // cancelled when the primary speaks below wire.ProtocolResearch; waits, |
| 531 | // with no runner, until that primary's site inventory is confirmed |
| 532 | // (research_inventory.go), or ends failed when its hello says it has no |
| 533 | // address at all and none was observed (research_no_inventory); and is |
| 534 | // then sent to the primary with its |
| 535 | // inputs, the confirmed prefixes, the approved specialist's brief at its |
| 536 | // revision and no repository, branch or SHA. The caller saves s. |
| 537 | func (t *txn) dispatchResearch(k *taskRecord, s *stepRecord) error { |
| 538 | if s.Placement == wire.PlacementBoundary || wire.StepTerminal(s.State) { |
| 539 | return nil |
| 540 | } |
| 541 | now := t.now() |
| 542 | end := func(state, reason string) { |
| 543 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince, s.RunnerID = state, reason, true, &now, "", nil, "" |
| 544 | } |
| 545 | if s.SourcesCard != "" { |
| 546 | var c cardRecord |
| 547 | if err := t.db.Where("id = ?", s.SourcesCard).First(&c).Error; err != nil { |
| 548 | return err |
| 549 | } |
| 550 | if c.State == wire.CardOpen { |
| 551 | s.Placement = wire.PlacementSources |
| 552 | return nil |
| 553 | } |
| 554 | } |
| 555 | sources, err := t.researchSources(s.ID, true) |
| 556 | if err != nil { |
| 557 | return err |
| 558 | } |
| 559 | if len(sources) == 0 { |
| 560 | end(wire.StepDone, wire.ReasonResearchNoSources) |
| 561 | s.Summary = "Nothing to read: no page was approved." |
| 562 | return nil |
| 563 | } |
| 564 | sp, g, err := t.researchGrant(k.ProjectID) |
| 565 | if errors.Is(err, ErrNoGrant) { |
| 566 | end(wire.StepCancelled, wire.ReasonResearchNoGrant) |
| 567 | return nil |
| 568 | } else if err != nil { |
| 569 | return err |
| 570 | } |
| 571 | if s.SpecialistID != "" && stepBinding(*s) != bindingOf(sp) { |
| 572 | // Bound at an earlier dispatch to a grant that no longer holds. |
| 573 | end(wire.StepCancelled, wire.ReasonResearchNoGrant) |
| 574 | return nil |
| 575 | } |
| 576 | // The attempt is bound to this grant at this revision, and to the |
| 577 | // specialist's full binding: its start is authorized only while it |
| 578 | // is still the usable one (authorizeResearch). |
| 579 | s.ResearchGrant, s.ResearchGrantRevision = g.ID, sp.Revision |
| 580 | bind(s, sp) |
| 581 | if _, err := t.place(k, s); err != nil { |
| 582 | return err |
| 583 | } |
| 584 | if s.RunnerID == "" { |
| 585 | s.Placement = wire.PlacementWaiting |
| 586 | if s.WaitingSince == nil { |
| 587 | s.WaitingSince = &now |
| 588 | } |
| 589 | return nil |
| 590 | } |
| 591 | rs, err := t.runners(s.Person) |
| 592 | if err != nil { |
| 593 | return err |
| 594 | } |
| 595 | for _, r := range rs { |
| 596 | if r.ID == s.RunnerID && r.Protocol != 0 && r.Protocol < wire.ProtocolResearch { |
| 597 | end(wire.StepCancelled, wire.ReasonResearchUnsupported) |
| 598 | return nil |
| 599 | } |
| 600 | } |
| 601 | // The primary's site inventory: every address detected for it now is |
| 602 | // inside a prefix an owner confirmed, else it waits and an owner is |
| 603 | // asked (once per primary). Not before the protocol check: a primary |
| 604 | // below 13 is never asked for an inventory it could not use. |
| 605 | inventory, detected, ok, err := t.researchInventory(s.RunnerID) |
| 606 | if err != nil { |
| 607 | return err |
| 608 | } |
| 609 | if !ok { |
| 610 | if len(detected) == 0 { |
| 611 | // No address at all, and the primary's hello says so (not just |
| 612 | // a first hello that has not said yet): there is nothing an |
| 613 | // owner could confirm, so waiting would hold Engineering for |
| 614 | // good. It ends failed, which releases Engineering. |
| 615 | said, err := t.helloSaysAddresses(s.RunnerID) |
| 616 | if err != nil { |
| 617 | return err |
| 618 | } |
| 619 | if said { |
| 620 | end(wire.StepFailed, wire.ReasonResearchNoInventory) |
| 621 | return nil |
| 622 | } |
| 623 | } |
| 624 | runner := s.RunnerID |
| 625 | s.Placement, s.RunnerID = wire.PlacementInventory, "" |
| 626 | return t.raiseInventory(k, s, runner, detected) |
| 627 | } |
| 628 | words, err := t.personWords(*k, s.RequestTurn) |
| 629 | if err != nil { |
| 630 | return err |
| 631 | } |
| 632 | if words == nil { |
| 633 | words = []string{} |
| 634 | } |
| 635 | in := &wire.ResearchDispatch{Question: s.Question, PersonWords: words, Sources: []wire.ResearchSource{}, Inventory: append([]string{}, inventory...), SpecialistBrief: sp.Brief, SpecialistRevision: sp.Revision} |
| 636 | for _, src := range sources { |
| 637 | in.Sources = append(in.Sources, wire.ResearchSource{ID: src.SourceID, URL: src.URL, Origin: src.Origin}) |
| 638 | } |
| 639 | cmd := wire.DispatchCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Specialist: wire.SpecialistResearch, Title: k.Title, Brief: k.Brief, Findings: []wire.Finding{}, RunnerID: s.RunnerID, Research: in} |
| 640 | // The scheduler's facts, as for every step. |
| 641 | if t.hk != nil { |
| 642 | s.HousekeepingAttempt = s.Attempt |
| 643 | } |
| 644 | if err := t.schedulerFields(*k, *s, &cmd); err != nil { |
| 645 | return err |
| 646 | } |
| 647 | if err := t.specialistUsed(sp, *k, *s); err != nil { |
| 648 | return err |
| 649 | } |
| 650 | return t.commandTo(s.RunnerID, s.Person, wire.FrameDispatch, cmd) |
| 651 | } |
| 652 | |
| 653 | // researchReport applies a runner's report of a Research step attempt |
| 654 | // (stepReport has checked the runner, the person and the attempt). It |
| 655 | // names no commit, branch or preview; a report that does is refused. |
| 656 | // Done, failed and cancelled end it, and its saveStep releases the |
| 657 | // Engineering it held; done stores its results first (researchResult). |
| 658 | func (t *txn) researchReport(l Lease, k *taskRecord, s *stepRecord, v *wire.StepReport, advanced bool) error { |
| 659 | if v.Pushed || v.BaseSHA != "" || v.CandidateSHA != "" || v.MergeSHA != "" || v.Preview != nil || v.Hosted != nil || v.Change != nil { |
| 660 | return fmt.Errorf("%w: a research report names a commit", ErrRefused) |
| 661 | } |
| 662 | now := t.now() |
| 663 | changed, stored := false, false |
| 664 | if advanced { |
| 665 | s.Attempt, changed = v.Attempt, true |
| 666 | } |
| 667 | if wire.StepTerminal(s.State) { |
| 668 | if v.State == s.State && v.Termination && !s.Terminated { |
| 669 | s.Terminated, changed = true, true |
| 670 | } |
| 671 | } else { |
| 672 | if wire.StepTerminal(v.State) { |
| 673 | if err := t.recordUsage(l, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| 674 | return err |
| 675 | } |
| 676 | } |
| 677 | if v.Family != "" && s.Family != v.Family || v.Account != "" && s.Account != v.Account { |
| 678 | s.Family, s.Account, changed = firstSet(v.Family, s.Family), firstSet(v.Account, s.Account), true |
| 679 | } |
| 680 | // The scheduler's hold, as for every step. |
| 681 | if acceptHold(s, v, t.now()) { |
| 682 | changed = true |
| 683 | } |
| 684 | switch v.State { |
| 685 | case wire.StepRunning: |
| 686 | if s.State == wire.StepQueued && v.Hold == nil { |
| 687 | s.State, changed = wire.StepRunning, true |
| 688 | if s.StartedAt == nil { |
| 689 | s.StartedAt = &now |
| 690 | } |
| 691 | } |
| 692 | default: |
| 693 | s.State, s.Reason, s.Terminated, s.FinishedAt, changed = v.State, v.Reason, v.Termination, &now, true |
| 694 | if s.Reason == "" && v.State != wire.StepDone { |
| 695 | s.Reason = v.State |
| 696 | } |
| 697 | s.Summary, s.LogTail = clipText(v.Summary, wire.MaxStepSummary), clipText(v.LogTail, wire.MaxLogTail) |
| 698 | s.Headline = cleanHeadline(v.Headline) |
| 699 | // Its results are stored before the step is saved, which |
| 700 | // releases Engineering: done keeps its findings (or the gap); |
| 701 | // any other end keeps no file it sent. |
| 702 | if v.State == wire.StepDone { |
| 703 | stored = true |
| 704 | if err := t.researchResult(k, s, v); err != nil { |
| 705 | return err |
| 706 | } |
| 707 | } else { |
| 708 | // Failed or cancelled: no file it sent is kept, but its |
| 709 | // fetch log is (the audit of what was requested). |
| 710 | if err := t.researchFetchLog(k, s, v); err != nil { |
| 711 | return err |
| 712 | } |
| 713 | if err := t.dropResearchFiles(s.ID); err != nil { |
| 714 | return err |
| 715 | } |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | if !changed { |
| 720 | return nil |
| 721 | } |
| 722 | if err := t.saveStep(s, k); err != nil { |
| 723 | return err |
| 724 | } |
| 725 | if stored { |
| 726 | if err := t.db.Model(&researchRecord{}).Where("step_id = ? AND attempt = ?", s.ID, s.Attempt).Update("revision", s.Revision).Error; err != nil { |
| 727 | return err |
| 728 | } |
| 729 | } |
| 730 | // Needs you for a held Research step, as for any step. |
| 731 | if err := t.heldCard(*k, *s); err != nil { |
| 732 | return err |
| 733 | } |
| 734 | return t.advance(k) |
| 735 | } |
| 736 | |
| 737 | // authorizeResearch is a Research attempt's start authorization, checked |
| 738 | // in Authorize's transaction right before its fetch phase (every lease, |
| 739 | // a deferred resume's too): the usable grant now for the task's project |
| 740 | // (researchGrant: active, unrevoked, its approver an owner now) is the |
| 741 | // one the attempt was dispatched under, at that revision, and its full |
| 742 | // binding is that grant's. A step dispatched before bindings (task 16) |
| 743 | // has none: its grant alone is checked, as before. Otherwise the start |
| 744 | // is refused and the step ends cancelled (research_no_grant), which |
| 745 | // releases the Engineering it held. |
| 746 | func (t *txn) authorizeResearch(s *stepRecord) (string, error) { |
| 747 | // Every lease call: a Research step of a job whose person can't have |
| 748 | // web pages read doesn't start, and can't renew its lease (§6.2). |
| 749 | if ok, err := t.researchAllowed(s.TaskID); err != nil || !ok { |
| 750 | return wire.CodeAbilityOff, err |
| 751 | } |
| 752 | k, err := t.loadTask(s.TaskID) |
| 753 | if err != nil { |
| 754 | return "", err |
| 755 | } |
| 756 | sp, g, err := t.researchGrant(k.ProjectID) |
| 757 | if err != nil && !errors.Is(err, ErrNoGrant) { |
| 758 | return "", err |
| 759 | } |
| 760 | if err == nil && s.ResearchGrant != "" && g.ID == s.ResearchGrant && sp.Revision == s.ResearchGrantRevision && (s.SpecialistID == "" || stepBinding(*s) == bindingOf(sp)) { |
| 761 | return "", nil |
| 762 | } |
| 763 | now := t.now() |
| 764 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, wire.ReasonResearchNoGrant, true, &now, "", nil |
| 765 | if err := t.saveStep(s, &k); err != nil { |
| 766 | return "", err |
| 767 | } |
| 768 | return wire.ReasonResearchNoGrant, nil |
| 769 | } |
| 770 | |
| 771 | // retireResearch makes sure a Research attempt never runs: its dispatch, |
| 772 | // if not yet delivered, is retired; a runner that may hold it is asked to |
| 773 | // cancel it (it never got a start authorization: Authorize refuses an |
| 774 | // ended step). |
| 775 | func (t *txn) retireResearch(s stepRecord) error { |
| 776 | if s.RunnerID == "" { |
| 777 | return nil |
| 778 | } |
| 779 | res := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, `%"step_id":"`+s.ID+`"%`).Update("acked_at", t.now()) |
| 780 | if res.Error != nil { |
| 781 | return res.Error |
| 782 | } |
| 783 | if res.RowsAffected != 0 && s.StartedAt == nil { |
| 784 | return nil |
| 785 | } |
| 786 | return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: s.TaskID, StepID: s.ID, Attempt: s.Attempt}) |
| 787 | } |
| 788 | |
| 789 | // withdrawSources resolves a Research step's open sources card. |
| 790 | func (t *txn) withdrawSources(s stepRecord) error { |
| 791 | if s.SourcesCard == "" { |
| 792 | return nil |
| 793 | } |
| 794 | var c cardRecord |
| 795 | if err := t.db.Where("id = ? AND state = ?", s.SourcesCard, wire.CardOpen).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 796 | return nil |
| 797 | } else if err != nil { |
| 798 | return err |
| 799 | } |
| 800 | c.State = wire.CardResolved |
| 801 | return t.saveCard(&c) |
| 802 | } |
| 803 | |
| 804 | // endResearch settles a task's Research when the task ends: a step that |
| 805 | // has not started is cancelled and its card withdrawn; a running one is |
| 806 | // asked to stop, and its runner reports its end. The task is saved by |
| 807 | // the caller (saveTask), so only the steps are written here. |
| 808 | func (t *txn) endResearch(k taskRecord) error { |
| 809 | var rows []stepRecord |
| 810 | if err := t.db.Where("task_id = ? AND specialist = ? AND state IN ?", k.ID, wire.SpecialistResearch, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil { |
| 811 | return err |
| 812 | } |
| 813 | for i := range rows { |
| 814 | s := &rows[i] |
| 815 | if err := t.retireResearch(*s); err != nil { |
| 816 | return err |
| 817 | } |
| 818 | if err := t.withdrawSources(*s); err != nil { |
| 819 | return err |
| 820 | } |
| 821 | if s.StartedAt != nil { |
| 822 | continue |
| 823 | } |
| 824 | now := t.now() |
| 825 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, "cancelled", true, &now, "", nil |
| 826 | if err := t.writeStep(s); err != nil { |
| 827 | return err |
| 828 | } |
| 829 | } |
| 830 | return nil |
| 831 | } |
| 832 | |
| 833 | // fenceResearch settles every Research step placed on a runner that |
| 834 | // connects below wire.ProtocolResearch: it never gets the dispatch, a |
| 835 | // copy it may hold is cancelled, and the step ends research_unsupported, |
| 836 | // which releases the Engineering it held. |
| 837 | func (t *txn) fenceResearch(l Lease) error { |
| 838 | if l.Protocol >= wire.ProtocolResearch { |
| 839 | return nil |
| 840 | } |
| 841 | var rows []stepRecord |
| 842 | if err := t.db.Where("runner_id = ? AND specialist = ? AND state IN ?", l.Runner.RunnerID, wire.SpecialistResearch, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil { |
| 843 | return err |
| 844 | } |
| 845 | for i := range rows { |
| 846 | s := &rows[i] |
| 847 | k, err := t.loadTask(s.TaskID) |
| 848 | if err != nil { |
| 849 | return err |
| 850 | } |
| 851 | if err := t.retireResearch(*s); err != nil { |
| 852 | return err |
| 853 | } |
| 854 | now := t.now() |
| 855 | s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepCancelled, wire.ReasonResearchUnsupported, true, &now |
| 856 | if err := t.saveStep(s, &k); err != nil { |
| 857 | return err |
| 858 | } |
| 859 | } |
| 860 | return nil |
| 861 | } |
| 862 | |
| 863 | // toolResearchOff is the Coordinator's refusal for Research in a job |
| 864 | // whose person can't have web pages read (model-facing, reviewed as code). |
| 865 | const toolResearchOff = "Refused: the person this work is for can't have web pages read. Carry on without Research." |
| 866 | |
| 867 | // researchAllowed reports whether Research may read the web for a task: |
| 868 | // true for a task no hand-off follows, else its person's web. |
| 869 | func (t *txn) researchAllowed(taskID string) (bool, error) { |
| 870 | h, ok, err := t.handoffOf("", taskID) |
| 871 | if err != nil || !ok { |
| 872 | return err == nil, err |
| 873 | } |
| 874 | sw, err := t.switches(h.Person) |
| 875 | if err != nil { |
| 876 | return false, err |
| 877 | } |
| 878 | return sw.Can(wire.AbilityWeb), nil |
| 879 | } |
| 880 | |