| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | ) |
| 8 | |
| 9 | func (r *Runtime) cachedPreflight(ctx context.Context, id, key string, probe func() error) error { |
| 10 | if err := ctx.Err(); err != nil { |
| 11 | return err |
| 12 | } |
| 13 | r.mu.Lock() |
| 14 | defer r.mu.Unlock() |
| 15 | if r.preflightCache == nil { |
| 16 | r.preflightCache = map[string]string{} |
| 17 | } |
| 18 | if r.preflightCache[id] == key && key != "" { |
| 19 | return nil |
| 20 | } |
| 21 | delete(r.preflightCache, id) |
| 22 | if err := probe(); err != nil { |
| 23 | return err |
| 24 | } |
| 25 | r.preflightCache[id] = key |
| 26 | return nil |
| 27 | } |
| 28 | func (j *Journal) prunePreflights(ctx context.Context, forget func(context.Context, containment.Record) error) error { |
| 29 | rows, err := j.db.QueryContext(ctx, `SELECT a.attempt,a.record FROM direct_attempts a WHERE contained=1 |
| 30 | AND (attempt LIKE 'codex-preflight-%' OR attempt LIKE 'claude-preflight-%') |
| 31 | AND NOT EXISTS(SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt) |
| 32 | AND NOT EXISTS(SELECT 1 FROM direct_frames f WHERE f.stream=a.stream) |
| 33 | AND NOT EXISTS(SELECT 1 FROM direct_events e WHERE e.attempt=a.attempt) |
| 34 | AND NOT EXISTS(SELECT 1 FROM journal_supervisor s WHERE s.kind='namespace' AND json_extract(s.body,'$.Record.AttemptKey')=a.attempt)`) |
| 35 | if err != nil { |
| 36 | return err |
| 37 | } |
| 38 | var records []containment.Record |
| 39 | for rows.Next() { |
| 40 | var attempt string |
| 41 | var raw []byte |
| 42 | if err = rows.Scan(&attempt, &raw); err != nil { |
| 43 | break |
| 44 | } |
| 45 | var record containment.Record |
| 46 | if err = json.Unmarshal(raw, &record); err != nil { |
| 47 | break |
| 48 | } |
| 49 | records = append(records, record) |
| 50 | } |
| 51 | if err == nil { |
| 52 | err = rows.Err() |
| 53 | } |
| 54 | rows.Close() |
| 55 | if err != nil { |
| 56 | return err |
| 57 | } |
| 58 | for _, record := range records { |
| 59 | if err = forget(ctx, record); err != nil { |
| 60 | return err |
| 61 | } |
| 62 | if _, err = j.db.ExecContext(ctx, "DELETE FROM direct_attempts WHERE attempt=? AND contained=1", record.AttemptKey); err != nil { |
| 63 | return err |
| 64 | } |
| 65 | } |
| 66 | return nil |
| 67 | } |
| 68 | |