| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/conversation/chatstate" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 6 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | ) |
| 12 | |
| 13 | func coordinatorAssignment(c CoordinatorClaim) Assignment { |
| 14 | return Assignment{ID: c.Turn.ID, TaskID: c.Turn.ID, Kind: "coordinator", StepKey: "coordinate", Scope: c.Scope, Selection: c.Brief.Selection, Revision: c.Turn.Revision} |
| 15 | } |
| 16 | |
| 17 | // CompleteCoordinator requires a server validator of committed tool results and |
| 18 | // delivery. A provider process-completed event is never this proof. |
| 19 | func (e *Engine) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| 20 | if event.Kind != "coordinator.delivery" || event.Validate() != nil { |
| 21 | return team.ErrEvidence |
| 22 | } |
| 23 | return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 24 | b, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| 25 | if err != nil { |
| 26 | return err |
| 27 | } |
| 28 | if event.Scope != c.Scope || event.Handle != c.Handle || event.AssignmentID != row.ID || event.TaskID != row.ID || event.TurnID != row.ID || event.ActionID != c.Admission.Dispatch.Action { |
| 29 | return e.Forbidden |
| 30 | } |
| 31 | if row.ProviderSessionID != "" && row.ProviderSessionID != event.SessionID { |
| 32 | return e.Conflict |
| 33 | } |
| 34 | hash := event.ContentHash() |
| 35 | if row.State == "delivered" { |
| 36 | if row.DeliveryHash != hash { |
| 37 | return e.Conflict |
| 38 | } |
| 39 | return nil |
| 40 | } |
| 41 | if row.State != "running" { |
| 42 | return team.ErrEvidence |
| 43 | } |
| 44 | if err = e.Core.ValidateHandle(ctx, c.Scope, c.Handle); err != nil { |
| 45 | return err |
| 46 | } |
| 47 | var body string |
| 48 | var receipt team.Receipt |
| 49 | committed := e.Delivery == nil |
| 50 | if committed { |
| 51 | receipt, err = e.committedToolDelivery(ctx, tx, c, row, event) |
| 52 | } else { |
| 53 | body, receipt, err = e.Delivery(ctx, c, event) |
| 54 | } |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | if receipt.Outcome != team.OutcomeSuccess { |
| 59 | return team.ErrEvidence |
| 60 | } |
| 61 | action, err := e.Core.GetAction(ctx, c.Scope, event.ActionID) |
| 62 | if err != nil { |
| 63 | return err |
| 64 | } |
| 65 | if saved := action.Receipt; saved != nil { |
| 66 | if action.State != team.ActionSucceeded || saved.Outcome != receipt.Outcome || (saved.Usage == nil) != (receipt.Usage == nil) || (saved.Usage != nil && *saved.Usage != *receipt.Usage) { |
| 67 | return team.ErrReceiptConflict |
| 68 | } |
| 69 | } else if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil { |
| 70 | return err |
| 71 | } |
| 72 | if !committed { |
| 73 | if err = e.Conversation(tx).DeliverCoordinator(row, body); err != nil { |
| 74 | return err |
| 75 | } |
| 76 | } |
| 77 | if err = e.Core.DeliverCoordinator(ctx, c.Scope, c.Handle, b.ID, hash); err != nil { |
| 78 | return err |
| 79 | } |
| 80 | if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "delivery_hash", "provider_session_id").Updates(map[string]any{"state": "delivered", "delivery_hash": hash, "provider_session_id": event.SessionID}).Error; err != nil { |
| 81 | return err |
| 82 | } |
| 83 | return e.Audit(tx, b, "coordinator.delivered", row.ID) |
| 84 | }) |
| 85 | } |
| 86 | func (e *Engine) coordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| 87 | if event.Kind == "coordinator.delivery" { |
| 88 | return e.CompleteCoordinator(ctx, p, c, event) |
| 89 | } |
| 90 | if event.Validate() != nil || event.Scope != c.Scope || event.Handle != c.Handle || event.AssignmentID != c.Turn.ID || event.TaskID != c.Turn.ID { |
| 91 | return e.Invalid |
| 92 | } |
| 93 | switch event.Kind { |
| 94 | case "coordinator.text", "namespace.owner", "namespace.launch", "session.bound", "turn.completed", "turn.failed", "turn.uncertain": |
| 95 | default: |
| 96 | return e.Invalid |
| 97 | } |
| 98 | return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 99 | b, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| 100 | if err != nil { |
| 101 | return err |
| 102 | } |
| 103 | if row.State != "running" { |
| 104 | return e.Conflict |
| 105 | } |
| 106 | if err = e.Core.ValidateHandle(ctx, c.Scope, c.Handle); err != nil { |
| 107 | return err |
| 108 | } |
| 109 | var prior EventRecord |
| 110 | err = tx.First(&prior, "key=?", event.DedupKey()).Error |
| 111 | if err == nil { |
| 112 | if prior.ContentHash != event.ContentHash() { |
| 113 | return e.Conflict |
| 114 | } |
| 115 | return nil |
| 116 | } |
| 117 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 118 | return err |
| 119 | } |
| 120 | if e.Events == nil { |
| 121 | return e.Unavailable |
| 122 | } |
| 123 | wire, err := runnerproto.Marshal(event) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | q := RunnerRequest{Version: 2, AssignmentID: row.ID, Scope: c.Scope, Handle: c.Handle, RequestID: event.ID, ActionID: event.ActionID, Event: wire} |
| 128 | if err = e.Events(ctx, coordinatorAssignment(c), q); err != nil { |
| 129 | return err |
| 130 | } |
| 131 | if event.Kind == "coordinator.text" { |
| 132 | if event.ActionID != c.Admission.Dispatch.Action || event.TurnID != row.ID || row.ProviderSessionID == "" || row.ProviderSessionID != event.SessionID { |
| 133 | return e.Forbidden |
| 134 | } |
| 135 | if err = chatstate.ApplyText(tx, row.ID, row.PartialSequence, row.PartialAt, e.Now(), event, e.Redact, e.Invalid); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | } |
| 139 | if event.Kind == "session.bound" { |
| 140 | if row.ProviderSessionID != "" && row.ProviderSessionID != event.SessionID { |
| 141 | return e.Conflict |
| 142 | } |
| 143 | if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("provider_session_id").Updates(map[string]any{"provider_session_id": event.SessionID}).Error; err != nil { |
| 144 | return err |
| 145 | } |
| 146 | } |
| 147 | if event.Kind == "turn.completed" || event.Kind == "turn.failed" || event.Kind == "turn.uncertain" { |
| 148 | if event.ActionID != c.Admission.Dispatch.Action || event.TurnID != row.ID || row.ProviderSessionID == "" || row.ProviderSessionID != event.SessionID { |
| 149 | return e.Forbidden |
| 150 | } |
| 151 | if event.Kind == "turn.uncertain" { |
| 152 | if err = e.Core.Lost(ctx, c.Scope, event.ActionID, "coordinator.uncertain"); err != nil { |
| 153 | return err |
| 154 | } |
| 155 | } else { |
| 156 | if e.Receipt == nil { |
| 157 | return e.Unavailable |
| 158 | } |
| 159 | receipt, err := e.Receipt(ctx, coordinatorAssignment(c), q) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil { |
| 164 | return err |
| 165 | } |
| 166 | } |
| 167 | if event.Kind != "turn.completed" { |
| 168 | if err = e.Core.StopAttempt(ctx, c.Scope, c.Handle, "coordinator.uncertain"); err != nil { |
| 169 | return err |
| 170 | } |
| 171 | if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "revision").Updates(map[string]any{"state": "uncertain", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| 172 | return err |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | hash := event.ContentHash() |
| 177 | event.Payload = e.Redact(event.Payload) |
| 178 | if err = tx.Create(&EventRecord{Key: event.DedupKey(), AssignmentID: row.ID, StreamKey: event.StreamKey(), Epoch: event.Epoch, Sequence: event.Sequence, Kind: event.Kind, ContentHash: hash, Body: string(mustCoordinatorJSON(event)), Isolation: string(mustCoordinatorJSON(c.Brief.Selection.Isolation))}).Error; err != nil { |
| 179 | return err |
| 180 | } |
| 181 | return e.Audit(tx, b, "coordinator.event", event.ID) |
| 182 | }) |
| 183 | } |
| 184 | func (e *Engine) containCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| 185 | return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 186 | // Cleanup authenticates the runner but deliberately permits an old generation. |
| 187 | if err := e.RunnerCurrent(tx, p); err != nil { |
| 188 | return err |
| 189 | } |
| 190 | var row TurnRecord |
| 191 | if err := tx.First(&row, "id=? AND person=?", c.Turn.ID, p.Person).Error; err != nil { |
| 192 | return err |
| 193 | } |
| 194 | var saved CoordinatorClaim |
| 195 | if err := decodeCoordinator(row.Claim, &saved); err != nil { |
| 196 | return err |
| 197 | } |
| 198 | if runnerproto.EventHash(saved) != runnerproto.EventHash(c) || c.Handle.Runner != p.RunnerID || proof.Scope != c.Scope || proof.Handle != c.Handle { |
| 199 | return e.Forbidden |
| 200 | } |
| 201 | if e.Containment == nil { |
| 202 | return e.Unavailable |
| 203 | } |
| 204 | raw, err := json.Marshal(proof) |
| 205 | if err != nil { |
| 206 | return err |
| 207 | } |
| 208 | if err = e.Containment(ctx, coordinatorAssignment(saved), RunnerRequest{Version: 2, AssignmentID: row.ID, RequestID: row.ID, Scope: c.Scope, Handle: c.Handle, Proof: raw}); err != nil { |
| 209 | return err |
| 210 | } |
| 211 | if err = e.Core.ContainUntrusted(ctx, c.Scope, c.Handle); err != nil { |
| 212 | return err |
| 213 | } |
| 214 | if row.State != "delivered" { |
| 215 | action, err := e.Core.GetAction(ctx, saved.Scope, saved.Admission.Dispatch.Action) |
| 216 | if err != nil { |
| 217 | return err |
| 218 | } |
| 219 | if action.State == team.ActionDispatching || action.State == team.ActionUncertain { |
| 220 | if err = e.Core.Lost(ctx, saved.Scope, saved.Admission.Dispatch.Action, "coordinator.uncertain"); err != nil { |
| 221 | return err |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | return tx.Model(&TurnRecord{}).Where("id=? AND state<>'uncertain'", row.ID).Select("state", "revision").Updates(map[string]any{"state": "uncertain", "revision": gorm.Expr("revision+1")}).Error |
| 226 | } |
| 227 | return nil |
| 228 | }) |
| 229 | } |
| 230 | |