| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 5 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "gorm.io/gorm" |
| 10 | ) |
| 11 | |
| 12 | func toolResource(c CoordinatorClaim, row TurnRecord) string { |
| 13 | return runnerproto.EventHash([]any{string(c.Scope.Account), c.Binding.ID, c.Binding.Generation, row.ID, c.Handle.Attempt, c.Handle.Fence, row.ProviderSessionID}) |
| 14 | } |
| 15 | |
| 16 | // committedToolDelivery reads only local bounded records. Provider text and a |
| 17 | // tool result without a previously validated provider receipt cannot complete. |
| 18 | func (e *Engine) committedToolDelivery(ctx context.Context, tx *gorm.DB, c CoordinatorClaim, row TurnRecord, event runnerproto.Event) (team.Receipt, error) { |
| 19 | var delivery struct { |
| 20 | RequestID string `json:"request_id"` |
| 21 | ResourceID string `json:"resource_id"` |
| 22 | } |
| 23 | if runnerproto.DecodeLimit(bytes.NewReader(event.Payload), &delivery, 1024) != nil || delivery.RequestID == "" || delivery.ResourceID == "" { |
| 24 | return team.Receipt{}, team.ErrEvidence |
| 25 | } |
| 26 | var saved requestRecord |
| 27 | if err := tx.Where("principal=? AND operation='coordinator.tool' AND resource=? AND request_id=?", c.Binding.Person, toolResource(c, row), delivery.RequestID).First(&saved).Error; err != nil { |
| 28 | return team.Receipt{}, team.ErrEvidence |
| 29 | } |
| 30 | var out CoordinatorToolResult |
| 31 | if len(saved.Result) > 65536 || json.Unmarshal([]byte(saved.Result), &out) != nil || out.ResourceID != delivery.ResourceID { |
| 32 | return team.Receipt{}, team.ErrEvidence |
| 33 | } |
| 34 | // The committed result marks the operation, so reads cannot prove delivery. |
| 35 | var value struct { |
| 36 | Tool string `json:"tool"` |
| 37 | } |
| 38 | if json.Unmarshal(out.Value, &value) != nil { |
| 39 | return team.Receipt{}, team.ErrEvidence |
| 40 | } |
| 41 | switch value.Tool { |
| 42 | case "propose_project", "post_message", "propose_plan", "ask_person", "route_to_task", "suggest_preference", "suggest_specialist", "suggest_playbook": |
| 43 | default: |
| 44 | return team.Receipt{}, team.ErrEvidence |
| 45 | } |
| 46 | action, err := e.Core.GetAction(ctx, c.Scope, c.Admission.Dispatch.Action) |
| 47 | if err != nil { |
| 48 | return team.Receipt{}, err |
| 49 | } |
| 50 | if action.State != team.ActionSucceeded || action.Receipt == nil || action.Receipt.Outcome != team.OutcomeSuccess { |
| 51 | return team.Receipt{}, team.ErrEvidence |
| 52 | } |
| 53 | return *action.Receipt, nil |
| 54 | } |
| 55 | |