diff --git a/pkg/cli/intents.go b/pkg/cli/intents.go index 914d400..2610843 100644 --- a/pkg/cli/intents.go +++ b/pkg/cli/intents.go @@ -214,6 +214,12 @@ type PlanConfig struct { // settled, and the decision label no longer parks the issue: the human // it was waiting for has decided. Nil adds nothing. MaintainerDecisions map[int32]string + // ContextBytes bounds the file contents in a prompt: the files the issue + // names come first, and the tracked files ranked most related to the + // issue fill what they leave. Zero adds no ranked files. + ContextBytes int + // ContextFiles caps how many ranked files a prompt holds. Zero adds none. + ContextFiles int } // PlanIssues asks the planner for an intent for each issue, writes each @@ -305,6 +311,7 @@ func (p planner) planOne(ctx context.Context, issue int32) (*QueueItem, []string return nil, nil, p.park(issue, ParkNeedsDecision, reason, nil) } comments, omitted := trustedComments(d.Comments, p.cfg.TrustedCommenters) + named := namedFileContents(p.listing.Root, p.listing.Files, d.Body) prompt := buildIntentPrompt(intentPromptInput{ Issue: issue, Title: d.Title, @@ -312,7 +319,8 @@ func (p planner) planOne(ctx context.Context, issue int32) (*QueueItem, []string Comments: comments, OmittedComments: omitted, Files: p.listing.Files, - Named: namedFileContents(p.listing.Root, p.listing.Files, d.Body), + Named: named, + Related: p.relatedFiles(d, named), Rules: p.cfg.Rules, BashTimeoutSeconds: p.cfg.BashTimeoutSeconds, MaintainerDecision: decided, @@ -364,6 +372,18 @@ func (p planner) planOne(ctx context.Context, issue int32) (*QueueItem, []string return &QueueItem{Issue: issue, IntentPath: intentPath, Lane: lane}, v.Files, nil } +// relatedFiles ranks the tracked files against the issue and returns the +// most related ones the named files leave room for. +func (p planner) relatedFiles(d IssueDetail, named []namedFile) []namedFile { + budget := p.cfg.ContextBytes + skip := make(map[string]bool, len(named)) + for _, f := range named { + skip[f.Path] = true + budget -= len(f.Content) + } + return relatedFileContents(p.listing.Root, p.listing.Files, d.Title, d.Body, skip, budget, p.cfg.ContextFiles) +} + // trustedComments keeps the comments by a trusted login and counts the rest. // No trusted logins means every comment is kept. func trustedComments(cs []IssueComment, trusted []string) ([]IssueComment, int) { @@ -651,6 +671,8 @@ type intentsOptions struct { trustedCommenters string decisionLabel string bashTimeout int + contextBytes int + contextFiles int } func newIntentsCommand() *cobra.Command { @@ -662,7 +684,9 @@ func newIntentsCommand() *cobra.Command { intents and a queue for 'meitheal run'. For each issue the planner reads the title, body and comments, the files -tracked in --repo-dir, and the contents of the files the issue names. It +tracked in --repo-dir, the contents of the files the issue names, and the +contents of the tracked files that share the most words with the issue +(--context-files of them, within --context-bytes with the named files). It either writes an intent or hands the issue to a human: an issue it cannot plan, labelled --decision-label, or whose answer cannot be read is parked as a decision under --decisions-dir for 'meitheal decisions', and is never put @@ -722,6 +746,12 @@ func addPlannerFlags(f *pflag.FlagSet, o *intentsOptions, need string) { "Issue label that parks an issue for a human without calling the planner; empty disables") f.IntVar(&o.bashTimeout, "bash-timeout-seconds", defaultBashTimeoutSeconds, "The coder's bash time limit, stated to the planner") + f.IntVar(&o.contextBytes, "context-bytes", defaultContextBytes, + "Bytes of file contents given to the planner: the files the issue names, then the tracked files "+ + "most related to it; 0 adds no related files") + f.IntVar(&o.contextFiles, "context-files", defaultContextFiles, + "Most related files (ranked against the issue, not named by it) whose contents the planner gets; "+ + "0 adds none") } // plannerSetup checks the planner flags and builds the PlanConfig and the @@ -740,10 +770,18 @@ func (o *intentsOptions) plannerSetup(progress io.Writer) (PlanConfig, PlannerCa if o.plannerTimeout <= 0 { return PlanConfig{}, nil, fmt.Errorf("--planner-timeout must be greater than 0, got %s", o.plannerTimeout) } + if o.contextBytes < 0 { + return PlanConfig{}, nil, fmt.Errorf("--context-bytes must not be negative, got %d", o.contextBytes) + } + if o.contextFiles < 0 { + return PlanConfig{}, nil, fmt.Errorf("--context-files must not be negative, got %d", o.contextFiles) + } cfg := PlanConfig{ DecisionLabel: o.decisionLabel, GPULabels: splitList(o.gpuLabels), GPUPaths: splitList(o.gpuPaths), + ContextBytes: o.contextBytes, + ContextFiles: o.contextFiles, TrustedCommenters: splitList(o.trustedCommenters), BashTimeoutSeconds: o.bashTimeout, Progress: progress, diff --git a/pkg/cli/intents_context.go b/pkg/cli/intents_context.go new file mode 100644 index 0000000..5efe34c --- /dev/null +++ b/pkg/cli/intents_context.go @@ -0,0 +1,311 @@ +/* +Copyright 2026. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "bytes" + "math" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + "unicode" +) + +// The planner has no tools, so the only file contents it sees are the ones in +// its prompt. Besides the files the issue names, it gets the tracked files +// that share the most words with the issue, ranked by a deterministic scorer: +// the same checkout and issue always give the same files. +// +// pkg/agent/repomap is not reused: it indexes only non-test Go files, ranks +// them by their Go declarations and walks the file system rather than the +// tracked list, while an issue here may be about documentation, configuration +// or any language. +// +// The score is BM25 (k1 1.2, b 0.75) over the words of the first +// scoreReadCap bytes of each tracked text file, plus pathTermBoost times a +// term's IDF when the term is a word of the file's path. Words are split +// at non-alphanumerics and camelCase boundaries and lowercased; -ies and -ied +// fold to -y and a plural -s is dropped. A word is kept when three or more +// characters long and not English filler. A title word counts twice. Ties +// break by path. + +const ( + // defaultContextBytes is the --context-bytes default: the budget for + // the contents of the named and the ranked files together. + defaultContextBytes = 64 * 1024 + // defaultContextFiles is the --context-files default. + defaultContextFiles = 6 + // relatedFileCap bounds one ranked file, so a long one cannot take the + // whole budget; a longer file is cut there and marked. + relatedFileCap = 16 * 1024 + // scoreReadCap is how much of each file the scorer reads. + scoreReadCap = 64 * 1024 + // scoreSizeLimit skips larger files entirely: they are data, not prose + // or code a planner reads. + scoreSizeLimit = 1 << 20 + // minRelativeScore drops a file scoring under this fraction of the top + // file: an incidental match is not related. + minRelativeScore = 0.25 + pathTermBoost = 2.0 + titleTermWeight = 2.0 + bm25K1 = 1.2 + bm25B = 0.75 +) + +// unrankedFiles are tracked files never worth ranking: lockfiles match every +// dependency name an issue mentions and say nothing about the change. +var unrankedFiles = map[string]bool{ + "go.sum": true, "Cargo.lock": true, "package-lock.json": true, "yarn.lock": true, + "pnpm-lock.yaml": true, "poetry.lock": true, "uv.lock": true, "Gemfile.lock": true, + "composer.lock": true, "flake.lock": true, +} + +// unrankedDirs are directories of vendored code, never ranked. +var unrankedDirs = map[string]bool{"vendor": true, "node_modules": true} + +// rankedDoc is one scored file's statistics for the query's terms. +type rankedDoc struct { + path string + length int + tf map[string]int + inPath map[string]bool + score float64 +} + +// relatedFileContents returns the tracked files most related to the issue's +// title and body, best first, skipping the paths in skip (the files the +// issue names). At most maxFiles are returned and their contents total at +// most budget bytes; each is capped at relatedFileCap and marked when cut. +// Binary files and anything readRegularFileInside refuses (symlinks, files +// outside root) are never ranked. +func relatedFileContents(root string, files []string, title, body string, skip map[string]bool, + budget, maxFiles int) []namedFile { + if budget <= 0 || maxFiles <= 0 { + return nil + } + query := queryTerms(title, body) + if len(query) == 0 { + return nil + } + docs := scanDocs(root, files, skip, query) + ranked := rankDocs(docs, query) + + var out []namedFile + for _, d := range ranked { + if len(out) >= maxFiles || budget <= 0 { + break + } + b, ok := readRegularFileInside(root, d.path) + if !ok || bytes.IndexByte(b, 0) >= 0 { + continue + } + limit := min(relatedFileCap, budget) + nf := namedFile{Path: d.path, Content: string(b)} + if len(b) > limit { + nf.Content, nf.Truncated = cutUTF8(string(b), limit), true + } + budget -= len(nf.Content) + out = append(out, nf) + } + return out +} + +// scanDocs reads the head of every rankable tracked file and counts the +// query's terms in it. +func scanDocs(root string, files []string, skip map[string]bool, query map[string]float64) []rankedDoc { + var docs []rankedDoc + for _, f := range files { + if skip[f] || !rankable(f) { + continue + } + fi, err := os.Lstat(filepath.Join(root, filepath.FromSlash(f))) + if err != nil || !fi.Mode().IsRegular() || fi.Size() > scoreSizeLimit { + continue + } + b, ok := readRegularFileInside(root, f) + if !ok { + continue + } + if len(b) > scoreReadCap { + b = b[:scoreReadCap] + } + if bytes.IndexByte(b, 0) >= 0 { + continue + } + d := rankedDoc{path: f, tf: map[string]int{}, inPath: map[string]bool{}} + eachTerm(string(b), func(t string) { + d.length++ + if query[t] > 0 { + d.tf[t]++ + } + }) + eachTerm(f, func(t string) { + if query[t] > 0 { + d.inPath[t] = true + } + }) + docs = append(docs, d) + } + return docs +} + +// rankDocs scores docs against the query and returns the related ones, best +// first. +func rankDocs(docs []rankedDoc, query map[string]float64) []rankedDoc { + if len(docs) == 0 { + return nil + } + df := map[string]int{} + total := 0 + for _, d := range docs { + total += d.length + for t := range query { + if d.tf[t] > 0 || d.inPath[t] { + df[t]++ + } + } + } + n := float64(len(docs)) + avg := math.Max(float64(total)/n, 1) + for i := range docs { + d := &docs[i] + norm := bm25K1 * (1 - bm25B + bm25B*float64(d.length)/avg) + for t, w := range query { + if df[t] == 0 { + continue + } + idf := math.Log(1 + (n-float64(df[t])+0.5)/(float64(df[t])+0.5)) + tf := float64(d.tf[t]) + s := idf * tf * (bm25K1 + 1) / (tf + norm) + if d.inPath[t] { + s += pathTermBoost * idf + } + d.score += w * s + } + } + sort.SliceStable(docs, func(i, j int) bool { + if docs[i].score != docs[j].score { + return docs[i].score > docs[j].score + } + return docs[i].path < docs[j].path + }) + if docs[0].score <= 0 { + return nil + } + cut := docs[0].score * minRelativeScore + end := sort.Search(len(docs), func(i int) bool { return docs[i].score < cut || docs[i].score <= 0 }) + return docs[:end] +} + +// rankable reports whether a tracked path may be ranked at all. +func rankable(f string) bool { + if unrankedFiles[path.Base(f)] { + return false + } + for _, seg := range strings.Split(path.Dir(f), "/") { + if unrankedDirs[seg] { + return false + } + } + return true +} + +// queryTerms weighs the issue's terms: a title term counts titleTermWeight, +// a body term 1. +func queryTerms(title, body string) map[string]float64 { + q := map[string]float64{} + eachTerm(body, func(t string) { q[t] = 1 }) + eachTerm(title, func(t string) { q[t] = titleTermWeight }) + return q +} + +// wordRE matches the alphanumeric runs terms are cut from. +var wordRE = regexp.MustCompile(`[A-Za-z0-9]+`) + +// eachTerm calls fn for each term of s, in order: every camelCase part of a +// word, and the whole word when it has more than one part, so +// "ParsePlanVerdict" gives parse, plan, verdict and parseplanverdict. +func eachTerm(s string, fn func(string)) { + for _, w := range wordRE.FindAllString(s, -1) { + parts := camelParts(w) + for _, p := range parts { + if t, ok := normTerm(p); ok { + fn(t) + } + } + if len(parts) > 1 { + if t, ok := normTerm(w); ok { + fn(t) + } + } + } +} + +// camelParts splits a word at lower-to-upper and acronym-to-word +// boundaries: "HTTPServerConfig" gives HTTP, Server, Config. +func camelParts(w string) []string { + r := []rune(w) + var parts []string + start := 0 + for i := 1; i < len(r); i++ { + lowerToUpper := unicode.IsLower(r[i-1]) && unicode.IsUpper(r[i]) + acronymEnd := i+1 < len(r) && unicode.IsUpper(r[i-1]) && unicode.IsUpper(r[i]) && unicode.IsLower(r[i+1]) + if lowerToUpper || acronymEnd { + parts = append(parts, string(r[start:i])) + start = i + } + } + return append(parts, string(r[start:])) +} + +// normTerm lowercases a word part and folds the endings that most often +// split one word in two ("retries", "retried" and "retry"; "attempts" and +// "attempt"); it refuses short parts, numbers and English filler. +func normTerm(p string) (string, bool) { + t := strings.ToLower(p) + switch { + case len(t) > 4 && (strings.HasSuffix(t, "ies") || strings.HasSuffix(t, "ied")): + t = t[:len(t)-3] + "y" + case len(t) > 4 && strings.HasSuffix(t, "s") && !strings.HasSuffix(t, "ss"): + t = t[:len(t)-1] + } + if len(t) < 3 || stopTerms[t] || strings.Trim(t, "0123456789") == "" { + return "", false + } + return t, true +} + +// stopTerms are English filler words, which would reward any prose file. +var stopTerms = func() map[string]bool { + m := map[string]bool{} + for _, w := range strings.Fields(` + about above after again against all also and any are aren because been before being + below between both but can cannot could did does doing done down during each + either else even ever every few for from further get gets had has have having her + here hers him his how however into its itself just let like may might more most + much must need needs nor not now off once one only onto other our ours out over own + per same she should since some such than that the their theirs them then there + these they this those through too two under until upon use used uses using very via + was wasn were what when where whether which while who whom whose why will with + within without would yet you your yours`) { + m[w] = true + } + return m +}() diff --git a/pkg/cli/intents_context_test.go b/pkg/cli/intents_context_test.go new file mode 100644 index 0000000..14e9173 --- /dev/null +++ b/pkg/cli/intents_context_test.go @@ -0,0 +1,353 @@ +/* +Copyright 2026. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" +) + +// contextFixture is a repository with two files about webhook retries and +// several that are not, including a binary and a symlink that mention the +// topic and must never be read. +func contextFixture(t *testing.T) repoListing { + t.Helper() + dir := gitRepo(t, map[string]string{ + "docs/retries.md": "# Webhook retries\n\nA failed webhook delivery is retried with exponential backoff.\n" + + "The backoff doubles after each attempt, up to the retry cap.\n", + "pkg/retry/backoff.go": "package retry\n\n// Backoff returns the delay before retry attempt n of a webhook\n" + + "// delivery: exponential, capped at MaxBackoff.\nfunc Backoff(n int) int { return n }\n", + // One incidental match: well under the topic files' score. + "docs/install.md": "# Install\n\nDownload the release, then start the service with the install script.\n" + + "If the download fails, the script retries once. Then check the service is up and serving requests.\n", + "pkg/metrics/prom.go": "package metrics\n\n// Register adds the Prometheus collectors to the registry.\n" + + "func Register() {}\n", + "README.md": "# widgets\n\nA small service. See docs/install.md to get started.\n", + "go.sum": "example.com/webhook/retry/backoff v1.0.0 h1:abc=\n", + "vendor/example.com/retry/backoff.go": "package retry\n\n// Webhook retry backoff, exponential, capped.\n" + + "func Backoff() {}\n", + "assets/logo.png": "PNG\x00webhook retries exponential backoff\x00", + }) + if err := os.Symlink("retries.md", filepath.Join(dir, "docs", "retries-link.md")); err != nil { + t.Fatal(err) + } + gitAdd(t, dir, "docs/retries-link.md") + listing, err := repoFiles(dir) + if err != nil { + t.Fatal(err) + } + return listing +} + +func gitAdd(t *testing.T, dir string, paths ...string) { + t.Helper() + out, err := gitOutput(dir, append([]string{"add", "--"}, paths...)...) + if err != nil { + t.Fatalf("git add: %v\n%s", err, out) + } +} + +func relatedPaths(fs []namedFile) []string { + out := make([]string, 0, len(fs)) + for _, f := range fs { + out = append(out, f.Path) + } + return out +} + +const ( + retryTitle = "Webhook retry backoff grows too fast" + retryBody = "Failed deliveries are retried with an exponential backoff that reaches the cap after two attempts." +) + +func TestRelatedFiles_RanksTheIssueTopic(t *testing.T) { + l := contextFixture(t) + got := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, defaultContextBytes, defaultContextFiles) + paths := relatedPaths(got) + slices.Sort(paths) + if want := []string{"docs/retries.md", "pkg/retry/backoff.go"}; !reflect.DeepEqual(paths, want) { + t.Fatalf("related = %v, want %v", paths, want) + } + for _, f := range got { + if f.Path == "docs/retries.md" && (!strings.Contains(f.Content, "doubles after each attempt") || f.Truncated) { + t.Fatalf("docs/retries.md content = %q truncated=%v", f.Content, f.Truncated) + } + } + again := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, defaultContextBytes, defaultContextFiles) + if !reflect.DeepEqual(got, again) { + t.Fatal("ranking is not deterministic") + } +} + +// A different topic in the same repository pulls in its own files. +func TestRelatedFiles_FollowsTheTopic(t *testing.T) { + l := contextFixture(t) + got := relatedPaths(relatedFileContents(l.Root, l.Files, "Install script fails", + "Starting the service after download fails.", nil, defaultContextBytes, defaultContextFiles)) + if len(got) == 0 || got[0] != "docs/install.md" { + t.Fatalf("related = %v, want docs/install.md first", got) + } + for _, p := range got { + if strings.Contains(p, "retry") || strings.Contains(p, "retries") || p == "pkg/metrics/prom.go" { + t.Errorf("related holds %s, which is not about installing", p) + } + } +} + +func TestRelatedFiles_SkipsNamedFilesAndRespectsLimits(t *testing.T) { + l := contextFixture(t) + skip := map[string]bool{"docs/retries.md": true} + got := relatedPaths(relatedFileContents(l.Root, l.Files, retryTitle, retryBody, skip, + defaultContextBytes, defaultContextFiles)) + if !reflect.DeepEqual(got, []string{"pkg/retry/backoff.go"}) { + t.Fatalf("related = %v, want the named file skipped", got) + } + + one := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, defaultContextBytes, 1) + if len(one) != 1 { + t.Fatalf("got %d files with a limit of 1", len(one)) + } + + const budget = 40 + cut := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, budget, defaultContextFiles) + total := 0 + for _, f := range cut { + total += len(f.Content) + } + if len(cut) != 1 || total != budget || !cut[0].Truncated { + t.Fatalf("with a %d-byte budget: %d files, %d bytes, truncated=%v", budget, len(cut), total, + len(cut) > 0 && cut[0].Truncated) + } + + for _, limits := range [][2]int{{0, defaultContextFiles}, {defaultContextBytes, 0}, {-1, 1}} { + if got := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, limits[0], limits[1]); got != nil { + t.Errorf("limits %v gave %v, want none", limits, relatedPaths(got)) + } + } +} + +// One ranked file never takes more than relatedFileCap, so a long file +// cannot crowd out the rest. +func TestRelatedFiles_PerFileCap(t *testing.T) { + long := "# Retries\n" + strings.Repeat("webhook retry backoff ", relatedFileCap/10) + dir := gitRepo(t, map[string]string{"docs/long.md": long, "docs/short.md": "webhook retry backoff\n"}) + l, err := repoFiles(dir) + if err != nil { + t.Fatal(err) + } + got := relatedFileContents(l.Root, l.Files, retryTitle, retryBody, nil, 4*relatedFileCap, defaultContextFiles) + if len(got) != 2 { + t.Fatalf("related = %v, want both", relatedPaths(got)) + } + for _, f := range got { + if f.Path == "docs/long.md" && (len(f.Content) != relatedFileCap || !f.Truncated) { + t.Fatalf("long file: %d bytes truncated=%v, want %d and truncated", len(f.Content), f.Truncated, + relatedFileCap) + } + } +} + +func TestEachTerm(t *testing.T) { + var got []string + eachTerm("ParsePlanVerdict reads HTTPServer configs; the 2026 issue_title is in it", func(s string) { + got = append(got, s) + }) + want := []string{"parse", "plan", "verdict", "parseplanverdict", "read", "http", "server", "httpserver", + "config", "issue", "title"} + if !reflect.DeepEqual(got, want) { + t.Fatalf("terms = %v, want %v", got, want) + } +} + +// The ranked files reach the prompt under their own heading, inside data +// blocks, and the prompt lists the files it holds. +func TestIntentPrompt_RelatedFilesFencedAndListed(t *testing.T) { + in := intentPromptInput{ + Issue: 7, Title: "t", Body: "b", + Named: []namedFile{{Path: "NAMED-PATH", Content: "NAMED-X"}}, + Related: []namedFile{ + {Path: "RELATED-PATH", Content: "RELATED-X"}, + {Path: "HEAD-PATH", Content: "HEAD-X", Truncated: true}, + }, + BashTimeoutSeconds: 900, + } + if !containsAny(in.untrustedText(), "RELATED-X") || !containsAny(in.untrustedText(), "RELATED-PATH") { + t.Fatal("untrustedText leaves out the related files, so a nonce in one would not be refused") + } + p := buildIntentPrompt(in) + n := promptNonce(t, p) + open, end := "<<>>", "<<>>" + for _, want := range []string{"RELATED-X", "HEAD-X"} { + i := strings.Index(p, want) + if i < 0 { + t.Fatalf("%s missing", want) + } + if strings.LastIndex(p[:i], open) <= strings.LastIndex(p[:i], end) { + t.Errorf("%s is not inside a data block", want) + } + } + if i, j := strings.Index(p, "NAMED-X"), strings.Index(p, relatedHeading); i < 0 || j < i || + j > strings.Index(p, "RELATED-X") { + t.Error("the related files do not follow the named files under their own heading") + } + for _, want := range []string{ + seenFullHeading + "\n" + open + "\nNAMED-PATH\nRELATED-PATH\n" + end, + seenHeadHeading + "\n" + open + "\nHEAD-PATH\n" + end, + seenNote, + } { + if !strings.Contains(p, want) { + t.Errorf("prompt lacks %q", want) + } + } + if strings.Contains(p, seenNoneNote) { + t.Error("prompt says it holds no contents") + } + + none := buildIntentPrompt(intentPromptInput{Issue: 1, Title: "t", Body: "b", BashTimeoutSeconds: 900}) + if !strings.Contains(none, seenNoneNote) || strings.Contains(none, seenFullHeading) || + strings.Contains(none, relatedHeading) { + t.Error("a prompt without contents does not say so") + } +} + +// Through PlanIssues: an issue that names no file gets the files about its +// topic and not the others; with no context budget it gets none. +func TestPlanIssues_PromptCarriesRelatedFiles(t *testing.T) { + for _, budget := range []int{defaultContextBytes, 0} { + e := newPlanEnv(t) + l := contextFixture(t) + e.repoDir = l.Root + e.cfg.ContextBytes, e.cfg.ContextFiles = budget, defaultContextFiles + f := newPlanForge(map[int32]IssueDetail{52: {Title: retryTitle, Body: retryBody}}) + s := &stubPlanner{answers: map[int32]string{52: plannedAnswer("cpu", "pkg/retry/backoff.go")}} + e.plan(t, f, s.call, 52) + p := s.prompts[52] + for _, content := range []string{"The backoff doubles after each attempt", "func Backoff(n int)"} { + if strings.Contains(p, content) != (budget > 0) { + t.Errorf("budget %d: prompt holds %q = %v", budget, content, budget == 0) + } + } + for _, unrelated := range []string{"start the service with the install script", "Prometheus collectors"} { + if strings.Contains(p, unrelated) { + t.Errorf("budget %d: prompt holds unrelated %q", budget, unrelated) + } + } + } +} + +// The named files come out of the same budget first. +func TestPlanIssues_NamedFilesShareTheContextBudget(t *testing.T) { + e := newPlanEnv(t) + l := contextFixture(t) + e.repoDir = l.Root + named, err := os.ReadFile(filepath.Join(l.Root, "docs", "retries.md")) + if err != nil { + t.Fatal(err) + } + // Room for the named file and nothing more. + e.cfg.ContextBytes, e.cfg.ContextFiles = len(named), defaultContextFiles + f := newPlanForge(map[int32]IssueDetail{52: {Title: retryTitle, Body: retryBody + " See docs/retries.md."}}) + s := &stubPlanner{answers: map[int32]string{52: plannedAnswer("cpu", "pkg/retry/backoff.go")}} + e.plan(t, f, s.call, 52) + p := s.prompts[52] + if !strings.Contains(p, "The backoff doubles") { + t.Fatal("the named file is missing") + } + if strings.Contains(p, "File pkg/retry/backoff.go:") { + t.Fatal("a related file was added past the budget the named file used") + } +} + +func TestPlannerSetup_ContextFlags(t *testing.T) { + cmd := newIntentsCommand() + for name, want := range map[string]string{"context-bytes": "65536", "context-files": "6"} { + fl := cmd.Flags().Lookup(name) + if fl == nil || fl.DefValue != want { + t.Fatalf("--%s = %+v, want default %s", name, fl, want) + } + } + o := &intentsOptions{plannerKwargs: defaultPlannerKwargs, plannerTimeout: 1, maxTokens: 1, bashTimeout: 1, + contextBytes: 1000, contextFiles: 3} + cfg, _, err := o.plannerSetup(nil) + if err != nil { + t.Fatal(err) + } + if cfg.ContextBytes != 1000 || cfg.ContextFiles != 3 { + t.Fatalf("cfg = %d bytes, %d files", cfg.ContextBytes, cfg.ContextFiles) + } + for _, bad := range []*intentsOptions{ + {plannerKwargs: defaultPlannerKwargs, plannerTimeout: 1, maxTokens: 1, bashTimeout: 1, contextBytes: -1}, + {plannerKwargs: defaultPlannerKwargs, plannerTimeout: 1, maxTokens: 1, bashTimeout: 1, contextFiles: -1}, + } { + if _, _, err := bad.plannerSetup(nil); err == nil { + t.Errorf("no error for %+v", bad) + } + } +} + +// A term in a file's path counts beyond its words: of two files with the +// same words, the one whose path names the topic ranks first even when it +// sorts last by path. +func TestRelatedFiles_PathTermsBoost(t *testing.T) { + dir := gitRepo(t, map[string]string{ + "docs/aaa-notes.md": "Tuning notes for the sender.\n", + "docs/zzz-backoff.md": "Tuning notes for the sender.\n", + "docs/other.md": "Unrelated text about logging.\n", + }) + l, err := repoFiles(dir) + if err != nil { + t.Fatal(err) + } + got := relatedPaths(relatedFileContents(l.Root, l.Files, "Backoff tuning", "", nil, defaultContextBytes, + defaultContextFiles)) + if len(got) == 0 || got[0] != "docs/zzz-backoff.md" { + t.Fatalf("related = %v, want docs/zzz-backoff.md first", got) + } +} + +func TestQueryTerms_TitleCountsDouble(t *testing.T) { + got := queryTerms("Retry backoff", "The backoff grows; deliveries fail.") + want := map[string]float64{"retry": 2, "backoff": 2, "grow": 1, "delivery": 1, + "fail": 1} + if !reflect.DeepEqual(got, want) { + t.Fatalf("query = %v, want %v", got, want) + } +} + +// A match in a short file outweighs the same match in a long one, so a long +// file with an incidental mention does not outrank a focused one. +func TestRelatedFiles_LengthNormalized(t *testing.T) { + filler := strings.Repeat("logging output format levels rotation ", 200) + dir := gitRepo(t, map[string]string{ + "docs/aaa-long.md": "Backoff.\n" + filler, + "docs/zzz-short.md": "Backoff.\n", + "docs/other.md": "Unrelated text about colours.\n", + }) + l, err := repoFiles(dir) + if err != nil { + t.Fatal(err) + } + got := relatedPaths(relatedFileContents(l.Root, l.Files, "Backoff", "", nil, defaultContextBytes, + defaultContextFiles)) + if len(got) == 0 || got[0] != "docs/zzz-short.md" { + t.Fatalf("related = %v, want docs/zzz-short.md first", got) + } +} diff --git a/pkg/cli/intents_prompt.go b/pkg/cli/intents_prompt.go index 4f814ae..e9424ff 100644 --- a/pkg/cli/intents_prompt.go +++ b/pkg/cli/intents_prompt.go @@ -101,6 +101,33 @@ reason: ` +// The headings and notes that tell the planner which files it has read. +const ( + relatedHeading = "Contents of the files most related to the issue (ranked by the words they share with it, " + + "not named by it; check that they are the right files before you rely on them):" + seenFullHeading = "Files whose full contents are in this message:" + seenHeadHeading = "Files of which this message holds only the head (cut at the contents cap):" + seenNote = "Those are the only files whose contents you have read. Every other file you know by its name " + + "alone:\nname it as a file to start from, never as the only files the coder may use." + seenNoneNote = "This message holds no file's contents: you know every file by its name alone. Name files as " + + "ones to start from,\nnever as the only files the coder may use." +) + +// readFiles lists the paths of the files whose contents the prompt holds: +// those given in full, and those cut at a cap. +func readFiles(groups ...[]namedFile) (full, head []string) { + for _, g := range groups { + for _, f := range g { + if f.Truncated { + head = append(head, oneLine(f.Path)) + } else { + full = append(full, oneLine(f.Path)) + } + } + } + return full, head +} + // truncatedMarker ends a named file cut off at the contents cap. const truncatedMarker = "[truncated: the contents cap was reached]" @@ -131,6 +158,9 @@ type intentPromptInput struct { // this issue, from the one login allowed to answer a park. It is placed // after the data blocks, as settled, not fenced as untrusted text. MaintainerDecision string + // Related are the tracked files ranked most related to the issue, + // besides the ones it names. + Related []namedFile } // maintainerDecisionHeading introduces a maintainer's decision in the prompt. @@ -151,7 +181,7 @@ func newNonce() string { // untrustedText is every string the prompt fences, so a nonce that happens // to occur in one of them can be refused. func (in intentPromptInput) untrustedText() []string { - out := make([]string, 0, 2+2*len(in.Comments)+len(in.Files)+2*len(in.Named)) + out := make([]string, 0, 2+2*len(in.Comments)+len(in.Files)+2*len(in.Named)+2*len(in.Related)) out = append(out, in.Title, in.Body) for _, c := range in.Comments { out = append(out, c.Author, c.Body) @@ -160,6 +190,9 @@ func (in intentPromptInput) untrustedText() []string { for _, f := range in.Named { out = append(out, f.Path, f.Content) } + for _, f := range in.Related { + out = append(out, f.Path, f.Content) + } return out } @@ -222,9 +255,12 @@ func buildIntentPrompt(in intentPromptInput) string { } block(&b, "Files in the repository (git ls-files):", list) - if len(in.Named) > 0 { - b.WriteString("\nContents of the files the issue names:\n") - for _, f := range in.Named { + fileBlocks := func(heading string, files []namedFile) { + if len(files) == 0 { + return + } + b.WriteString("\n" + heading + "\n") + for _, f := range files { content := f.Content if f.Truncated { if !strings.HasSuffix(content, "\n") { @@ -235,6 +271,20 @@ func buildIntentPrompt(in intentPromptInput) string { block(&b, "File "+oneLine(f.Path)+":", content) } } + fileBlocks("Contents of the files the issue names:", in.Named) + fileBlocks(relatedHeading, in.Related) + full, head := readFiles(in.Named, in.Related) + if len(full) > 0 { + block(&b, seenFullHeading, strings.Join(full, "\n")) + } + if len(head) > 0 { + block(&b, seenHeadHeading, strings.Join(head, "\n")) + } + if len(full)+len(head) > 0 { + b.WriteString("\n" + seenNote + "\n") + } else { + b.WriteString("\n" + seenNoneNote + "\n") + } if d := strings.TrimSpace(in.MaintainerDecision); d != "" { b.WriteString("\n" + maintainerDecisionHeading + " It is settled: follow it, and do not answer\n" +