| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "os" |
| 7 | "slices" |
| 8 | "strconv" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/copydesk" |
| 13 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 14 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | type copyBatch struct { |
| 19 | extraction copydesk.Extraction |
| 20 | prompt string |
| 21 | estimate int64 |
| 22 | } |
| 23 | |
| 24 | func copyBatches(ex copydesk.Extraction, edits []copydesk.Feedback, guidance []byte) ([]copyBatch, int64) { |
| 25 | var batches []copyBatch |
| 26 | var total int64 |
| 27 | for start := 0; start < len(ex.Strings); { |
| 28 | var best copyBatch |
| 29 | end := start |
| 30 | for next := start + 1; next <= len(ex.Strings); next++ { |
| 31 | part := copydesk.Extraction{Version: 1, Strings: ex.Strings[start:next]} |
| 32 | prompt, estimate := copyPrompt(part, edits, guidance) |
| 33 | if estimate > copydesk.PassTokens { |
| 34 | break |
| 35 | } |
| 36 | best = copyBatch{part, prompt, estimate} |
| 37 | end = next |
| 38 | } |
| 39 | if end == start { |
| 40 | return nil, 0 |
| 41 | } |
| 42 | batches = append(batches, best) |
| 43 | total += best.estimate |
| 44 | start = end |
| 45 | } |
| 46 | return batches, total |
| 47 | } |
| 48 | func (e *Engineer) reviewCopyBatches(ctx context.Context, r stepRow, tree workspace.TaskTree, ex copydesk.Extraction, result *wire.CopyResult, rep *wire.StepReport, progress func(wire.StepReport)) bool { |
| 49 | fail := func(reason string) bool { |
| 50 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| 51 | return true |
| 52 | } |
| 53 | var spent int64 |
| 54 | if err := e.O.State.db.QueryRowContext(ctx, "SELECT COALESCE(SUM(CASE WHEN c.known=0 THEN MAX(c.spent,?) ELSE c.spent END),0) FROM copy_attempts c JOIN steps s ON s.step_id=c.step_id AND s.attempt=c.attempt WHERE s.task_id=?", copydesk.PassTokens, r.TaskID).Scan(&spent); err != nil { |
| 55 | result.UsageKnown = false |
| 56 | return fail("policy_rejected") |
| 57 | } |
| 58 | guidance, _ := e.copyRead(ctx, tree, r.BaseSHA, "AGENTS.md") |
| 59 | batches, estimate := copyBatches(ex, append(slices.Clone(r.Copy.Edits), r.Copy.Notes...), guidance) |
| 60 | available := min(r.Copy.Remaining, int64(copydesk.TaskTokens)-spent) |
| 61 | if len(batches) == 0 || estimate > available { |
| 62 | return fail("copy_budget") |
| 63 | } |
| 64 | if e.Conns == nil { |
| 65 | return fail("account_unavailable") |
| 66 | } |
| 67 | model := "" |
| 68 | for index, batch := range batches { |
| 69 | if err := e.lease(ctx, r); err != nil { |
| 70 | return fail(leaseReason(err)) |
| 71 | } |
| 72 | if batch.estimate > available-result.Tokens { |
| 73 | return fail("copy_budget") |
| 74 | } |
| 75 | b, hold, admit, err := e.Conns.admit(ctx, r, "copy", keptRef{}, nil, nil) |
| 76 | if hold != nil { |
| 77 | if index > 0 { |
| 78 | return fail("account_unavailable") |
| 79 | } |
| 80 | *rep = heldReport(*rep, hold) |
| 81 | return true |
| 82 | } |
| 83 | if err != nil { |
| 84 | return fail("account_unavailable") |
| 85 | } |
| 86 | if index > 0 && (b.LocalID != rep.Account || b.Family != rep.Family || b.Model != model) { |
| 87 | return fail("account_unavailable") |
| 88 | } |
| 89 | if index == 0 { |
| 90 | res, err := e.O.State.db.ExecContext(ctx, "INSERT INTO copy_attempts(step_id,attempt,result,spent,known) VALUES(?,?,?,0,0) ON CONFLICT DO NOTHING", r.StepID, r.Attempt, "{}") |
| 91 | if err != nil { |
| 92 | return fail("provider_failed") |
| 93 | } |
| 94 | n, _ := res.RowsAffected() |
| 95 | if n != 1 { |
| 96 | result.UsageKnown = false |
| 97 | return fail("policy_rejected") |
| 98 | } |
| 99 | } |
| 100 | dir, err := os.MkdirTemp(e.O.Runner.WorkspaceRoot, "copy-model-") |
| 101 | if err != nil { |
| 102 | return fail("workspace_refused") |
| 103 | } |
| 104 | defer os.RemoveAll(dir) |
| 105 | var mu sync.Mutex |
| 106 | submitted := false |
| 107 | var reviewed copydesk.Review |
| 108 | call := func(_ context.Context, name, _ string, args json.RawMessage) (string, bool) { |
| 109 | mu.Lock() |
| 110 | defer mu.Unlock() |
| 111 | if name != "submit_review" || submitted { |
| 112 | return "Submit exactly one structured review.", true |
| 113 | } |
| 114 | if len(args) > 1<<20 || json.Unmarshal(args, &reviewed) != nil { |
| 115 | return "Invalid structured review.", true |
| 116 | } |
| 117 | if _, err := copydesk.ValidateReview(batch.extraction.Strings, reviewed); err != nil { |
| 118 | return err.Error(), true |
| 119 | } |
| 120 | submitted = true |
| 121 | return "Recorded. Finish now.", false |
| 122 | } |
| 123 | previousKnown := result.UsageKnown |
| 124 | // Keep prior spend plus an uncertain pass across process death. |
| 125 | if _, err := e.O.State.db.ExecContext(ctx, "UPDATE copy_attempts SET spent=?,known=0 WHERE step_id=? AND attempt=?", result.Tokens+copydesk.PassTokens, r.StepID, r.Attempt); err != nil { |
| 126 | return fail("provider_failed") |
| 127 | } |
| 128 | rep.Family, rep.Account, model = b.Family, b.LocalID, b.Model |
| 129 | result.UsageKnown = false |
| 130 | progress(*rep) |
| 131 | run := e.run(ctx, r, workspace.TaskTree{Dir: dir}, specialistRun{meterTurn: "copy-pass-" + strconv.Itoa(index), admit: admit, action: "inspect", binding: b, tools: copyTools, names: []string{"submit_review"}, permission: claude.ReadPermission, call: call, prompt: batch.prompt, limit: 5 * time.Minute, noLog: true}) |
| 132 | if run.reason == reasonHeld { |
| 133 | if index == 0 { |
| 134 | if _, err := e.O.State.db.ExecContext(context.WithoutCancel(ctx), "DELETE FROM copy_attempts WHERE step_id=? AND attempt=? AND spent=? AND known=0", r.StepID, r.Attempt, copydesk.PassTokens); err != nil { |
| 135 | return fail("provider_failed") |
| 136 | } |
| 137 | result.UsageKnown = true |
| 138 | *rep = heldGuard(*rep, run) |
| 139 | return true |
| 140 | } |
| 141 | if _, err := e.O.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE copy_attempts SET spent=?,known=? WHERE step_id=? AND attempt=?", result.Tokens, previousKnown, r.StepID, r.Attempt); err != nil { |
| 142 | return fail("provider_failed") |
| 143 | } |
| 144 | result.UsageKnown = previousKnown |
| 145 | return fail("account_unavailable") |
| 146 | } |
| 147 | rows := run.usage(b, r.Attempt) |
| 148 | tokens, known := copyUsage(rows) |
| 149 | if !known { |
| 150 | tokens = max(tokens, int64(copydesk.PassTokens)) |
| 151 | } |
| 152 | result.Tokens += tokens |
| 153 | result.UsageKnown = previousKnown && known |
| 154 | rep.Usage = copyUsageRows(rep.Usage, rows) |
| 155 | if submitted { |
| 156 | result.Review.Strings = append(result.Review.Strings, reviewed.Strings...) |
| 157 | } |
| 158 | raw, _ := json.Marshal(result) |
| 159 | if _, err := e.O.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE copy_attempts SET result=?,spent=?,known=? WHERE step_id=? AND attempt=?", string(raw), result.Tokens, result.UsageKnown, r.StepID, r.Attempt); err != nil { |
| 160 | return fail("provider_failed") |
| 161 | } |
| 162 | if !run.terminated { |
| 163 | fail("provider_failed") |
| 164 | rep.Termination = false |
| 165 | return true |
| 166 | } |
| 167 | if run.reason != "" { |
| 168 | return fail(run.reason) |
| 169 | } |
| 170 | if !submitted { |
| 171 | return fail("policy_rejected") |
| 172 | } |
| 173 | if index+1 < len(batches) { |
| 174 | // The verified exit above permits another bounded call. The durable |
| 175 | // Copy reservation still refuses a replay of this whole attempt. |
| 176 | res, err := e.O.State.db.ExecContext(ctx, "UPDATE steps SET ns_id='' WHERE step_id=? AND attempt=? AND cancel=0", r.StepID, r.Attempt) |
| 177 | if err != nil { |
| 178 | return fail("provider_failed") |
| 179 | } |
| 180 | if n, _ := res.RowsAffected(); n != 1 { |
| 181 | return fail("policy_rejected") |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | return false |
| 186 | } |
| 187 | func copyUsageRows(all, rows []wire.Usage) []wire.Usage { |
| 188 | sum := func(a, b *int64) *int64 { |
| 189 | if a == nil || b == nil { |
| 190 | return nil |
| 191 | } |
| 192 | v := *a + *b |
| 193 | return &v |
| 194 | } |
| 195 | for _, u := range rows { |
| 196 | i := slices.IndexFunc(all, func(v wire.Usage) bool { |
| 197 | return v.Provider == u.Provider && v.Connection == u.Connection && v.Model == u.Model && v.Attempt == u.Attempt |
| 198 | }) |
| 199 | if i < 0 { |
| 200 | all = append(all, u) |
| 201 | continue |
| 202 | } |
| 203 | v := &all[i] |
| 204 | v.Complete = v.Complete && u.Complete |
| 205 | v.ModelMismatch = v.ModelMismatch || u.ModelMismatch |
| 206 | v.Outcome = u.Outcome |
| 207 | v.InputTokens = sum(v.InputTokens, u.InputTokens) |
| 208 | v.OutputTokens = sum(v.OutputTokens, u.OutputTokens) |
| 209 | v.CachedInputTokens = sum(v.CachedInputTokens, u.CachedInputTokens) |
| 210 | v.CacheWriteTokens = sum(v.CacheWriteTokens, u.CacheWriteTokens) |
| 211 | v.ReasoningOutputTokens = sum(v.ReasoningOutputTokens, u.ReasoningOutputTokens) |
| 212 | v.Turns = sum(v.Turns, u.Turns) |
| 213 | v.CostMicros = sum(v.CostMicros, u.CostMicros) |
| 214 | v.CostReportedMicros = sum(v.CostReportedMicros, u.CostReportedMicros) |
| 215 | } |
| 216 | return all |
| 217 | } |
| 218 | |