Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/run-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ by `meitheal decisions`.
| Kind | When |
|---|---|
| `escalate` | The coder stalled; the Workload failed (see below); the gate failed again after the feedback pass; the GPU node stayed busy; the loop lost track of the issue's run; the loop kept failing on the issue. |
| `needs-decision` | A task raised a concern (one the loop cannot read, or with no text, counts); the planner found a decision only a maintainer can make, its answer was unreadable, or its call failed; the issue carries the `--decision-label` label. |
| `needs-decision` | A task raised a concern (one the loop cannot read, or with no text, counts); the planner found a decision only a maintainer can make, its answer was unreadable, its call failed, or its intent failed the lint (it names a path the repository does not have, or its files list holds an existing file the intent never mentions); the issue carries the `--decision-label` label. |
| `needs-split` | The planner judged the issue too big for one run. |

A failed Workload's reason comes from its tasks' outcomes, judged by the
Expand Down
49 changes: 45 additions & 4 deletions pkg/cli/intents.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,9 @@ type PlanConfig struct {
BashTimeoutSeconds int
// Progress, when set, gets one line per issue.
Progress io.Writer
// ShowLint adds each planned intent's lint result to its progress line,
// and prints a failed lint's report before the park line.
ShowLint bool
// MaintainerDecisions maps an issue to a decision its maintainer made
// (a '/meitheal decide' answer). It reaches that issue's prompt as
// settled, and the decision label no longer parks the issue: the human
Expand Down Expand Up @@ -266,8 +269,8 @@ func planIssuesTo(ctx context.Context, f RunForge, call PlannerCaller, repo, rep
if err := os.MkdirAll(outDir, 0o755); err != nil {
return plannedQueue{}, fmt.Errorf("create --out: %w", err)
}
p := planner{f: f, call: call, repo: repo, listing: listing, outDir: outDir, decisionsDir: decisionsDir,
cfg: cfg}
p := planner{f: f, call: call, repo: repo, listing: listing, paths: newRepoPaths(listing.Files),
outDir: outDir, decisionsDir: decisionsDir, cfg: cfg}
q := Queue{Repo: repo}
planned := map[int32][]string{}
for _, issue := range issues {
Expand All @@ -294,6 +297,7 @@ type planner struct {
call PlannerCaller
repo string
listing repoListing
paths repoPaths
outDir string
decisionsDir string
cfg PlanConfig
Expand Down Expand Up @@ -357,6 +361,20 @@ func (p planner) planOne(ctx context.Context, issue int32) (*QueueItem, []string
return nil, nil, p.park(issue, ParkNeedsSplit, reasonNeedsSplit, ev)
}

// A planned intent that names a path the repository does not have, or
// whose header disagrees with its body, is parked before a coder run is
// spent on it.
lint := lintIntent(v, p.paths)
if !lint.ok() {
if p.cfg.ShowLint {
p.progress("issue %d: intent failed lint:\n%s", issue, indentLines(lint.report()))
}
return nil, nil, p.park(issue, ParkNeedsDecision, lint.reason(), map[string]string{
"lint": lint.report(),
"intent": capString(v.Intent, unreadableEvidenceCap),
})
}

intentPath := filepath.Join(p.outDir, fmt.Sprintf("%d.intent.md", issue))
if err := os.WriteFile(intentPath, []byte(v.Intent+"\n"), 0o644); err != nil {
return nil, nil, fmt.Errorf("write intent for issue %d: %w", issue, err)
Expand All @@ -368,7 +386,12 @@ func (p planner) planOne(ctx context.Context, issue int32) (*QueueItem, []string
if p.forcesGPU(d.Labels, v.Files) {
lane = "gpu"
}
p.progress("issue %d: planned, lane %s, intent %s\n", issue, lane, intentPath)
if p.cfg.ShowLint {
p.progress("issue %d: planned, lane %s, intent %s, lint passed (%d repository paths checked)\n",
issue, lane, intentPath, lint.Checked)
} else {
p.progress("issue %d: planned, lane %s, intent %s\n", issue, lane, intentPath)
}
return &QueueItem{Issue: issue, IntentPath: intentPath, Lane: lane}, v.Files, nil
}

Expand Down Expand Up @@ -472,6 +495,11 @@ func sharesFile(a, b []string) bool {
return false
}

// indentLines indents every line of a report under its progress line.
func indentLines(s string) string {
return " " + strings.ReplaceAll(strings.TrimSuffix(s, "\n"), "\n", "\n ") + "\n"
}

func capString(s string, n int) string {
if len(s) <= n {
return s
Expand Down Expand Up @@ -692,6 +720,11 @@ 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
in the queue.

A planned intent is linted against --repo-dir before it is queued, and parked
when it names a path under a tracked directory that the repository does not
have and its files list does not create, or when its files list holds an
existing file the intent never mentions. --hold prints each lint result.

Rules that belong to one repository go in --rules-file; they reach the
planner verbatim, and override the general rules where the two conflict.
--gpu-labels and --gpu-paths put an issue in the gpu lane.
Expand All @@ -714,7 +747,7 @@ Example:
}
f := cmd.Flags()
addPlannerFlags(f, o, " (required)")
f.BoolVar(&o.hold, "hold", false, "Write the intents and queue, then stop for review")
f.BoolVar(&o.hold, "hold", false, "Write the intents and queue, print each intent's lint result, then stop for review")
f.StringVar(&o.decisionsDir, "decisions-dir", defaultDecisionsDir, "Where parked decisions are written")
for _, name := range []string{"repo", "issues", "repo-dir", "planner-url"} {
_ = cmd.MarkFlagRequired(name)
Expand Down Expand Up @@ -786,6 +819,7 @@ func (o *intentsOptions) plannerSetup(progress io.Writer) (PlanConfig, PlannerCa
TrustedCommenters: splitList(o.trustedCommenters),
BashTimeoutSeconds: o.bashTimeout,
Progress: progress,
ShowLint: o.hold,
}
if o.rulesFile != "" {
b, err := os.ReadFile(o.rulesFile)
Expand Down Expand Up @@ -821,6 +855,13 @@ func runIntents(ctx context.Context, w io.Writer, o *intentsOptions) error {
if ctx == nil {
ctx = context.Background()
}
return planAndReport(ctx, w, o, forge, call, cfg, issues)
}

// planAndReport plans the issues and prints the summary 'meitheal intents'
// ends with.
func planAndReport(ctx context.Context, w io.Writer, o *intentsOptions, forge RunForge, call PlannerCaller,
cfg PlanConfig, issues []int32) error {
q, err := PlanIssues(ctx, forge, call, o.repo, o.repoDir, issues, o.out, o.decisionsDir, cfg)
if err != nil {
return err
Expand Down
227 changes: 227 additions & 0 deletions pkg/cli/intents_lint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
/*
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 (
"fmt"
"path"
"regexp"
"strings"
)

// The intent lint checks a planned intent against the repository before it is
// queued: no model judgement, only the tracked file list. It is tuned for
// precision. A token is checked only when it is shaped like a path from the
// repository root under a top-level directory the repository tracks, so URLs,
// import paths, flags, globs and absolute paths pass unchecked, and a false
// park costs a human more than a missed one.

// The lint check names. They reach the public park comment through the
// reason, so they are fixed strings and never model text.
const (
lintUnknownPaths = "unknown paths"
lintUnmentionedFile = "files the intent never mentions"
reasonLintPrefix = "intent failed lint: "
// lintLinesCap bounds the offending intent lines kept per check.
lintLinesCap = 20
)

// repoPaths indexes a checkout's tracked files for the lint.
type repoPaths struct {
files map[string]bool
// dirs holds every directory a tracked file is under.
dirs map[string]bool
// top holds the top-level directories; only a token under one of them
// is checked.
top map[string]bool
}

func newRepoPaths(files []string) repoPaths {
r := repoPaths{files: make(map[string]bool, len(files)), dirs: map[string]bool{}, top: map[string]bool{}}
for _, f := range files {
r.files[f] = true
if first, _, ok := strings.Cut(f, "/"); ok {
r.top[first] = true
}
for d := path.Dir(f); d != "." && !r.dirs[d]; d = path.Dir(d) {
r.dirs[d] = true
}
}
return r
}

// lintFailure is one failed check and what failed it.
type lintFailure struct {
Check string
// Tokens are the offending paths, in the order the intent names them.
Tokens []string
// Lines are the intent lines that name an offending path.
Lines []string
}

// intentLint is the result of linting one intent.
type intentLint struct {
// Checked counts the distinct repository paths the intent names.
Checked int
Failures []lintFailure
}

func (l intentLint) ok() bool { return len(l.Failures) == 0 }

// reason is the fixed park reason: the failed checks' names.
func (l intentLint) reason() string {
names := make([]string, 0, len(l.Failures))
for _, f := range l.Failures {
names = append(names, f.Check)
}
return reasonLintPrefix + strings.Join(names, ", ")
}

// report is the evidence a human reads: each failed check, its tokens and
// the lines that name them.
func (l intentLint) report() string {
var b strings.Builder
for _, f := range l.Failures {
fmt.Fprintf(&b, "%s: %s\n", f.Check, strings.Join(f.Tokens, ", "))
for _, line := range f.Lines {
fmt.Fprintf(&b, " %s\n", line)
}
}
return b.String()
}

// lintIntent runs the checks on a planned verdict:
//
// 1. unknown paths: every repository path the intent names is tracked (a
// file or a directory), or is in the header's files list (a file to
// create) or under a directory one of those creates. This also catches a
// file the intent says to create but the header leaves out.
// 2. files the intent never mentions: every header file that already exists
// is named in the intent, by its path or its base name.
func lintIntent(v PlanVerdict, repo repoPaths) intentLint {
header := map[string]bool{}
headerDirs := map[string]bool{}
for _, f := range v.Files {
header[f] = true
for d := path.Dir(f); d != "." && !headerDirs[d]; d = path.Dir(d) {
headerDirs[d] = true
}
}
var res intentLint
unknown := lintFailure{Check: lintUnknownPaths}
checked := map[string]bool{}
missing := map[string]bool{}
// words holds every word of the intent and its base name, for check 2.
words := map[string]bool{}
for _, line := range strings.Split(v.Intent, "\n") {
hit := false
for _, raw := range intentWordRE.FindAllString(line, -1) {
word := trimWord(raw)
if word == "" {
continue
}
words[word], words[path.Base(word)] = true, true
p, ok := repoPathToken(word, repo)
if !ok {
continue
}
if !checked[p] {
checked[p] = true
if !repo.known(p) && !header[p] && !headerDirs[p] {
missing[p] = true
unknown.Tokens = append(unknown.Tokens, p)
}
}
hit = hit || missing[p]
}
if hit {
unknown.Lines = appendLine(unknown.Lines, line)
}
}
res.Checked = len(checked)
if len(unknown.Tokens) > 0 {
res.Failures = append(res.Failures, unknown)
}

unmentioned := lintFailure{Check: lintUnmentionedFile}
for _, f := range v.Files {
if !repo.files[f] || words[path.Base(f)] || strings.Contains(v.Intent, f) {
continue
}
unmentioned.Tokens = append(unmentioned.Tokens, f)
}
if len(unmentioned.Tokens) > 0 {
res.Failures = append(res.Failures, unmentioned)
}
return res
}

func appendLine(lines []string, line string) []string {
if len(lines) >= lintLinesCap {
return lines
}
return append(lines, strings.TrimSpace(line))
}

// known reports whether p is a tracked file or directory, or a Go symbol in
// a tracked package directory ("pkg/cli.ParsePlanVerdict").
func (r repoPaths) known(p string) bool {
if r.files[p] || r.dirs[p] {
return true
}
dir, base := path.Split(p)
if pkg, _, ok := strings.Cut(base, "."); ok && pkg != "" {
return r.dirs[dir+pkg]
}
return false
}

// intentWordRE splits intent text into words: Markdown and shell punctuation
// end a word, and so does = (a --flag=value names its value as a word).
var intentWordRE = regexp.MustCompile("[^\\s`'\"()<>,;|=]+")

// trimWord drops Markdown emphasis and sentence punctuation around a word.
func trimWord(w string) string {
w = strings.Trim(w, "*_~")
w = strings.TrimRight(w, ".:!?")
return w
}

// repoPathToken returns the repository path a word names, if it is shaped
// like one: relative, under a tracked top-level directory, with no glob,
// variable or template characters. Everything from the first : or # is
// dropped (a :line, an #anchor, or a URL after its scheme), and so is a
// leading ./ or a trailing / or /... (a directory or a Go package pattern).
func repoPathToken(w string, repo repoPaths) (string, bool) {
w, _, _ = strings.Cut(w, "#")
w, _, _ = strings.Cut(w, ":")
w = strings.TrimPrefix(w, "./")
w = strings.TrimRight(w, "/.")
if !strings.Contains(w, "/") || strings.HasPrefix(w, "/") || strings.HasPrefix(w, "-") ||
strings.ContainsAny(w, "*?[]{}$@~%\\") {
return "", false
}
first, _, _ := strings.Cut(w, "/")
if !repo.top[first] {
return "", false
}
p := path.Clean(w)
if p == "." || strings.HasPrefix(p, "../") {
return "", false
}
return p, true
}
Loading