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 "encoding/json"
5 "errors"
6 "fmt"
7 "regexp"
8 "slices"
9 "strings"
10 "unicode"
11 "unicode/utf8"
12
13 "amadan.net/oficina/equipo/internal/runnerproto"
14 "amadan.net/oficina/equipo/internal/wire"
15 "gorm.io/gorm"
16)
17
18// askNamedProject builds every option from current project records. Neither
19// repository text nor the model supplies an option label or its destination.
20func (t *txn) askNamedProject(r turnRecord, name string, star *bool) (wire.ToolResult, error) {
21 if repo, err := t.turnProject(r); err != nil {
22 return wire.ToolResult{}, err
23 } else if repo != "" && star == nil {
24 return wire.ToolResult{Code: "found", Repo: repo, Text: fmt.Sprintf(t.s.authority.Copy("projects.selected"), repo)}, nil
25 }
26 if pending, err := t.placementPending(r); err != nil {
27 return wire.ToolResult{}, err
28 } else if pending {
29 return wire.ToolResult{Code: "asked", Text: toolAsked}, nil
30 }
31 rows, err := t.orderedProjects(r.Person)
32 if err != nil {
33 return wire.ToolResult{}, err
34 }
35 allowed, err := t.allowed(r.Person)
36 if err != nil {
37 return wire.ToolResult{}, err
38 }
39 data := placementData{Labels: []string{}, Star: star}
40 // This is a suggestion only. The person's card answer confirms or edits it.
41 name = strings.TrimSpace(name)
42 if eligibleProjectName(name) {
43 data.RequestedName = name
44 }
45 stars, err := t.stars(r.Person)
46 if err != nil {
47 return wire.ToolResult{}, err
48 }
49 // Stable ordering retains recent activity for otherwise equal candidates.
50 slices.SortStableFunc(rows, func(a, b projectRecord) int {
51 if stars[a.ID].Starred != stars[b.ID].Starred {
52 if stars[a.ID].Starred {
53 return -1
54 }
55 return 1
56 }
57 score := func(p projectRecord) int {
58 if strings.Contains(strings.ToLower(ProjectName(p.Repo)), strings.ToLower(name)) {
59 return 1
60 }
61 return 0
62 }
63 return score(b) - score(a)
64 })
65 more := false
66 for _, p := range rows {
67 if !slices.Contains(allowed, p.Repo) {
68 continue
69 }
70 label := ProjectName(p.Repo)
71 if len(data.Repos) >= wire.MaxOptions-1 || len(label) > wire.MaxOption {
72 more = true
73 continue
74 }
75 data.Repos = append(data.Repos, p.Repo)
76 data.Labels = append(data.Labels, label)
77 }
78 if more {
79 data.OtherLabel = t.s.authority.Copy("projects.other")
80 data.Labels = append(data.Labels, data.OtherLabel)
81 }
82
83 if len(data.Repos) == 0 && !more {
84 return refused("unknown_project", toolUnknownProject), nil
85 }
86 if err := t.placementRunner(r.Person); err != nil {
87 return refused("unknown_project", toolUnknownProject), nil
88 }
89 raw, _ := json.Marshal(data)
90 options, _ := json.Marshal(data.Labels)
91 now := t.now()
92 c := cardRecord{ID: newID("c_"), Person: r.Person, Kind: wire.CardQuestion, State: wire.CardOpen, TurnID: r.ID, Lane: r.Lane, Question: t.s.authority.Copy("placement.question"), Options: string(options), Placement: string(raw), Revision: 1, CreatedAt: now, UpdatedAt: now}
93 if err := t.db.Create(&c).Error; err != nil {
94 return wire.ToolResult{}, err
95 }
96 if err := t.s.authority.Audit(t.db, r.Person, "placement.asked", c.ID); err != nil {
97 return wire.ToolResult{}, err
98 }
99 if err := t.cardEvent(c); err != nil {
100 return wire.ToolResult{}, err
101 }
102 return wire.ToolResult{Code: "asked", Text: toolAsked}, nil
103}
104
105// Recognise a name in the person's placement language before comparing it
106// with the model's query. Mere occurrence of a feature phrase is insufficient.
107func eligibleProjectName(name string) bool {
108 name = strings.TrimSpace(name)
109 if utf8.RuneCountInString(name) < 3 || !validProjectText(name, 120) {
110 return false
111 }
112 lower := strings.ToLower(name)
113 if slices.Contains([]string{"a", "an", "and", "are", "as", "at", "be", "but", "by", "do", "does", "for", "from", "had", "has", "have", "here", "if", "in", "into", "is", "it", "its", "of", "on", "or", "our", "that", "the", "their", "them", "then", "there", "these", "they", "this", "those", "to", "too", "us", "use", "was", "we", "were", "what", "when", "where", "which", "who", "why", "will", "with", "you", "your", "yours", "app", "project", "repository", "new", "old"}, lower) {
114 return false
115 }
116 if slices.Contains([]string{"swipe back", "edge swipe", "swipe gesture", "back button", "dark mode", "sign in", "log in"}, lower) {
117 return false
118 }
119 return true
120}
121
122func containsProjectPhrase(text, name string) bool {
123 if !eligibleProjectName(name) {
124 return false
125 }
126 for _, prefix := range []string{"in ", "for ", "project ", "repository ", "called "} {
127 for _, quote := range []string{"", "\"", "'"} {
128 pattern := regexp.MustCompile(`(?i)(?:^|[^\pL\pN])` + prefix + quote + `(` + regexp.QuoteMeta(name) + `)` + quote + `(?:$|[^\pL\pN])`)
129 for _, at := range pattern.FindAllStringSubmatchIndex(text, -1) {
130 source := text[at[2]:at[3]]
131 named := true
132 for _, word := range strings.Fields(source) {
133 first, _ := utf8.DecodeRuneInString(word)
134 if !unicode.IsUpper(first) {
135 named = false
136 }
137 }
138 if quote != "" {
139 return true
140 }
141 // A model-selected prefix of a longer proper name is not that name.
142 tail := text[at[3]:]
143 if strings.HasPrefix(tail, " ") {
144 next, _ := utf8.DecodeRuneInString(strings.TrimSpace(tail))
145 if unicode.IsUpper(next) {
146 continue
147 }
148 }
149 if named {
150 return true
151 }
152 }
153 }
154 }
155 return false
156}
157
158func (t *txn) namedPlacementRequest(r turnRecord, name string) (bool, error) {
159 if r.Kind != wire.TurnPerson {
160 return false, nil
161 }
162 var messages []messageRecord
163 if err := t.db.Where("turn_id = ? AND person = ? AND origin = ?", r.ID, r.Person, originComposer).Find(&messages).Error; err != nil {
164 return false, err
165 }
166 for _, m := range messages {
167 words := strings.Fields(strings.ToLower(m.Text))
168 if len(words) > 12 {
169 words = words[:12]
170 }
171 work := false
172 for _, word := range words {
173 if slices.Contains([]string{"fix", "build", "change", "add", "update", "remove", "implement", "create", "make", "work", "start", "move", "star", "prioritize"}, word) {
174 work = true
175 break
176 }
177 }
178 if work && containsProjectPhrase(m.Text, name) {
179 return true, nil
180 }
181 }
182 return false, nil
183}
184
185func (t *txn) learnPlacement(c cardRecord, choice string, remember bool) error {
186 if c.Placement == "" {
187 return nil
188 }
189 var p placementData
190 if err := json.Unmarshal([]byte(c.Placement), &p); err != nil {
191 return err
192 }
193 if !remember || !eligibleProjectName(p.RequestedName) {
194 p.RequestedName = ""
195 }
196 if p.RequestedName == "" && p.Star == nil {
197 return nil
198 }
199 for _, repo := range p.Repos {
200 if choice != ProjectName(repo) && repo != p.ChosenRepo {
201 continue
202 }
203 var project projectRecord
204 if err := t.db.First(&project, "repo = ? AND state = ?", repo, wire.ProjectActive).Error; errors.Is(err, gorm.ErrRecordNotFound) {
205 return ErrNotFound
206 } else if err != nil {
207 return err
208 }
209 if p.RequestedName != "" {
210 if err := t.learnProjectName(c.Person, project.ID, p.RequestedName); err != nil {
211 return err
212 }
213 }
214 if p.Star != nil {
215 return t.setStar(c.Person, project.ID, *p.Star, StarByYou)
216 }
217 return nil
218 }
219 return ErrInvalid
220}
221
222func (t *txn) findProject(r turnRecord, query string) (wire.ToolResult, error) {
223 p, err := t.namedProject(r.Person, query)
224 if err != nil {
225 return wire.ToolResult{}, err
226 }
227 if p == nil {
228 result, err := t.askNamedProject(r, query, nil)
229 if err != nil {
230 return result, err
231 }
232 h, err := t.hello(r.Person)
233 if err != nil {
234 return wire.ToolResult{}, err
235 }
236 entries, _ := reachable(h)
237 references := []map[string]string{}
238 for i, hit := range catalogHits(entries, query) {
239 if i == 5 {
240 break
241 }
242 references = append(references, map[string]string{"source": "repository", "forge": "amadan", "repo": hit.e.Repo, "description": clipText(runnerproto.RedactText(hit.e.Summary, nil), 500)})
243 }
244 if len(references) > 0 {
245 raw, _ := json.Marshal(references)
246 result.Text += "\n" + string(raw)
247 }
248 return result, nil
249 }
250 allowed, err := t.allowed(r.Person)
251 if err != nil {
252 return wire.ToolResult{}, err
253 }
254 if !slices.Contains(allowed, p.Repo) {
255 return refused("not_allowed", toolUnknownProject), nil
256 }
257 v, err := t.projectView(*p)
258 if err != nil {
259 return wire.ToolResult{}, err
260 }
261 raw, _ := json.Marshal(struct {
262 Title string `json:"title"`
263 Description string `json:"description"`
264 Source string `json:"description_source"`
265 }{clipText(runnerproto.RedactText(v.Title, nil), 120), clipText(runnerproto.RedactText(v.Description, nil), 500), v.DescriptionSource})
266 text := fmt.Sprintf(t.s.authority.Copy("projects.found"), p.Repo, raw)
267 if info, ok, err := t.catalogEntry(p.Repo); err != nil {
268 return wire.ToolResult{}, err
269 } else if ok && info.Empty {
270 text += toolFoundEmpty
271 }
272 return wire.ToolResult{Code: "found", Repo: p.Repo, Text: text}, nil
273}
274
275func redactProjectReferences(values []string) []string {
276 if len(values) > 12 {
277 values = values[:12]
278 }
279 out := make([]string, 0, len(values))
280 for _, value := range values {
281 out = append(out, clipText(runnerproto.RedactText(value, nil), 120))
282 }
283 return out
284}
285
286// expandNamedAnswer keeps the existing card open for a person's typed choice.
287// No turn is sent until that choice resolves to one reachable active project.
288func (t *txn) expandNamedAnswer(c *cardRecord, choice *string) (bool, error) {
289 if c.Placement == "" {
290 return false, nil
291 }
292 var data placementData
293 if err := json.Unmarshal([]byte(c.Placement), &data); err != nil {
294 return false, err
295 }
296 if data.OtherLabel != "" && *choice == data.OtherLabel && !data.ByName {
297 data.ByName = true
298 raw, _ := json.Marshal(data)
299 c.Placement = string(raw)
300 c.Options = "[]"
301 c.Question = t.s.authority.Copy("projects.name_question")
302 return true, t.saveCard(c)
303 }
304 if !data.ByName {
305 return false, nil
306 }
307 p, err := t.namedProject(c.Person, *choice)
308 if err != nil {
309 return false, err
310 }
311 if p == nil {
312 return false, ErrInvalid
313 }
314 if _, err := t.selectedProject(c.Person, p.ID); err != nil {
315 return false, err
316 }
317 data.ChosenRepo = p.Repo
318 data.Repos = []string{p.Repo}
319 data.Labels = []string{*choice}
320 data.ByName = false
321 data.OtherLabel = ""
322 raw, _ := json.Marshal(data)
323 c.Placement = string(raw)
324 return false, nil
325}
326