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
41 changes: 32 additions & 9 deletions packages/cuttle/internal/jev/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ var (
errTaskRequired = errors.New("--task is required")
errNoSteps = errors.New("--max-steps must be at least 1")
errNoStartPage = errors.New("the session has no page - pass --url, or navigate first with cuttle pw")
// The mock never answers done, which is the only way an extract is reached,
// and it has no judgement to pick lines with even if it did.
// An extract runs on whatever page the run ended on, so the mock reaches one
// on every ending - and it has no judgement to pick lines with.
errMockExtract = errors.New("--extract needs the model's judgement and cannot run with --mock")
// errBadAnswer covers the two ways an answer is unusable once it is back: a
// key that does not parse, and a value name nobody supplied. Neither is the
Expand Down Expand Up @@ -168,7 +168,7 @@ func (l *loop) run(ctx context.Context) (int, error) {
// stale page. Recognizing that is worth more than any action the loop
// could take next, and the modal block itself names the verb that clears
// it (dialog-accept / dialog-dismiss).
return l.stop(ExitBlocked, snap, "the page is parked behind a native dialog: "+snap.Modal), nil
return l.stop(ctx, ExitBlocked, snap, "the page is parked behind a native dialog: "+snap.Modal), nil
}
// Without --url the run starts wherever the session already is, and a fresh
// session is a blank tab: there is nothing to read, nothing to pick, and the
Expand All @@ -194,13 +194,13 @@ func (l *loop) run(ctx context.Context) (int, error) {
return ExitError, fmt.Errorf("the task is done at <%s>, but the extract failed: %w", snap.URL, err)
}
}
return l.stop(ExitDone, snap, "the task is done"), nil
return l.stop(ctx, ExitDone, snap, "the task is done"), nil
case dec.Blocked >= doneThreshold:
l.report(step, snap, dec, "blocked")
return l.stop(ExitBlocked, snap, "the task needs an action this loop cannot take"), nil
return l.stop(ctx, ExitBlocked, snap, "the task needs an action this loop cannot take"), nil
case dec.Key == noneKey || dec.Key == "":
l.report(step, snap, dec, noneKey)
return l.stop(ExitBlocked, snap, "nothing on this page makes progress toward the task"+l.valueHint(snap)), nil
return l.stop(ctx, ExitBlocked, snap, "nothing on this page makes progress toward the task"+l.valueHint(snap)), nil
}

