34b8b94223
- Runner-owned findings ledger per run: stages report a # findings section (new items and F<n> status changes); stable IDs, persisted (run_loop_state), in RunDetail.findings, findings.md, memory.md, inspect. - type=findings gate stage routes open/clear on the ledger mechanically. - retry --extra-visits N [--stage KEY] continues an exhausted loop; limits on_exhausted=decide parks the run on accept/continue/abort. - Essential memory cap 20 KB, task never truncated, handoff and open findings ahead of the outcome ledger. - Lint rejects limits.on outcomes on forward edges; warns on ineffective limits and resume_session. - A resumed retry carries the failed visit's output.md and private/ under previous-attempt/. - resume_session=true resumes a Claude stage's previous session on loop visits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
375 lines
12 KiB
Go
375 lines
12 KiB
Go
// Package findings is the run-level findings ledger the runner owns. Stages
|
||
// report new findings and status changes in an output.md "# findings" section;
|
||
// the runner parses them (Parse), applies them to the ledger (Apply), assigns
|
||
// stable IDs, persists the ledger and feeds it to later visits (Render).
|
||
//
|
||
// Section syntax, one item per line (a leading list marker is optional):
|
||
//
|
||
// - <severity> <origin> <file:line>: <summary> a new finding
|
||
// - <severity> <origin>: <summary> a new finding without a location
|
||
// - F3 fixed: <how> status change
|
||
// - F3 dismissed: <why> - F3 settled: <why> closed for good
|
||
// - F3 open: <why the fix is wrong> reopen a fixed finding
|
||
//
|
||
// severity is critical, important, minor or nit; origin is introduced or
|
||
// pre-existing. Unparseable lines are ignored.
|
||
package findings
|
||
|
||
import (
|
||
"fmt"
|
||
"regexp"
|
||
"slices"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||
"git.a-wan.net/alan/pipelines/internal/turn"
|
||
)
|
||
|
||
// Bounds keep the ledger and each item small: it is persisted on the run and
|
||
// rendered into every later visit's memory.
|
||
const (
|
||
MaxFindings = 200
|
||
MaxNewPerVisit = 50
|
||
maxSummaryBytes = 300
|
||
maxLocationBytes = 200
|
||
maxReasonBytes = 300
|
||
maxEvents = 20
|
||
)
|
||
|
||
// Severities in rank order, most severe first.
|
||
var Severities = []string{protocol.SeverityCritical, protocol.SeverityImportant, protocol.SeverityMinor, protocol.SeverityNit}
|
||
|
||
var severityAliases = map[string]string{
|
||
"critical": protocol.SeverityCritical, "blocker": protocol.SeverityCritical,
|
||
"important": protocol.SeverityImportant, "major": protocol.SeverityImportant,
|
||
"minor": protocol.SeverityMinor,
|
||
"nit": protocol.SeverityNit, "nitpick": protocol.SeverityNit, "trivial": protocol.SeverityNit,
|
||
}
|
||
|
||
var originAliases = map[string]string{
|
||
"introduced": protocol.OriginIntroduced, "new": protocol.OriginIntroduced,
|
||
"pre-existing": protocol.OriginPreExisting, "preexisting": protocol.OriginPreExisting,
|
||
"pre_existing": protocol.OriginPreExisting, "existing": protocol.OriginPreExisting,
|
||
}
|
||
|
||
var statusWords = map[string]string{
|
||
"fixed": protocol.FindingFixed, "resolved": protocol.FindingFixed,
|
||
"dismissed": protocol.FindingDismissed, "rejected": protocol.FindingDismissed, "wontfix": protocol.FindingDismissed,
|
||
"settled": protocol.FindingSettled, "accepted": protocol.FindingSettled,
|
||
"open": protocol.FindingOpen, "reopen": protocol.FindingOpen, "reopened": protocol.FindingOpen,
|
||
}
|
||
|
||
// SeverityRank is 0 for critical through 3 for nit, and -1 when unknown.
|
||
func SeverityRank(severity string) int {
|
||
return slices.Index(Severities, severity)
|
||
}
|
||
|
||
// NormalizeSeverity returns the canonical severity or "".
|
||
func NormalizeSeverity(word string) string { return severityAliases[strings.ToLower(word)] }
|
||
|
||
// NormalizeOrigin returns the canonical origin, "any", or "".
|
||
func NormalizeOrigin(word string) string {
|
||
if strings.EqualFold(word, "any") {
|
||
return "any"
|
||
}
|
||
return originAliases[strings.ToLower(word)]
|
||
}
|
||
|
||
// New is a finding a stage raised; Change is a status change it reported.
|
||
type New struct {
|
||
Severity, Origin, Location, Summary string
|
||
}
|
||
|
||
type Change struct {
|
||
ID, Status, Reason string
|
||
}
|
||
|
||
// Report is one visit's parsed "# findings" section.
|
||
type Report struct {
|
||
New []New
|
||
Changes []Change
|
||
}
|
||
|
||
var (
|
||
listMarker = regexp.MustCompile(`^\s*(?:[-*+]|\d+[.)])\s+`)
|
||
findingID = regexp.MustCompile(`^(?i)F(\d+)$`)
|
||
)
|
||
|
||
// Parse reads the "# findings" section of a turn's output. It returns an empty
|
||
// report when there is none.
|
||
func Parse(markdown string) Report {
|
||
section, ok := turn.Section(markdown, "findings")
|
||
if !ok {
|
||
return Report{}
|
||
}
|
||
var report Report
|
||
fence := ""
|
||
for _, line := range strings.Split(section, "\n") {
|
||
trimmed := strings.TrimSpace(line)
|
||
if fence != "" {
|
||
if strings.HasPrefix(trimmed, fence) {
|
||
fence = ""
|
||
}
|
||
continue
|
||
}
|
||
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
|
||
fence = trimmed[:3]
|
||
continue
|
||
}
|
||
line = strings.TrimSpace(listMarker.ReplaceAllString(line, ""))
|
||
line = strings.Trim(line, "`")
|
||
if line == "" {
|
||
continue
|
||
}
|
||
if change, ok := parseChange(line); ok {
|
||
report.Changes = append(report.Changes, change)
|
||
continue
|
||
}
|
||
if item, ok := parseNew(line); ok {
|
||
report.New = append(report.New, item)
|
||
}
|
||
}
|
||
return report
|
||
}
|
||
|
||
// splitReason splits "word: reason", "word — reason" or "word - reason".
|
||
func splitReason(text string) (string, string) {
|
||
for _, sep := range []string{": ", " — ", " – ", " - "} {
|
||
if head, tail, ok := strings.Cut(text, sep); ok {
|
||
return strings.TrimSpace(head), strings.TrimSpace(tail)
|
||
}
|
||
}
|
||
return strings.TrimSpace(strings.TrimSuffix(text, ":")), ""
|
||
}
|
||
|
||
func parseChange(line string) (Change, bool) {
|
||
fields := strings.Fields(line)
|
||
if len(fields) < 2 {
|
||
return Change{}, false
|
||
}
|
||
id := strings.TrimSuffix(strings.TrimSuffix(fields[0], ":"), ",")
|
||
match := findingID.FindStringSubmatch(id)
|
||
if match == nil {
|
||
return Change{}, false
|
||
}
|
||
rest := strings.TrimSpace(strings.TrimPrefix(line, fields[0]))
|
||
word, reason := splitReason(rest)
|
||
status, ok := statusWords[strings.ToLower(strings.Trim(word, "*_`"))]
|
||
if !ok {
|
||
return Change{}, false
|
||
}
|
||
return Change{ID: "F" + match[1], Status: status, Reason: capText(reason, maxReasonBytes)}, true
|
||
}
|
||
|
||
func parseNew(line string) (New, bool) {
|
||
fields := strings.Fields(line)
|
||
if len(fields) < 2 {
|
||
return New{}, false
|
||
}
|
||
severity := NormalizeSeverity(strings.Trim(fields[0], "*_[]:"))
|
||
if severity == "" {
|
||
return New{}, false
|
||
}
|
||
originWord := fields[1]
|
||
noLocation := strings.HasSuffix(originWord, ":")
|
||
origin := originAliases[strings.ToLower(strings.Trim(originWord, "*_[]:"))]
|
||
if origin == "" {
|
||
return New{}, false
|
||
}
|
||
rest := strings.TrimSpace(line[strings.Index(line, originWord)+len(originWord):])
|
||
var location, summary string
|
||
if noLocation {
|
||
summary = rest
|
||
} else {
|
||
summary = rest
|
||
for _, sep := range []string{": ", " — "} {
|
||
// The location is one token (a path, file:line or "-"); a
|
||
// multi-word head is prose and stays in the summary.
|
||
if head, tail, ok := strings.Cut(rest, sep); ok && !strings.ContainsAny(strings.TrimSpace(head), " \t") {
|
||
location, summary = strings.Trim(strings.TrimSpace(head), "`"), strings.TrimSpace(tail)
|
||
break
|
||
}
|
||
}
|
||
}
|
||
if location == "-" {
|
||
location = ""
|
||
}
|
||
summary = strings.TrimSpace(summary)
|
||
if summary == "" {
|
||
return New{}, false
|
||
}
|
||
return New{Severity: severity, Origin: origin, Location: capText(location, maxLocationBytes), Summary: capText(summary, maxSummaryBytes)}, true
|
||
}
|
||
|
||
func capText(text string, limit int) string {
|
||
text = strings.Join(strings.Fields(text), " ")
|
||
if len(text) <= limit {
|
||
return text
|
||
}
|
||
cut := limit - len("…")
|
||
for cut > 0 && cut < len(text) && (text[cut]&0xC0) == 0x80 {
|
||
cut--
|
||
}
|
||
return text[:cut] + "…"
|
||
}
|
||
|
||
// Outcome summarises what Apply did, for logs and tests.
|
||
type Outcome struct {
|
||
Added []string
|
||
Changed []string
|
||
Ignored []string
|
||
}
|
||
|
||
func key(location, summary string) string {
|
||
return strings.ToLower(location) + "\x00" + strings.ToLower(summary)
|
||
}
|
||
|
||
// Apply folds one visit's report into the ledger and returns the new ledger.
|
||
// IDs are assigned in order (F1, F2, ...) and never reused. A new finding that
|
||
// repeats an open one is ignored, one that repeats a fixed one reopens it, and
|
||
// one that repeats a dismissed or settled one is ignored: those are closed for
|
||
// good. Reopening a dismissed or settled finding is ignored for the same
|
||
// reason.
|
||
func Apply(ledger []protocol.Finding, report Report, stageKey string, sequence int) ([]protocol.Finding, Outcome) {
|
||
out := append([]protocol.Finding(nil), ledger...)
|
||
var result Outcome
|
||
byID := map[string]int{}
|
||
byKey := map[string]int{}
|
||
next := 1
|
||
for i, item := range out {
|
||
byID[item.ID] = i
|
||
byKey[key(item.Location, item.Summary)] = i
|
||
if n, err := strconv.Atoi(strings.TrimPrefix(item.ID, "F")); err == nil && n >= next {
|
||
next = n + 1
|
||
}
|
||
}
|
||
setStatus := func(i int, status, reason string) {
|
||
item := out[i]
|
||
item.Events = append(append([]protocol.FindingEvent(nil), item.Events...), protocol.FindingEvent{Sequence: sequence, Stage: stageKey, Status: status, Reason: reason})
|
||
if len(item.Events) > maxEvents {
|
||
item.Events = item.Events[len(item.Events)-maxEvents:]
|
||
}
|
||
item.Status, item.Reason = status, reason
|
||
item.UpdatedBy, item.UpdatedSequence = stageKey, sequence
|
||
out[i] = item
|
||
}
|
||
for _, change := range report.Changes {
|
||
i, ok := byID[change.ID]
|
||
if !ok {
|
||
result.Ignored = append(result.Ignored, change.ID+": unknown id")
|
||
continue
|
||
}
|
||
current := out[i].Status
|
||
if current == change.Status {
|
||
continue
|
||
}
|
||
if change.Status == protocol.FindingOpen && (current == protocol.FindingDismissed || current == protocol.FindingSettled) {
|
||
result.Ignored = append(result.Ignored, change.ID+": "+current+" findings are closed")
|
||
continue
|
||
}
|
||
setStatus(i, change.Status, change.Reason)
|
||
result.Changed = append(result.Changed, change.ID)
|
||
}
|
||
added := 0
|
||
for _, item := range report.New {
|
||
if i, ok := byKey[key(item.Location, item.Summary)]; ok {
|
||
switch out[i].Status {
|
||
case protocol.FindingFixed:
|
||
setStatus(i, protocol.FindingOpen, "raised again by "+stageKey)
|
||
result.Changed = append(result.Changed, out[i].ID)
|
||
default:
|
||
result.Ignored = append(result.Ignored, out[i].ID+": already "+out[i].Status)
|
||
}
|
||
continue
|
||
}
|
||
if added >= MaxNewPerVisit || len(out) >= MaxFindings {
|
||
result.Ignored = append(result.Ignored, "over the findings limit: "+item.Summary)
|
||
continue
|
||
}
|
||
added++
|
||
id := fmt.Sprintf("F%d", next)
|
||
next++
|
||
out = append(out, protocol.Finding{
|
||
ID: id, Severity: item.Severity, Origin: item.Origin, Location: item.Location, Summary: item.Summary,
|
||
Status: protocol.FindingOpen, RaisedBy: stageKey, RaisedSequence: sequence,
|
||
Events: []protocol.FindingEvent{{Sequence: sequence, Stage: stageKey, Status: protocol.FindingOpen}},
|
||
})
|
||
byID[id] = len(out) - 1
|
||
byKey[key(item.Location, item.Summary)] = len(out) - 1
|
||
result.Added = append(result.Added, id)
|
||
}
|
||
return out, result
|
||
}
|
||
|
||
// Before returns the ledger as it stood before visit sequence: findings raised
|
||
// at or after it are dropped and later events are rolled back. A retry resuming
|
||
// at sequence starts from this ledger.
|
||
func Before(ledger []protocol.Finding, sequence int) []protocol.Finding {
|
||
var out []protocol.Finding
|
||
for _, item := range ledger {
|
||
if item.RaisedSequence >= sequence {
|
||
continue
|
||
}
|
||
var events []protocol.FindingEvent
|
||
for _, event := range item.Events {
|
||
if event.Sequence < sequence {
|
||
events = append(events, event)
|
||
}
|
||
}
|
||
item.Events = events
|
||
item.Status, item.Reason, item.UpdatedBy, item.UpdatedSequence = protocol.FindingOpen, "", "", 0
|
||
if n := len(events); n > 0 {
|
||
last := events[n-1]
|
||
item.Status, item.Reason = last.Status, last.Reason
|
||
if n > 1 || last.Status != protocol.FindingOpen || last.Sequence != item.RaisedSequence {
|
||
item.UpdatedBy, item.UpdatedSequence = last.Stage, last.Sequence
|
||
}
|
||
}
|
||
out = append(out, item)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// Gate is a mechanical routing condition on the ledger: open findings at or
|
||
// above MinSeverity whose origin matches (Origin "any" matches both).
|
||
type Gate struct {
|
||
MinSeverity string
|
||
Origin string
|
||
}
|
||
|
||
// Matching returns the open findings the gate counts.
|
||
func (g Gate) Matching(ledger []protocol.Finding) []protocol.Finding {
|
||
limit := SeverityRank(g.MinSeverity)
|
||
if limit < 0 {
|
||
limit = SeverityRank(protocol.SeverityImportant)
|
||
}
|
||
var out []protocol.Finding
|
||
for _, item := range ledger {
|
||
if item.Status != protocol.FindingOpen {
|
||
continue
|
||
}
|
||
rank := SeverityRank(item.Severity)
|
||
if rank < 0 || rank > limit {
|
||
continue
|
||
}
|
||
if g.Origin != "any" && g.Origin != "" && item.Origin != g.Origin {
|
||
continue
|
||
}
|
||
if g.Origin == "" && item.Origin != protocol.OriginIntroduced {
|
||
continue
|
||
}
|
||
out = append(out, item)
|
||
}
|
||
return out
|
||
}
|
||
|
||
// Counts returns the number of findings per status.
|
||
func Counts(ledger []protocol.Finding) map[string]int {
|
||
counts := map[string]int{}
|
||
for _, item := range ledger {
|
||
counts[item.Status]++
|
||
}
|
||
return counts
|
||
}
|