gunk-dev/the-valley

prose.go

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