gunk-dev/the-valley

valley_test.go

sourced9c8073fd613main's published tip history
26.8 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "bufio"
7 "encoding/json"
8 "fmt"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/event"
16 "the-valley/flow/internal/run"
17)
18
19// installValleyStub writes a fake valley with the verbs klaus uses. It logs
20// each call ("<cwd>: <args>") to valley.argv, answers ready with
21// "widget nxvp v1 ready" or, when valley.refuse exists, refuses with its
22// contents, and answers changes with valley.changes.json or, when that is
23// absent, fails as an unreachable valley does. A listing's versions carry
24// their checks only when changes is given --checks (see writeValleyChanges),
25// and changes --checks is refused as an older CLI does when
26// valley.checks-refuse exists, once valley.checks-hold doesn't. Its help lists unready only
27// when valley.has-unready exists; unready answers "widget nxvp v1 draft" or,
28// when valley.unready-refuse exists, refuses with its contents, and creates
29// valley.unready-late if the fake agent had already started. After an
30// unready, the n-th changes answers with valley.changes.unready.<n>.json, or
31// valley.changes.unready.json, when one exists, so a test can say what the
32// valley lists once a change is a draft. Its knot verbs serve the knots
33// writeKnot wrote (see there). Its telemetry verb is unknown, as in a valley
34// without telemetry, until valley.has-telemetry exists; then a follow prints
35// a header, the records of valley.telemetry.jsonl once that appears (one
36// follow takes them), and an end line with a cursor, within 2s. A follow
37// that starts while another runs creates valley.follow-overlap.
38func (h *Harness) installValleyStub() {
39 h.t.Helper()
40 h.WriteStub("valley", fmt.Sprintf(`#!/usr/bin/env bash
41dir=%q
42# One write per call, so calls made at once (a follow beside a check) don't
43# interleave their words.
44line="$PWD:"; for a in "$@"; do line="$line $a"; done
45printf '%%s\n' "$line" >> "$dir/valley.argv"
46case "$1" in
47help)
48 printf 'usage: valley <verb> [args]\n\n ready --change <id> --head <sha> <branch>\n changes [--all] [--json]\n approve <change>\n'
49 if [ -f "$dir/valley.has-unready" ]; then printf ' unready <change>\n'; fi
50 printf ' knot <verb> [args]\n'
51 ;;
52knot)
53 id=$3
54 case "$2" in
55 show)
56 if [ -f "$dir/knot.$id.json" ]; then cat "$dir/knot.$id.json"; exit 0; fi
57 echo "valley: the graph of widget holds no knot $id" >&2
58 exit 1
59 ;;
60 claim)
61 if [ -f "$dir/claude.started" ]; then : > "$dir/knot.claim-late"; fi
62 if [ -f "$dir/knot.claim-refuse" ]; then cat "$dir/knot.claim-refuse" >&2; exit 3; fi
63 echo "knot claim $id: $5 (0000000)"
64 ;;
65 link)
66 if [ -f "$dir/knot.link-refuse" ]; then cat "$dir/knot.link-refuse" >&2; exit 1; fi
67 echo "knot link $id (0000000)"
68 ;;
69 set)
70 if [ -f "$dir/knot.$id.set-refuse" ]; then cat "$dir/knot.$id.set-refuse" >&2; exit 3; fi
71 echo "knot set $id (0000000)"
72 ;;
73 comment)
74 { printf '== %%s\n' "$id"; cat; } >> "$dir/knot.comments"
75 echo "knot comment $id (0000000)"
76 ;;
77 *)
78 echo "knot $2 $id (0000000)"
79 ;;
80 esac
81 ;;
82ready)
83 if [ -f "$dir/valley.refuse" ]; then cat "$dir/valley.refuse" >&2; exit 1; fi
84 echo "widget nxvp v1 ready"
85 ;;
86unready)
87 if [ -f "$dir/claude.started" ]; then : > "$dir/valley.unready-late"; fi
88 if [ -f "$dir/valley.unready-refuse" ]; then cat "$dir/valley.unready-refuse" >&2; exit 1; fi
89 : > "$dir/valley.after-unready"
90 echo "widget nxvp v1 draft"
91 ;;
92telemetry)
93 if [ ! -f "$dir/valley.has-telemetry" ]; then echo "valley: unknown verb $1" >&2; exit 2; fi
94 if ! mkdir "$dir/valley.following" 2>/dev/null; then : > "$dir/valley.follow-overlap"; fi
95 printf '{"kind":"header","format":"valley-telemetry/v1","op":"follow"}\n'
96 for i in 1 2 3 4 5 6 7 8 9 10; do
97 if mv "$dir/valley.telemetry.jsonl" "$dir/valley.telemetry.$$" 2>/dev/null; then cat "$dir/valley.telemetry.$$"; break; fi
98 sleep 0.2
99 done
100 rmdir "$dir/valley.following" 2>/dev/null
101 printf '{"kind":"end","cursor":"c%%s","truncated":false}\n' "$$"
102 ;;
103changes)
104 checks=
105 for a in "$@"; do if [ "$a" = --checks ]; then checks=1; fi; done
106 if [ -n "$checks" ] && [ -f "$dir/valley.checks-refuse" ]; then
107 while [ -f "$dir/valley.checks-hold" ]; do sleep 0.1; done
108 echo "valley: changes does not take --checks" >&2; exit 1
109 fi
110 if [ -n "$checks" ] && [ -f "$dir/valley.changes.checks.json" ]; then cat "$dir/valley.changes.checks.json"; exit 0; fi
111 if [ -f "$dir/valley.after-unready" ]; then
112 echo >> "$dir/valley.after-unready"
113 n=$(wc -l < "$dir/valley.after-unready" | tr -d ' ')
114 for f in "$dir/valley.changes.unready.$n.json" "$dir/valley.changes.unready.json"; do
115 if [ -f "$f" ]; then cat "$f"; exit 0; fi
116 done
117 fi
118 if [ -f "$dir/valley.changes.json" ]; then cat "$dir/valley.changes.json"; exit 0; fi
119 echo "valley: cannot reach valley-host" >&2
120 exit 1
121 ;;
122*)
123 echo "valley: unknown verb $1" >&2
124 exit 2
125 ;;
126esac
127`, h.E2EDir))
128}
129
130// joinValley commits the valley's policy to the sandbox repo's main and
131// pushes it, so the repo delivers to a valley.
132func (h *Harness) joinValley() {
133 h.t.Helper()
134 if err := os.MkdirAll(filepath.Join(h.RepoDir, "policy"), 0o755); err != nil {
135 h.t.Fatal(err)
136 }
137 if err := os.WriteFile(filepath.Join(h.RepoDir, "policy", "valley"), []byte("widget\n"), 0o644); err != nil {
138 h.t.Fatal(err)
139 }
140 h.git(h.RepoDir, "add", "policy")
141 h.git(h.RepoDir, "commit", "-qm", "join the valley")
142 h.git(h.RepoDir, "push", "-q", "origin", "main")
143}
144
145// valleyCalls returns the logged valley calls whose arguments start with
146// verb.
147func (h *Harness) valleyCalls(verb string) []string {
148 data, _ := os.ReadFile(filepath.Join(h.E2EDir, "valley.argv"))
149 var calls []string
150 for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
151 if _, args, ok := strings.Cut(line, ": "); ok && strings.HasPrefix(args, verb) {
152 calls = append(calls, line)
153 }
154 }
155 return calls
156}
157
158// writeValleyChanges sets what the fake valley's changes verb prints.
159func (h *Harness) writeValleyChanges(v any) {
160 h.t.Helper()
161 data, err := json.Marshal(v)
162 if err != nil {
163 h.t.Fatal(err)
164 }
165 // The plain listing leaves out checks; --checks adds them.
166 var plain any
167 if err := json.Unmarshal(data, &plain); err != nil {
168 h.t.Fatal(err)
169 }
170 dropChecks(plain)
171 plainData, err := json.Marshal(plain)
172 if err != nil {
173 h.t.Fatal(err)
174 }
175 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.changes.json"), plainData, 0o644); err != nil {
176 h.t.Fatal(err)
177 }
178 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.changes.checks.json"), data, 0o644); err != nil {
179 h.t.Fatal(err)
180 }
181}
182
183// dropChecks removes the checks of every version in a decoded listing.
184func dropChecks(v any) {
185 switch v := v.(type) {
186 case map[string]any:
187 if _, ok := v["head"]; ok {
188 delete(v, "checks")
189 }
190 for _, c := range v {
191 dropChecks(c)
192 }
193 case []any:
194 for _, c := range v {
195 dropChecks(c)
196 }
197 }
198}
199
200// runEvents returns the session's events for one run, in order.
201func (h *Harness) runEvents(runID string) []event.Event {
202 h.t.Helper()
203 f, err := os.Open(filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "events.jsonl"))
204 if err != nil {
205 h.t.Fatal(err)
206 }
207 defer f.Close()
208 var evts []event.Event
209 sc := bufio.NewScanner(f)
210 for sc.Scan() {
211 var e event.Event
212 if json.Unmarshal(sc.Bytes(), &e) == nil && e.RunID == runID {
213 evts = append(evts, e)
214 }
215 }
216 return evts
217}
218
219// TestFinalizeMarksValleyChangeReady launches an agent that commits and
220// pushes its branch, and lets the real finalize run against a fake valley:
221// in a repo that carries the valley's policy it marks the head ready and
222// records the version; in a plain direct-push repo it never runs valley; and
223// a refusal is recorded without failing finalize. The agent's log names a
224// GitHub PR, as a test fixture would, and none of these runs takes it for
225// theirs: their repos deliver by push.
226func TestFinalizeMarksValleyChangeReady(t *testing.T) {
227 for _, tc := range []struct {
228 name string
229 policy bool
230 refuse string
231 }{
232 {name: "valley repo", policy: true},
233 {name: "direct-push repo without the policy"},
234 {name: "valley refuses", policy: true, refuse: "valley: refused: no principal for this host\n(set valley.principal)\n"},
235 } {
236 t.Run(tc.name, func(t *testing.T) {
237 t.Parallel()
238 h := NewHarness(t)
239 h.installValleyStub()
240 if tc.policy {
241 h.joinValley()
242 }
243 if tc.refuse != "" {
244 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.refuse"), []byte(tc.refuse), 0o644); err != nil {
245 t.Fatal(err)
246 }
247 }
248 const fixturePR = "https://github.com/acme/widget/pull/7"
249 h.WriteDefaultClaudeOutput(`{"type":"user","message":{"content":[{"type":"tool_result","content":"--- FAIL: want ` + fixturePR + `"}]}}
250{"type":"assistant","message":{"content":[{"type":"text","text":"The knot links ` + fixturePR + `; fixing the test."}]}}
251{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"11111111-2222-4333-8444-555555555555"}` + "\n")
252
253 res := h.RunKlaus("launch", "add a health check endpoint")
254 if res.ExitCode != 0 {
255 t.Fatalf("launch exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
256 }
257 id := h.RunIDs()[0]
258 h.WaitForClaudeStart(30 * time.Second)
259 st, err := h.ReadState(id)
260 if err != nil {
261 t.Fatal(err)
262 }
263 worktree := st.Worktree
264 if err := os.WriteFile(filepath.Join(worktree, "health.go"), []byte("package health\n"), 0o644); err != nil {
265 t.Fatal(err)
266 }
267 h.git(worktree, "add", "-A")
268 h.git(worktree, "commit", "-qm", "Add a health check")
269 h.git(worktree, "push", "-q", "origin", st.Branch)
270 head := h.GitOutput(worktree, "rev-parse", "HEAD")
271
272 h.ReleaseClaude()
273 st = h.WaitForState(id, func(s *run.State) bool {
274 return s.DurationMS != nil && s.TmuxPane == nil && s.Worktree == ""
275 }, 60*time.Second)
276 if st.Delivery != run.DeliveryPush {
277 t.Errorf("delivery = %q, want %q", st.Delivery, run.DeliveryPush)
278 }
279 if st.PRURL != nil {
280 t.Errorf("PR URL = %q, want none from a run that delivers by push", *st.PRURL)
281 }
282 if st.PushedBranch == nil || *st.PushedBranch != st.Branch {
283 t.Errorf("pushed branch = %v, want %s", st.PushedBranch, st.Branch)
284 }
285 if st.PushedSHA == nil || *st.PushedSHA != head {
286 t.Fatalf("pushed SHA = %v, want %s", st.PushedSHA, head)
287 }
288 // The head's subject titles the change's row, valley or not.
289 if st.PushedSubject != "Add a health check" {
290 t.Errorf("pushed subject = %q, want the head's subject", st.PushedSubject)
291 }
292
293 var types []string
294 var ready map[string]any
295 for _, e := range h.runEvents(id) {
296 types = append(types, e.Type)
297 if e.Type == event.AgentChangeReady {
298 ready = e.Data
299 }
300 }
301 calls := h.valleyCalls("ready")
302
303 switch {
304 case !tc.policy:
305 if len(calls) != 0 || st.Valley != nil || ready != nil {
306 t.Errorf("a repo without the policy must not run valley ready: calls %v, valley %+v, event %v", calls, st.Valley, ready)
307 }
308 case tc.refuse != "":
309 if st.Valley == nil || st.Valley.Handle != "" ||
310 st.Valley.Error != "valley ready: valley: refused: no principal for this host; (set valley.principal)" {
311 t.Errorf("refusal recorded as %+v", st.Valley)
312 }
313 if ready != nil {
314 t.Errorf("a refused change must not emit agent:change-ready: %v", ready)
315 }
316 default:
317 want := fmt.Sprintf("%s: ready --change %s --head %s %s", worktree, st.ChangeID, head, st.Branch)
318 if len(calls) != 1 || calls[0] != want {
319 t.Errorf("valley ready calls = %q, want [%q]", calls, want)
320 }
321 if st.Valley == nil || *st.Valley != (run.Valley{Repo: "widget", Handle: "nxvp", Version: 1, Title: "Add a health check"}) {
322 t.Errorf("recorded valley = %+v", st.Valley)
323 }
324 // Its own fields, and the keys every run event carries: the
325 // valley's name for the repo is the one it reported.
326 wantData := map[string]any{"id": id, "repo": "widget", "change_id": st.ChangeID, "handle": "nxvp",
327 "version": float64(1), "title": "Add a health check", "head": head,
328 "repo_key": "valley:widget", "key": "valley:widget@" + st.ChangeID, "dispatch_reason": "launch", "head_sha": head}
329 if fmt.Sprint(ready) != fmt.Sprint(wantData) {
330 t.Errorf("agent:change-ready data = %v, want %v", ready, wantData)
331 }
332 }
333 for _, typ := range types {
334 if typ == event.AgentPRCreated {
335 t.Errorf("a run that delivers by push must not emit %s: events %v", typ, types)
336 }
337 }
338 // Finalize always completes, and the branch is reported pushed before
339 // any valley call; the finalize phase ends after both.
340 want := []string{event.AgentCompleted, event.AgentBranchPushed}
341 if ready != nil {
342 want = append(want, event.AgentChangeReady)
343 }
344 want = append(want, event.PhaseCompleted)
345 if len(types) < len(want) || strings.Join(types[len(types)-len(want):], ",") != strings.Join(want, ",") {
346 t.Errorf("events = %v, want them to end with %v", types, want)
347 }
348 })
349 }
350}
351
352// valleyRun seeds a run that finalize marked ready on the valley as version
353// version of a change with the given handle, pushed at sha from the sandbox
354// repo.
355func (h *Harness) valleyRun(id, prompt, handle, title string, version int, sha string, created time.Time) *run.State {
356 h.t.Helper()
357 clone, branch, cost := h.RepoDir, "agent/"+id, 1.0
358 changeID := handle + strings.Repeat("k", 32-len(handle))
359 st := &run.State{
360 ID: id, Type: "launch", Prompt: prompt, TargetRepo: strPtrE2E("acme/widget"), CloneDir: &clone,
361 Branch: branch, PushedBranch: &branch, PushedSHA: &sha, CostUSD: &cost, ChangeID: changeID,
362 CreatedAt: created.Format(time.RFC3339),
363 Valley: &run.Valley{Repo: "widget", Handle: handle, Version: version, Title: title},
364 }
365 h.SeedState(st)
366 return st
367}
368
369// version is a valley-changes/v1 version.
370func version(n int, head, title, landing string) map[string]any {
371 return map[string]any{"n": n, "head": head, "title": title, "branch": "agent/x", "uploader": "operator",
372 "landing": landing, "landed_commit": nil, "request": nil, "outcome": nil}
373}
374
375// change is a valley-changes/v1 change record.
376func change(st *run.State, state string, active int, versions ...map[string]any) map[string]any {
377 return map[string]any{"change_id": st.ChangeID, "handle": st.Valley.Handle, "target": "main", "owner": "operator",
378 "state": state, "record": "0000000000000000000000000000000000000000", "seq": 1, "active": active,
379 "versions": versions, "includes": []string{}}
380}
381
382// startDashboard runs the real dashboard in its own tmux session and returns
383// a function that waits until the screen shows every wanted string.
384func (h *Harness) startDashboard(width int) (pane string, screen func(want ...string) string) {
385 h.t.Helper()
386 pane = strings.TrimSpace(h.tmux("new-session", "-d", "-s", "dash", "-x", fmt.Sprint(width), "-y", "16", "-c", h.RepoDir,
387 "-P", "-F", "#{pane_id}", "env KLAUS_SESSION_ID="+h.SessionID+" klaus dashboard"))
388 return pane, func(want ...string) string {
389 h.t.Helper()
390 var last string
391 for deadline := time.Now().Add(30 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Millisecond) {
392 last = h.tmux("capture-pane", "-p", "-t", pane)
393 ok := true
394 for _, w := range want {
395 ok = ok && strings.Contains(last, w)
396 }
397 if ok {
398 return last
399 }
400 }
401 h.t.Fatalf("dashboard screen never showed %q; last screen:\n%s", want, last)
402 return ""
403 }
404}
405
406// rowOf returns the screen line for the row with the given handle.
407func rowOf(t *testing.T, screen, handle string) string {
408 t.Helper()
409 for _, line := range strings.Split(screen, "\n") {
410 if f := strings.Fields(strings.TrimPrefix(line, ">")); len(f) > 1 && f[1] == handle {
411 return line
412 }
413 }
414 t.Fatalf("no row for %s on screen:\n%s", handle, screen)
415 return ""
416}
417
418// TestDashboardShowsValleyChanges runs the real dashboard and klaus status
419// over runs a fake valley reports in every state: each valley row shows the
420// repo, the handle and the title, under its label and in its group, and the
421// footer offers the approve command bound to the head on screen. A change
422// whose active version was marked ready elsewhere reads as that version,
423// while klaus status shows the local run's own version as an older version.
424func TestDashboardShowsValleyChanges(t *testing.T) {
425 t.Parallel()
426 h := NewHarness(t)
427 h.installValleyStub()
428 h.AmendRepoConfig(map[string]any{
429 "dashboard": map[string]any{"approve_command": "cd ~/hack/{repo} && valley approve {handle} --head {head}"},
430 })
431 sha := func(c byte) string { return strings.Repeat(string(c), 40) }
432 ago := func(m int) time.Time { return time.Now().Add(-time.Duration(m) * time.Minute) }
433
434 ready := h.valleyRun("20261013-0900-0001", "prompt one", "nxvp", "Add a health check", 1, sha('1'), ago(5))
435 uncertain := h.valleyRun("20261013-0900-0002", "prompt two", "uncr", "Tune the cache", 1, sha('2'), ago(10))
436 landed := h.valleyRun("20261013-0900-0003", "prompt three", "lndd", "Fix the build", 1, sha('3'), ago(15))
437 superseded := h.valleyRun("20261013-0900-0004", "prompt four", "sprs", "Rename the flag", 1, sha('4'), ago(20))
438 withdrawn := h.valleyRun("20261013-0900-0005", "prompt five", "wdrn", "Drop the shim", 1, sha('5'), ago(25))
439
440 uncertainV := version(1, sha('2'), "Tune the cache", "uncertain")
441 uncertainV["request"] = map[string]any{"ref": "refs/valley/requests/uncr", "commit": sha('a')}
442 uncertainV["outcome"] = map[string]any{"decision": "failed", "head": sha('2'), "tip": sha('b')}
443 landedV := version(1, sha('3'), "Fix the build", "landed")
444 landedV["landed_commit"] = sha('3')
445 h.writeValleyChanges(map[string]any{
446 "schema": "valley-changes/v1",
447 "host": "valley-host",
448 "repos": []any{map[string]any{
449 "repo": "widget", "url": "git@valley-host:widget.git", "error": nil,
450 "changes": []any{
451 change(ready, "ready", 1, version(1, sha('1'), "Add a health check", "not-landed")),
452 change(uncertain, "ready", 1, uncertainV),
453 change(landed, "ready", 1, landedV),
454 change(superseded, "ready", 2, version(1, sha('4'), "Rename the flag", "not-landed"),
455 version(2, sha('6'), "Rename the flag", "not-landed")),
456 change(withdrawn, "withdrawn", 1, version(1, sha('5'), "Drop the shim", "not-landed")),
457 },
458 "branches": []any{},
459 }},
460 })
461
462 pane, screen := h.startDashboard(170)
463 s := screen("3 yours", "2 done", "READY v2@6666666", "approve: cd ~/hack/widget && valley approve nxvp --head "+sha('1'))
464 for handle, want := range map[string]string{
465 "nxvp": "Add a health check",
466 "uncr": "Tune the cache",
467 "lndd": "Fix the build",
468 "sprs": "Rename the flag",
469 "wdrn": "Drop the shim",
470 } {
471 row := rowOf(t, s, handle)
472 if f := strings.Fields(strings.TrimPrefix(row, ">")); f[0] != "widget" || !strings.Contains(row, want) || strings.Contains(row, "prompt ") {
473 t.Errorf("%s: row should show repo widget, handle and title %q, not the prompt: %q", handle, want, row)
474 }
475 }
476 // Yours first (most recent first), then done.
477 labels := []string{"READY v1@1111111", "UNCERTAIN", "READY v2@6666666", "INTEGRATED", "WITHDRAWN"}
478 var order []string
479 for _, line := range strings.Split(s, "\n") {
480 for _, l := range labels {
481 if strings.Contains(line, l) {
482 order = append(order, l)
483 }
484 }
485 }
486 if strings.Join(order, ",") != strings.Join(labels, ",") {
487 t.Errorf("labels in order %v, want %v:\n%s", order, labels, s)
488 }
489
490 // Moving the selection doesn't ask the valley again: one listing per
491 // minute, for every run.
492 h.tmux("send-keys", "-t", pane, "j")
493 screen("> widget uncr")
494 if calls := h.valleyCalls("changes"); len(calls) != 1 || !strings.HasSuffix(calls[0], ": changes --all --json --checks") {
495 t.Errorf("valley changes calls = %q, want one", calls)
496 }
497
498 res := h.RunKlaus("status")
499 if res.ExitCode != 0 {
500 t.Fatalf("status exited %d; stderr: %s", res.ExitCode, res.Stderr)
501 }
502 for _, tc := range []struct {
503 st *run.State
504 status string
505 }{
506 {ready, "awaiting-approval"},
507 {uncertain, "uncertain"},
508 {landed, "integrated"},
509 {superseded, "older-version"},
510 {withdrawn, "withdrawn"},
511 } {
512 // A valley run's row keeps its run ID, names its change by handle
513 // where a PR run shows its number, and shows the change's title.
514 if got := statusOf(t, res.Stdout, tc.st.ID); got != tc.status {
515 t.Errorf("%s: status %q, want %q", tc.st.Valley.Handle, got, tc.status)
516 }
517 if got := changeColumn(t, res.Stdout, tc.st.ID); got != tc.st.Valley.Handle {
518 t.Errorf("%s: CHANGE %q, want the handle %q", tc.st.ID, got, tc.st.Valley.Handle)
519 }
520 if line := statusLine(t, res.Stdout, tc.st.ID); !strings.HasSuffix(line, tc.st.Valley.Title) {
521 t.Errorf("status row should end with the title %q: %q", tc.st.Valley.Title, line)
522 }
523 }
524}
525
526// TestDashboardValleyFailureFallsBackToGit runs the real dashboard while
527// valley can't be reached: valley runs get git's verdicts against their real
528// branches, and a run whose change finalize couldn't mark ready says why.
529func TestDashboardValleyFailureFallsBackToGit(t *testing.T) {
530 t.Parallel()
531 h := NewHarness(t)
532 h.installValleyStub() // no valley.changes.json: changes fails
533
534 landedSHA := h.pushBranch("agent/landed", "l.txt")
535 h.git(h.RepoDir, "push", "-q", "origin", landedSHA+":refs/heads/main")
536 waitingSHA := h.pushBranch("agent/waiting", "w.txt")
537 refusedSHA := h.pushBranch("agent/refused", "r.txt")
538 landed := h.valleyRun("20261013-0900-0001", "prompt one", "lndd", "Fix the build", 1, landedSHA, time.Now().Add(-10*time.Minute))
539 landed.PushedBranch = strPtrE2E("agent/landed")
540 h.SeedState(landed)
541 waiting := h.valleyRun("20261013-0900-0002", "prompt two", "wait", "Tune the cache", 2, waitingSHA, time.Now().Add(-5*time.Minute))
542 waiting.PushedBranch = strPtrE2E("agent/waiting")
543 h.SeedState(waiting)
544 refused := h.valleyRun("20261013-0900-0003", "refused one", "", "", 0, refusedSHA, time.Now().Add(-20*time.Minute))
545 refused.PushedBranch = strPtrE2E("agent/refused")
546 refused.Valley = &run.Valley{Title: "Drop the shim", Error: "valley ready: refused: no principal"}
547 h.SeedState(refused)
548
549 _, screen := h.startDashboard(170)
550 s := screen("INTEGRATED", "2 yours", "1 done")
551 if row := rowOf(t, s, "lndd"); !strings.Contains(row, "Fix the build") || !strings.Contains(row, "INTEGRATED") {
552 t.Errorf("landed change should show INTEGRATED from git: %q", row)
553 }
554 if row := rowOf(t, s, "wait"); !strings.Contains(row, "READY v2@"+waitingSHA[:7]) {
555 t.Errorf("waiting change should still read READY: %q", row)
556 }
557 var refusedRow string
558 for _, line := range strings.Split(s, "\n") {
559 if strings.Contains(line, "refused one") {
560 refusedRow = line
561 }
562 }
563 if !strings.Contains(refusedRow, "SUBMIT agent/refused@"+refusedSHA[:7]) || !strings.Contains(refusedRow, "valley ready: refused: no principal") {
564 t.Errorf("a run finalize couldn't mark ready should show SUBMIT and why: %q\n%s", refusedRow, s)
565 }
566 if !strings.Contains(s, "valley unreachable: valley: cannot reach valley-host; showing git's view") {
567 t.Errorf("the dashboard should say the valley check failed:\n%s", s)
568 }
569 if calls := h.valleyCalls("changes"); len(calls) != 1 {
570 t.Errorf("valley changes calls = %q, want one failed attempt", calls)
571 }
572
573 res := h.RunKlaus("status")
574 if res.ExitCode != 0 {
575 t.Fatalf("status exited %d\n%s%s", res.ExitCode, res.Stdout, res.Stderr)
576 }
577 if !strings.Contains(res.Stderr, "valley unreachable: valley: cannot reach valley-host; showing git's view") {
578 t.Errorf("status should note the failed valley check on stderr: %q", res.Stderr)
579 }
580 h.writeValleyChanges(map[string]any{"schema": "valley-changes/v1", "host": "h", "repos": []any{}})
581 if res := h.RunKlaus("status"); strings.Contains(res.Stderr, "valley unreachable") {
582 t.Errorf("status should not note a valley that answered: %q", res.Stderr)
583 }
584}
585
586// TestDashboardWakesOnValleyDecision runs the real dashboard over a valley
587// change while the fake valley's telemetry reports a landing: the host is
588// followed by one follow at a time, of every stream, the decision wakes the
589// integration check at once, well before the minute's check, a burst of
590// records costs one check, and each follow resumes from the cursor the last
591// one ended with. The listing, not the record, says the change landed.
592func TestDashboardWakesOnValleyDecision(t *testing.T) {
593 t.Parallel()
594 h := NewHarness(t)
595 h.installValleyStub()
596 if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.has-telemetry"), nil, 0o644); err != nil {
597 t.Fatal(err)
598 }
599 head := strings.Repeat("1", 40)
600 st := h.valleyRun("20261102-2047-0001", "prompt one", "nxvp", "Add a health check", 1, head, time.Now().Add(-5*time.Minute))
601 listing := func(landing string) map[string]any {
602 return map[string]any{
603 "schema": "valley-changes/v1",
604 "host": "valley-host",
605 "repos": []any{map[string]any{
606 "repo": "widget", "url": "git@valley-host:widget.git", "error": nil,
607 "changes": []any{change(st, "ready", 1, version(1, head, "Add a health check", landing))},
608 "branches": []any{},
609 }},
610 }
611 }
612 h.writeValleyChanges(listing("not-landed"))
613
614 _, screen := h.startDashboard(170)
615 screen("READY v1@1111111")
616 // Every stream is followed, from the run's clone.
617 for deadline := time.Now().Add(15 * time.Second); ; time.Sleep(100 * time.Millisecond) {
618 followed := false
619 for _, c := range h.valleyCalls("telemetry") {
620 followed = followed || c == h.RepoDir+": telemetry --json follow"
621 }
622 if followed {
623 break
624 }
625 if time.Now().After(deadline) {
626 t.Fatalf("the dashboard should follow the host's every stream; valley calls: %q", h.valleyCalls(""))
627 }
628 }
629 if calls := h.valleyCalls("changes"); len(calls) != 1 {
630 t.Fatalf("valley changes calls = %q, want the first check's alone", calls)
631 }
632
633 // The integrator lands the change: its decision and the worker's
634 // evidence arrive together.
635 h.writeValleyChanges(listing("landed"))
636 records := `{"kind":"record","stream":"integrator","seq":8,"type":"decision","project":"widget","change":"` + st.ChangeID + `","data":{"outcome":"land"}}
637{"kind":"record","stream":"worker","seq":920,"type":"evidence.stored","data":{}}
638{"kind":"record","stream":"worker","seq":921,"type":"batch.end","data":{}}
639`
640 tmp := filepath.Join(h.E2EDir, "telemetry.tmp")
641 if err := os.WriteFile(tmp, []byte(records), 0o644); err != nil {
642 t.Fatal(err)
643 }
644 woke := time.Now()
645 if err := os.Rename(tmp, filepath.Join(h.E2EDir, "valley.telemetry.jsonl")); err != nil {
646 t.Fatal(err)
647 }
648 screen("INTEGRATED")
649 if d := time.Since(woke); d > 20*time.Second {
650 t.Errorf("the change read INTEGRATED %s after the decision; a decision should wake the check at once", d)
651 }
652 time.Sleep(3 * time.Second) // room for any further check
653 if calls := h.valleyCalls("changes"); len(calls) != 2 {
654 t.Errorf("valley changes calls = %q, want one more check for the burst", calls)
655 }
656 resumed := false
657 for _, c := range h.valleyCalls("telemetry") {
658 resumed = resumed || strings.HasPrefix(c, h.RepoDir+": telemetry --json follow --since c")
659 if strings.Contains(c, "--source") {
660 t.Errorf("a follow should name no source, so one follow carries every stream: %q", c)
661 }
662 }
663 if !resumed {
664 t.Errorf("a follow should resume from the last one's cursor; valley calls: %q", h.valleyCalls("telemetry"))
665 }
666 if _, err := os.Stat(filepath.Join(h.E2EDir, "valley.follow-overlap")); err == nil {
667 t.Errorf("the dashboard should hold one follow of the host at a time; valley calls: %q", h.valleyCalls("telemetry"))
668 }
669}