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
44 changes: 44 additions & 0 deletions lab/internal/ui/findings.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"regexp"
"strings"
"time"
"unicode/utf8"

"github.com/DanielNetzer/forgecell/lab/internal/delivery"
"github.com/DanielNetzer/forgecell/lab/internal/fixround"
Expand Down Expand Up @@ -45,6 +46,8 @@ const (
findingsMaxOpen = 500
// findingsMaxRuneText bounds a served finding title or error.
findingsMaxRuneText = 300
// findingsMaxBodyRunes bounds a served finding body.
findingsMaxBodyRunes = 4000
// findingsMaxPathBytes bounds a served finding path.
findingsMaxPathBytes = 1024
// findingsWriteTimeout bounds a synchronous findings write and the
Expand Down Expand Up @@ -89,6 +92,10 @@ var findingsReasons = map[string]string{
"fix-rounds-stop": "This change request has reached its fix-round bound; continue it by hand",
"too-many": "Raise the reviewers' autoFix level in the Formula or include fewer findings",
"no-formula": "This Lab has no approved active Formula; approve one with forgecell init first",
// The tab follows this Molecule's Formula snapshot; a proposal follows the
// Lab's active approved Formula, so the two can differ.
"no-active-reviewers": "This Molecule's Formula snapshot declares reviewers, but the Lab's active approved Formula does not; approve a Formula that declares them, then propose again",
"not-live": "The change request is merged or closed, so there is nothing left to fix on it",
}

// findingsRefuse answers a findings refusal with its fixed message and the
Expand Down Expand Up @@ -194,6 +201,35 @@ func findingsText(x redactor, s string, limit int) string {
return harness.ReviewDisplayText(x.text(redactSecrets(s)), limit)
}

// findingsBody is an untrusted finding body as bounded display text: secrets
// and local paths replaced, each line control-free with its whitespace
// collapsed, blank runs kept to one empty line, at most findingsMaxBodyRunes
// in all. cut reports a body the record or this bound shortened.
func findingsBody(x redactor, body string, recordedCut bool) (string, bool) {
var lines []string
left, cut := findingsMaxBodyRunes, recordedCut
for _, line := range strings.Split(x.text(redactSecrets(body)), "\n") {
line = harness.ReviewDisplayText(line, findingsMaxBodyRunes)
if line == "" && (len(lines) == 0 || lines[len(lines)-1] == "") {
continue
}
n := utf8.RuneCountInString(line) + 1
if n > left {
if left > 1 {
lines = append(lines, harness.ReviewDisplayText(line, left-1))
}
cut = true
break
}
left -= n
lines = append(lines, line)
}
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n"), cut
}

// findingsPath is a finding's recorded path when it serves unchanged, or "".
func findingsPath(x redactor, p string) string {
if p == "" || len(p) > findingsMaxPathBytes || findingsText(x, p, findingsMaxPathBytes) != p {
Expand Down Expand Up @@ -356,6 +392,10 @@ func (h *handler) findingsPost(w http.ResponseWriter, r *http.Request, id, actio
case "findings/collect":
h.findingsCollectPost(w, id, f)
case "findings/propose":
if !findingsLive(receipt) {
h.findingsRefuse(w, http.StatusConflict, "not-live", "the change request is merged or closed; nothing was proposed")
return
}
h.findingsProposePost(w, id, propose.Include)
case "findings/dismiss":
h.findingsDismissPost(w, id, dismiss.Fingerprint, func() error {
Expand Down Expand Up @@ -476,6 +516,10 @@ func (h *handler) findingsEngineRefusal(w http.ResponseWriter, err error) {
h.refuseGate(w, http.StatusServiceUnavailable, "interrupted", "the request was interrupted before the engine finished")
return
}
if errors.Is(err, delivery.ErrNoReviewers) {
h.findingsRefuse(w, http.StatusConflict, "no-active-reviewers", "this Lab's Formula declares no reviewers; nothing was proposed")
return
}
text := err.Error()
for _, m := range []struct {
part, category, message string
Expand Down
5 changes: 3 additions & 2 deletions lab/internal/ui/findings_inbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,10 @@ func findingsLive(receipt delivery.Receipt) bool {
// confirmation, else open reviewer findings to triage when none of them is
// pending in a fix round. It replaces only an In-progress, Recently recorded
// or empty entry, never a scope, publish or blocked card, and reads no
// workspace and starts no process.
// workspace and starts no process. A merged or closed change request has no
// findings decision: its entry stays as it is.
func inboxFindingsOverlay(lab string, r molecule.Record, v *InboxView) {
if v == nil || r.Status == molecule.StatusRetired || (v.Kind != "" && v.Kind != InboxProgress && v.Kind != InboxRecorded) {
if v == nil || v.Merged || r.Status == molecule.StatusRetired || (v.Kind != "" && v.Kind != InboxProgress && v.Kind != InboxRecorded) {
return
}
f, ok := findingsSnapshot(r)
Expand Down
13 changes: 11 additions & 2 deletions lab/internal/ui/findings_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import (
// holds a pending or errored reviewer. Each Molecule is collected at most once
// per max(60s, the largest needs.minPollSeconds of its reviewer plugins); a
// failed collection, or one whose newest round is incomplete or holds an
// errored reviewer, doubles that wait for each further consecutive failure, up
// to one hour, as the keyed Issues view does. A Lab UI started without a source checkout runs nothing.
// errored reviewer, waits twice that, and doubles the wait for each further
// consecutive failure, up to one hour, as the keyed Issues view does. So a
// failing reviewer is not collected again a minute after the Lab opens. A Lab
// UI started without a source checkout runs nothing.
// The pass never proposes, dismisses or pushes.

const (
Expand Down Expand Up @@ -229,11 +231,18 @@ func (h *handler) findingsSyncPass(ctx context.Context, ids []string) {
s.entries[d.id] = e
}
e.ttl = issuesKeyedBackoff(d.interval, e.ttl, e.failed, failed)
if failed {
e.ttl = min(max(e.ttl, findingsSyncFailedWait(d.interval)), issuesKeyedMaxPoll)
}
e.finished, e.failed = h.findingsNow(), failed
s.mu.Unlock()
}
}

// findingsSyncFailedWait is the shortest wait after a failed collection:
// twice the Molecule's interval.
func findingsSyncFailedWait(interval time.Duration) time.Duration { return 2 * interval }

// findingsSyncFailedRound reports a collection whose newest round is cut by a
// bound or holds a reviewer that errored: it backs off as a failure does.
func findingsSyncFailedRound(record delivery.FindingsRecord) bool {
Expand Down
59 changes: 49 additions & 10 deletions lab/internal/ui/findings_sync_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"sort"
Expand Down Expand Up @@ -216,14 +217,16 @@ func TestFindingsSyncBacksOffOnFailure(t *testing.T) {
t.Fatalf("at %v: %d collections, want %d", clock.get().Format(time.TimeOnly), got, want)
}
}
at(1) // fails: the next waits a minute
at(1) // fails: the next waits twice the minute
clock.advance(time.Minute)
at(2) // fails again: the wait doubles to 2 minutes
at(1)
clock.advance(time.Minute)
at(2) // fails again: the wait doubles to 4 minutes
clock.advance(3 * time.Minute)
at(2)
clock.advance(time.Minute)
at(3) // 4 minutes next
clock.advance(3 * time.Minute)
at(3) // 8 minutes next
clock.advance(7 * time.Minute)
at(3)
clock.advance(time.Minute)
at(4)
Expand Down Expand Up @@ -262,14 +265,16 @@ func TestFindingsSyncRetriesAnErroredReviewerWithBackoff(t *testing.T) {
findingsTestWrite(t, lab, id, nil, errored)
c.returns(delivery.FindingsRecord{Rounds: []delivery.FindingsRound{errored}})
at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) }
at(1) // collected without error, but the reviewer errored: a minute next
at(1) // collected without error, but the reviewer errored: 2 minutes next
clock.advance(time.Minute)
at(2) // errored again: the wait doubles to 2 minutes
at(1)
clock.advance(time.Minute)
at(2) // errored again: the wait doubles to 4 minutes
clock.advance(3 * time.Minute)
at(2)
clock.advance(time.Minute)
at(3) // 4 minutes next
clock.advance(3 * time.Minute)
at(3) // 8 minutes next
clock.advance(7 * time.Minute)
at(3)
// The reviewer answers: a good round resets the wait, and a complete
// round on the head without errors is not collected again.
Expand Down Expand Up @@ -297,10 +302,12 @@ func TestFindingsSyncBacksOffATruncatedRound(t *testing.T) {
at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) }
at(1)
clock.advance(time.Minute)
at(2)
at(1) // not a minute later: a failure waits twice the minute
clock.advance(time.Minute)
at(2) // not every minute: the wait doubled
at(2)
clock.advance(time.Minute)
at(2) // the wait doubled
clock.advance(3 * time.Minute)
at(3)
// A persistently truncated reviewer settles at one collection an hour.
for i := 0; i < 10; i++ {
Expand All @@ -323,6 +330,38 @@ func TestFindingsSyncBacksOffATruncatedRound(t *testing.T) {
}
}

// Opening the Lab while a reviewer fails collects once, not again a minute
// later: a failed round waits twice the interval. Collect now still runs.
func TestFindingsSyncDoesNotRecollectAFailedRoundWithinTheWindow(t *testing.T) {
h, list, clock, c := findingsSyncFixture(t, 1, "/src")
h.findingsPoll = func(string, formula.Formula) time.Duration { return 0 }
errored := findingsTestRound(findingsTestCommit, delivery.FindingsError, true)
errored.Reviewers[0].Error = "the reviewer failed"
c.returns(delivery.FindingsRecord{Rounds: []delivery.FindingsRound{errored}})
at := func(want int) { t.Helper(); findingsSyncAt(t, h, list, clock, c, want) }
at(1)
clock.advance(findingsSyncMinPoll)
at(1)
clock.advance(findingsSyncMinPoll - time.Second)
at(1)
clock.advance(time.Second)
at(2)
h.findingsSync.mu.Lock()
ttl := h.findingsSync.entries[list[0].ID].ttl
h.findingsSync.mu.Unlock()
if ttl < findingsSyncFailedWait(findingsSyncMinPoll) {
t.Fatalf("wait %v after two failures", ttl)
}
// The throttle is the background pass's alone: Collect now is not held back.
if w := do(t, h, gatePost("/api/molecules/"+list[0].ID+"/findings/collect", `{}`)); w.Code != http.StatusAccepted {
t.Fatalf("collect now: %d %s", w.Code, w.Body)
}
waitJob(t, h, findingsJobKey(list[0].ID))
if got := len(c.collected()); got != 3 {
t.Fatalf("%d collections after Collect now, want 3", got)
}
}

func TestFindingsSyncStopsOnCancel(t *testing.T) {
h, list, _, c := findingsSyncFixture(t, 3, "/src")
c.during = func(ctx context.Context, id string) error {
Expand Down
89 changes: 89 additions & 0 deletions lab/internal/ui/findings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,95 @@ func TestFindingsProposeServesALineOnlyWithItsPath(t *testing.T) {
}
}

// findingsTestLifecycle records the change request's observed state on the
// Molecule's receipt.
func findingsTestLifecycle(t *testing.T, lab, id, state string) {
t.Helper()
path := filepath.Join(lab, "deliveries", id+".json")
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
observed := strings.Replace(string(raw), `"state":"published"`, `"state":"published","lifecycle":{"state":"`+state+`","observedAt":"2026-11-02T10:00:00Z"}`, 1)
if err := os.WriteFile(path, []byte(observed), 0600); err != nil {
t.Fatal(err)
}
}

// Item 3 of #386: each open finding serves its body, redacted, control-free
// with its lines kept, and bounded; the snapshot's reviewer plugins are named.
func TestFindingsViewServesFindingBodies(t *testing.T) {
lab := t.TempDir()
r := findingsTestRecord(lab, findingsTestID, true)
findingsTestReceipt(t, lab, r.ID)
explained := findingsTestFinding("a", "high", "src/a.go", "Nil deref")
explained.Body = "The pointer is nil with " + findingsTestSecret + ".\r\n\n\n\x1b[31mSee " + r.Workspace.Path + "/src/a.go\x07 too.\nLast line."
long := findingsTestFinding("b", "medium", "src/b.go", "Long")
long.Body = strings.Repeat("word ", 2000)
bare := findingsTestFinding("c", "low", "src/c.go", "No body")
findingsTestWrite(t, lab, r.ID, nil, findingsTestRound(findingsTestCommit, delivery.FindingsComplete, true, explained, long, bare))
h, _ := findingsTestHandler(t, lab, "/src", r)
v, body := findingsGetView(t, h, r.ID)
if len(v.Open) != 3 || len(v.Plugins) != 1 || v.Plugins[0] != "critic" || v.Lifecycle != "" {
t.Fatalf("view %+v", v)
}
got := v.Open[0]
if got.BodyTruncated || !strings.HasPrefix(got.Body, "The pointer is nil with ") || !strings.HasSuffix(got.Body, "\nLast line.") || strings.Count(got.Body, "\n") != 3 || strings.Contains(got.Body, "\n\n\n") {
t.Fatalf("body %q", got.Body)
}
if strings.ContainsAny(got.Body, "\r\x1b\x07") || strings.Contains(got.Body, findingsTestSecret) || strings.Contains(body, r.Workspace.Path) {
t.Fatalf("body served unredacted: %q", got.Body)
}
if n := len([]rune(v.Open[1].Body)); !v.Open[1].BodyTruncated || n == 0 || n > findingsMaxBodyRunes {
t.Fatalf("long body: %d runes, truncated %v", n, v.Open[1].BodyTruncated)
}
if v.Open[2].Body != "" || v.Open[2].BodyTruncated || strings.Count(body, `"body":`) != 2 {
t.Fatalf("an empty body was served: %+v", v.Open[2])
}
}

// Item 5 of #386: the engine's "this Lab's Formula declares no reviewers" is
// its own refusal, whose next step names the Formula mismatch.
func TestFindingsProposeNoActiveReviewersReason(t *testing.T) {
_, r, h, fake := findingsTestLab(t, "/src")
fake.proposeErr = delivery.ErrNoReviewers
got := findingsRefusalOf(t, do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)), http.StatusConflict, "no-active-reviewers")
if got.Error != "this Lab's Formula declares no reviewers; nothing was proposed" || got.Reason != findingsReasons["no-active-reviewers"] {
t.Fatalf("refusal %+v", got)
}
if !strings.Contains(got.Reason, "This Molecule's Formula snapshot declares reviewers, but the Lab's active approved Formula does not") {
t.Fatalf("reason %q", got.Reason)
}
}

// Item 4 of #386: once the change request is merged or closed, the view says
// so and a proposal is refused without calling the engine.
func TestFindingsProposeRefusedAfterMergeOrClose(t *testing.T) {
for state, want := range map[string]string{"MERGED": "merged", "CLOSED": "closed"} {
t.Run(state, func(t *testing.T) {
lab, r, h, fake := findingsTestLab(t, "/src")
findingsTestLifecycle(t, lab, r.ID, state)
if v, _ := findingsGetView(t, h, r.ID); v.Lifecycle != want || !v.Published {
t.Fatalf("view lifecycle %q, want %q", v.Lifecycle, want)
}
got := findingsRefusalOf(t, do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)), http.StatusConflict, "not-live")
if got.Reason != findingsReasons["not-live"] {
t.Fatalf("refusal %+v", got)
}
if _, proposes, _, pushes := fake.counts(); proposes != 0 || pushes != 0 {
t.Fatalf("a refused proposal called the engine: %d proposals, %d pushes", proposes, pushes)
}
})
}
// An open change request still proposes.
lab, r, h, fake := findingsTestLab(t, "/src")
findingsTestLifecycle(t, lab, r.ID, "OPEN")
fake.proposal = fixround.Proposal{Round: 1, None: true}
if w := do(t, h, gatePost("/api/molecules/"+r.ID+"/findings/propose", `{"include":[]}`)); w.Code != http.StatusOK {
t.Fatalf("open change request: %d %s", w.Code, w.Body)
}
}

func TestFindingsSampleDataServesNoFindings(t *testing.T) {
h := testHandler(t, Options{Demo: true})
if w := do(t, h, authed("/api/molecules/"+findingsTestID+"/findings")); w.Code != http.StatusNotFound {
Expand Down
Loading
Loading