| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "encoding/base64" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "image/png" |
| 12 | "slices" |
| 13 | "strings" |
| 14 | |
| 15 | "gorm.io/gorm" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/attach" |
| 18 | "amadan.net/oficina/equipo/internal/specialist" |
| 19 | "amadan.net/oficina/equipo/internal/wire" |
| 20 | ) |
| 21 | |
| 22 | // A Design attempt's captures (spec 2026-11-28-dynamic-specialists.md, |
| 23 | // sections 3 and 5; protocol 38), kept as Research keeps its images: the |
| 24 | // runner sends the captures its final report names as render_file chunks |
| 25 | // before that report; they are staged for the step's current attempt |
| 26 | // (renderFile) and never served. The final report's options are then |
| 27 | // checked against them in the report's transaction (keepCaptures): the |
| 28 | // options valid, every capture complete with the report's hash, the tree |
| 29 | // digests consistent, each PNG decoded within the capture bounds, and |
| 30 | // the step's binding still what grantFor finds. Only then are they kept, |
| 31 | // with the options; anything else keeps nothing. Whatever the attempt |
| 32 | // sent and did not keep is deleted with its bytes when the step ends. |
| 33 | |
| 34 | // ErrDirectionNote: Build this on a direction card with more than one |
| 35 | // option, without the person's note. A card conflict: the card stands. |
| 36 | var ErrDirectionNote = fmt.Errorf("%w: build needs a note", ErrCardConflict) |
| 37 | |
| 38 | // designKept is a step's DesignOptions: the done attempt and its |
| 39 | // options, each with its capture ids in the report's order. |
| 40 | type designKept struct { |
| 41 | Attempt int64 `json:"attempt"` |
| 42 | Options []keptOption `json:"options"` |
| 43 | } |
| 44 | |
| 45 | type keptOption struct { |
| 46 | Name string `json:"name"` |
| 47 | Captures []string `json:"captures"` |
| 48 | } |
| 49 | |
| 50 | // refuseRender refuses a render_file chunk: acked and dropped, logged. |
| 51 | func refuseRender(why string) error { |
| 52 | return fmt.Errorf("%w: render_file: %s", ErrRefused, why) |
| 53 | } |
| 54 | |
| 55 | // renderFile stages one chunk of a Design capture only at protocol 38, |
| 56 | // valid on the wire, from the runner the step is placed on, for a step |
| 57 | // bound to its task's maker, for the step's current attempt while it |
| 58 | // runs and the task has not ended, in order, and at most |
| 59 | // wire.MaxDesignCaptures captures per attempt. The last chunk completes |
| 60 | // the file only when the whole is the declared size and hash. A staged |
| 61 | // file is never served (TaskFile serves kept files only). |
| 62 | func (t *txn) renderFile(l Lease, v *wire.RenderFile) error { |
| 63 | if l.Protocol < wire.ProtocolDesign { |
| 64 | return refuseRender("below protocol 38") |
| 65 | } |
| 66 | if !wire.ValidRenderFile(*v) { |
| 67 | return refuseRender("bad chunk") |
| 68 | } |
| 69 | data, err := base64.StdEncoding.Strict().DecodeString(v.Data) |
| 70 | if err != nil { |
| 71 | return refuseRender("bad chunk data") |
| 72 | } |
| 73 | var s stepRecord |
| 74 | if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 75 | return refuseRender("no such step") |
| 76 | } else if err != nil { |
| 77 | return err |
| 78 | } |
| 79 | if s.Specialist != wire.SpecialistEngineering || s.SpecialistID == "" || s.Person != l.Runner.Person || s.RunnerID != l.Runner.RunnerID { |
| 80 | return refuseRender("not this runner's Design step") |
| 81 | } |
| 82 | if s.State != wire.StepRunning || v.Attempt != s.Attempt || s.Withdrawn { |
| 83 | return refuseRender("attempt not current") |
| 84 | } |
| 85 | k, err := t.loadTask(s.TaskID) |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | if k.MakerSpecialistID != s.SpecialistID { |
| 90 | return refuseRender("not the task's maker") |
| 91 | } |
| 92 | if wire.FinalStage(k.Stage) || k.CancelRequested { |
| 93 | return refuseRender("task ended") |
| 94 | } |
| 95 | now := t.now() |
| 96 | var f taskFileRecord |
| 97 | err = t.db.Where("step_id = ? AND attempt = ? AND image_id = ?", s.ID, s.Attempt, v.CaptureID).First(&f).Error |
| 98 | fresh := errors.Is(err, gorm.ErrRecordNotFound) |
| 99 | if err != nil && !fresh { |
| 100 | return err |
| 101 | } |
| 102 | if fresh { |
| 103 | if v.Index != 0 { |
| 104 | return refuseRender("chunk out of order") |
| 105 | } |
| 106 | var n int64 |
| 107 | if err := t.db.Model(&taskFileRecord{}).Where("step_id = ? AND attempt = ?", s.ID, s.Attempt).Count(&n).Error; err != nil { |
| 108 | return err |
| 109 | } |
| 110 | if n >= wire.MaxDesignCaptures { |
| 111 | return refuseRender("too many captures") |
| 112 | } |
| 113 | f = taskFileRecord{ID: newID("tf_"), TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, RunnerID: l.Runner.RunnerID, ImageID: v.CaptureID, Size: v.Size, SHA256: v.SHA256, Total: v.Total, Source: taskFileRender, CreatedAt: now} |
| 114 | } else if f.Complete || f.Total != v.Total || f.Size != v.Size || f.SHA256 != v.SHA256 || v.Index != f.Received { |
| 115 | return refuseRender("chunk out of order") |
| 116 | } |
| 117 | f.Received, f.Bytes, f.UpdatedAt = f.Received+1, f.Bytes+int64(len(data)), now |
| 118 | if f.Bytes > f.Size || f.Received == f.Total && f.Bytes != f.Size { |
| 119 | return refuseRender("size does not match") |
| 120 | } |
| 121 | if err := t.db.Create(&taskFileDataRecord{FileID: f.ID, Idx: v.Index, Data: data}).Error; err != nil { |
| 122 | return err |
| 123 | } |
| 124 | if f.Received == f.Total { |
| 125 | whole, err := t.fileBytes(f.ID) |
| 126 | if err != nil { |
| 127 | return err |
| 128 | } |
| 129 | if sum := sha256.Sum256(whole); int64(len(whole)) != f.Size || hex.EncodeToString(sum[:]) != f.SHA256 { |
| 130 | return refuseRender("hash does not match") |
| 131 | } |
| 132 | f.Complete = true |
| 133 | } |
| 134 | if fresh { |
| 135 | return t.db.Create(&f).Error |
| 136 | } |
| 137 | return t.db.Model(&taskFileRecord{}).Where("id = ?", f.ID).Select("received", "bytes", "complete", "updated_at").Updates(&f).Error |
| 138 | } |
| 139 | |
| 140 | // keptCapture is a capture the report names and the staged file it is, |
| 141 | // checked, with its option and pixel size. |
| 142 | type keptCapture struct { |
| 143 | file taskFileRecord |
| 144 | option string |
| 145 | digest string |
| 146 | w, h int |
| 147 | } |
| 148 | |
| 149 | // keepCaptures applies a done Design attempt's options (stepReport has |
| 150 | // accepted the done report, before the step is saved): kept whole when |
| 151 | // checkCaptures finds them sound, stored on the step for its read shape; |
| 152 | // otherwise nothing. Saving the ended step then deletes every file it |
| 153 | // sent and did not keep (saveStep). |
| 154 | func (t *txn) keepCaptures(k *taskRecord, s *stepRecord, opts []wire.DesignOption) error { |
| 155 | keep, ok, err := t.checkCaptures(k, s, opts) |
| 156 | if err != nil { |
| 157 | return err |
| 158 | } |
| 159 | s.DesignOptions = "" |
| 160 | if ok { |
| 161 | kept := designKept{Attempt: s.Attempt, Options: []keptOption{}} |
| 162 | for _, o := range opts { |
| 163 | ko := keptOption{Name: o.Name, Captures: []string{}} |
| 164 | for _, c := range o.Captures { |
| 165 | ko.Captures = append(ko.Captures, c.ID) |
| 166 | } |
| 167 | kept.Options = append(kept.Options, ko) |
| 168 | } |
| 169 | raw, err := json.Marshal(kept) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | s.DesignOptions = string(raw) |
| 174 | for _, c := range keep { |
| 175 | f := c.file |
| 176 | f.Kept, f.Option, f.TreeDigest, f.MediaType, f.Width, f.Height, f.UpdatedAt = true, c.option, c.digest, attach.PNG, c.w, c.h, t.now() |
| 177 | if err := t.db.Model(&taskFileRecord{}).Where("id = ?", f.ID).Select("kept", "option", "tree_digest", "media_type", "width", "height", "updated_at").Updates(&f).Error; err != nil { |
| 178 | return err |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | return nil |
| 183 | } |
| 184 | |
| 185 | // checkCaptures reports whether a done Design attempt's options can be |
| 186 | // kept, and the captures to keep: no options keeps nothing; otherwise |
| 187 | // the options must be valid (wire.ValidOptions); the step bound to the |
| 188 | // task's maker, its binding still exactly what grantFor finds for the |
| 189 | // task's project and holding page.render; every capture a complete file |
| 190 | // this attempt staged with the report's hash, a PNG within the capture |
| 191 | // bounds (checkCapture); and the captures of one render agreeing on each |
| 192 | // tree's digest (a diff is of work's tree). |
| 193 | func (t *txn) checkCaptures(k *taskRecord, s *stepRecord, opts []wire.DesignOption) ([]keptCapture, bool, error) { |
| 194 | if len(opts) == 0 || wire.ValidOptions(opts) != nil { |
| 195 | return nil, false, nil |
| 196 | } |
| 197 | if s.SpecialistID == "" || s.SpecialistID != k.MakerSpecialistID || !slices.Contains(boundCaps(*s), specialist.CapabilityPageRender) { |
| 198 | return nil, false, nil |
| 199 | } |
| 200 | holds, err := t.bindingHolds(*s, *k) |
| 201 | if err != nil || !holds { |
| 202 | return nil, false, err |
| 203 | } |
| 204 | digests := map[string]string{} |
| 205 | var out []keptCapture |
| 206 | for _, o := range opts { |
| 207 | for _, c := range o.Captures { |
| 208 | call, _, _ := strings.Cut(c.ID, "-") |
| 209 | tree := wire.CaptureTree(c.ID) |
| 210 | if tree == "diff" { |
| 211 | tree = "work" |
| 212 | } |
| 213 | if d, seen := digests[call+"-"+tree]; seen && d != c.TreeDigest { |
| 214 | return nil, false, nil |
| 215 | } |
| 216 | digests[call+"-"+tree] = c.TreeDigest |
| 217 | var f taskFileRecord |
| 218 | if err := t.db.Where("step_id = ? AND attempt = ? AND image_id = ? AND source = ? AND complete = ?", s.ID, s.Attempt, c.ID, taskFileRender, true).First(&f).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 219 | return nil, false, nil |
| 220 | } else if err != nil { |
| 221 | return nil, false, err |
| 222 | } |
| 223 | if f.SHA256 != c.SHA256 { |
| 224 | return nil, false, nil |
| 225 | } |
| 226 | data, err := t.fileBytes(f.ID) |
| 227 | if err != nil { |
| 228 | return nil, false, err |
| 229 | } |
| 230 | w, h, ok := checkCapture(data) |
| 231 | if !ok { |
| 232 | return nil, false, nil |
| 233 | } |
| 234 | out = append(out, keptCapture{file: f, option: o.Name, digest: c.TreeDigest, w: w, h: h}) |
| 235 | } |
| 236 | } |
| 237 | return out, true, nil |
| 238 | } |
| 239 | |
| 240 | // checkCapture checks a complete capture's bytes (renderFile checked |
| 241 | // their size and hash): a PNG whose header says it is within the capture |
| 242 | // bounds, read before any pixel is decoded; one attach keeps byte for |
| 243 | // byte (nothing after its end, no location); and fully decoded (every |
| 244 | // chunk's CRC and the image data checked; image/png decodes exactly the |
| 245 | // header's size). |
| 246 | func checkCapture(data []byte) (w, h int, ok bool) { |
| 247 | cfg, err := png.DecodeConfig(bytes.NewReader(data)) |
| 248 | if err != nil || cfg.Width < 1 || cfg.Height < 1 || cfg.Width > wire.MaxCaptureWidth || cfg.Height > wire.MaxCaptureHeight { |
| 249 | return 0, 0, false |
| 250 | } |
| 251 | info, clean, err := attach.Inspect("capture.png", attach.PNG, data) |
| 252 | if err != nil || info.MediaType != attach.PNG || !bytes.Equal(clean, data) { |
| 253 | return 0, 0, false |
| 254 | } |
| 255 | if _, err := png.Decode(bytes.NewReader(data)); err != nil { |
| 256 | return 0, 0, false |
| 257 | } |
| 258 | return cfg.Width, cfg.Height, true |
| 259 | } |
| 260 | |
| 261 | // dropUnkept deletes a step's files that are not kept, and their bytes. |
| 262 | func (t *txn) dropUnkept(stepID string) error { return t.dropResearchFiles(stepID) } |
| 263 | |
| 264 | // designView is a done Design attempt's kept options and captures on |
| 265 | // the task's read shape; nil when it kept none. |
| 266 | func (t *txn) designView(s stepRecord) (*wire.StepDesign, error) { |
| 267 | if s.DesignOptions == "" { |
| 268 | return nil, nil |
| 269 | } |
| 270 | var kept designKept |
| 271 | if err := json.Unmarshal([]byte(s.DesignOptions), &kept); err != nil { |
| 272 | return nil, err |
| 273 | } |
| 274 | var files []taskFileRecord |
| 275 | if err := t.db.Where("step_id = ? AND attempt = ? AND source = ? AND kept = ? AND complete = ?", s.ID, kept.Attempt, taskFileRender, true, true).Find(&files).Error; err != nil { |
| 276 | return nil, err |
| 277 | } |
| 278 | byID := map[string]taskFileRecord{} |
| 279 | for _, f := range files { |
| 280 | byID[f.ImageID] = f |
| 281 | } |
| 282 | v := &wire.StepDesign{Attempt: kept.Attempt, Options: []wire.StepDesignOption{}} |
| 283 | for _, o := range kept.Options { |
| 284 | vo := wire.StepDesignOption{Name: o.Name, Captures: []wire.StepCapture{}} |
| 285 | for _, id := range o.Captures { |
| 286 | if f, ok := byID[id]; ok { |
| 287 | vo.Captures = append(vo.Captures, wire.StepCapture{ID: f.ID, CaptureID: f.ImageID, Size: f.Size, Width: f.Width, Height: f.Height}) |
| 288 | } |
| 289 | } |
| 290 | v.Options = append(v.Options, vo) |
| 291 | } |
| 292 | return v, nil |
| 293 | } |
| 294 | |
| 295 | // candidateDesign is what the newest Engineering step of the task kept, |
| 296 | // once it is done: the options the direction card shows, and Build this |
| 297 | // reads. nil when it kept none. |
| 298 | func (t *txn) candidateDesign(p progress) (*wire.StepDesign, error) { |
| 299 | if p.eng == nil || p.eng.State != wire.StepDone { |
| 300 | return nil, nil |
| 301 | } |
| 302 | return t.designView(*p.eng) |
| 303 | } |
| 304 | |