gunk-dev/the-valley

harness_test.go

source6a6791929c36main's published tip history
23.6 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "bytes"
7 "encoding/json"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "the-valley/flow/internal/run"
17)
18
19// Harness is a fully isolated environment for driving the real klaus binary.
20//
21// Isolation guarantees (so tests never touch the developer's real tmux server
22// or ~/.klaus state):
23// - tmux: a private server on a per-test unix socket (Sock). klaus' own tmux
24// calls are pointed at it via the $TMUX env var; the test's control-plane
25// queries use `tmux -S <Sock>`.
26// - state: HOME is a per-test temp dir, so all ~/.klaus/sessions state lands
27// under Home. The harness's session exists, as a coordinator's does:
28// flow never creates a session it is asked to look up.
29// - externals: a per-test bin dir (BinDir) is prepended to PATH and holds the
30// klaus binary plus fake `claude`/`gh` stubs. git and tmux stay real.
31//
32// A unique socket name + temp HOME per test keeps tests parallel-safe.
33type Harness struct {
34 t *testing.T
35
36 Home string // temp HOME ($HOME for all klaus invocations)
37 BinDir string // dir prepended to PATH; holds klaus + stubs
38 E2EDir string // scratch dir for stub coordination/log files
39 RepoDir string // sandbox repo working tree (CWD for klaus)
40 OriginDir string // bare "origin" remote backing RepoDir
41
42 Sock string // tmux server socket path (isolated server)
43 ServerPID string // isolated tmux server pid (for the $TMUX value)
44 InitialPane string // the session's first pane id (klaus splits from here)
45
46 SessionID string // KLAUS_SESSION_ID for all invocations
47 StateRoot string // where the session's root is: Home/.klaus, or Home/.valley/flow after UseFlowNames
48 shellWrap string // path to the no-profile shell wrapper for tmux panes
49}
50
51// RunResult is the outcome of a klaus invocation.
52type RunResult struct {
53 Stdout string
54 Stderr string
55 ExitCode int
56}
57
58// NewHarness builds nothing (the binary is built once in TestMain) but wires up
59// a complete isolated environment: temp HOME, a bin dir with the klaus binary
60// and fake claude/gh stubs, a sandbox git repo with a bare origin, and an
61// isolated tmux server. It registers cleanup to kill the tmux server; temp dirs
62// are removed automatically by t.TempDir.
63func NewHarness(t *testing.T) *Harness {
64 t.Helper()
65
66 if klausBinary == "" {
67 t.Fatal("klaus binary not built (TestMain did not run)")
68 }
69
70 root := t.TempDir()
71 h := &Harness{
72 t: t,
73 Home: filepath.Join(root, "home"),
74 BinDir: filepath.Join(root, "bin"),
75 E2EDir: filepath.Join(root, "e2e"),
76 RepoDir: filepath.Join(root, "repo"),
77 OriginDir: filepath.Join(root, "origin.git"),
78 Sock: filepath.Join(root, "tmux.sock"),
79 // Not session-<time>: a coordinator started by a test resumes the
80 // most recent such session, never this one.
81 SessionID: "e2e-" + filepath.Base(root),
82 }
83 h.StateRoot = filepath.Join(h.Home, ".klaus")
84
85 for _, d := range []string{h.Home, h.BinDir, h.E2EDir, h.SessionDir()} {
86 if err := os.MkdirAll(d, 0o755); err != nil {
87 t.Fatalf("mkdir %s: %v", d, err)
88 }
89 }
90
91 h.installKlausBinary()
92 h.installDefaultStubs()
93 h.setupGitConfig()
94 h.setupSandboxRepo()
95 h.writeRepoConfig()
96 h.startTmuxServer()
97
98 return h
99}
100
101// installKlausBinary copies the prebuilt klaus binary into BinDir as "klaus"
102// so the pane pipeline (which runs `klaus _format-stream`/`klaus _finalize`)
103// resolves it from PATH.
104func (h *Harness) installKlausBinary() {
105 h.t.Helper()
106 data, err := os.ReadFile(klausBinary)
107 if err != nil {
108 h.t.Fatalf("reading klaus binary: %v", err)
109 }
110 dst := filepath.Join(h.BinDir, "klaus")
111 if err := os.WriteFile(dst, data, 0o755); err != nil {
112 h.t.Fatalf("installing klaus binary: %v", err)
113 }
114}
115
116// WriteStub writes an executable script into BinDir, shadowing any real binary
117// of the same name for klaus invocations in this harness. A script that starts
118// with "#!/usr/bin/env bash" runs under the bash on PATH, named by its path:
119// the nix build sandbox the e2e check runs in has no /usr/bin/env.
120func (h *Harness) WriteStub(name, script string) {
121 h.t.Helper()
122 if rest, ok := strings.CutPrefix(script, "#!/usr/bin/env bash\n"); ok {
123 script = "#!" + mustBash(h.t) + "\n" + rest
124 }
125 p := filepath.Join(h.BinDir, name)
126 if err := os.WriteFile(p, []byte(script), 0o755); err != nil {
127 h.t.Fatalf("writing stub %s: %v", name, err)
128 }
129}
130
131// installDefaultStubs writes the fake claude and gh binaries. The claude stub
132// blocks until released (see ReleaseClaude) so tests can deterministically
133// observe the live pane before _finalize tears it down. Tests may override
134// either stub with WriteStub before launching.
135func (h *Harness) installDefaultStubs() {
136 h.t.Helper()
137 h.WriteDefaultClaudeOutput(defaultClaudeOutput)
138 h.WriteStub("claude", h.claudeStubScript())
139 h.WriteStub("gh", h.ghStubScript())
140}
141
142// defaultClaudeOutput is the stream-json the fake agent emits. It contains a PR
143// URL (matched by hidden.go's prURLExtractRegex), which _finalize records for
144// a run whose origin is on GitHub (UseGitHubOrigin), and a result event
145// carrying cost/duration/session_id so _finalize can populate run state.
146const defaultClaudeOutput = `{"type":"system","subtype":"init","model":"claude-e2e"}
147{"type":"assistant","message":{"content":[{"type":"text","text":"Opened PR: https://github.com/acme/widget/pull/4242"}]}}
148{"type":"result","subtype":"success","total_cost_usd":0.1234,"duration_ms":4242,"session_id":"11111111-2222-4333-8444-555555555555"}
149`
150
151// WriteDefaultClaudeOutput sets the JSONL the fake claude prints once released.
152func (h *Harness) WriteDefaultClaudeOutput(jsonl string) {
153 h.t.Helper()
154 if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.output.jsonl"), []byte(jsonl), 0o644); err != nil {
155 h.t.Fatalf("writing claude output: %v", err)
156 }
157}
158
159func (h *Harness) claudeStubScript() string {
160 // Records argv, stdin (unless it is the pane's tty) + cwd, signals start,
161 // blocks until a release file appears (max ~60s), then emits the canned
162 // stream-json. Paths are baked in so the stub is independent of the pane's
163 // environment.
164 return fmt.Sprintf(`#!/usr/bin/env bash
165dir=%q
166{ for a in "$@"; do printf '%%s\n' "$a"; done; } > "$dir/claude.argv"
167[ -t 0 ] || cat > "$dir/claude.stdin"
168printf '%%s' "$PWD" > "$dir/claude.cwd"
169: > "$dir/claude.started"
170for _ in {1..600}; do
171 [ -f "$dir/claude.release" ] && break
172 sleep 0.1
173done
174cat "$dir/claude.output.jsonl"
175`, h.E2EDir)
176}
177
178func (h *Harness) ghStubScript() string {
179 // Logs every invocation so tests can prove how (or whether) gh was called,
180 // and returns benign output. The launch path avoids gh entirely (pr_reviewer
181 // is configured), so this is mostly a safety net against hitting real gh.
182 return fmt.Sprintf(`#!/usr/bin/env bash
183dir=%q
184{ printf 'gh'; for a in "$@"; do printf ' %%q' "$a"; done; printf '\n'; } >> "$dir/gh.argv"
185exit 0
186`, h.E2EDir)
187}
188
189// ReleaseClaude unblocks the fake claude so the pane pipeline proceeds to
190// _format-stream and _finalize.
191func (h *Harness) ReleaseClaude() {
192 h.t.Helper()
193 if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.release"), nil, 0o644); err != nil {
194 h.t.Fatalf("releasing claude: %v", err)
195 }
196}
197
198// WaitForClaudeStart blocks until the fake claude has started running in the
199// pane (or the timeout elapses).
200func (h *Harness) WaitForClaudeStart(timeout time.Duration) {
201 h.t.Helper()
202 started := filepath.Join(h.E2EDir, "claude.started")
203 deadline := time.Now().Add(timeout)
204 for time.Now().Before(deadline) {
205 if _, err := os.Stat(started); err == nil {
206 return
207 }
208 time.Sleep(50 * time.Millisecond)
209 }
210 h.t.Fatalf("fake claude did not start within %s", timeout)
211}
212
213// ClaudeArgv returns the argv the fake claude was invoked with (one entry per
214// line as recorded), or "" if it has not run yet.
215func (h *Harness) ClaudeArgv() string {
216 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "claude.argv"))
217 return string(b)
218}
219
220// ClaudeStdin returns what the fake claude read on stdin — the prompt, for
221// backends that take it there — or "" if stdin was the pane's tty.
222func (h *Harness) ClaudeStdin() string {
223 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "claude.stdin"))
224 return string(b)
225}
226
227// WorkerSystemPrompt returns the system prompt file the fake claude was given
228// with --append-system-prompt-file, failing the test if there is none.
229func (h *Harness) WorkerSystemPrompt() string {
230 h.t.Helper()
231 argv := strings.Split(h.ClaudeArgv(), "\n")
232 for i, a := range argv {
233 if a == "--append-system-prompt-file" && i+1 < len(argv) {
234 data, err := os.ReadFile(argv[i+1])
235 if err != nil {
236 h.t.Fatalf("reading system prompt file: %v", err)
237 }
238 return string(data)
239 }
240 }
241 h.t.Fatalf("claude got no --append-system-prompt-file:\n%s", h.ClaudeArgv())
242 return ""
243}
244
245// GHArgv returns the logged gh invocations (one per line), or "" if gh was
246// never called.
247func (h *Harness) GHArgv() string {
248 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "gh.argv"))
249 return string(b)
250}
251
252// setupGitConfig writes a global gitconfig under the temp HOME so git has a
253// committer identity (needed by data-ref commits) without touching the real
254// user config.
255func (h *Harness) setupGitConfig() {
256 h.t.Helper()
257 cfg := "[user]\n\tname = klaus-e2e\n\temail = klaus-e2e@example.com\n[init]\n\tdefaultBranch = main\n[protocol \"file\"]\n\tallow = always\n[safe]\n\tdirectory = *\n"
258 if err := os.WriteFile(filepath.Join(h.Home, ".gitconfig"), []byte(cfg), 0o644); err != nil {
259 h.t.Fatalf("writing gitconfig: %v", err)
260 }
261}
262
263// setupSandboxRepo creates a bare origin and a working clone with one commit on
264// main, pushed to origin. klaus' worktree/branch/push operations run against
265// these real repos with no network.
266func (h *Harness) setupSandboxRepo() {
267 h.t.Helper()
268 h.git("", "init", "-q", "--bare", "-b", "main", h.OriginDir)
269 h.git("", "init", "-q", "-b", "main", h.RepoDir)
270 if err := os.WriteFile(filepath.Join(h.RepoDir, "README.md"), []byte("# widget\n"), 0o644); err != nil {
271 h.t.Fatalf("seeding repo: %v", err)
272 }
273 h.git(h.RepoDir, "add", "-A")
274 h.git(h.RepoDir, "commit", "-qm", "init")
275 h.git(h.RepoDir, "remote", "add", "origin", h.OriginDir)
276 h.git(h.RepoDir, "push", "-q", "origin", "main")
277}
278
279// writeRepoConfig writes .klaus/config.json pointing WorktreeBase at the temp
280// root and setting pr_reviewer (so launch's prompt render does not shell out to
281// gh). It is committed so worktrees see the same config.
282func (h *Harness) writeRepoConfig() {
283 h.t.Helper()
284 cfgDir := filepath.Join(h.RepoDir, ".klaus")
285 if err := os.MkdirAll(cfgDir, 0o755); err != nil {
286 h.t.Fatalf("mkdir .klaus: %v", err)
287 }
288 cfg := map[string]any{
289 "worktree_base": filepath.Join(filepath.Dir(h.RepoDir), "worktrees"),
290 "default_budget": "5.00",
291 "default_branch": "main",
292 "data_ref": "refs/klaus/data",
293 "pr_reviewer": "acme-bot",
294 }
295 data, _ := json.MarshalIndent(cfg, "", " ")
296 if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), append(data, '\n'), 0o644); err != nil {
297 h.t.Fatalf("writing repo config: %v", err)
298 }
299 h.git(h.RepoDir, "add", "-A")
300 h.git(h.RepoDir, "commit", "-qm", "add klaus config")
301 h.git(h.RepoDir, "push", "-q", "origin", "main")
302}
303
304// UseGitHubOrigin points the sandbox repo's origin at git@github.com:acme/widget.git,
305// so launch treats it as a GitHub repo that gets the PR workflow. An ssh stub
306// serves that URL from the local bare origin, so fetches still work offline.
307func (h *Harness) UseGitHubOrigin() {
308 h.t.Helper()
309 // git runs `ssh [opts] git@github.com "git-upload-pack 'acme/widget.git'"`;
310 // run that service against the local bare origin instead.
311 h.WriteStub("ssh", fmt.Sprintf(`#!/usr/bin/env bash
312service="${@: -1}"
313exec "${service%%%% *}" %q
314`, h.OriginDir))
315 h.git(h.RepoDir, "remote", "set-url", "origin", "git@github.com:acme/widget.git")
316}
317
318// AmendRepoConfig merges the given keys into the sandbox repo's
319// .klaus/config.json. No commit is needed: klaus loads config from the host
320// repo's working tree.
321func (h *Harness) AmendRepoConfig(extra map[string]any) {
322 h.t.Helper()
323 path := filepath.Join(h.RepoDir, ".klaus", "config.json")
324 data, err := os.ReadFile(path)
325 if err != nil {
326 h.t.Fatalf("reading repo config: %v", err)
327 }
328 var cfg map[string]any
329 if err := json.Unmarshal(data, &cfg); err != nil {
330 h.t.Fatalf("parsing repo config: %v", err)
331 }
332 for k, v := range extra {
333 cfg[k] = v
334 }
335 out, err := json.MarshalIndent(cfg, "", " ")
336 if err != nil {
337 h.t.Fatalf("marshaling repo config: %v", err)
338 }
339 if err := os.WriteFile(path, append(out, '\n'), 0o644); err != nil {
340 h.t.Fatalf("writing repo config: %v", err)
341 }
342}
343
344// startTmuxServer launches an isolated tmux server on h.Sock and points its
345// panes at a no-profile shell wrapper so they inherit BinDir-first PATH and the
346// temp HOME (the user's login shell would otherwise reset PATH via the Nix
347// profile). Registers cleanup to kill the server.
348func (h *Harness) startTmuxServer() {
349 h.t.Helper()
350
351 // A wrapper shell that forces a deterministic PATH/HOME and refuses to
352 // source the user's profile. tmux runs pane commands via the default-shell;
353 // without this, a login shell would reset PATH and our stubs/binary would
354 // not be found. It also keeps every pane off the real tmux server: a
355 // process that drops $TMUX finds only this test's TMUX_TMPDIR, and neither
356 // spelling of the socket variable inherited from a klaus worker running
357 // the suite.
358 h.shellWrap = filepath.Join(filepath.Dir(h.BinDir), "shellwrap")
359 tmuxTmp := filepath.Join(filepath.Dir(h.BinDir), "tmuxtmp")
360 if err := os.Mkdir(tmuxTmp, 0o700); err != nil {
361 h.t.Fatalf("mkdir %s: %v", tmuxTmp, err)
362 }
363 wrap := fmt.Sprintf("#!/bin/sh\nexport HOME=%q\nexport PATH=%q\nexport TMUX_TMPDIR=%q\nunset VALLEY_FLOW_TMUX_SOCKET KLAUS_TMUX_SOCKET\nexec %q --noprofile --norc \"$@\"\n",
364 h.Home, h.BinDir+":"+os.Getenv("PATH"), tmuxTmp, mustBash(h.t))
365 if err := os.WriteFile(h.shellWrap, []byte(wrap), 0o755); err != nil {
366 h.t.Fatalf("writing shell wrapper: %v", err)
367 }
368
369 // Start the server and set the global default-shell *before* creating the
370 // session, so even the session's initial pane uses the no-profile wrapper
371 // rather than the system default shell (which could source login profiles).
372 // h.tmux passes -f /dev/null, so the server starts ignoring any
373 // user/system tmux.conf for full isolation. exit-empty must be turned off
374 // in the same command that starts the server, otherwise the freshly started
375 // (session-less) server exits before we can set default-shell.
376 h.tmux("start-server", ";", "set-option", "-g", "exit-empty", "off")
377 h.tmux("set-option", "-g", "default-shell", h.shellWrap)
378 h.tmux("new-session", "-d", "-s", "main", "-x", "200", "-y", "50")
379 h.t.Cleanup(func() {
380 _ = exec.Command("tmux", "-S", h.Sock, "-f", "/dev/null", "kill-server").Run()
381 })
382
383 h.ServerPID = strings.TrimSpace(h.tmux("display-message", "-p", "#{pid}"))
384 panes := h.ListPanes()
385 if len(panes) == 0 {
386 h.t.Fatal("isolated tmux server has no panes")
387 }
388 h.InitialPane = panes[0]
389}
390
391// env returns the environment for a klaus invocation: isolated HOME, BinDir-first
392// PATH, the session id, and $TMUX/$TMUX_PANE pointing at the isolated server.
393func (h *Harness) env() []string {
394 return []string{
395 "HOME=" + h.Home,
396 "PATH=" + h.BinDir + ":" + os.Getenv("PATH"),
397 "KLAUS_SESSION_ID=" + h.SessionID,
398 "TMUX=" + h.Sock + "," + h.ServerPID + ",0",
399 "TMUX_PANE=" + h.InitialPane,
400 "TERM=xterm",
401 }
402}
403
404// RunKlaus runs the real klaus binary with the isolated environment, with CWD
405// set to the sandbox repo. It returns stdout/stderr/exit and never fails the
406// test on a non-zero exit (callers assert as needed).
407func (h *Harness) RunKlaus(args ...string) RunResult {
408 h.t.Helper()
409 return h.RunKlausIn(h.RepoDir, args...)
410}
411
412// RunKlausIn is RunKlaus with an explicit working directory, for commands that
413// must behave correctly outside a git checkout (E2EDir is not a repo).
414func (h *Harness) RunKlausIn(dir string, args ...string) RunResult {
415 h.t.Helper()
416 cmd := exec.Command(klausBinary, args...)
417 cmd.Dir = dir
418 cmd.Env = h.env()
419 var stdout, stderr bytes.Buffer
420 cmd.Stdout = &stdout
421 cmd.Stderr = &stderr
422 err := cmd.Run()
423 res := RunResult{Stdout: stdout.String(), Stderr: stderr.String()}
424 if ee, ok := err.(*exec.ExitError); ok {
425 res.ExitCode = ee.ExitCode()
426 } else if err != nil {
427 h.t.Fatalf("running klaus %v: %v", args, err)
428 }
429 return res
430}
431
432// RegisterProject registers a local checkout in the temp HOME's project
433// registry via the real `klaus project add`, so commands that resolve a repo
434// through the registry (merge, for one) can find it.
435func (h *Harness) RegisterProject(ref, path string) {
436 h.t.Helper()
437 res := h.RunKlaus("project", "add", ref, "--path", path, "--description", "e2e sandbox")
438 if res.ExitCode != 0 {
439 h.t.Fatalf("registering project %s: exit %d\n%s%s", ref, res.ExitCode, res.Stdout, res.Stderr)
440 }
441}
442
443// tmux runs a control-plane tmux command against the isolated server and
444// returns trimmed stdout, failing the test on error.
445func (h *Harness) tmux(args ...string) string {
446 h.t.Helper()
447 full := append([]string{"-S", h.Sock, "-f", "/dev/null"}, args...)
448 out, err := exec.Command("tmux", full...).CombinedOutput()
449 if err != nil {
450 h.t.Fatalf("tmux %v: %v: %s", args, err, out)
451 }
452 return string(out)
453}
454
455// ListPanes returns all pane ids on the isolated server.
456func (h *Harness) ListPanes() []string {
457 h.t.Helper()
458 out := h.tmux("list-panes", "-a", "-F", "#{pane_id}")
459 var panes []string
460 for _, line := range strings.Split(out, "\n") {
461 if s := strings.TrimSpace(line); s != "" {
462 panes = append(panes, s)
463 }
464 }
465 return panes
466}
467
468// PaneExists reports whether the given pane id is alive on the isolated server.
469func (h *Harness) PaneExists(paneID string) bool {
470 for _, p := range h.ListPanes() {
471 if p == paneID {
472 return true
473 }
474 }
475 return false
476}
477
478// AgentsSession is the detached tmux session klaus puts agent panes in.
479func (h *Harness) AgentsSession() string {
480 return "klaus-agents-" + h.SessionID
481}
482
483// SessionExists reports whether a tmux session with this exact name exists on
484// the isolated server.
485func (h *Harness) SessionExists(name string) bool {
486 h.t.Helper()
487 err := exec.Command("tmux", "-S", h.Sock, "-f", "/dev/null", "has-session", "-t", "="+name).Run()
488 return err == nil
489}
490
491// SessionPanes returns the pane ids belonging to the named session.
492func (h *Harness) SessionPanes(name string) []string {
493 h.t.Helper()
494 if !h.SessionExists(name) {
495 return nil
496 }
497 out := h.tmux("list-panes", "-s", "-t", "="+name, "-F", "#{pane_id}")
498 var panes []string
499 for _, line := range strings.Split(out, "\n") {
500 if s := strings.TrimSpace(line); s != "" {
501 panes = append(panes, s)
502 }
503 }
504 return panes
505}
506
507// WindowPanes returns the pane ids in the window containing the given pane.
508func (h *Harness) WindowPanes(paneID string) []string {
509 h.t.Helper()
510 out := h.tmux("list-panes", "-t", paneID, "-F", "#{pane_id}")
511 var panes []string
512 for _, line := range strings.Split(out, "\n") {
513 if s := strings.TrimSpace(line); s != "" {
514 panes = append(panes, s)
515 }
516 }
517 return panes
518}
519
520// PaneTitle returns the title of the given pane.
521func (h *Harness) PaneTitle(paneID string) string {
522 h.t.Helper()
523 return strings.TrimSpace(h.tmux("display-message", "-p", "-t", paneID, "#{pane_title}"))
524}
525
526// SessionDir is this session's directory.
527func (h *Harness) SessionDir() string {
528 return filepath.Join(h.StateRoot, "sessions", h.SessionID)
529}
530
531// UseFlowNames moves the harness's session under the flow names
532// (~/.valley/flow/sessions), where a later build puts new sessions.
533func (h *Harness) UseFlowNames() {
534 h.t.Helper()
535 old := h.SessionDir()
536 h.StateRoot = filepath.Join(h.Home, ".valley", "flow")
537 if err := os.MkdirAll(filepath.Dir(h.SessionDir()), 0o755); err != nil {
538 h.t.Fatal(err)
539 }
540 if err := os.Rename(old, h.SessionDir()); err != nil {
541 h.t.Fatal(err)
542 }
543 // The emptied legacy roots go too: nothing is left under the old names.
544 for _, dir := range []string{filepath.Dir(old), filepath.Dir(filepath.Dir(old))} {
545 if err := os.Remove(dir); err != nil {
546 h.t.Fatal(err)
547 }
548 }
549}
550
551// RunsDir is the directory holding this session's run-state JSON files.
552func (h *Harness) RunsDir() string {
553 return filepath.Join(h.SessionDir(), "runs")
554}
555
556// RunIDs returns the run ids (state file basenames) currently on disk.
557func (h *Harness) RunIDs() []string {
558 entries, err := os.ReadDir(h.RunsDir())
559 if err != nil {
560 return nil
561 }
562 var ids []string
563 for _, e := range entries {
564 if name := e.Name(); strings.HasSuffix(name, ".json") {
565 ids = append(ids, strings.TrimSuffix(name, ".json"))
566 }
567 }
568 return ids
569}
570
571// ReadState reads and decodes a run's state JSON from the isolated HOME.
572func (h *Harness) ReadState(runID string) (*run.State, error) {
573 data, err := os.ReadFile(filepath.Join(h.RunsDir(), runID+".json"))
574 if err != nil {
575 return nil, err
576 }
577 var st run.State
578 if err := json.Unmarshal(data, &st); err != nil {
579 return nil, err
580 }
581 return &st, nil
582}
583
584// WaitForState polls a run's state until pred is satisfied or the timeout
585// elapses, returning the final state. It fails the test on timeout.
586func (h *Harness) WaitForState(runID string, pred func(*run.State) bool, timeout time.Duration) *run.State {
587 h.t.Helper()
588 deadline := time.Now().Add(timeout)
589 var last *run.State
590 for time.Now().Before(deadline) {
591 st, err := h.ReadState(runID)
592 if err == nil {
593 last = st
594 if pred(st) {
595 return st
596 }
597 }
598 time.Sleep(100 * time.Millisecond)
599 }
600 h.t.Fatalf("state predicate not satisfied for %s within %s (last: %+v)", runID, timeout, last)
601 return last
602}
603
604// SeedState writes a run-state JSON directly into the session store, for tests
605// that exercise read paths (e.g. status) without launching an agent.
606func (h *Harness) SeedState(st *run.State) {
607 h.t.Helper()
608 if err := os.MkdirAll(h.RunsDir(), 0o755); err != nil {
609 h.t.Fatalf("mkdir runs: %v", err)
610 }
611 data, err := json.MarshalIndent(st, "", " ")
612 if err != nil {
613 h.t.Fatalf("marshal state: %v", err)
614 }
615 if err := os.WriteFile(filepath.Join(h.RunsDir(), st.ID+".json"), data, 0o644); err != nil {
616 h.t.Fatalf("writing seeded state: %v", err)
617 }
618}
619
620func (h *Harness) git(dir string, args ...string) {
621 h.t.Helper()
622 h.GitOutput(dir, args...)
623}
624
625// GitOutput runs real git in dir with the harness's git config and returns
626// its trimmed stdout, failing the test if git fails.
627func (h *Harness) GitOutput(dir string, args ...string) string {
628 h.t.Helper()
629 cmd := exec.Command("git", args...)
630 if dir != "" {
631 cmd.Dir = dir
632 }
633 cmd.Env = append(os.Environ(), "HOME="+h.Home, "GIT_CONFIG_GLOBAL="+filepath.Join(h.Home, ".gitconfig"), "GIT_CONFIG_NOSYSTEM=1")
634 var stdout, stderr bytes.Buffer
635 cmd.Stdout, cmd.Stderr = &stdout, &stderr
636 if err := cmd.Run(); err != nil {
637 h.t.Fatalf("git %v: %v: %s%s", args, err, stdout.String(), stderr.String())
638 }
639 return strings.TrimSpace(stdout.String())
640}
641
642func mustBash(t *testing.T) string {
643 t.Helper()
644 p, err := exec.LookPath("bash")
645 if err != nil {
646 t.Fatalf("bash not found: %v", err)
647 }
648 return p
649}
650
651// ghGraphQLAnswer is a gh stub fragment that answers the dashboard's PR
652// query: each PR in states (number -> OPEN, MERGED or CLOSED) is mergeable,
653// with its checks in rollup (SUCCESS, FAILURE or PENDING).
654func ghGraphQLAnswer(states map[int]string, rollup string) string {
655 var prs []string
656 for n, state := range states {
657 prs = append(prs, fmt.Sprintf(`"pr%d": {"state": "%s", "mergeable": "MERGEABLE", "headRefOid": "h%d", "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "%s"}}}]}}`, n, state, n, rollup))
658 }
659 body := `{"data": {"repository": {` + strings.Join(prs, ", ") + `}}}`
660 return fmt.Sprintf("if [[ \"$*\" == *graphql* ]]; then printf 'HTTP/2.0 200 OK\\r\\n\\r\\n%%s' %q; exit 0; fi\n", body)
661}
662
663// skipWithout skips t for want of a tool, or of a feature of one, unless
664// KLAUS_TEST_TOOLS=required, as the flow checks set: there it fails t, so a
665// scenario that did not run cannot pass.
666func skipWithout(t testing.TB, format string, args ...any) {
667 t.Helper()
668 if os.Getenv("KLAUS_TEST_TOOLS") == "required" {
669 t.Fatalf(format, args...)
670 }
671 t.Skipf(format, args...)
672}