| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "slices" |
| 8 | "strings" |
| 9 | "time" |
| 10 | "unicode/utf8" |
| 11 | |
| 12 | "gorm.io/gorm" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | ) |
| 16 | |
| 17 | // The coordinator's place tools (protocol 31). places and site_status are |
| 18 | // read-only and answer quoted data; propose_place raises a place card and |
| 19 | // publish_site a publish card (or a place card first), and only the |
| 20 | // person's tap confirms or publishes. No tool takes a console, account or |
| 21 | // app: a place is chosen by a candidate id code derived. |
| 22 | |
| 23 | // What the model reads back; people never see these. |
| 24 | const ( |
| 25 | toolPlaceProposed = "Proposed: a card in the person's conversation asks where the site goes. Only an owner's tap confirms it and nothing is published or created until they also tap Publish. Tell them in one line; do not ask again." |
| 26 | toolPlaceExists = "This project's site already has a confirmed place; call places to see it. Use publish_site to offer publishing." |
| 27 | toolPlaceOpen = "The person already has a card about where this site goes. Wait for their tap." |
| 28 | toolPlaceUnknown = "That candidate is not one this person's runner can reach now; call places for the current candidates." |
| 29 | toolPlaceNoProject = "No such project; call status for the projects." |
| 30 | toolSiteOffered = "Offered: a card in the person's conversation asks whether to publish the merged site to the place it names. Only their tap publishes. Tell them in one line, and never say it is live until the task shows its address." |
| 31 | toolSiteProposed = "There is no confirmed place for this site yet: a card asks the person where it goes first, and the publish card follows their choice. Tell them in one line." |
| 32 | toolSiteNotWebsite = "Not offered: this task is not a website Equipo merged with an approved Review of its site config (release/preview.json). read_task shows where it stands." |
| 33 | toolSiteNothingDue = "Not offered: a publish card is already open for this task, or its merged commit is being published or was published. read_task shows where it stands." |
| 34 | toolSiteMissing = "Not offered: it cannot be published now (missing: %s). The person was told why in their conversation; say it in one line in plain words and do not ask again." |
| 35 | toolSiteTargetLater = "Only target site is available; temporary sites are not places yet." |
| 36 | toolPlaceNotOwner = "Only a team owner can choose where a site goes or publish one. Tell the person in one line." |
| 37 | ) |
| 38 | |
| 39 | // placesTool is places: for one project (or every project with a site |
| 40 | // binding), its site place and app, the newest publish's outcome, the |
| 41 | // primary's mode or what is missing, and, while unplaced, the candidates |
| 42 | // propose_place takes. Quoted data: names are repository and CARLOS text. |
| 43 | func (t *txn) placesTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 44 | var in struct { |
| 45 | Project string `json:"project"` |
| 46 | } |
| 47 | if wire.Strict(v.Args, &in) != nil || len(in.Project) > 300 || !utf8.ValidString(in.Project) { |
| 48 | return refused("invalid", toolBadInput), nil |
| 49 | } |
| 50 | var projects []projectRecord |
| 51 | if in.Project != "" { |
| 52 | pr, ok, err := t.placeProject(r.Person, in.Project) |
| 53 | if err != nil || !ok { |
| 54 | return refused("not_found", toolPlaceNoProject), err |
| 55 | } |
| 56 | projects = append(projects, pr) |
| 57 | } else { |
| 58 | var ids []string |
| 59 | if err := t.db.Model(&projectPlaceRecord{}).Where("kind = ?", wire.PlaceSite).Pluck("project_id", &ids).Error; err != nil { |
| 60 | return wire.ToolResult{}, err |
| 61 | } |
| 62 | if err := t.db.Where("id IN ?", ids).Order("repo").Find(&projects).Error; err != nil { |
| 63 | return wire.ToolResult{}, err |
| 64 | } |
| 65 | } |
| 66 | out := []siteLine{} |
| 67 | for _, pr := range projects { |
| 68 | line, err := t.siteLine(r.Person, pr, in.Project != "") |
| 69 | if err != nil { |
| 70 | return wire.ToolResult{}, err |
| 71 | } |
| 72 | out = append(out, line) |
| 73 | } |
| 74 | raw, _ := json.Marshal(map[string]any{"sites": out}) |
| 75 | return wire.ToolResult{Code: "places", Text: "Equipo's places (CARLOS and repository names quoted as data): " + wire.QuotedData(string(raw))}, nil |
| 76 | } |
| 77 | |
| 78 | // siteLine is one project's site as places and site_status say it. |
| 79 | type siteLine struct { |
| 80 | Project string `json:"project"` |
| 81 | Place string `json:"place,omitempty"` |
| 82 | Console string `json:"console,omitempty"` |
| 83 | Account string `json:"account,omitempty"` |
| 84 | App string `json:"app,omitempty"` |
| 85 | Mode string `json:"can,omitempty"` |
| 86 | Missing string `json:"missing,omitempty"` |
| 87 | Deploy string `json:"deploy_key,omitempty"` |
| 88 | LostKeys []string `json:"lost_keys,omitempty"` |
| 89 | LastPublish *sitePublish `json:"last_publish,omitempty"` |
| 90 | Candidates []wire.PlaceCandidate `json:"candidates,omitempty"` |
| 91 | } |
| 92 | |
| 93 | type sitePublish struct { |
| 94 | Task string `json:"task"` |
| 95 | SHA string `json:"sha"` |
| 96 | State string `json:"state"` |
| 97 | URL string `json:"url,omitempty"` |
| 98 | At *time.Time `json:"at,omitempty"` |
| 99 | Version string `json:"version,omitempty"` |
| 100 | } |
| 101 | |
| 102 | func (t *txn) siteLine(person string, pr projectRecord, candidates bool) (siteLine, error) { |
| 103 | line := siteLine{Project: ProjectName(pr.Repo)} |
| 104 | b, p, err := t.siteBinding(pr.ID) |
| 105 | if err != nil { |
| 106 | return line, err |
| 107 | } |
| 108 | if b != nil { |
| 109 | line.App = b.App |
| 110 | } |
| 111 | if p == nil || p.State != wire.PlaceConfirmed { |
| 112 | line.Missing = missingNoPlace |
| 113 | if candidates { |
| 114 | h, err := t.hello(person) |
| 115 | if err != nil { |
| 116 | return line, err |
| 117 | } |
| 118 | line.Candidates = siteCandidates(h, pr.Repo) |
| 119 | } |
| 120 | return line, nil |
| 121 | } |
| 122 | line.Place, line.Console, line.Account = p.ID, wire.ConsoleLabel(p.Console), p.AccountName |
| 123 | if line.Mode, line.Missing, err = t.siteMode(person, *b, *p); err != nil { |
| 124 | return line, err |
| 125 | } |
| 126 | line.Deploy = "none" |
| 127 | if r, _, err := t.siteReach(person); err != nil { |
| 128 | return line, err |
| 129 | } else if r != nil { |
| 130 | for _, d := range r.Deploys { |
| 131 | if d.Console != p.Console || d.Account != p.AccountSqid || d.App != b.App { |
| 132 | continue |
| 133 | } |
| 134 | switch { |
| 135 | case d.Lost: |
| 136 | line.LostKeys = append(line.LostKeys, d.Name) |
| 137 | default: |
| 138 | line.Deploy = "held" |
| 139 | } |
| 140 | } |
| 141 | if line.Deploy == "none" && len(line.LostKeys) > 0 { |
| 142 | line.Deploy = "lost" |
| 143 | } |
| 144 | } |
| 145 | last, err := t.lastPublish(pr.ID) |
| 146 | line.LastPublish = last |
| 147 | return line, err |
| 148 | } |
| 149 | |
| 150 | // lastPublish is the newest publish step of the project's tasks. |
| 151 | func (t *txn) lastPublish(projectID string) (*sitePublish, error) { |
| 152 | var s stepRecord |
| 153 | err := t.db.Joins("JOIN chat_tasks ON chat_tasks.id = chat_steps.task_id").Where("chat_tasks.project_id = ? AND chat_steps.specialist = ?", projectID, wire.SpecialistPublish).Order("chat_steps.created_at DESC").Limit(1).Find(&s).Error |
| 154 | if err != nil || s.ID == "" { |
| 155 | return nil, err |
| 156 | } |
| 157 | out := &sitePublish{Task: s.TaskID, SHA: short(s.CandidateSHA), State: s.State, At: s.FinishedAt} |
| 158 | if p := decodePublish(s.Publish); p != nil { |
| 159 | if p.Outcome != "" { |
| 160 | out.State = p.Outcome |
| 161 | } |
| 162 | out.URL, out.Version = p.URL, p.Version |
| 163 | } |
| 164 | return out, nil |
| 165 | } |
| 166 | |
| 167 | // placeProject is the project a place tool names, by the one exact |
| 168 | // resolver (namedProject) or its repository. |
| 169 | func (t *txn) placeProject(person, name string) (projectRecord, bool, error) { |
| 170 | p, err := t.namedProject(person, name) |
| 171 | if err != nil || p != nil { |
| 172 | if p == nil { |
| 173 | return projectRecord{}, false, err |
| 174 | } |
| 175 | return *p, true, nil |
| 176 | } |
| 177 | var pr projectRecord |
| 178 | err = t.db.Where("repo = ? AND state = ?", NormalizeRepo(name), wire.ProjectActive).Limit(1).Find(&pr).Error |
| 179 | return pr, err == nil && pr.ID != "", err |
| 180 | } |
| 181 | |
| 182 | // proposePlaceTool is propose_place: an owner's coordinator raises a |
| 183 | // place card for a project's site, with a candidate places listed first. |
| 184 | func (t *txn) proposePlaceTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 185 | var in struct { |
| 186 | Kind string `json:"kind"` |
| 187 | Project string `json:"project"` |
| 188 | Candidate string `json:"candidate"` |
| 189 | } |
| 190 | if wire.Strict(v.Args, &in) != nil || in.Kind != wire.PlaceSite || in.Project == "" || len(in.Project) > 300 || !wire.ValidCandidateID(in.Candidate) { |
| 191 | return refused("invalid", toolBadInput), nil |
| 192 | } |
| 193 | if err := t.isOwner(r.Person); err != nil { |
| 194 | if errors.Is(err, ErrForbidden) { |
| 195 | return refused("not_owner", toolPlaceNotOwner), nil |
| 196 | } |
| 197 | return wire.ToolResult{}, err |
| 198 | } |
| 199 | pr, ok, err := t.placeProject(r.Person, in.Project) |
| 200 | if err != nil || !ok { |
| 201 | return refused("not_found", toolPlaceNoProject), err |
| 202 | } |
| 203 | if _, p, err := t.siteBinding(pr.ID); err != nil || p != nil { |
| 204 | return refused("already_placed", toolPlaceExists), err |
| 205 | } |
| 206 | // A card the person cannot see where they asked, or one older than |
| 207 | // this request, gives way to a fresh one: it never strands them. |
| 208 | open, err := t.openPlaceCards(pr.ID) |
| 209 | if err != nil { |
| 210 | return wire.ToolResult{}, err |
| 211 | } |
| 212 | since := r.CreatedAt |
| 213 | stands, stale := standingCard(open, r.Person, r.Lane, &since) |
| 214 | if stands != nil { |
| 215 | return refused("already_proposed", toolPlaceOpen+cardAt(*stands)), nil |
| 216 | } |
| 217 | task := "" |
| 218 | for _, c := range stale { |
| 219 | if task == "" && c.Person == r.Person && c.TaskID != "" { |
| 220 | task = c.TaskID |
| 221 | } |
| 222 | } |
| 223 | h, err := t.hello(r.Person) |
| 224 | if err != nil { |
| 225 | return wire.ToolResult{}, err |
| 226 | } |
| 227 | found := false |
| 228 | for _, c := range siteCandidates(h, pr.Repo) { |
| 229 | found = found || c.ID == in.Candidate |
| 230 | } |
| 231 | if !found { |
| 232 | return refused("unknown_candidate", toolPlaceUnknown), nil |
| 233 | } |
| 234 | c, ok, err := t.raisePlace(r.Person, r.Lane, r.ID, pr, task, in.Candidate) |
| 235 | if err != nil || !ok { |
| 236 | return refused("unknown_candidate", toolPlaceUnknown), err |
| 237 | } |
| 238 | if err := t.supersedePlaces("coordinator:"+r.Person, stale, c); err != nil { |
| 239 | return wire.ToolResult{}, err |
| 240 | } |
| 241 | return wire.ToolResult{Code: "proposed", Text: toolPlaceProposed + cardAt(c)}, nil |
| 242 | } |
| 243 | |
| 244 | // publishSiteTool is publish_site: for the person's own merged website |
| 245 | // task, the publish card (or the place card first), as offerPublish would |
| 246 | // have raised it; also for an older merged task that was never asked. |
| 247 | func (t *txn) publishSiteTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 248 | var in struct { |
| 249 | Task string `json:"task"` |
| 250 | Target string `json:"target"` |
| 251 | } |
| 252 | if wire.Strict(v.Args, &in) != nil || strings.TrimSpace(in.Task) == "" || len(in.Task) > 100 { |
| 253 | return refused("invalid", toolBadInput), nil |
| 254 | } |
| 255 | if in.Target != "" && in.Target != wire.PlaceSite { |
| 256 | return refused("target_later", toolSiteTargetLater), nil |
| 257 | } |
| 258 | k, err := t.loadTask(strings.TrimSpace(in.Task)) |
| 259 | if errors.Is(err, ErrNotFound) { |
| 260 | return refused("not_found", toolNoTask), nil |
| 261 | } |
| 262 | if err != nil { |
| 263 | return wire.ToolResult{}, err |
| 264 | } |
| 265 | if k.Creator != r.Person { |
| 266 | return refused("not_yours", toolNotYours), nil |
| 267 | } |
| 268 | if err := t.isOwner(r.Person); err != nil { |
| 269 | if errors.Is(err, ErrForbidden) { |
| 270 | return refused("not_owner", toolPlaceNotOwner), nil |
| 271 | } |
| 272 | return wire.ToolResult{}, err |
| 273 | } |
| 274 | steps, err := t.steps(k.ID) |
| 275 | if err != nil { |
| 276 | return wire.ToolResult{}, err |
| 277 | } |
| 278 | if k.Stage != wire.StageDone || !mergedWebsite(k, steps) { |
| 279 | return refused("not_website", toolSiteNotWebsite), nil |
| 280 | } |
| 281 | // The person's own request: its cards go where they asked, and a place |
| 282 | // card they cannot see there gives way to a fresh one. |
| 283 | since := r.CreatedAt |
| 284 | o, err := t.offerSite(&k, "", "coordinator:"+r.Person, siteAsk{lane: r.Lane, since: &since}) |
| 285 | switch { |
| 286 | case err != nil: |
| 287 | return wire.ToolResult{}, err |
| 288 | case o.did == siteOffered: |
| 289 | return wire.ToolResult{Code: "offered", Text: toolSiteOffered + cardAt(o.card)}, nil |
| 290 | case o.did == siteProposed: |
| 291 | return wire.ToolResult{Code: "proposed", Text: toolSiteProposed + cardAt(o.card)}, nil |
| 292 | case o.missing != "": |
| 293 | return refused("not_ready", strings.Replace(toolSiteMissing, "%s", o.missing, 1)), nil |
| 294 | case o.card.Kind == wire.CardPlace: |
| 295 | return refused("already_proposed", toolPlaceOpen+cardAt(o.card)), nil |
| 296 | case o.card.ID != "": |
| 297 | return refused("nothing_due", toolSiteNothingDue+cardAt(o.card)), nil |
| 298 | } |
| 299 | return refused("nothing_due", toolSiteNothingDue), nil |
| 300 | } |
| 301 | |
| 302 | // siteStatusTool is site_status: what Equipo recorded about one project's |
| 303 | // site. It does not read CARLOS: the live edge version and domains come |
| 304 | // later. |
| 305 | func (t *txn) siteStatusTool(r turnRecord, v *wire.ToolCall) (wire.ToolResult, error) { |
| 306 | var in struct { |
| 307 | Project string `json:"project"` |
| 308 | } |
| 309 | if wire.Strict(v.Args, &in) != nil || strings.TrimSpace(in.Project) == "" || len(in.Project) > 300 { |
| 310 | return refused("invalid", toolBadInput), nil |
| 311 | } |
| 312 | pr, ok, err := t.placeProject(r.Person, in.Project) |
| 313 | if err != nil || !ok { |
| 314 | return refused("not_found", toolPlaceNoProject), err |
| 315 | } |
| 316 | line, err := t.siteLine(r.Person, pr, false) |
| 317 | if err != nil { |
| 318 | return wire.ToolResult{}, err |
| 319 | } |
| 320 | raw, _ := json.Marshal(line) |
| 321 | return wire.ToolResult{Code: "site", Text: "What Equipo recorded about this site (quoted as data; it has not asked CARLOS): " + wire.QuotedData(string(raw))}, nil |
| 322 | } |
| 323 | |
| 324 | // SitePlace is one project's site as the Places page shows it, state |
| 325 | // first. Pending: a place card is open for it; Unplaced: an app kept from |
| 326 | // before places, with no place. |
| 327 | type SitePlace struct { |
| 328 | Project, App, Console, Account string |
| 329 | Pending, Unplaced bool |
| 330 | State, URL string |
| 331 | At *time.Time |
| 332 | // Deploy is the runner's key for it: held or "" (none yet), by |
| 333 | // DeployName; Lost names every key asked for and not held, each of |
| 334 | // which may be live on CARLOS. |
| 335 | Deploy, DeployName string |
| 336 | Lost []string |
| 337 | } |
| 338 | |
| 339 | // Places is the Places page: every project with a site binding or an |
| 340 | // open place card, for any current member (team records: the same for |
| 341 | // everyone). The runner's reach read is the person's own primary's. |
| 342 | func (s *Store) Places(ctx context.Context, person string) (out []SitePlace, err error) { |
| 343 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 344 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 345 | return err |
| 346 | } |
| 347 | t := &txn{s: s, db: tx} |
| 348 | var bindings []projectPlaceRecord |
| 349 | if err := tx.Where("kind = ?", wire.PlaceSite).Find(&bindings).Error; err != nil { |
| 350 | return err |
| 351 | } |
| 352 | var pending []string |
| 353 | if err := tx.Model(&cardRecord{}).Where("kind = ? AND state = ?", wire.CardPlace, wire.CardOpen).Distinct().Pluck("project_id", &pending).Error; err != nil { |
| 354 | return err |
| 355 | } |
| 356 | seen := map[string]bool{} |
| 357 | ids := append([]string{}, pending...) |
| 358 | for _, b := range bindings { |
| 359 | ids = append(ids, b.ProjectID) |
| 360 | } |
| 361 | var projects []projectRecord |
| 362 | if err := tx.Where("id IN ?", ids).Order("repo").Find(&projects).Error; err != nil { |
| 363 | return err |
| 364 | } |
| 365 | for _, pr := range projects { |
| 366 | if seen[pr.ID] { |
| 367 | continue |
| 368 | } |
| 369 | seen[pr.ID] = true |
| 370 | line := SitePlace{Project: projectTitle(pr), Pending: slices.Contains(pending, pr.ID)} |
| 371 | b, p, err := t.siteBinding(pr.ID) |
| 372 | if err != nil { |
| 373 | return err |
| 374 | } |
| 375 | if b != nil { |
| 376 | line.App = b.App |
| 377 | } |
| 378 | if p == nil { |
| 379 | line.Unplaced = b != nil |
| 380 | out = append(out, line) |
| 381 | continue |
| 382 | } |
| 383 | line.Console, line.Account = wire.ConsoleLabel(p.Console), p.AccountName |
| 384 | if last, err := t.lastPublish(pr.ID); err != nil { |
| 385 | return err |
| 386 | } else if last != nil { |
| 387 | line.State, line.URL, line.At = last.State, last.URL, last.At |
| 388 | } |
| 389 | if r, _, err := t.siteReach(person); err != nil { |
| 390 | return err |
| 391 | } else if r != nil { |
| 392 | for _, d := range r.Deploys { |
| 393 | if d.Console != p.Console || d.Account != p.AccountSqid || d.App != b.App { |
| 394 | continue |
| 395 | } |
| 396 | if d.Lost { |
| 397 | line.Lost = append(line.Lost, d.Name) |
| 398 | } else { |
| 399 | line.Deploy, line.DeployName = "held", d.Name |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | out = append(out, line) |
| 404 | } |
| 405 | return nil |
| 406 | }) |
| 407 | return out, err |
| 408 | } |
| 409 | |