chosen, ok := find(candidates, dec.Key)
Expand All @@ -209,7 +209,7 @@ func (l *loop) run(ctx context.Context) (int, error) {
// not one of them is a malformed answer aimed at an element nobody
// vouched for - and acting on it would aim a prepared value at nothing.
l.report(step, snap, dec, dec.Key)
return l.stop(ExitBlocked, snap, fmt.Sprintf("chose %q, which this page did not offer", dec.Key)), nil
return l.stop(ctx, ExitBlocked, snap, fmt.Sprintf("chose %q, which this page did not offer", dec.Key)), nil
}
l.report(step, snap, dec, chosen.Label)
if err := l.act(ctx, snap, chosen); err != nil {
Expand All @@ -225,7 +225,7 @@ func (l *loop) run(ctx context.Context) (int, error) {
if final, err := l.settle(ctx); err == nil {
snap = final
}
return l.stop(ExitMaxSteps, snap, fmt.Sprintf("gave up after %d steps with the task unfinished", l.MaxSteps)), nil
return l.stop(ctx, ExitMaxSteps, snap, fmt.Sprintf("gave up after %d steps with the task unfinished", l.MaxSteps)), nil
}

func (l *loop) state(snap Snapshot, candidates []candidate) state {
Expand Down Expand Up @@ -474,6 +474,18 @@ func (l *loop) extract(ctx context.Context, snap Snapshot) error {
return nil
}

// noteExtractFailed reports an extract that failed on an ending that was already
// going to be non-zero. Masking a blocked or out-of-budget run with an exit 1
// would cost the caller the outcome it branches on, so this says what was lost
// and nothing else changes.
func (l *loop) noteExtractFailed(err error) {
if l.JSON {
_ = l.emit(map[string]any{"extract": l.Extract, "failed": true, "trouble": firstLine(err.Error())})
return
}
fmt.Fprintf(l.Err, "%s %s\n", l.err.paint("cuttle jev-browse: the extract failed:", yellow), firstLine(err.Error()))
}

// extractState is the whole state an extract call sees: what was asked for, and
// the page lines to judge against it. The questions address both by name, so it
// is a shape of its own rather than the browsing state with fields left empty.
Expand Down Expand Up @@ -591,7 +603,18 @@ func (l *loop) note(entry Step, trouble string) {
// still live at exactly this page, so the brief says where it is and the literal
// command that picks it up - which is what makes a blocked run something a
// person or an agent can continue rather than something they have to restart.
func (l *loop) stop(code int, snap Snapshot, reason string) int {
func (l *loop) stop(ctx context.Context, code int, snap Snapshot, reason string) int {
// An extract's lifetime is the page the run ended on, not the ending that got
// there: a run that stopped blocked or out of budget still stopped on a page,
// and the caller asked for those lines by name. The done path extracts before
// this, because there a failed extract is the whole result and turns the run
// into an error; here the outcome being reported is the real one, so a failed
// extract is a line of its own and the code stands.
if l.Extract != "" && code != ExitDone {
if err := l.extract(ctx, snap); err != nil {
l.noteExtractFailed(err)
}
}
url := l.stopURL(snap)
if l.JSON {
_ = l.emit(map[string]any{
Expand Down
116 changes: 109 additions & 7 deletions packages/cuttle/internal/jev/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"regexp"
"strings"
"testing"
Expand Down Expand Up @@ -597,22 +598,36 @@ func TestRunWritesJSONLines(t *testing.T) {
}
}

// extractTransport says the task is done, then answers the per-line nouls: yes
// for the lines that name a product, no for everything else.
type extractTransport struct{ wanted string }
// extractTransport ends the run (done, unless browse says otherwise), then
// answers the per-line nouls: yes for the lines that name a product, no for
// everything else.
type extractTransport struct {
wanted string
// browse overrides the browsing step's answers, so the same fake can script a
// run that ends blocked or out of budget instead of done.
browse map[string]answer
// broken is what the extract call fails with, for the endings where a failed
// extract must not become the outcome.
broken error
}

func (e extractTransport) evaluate(_ context.Context, req request) (response, error) {
st, ok := req.State.(extractState)
if !ok {
// The browsing step: done on the first read, so the run is only its extract.
// The browsing step: done on the first read unless browse scripts another
// ending, so the run is only its extract.
answers := map[string]answer{questionDone: {Noul: 0.99}, questionBlocked: {}}
maps.Copy(answers, e.browse)
for id, q := range req.Questions {
if q.Type == typeChoice {
if _, scripted := answers[id]; !scripted && q.Type == typeChoice {
answers[id] = answer{Choice: noneKey, Confidence: 1}
}
}
return response{Answers: answers}, nil
}
if e.broken != nil {
return response{}, e.broken
}
answers := make(map[string]answer, len(st.Lines))
for i, line := range st.Lines {
noul := 0.0
Expand Down Expand Up @@ -643,8 +658,95 @@ func TestRunExtractsLinesVerbatim(t *testing.T) {
}
}

// The mock never answers done, so an extract under it could never run - and it
// has no judgement to pick lines with. Saying so beats a run that silently skips it.
// An extract's lifetime is the page the run ended on, not the ending that got
// there. A blocked run stopped on a page, and the lines the caller asked for are
// on it - which is also why the brief that follows still names that page.
func TestRunExtractsOnABlockedEnding(t *testing.T) {
tr := extractTransport{wanted: "Cart", browse: map[string]answer{
questionDone: {}, questionBlocked: {Noul: 0.99},
}}
d := &fakeDriver{pages: []string{readFixture(t, "signin.snapshot")}}
res := runLoop(t, d, Options{transport: tr, Extract: "the cart link", MaxSteps: 1})
if res.err != nil {
t.Fatalf("run: %v", res.err)
}
if res.code != ExitBlocked {
t.Fatalf("exit code: got %d, want %d - an extract must not change the outcome", res.code, ExitBlocked)
}
if !strings.Contains(res.stdout, "- Cart (0)") {
t.Errorf("the blocked ending skipped the extract:\n%s", res.stdout)
}
if !strings.Contains(res.stderr, "page: <"+signinURL+">") {
t.Errorf("the brief no longer names the page the lines came from:\n%s", res.stderr)
}
}

// The budget running out is the ending most worth extracting from: the run got
// somewhere, it just ran out of steps to finish. --json carries the same extract
// object here as on a done run, ahead of the outcome.
func TestRunExtractsWhenTheBudgetRunsOut(t *testing.T) {
tr := extractTransport{wanted: "Cart", browse: map[string]answer{
questionDone: {}, "pick0": {Choice: "f2e11", Confidence: 0.9},
}}
d := &fakeDriver{pages: []string{readFixture(t, "signin.snapshot")}}
res := runLoop(t, d, Options{transport: tr, Extract: "the cart link", MaxSteps: 1, JSON: true})
if res.err != nil {
t.Fatalf("run: %v", res.err)
}
if res.code != ExitMaxSteps {
t.Fatalf("exit code: got %d, want %d", res.code, ExitMaxSteps)
}
var extracted, last map[string]any
for line := range strings.SplitSeq(strings.TrimSpace(res.stdout), "\n") {
var obj map[string]any
if err := json.Unmarshal([]byte(line), &obj); err != nil {
t.Fatalf("not JSON: %q: %v", line, err)
}
if _, ok := obj["lines"]; ok {
extracted = obj
}
last = obj
}
if extracted == nil {
t.Fatalf("no extract object was emitted:\n%s", res.stdout)
}
if got := fmt.Sprint(extracted["lines"]); !strings.Contains(got, "Cart (0)") {
t.Errorf("extracted lines: got %v, want the line the model picked", got)
}
if last["outcome"] != "max-steps" {
t.Errorf("the extract replaced the outcome: %v", last)
}
}

// errExtractRefused stands in for an extract call the API would not answer.
var errExtractRefused = errors.New("the API said no")

// An extract that fails on an ending that was already non-zero must not mask it:
// the caller branches on 3 and 4, and an exit 1 would cost it the one fact the
// run produced.
func TestRunExtractFailureKeepsTheExitCode(t *testing.T) {
tr := extractTransport{
browse: map[string]answer{questionDone: {}, questionBlocked: {Noul: 0.99}},
broken: errExtractRefused,
}
d := &fakeDriver{pages: []string{readFixture(t, "signin.snapshot")}}
res := runLoop(t, d, Options{transport: tr, Extract: "the cart link", MaxSteps: 1})
if res.err != nil {
t.Fatalf("run: %v, want the blocked outcome to stand", res.err)
}
if res.code != ExitBlocked {
t.Fatalf("exit code: got %d, want %d", res.code, ExitBlocked)
}
if !strings.Contains(res.stderr, "the extract failed: the API said no") {
t.Errorf("the failed extract was not reported:\n%s", res.stderr)
}
if !strings.Contains(res.stderr, "cuttle pw snapshot") {
t.Errorf("the handoff brief was lost to the failed extract:\n%s", res.stderr)
}
}

// The mock reaches an extract on every ending now, and it has no judgement to
// pick lines with. Saying so up front beats a run that silently skips it.
func TestRunRefusesExtractWithTheMock(t *testing.T) {
d := &fakeDriver{pages: []string{readFixture(t, "signin.snapshot")}}
res := runLoop(t, d, Options{Mock: true, Extract: "the cart link"})
Expand Down
Loading