| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/conversation/chatstate" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "strconv" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 11 | "amadan.net/oficina/equipo/internal/equipo/planning" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 13 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | var errCoordinatorContextUnavailable = chatstate.ErrContextUnavailable |
| 18 | |
| 19 | // ContextSource supplies instance-owned context inside the claim transaction. |
| 20 | type ContextSource func(context.Context, *gorm.DB, CoordinatorClaim) (instructions, decisions, preferences, retrieved []runnerproto.ContextRef, err error) |
| 21 | |
| 22 | func (s *Store) CoordinatorContext(ctx context.Context, c CoordinatorClaim) (CoordinatorContext, error) { |
| 23 | if _, err := s.deps.Authorize(s.tx, kernel.Actor{Address: c.Binding.Person}); err != nil { |
| 24 | return CoordinatorContext{}, err |
| 25 | } |
| 26 | var row TurnRecord |
| 27 | if err := s.tx.Where("id=? AND person=? AND binding_id=? AND generation=?", c.Turn.ID, c.Binding.Person, c.Binding.ID, c.Binding.Generation).First(&row).Error; err != nil { |
| 28 | return CoordinatorContext{}, err |
| 29 | } |
| 30 | var main Main |
| 31 | if err := s.tx.Where("id=? AND team_id=? AND person=?", row.ConversationID, row.TeamID, row.Person).First(&main).Error; err != nil { |
| 32 | return CoordinatorContext{}, err |
| 33 | } |
| 34 | var admitted messageRecord |
| 35 | if err := s.tx.Where("id=? AND conversation_id=? AND author_kind='person' AND author_id=? AND sequence=?", row.MessageID, main.ID, row.Person, row.Sequence).First(&admitted).Error; err != nil { |
| 36 | return CoordinatorContext{}, err |
| 37 | } |
| 38 | out := CoordinatorContext{ConversationID: main.ID, Revision: main.Revision} |
| 39 | var messages []messageRecord |
| 40 | if err := s.tx.Where("conversation_id=? AND sequence<=?", main.ID, row.Sequence).Order("sequence DESC").Limit(50).Find(&messages).Error; err != nil { |
| 41 | return out, err |
| 42 | } |
| 43 | for i := len(messages) - 1; i >= 0; i-- { |
| 44 | m := messages[i] |
| 45 | allowed := true |
| 46 | if s.deps.ContextMessage != nil { |
| 47 | var err error |
| 48 | allowed, err = s.deps.ContextMessage(s.tx, c, m.message()) |
| 49 | if err != nil { |
| 50 | return out, err |
| 51 | } |
| 52 | } |
| 53 | if !allowed { |
| 54 | continue |
| 55 | } |
| 56 | out.Recent = append(out.Recent, runnerproto.MessageRef{ID: m.ID, AuthorKind: m.AuthorKind, Body: m.Body, Sequence: m.Sequence, Revision: m.Revision}) |
| 57 | } |
| 58 | if len(out.Recent) == 0 || out.Recent[len(out.Recent)-1].ID != admitted.ID { |
| 59 | return out, errCoordinatorContextUnavailable |
| 60 | } |
| 61 | if s.deps.ContextSource != nil { |
| 62 | var err error |
| 63 | out.Instructions, out.ConfirmedDecisions, out.ConfirmedPreferences, out.Retrieved, err = s.deps.ContextSource(ctx, s.tx, c) |
| 64 | if err != nil { |
| 65 | return out, err |
| 66 | } |
| 67 | } |
| 68 | return chatstate.BoundContext(s.tx, row.ID, row.BindingID, row.Generation, out) |
| 69 | } |
| 70 | func (e *Engine) contextStore(tx *gorm.DB) *Store { |
| 71 | cs := *e.Conversation(tx) |
| 72 | cs.deps.ContextMessage = e.contextMessage |
| 73 | cs.deps.ContextSource = e.contextSource |
| 74 | return &cs |
| 75 | } |
| 76 | func (e *Engine) contextMessage(tx *gorm.DB, c CoordinatorClaim, m Message) (bool, error) { |
| 77 | // Preference sources stay inspectable, but old wording must not return through |
| 78 | // recent history after correction or deletion. Suggestions are never instructions. |
| 79 | var preferenceSources int64 |
| 80 | if err := tx.Table("personal_preferences").Where("person=? AND (source_message_id=? OR id=?)", c.Binding.Person, m.ID, m.ID).Count(&preferenceSources).Error; err != nil { |
| 81 | return false, err |
| 82 | } |
| 83 | if preferenceSources > 0 { |
| 84 | return false, nil |
| 85 | } |
| 86 | var suggestions int64 |
| 87 | if err := tx.Table("conversation_cards").Where("resource_id=? AND kind='suggest_preference'", m.ID).Count(&suggestions).Error; err != nil { |
| 88 | return false, err |
| 89 | } |
| 90 | if suggestions > 0 { |
| 91 | return false, nil |
| 92 | } |
| 93 | return e.contextSourceMessage(tx, c, m) |
| 94 | } |
| 95 | func (e *Engine) contextSourceMessage(tx *gorm.DB, c CoordinatorClaim, m Message) (bool, error) { |
| 96 | // Source references and explicit routing/queue classification survive turns. |
| 97 | var projects []int64 |
| 98 | if err := tx.Model(&TurnRecord{}).Where("message_id=? AND project_id>0", m.ID).Distinct("project_id").Pluck("project_id", &projects).Error; err != nil { |
| 99 | return false, err |
| 100 | } |
| 101 | var routed []int64 |
| 102 | if err := tx.Table("conversation_routes r").Select("t.project_id").Joins("JOIN tasks t ON t.id=r.task_id").Where("r.source_id=? OR r.notice_id=?", m.ID, m.ID).Scan(&routed).Error; err != nil { |
| 103 | return false, err |
| 104 | } |
| 105 | projects = append(projects, routed...) |
| 106 | for _, id := range projects { |
| 107 | if _, err := e.CheckProject(tx, c.Binding.Person, id, c.Brief.Selection); err != nil { |
| 108 | return e.contextDenied(err) |
| 109 | } |
| 110 | } |
| 111 | for _, ref := range m.SourceRefs { |
| 112 | var source runnerproto.SourceSnapshot |
| 113 | var err error |
| 114 | switch ref.Kind { |
| 115 | case "project": |
| 116 | id, er := strconv.ParseInt(ref.ID, 10, 64) |
| 117 | if er != nil { |
| 118 | return false, e.Invalid |
| 119 | } |
| 120 | _, source, err = e.Project(tx, c.Binding.Person, id, c.Brief.Selection) |
| 121 | case "task": |
| 122 | source, err = e.toolTaskSource(tx, c.Binding.Person, ref.ID, c.Brief.Selection) |
| 123 | default: |
| 124 | return false, nil |
| 125 | } |
| 126 | if err != nil { |
| 127 | return e.contextDenied(err) |
| 128 | } |
| 129 | source.Payload = e.Redact(source.Payload) |
| 130 | source.Ref.Hash = team.ContentDigest(source.Payload) |
| 131 | if ref != source.Ref { |
| 132 | return false, nil |
| 133 | } |
| 134 | } |
| 135 | // Unattributed old assistant material may contain text from a revoked source. |
| 136 | if m.AuthorKind != "person" && len(m.SourceRefs) == 0 { |
| 137 | return false, nil |
| 138 | } |
| 139 | return true, nil |
| 140 | } |
| 141 | func (e *Engine) contextDenied(err error) (bool, error) { |
| 142 | if errors.Is(err, e.Forbidden) || errors.Is(err, e.NotFound) { |
| 143 | return false, nil |
| 144 | } |
| 145 | return false, err |
| 146 | } |
| 147 | func (e *Engine) contextSource(ctx context.Context, tx *gorm.DB, c CoordinatorClaim) (instructions, decisions, preferences, retrieved []runnerproto.ContextRef, err error) { |
| 148 | // Fixture and later feature sources must enforce the same current-person and |
| 149 | // selected-provider visibility as the instance's source operations. |
| 150 | if e.ContextSource != nil { |
| 151 | instructions, decisions, preferences, retrieved, err = e.ContextSource(ctx, tx, c) |
| 152 | if err != nil { |
| 153 | return |
| 154 | } |
| 155 | } |
| 156 | var row TurnRecord |
| 157 | err = tx.Where("id=?", c.Turn.ID).First(&row).Error |
| 158 | if err != nil { |
| 159 | return |
| 160 | } |
| 161 | cs := e.Conversation(tx) |
| 162 | var confirmed []Preference |
| 163 | confirmed, err = cs.ConfirmedPreferences(Actor{Address: c.Binding.Person}, row.ProjectID) |
| 164 | if err != nil { |
| 165 | return |
| 166 | } |
| 167 | var main Main |
| 168 | main, err = cs.main(Actor{Address: c.Binding.Person}) |
| 169 | if err != nil { |
| 170 | return |
| 171 | } |
| 172 | for _, pref := range confirmed { |
| 173 | var source Message |
| 174 | source, err = cs.preferenceSource(main, pref.SourceMessageID) |
| 175 | if err != nil { |
| 176 | return |
| 177 | } |
| 178 | if pref.SourceMessageID != "" { |
| 179 | var allowed bool |
| 180 | allowed, err = e.contextSourceMessage(tx, c, source) |
| 181 | if err != nil { |
| 182 | return |
| 183 | } |
| 184 | if !allowed { |
| 185 | continue |
| 186 | } |
| 187 | } |
| 188 | raw, _ := json.Marshal(struct { |
| 189 | Preference Preference |
| 190 | SourceRevision int64 |
| 191 | }{pref, source.Revision}) |
| 192 | preferences = append(preferences, runnerproto.CoordinatorContextRef("preference", pref.ID, pref.Revision, string(raw))) |
| 193 | } |
| 194 | projects, e2 := e.projects(tx, c.Binding.Person, c.Brief.Selection) |
| 195 | if e2 != nil { |
| 196 | err = e2 |
| 197 | return |
| 198 | } |
| 199 | if row.ProjectID > 0 { |
| 200 | var source runnerproto.SourceSnapshot |
| 201 | _, source, err = e.Project(tx, c.Binding.Person, row.ProjectID, c.Brief.Selection) |
| 202 | if err != nil { |
| 203 | return |
| 204 | } |
| 205 | var rules planning.ProjectRules |
| 206 | ruleErr := tx.First(&rules, "project_id=?", row.ProjectID).Error |
| 207 | if ruleErr != nil && !errors.Is(ruleErr, gorm.ErrRecordNotFound) { |
| 208 | err = ruleErr |
| 209 | return |
| 210 | } |
| 211 | if rules.Text != "" { |
| 212 | instructions = append(instructions, runnerproto.CoordinatorContextRef("project_rules", strconv.FormatInt(row.ProjectID, 10), rules.Revision, rules.Text)) |
| 213 | } |
| 214 | source.Payload = e.Redact(source.Payload) |
| 215 | source.Ref.Hash = team.ContentDigest(source.Payload) |
| 216 | retrieved = append(retrieved, runnerproto.ContextRef{Source: source.Ref, Text: string(source.Payload)}) |
| 217 | } |
| 218 | setup, setupErr := e.setupContext(tx, c) |
| 219 | if setupErr != nil { |
| 220 | err = setupErr |
| 221 | return |
| 222 | } |
| 223 | if setup != "" { |
| 224 | retrieved = append(retrieved, runnerproto.CoordinatorContextRef("project_setup", c.Binding.Person, 1, setup)) |
| 225 | } |
| 226 | for _, p := range projects { |
| 227 | raw, _ := json.Marshal(p) |
| 228 | retrieved = append(retrieved, runnerproto.CoordinatorContextRef("project_label", strconv.FormatInt(p.ID, 10), p.Revision, string(raw))) |
| 229 | } |
| 230 | var current, past []runnerproto.ContextRef |
| 231 | current, past, err = e.contextDecisions(tx, c, row) |
| 232 | decisions = append(decisions, current...) |
| 233 | retrieved = append(retrieved, past...) |
| 234 | return |
| 235 | } |
| 236 | |