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