| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "slices" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/copydesk" |
| 14 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | var copyTools = []any{map[string]any{"name": "submit_review", "description": "Review each changed app string. Return final text and accept, or question only when meaning is ambiguous. Flag uncertain wording while accepting your best version.", "inputSchema": toolSchema(map[string]any{"version": map[string]any{"type": "integer", "enum": []int{1}}, "strings": map[string]any{"type": "array", "maxItems": copydesk.MaxStrings, "items": map[string]any{"type": "object", "properties": map[string]any{"key": str, "text": str, "action": map[string]any{"type": "string", "enum": []string{"accept", "question"}}, "flag": str}, "required": []string{"key", "text", "action"}, "additionalProperties": false}}}, "version", "strings")}} |
| 19 | |
| 20 | func copyUsage(rows []wire.Usage) (int64, bool) { |
| 21 | if len(rows) == 0 { |
| 22 | return 0, false |
| 23 | } |
| 24 | var total int64 |
| 25 | for _, u := range rows { |
| 26 | if !u.Complete || u.InputTokens == nil || u.OutputTokens == nil { |
| 27 | return total, false |
| 28 | } |
| 29 | parts := []*int64{u.InputTokens, u.OutputTokens} |
| 30 | if u.Provider == "claude" { |
| 31 | parts = append(parts, u.CachedInputTokens, u.CacheWriteTokens) |
| 32 | } |
| 33 | for _, v := range parts { |
| 34 | if v != nil { |
| 35 | if *v < 0 { |
| 36 | return total, false |
| 37 | } |
| 38 | total += *v |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | return total, true |
| 43 | } |
| 44 | func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| 45 | rep := judgeReport(r) |
| 46 | fail := func(reason string) wire.StepReport { |
| 47 | rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| 48 | return rep |
| 49 | } |
| 50 | if r.Copy == nil || !copydesk.ShouldRun(copydesk.Delegation{Owner: r.Copy.Owner, Revision: r.Copy.Delegation}, true) || r.Copy.Remaining <= 0 { |
| 51 | return fail("policy_rejected") |
| 52 | } |
| 53 | rep.Copy = &wire.CopyResult{Owner: r.Copy.Owner, Delegation: r.Copy.Delegation, Input: r.CandidateSHA, Compared: r.Copy.Compared, UsageKnown: true, Extraction: copydesk.Extraction{Version: 1}, Review: copydesk.Review{Version: 1}} |
| 54 | if r.Phase == phaseCommitted { |
| 55 | rep.Copy.UsageKnown = false |
| 56 | var raw string |
| 57 | if err := e.O.State.db.QueryRowContext(ctx, "SELECT result FROM copy_attempts WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&raw); err != nil { |
| 58 | return fail("policy_rejected") |
| 59 | } |
| 60 | var saved wire.CopyResult |
| 61 | if json.Unmarshal([]byte(raw), &saved) != nil || saved.Owner != r.Copy.Owner || saved.Delegation != r.Copy.Delegation || saved.Input != r.CandidateSHA || saved.Extraction.Version != 1 || saved.Review.Version != 1 { |
| 62 | return fail("policy_rejected") |
| 63 | } |
| 64 | rep.Copy = &saved |
| 65 | return e.publish(ctx, r, rep) |
| 66 | } |
| 67 | var recoverySignature *copydesk.Signature |
| 68 | if r.Copy.Recovery { |
| 69 | var err error |
| 70 | recoverySignature, err = e.recoveryEvidence(ctx, r) |
| 71 | if err != nil { |
| 72 | rep.LogTail = err.Error() |
| 73 | return fail("policy_rejected") |
| 74 | } |
| 75 | } |
| 76 | tree, reason, err := e.judgeTree(ctx, r) |
| 77 | if err != nil { |
| 78 | return fail(reason) |
| 79 | } |
| 80 | // Keep a committed tree for the existing publication retry mechanism. |
| 81 | defer func() { |
| 82 | if rep.CandidateSHA == r.CandidateSHA { |
| 83 | _ = os.RemoveAll(tree.Dir) |
| 84 | _ = os.RemoveAll(tree.GitDir) |
| 85 | } |
| 86 | }() |
| 87 | if r.Copy.Recovery { |
| 88 | tree, err = e.rebaseCopy(ctx, r, tree) |
| 89 | if err != nil { |
| 90 | rep.LogTail = err.Error() |
| 91 | return fail("policy_rejected") |
| 92 | } |
| 93 | } |
| 94 | w, err := e.prepareCopy(ctx, r, tree) |
| 95 | if w.root != "" { |
| 96 | defer os.RemoveAll(w.root) |
| 97 | } |
| 98 | if err != nil { |
| 99 | return fail("workspace_refused") |
| 100 | } |
| 101 | if r.Copy.Recovery { |
| 102 | if err := e.regenerateCopy(ctx, r, tree, &w); err != nil { |
| 103 | rep.LogTail = err.Error() |
| 104 | return fail("copy_question") |
| 105 | } |
| 106 | } |
| 107 | ex, err := e.copyExtract(ctx, r, w) |
| 108 | if err != nil || ex.Version != 1 || len(ex.Strings) > copydesk.MaxStrings { |
| 109 | return fail("policy_rejected") |
| 110 | } |
| 111 | result := &wire.CopyResult{Suggestions: w.contract == nil, Signature: recoverySignature, Owner: r.Copy.Owner, Delegation: r.Copy.Delegation, Input: r.CandidateSHA, Compared: r.Copy.Compared, Extraction: ex, Review: copydesk.Review{Version: 1, Strings: []copydesk.Wording{}}, UsageKnown: true} |
| 112 | rep.Copy = result |
| 113 | if len(ex.Strings) == 0 && !r.Copy.Recovery { |
| 114 | rep.State, rep.Termination, rep.Pushed = wire.StepDone, true, true |
| 115 | return rep |
| 116 | } |
| 117 | if reviewed, ok := copydesk.ReviewedWords(ex.Strings, r.CandidateSHA, copydesk.Delegation{Owner: r.Copy.Owner, Revision: r.Copy.Delegation}, r.Copy.Records); ok { |
| 118 | result.Review = reviewed |
| 119 | } else if e.reviewCopyBatches(ctx, r, tree, ex, result, &rep, progress) { |
| 120 | return rep |
| 121 | } |
| 122 | |
| 123 | for i, word := range result.Review.Strings { |
| 124 | for _, edit := range r.Copy.Edits { |
| 125 | if word.Key != edit.Key { |
| 126 | continue |
| 127 | } |
| 128 | for _, literal := range ex.Strings { |
| 129 | if literal.Key == edit.Key && literal.Text == edit.Before { |
| 130 | result.Review.Strings[i] = copydesk.Wording{Key: word.Key, Text: edit.After, Action: "accept"} |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | if _, err := copydesk.ValidateReview(ex.Strings, result.Review); err != nil { |
| 136 | return fail("copy_question") |
| 137 | } |
| 138 | if result.Suggestions { |
| 139 | rep.State, rep.Termination, rep.Pushed = wire.StepDone, true, true |
| 140 | return rep |
| 141 | } |
| 142 | for _, word := range result.Review.Strings { |
| 143 | if word.Action == "question" { |
| 144 | rep.Summary = word.Flag |
| 145 | return fail("copy_question") |
| 146 | } |
| 147 | } |
| 148 | if err := e.applyCopy(ctx, r, w, ex, result.Review); err != nil { |
| 149 | return fail("workspace_refused") |
| 150 | } |
| 151 | after, err := copyFiles(filepath.Join(w.root, "candidate")) |
| 152 | if err != nil { |
| 153 | return fail("workspace_refused") |
| 154 | } |
| 155 | bookkeeping := []string{} |
| 156 | if w.contract != nil { |
| 157 | bookkeeping = w.contract.Bookkeeping |
| 158 | } |
| 159 | if err := copydesk.ValidateFiles(w.before, after, ex.Strings, result.Review, bookkeeping, w.contract != nil); err != nil { |
| 160 | return fail("policy_rejected") |
| 161 | } |
| 162 | for path, value := range after { |
| 163 | if err := putCopyFile(tree.Dir, path, value); err != nil { |
| 164 | return fail("workspace_refused") |
| 165 | } |
| 166 | } |
| 167 | if err := e.lease(ctx, r); err != nil { |
| 168 | return fail(leaseReason(err)) |
| 169 | } |
| 170 | sha, err := tree.Commit(ctx, "Review app wording", "Equipo Copy", "copy@equipo.invalid") |
| 171 | if errors.Is(err, workspace.ErrNoChanges) { |
| 172 | rep.State, rep.Termination, rep.Pushed = wire.StepDone, true, true |
| 173 | return rep |
| 174 | } |
| 175 | if err != nil { |
| 176 | return fail("workspace_refused") |
| 177 | } |
| 178 | rawResult, _ := json.Marshal(result) |
| 179 | if _, err := e.O.State.db.ExecContext(ctx, "INSERT INTO copy_attempts(step_id,attempt,result,spent,known) VALUES(?,?,?,?,?) ON CONFLICT(step_id,attempt) DO UPDATE SET result=excluded.result,spent=excluded.spent,known=excluded.known", r.StepID, r.Attempt, string(rawResult), result.Tokens, result.UsageKnown); err != nil { |
| 180 | return fail("provider_failed") |
| 181 | } |
| 182 | publicationBase := r.CandidateSHA |
| 183 | if r.Copy.Recovery { |
| 184 | publicationBase = r.BaseSHA |
| 185 | } |
| 186 | if err := e.O.State.setStepPhase(ctx, r, phaseCommitted, publicationBase, sha); err != nil { |
| 187 | return fail("provider_failed") |
| 188 | } |
| 189 | r.Base, r.Candidate, rep.CandidateSHA = publicationBase, sha, sha |
| 190 | progress(rep) |
| 191 | return e.publish(ctx, r, rep) |
| 192 | } |
| 193 | func (e *Engineer) applyCopy(ctx context.Context, r stepRow, w copyWork, ex copydesk.Extraction, review copydesk.Review) error { |
| 194 | if c := w.contract; c != nil { |
| 195 | if len(ex.Strings) > 0 { |
| 196 | if err := e.copyCommand(ctx, r, w, c.Apply, map[string]any{"candidate": "/workspace/candidate", "extraction": ex, "review": review}, nil); err != nil { |
| 197 | return err |
| 198 | } |
| 199 | keys := []string{} |
| 200 | records := []map[string]any{} |
| 201 | for _, s := range review.Strings { |
| 202 | keys = append(keys, s.Key) |
| 203 | records = append(records, map[string]any{"key": s.Key, "hash": copydesk.Hash(s.Text), "owner": r.Copy.Owner, "revision": r.Copy.Delegation, "candidate": r.CandidateSHA}) |
| 204 | } |
| 205 | if err := e.copyCommand(ctx, r, w, c.Accept, map[string]any{"candidate": "/workspace/candidate", "keys": keys, "changed": keys, "records": records}, nil); err != nil { |
| 206 | return err |
| 207 | } |
| 208 | } |
| 209 | if len(r.Copy.References) > 0 { |
| 210 | if len(c.Reference) == 0 { |
| 211 | return errors.New("copy: no reference command") |
| 212 | } |
| 213 | return e.copyCommand(ctx, r, w, c.Reference, map[string]any{"candidate": "/workspace/candidate", "references": r.Copy.References}, nil) |
| 214 | } |
| 215 | return nil |
| 216 | } |
| 217 | words := map[string]string{} |
| 218 | for _, s := range review.Strings { |
| 219 | words[s.Key] = s.Text |
| 220 | } |
| 221 | files := map[string][]copydesk.Literal{} |
| 222 | for _, s := range ex.Strings { |
| 223 | files[s.Path] = append(files[s.Path], s) |
| 224 | } |
| 225 | for path, locations := range files { |
| 226 | raw := slices.Clone(w.before[path]) |
| 227 | sort.Slice(locations, func(i, j int) bool { return locations[i].Start > locations[j].Start }) |
| 228 | for _, s := range locations { |
| 229 | next := words[s.Key] |
| 230 | if strings.ContainsAny(next, "\"`\\\n\r") { |
| 231 | return errors.New("copy: unsafe generic literal") |
| 232 | } |
| 233 | if s.Start < 0 || s.End < s.Start || s.End > len(raw) { |
| 234 | return errors.New("copy: stale location") |
| 235 | } |
| 236 | raw = append(append(append([]byte{}, raw[:s.Start]...), []byte(next)...), raw[s.End:]...) |
| 237 | } |
| 238 | if err := putCopyFile(filepath.Join(w.root, "candidate"), path, raw); err != nil { |
| 239 | return err |
| 240 | } |
| 241 | } |
| 242 | return nil |
| 243 | } |
| 244 | |