gunk-dev/the-valley

prose.go

source4cbb5ec9c5dbmain's published tip history
16.3 KiB
1// Package prose is _pre-review's prose pass: a model of another family
2// rewrites the prose a change adds, a third fact-checks the rewrite against
3// the change, and the author decides what to apply.
4package prose
5
6import (
7 "bytes"
8 "context"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "io"
13 "os"
14 "os/exec"
15 "path"
16 "path/filepath"
17 "regexp"
18 "sort"
19 "strconv"
20 "strings"
21 "time"
22 "unicode/utf8"
23
24 "the-valley/flow/internal/backend"
25 "the-valley/flow/internal/consult"
26 kgit "the-valley/flow/internal/git"
27 "the-valley/flow/internal/location"
28)
29
30// CommitFile is the file name edits to the head commit's message use.
31const CommitFile = "COMMIT_EDITMSG"
32
33// shortMessage is the length under which a commit message alone isn't worth
34// a rewrite.
35const shortMessage = 200
36
37// Options configure one pass.
38type Options struct {
39 Dir, Base string // the worktree, and the ref the change is diffed against
40 Author backend.Kind
41 Order []string // writer preference
42 Patterns []string // more prose paths, beyond Markdown and READMEs
43 MaxInput int // bytes of diff sent
44 Timeout time.Duration
45 // HouseRules are the operator's house rules, added to both models'
46 // context beside the repository's own writing rules.
47 HouseRules string
48 // Writer and Checker give the model and effort the writer and the fact
49 // checker run at on a backend.
50 Writer, Checker func(backend.Kind) (model, effort string)
51 // Started, if set, is called when the writer is about to be asked.
52 Started func(*Result)
53}
54
55// Claim is one ledger entry: a claim a passage makes and the conditions it
56// holds under.
57type Claim struct {
58 ID string `json:"id"`
59 Where string `json:"where"`
60 Claim string `json:"claim"`
61 Conditions []string `json:"conditions,omitempty"`
62}
63
64// Edit replaces Old, text the change added to File, with New.
65type Edit struct {
66 File string `json:"file"`
67 Old string `json:"old"`
68 New string `json:"new"`
69 Claims []string `json:"claims,omitempty"`
70 // Skipped says why klaus left the edit out of the patch, unchecked.
71 Skipped string `json:"skipped,omitempty"`
72 // Outcome is applied or rejected, judged from the worktree when the run
73 // finalizes.
74 Outcome string `json:"outcome,omitempty"`
75}
76
77// Failure is a fact-check finding against edit number Edit (1-based).
78type Failure struct {
79 Edit int `json:"edit"`
80 Claim string `json:"claim,omitempty"`
81 Problem string `json:"problem"`
82}
83
84// Result is what a pass found; it is also the job record's prose.
85type Result struct {
86 Skipped string `json:"skipped,omitempty"` // why no rewrite was asked for
87 Files []string `json:"files,omitempty"`
88 Omitted []string `json:"omitted,omitempty"` // prose files over the input limit
89 Writer string `json:"writer,omitempty"`
90 WriterModel string `json:"writer_model,omitempty"`
91 Checker string `json:"checker,omitempty"`
92 CheckerModel string `json:"checker_model,omitempty"`
93 Error string `json:"error,omitempty"` // the rewrite failed
94 CheckError string `json:"check_error,omitempty"` // the fact check failed
95 Ledger []Claim `json:"ledger,omitempty"`
96 Edits []Edit `json:"edits,omitempty"`
97 Failures []Failure `json:"failures,omitempty"`
98 Patch string `json:"-"` // the edits that passed, as a diff git apply takes
99 Message string `json:"-"` // the commit message with its passing edits
100 PatchFile string `json:"patch_file,omitempty"`
101 MessageFile string `json:"message_file,omitempty"`
102}
103
104// Failed reports whether the fact check failed edit i (0-based). A failure
105// that names no edit fails them all.
106func (r *Result) Failed(i int) bool {
107 for _, f := range r.Failures {
108 if f.Edit == i+1 || f.Edit < 1 || f.Edit > len(r.Edits) {
109 return true
110 }
111 }
112 return false
113}
114
115// Passed reports whether edit i passed the fact check, so goes in the patch.
116func (r *Result) Passed(i int) bool {
117 return r.Edits[i].Skipped == "" && r.CheckError == "" && !r.Failed(i)
118}
119
120// input is the prose a change adds.
121type input struct {
122 diff string // prose hunks with context
123 added map[string]map[int]bool // file → the line numbers it adds
124 message string // head commit message; "" when the change has no commit
125}
126
127// Choose picks the writer, the first installed family in order that isn't
128// the author's, and the checker, the next one, else the author's. ok is
129// false when there is no writer.
130func Choose(order []string, author backend.Kind, installed func(string) bool) (writer, checker backend.Kind, ok bool) {
131 var others []backend.Kind
132 for _, name := range order {
133 k, err := backend.Parse(name)
134 if err != nil || name == "" || k == author || contains(others, k) || !installed(name) {
135 continue
136 }
137 others = append(others, k)
138 }
139 switch len(others) {
140 case 0:
141 return "", "", false
142 case 1:
143 return others[0], author, true
144 }
145 return others[0], others[1], true
146}
147
148func contains(ks []backend.Kind, k backend.Kind) bool {
149 for _, x := range ks {
150 if x == k {
151 return true
152 }
153 }
154 return false
155}
156
157// Run runs a pass. Its failures are in the result, never returned: the pass
158// must not stop _pre-review.
159func Run(ctx context.Context, o Options) *Result {
160 r := &Result{}
161 in, err := collect(ctx, o, r)
162 if err != nil {
163 r.Error = "reading the change: " + err.Error()
164 return r
165 }
166 if len(r.Files) == 0 && len(strings.TrimSpace(in.message)) < shortMessage {
167 r.Skipped = "no prose beyond a short commit message"
168 return r
169 }
170 writer, checker, ok := Choose(o.Order, o.Author, func(name string) bool { _, err := consult.LookupBinary(name); return err == nil })
171 if !ok {
172 r.Skipped = "no model family other than the author's (" + string(o.Author) + ") is installed"
173 return r
174 }
175 r.Writer, r.Checker = string(writer), string(checker)
176 var wEffort, cEffort string
177 if o.Writer != nil {
178 r.WriterModel, wEffort = o.Writer(writer)
179 }
180 if o.Checker != nil {
181 r.CheckerModel, cEffort = o.Checker(checker)
182 }
183
184 if o.Started != nil {
185 o.Started(r)
186 }
187 answer, err := ask(ctx, o, writer, r.WriterModel, wEffort, writerRole, rewritePrompt(o.Dir, in))
188 if err != nil {
189 r.Error = err.Error()
190 return r
191 }
192 var p struct {
193 Ledger []Claim `json:"ledger"`
194 Edits []Edit `json:"edits"`
195 }
196 if err := decodeJSON(answer, "edits", &p); err != nil {
197 r.Error = fmt.Sprintf("%s's rewrite: %v", writer, err)
198 return r
199 }
200 r.Ledger, r.Edits = p.Ledger, p.Edits
201 for i := range r.Edits {
202 r.Edits[i].Outcome = ""
203 r.Edits[i].Skipped = validate(o.Dir, in, r.Edits[i])
204 }
205
206 if checkable := checkPrompt(in, r); checkable != "" {
207 answer, err := ask(ctx, o, checker, r.CheckerModel, cEffort, checkerRole, checkable)
208 var c struct {
209 Failures []Failure `json:"failures"`
210 }
211 if err == nil {
212 err = decodeJSON(answer, "failures", &c)
213 }
214 if err != nil {
215 r.CheckError = err.Error()
216 }
217 r.Failures = c.Failures
218 }
219 r.Patch, r.Message = build(o.Dir, in, r)
220 return r
221}
222
223// collect reads the change's prose: the hunks of the prose files it changes,
224// as many whole files as fit in o.MaxInput, and its head commit message.
225func collect(ctx context.Context, o Options, r *Result) (*input, error) {
226 in := &input{added: map[string]map[int]bool{}}
227 names, err := git(ctx, o.Dir, "diff", "--name-only", "-z", "--diff-filter=AM", "--no-renames", o.Base+"...HEAD")
228 if err != nil {
229 return nil, err
230 }
231 var diff strings.Builder
232 for _, name := range strings.Split(names, "\x00") {
233 if name == "" || !IsProse(name, o.Patterns) {
234 continue
235 }
236 hunks, err := git(ctx, o.Dir, "diff", "-U8", "--no-color", "--no-ext-diff", "--no-textconv", o.Base+"...HEAD", "--", ":(literal)"+name)
237 if err != nil {
238 return nil, err
239 }
240 hunks = kgit.TextDiff(ctx, o.Dir, hunks)
241 if diff.Len()+len(hunks) > o.MaxInput {
242 r.Omitted = append(r.Omitted, name)
243 continue
244 }
245 diff.WriteString(hunks)
246 r.Files = append(r.Files, name)
247 in.added[name] = addedLines(hunks)
248 }
249 in.diff = diff.String()
250 if n, err := git(ctx, o.Dir, "rev-list", "--count", o.Base+"..HEAD"); err == nil && strings.TrimSpace(n) != "0" {
251 // A message that isn't valid UTF-8 isn't text to rewrite, and the
252 // CLIs refuse it.
253 if msg, err := git(ctx, o.Dir, "log", "-1", "--format=%B"); err == nil && len(msg) > o.MaxInput {
254 r.Omitted = append(r.Omitted, "commit message")
255 } else if err == nil && utf8.ValidString(msg) {
256 in.message = strings.TrimSpace(msg)
257 in.added[CommitFile] = map[int]bool{}
258 for n := range strings.Split(in.message, "\n") {
259 in.added[CommitFile][n+1] = true
260 }
261 }
262 }
263 return in, nil
264}
265
266// IsProse reports whether a changed file's added lines are prose: Markdown,
267// a README, or a match for one of patterns. A pattern with no slash matches
268// a file's name in any directory; a pattern ending in /** matches everything
269// under a directory.
270func IsProse(name string, patterns []string) bool {
271 base := path.Base(name)
272 ext := strings.ToLower(path.Ext(name))
273 if ext == ".md" || ext == ".markdown" || strings.HasPrefix(strings.ToUpper(base), "README") {
274 return true
275 }
276 for _, p := range patterns {
277 if dir, ok := strings.CutSuffix(p, "/**"); ok && strings.HasPrefix(name, dir+"/") {
278 return true
279 }
280 target := name
281 if !strings.Contains(p, "/") {
282 target = base
283 }
284 if ok, _ := path.Match(p, target); ok {
285 return true
286 }
287 }
288 return false
289}
290
291var hunkStart = regexp.MustCompile(`^@@ -\d+(?:,\d+)? \+(\d+)`)
292
293// addedLines is the line numbers a file's diff adds.
294func addedLines(diff string) map[int]bool {
295 added := map[int]bool{}
296 line := 0 // the next new-side line; 0 in the header
297 for _, l := range strings.Split(diff, "\n") {
298 switch {
299 case strings.HasPrefix(l, "@@"):
300 if m := hunkStart.FindStringSubmatch(l); m != nil {
301 line, _ = strconv.Atoi(m[1])
302 }
303 case line == 0, strings.HasPrefix(l, "-"), strings.HasPrefix(l, `\`):
304 case strings.HasPrefix(l, "+"):
305 added[line] = true
306 line++
307 default:
308 line++
309 }
310 }
311 return added
312}
313
314// validate says why an edit can't go in the patch, or "".
315func validate(dir string, in *input, e Edit) string {
316 added, ok := in.added[e.File]
317 switch {
318 case !ok:
319 return "not prose this change adds"
320 case e.Old == "" || e.Old == e.New:
321 return "no change"
322 }
323 text, err := current(dir, in, e.File)
324 if err != nil {
325 return err.Error()
326 }
327 if strings.Count(text, e.Old) != 1 {
328 return "its old text isn't in the file exactly once"
329 }
330 first := strings.Count(text[:strings.Index(text, e.Old)], "\n") + 1
331 for n, l := range strings.Split(e.Old, "\n") {
332 if strings.TrimSpace(l) != "" && !added[first+n] {
333 return "it rewrites text the change didn't add"
334 }
335 }
336 return ""
337}
338
339// current is a file's text in the worktree, or the commit message.
340func current(dir string, in *input, file string) (string, error) {
341 if file == CommitFile {
342 return in.message, nil
343 }
344 data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(file)))
345 return string(data), err
346}
347
348// build applies the passing edits to the original text: the files' as a
349// patch, the commit message's to the message. An edit that overlaps an
350// earlier one in its file is marked skipped.
351func build(dir string, in *input, r *Result) (patch, message string) {
352 type span struct{ edit, start, end int }
353 spans := map[string][]span{}
354 origs := map[string]string{}
355 var order []string
356 for i, e := range r.Edits {
357 if !r.Passed(i) {
358 continue
359 }
360 if _, ok := origs[e.File]; !ok {
361 text, err := current(dir, in, e.File)
362 if err != nil {
363 r.Edits[i].Skipped = err.Error()
364 continue
365 }
366 origs[e.File] = text
367 order = append(order, e.File)
368 }
369 at := strings.Index(origs[e.File], e.Old)
370 spans[e.File] = append(spans[e.File], span{i, at, at + len(e.Old)})
371 }
372 var b strings.Builder
373 for _, file := range order {
374 ss, orig := spans[file], origs[file]
375 sort.Slice(ss, func(a, b int) bool { return ss[a].start < ss[b].start })
376 var text strings.Builder
377 pos := 0
378 for _, sp := range ss {
379 if sp.start < pos {
380 r.Edits[sp.edit].Skipped = "an earlier rewrite overlaps it"
381 continue
382 }
383 text.WriteString(orig[pos:sp.start] + r.Edits[sp.edit].New)
384 pos = sp.end
385 }
386 text.WriteString(orig[pos:])
387 if file == CommitFile {
388 message = text.String() + "\n"
389 continue
390 }
391 d, err := diffFile(file, orig, text.String())
392 if err != nil {
393 for _, sp := range ss {
394 r.Edits[sp.edit].Skipped = "building the patch: " + err.Error()
395 }
396 continue
397 }
398 b.WriteString(d)
399 }
400 return b.String(), message
401}
402
403// diffFile is a git-style diff of file from old to new, for git apply.
404func diffFile(file, old, new string) (string, error) {
405 tmp, err := os.MkdirTemp("", location.TempPattern("prose-"))
406 if err != nil {
407 return "", err
408 }
409 defer os.RemoveAll(tmp)
410 for side, text := range map[string]string{"a": old, "b": new} {
411 p := filepath.Join(tmp, side, filepath.FromSlash(file))
412 if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
413 return "", err
414 }
415 if err := os.WriteFile(p, []byte(text), 0o600); err != nil {
416 return "", err
417 }
418 }
419 cmd := exec.Command("git", "diff", "--no-index", "--no-prefix", "--no-color", "--no-ext-diff", "a/"+file, "b/"+file)
420 cmd.Dir = tmp
421 out, err := cmd.Output()
422 var exit *exec.ExitError
423 if errors.As(err, &exit) && exit.ExitCode() == 1 { // 1: the files differ
424 err = nil
425 }
426 return string(out), err
427}
428
429// Settle records whether each of a pass's edits was applied, judged from
430// the worktree dir: applied when the file, or the head commit's message,
431// holds its new text and not its old.
432func Settle(dir string, r *Result) {
433 msg, _ := git(context.Background(), dir, "log", "-1", "--format=%B")
434 for i, e := range r.Edits {
435 if e.Skipped != "" || e.Outcome != "" {
436 continue
437 }
438 text := msg
439 if e.File != CommitFile {
440 data, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(e.File)))
441 if err != nil {
442 continue
443 }
444 text = string(data)
445 }
446 applied := strings.Contains(text, strings.TrimSpace(e.New))
447 if !strings.Contains(e.New, e.Old) && strings.Contains(text, e.Old) {
448 applied = false // the old passage is still there
449 }
450 r.Edits[i].Outcome = "rejected"
451 if applied {
452 r.Edits[i].Outcome = "applied"
453 }
454 }
455}
456
457func ask(ctx context.Context, o Options, kind backend.Kind, model, effort, role, prompt string) (string, error) {
458 ctx, cancel := context.WithTimeout(ctx, o.Timeout)
459 defer cancel()
460 t := &consult.Thread{Backend: kind, Model: model, Effort: effort, Role: role, Dir: o.Dir, HouseRules: o.HouseRules}
461 res, err := consult.Ask(ctx, t, prompt, false, "", io.Discard, io.Discard)
462 if err != nil {
463 if s := lastLine(res.Stderr); s != "" {
464 err = fmt.Errorf("%w: %s", err, s)
465 }
466 return "", err
467 }
468 return res.Answer, nil
469}
470
471func lastLine(s string) string {
472 lines := strings.Split(strings.TrimSpace(s), "\n")
473 l := strings.TrimSpace(lines[len(lines)-1])
474 return kgit.TruncateText(l, 200)
475}
476
477// decodeJSON reads the first JSON object with key in a model's answer,
478// which may wrap it in fences or prose.
479func decodeJSON(text, key string, v any) error {
480 for i := strings.IndexByte(text, '{'); i >= 0; {
481 dec := json.NewDecoder(strings.NewReader(text[i:]))
482 var probe map[string]json.RawMessage
483 if dec.Decode(&probe) == nil && probe[key] != nil {
484 return json.Unmarshal([]byte(text[i:i+int(dec.InputOffset())]), v)
485 }
486 next := strings.IndexByte(text[i+1:], '{')
487 if next < 0 {
488 break
489 }
490 i += 1 + next
491 }
492 return fmt.Errorf("no JSON object with %q in the answer", key)
493}
494
495func git(ctx context.Context, dir string, args ...string) (string, error) {
496 cmd := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...)
497 var stderr bytes.Buffer
498 cmd.Stderr = &stderr
499 out, err := cmd.Output()
500 if err != nil {
501 return "", fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.String()))
502 }
503 return string(out), nil
504}
505
506var writingHeading = regexp.MustCompile(`(?i)^#+ .*(writ|prose|style|doc)`)
507
508// Rules are the sections on writing of the repo's AGENTS.md and CLAUDE.md:
509// those whose heading names writing, prose, style or docs.
510func Rules(dir string) string {
511 var b strings.Builder
512 for _, name := range []string{"AGENTS.md", "CLAUDE.md"} {
513 data, err := os.ReadFile(filepath.Join(dir, name))
514 if err != nil {
515 continue
516 }
517 level := 0 // the heading level of the section being kept; 0 when none
518 for _, l := range strings.Split(string(data), "\n") {
519 if h := len(l) - len(strings.TrimLeft(l, "#")); h > 0 && strings.HasPrefix(l[h:], " ") {
520 switch {
521 case writingHeading.MatchString(l) && (level == 0 || h <= level):
522 level = h
523 case level > 0 && h <= level:
524 level = 0
525 }
526 }
527 if level > 0 {
528 b.WriteString(l + "\n")
529 }
530 }
531 }
532 return kgit.TruncateText(b.String(), 8000)
533}