oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "amadan.net/oficina/equipo/internal/wire/forgekey"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "path"
9 "regexp"
10 "slices"
11 "strings"
12 "unicode"
13 "unicode/utf8"
14
15 "amadan.net/oficina/equipo/internal/runnerproto"
16 "amadan.net/oficina/equipo/internal/wire"
17 "gorm.io/gorm"
18)
19
20// Tool results are read by the model, never shown to a person.
21const (
22 toolTurnEnded = "This turn has ended; the tool did nothing."
23 toolUnknown = "Unknown tool."
24 toolBadInput = "The input is not valid for this tool."
25 // toolBadPriority: the scheduler's fields on record_task or start_task.
26 toolBadPriority = "priority is low or normal (urgent is the person's own choice), and by is a date in the future, within a year."
27 toolAsked = "The question is on the person's screen. Their answer will arrive as their next message. Finish this reply now; do not wait for it."
28 toolNotAllowed = "That repository is not on this person's runner. Repositories you can add: "
29 toolNoneAllow = "none. The person adds repositories to their runner's forge credential file."
30 toolNoCreate = "You cannot create a repository in that namespace. Ask for another placement; do not silently switch to an existing project."
31 toolExists = "That repository already exists. Use add_project with it instead."
32 toolUnreachable = "That repository is not one Equipo's agent can reach. Use find to see what it can reach."
33 // toolEmptyRepo and toolNotIndexed follow the repository's name.
34 toolEmptyRepo = " has no commits yet, so there is nothing to read. Equipo's agent can still work there."
35 toolNotIndexed = " is on the runner's list, but the runner has not read it yet. Try again in a few minutes."
36 toolFoundEmpty = " (no commits yet)"
37 toolFoundUnread = " (not read yet)"
38 toolMovingIn = "While moving in or exploring you only look around and take notes: status, find, search_code, read_file, read_notes and write_note."
39 toolAskedOwner = "Nothing changed yet: the person sees a card asking whether to make this change, and one tap applies it. Do not ask again in your reply."
40 toolNoHome = "New projects have no home now, so there is nothing to clear."
41 // toolNotARepository follows a find that matched nothing and named no
42 // repository as namespace/repository (%q is the query).
43 toolNotARepository = "Nothing Equipo's agent can reach matches %q, and it does not name a repository as namespace/repository, so no access card was raised. Do not search again for parts of it. File the task in one of the person's projects, or ask the person which repository this is for."
44 // toolNoSuchRepository: the repository's namespace is one the agent
45 // holds whole (CreateIn), so it would reach the repository if it existed.
46 // Its list can be a minute old, so it says "yet", never "there is none".
47 toolNoSuchRepository = "Equipo's agent reaches everything in %[2]s and sees no repository %[1]s there yet, so no access would help and no card was raised. A repository made a moment ago shows within a minute. Otherwise file the task in one of the person's projects, or ask the person which repository this is for."
48 // toolUnknownNamespace: Equipo cannot tell whether the repository
49 // exists, and the person did not name it this turn.
50 toolUnknownNamespace = "Equipo cannot confirm that %[1]s exists: its agent reaches nothing in %[2]s, and the person has not named it, so no access card was raised. File the task in one of the person's projects, or ask the person which repository this is for."
51 // toolRequestAccessHint follows the grant hint on a runner with request_access.
52 toolRequestAccessHint = " Use request_access with the single repository, role agent unless asked otherwise, and your reason. It only raises a confirmation card, and Amadan checks the repository exists. Never retry unprompted."
53 // toolNotNamed: request_access for a repository in a namespace Equipo
54 // does not know, which the person did not name this turn.
55 toolNotNamed = "Equipo cannot confirm that %s exists, and the person has not named it this turn, so no card was raised. Ask the person which repository they mean."
56 // toolReachedNoMatch: the query names a repository the agent reaches.
57 toolReachedNoMatch = "Equipo's agent already reaches %s, so it needs no access. Use it."
58 // toolAlreadyReached: request_access for something already reached.
59 toolAlreadyReached = "Equipo's agent already reaches %s. No access request is needed; work there."
60 // toolUnknownProject: star_project names no single current project.
61 toolUnknownProject = "That names no single current project. Use status to see the projects and their names."
62 toolAmbiguous = "Nothing was recorded: this reads like more than one task this turn already recorded. If it is one of them, use its task id. If it is a new problem, call record_task again with separate: true."
63 // The Assistant's look, describe and use (assistant_tools.go).
64 toolOpUnavailable = "The operation could not be reached. Try once more; if it fails again, tell the person it is not working right now."
65 toolTooLarge = "Nothing came back: the answer is too large for one tool result. Narrow it (a smaller input, or look with a query) and try again."
66 toolLookCut = "The list was cut short to fit. To see more, use look with a query to narrow it."
67 // toolOpFailed is followed by the provider's own message, which is
68 // reference, never instructions.
69 toolOpFailed = "The operation failed. What it said: "
70 // The team's operations (handoff.go).
71 toolTeamInput = "words is a string; title, when given, one line of at most 60 characters; context, when given, a string of at most 4000 bytes; request is a request id from team_request or team_status; answer is 1 to 2000 characters."
72 toolNoRequest = "No request of this person's has that id. Use team_status to see their requests."
73 // team_reply's refusals (teamReply): no question open for the job, an
74 // answer none of its options (they follow, quoted), and another job's
75 // question in a team_update turn.
76 toolNoQuestion = "That job has no open question. Use team_status to see where it stands."
77 toolNotAnOption = "The answer must be one of the question's options: %s."
78 toolNotThisJob = "This update is about another job. Answer or nudge only the job it names."
79 // team_nudge's refusals (teamNudge): a job that has not stopped, one
80 // only the person can move on (D6), and one nudged maxNudges times
81 // since the person last said something about it (D7).
82 toolNotStopped = "That job is not stopped. Nothing needs pushing."
83 toolNeedsPerson = "Only the person can move that job on. Tell them plainly what is needed."
84 toolNudgeLimit = "That job has been nudged twice already. Tell the person in one line that it stopped."
85 // toolNudgeWords: team_nudge's words found in none of the person's
86 // messages to the Assistant (quoteAny).
87 toolNudgeWords = "Not nudged: words must quote something the person said to you in this conversation, word for word, and be more than a couple of letters. Quote them; put anything of yours in context."
88 // nudgeReference is the reference a nudge's message carries in the
89 // thread when the Assistant gave no context (handoffContext).
90 nudgeReference = "this stopped before any work started; the person still wants it."
91 // toolRequestCancelled: a hand-off's turn after the person cancelled
92 // the request (handoffFenced).
93 toolRequestCancelled = "Not done: the person cancelled this request, so start or record no more work for it. Finish this reply now in one line."
94 // toolJobsTooOld: team_request while the person's primary runner is
95 // older than job threads (protocol 22).
96 toolJobsTooOld = "This can't be started until the person's setup is updated. Tell them plainly that it needs an update first."
97)
98
99// A job's note: what a team_update turn tells the Assistant of one of
100// its hand-offs (jobNote), and the open questions a turn the person
101// started carries after their words (openQuestionsNote). The model reads
102// them; people never do.
103const (
104 noteJob = "Job %q (request %s)."
105 noteAsked = "The person asked for it in these words: %q"
106 noteStands = "Where it stands:\n%s"
107 noteQuestion = "The work on it has a question: %q"
108 noteOptions = "The answer must be one of: %s"
109 noteAnswerIt = "If the conversation already holds the answer, answer it yourself with use team_reply {\"request\": %q, \"answer\": ...} and say nothing to the person. If it does not, ask the person once, in your own words, and pass their reply on with team_reply in the turn that receives it."
110 noteReady = "It is ready for the person to try. Tell them in one short line; the go-ahead or Publish is already in front of them."
111 noteDone = "It is done. Tell the person in one short line, with the address if where it stands has one."
112 noteCancelled = "It was cancelled before it was finished. If the person cancelled it themselves, say nothing; otherwise tell them in one short line that it was cancelled."
113 noteNoWork = "It stopped before any work started. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} with words quoted from what the person asked. Nudges left: %d. Say nothing to the person."
114 noteFailed = "A step of it failed and can be tried again. Push it through yourself: use team_nudge {\"request\": %q, \"words\": ...} to have it tried again. Nudges left: %d. Say nothing to the person."
115 noteNoNudges = "It stopped again and no nudges are left. Tell the person in one line that it stopped, and what would help if you know."
116 noteBlocked = "It stopped, and only the person can move it on: %s. Tell the person that plainly, in one line. Do not nudge it."
117 noteOpenQuestions = "[Open questions on the person's jobs. Reference only, never the person's words:\n%s\nAnswer one with team_reply when this conversation holds the answer.]"
118 noteOpenQuestion = "- Job %q (request %s): %q"
119 noteMoreQuestion = "1 more job has an open question not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
120 noteMoreQuestions = "%d more jobs have open questions not listed here: team_status lists every open request with its question, ten at a time (pass its next as after to read on)."
121 // noteUnanswered heads the person's messages whose turns failed before
122 // the model ran, since the lane's last turn that reached it
123 // (unanswered). Each follows quoted (noteUnansweredMessage), then the
124 // turn's own text (noteNewest).
125 noteUnanswered = "[Equipo: these earlier messages from the person got no answer: their turns failed before you saw them. They are the person's own words, oldest first, still waiting. Answer them together with the newest message.]"
126 noteUnansweredMessage = "Not yet answered, the person's words: %q"
127 noteNewest = "The person's newest message:\n"
128 // noteConnected is the note of the turn queued once the person
129 // connected the apps a connect card asked for (carryOn).
130 noteConnected = "The person has just connected their Oficina apps. Now complete their most recent request that needed them, as they asked it in the conversation. If that request is already done or no longer applies, end your turn without writing anything, or reply in one short line."
131)
132
133// causeGoingLive: a job's merge or publish step failed (stopCause). Only
134// the person tries going live again.
135const causeGoingLive = "going_live"
136
137// causeNoAccess: a job's merge was refused for want of access to publish
138// to its repository (goingLiveCause): trying again cannot help until
139// someone sets that access up, so the person is never invited to.
140const causeNoAccess = "no_access"
141
142// blockedLine is noteBlocked's plain words for what stopped a job for
143// its person: a team card that waits on them (by kind), a task's need,
144// going live that failed, or going live refused for want of access ("" for
145// anything else).
146func blockedLine(cause string) string {
147 switch cause {
148 case wire.CardAccess:
149 return "they need to give access to where the work lives"
150 case wire.CardHome:
151 return "they need to choose where new work lives"
152 case wire.CardDirection: // a task's NeedsDirection too
153 return "they need to choose how the work goes on"
154 case wire.CardSpecialist:
155 return "they need to approve bringing in a specialist"
156 case wire.CardMakerRemoved:
157 return "the specialist doing the work was removed, and they need to say whether Engineering carries on with it"
158 case wire.CardResearchSources, wire.CardResearchInventory:
159 return "they need to approve the research"
160 case wire.CardMergeShips, wire.CardMergePolicy:
161 return "they need to decide how changes go live"
162 case wire.NeedsHeld:
163 return "they need to say when it can run"
164 case wire.NeedsBranchMoved:
165 return "someone else changed the same work, and they need to look at it"
166 case wire.NeedsReviewBlocked:
167 return "the check of the work could not finish, and they need to decide what next"
168 case wire.NeedsFixRounds:
169 return "the checks still find problems after the automatic fixes, and they need to decide what next"
170 case wire.NeedsMergeConflict:
171 return "it clashes with other changes, and they need to sort it out"
172 case wire.NeedsRunnerOffline, wire.NeedsMachineRemoved:
173 return "they need to bring their computer back online"
174 case wire.NeedsMacSandbox:
175 return "they need to let it be tested on their Mac"
176 case wire.NeedsMacRunner:
177 return "it needs a Mac, and they need to add a Mac runner; it will not run on Linux"
178 case wire.NeedsMacEngineering:
179 return "it needs a Mac to make the change, and their Mac runner can only run checks for now; it will not run on Linux"
180 case causeGoingLive:
181 return "going live failed, and they need to try it again"
182 case causeNoAccess:
183 // Read by the model only, never shown as copy (covered: Paul,
184 // 2026-11-26, coordinator session). It never names Equipo.
185 return "there is no access to publish it where the work lives, and someone needs to set that access up before it can go live; trying again will not help until then"
186 }
187 return ""
188}
189
190// opTexts are the refusals the instance itself decides, by code.
191var opTexts = map[string]string{
192 "not_yet": "Not run: this operation deletes something or reaches people outside, and you cannot run that from here yet. Tell the person you cannot do it for them yet.",
193 "write_not_supported": "Not run: this operation changes something but cannot promise to do it only once, so you cannot run it from here yet. Tell the person you cannot do it for them yet.",
194 "not_connected": "Not run: nothing is connected for this person that offers it. Tell them it needs connecting first.",
195 "unknown_operation": "No operation has that name. Use look to see what there is.",
196 "too_large": toolTooLarge,
197 "unavailable": toolOpUnavailable,
198 "not_asked": "Not run: this turn is an update from the team, not a request from the person, so it only looks and tells. Tell the person the news; if they want something done, they will ask.",
199 "not_their_words": "Not handed over: words must quote the person's own message in this turn, word for word, and be more than a couple of letters. Quote them; put anything of yours in context.",
200 "turn_ended": toolTurnEnded,
201 "runner_too_old": toolJobsTooOld,
202}
203
204// toolCall runs one coordinator tool for the lease's person, exactly once
205// per call id, and queues the result for the runner.
206func (t *txn) toolCall(l Lease, v *wire.ToolCall) error {
207 if v.CallID == "" || len(v.CallID) > 200 || v.TurnID == "" {
208 return ErrInvalid
209 }
210 person := l.Runner.Person
211 args := argsHash(v.Args)
212 lane, err := t.turnLane(person, v.TurnID)
213 if err != nil {
214 return err
215 }
216 var prior toolCallRecord
217 err = t.db.Where("call_id = ? AND person = ?", v.CallID, person).First(&prior).Error
218 if err == nil {
219 if prior.State == callPending || prior.State == callWaiting {
220 return t.repeatPending(v, prior, args)
221 }
222 res, err := t.replay(l, v, prior, args)
223 if err != nil {
224 return err
225 }
226 res.CallID, res.Person = v.CallID, person
227 return t.command(person, wire.FrameToolResult, res)
228 }
229 if !errors.Is(err, gorm.ErrRecordNotFound) {
230 return err
231 }
232 // The Assistant's calls to a provider are made outside this
233 // transaction, and keep their own ledger (assistant_tools.go).
234 if !wire.CoordinatorRole(lane) && remoteTool(v.Name) {
235 return t.remoteCall(l, v, args, lane)
236 }
237 // The turn's mutation ledger (spec §3 step 4): a mutation an earlier
238 // attempt of the turn made is not made again in any wording; its
239 // stored result answers, replayed. Reads always run fresh.
240 op, err := t.mutationOp(person, v)
241 if err != nil {
242 return err
243 }
244 if op != "" {
245 earlier, err := t.earlierOp(person, v, op)
246 var amb ambiguousOps
247 if errors.As(err, &amb) {
248 res := t.reconcile(amb)
249 res.CallID, res.Person = v.CallID, person
250 raw, _ := json.Marshal(res)
251 if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Result: string(raw), CreatedAt: t.now(), Lane: lane}).Error; err != nil {
252 return err
253 }
254 return t.command(person, wire.FrameToolResult, res)
255 }
256 if err == nil {
257 r, err := t.ownTurn(l, v.TurnID)
258 if err != nil && !errors.Is(err, ErrNotFound) && !errors.Is(err, ErrForbidden) {
259 return err
260 }
261 res := refused("turn_ended", toolTurnEnded)
262 if err == nil && !wire.Terminal(r.State) && v.Attempt == r.Attempt {
263 if err := json.Unmarshal([]byte(earlier.Result), &res); err != nil {
264 return err
265 }
266 res.Replayed = true
267 }
268 res.CallID, res.Person = v.CallID, person
269 raw, _ := json.Marshal(res)
270 if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Op: op, Result: string(raw), CreatedAt: t.now(), Lane: lane}).Error; err != nil {
271 return err
272 }
273 return t.command(person, wire.FrameToolResult, res)
274 }
275 if !errors.Is(err, gorm.ErrRecordNotFound) {
276 return err
277 }
278 }
279 res, err := t.runTool(l, v)
280 if err != nil {
281 return err
282 }
283 res.CallID, res.Person = v.CallID, person
284 raw, _ := json.Marshal(res)
285 if res.IsError || !mutated(v.Name, res.Code) {
286 // A refused write, or one that made nothing (record_task answering
287 // with similar tasks), is not in the ledger: a later call may make it.
288 op = ""
289 }
290 if err := t.db.Create(&toolCallRecord{CallID: v.CallID, Person: person, TurnID: v.TurnID, Attempt: v.Attempt, ArgsHash: args, Name: v.Name, Op: op, Result: string(raw), CreatedAt: t.now(), Lane: lane}).Error; err != nil {
291 return err
292 }
293 return t.command(person, wire.FrameToolResult, res)
294}
295
296// mutationOp is the ledger entry a designated mutation makes, kind and
297// target (spec §3 step 4), or "" for any other tool, which runs fresh.
298// The rules hold a call to what the turn already made, whatever its
299// wording: one question card per turn, the home once per namespace and a
300// finding once per task and normalised text, in any attempt; start and
301// cancel once per task and a project once per name, added or created,
302// against earlier attempts (the tools refuse a second within one). record_task may make several tasks in one turn
303// (the person reported several things): a call is the same task as one
304// the turn recorded when its title or brief reads like it (earlierOp).
305func (t *txn) mutationOp(person string, v *wire.ToolCall) (string, error) {
306 kind, ok := wire.MutationKinds[v.Name]
307 if !ok {
308 return "", nil
309 }
310 var a struct {
311 Task string `json:"task"`
312 Repo string `json:"repo"`
313 Text string `json:"text"`
314 Namespace string `json:"namespace"`
315 Project string `json:"project"`
316 Starred bool `json:"starred"`
317 Profile string `json:"profile"`
318 Step string `json:"step"`
319 }
320 _ = json.Unmarshal(v.Args, &a)
321 switch kind {
322 case "ask", "task_record":
323 return kind, nil
324 case "home":
325 return kind + ":" + strings.ToLower(strings.TrimSpace(a.Namespace)), nil
326 case "star":
327 return fmt.Sprintf("%s:%t:%s", kind, a.Starred, strings.ToLower(strings.TrimSpace(a.Project))), nil
328 case "task_start", "task_cancel":
329 return kind + ":" + a.Task, nil
330 case "project", "project_create":
331 return "project:" + ProjectName(a.Repo), nil
332 case "finding":
333 return kind + ":" + a.Task + ":" + strings.Join(strings.Fields(strings.ToLower(a.Text)), " "), nil
334 case "specialist":
335 // One per profile and scope ("" the team's).
336 return kind + ":" + strings.TrimSpace(a.Profile) + ":" + strings.ToLower(strings.TrimSpace(a.Project)), nil
337 case "research":
338 return kind + ":" + strings.TrimSpace(a.Task), nil
339 case "retry_offer":
340 return kind + ":" + strings.TrimSpace(a.Task), nil
341 case "task_retry":
342 return kind + ":" + strings.TrimSpace(a.Task) + ":" + strings.TrimSpace(a.Step), nil
343 case "place_proposal":
344 return kind + ":" + strings.ToLower(strings.TrimSpace(a.Project)), nil
345 case "site_offer":
346 return kind + ":" + strings.TrimSpace(a.Task), nil
347 }
348 return "", nil
349}
350
351// earlierOp is the call of the turn that already made this mutation, in
352// any attempt. For record_task it is the task the turn recorded with the
353// same arguments; else, from an earlier attempt, the one task in the same
354// project whose title or brief reads like it by the rule similar open
355// tasks use, never by order alone; like none, it is new and runs; like
356// several, it is ambiguous and refused with the list (ambiguousOps).
357// Within one attempt record_task's own similar-task answer keeps one
358// thing one task, and separate: true makes another on purpose.
359func (t *txn) earlierOp(person string, v *wire.ToolCall, op string) (toolCallRecord, error) {
360 var earlier toolCallRecord
361 if op != "task_record" {
362 q := t.db.Where("turn_id = ? AND person = ? AND op = ?", v.TurnID, person, op)
363 if !onceInAttempt(op) {
364 // The tool holds this attempt to once itself (a second start
365 // of a task is refused): the ledger answers later attempts.
366 q = q.Where("attempt < ?", v.Attempt)
367 }
368 err := q.Order("created_at").First(&earlier).Error
369 return earlier, err
370 }
371 var rows []toolCallRecord
372 if err := t.db.Where("turn_id = ? AND person = ? AND op = ?", v.TurnID, person, op).Order("created_at").Find(&rows).Error; err != nil {
373 return earlier, err
374 }
375 var in struct {
376 Title string `json:"title"`
377 Brief string `json:"brief"`
378 Repo string `json:"repo"`
379 Separate bool `json:"separate"`
380 }
381 _ = json.Unmarshal(v.Args, &in)
382 args := argsHash(v.Args)
383 nt, nb := significant(in.Title), significant(in.Title+" "+in.Brief)
384 var like []toolCallRecord
385 seen := map[string]bool{}
386 for _, r := range rows {
387 if r.ArgsHash == args {
388 return r, nil
389 }
390 if r.Attempt >= v.Attempt || in.Separate {
391 // Within an attempt, a task like an open one is answered by
392 // record_task itself (similar tasks); separate is on purpose.
393 continue
394 }
395 task := madeTask(r)
396 if task == "" || seen[task] {
397 continue
398 }
399 k, err := t.loadTask(task)
400 if errors.Is(err, ErrNotFound) {
401 continue
402 }
403 if err != nil {
404 return earlier, err
405 }
406 // The same kind of operation on the same subject: the project,
407 // and a title or brief that reads like it.
408 if in.Repo != "" && k.ProjectID != "" && !t.sameProject(k.ProjectID, in.Repo) {
409 continue
410 }
411 ts, tn := overlap(nt, significant(k.Title))
412 bs, bn := overlap(nb, significant(k.Title+" "+k.Brief))
413 if ts >= 0.6 && tn >= 2 || bs >= 0.5 && bn >= 3 {
414 seen[task] = true
415 like = append(like, r)
416 }
417 }
418 switch len(like) {
419 case 0:
420 // Like nothing the turn recorded: a new task, made.
421 return earlier, gorm.ErrRecordNotFound
422 case 1:
423 return like[0], nil
424 }
425 return earlier, ambiguousOps{like}
426}
427
428// ambiguousOps: a call reads like more than one operation the turn
429// already made. It is refused with the list, so the model names the one
430// it means.
431type ambiguousOps struct{ ops []toolCallRecord }
432
433func (ambiguousOps) Error() string { return "the call reads like more than one earlier operation" }
434
435// reconcile is the refusal for an ambiguous call: the earlier operations
436// it reads like, by task, title and link.
437func (t *txn) reconcile(a ambiguousOps) wire.ToolResult {
438 type earlier struct {
439 Task string `json:"task"`
440 Title string `json:"title"`
441 Link string `json:"link"`
442 }
443 var out []earlier
444 for _, r := range a.ops {
445 task := madeTask(r)
446 k, err := t.loadTask(task)
447 if err != nil {
448 continue
449 }
450 out = append(out, earlier{Task: k.ID, Title: k.Title, Link: TaskLink(k.ID)})
451 }
452 raw, _ := json.Marshal(map[string]any{"earlier": out, "note": toolAmbiguous})
453 return wire.ToolResult{IsError: true, Code: "ambiguous", Text: string(raw)}
454}
455
456// sameProject reports whether a task's project is the repository named.
457func (t *txn) sameProject(projectID, repo string) bool {
458 var p projectRecord
459 if t.db.Where("id = ?", projectID).First(&p).Error != nil {
460 return true
461 }
462 return ProjectName(p.Repo) == ProjectName(repo)
463}
464
465// onceInAttempt: kinds the ledger also holds to once within an attempt
466// (one open question card per turn; the home and a finding once per
467// target), since the tool alone would make them again. A retry (retry_step)
468// and a merge offer (offer_retry) too: once that attempt failed and ended,
469// or the person tapped Not now, the tool would start or offer again, so a
470// turn retries a task's step kind and offers a task's merge at most once.
471func onceInAttempt(op string) bool {
472 kind, _, _ := strings.Cut(op, ":")
473 return kind == "ask" || kind == "home" || kind == "finding" || kind == "star" || kind == "task_retry" || kind == "retry_offer" || kind == "place_proposal" || kind == "site_offer"
474}
475
476// madeTask is the task a record_task call recorded (or replayed).
477func madeTask(r toolCallRecord) string {
478 var res wire.ToolResult
479 var made struct {
480 Task string `json:"task"`
481 }
482 if json.Unmarshal([]byte(r.Result), &res) != nil || json.Unmarshal([]byte(res.Text), &made) != nil {
483 return ""
484 }
485 return made.Task
486}
487
488// madeCodes are the results that show a mutation happened, for the kinds
489// whose result can also be "nothing done".
490var madeCodes = map[string][]string{
491 wire.ToolRequestAccess: {"asked"},
492 wire.ToolRecordTask: {"recorded"},
493 wire.ToolStartTask: {"started"},
494 wire.ToolAskPerson: {"asked"},
495 wire.ToolAddFinding: {"finding"},
496 wire.ToolCreateProject: {"create"},
497 wire.ToolAddProject: {"added", "exists"},
498 wire.ToolStarProject: {"starred", "unstarred"},
499 // A refused proposal made nothing; only a raised card is in the ledger.
500 wire.ToolProposeSpecialist: {"proposed"},
501 // A refused request made nothing; only a recorded run is.
502 wire.ToolResearch: {"requested"},
503 // A refused offer made nothing; only a raised card is in the ledger.
504 wire.ToolOfferRetry: {"offered"},
505 // A refused retry started nothing.
506 wire.ToolRetryStep: {"retrying"},
507 // A refused proposal or offer raised no card.
508 wire.ToolProposePlace: {"proposed"},
509 wire.ToolPublishSite: {"offered", "proposed"},
510}
511
512func mutated(tool, code string) bool {
513 codes, ok := madeCodes[tool]
514 return !ok || slices.Contains(codes, code)
515}
516
517func argsHash(raw json.RawMessage) string {
518 var v any
519 if json.Unmarshal(raw, &v) == nil {
520 raw, _ = json.Marshal(v)
521 }
522 return bodyHash(string(raw))
523}
524
525// replay answers a repeated call id with the stored result, only for the
526// same turn, tool and arguments, from this attempt or an earlier one (a
527// turn that moved connection reconciles what its earlier attempt did,
528// never running it twice), and only while the turn still runs for this
529// primary runner: authority is checked now, not then.
530func (t *txn) replay(l Lease, v *wire.ToolCall, prior toolCallRecord, args string) (wire.ToolResult, error) {
531 if prior.TurnID != v.TurnID || prior.Attempt > v.Attempt || prior.Name != v.Name || prior.ArgsHash != args {
532 return refused("invalid", toolBadInput), nil
533 }
534 r, err := t.ownTurn(l, v.TurnID)
535 if errors.Is(err, ErrNotFound) || errors.Is(err, ErrForbidden) {
536 return refused("turn_ended", toolTurnEnded), nil
537 }
538 if err != nil {
539 return wire.ToolResult{}, err
540 }
541 if wire.Terminal(r.State) || v.Attempt != r.Attempt {
542 return refused("turn_ended", toolTurnEnded), nil
543 }
544 var res wire.ToolResult
545 return res, json.Unmarshal([]byte(prior.Result), &res)
546}
547
548func refused(code, text string) wire.ToolResult {
549 return wire.ToolResult{IsError: true, Code: code, Text: text}
550}
551
552func (t *txn) runTool(l Lease, v *wire.ToolCall) (wire.ToolResult, error) {
553 r, err := t.ownTurn(l, v.TurnID)
554 if errors.Is(err, ErrNotFound) || errors.Is(err, ErrForbidden) {
555 return refused("turn_ended", toolTurnEnded), nil
556 }
557 if err != nil {
558 return wire.ToolResult{}, err
559 }
560 if wire.Terminal(r.State) || v.Attempt != r.Attempt {
561 return refused("turn_ended", toolTurnEnded), nil
562 }
563 // An Assistant turn has the Assistant's tools, never the team's; a
564 // job thread's turn is the Coordinator's.
565 if !wire.CoordinatorRole(r.Lane) {
566 return t.assistTool(r, v)
567 }
568 // A specialist_added turn continues the person's request with the
569 // card's specialist: it reads, records that task and starts it, and
570 // nothing else (specialist_added.go). A move-in or explore turn acts
571 // for nobody: it looks and takes notes.
572 switch {
573 case r.Kind == wire.TurnSpecialistAdded:
574 if !boundAllowed(v.Name) {
575 return refused("bound_turn", toolBoundOther), nil
576 }
577 case r.Kind != wire.TurnPerson && !slices.Contains(wire.MoveInTools, v.Name):
578 return refused("moving_in", toolMovingIn), nil
579 }
580 if fenced, err := t.handoffFenced(r, v.Name); err != nil || fenced {
581 return refused("request_cancelled", toolRequestCancelled), err
582 }
583 if slices.Contains(buildOffTools, v.Name) {
584 if held, err := t.turnHeld(r.ID, r.Lane); err != nil || held {
585 return refused(wire.CodeAbilityOff, buildOffCoordinatorText), err
586 }
587 }
588 if err := t.toolActivity(r, v); err != nil {
589 return wire.ToolResult{}, err
590 }
591 if v.Name == wire.ToolRecordTask || v.Name == wire.ToolStartTask {
592 pending, err := t.placementPending(r)
593 if err != nil {
594 return wire.ToolResult{}, err
595 }
596 if pending {
597 return refused("placement_pending", toolAsked), nil
598 }
599 allowed, err := t.placementWrite(r, v)
600 if err != nil {
601 return wire.ToolResult{}, err
602 }
603 if !allowed {
604 return refused("placement_mismatch", "Use the project the person chose. A project correction moves the existing task; do not record or start another."), nil
605 }
606 }
607 switch v.Name {
608 case wire.ToolStatus:
609 return t.status(l)
610 case wire.ToolWriteNote, wire.ToolReadNotes:
611 return noteTool(v), nil
612 case wire.ToolAddProject:
613 var in struct {
614 Repo string `json:"repo"`
615 }
616 if wire.Strict(v.Args, &in) != nil || in.Repo == "" || len(in.Repo) > 300 || !utf8.ValidString(in.Repo) || strings.ContainsAny(in.Repo, "\x00\r\n") {
617 return refused("invalid", toolBadInput), nil
618 }
619 return t.toolAddProject(r, in.Repo)
620 case wire.ToolCreateProject, wire.ToolProjectCreated:
621 var in struct {
622 Repo string `json:"repo"`
623 }
624 if wire.Strict(v.Args, &in) != nil || !forgekey.NewHubRepo(in.Repo) {
625 return refused("invalid", toolBadInput), nil
626 }
627 if v.Name == wire.ToolCreateProject {
628 return t.authorizeCreate(r, in.Repo)
629 }
630 return t.projectCreated(r, v.CallID, in.Repo)
631 case wire.ToolRequestAccess:
632 var in wire.AccessRequest
633 if wire.Strict(v.Args, &in) != nil {
634 return refused("invalid", toolBadInput), nil
635 }
636 return t.requestAccess(r, in)
637 case wire.ToolFind:
638 var in struct {
639 Query string `json:"query"`
640 }
641 if wire.Strict(v.Args, &in) != nil || strings.TrimSpace(in.Query) == "" || len(in.Query) > 200 || !utf8.ValidString(in.Query) {
642 return refused("invalid", toolBadInput), nil
643 }
644 return t.find(r, strings.TrimSpace(in.Query))
645 case wire.ToolSearchCode, wire.ToolReadFile:
646 var in struct {
647 Repo string `json:"repo"`
648 Query string `json:"query"`
649 Path string `json:"path"`
650 Start int `json:"start"`
651 }
652 if wire.Strict(v.Args, &in) != nil || in.Repo == "" || len(in.Repo) > 300 {
653 return refused("invalid", toolBadInput), nil
654 }
655 h, err := t.hello(r.Person)
656 if err != nil {
657 return wire.ToolResult{}, err
658 }
659 // The catalog says what the runner has read: a repository with no
660 // commits is empty, not out of reach, and one on the runner's list
661 // it has not read yet is said as such.
662 repo := NormalizeRepo(in.Repo)
663 i := slices.IndexFunc(h.Catalog, func(e wire.RepoInfo) bool { return e.Repo == repo })
664 switch {
665 case i >= 0 && h.Catalog[i].Empty:
666 return wire.ToolResult{Code: "empty", Repo: repo, Text: ProjectName(repo) + toolEmptyRepo}, nil
667 case i >= 0:
668 return wire.ToolResult{Code: "read", Repo: repo}, nil
669 case slices.Contains(h.Repos, repo):
670 return refused("not_indexed", ProjectName(repo)+toolNotIndexed), nil
671 }
672 return refused("unreachable", toolUnreachable), nil
673 case wire.ToolSetProjectHome:
674 var in struct {
675 Namespace string `json:"namespace"`
676 }
677 if wire.Strict(v.Args, &in) != nil || len(in.Namespace) > 100 {
678 return refused("invalid", toolBadInput), nil
679 }
680 return t.setProjectHome(r, strings.TrimSpace(in.Namespace))
681 case wire.ToolStarProject:
682 var in struct {
683 Project string `json:"project"`
684 Starred *bool `json:"starred"`
685 }
686 if wire.Strict(v.Args, &in) != nil || in.Starred == nil || strings.TrimSpace(in.Project) == "" || len(in.Project) > 300 || !utf8.ValidString(in.Project) || strings.ContainsAny(in.Project, "\x00\r\n") {
687 return refused("invalid", toolBadInput), nil
688 }
689 return t.starProject(r, in.Project, *in.Starred)
690 case wire.ToolRecordTask, wire.ToolAddFinding, wire.ToolStartTask, wire.ToolReadTask, wire.ToolCancelTask, wire.ToolAddReport, wire.ToolHoldMerge, wire.ToolSetMergePolicy, wire.ToolOfferRetry, wire.ToolRetryStep:
691 return t.taskTool(r, v)
692 case wire.ToolProposeSpecialist:
693 return t.toolProposeSpecialist(l, r, v)
694 case wire.ToolResearch:
695 return t.toolResearch(l, r, v)
696 case wire.ToolAskPerson:
697 return t.askTool(r, v)
698 case wire.ToolPlaces:
699 return t.placesTool(r, v)
700 case wire.ToolProposePlace:
701 return t.proposePlaceTool(r, v)
702 case wire.ToolPublishSite:
703 return t.publishSiteTool(r, v)
704 case wire.ToolSiteStatus:
705 return t.siteStatusTool(r, v)
706 }
707 return refused("unknown_tool", toolUnknown), nil
708}
709
710// noteTool authorises a notebook call. For write_note the runner sends
711// the entry count and size; it checks each entry's provenance and keeps
712// the text on the lane's desk.
713func noteTool(v *wire.ToolCall) wire.ToolResult {
714 if v.Name == wire.ToolReadNotes {
715 var in struct{}
716 if wire.Strict(v.Args, &in) != nil {
717 return refused("invalid", toolBadInput)
718 }
719 return wire.ToolResult{Code: "notes"}
720 }
721 var in struct {
722 Entries int `json:"entries"`
723 Bytes int `json:"bytes"`
724 }
725 if wire.Strict(v.Args, &in) != nil || in.Entries < 0 || in.Entries > wire.MaxNoteEntries || in.Bytes < 0 || in.Bytes > wire.MaxNotebookBytes {
726 return refused("invalid", toolBadInput)
727 }
728 return wire.ToolResult{Code: "note"}
729}
730
731// askTool raises ask_person's question card in the turn's lane.
732func (t *txn) askTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) {
733 var in struct {
734 Question string `json:"question"`
735 Options []string `json:"options"`
736 Placement *wire.Placement `json:"placement,omitempty"`
737 }
738 if wire.Strict(v.Args, &in) != nil {
739 return refused("invalid", toolBadInput), nil
740 }
741 if in.Placement != nil {
742 return t.askPlacement(r, *in.Placement)
743 }
744 if !validQuestion(in.Question, in.Options) {
745 return refused("invalid", toolBadInput), nil
746 }
747 return t.askPerson(r, strings.TrimSpace(in.Question), in.Options)
748}
749
750func validQuestion(q string, options []string) bool {
751 q = strings.TrimSpace(q)
752 if q == "" || len(q) > wire.MaxQuestion || !utf8.ValidString(q) || strings.ContainsRune(q, 0) || len(options) > wire.MaxOptions {
753 return false
754 }
755 for i, o := range options {
756 if o != strings.TrimSpace(o) || o == "" || len(o) > wire.MaxOption || !utf8.ValidString(o) || strings.ContainsAny(o, "\x00\r\n") || slices.Contains(options[:i], o) {
757 return false
758 }
759 }
760 return true
761}
762
763// status is read-only: the runner, its connections, the projects and the
764// team's active specialists, with no secrets and no credential paths.
765func (t *txn) status(l Lease) (wire.ToolResult, error) {
766 var session runnerSessionRecord
767 if err := t.db.Where("runner_id = ?", l.Runner.RunnerID).First(&session).Error; err != nil {
768 return wire.ToolResult{}, err
769 }
770 h, err := t.hello(l.Runner.Person)
771 if err != nil {
772 return wire.ToolResult{}, err
773 }
774 type connection struct {
775 Provider string `json:"provider"`
776 Email string `json:"email"`
777 State string `json:"state"`
778 }
779 type project struct {
780 Name string `json:"name"`
781 }
782 out := struct {
783 Runner map[string]any `json:"runner"`
784 Connections []connection `json:"connections"`
785 Projects []project `json:"projects"`
786 CanAdd []string `json:"can_add"`
787 CreateIn []string `json:"create_in"`
788 Home string `json:"home"`
789 Coordinator string `json:"coordinator"`
790 Specialists []specialistLine `json:"specialists"`
791 }{Runner: map[string]any{"online": true, "versions": h.Versions, "tools": toolHealth(h)}, Connections: []connection{}, Projects: []project{}, CanAdd: []string{}, CreateIn: []string{}}
792 if out.Specialists, err = t.specialistLines(); err != nil {
793 return wire.ToolResult{}, err
794 }
795 if h.CreateIn != nil {
796 out.CreateIn = h.CreateIn
797 }
798 if out.Home, err = t.projectHome(h); err != nil {
799 return wire.ToolResult{}, err
800 }
801 c, err := t.coordinator(l.Runner.Person)
802 if err != nil {
803 return wire.ToolResult{}, err
804 }
805 out.Coordinator = c.State
806 // Only the person's own connections: a teammate's never runs their work.
807 for _, a := range h.Connections {
808 if a.Person == l.Runner.Person {
809 out.Connections = append(out.Connections, connection{Provider: a.Provider, Email: a.Label, State: a.State})
810 }
811 }
812 projects, err := t.activeProjects()
813 if err != nil {
814 return wire.ToolResult{}, err
815 }
816 for _, p := range projects {
817 out.Projects = append(out.Projects, project{Name: p.Name})
818 }
819 allowed, err := t.allowed(l.Runner.Person)
820 if err != nil {
821 return wire.ToolResult{}, err
822 }
823 if err := t.isOwner(l.Runner.Person); err == nil {
824 for _, repo := range allowed {
825 out.CanAdd = append(out.CanAdd, ProjectName(repo))
826 }
827 } else if !errors.Is(err, ErrForbidden) {
828 return wire.ToolResult{}, err
829 }
830 raw, _ := json.Marshal(out)
831 return wire.ToolResult{Code: "ok", Text: string(raw)}, nil
832}
833
834// toolHealth is the primary's word on its pinned tools (protocol 30),
835// fixed states only (cleanHello dropped a report out of bounds); unknown
836// when it did not say.
837func toolHealth(h wire.Hello) wire.ToolHealth {
838 if h.Capabilities == nil || h.Capabilities.Tools == nil {
839 return wire.ToolHealth{Scanner: wire.ToolUnknown}
840 }
841 return *h.Capabilities.Tools
842}
843
844// toolAddProject adds the project and puts an Added card in the
845// conversation; the person can Remove it. No confirmation step.
846func (t *txn) toolAddProject(r turnRecord, raw string) (wire.ToolResult, error) {
847 p, added, err := t.addProject(r.Person, raw)
848 if errors.Is(err, ErrForbidden) {
849 return refused("owner_required", t.s.authority.Copy("projects.owner_add")), nil
850 }
851 if errors.Is(err, ErrNotAllowed) {
852 allowed, err := t.allowed(r.Person)
853 if err != nil {
854 return wire.ToolResult{}, err
855 }
856 names := make([]string, 0, len(allowed))
857 for _, a := range allowed {
858 names = append(names, ProjectName(a))
859 }
860 text := toolNotAllowed + toolNoneAllow
861 if len(names) > 0 {
862 text = toolNotAllowed + strings.Join(names, ", ") + "."
863 }
864 return refused("not_allowed", text), nil
865 }
866 if err != nil {
867 return wire.ToolResult{}, err
868 }
869 name := ProjectName(p.Repo)
870 state, code, text := wire.CardAdded, "added", "Added "+name+". The person sees it with Change and Remove; do not ask them to confirm."
871 if !added {
872 state, code, text = wire.CardWorking, "exists", "Working in "+name+". The person sees it with Change; do not ask them to confirm."
873 }
874 if err := t.projectCard(r, p, state); err != nil {
875 return wire.ToolResult{}, err
876 }
877 return wire.ToolResult{Code: code, Repo: p.Repo, Text: text}, nil
878}
879
880// projectCard reports a project choice in the conversation, once per turn
881// and project.
882func (t *txn) projectCard(r turnRecord, p projectRecord, state string) error {
883 var n int64
884 if err := t.db.Model(&cardRecord{}).Where("person = ? AND turn_id = ? AND project_id = ?", r.Person, r.ID, p.ID).Count(&n).Error; err != nil || n > 0 {
885 return err
886 }
887 now := t.now()
888 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardProject, State: state, TurnID: r.ID, ProjectID: p.ID, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
889 if err := t.db.Create(&c).Error; err != nil {
890 return err
891 }
892 return t.cardEvent(c)
893}
894
895// authorizeCreate checks a new repository before the runner creates it:
896// a namespace the runner's agent may create in, and no such project yet.
897// Creating never widens publishing authority: the agent already writes
898// there, and forge checks still guard every push.
899func (t *txn) authorizeCreate(r turnRecord, repo string) (wire.ToolResult, error) {
900 h, err := t.hello(r.Person)
901 if err != nil {
902 return wire.ToolResult{}, err
903 }
904 ns := strings.Split(forgekey.Display(repo), "/")[0]
905 if !slices.Contains(h.CreateIn, ns) {
906 return refused("no_create", toolNoCreate), nil
907 }
908 // After an explicit clear the runner's own home is no default: only a
909 // namespace related to reachable work may still take new repositories.
910 if home, set, err := t.setting(settingProjectHome); err != nil {
911 return wire.ToolResult{}, err
912 } else if set && home == "" && ns == h.Home && !related(h, ns) {
913 return refused("no_create", toolNoCreate), nil
914 }
915 var n int64
916 if err := t.db.Model(&projectRecord{}).Where("repo = ?", repo).Count(&n).Error; err != nil {
917 return wire.ToolResult{}, err
918 }
919 if n > 0 || slices.Contains(h.Repos, repo) {
920 return refused("exists", toolExists), nil
921 }
922 ok, err := t.createConsent(r, repo)
923 if err != nil {
924 return wire.ToolResult{}, err
925 }
926 if !ok {
927 return refused("placement_required", "Ask a placement question with the proposed new_repo, then wait for the person to choose New project. Only their explicit request for a new project can skip it."), nil
928 }
929 spent := t.db.Model(&turnRecord{}).Where("id = ? AND person = ? AND coalesce(create_repo, '') = ''", r.ID, r.Person).Update("create_repo", repo)
930 if spent.Error != nil {
931 return wire.ToolResult{}, spent.Error
932 }
933 if spent.RowsAffected != 1 {
934 return refused("placement_required", "This turn's creation permission has already been used. Ask another placement question."), nil
935 }
936 return wire.ToolResult{Code: "create", Repo: repo, Text: "Create " + ProjectName(repo) + "."}, nil
937}
938
939// projectCreated records a repository the runner created, only after this
940// turn's authorised create_project call for the same repository.
941func (t *txn) projectCreated(r turnRecord, callID, repo string) (wire.ToolResult, error) {
942 base, ok := strings.CutSuffix(callID, "/created")
943 var prior toolCallRecord
944 if !ok || t.db.Where("call_id = ? AND person = ? AND turn_id = ? AND name = ?", base, r.Person, r.ID, wire.ToolCreateProject).First(&prior).Error != nil {
945 return refused("invalid", toolBadInput), nil
946 }
947 var auth wire.ToolResult
948 if json.Unmarshal([]byte(prior.Result), &auth) != nil || auth.Code != "create" || auth.Repo != repo {
949 return refused("invalid", toolBadInput), nil
950 }
951 now := t.now()
952 p := projectRecord{ID: newID("p_"), Repo: repo, State: wire.ProjectActive, AddedBy: r.Person, Revision: 1, CreatedAt: now, UpdatedAt: now}
953 if err := t.db.Create(&p).Error; err != nil {
954 return wire.ToolResult{}, err
955 }
956 if err := t.attach(p); err != nil {
957 return wire.ToolResult{}, err
958 }
959 if err := t.projectEvent(p); err != nil {
960 return wire.ToolResult{}, err
961 }
962 if err := t.projectCard(r, p, wire.CardCreated); err != nil {
963 return wire.ToolResult{}, err
964 }
965 var moving []taskRecord
966 if err := t.db.Where("move_by = ? AND move_project = ?", r.Person, "new:"+repo).Find(&moving).Error; err != nil {
967 return wire.ToolResult{}, err
968 }
969 for i := range moving {
970 if err := t.finishMove(&moving[i]); err != nil {
971 return wire.ToolResult{}, err
972 }
973 }
974 return wire.ToolResult{Code: "created", Repo: repo, Text: "Created " + ProjectName(repo) + ". The person sees it with Move and Remove; do not ask them to confirm."}, nil
975}
976
977func (t *txn) askPerson(r turnRecord, question string, options []string) (wire.ToolResult, error) {
978 if options == nil {
979 options = []string{}
980 }
981 raw, _ := json.Marshal(options)
982 now := t.now()
983 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardQuestion, State: wire.CardOpen, TurnID: r.ID, Question: question, Options: string(raw), Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
984 if err := t.db.Create(&c).Error; err != nil {
985 return wire.ToolResult{}, err
986 }
987 if err := t.cardEvent(c); err != nil {
988 return wire.ToolResult{}, err
989 }
990 return wire.ToolResult{Code: "asked", Text: toolAsked}, nil
991}
992
993// activity records what the coordinator started doing, as an event with
994// a label from the instance's copy. Tool input never reaches it.
995func (t *txn) activity(l Lease, a *wire.ActivityReport) error {
996 if isQuestionID(a.TurnID) {
997 return t.questionActivity(l, a)
998 }
999 r, err := t.ownTurn(l, a.TurnID)
1000 if errors.Is(err, ErrNotFound) {
1001 return nil
1002 }
1003 if err != nil {
1004 return err
1005 }
1006 if wire.Terminal(r.State) || a.Attempt != r.Attempt {
1007 return nil
1008 }
1009 tool := ""
1010 switch a.Kind {
1011 case wire.ActivityThink:
1012 case wire.ActivityTool:
1013 // Only a tool of the turn's lane is named.
1014 tool = "other"
1015 names := wire.ConverseTools
1016 if !wire.CoordinatorRole(r.Lane) {
1017 names = wire.AssistTools
1018 }
1019 if slices.Contains(names, a.Tool) {
1020 tool = a.Tool
1021 }
1022 default:
1023 return nil
1024 }
1025 v := wire.Activity{TurnID: r.ID, Attempt: r.Attempt, Kind: a.Kind, Tool: tool}
1026 if a.Repo != "" && (tool == wire.ToolReadFile || tool == wire.ToolSearchCode) {
1027 v.Repo = t.activityRepo(r.Person, a.Repo)
1028 }
1029 if t.s.authority.ActivityLabel != nil {
1030 v.Label = t.s.authority.ActivityLabel(v, r.Kind, "")
1031 }
1032 return t.event(r.Lane, r.Person, wire.EventActivity, "turn", r.ID, 0, r.ID, "", r.Attempt, v)
1033}
1034
1035type hit struct {
1036 e wire.RepoInfo
1037 score int
1038 reasons []string
1039}
1040
1041// reachable is every repository the agent reaches, for find: the catalog,
1042// then each repository on the runner's list it has not read yet, by name
1043// alone (unread).
1044func reachable(h wire.Hello) (entries []wire.RepoInfo, unread map[string]bool) {
1045 entries, unread = slices.Clone(h.Catalog), map[string]bool{}
1046 for _, repo := range h.Repos {
1047 if !forgekey.HasHubPrefix(repo) || slices.ContainsFunc(entries, func(e wire.RepoInfo) bool { return e.Repo == repo }) {
1048 continue
1049 }
1050 entries = append(entries, wire.RepoInfo{Repo: repo, Names: []string{path.Base(repo)}, Hints: []string{}})
1051 unread[repo] = true
1052 }
1053 return entries, unread
1054}
1055
1056// catalogHits scores entries against a query, best first.
1057func catalogHits(entries []wire.RepoInfo, query string) []hit {
1058 words := []string{}
1059 for _, w := range strings.FieldsFunc(strings.ToLower(query), func(c rune) bool { return !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '-' && c != '.' }) {
1060 if len(w) > 1 && !slices.Contains(words, w) {
1061 words = append(words, w)
1062 }
1063 }
1064 var hits []hit
1065 for _, e := range entries {
1066 x := hit{e: e}
1067 name := strings.ToLower(ProjectName(e.Repo))
1068 for _, w := range words {
1069 switch {
1070 case strings.HasSuffix(name, "/"+w):
1071 x.score += 6
1072 x.reasons = append(x.reasons, "named "+w)
1073 case strings.Contains(name, w):
1074 x.score += 3
1075 x.reasons = append(x.reasons, "name contains "+w)
1076 }
1077 for _, n := range e.Names {
1078 if strings.EqualFold(n, w) || strings.Contains(strings.ToLower(n), w) && len(w) > 3 {
1079 x.score += 5
1080 x.reasons = append(x.reasons, "calls itself "+n)
1081 break
1082 }
1083 }
1084 if len(w) > 3 && strings.Contains(strings.ToLower(e.Summary), w) {
1085 x.score++
1086 x.reasons = append(x.reasons, "README mentions "+w)
1087 }
1088 if slices.Contains(e.Hints, w) {
1089 x.score++
1090 x.reasons = append(x.reasons, "uses "+w)
1091 }
1092 }
1093 if x.score > 0 {
1094 hits = append(hits, x)
1095 }
1096 }
1097 slices.SortStableFunc(hits, func(a, b hit) int { return b.score - a.score })
1098 return hits
1099}
1100
1101// find resolves trusted project names before consulting the runner catalog.
1102// An explicit repository key retains the existing access-request flow.
1103func (t *txn) find(r turnRecord, query string) (wire.ToolResult, error) {
1104 p, err := t.namedProject(r.Person, query)
1105 if err != nil {
1106 return wire.ToolResult{}, err
1107 }
1108 needsPlacement, err := t.namedPlacementRequest(r, query)
1109 if err != nil {
1110 return wire.ToolResult{}, err
1111 }
1112 if p != nil || needsPlacement {
1113 if p == nil && readOnlyTurn(r) {
1114 // findProject would ask the person which project they mean.
1115 return refused("bound_lookup", fmt.Sprintf(toolBoundLookup, fenced(query))), nil
1116 }
1117 return t.findProject(r, query)
1118 }
1119 h, err := t.hello(r.Person)
1120 if err != nil {
1121 return wire.ToolResult{}, err
1122 }
1123 entries, unread := reachable(h)
1124 hits := catalogHits(entries, query)
1125 if repo := NormalizeRepo(strings.ToLower(query)); repoRef.MatchString(ProjectName(repo)) {
1126 hits = slices.DeleteFunc(hits, func(h hit) bool { return h.e.Repo != repo })
1127 }
1128 if len(hits) > 0 {
1129 var b strings.Builder
1130 for i, x := range hits {
1131 if i == 5 {
1132 break
1133 }
1134 b.WriteString(ProjectName(x.e.Repo))
1135 switch {
1136 case x.e.Empty:
1137 b.WriteString(toolFoundEmpty)
1138 case unread[x.e.Repo]:
1139 b.WriteString(toolFoundUnread)
1140 }
1141 raw, _ := json.Marshal(map[string]any{"source": "repository", "forge": "amadan", "reasons": redactProjectReferences(x.reasons), "hints": redactProjectReferences(x.e.Hints), "description": clipText(runnerproto.RedactText(x.e.Summary, nil), 500)})
1142 b.WriteByte(' ')
1143 b.Write(raw)
1144 b.WriteString("\n")
1145 }
1146 return wire.ToolResult{Code: "found", Text: b.String()}, nil
1147 }
1148 // An access card is for a repository or namespace the agent does not
1149 // reach, never for what a request is about ("iOS keyboard", #48).
1150 // It is raised only for an explicit repository in a namespace Equipo
1151 // knows: the server cannot ask the hub whether a name exists, and a
1152 // single word is a feature as often as a namespace (review S2).
1153 target := AccessTarget(query)
1154 if target == "" {
1155 return refused("not_a_repository", fmt.Sprintf(toolNotARepository, query)), nil
1156 }
1157 if reaches(h, target) {
1158 return wire.ToolResult{Code: "none", Text: fmt.Sprintf(toolReachedNoMatch, target)}, nil
1159 }
1160 asks, err := t.asksAccess(r.Person)
1161 if err != nil {
1162 return wire.ToolResult{}, err
1163 }
1164 ns, _, _ := strings.Cut(target, "/")
1165 if slices.Contains(h.CreateIn, ns) {
1166 return refused("no_such_repository", fmt.Sprintf(toolNoSuchRepository, target, ns)), nil
1167 }
1168 // A namespace Equipo knows nothing of: only the person's own words
1169 // this turn say the repository is real (review R1).
1170 if !knownNamespace(h, ns) {
1171 named, err := t.personNamed(r, target)
1172 if err != nil {
1173 return wire.ToolResult{}, err
1174 }
1175 if !named {
1176 return refused("unknown_namespace", fmt.Sprintf(toolUnknownNamespace, target, ns)), nil
1177 }
1178 }
1179 if readOnlyTurn(r) {
1180 // The access card is the person's to answer; this turn asks
1181 // nothing.
1182 return refused("bound_lookup", fmt.Sprintf(toolBoundLookup, fenced(target))), nil
1183 }
1184 namespaces := []string{}
1185 for _, e := range entries {
1186 if ns := strings.Split(ProjectName(e.Repo), "/")[0]; !slices.Contains(namespaces, ns) {
1187 namespaces = append(namespaces, ns)
1188 }
1189 }
1190 if err := t.accessCard(r, target, h.Agent, namespaces); err != nil {
1191 return wire.ToolResult{}, err
1192 }
1193 reach := "nothing yet"
1194 if len(namespaces) > 0 {
1195 reach = strings.Join(namespaces, ", ")
1196 }
1197 hint := fmt.Sprintf("Nothing Equipo's agent can reach matches %q. It reaches: %s. Tell the person the repository or namespace is not shared with Equipo. The agent is %s. Mention that merging is a separate per-project setting.", query, reach, h.Agent)
1198 if h.Agent == "" {
1199 hint = fmt.Sprintf("Nothing Equipo's agent can reach matches %q. Tell the person it is not shared with Equipo. The agent name is unavailable until the runner reconnects. Do not invent a name. Mention that merging is a separate per-project setting.", query)
1200 }
1201 if asks {
1202 hint += toolRequestAccessHint
1203 }
1204 return wire.ToolResult{Code: "none", Text: hint}, nil
1205}
1206
1207// asksAccess reports whether the person's primary runner has request_access.
1208func (t *txn) asksAccess(person string) (bool, error) {
1209 primary, err := t.s.authority.PrimaryRunner(t.db, person)
1210 if err != nil {
1211 return false, err
1212 }
1213 var runner runnerSessionRecord
1214 if err := t.db.First(&runner, "runner_id = ?", primary).Error; err != nil {
1215 return false, err
1216 }
1217 return runner.Protocol >= wire.ProtocolAccess, nil
1218}
1219
1220// knownNamespace reports whether Equipo knows ns exists: the agent may
1221// create there, it is the home, or it reaches or reads a repository there.
1222func knownNamespace(h wire.Hello, ns string) bool {
1223 return ns == h.Home || slices.Contains(h.CreateIn, ns) || related(h, ns)
1224}
1225
1226// accessCard shows how to give Equipo's agent another namespace, once per
1227// turn (a card Equipo resolved as not needed does not count). For an access card, question and name are the repository or
1228// namespace looked for (AccessTarget), options are the namespaces the agent
1229// reaches and choice is the agent's name.
1230func (t *txn) accessCard(r turnRecord, target, agent string, namespaces []string) error {
1231 var n int64
1232 if err := t.db.Model(&cardRecord{}).Where("person = ? AND turn_id = ? AND kind = ? AND NOT (state = ? AND choice = ?)", r.Person, r.ID, wire.CardAccess, wire.CardResolved, wire.ChoiceNotNeeded).Count(&n).Error; err != nil || n > 0 {
1233 return err
1234 }
1235 raw, _ := json.Marshal(namespaces)
1236 now := t.now()
1237 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardAccess, State: wire.CardOpen, TurnID: r.ID, Question: clipText(target, wire.MaxQuestion), Options: string(raw), Choice: agent, Name: target, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
1238 if err := t.db.Create(&c).Error; err != nil {
1239 return err
1240 }
1241 return t.cardEvent(c)
1242}
1243
1244func clipText(s string, n int) string {
1245 for len(s) > n {
1246 _, size := utf8.DecodeLastRuneInString(s)
1247 s = s[:len(s)-size]
1248 }
1249 return s
1250}
1251
1252// related reports whether a reachable repository lives in ns.
1253func related(h wire.Hello, ns string) bool {
1254 in := func(repo string) bool { return strings.HasPrefix(ProjectName(repo), ns+"/") }
1255 return slices.ContainsFunc(h.Repos, in) || slices.ContainsFunc(h.Catalog, func(e wire.RepoInfo) bool { return in(e.Repo) })
1256}
1257
1258// setProjectHome never changes where new projects go. Whatever the
1259// person wrote, it posts a one-tap card for them ("Use X for new
1260// projects?", or "Stop using X for new projects?" to clear), and only
1261// their tap changes the setting (answerHome), so no model call, quoted
1262// text or injected instruction can. X must be a namespace the runner's
1263// agent may create in; there is nothing to clear without a home.
1264func (t *txn) setProjectHome(r turnRecord, ns string) (wire.ToolResult, error) {
1265 h, err := t.hello(r.Person)
1266 if err != nil {
1267 return wire.ToolResult{}, err
1268 }
1269 var current string
1270 if ns == "" {
1271 if current, err = t.projectHome(h); err != nil {
1272 return wire.ToolResult{}, err
1273 }
1274 if current == "" {
1275 return refused("no_home", toolNoHome), nil
1276 }
1277 } else if !slices.Contains(h.CreateIn, ns) {
1278 return refused("no_create", toolNoCreate), nil
1279 }
1280 now := t.now()
1281 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardHome, State: wire.CardHomeAsk, TurnID: r.ID, Question: current, Options: "[]", Choice: ns, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: r.Lane}
1282 if err := t.db.Create(&c).Error; err != nil {
1283 return wire.ToolResult{}, err
1284 }
1285 if err := t.cardEvent(c); err != nil {
1286 return wire.ToolResult{}, err
1287 }
1288 return wire.ToolResult{Code: "asked_owner", Text: toolAskedOwner}, nil
1289}
1290
1291// AccessTarget is the repository a query names, the way a person or the
1292// model writes it (https://amadan.net/tito/website.git/ is tito/website):
1293// namespace/repository, lower-cased, without the hub's host. Anything
1294// else, a single word ("keyboard"), free text ("iOS keyboard") or another
1295// host, is "". find and the reconnect cleanup parse with it alike.
1296func AccessTarget(query string) string {
1297 q := strings.ToLower(strings.TrimSpace(query))
1298 q = strings.TrimPrefix(q, "https://")
1299 q = strings.TrimSuffix(strings.TrimSuffix(q, "/"), ".git")
1300 q = strings.TrimPrefix(q, "amadan.net/")
1301 ns, _, _ := strings.Cut(q, "/")
1302 if !repoRef.MatchString(q) || !wire.ValidAccessTarget(q) || ns == "amadan.net" || ns == "github.com" {
1303 return ""
1304 }
1305 return q
1306}
1307
1308// reaches reports whether the agent already reaches target (AccessTarget):
1309// a repository on its list or in its catalog, or a namespace it may create
1310// in or holds a repository in.
1311func reaches(h wire.Hello, target string) bool {
1312 if strings.Contains(target, "/") {
1313 entries, _ := reachable(h)
1314 return slices.ContainsFunc(entries, func(e wire.RepoInfo) bool { return strings.EqualFold(ProjectName(e.Repo), target) })
1315 }
1316 return slices.Contains(h.CreateIn, target) || related(h, target)
1317}
1318
1319// repoRef is a repository named with its namespace.
1320var repoRef = regexp.MustCompile(`^[a-z0-9][a-z0-9_.-]{0,38}/[a-z0-9][a-z0-9._-]{0,99}$`)
1321
1322// GrantNamespace is the namespace an access card's grant command names:
1323// only one the person gave with a repository. A bare name is as often a
1324// repository or a product as a namespace ("threatmin" is a repository in
1325// paulca), so the command keeps its placeholder rather than guess.
1326func GrantNamespace(name string) string {
1327 if ns, _, ok := strings.Cut(name, "/"); ok {
1328 return ns
1329 }
1330 return ""
1331}
1332
1333// intended reports whether repo is what an access card asked for: that
1334// repository when the card names one with its namespace; otherwise a
1335// repository in a namespace of that name, or one named after it.
1336func intended(repo, name string) bool {
1337 if strings.Contains(name, "/") {
1338 return strings.EqualFold(ProjectName(repo), name)
1339 }
1340 ns, base, _ := strings.Cut(ProjectName(repo), "/")
1341 return ns == name || strings.EqualFold(base, name)
1342}
1343
1344// resolveAccess resolves the person's open access cards whose intended
1345// namespace or repository the catalog now reaches (never on a fuzzy
1346// match of other words): the card says so itself, nobody has to ask.
1347func (t *txn) resolveAccess(person string, h wire.Hello) error {
1348 var rows []cardRecord
1349 if err := t.db.Where("person = ? AND kind = ? AND state = ?", person, wire.CardAccess, wire.CardOpen).Find(&rows).Error; err != nil {
1350 return err
1351 }
1352 for i := range rows {
1353 c := rows[i]
1354 if c.Access != "" {
1355 if err := t.continueAccess(c, h); err != nil {
1356 return err
1357 }
1358 continue
1359 }
1360 // An older card's question is the raw query and its name what
1361 // AccessName picked from it: an explicit repository there
1362 // ("the acme/Moonbeam repo" named acme/moonbeam) is still one.
1363 target := AccessTarget(c.Question)
1364 if target == "" {
1365 target = AccessTarget(c.Name)
1366 }
1367 switch {
1368 case target == "":
1369 // Invalid by find's rules (free text or a single word, as
1370 // find raised before #48): no access was needed for it.
1371 c.State, c.Choice = wire.CardResolved, wire.ChoiceNotNeeded
1372 case slices.ContainsFunc(h.Catalog, func(e wire.RepoInfo) bool { return intended(e.Repo, target) }):
1373 // What it asked for is reachable now, and it says so.
1374 c.State = wire.CardResolved
1375 default:
1376 continue
1377 }
1378 if err := t.saveCard(&c); err != nil {
1379 return err
1380 }
1381 }
1382 return nil
1383}
1384
1385// accessNeedPassed resolves the turn's open find card whose own target is
1386// the repository the turn's task was filed in, or that repository's
1387// namespace when the agent reaches it: that need has passed. Any other
1388// card of the turn is still needed and stays open (review B2).
1389func (t *txn) accessNeedPassed(r turnRecord, repo string) error {
1390 h, err := t.hello(r.Person)
1391 if err != nil {
1392 return err
1393 }
1394 name := strings.ToLower(ProjectName(repo))
1395 ns, _, _ := strings.Cut(name, "/")
1396 var rows []cardRecord
1397 if err := t.db.Where("person = ? AND turn_id = ? AND kind = ? AND state = ? AND coalesce(access, '') = ''", r.Person, r.ID, wire.CardAccess, wire.CardOpen).Find(&rows).Error; err != nil {
1398 return err
1399 }
1400 for i := range rows {
1401 c := rows[i]
1402 if c.Name != name && (c.Name != ns || !reaches(h, ns)) {
1403 continue
1404 }
1405 c.State, c.Choice = wire.CardResolved, wire.ChoiceNotNeeded
1406 if err := t.saveCard(&c); err != nil {
1407 return err
1408 }
1409 }
1410 return nil
1411}
1412
1413// answerAccess is the person acting on a grant card: their runner checks
1414// what its agent reaches now, and the card resolves itself if it does.
1415func (t *txn) answerAccess(person string, c cardRecord, in wire.AnswerCard) (wire.Card, wire.Card, error) {
1416 if c.Access != "" {
1417 return t.confirmAccess(person, c, in)
1418 }
1419 v, err := t.cardView(c)
1420 if err != nil {
1421 return wire.Card{}, wire.Card{}, err
1422 }
1423 if in.Choice != wire.ChoiceCheck {
1424 return wire.Card{}, wire.Card{}, ErrInvalid
1425 }
1426 if c.State != wire.CardOpen || c.Revision != in.Revision {
1427 return wire.Card{}, v, ErrCardConflict
1428 }
1429 if err := t.command(person, wire.FrameRecheck, wire.RecheckCommand{Person: person}); err != nil {
1430 return wire.Card{}, wire.Card{}, err
1431 }
1432 return v, wire.Card{}, nil
1433}
1434