| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "regexp" |
| 10 | "strings" |
| 11 | "syscall" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // newCoordinatorSession runs the real `klaus new --backend kind` with a stub |
| 17 | // coordinator that saves its system prompt and exits, points the harness at |
| 18 | // the new session, and returns the prompt. |
| 19 | func (h *Harness) newCoordinatorSession(kind string) string { |
| 20 | h.t.Helper() |
| 21 | promptFile := filepath.Join(h.E2EDir, kind+".prompt") |
| 22 | // Claude takes the prompt in --append-system-prompt, agy in |
| 23 | // --prompt-interactive, Codex in -c developer_instructions=. |
| 24 | h.WriteStub(kind, fmt.Sprintf(`#!/bin/sh |
| 25 | while [ $# -gt 0 ]; do |
| 26 | case "$1" in |
| 27 | --append-system-prompt|--prompt-interactive) printf '%%s' "$2" > %[1]q; shift ;; |
| 28 | developer_instructions=*) printf '%%s' "$1" > %[1]q ;; |
| 29 | esac |
| 30 | shift |
| 31 | done |
| 32 | `, promptFile)) |
| 33 | before := map[string]bool{} |
| 34 | if _, err := os.Stat(filepath.Join(h.Home, ".klaus", "sessions")); err == nil { |
| 35 | for _, id := range h.sessionIDs() { |
| 36 | before[id] = true |
| 37 | } |
| 38 | } |
| 39 | res := h.RunKlausIn(h.E2EDir, "new", "--backend", kind) |
| 40 | if res.ExitCode != 0 { |
| 41 | h.t.Fatalf("klaus new --backend %s exited %d\nstdout:\n%s\nstderr:\n%s", kind, res.ExitCode, res.Stdout, res.Stderr) |
| 42 | } |
| 43 | for _, id := range h.sessionIDs() { |
| 44 | if !before[id] { |
| 45 | h.SessionID = id |
| 46 | } |
| 47 | } |
| 48 | if before[h.SessionID] { |
| 49 | h.t.Fatalf("klaus new made no session (sessions: %v)", h.sessionIDs()) |
| 50 | } |
| 51 | prompt, err := os.ReadFile(promptFile) |
| 52 | if err != nil { |
| 53 | h.t.Fatalf("the %s coordinator got no prompt: %v", kind, err) |
| 54 | } |
| 55 | return string(prompt) |
| 56 | } |
| 57 | |
| 58 | func (h *Harness) eventsFile() string { |
| 59 | return filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "events.jsonl") |
| 60 | } |
| 61 | |
| 62 | // emitMerged appends a pr:merged event for PR n to the session's event log |
| 63 | // through the real binary. |
| 64 | func (h *Harness) emitMerged(n int) { |
| 65 | h.t.Helper() |
| 66 | res := h.RunKlaus("_event", "--run-id", fmt.Sprint(n), "--type", "pr:merged", "--data", fmt.Sprintf(`{"pr_number":"%d"}`, n)) |
| 67 | if res.ExitCode != 0 { |
| 68 | h.t.Fatalf("klaus _event exited %d: %s%s", res.ExitCode, res.Stdout, res.Stderr) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // exited reports whether p has exited. |
| 73 | func (p *klausProcess) exited() bool { |
| 74 | select { |
| 75 | case <-p.done: |
| 76 | return true |
| 77 | default: |
| 78 | return false |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // waitOpened waits until p has path open, which a streaming watch does just |
| 83 | // before it seeks to the end of the file and starts following it. |
| 84 | func (p *klausProcess) waitOpened(path string) { |
| 85 | p.t.Helper() |
| 86 | real, err := filepath.EvalSymlinks(path) |
| 87 | if err != nil { |
| 88 | p.t.Fatal(err) |
| 89 | } |
| 90 | fdDir := fmt.Sprintf("/proc/%d/fd", p.cmd.Process.Pid) |
| 91 | p.waitFor(func() bool { |
| 92 | fds, _ := os.ReadDir(fdDir) |
| 93 | for _, fd := range fds { |
| 94 | if target, _ := os.Readlink(filepath.Join(fdDir, fd.Name())); target == real { |
| 95 | return true |
| 96 | } |
| 97 | } |
| 98 | return false |
| 99 | }, "open "+path) |
| 100 | time.Sleep(200 * time.Millisecond) |
| 101 | } |
| 102 | |
| 103 | // stop sends p SIGTERM and returns its outcome. |
| 104 | func (p *klausProcess) stop() RunResult { |
| 105 | p.t.Helper() |
| 106 | if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil { |
| 107 | p.t.Fatal(err) |
| 108 | } |
| 109 | return p.wait() |
| 110 | } |
| 111 | |
| 112 | // watchOnce runs a `klaus watch --once` command line as printed on a next: |
| 113 | // line, waits up to 30s for it to exit 0, and returns the PR numbers of the |
| 114 | // pr:merged events it printed and the command on its next: line. |
| 115 | func (h *Harness) watchOnce(cmdline string) (prs []string, next string) { |
| 116 | h.t.Helper() |
| 117 | p := h.startKlaus(nil, strings.Fields(strings.TrimPrefix(cmdline, "klaus "))...) |
| 118 | p.waitFor(p.exited, "exit") |
| 119 | res := p.wait() |
| 120 | if res.ExitCode != 0 { |
| 121 | h.t.Fatalf("%s exited %d\nstdout:\n%s\nstderr:\n%s", cmdline, res.ExitCode, res.Stdout, res.Stderr) |
| 122 | } |
| 123 | return parseWatchBatch(h.t, cmdline, res.Stdout) |
| 124 | } |
| 125 | |
| 126 | var mergedLine = regexp.MustCompile(`pr:merged +PR #(\d+) merged$`) |
| 127 | |
| 128 | func parseWatchBatch(t *testing.T, cmdline, out string) (prs []string, next string) { |
| 129 | t.Helper() |
| 130 | lines := strings.Split(strings.TrimSuffix(out, "\n"), "\n") |
| 131 | last := lines[len(lines)-1] |
| 132 | if !strings.HasPrefix(last, "next: klaus watch --once --after ") { |
| 133 | t.Fatalf("%s: last line %q is not a next: line\n%s", cmdline, last, out) |
| 134 | } |
| 135 | for _, l := range lines[:len(lines)-1] { |
| 136 | m := mergedLine.FindStringSubmatch(l) |
| 137 | if m == nil { |
| 138 | t.Fatalf("%s printed %q, not a pr:merged event\n%s", cmdline, l, out) |
| 139 | } |
| 140 | prs = append(prs, m[1]) |
| 141 | } |
| 142 | return prs, strings.TrimPrefix(last, "next: ") |
| 143 | } |
| 144 | |
| 145 | // TestAgyCoordinatorWatchesWithOneShotWatches follows the event channel |
| 146 | // pattern the agy coordinator's prompt gives it, with the real binary: start |
| 147 | // the prompt's one-shot watch, and when it exits, start the command on its |
| 148 | // next: line. An event that lands before the first watch starts, two that land |
| 149 | // between two watches, and one that lands while a watch waits are each |
| 150 | // printed once. |
| 151 | func TestAgyCoordinatorWatchesWithOneShotWatches(t *testing.T) { |
| 152 | t.Parallel() |
| 153 | h := NewHarness(t) |
| 154 | prompt := h.newCoordinatorSession("agy") |
| 155 | if strings.Contains(prompt, "Monitor") { |
| 156 | t.Fatalf("the agy coordinator's prompt mentions Monitor:\n%s", prompt) |
| 157 | } |
| 158 | for _, want := range []string{"run_command", "only when they exit", "as a background task", "next:"} { |
| 159 | if !strings.Contains(prompt, want) { |
| 160 | t.Errorf("the agy coordinator's prompt doesn't say %q", want) |
| 161 | } |
| 162 | } |
| 163 | m := regexp.MustCompile("start `(klaus watch --once --after 0)` as a background task").FindStringSubmatch(prompt) |
| 164 | if m == nil { |
| 165 | t.Fatalf("the agy coordinator's prompt has no first watch from the start of the new session's events:\n%s", prompt) |
| 166 | } |
| 167 | |
| 168 | // The coordinator hasn't armed its watch yet when PR 1 merges. |
| 169 | h.emitMerged(1) |
| 170 | prs, next := h.watchOnce(m[1]) |
| 171 | if strings.Join(prs, " ") != "1" { |
| 172 | t.Fatalf("the first watch printed PRs %v, want [1]", prs) |
| 173 | } |
| 174 | |
| 175 | // Two events between two watches: the next one prints both, and not PR 1. |
| 176 | h.emitMerged(2) |
| 177 | h.emitMerged(3) |
| 178 | prs, next = h.watchOnce(next) |
| 179 | if strings.Join(prs, " ") != "2 3" { |
| 180 | t.Fatalf("the second watch printed PRs %v, want [2 3]", prs) |
| 181 | } |
| 182 | |
| 183 | // The third waits: it has nothing to print until PR 4 merges. |
| 184 | p := h.startKlaus(nil, strings.Fields(strings.TrimPrefix(next, "klaus "))...) |
| 185 | time.Sleep(time.Second) |
| 186 | if p.exited() { |
| 187 | res := p.wait() |
| 188 | t.Fatalf("%s exited before any new event\nstdout:\n%s\nstderr:\n%s", next, res.Stdout, res.Stderr) |
| 189 | } |
| 190 | h.emitMerged(4) |
| 191 | p.waitFor(p.exited, "exit") |
| 192 | res := p.wait() |
| 193 | if res.ExitCode != 0 { |
| 194 | t.Fatalf("%s exited %d: %s%s", next, res.ExitCode, res.Stdout, res.Stderr) |
| 195 | } |
| 196 | prs, next = parseWatchBatch(t, next, res.Stdout) |
| 197 | if strings.Join(prs, " ") != "4" { |
| 198 | t.Fatalf("the third watch printed PRs %v, want [4]", prs) |
| 199 | } |
| 200 | |
| 201 | // Its cursor is the end of the stream: a watch from it waits too, and |
| 202 | // interrupted, says to start the same command again. |
| 203 | p = h.startKlaus(nil, strings.Fields(strings.TrimPrefix(next, "klaus "))...) |
| 204 | time.Sleep(500 * time.Millisecond) |
| 205 | res = p.stop() |
| 206 | if res.ExitCode != 0 || res.Stdout != "next: "+next+"\n" { |
| 207 | t.Fatalf("interrupted, %s exited %d with %q, want just %q", next, res.ExitCode, res.Stdout, "next: "+next+"\n") |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // TestCoordinatorPromptsFollowTheirBackends: Claude's prompt arms klaus watch |
| 212 | // in Monitor; Codex's, like agy's, never mentions Monitor and gives the |
| 213 | // one-shot watch. |
| 214 | func TestCoordinatorPromptsFollowTheirBackends(t *testing.T) { |
| 215 | for _, kind := range []string{"claude", "codex"} { |
| 216 | t.Run(kind, func(t *testing.T) { |
| 217 | t.Parallel() |
| 218 | h := NewHarness(t) |
| 219 | prompt := h.newCoordinatorSession(kind) |
| 220 | monitor := strings.Contains(prompt, "Command to arm in Monitor") |
| 221 | oneShot := strings.Contains(prompt, "klaus watch --once --after 0") |
| 222 | if kind == "claude" && (!monitor || oneShot) { |
| 223 | t.Errorf("Claude's prompt: Monitor instructions %t, one-shot watch %t; want only Monitor", monitor, oneShot) |
| 224 | } |
| 225 | if kind == "codex" && (strings.Contains(prompt, "Monitor") || !oneShot) { |
| 226 | t.Errorf("Codex's prompt: mentions Monitor %t, one-shot watch %t; want only the one-shot watch", strings.Contains(prompt, "Monitor"), oneShot) |
| 227 | } |
| 228 | }) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // TestWatchBeforeTheFirstEvent: a coordinator arms klaus watch as its session |
| 233 | // starts, before any event. klaus new makes the events file, and a watch |
| 234 | // started then prints the first event (#345). |
| 235 | func TestWatchBeforeTheFirstEvent(t *testing.T) { |
| 236 | t.Parallel() |
| 237 | h := NewHarness(t) |
| 238 | h.newCoordinatorSession("claude") |
| 239 | if info, err := os.Stat(h.eventsFile()); err != nil || info.Size() != 0 { |
| 240 | t.Fatalf("klaus new should leave an empty events file: %v %v", info, err) |
| 241 | } |
| 242 | |
| 243 | w := h.startKlaus(nil, "watch") |
| 244 | w.waitOpened(h.eventsFile()) |
| 245 | h.emitMerged(7) |
| 246 | w.waitFor(func() bool { |
| 247 | out, _ := w.output() |
| 248 | return strings.Contains(out, "PR #7 merged") |
| 249 | }, "print PR #7's merge") |
| 250 | if res := w.stop(); res.ExitCode != 0 { |
| 251 | t.Fatalf("watch exited %d after SIGTERM: %s", res.ExitCode, res.Stderr) |
| 252 | } |
| 253 | |
| 254 | // Resuming a session that has no events file, as one from an older |
| 255 | // klaus, makes it too. |
| 256 | if err := os.Remove(h.eventsFile()); err != nil { |
| 257 | t.Fatal(err) |
| 258 | } |
| 259 | if res := h.RunKlausIn(h.E2EDir, "session"); res.ExitCode != 0 { |
| 260 | t.Fatalf("klaus session exited %d: %s%s", res.ExitCode, res.Stdout, res.Stderr) |
| 261 | } |
| 262 | if _, err := os.Stat(h.eventsFile()); err != nil { |
| 263 | t.Fatalf("resuming the session should make the events file: %v", err) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // TestWatchWaitsForTheEventsFile: in a session with no events file yet, as |
| 268 | // one from an older klaus, watch waits for the file as long as the session |
| 269 | // exists, well past the 10s it used to give up after, and prints the event |
| 270 | // that makes the file. An unknown session ID fails at once. |
| 271 | func TestWatchWaitsForTheEventsFile(t *testing.T) { |
| 272 | t.Parallel() |
| 273 | h := NewHarness(t) |
| 274 | h.newCoordinatorSession("claude") |
| 275 | if err := os.Remove(h.eventsFile()); err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | |
| 279 | w := h.startKlaus(nil, "watch") |
| 280 | once := h.startKlaus(nil, "watch", "--once") |
| 281 | time.Sleep(11 * time.Second) |
| 282 | for _, p := range []*klausProcess{w, once} { |
| 283 | if p.exited() { |
| 284 | res := p.wait() |
| 285 | t.Fatalf("klaus %v gave up waiting for the events file: exit %d\n%s%s", p.cmd.Args[1:], res.ExitCode, res.Stdout, res.Stderr) |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | h.emitMerged(8) |
| 290 | w.waitFor(func() bool { |
| 291 | out, _ := w.output() |
| 292 | return strings.Contains(out, "PR #8 merged") |
| 293 | }, "print PR #8's merge") |
| 294 | if res := w.stop(); res.ExitCode != 0 { |
| 295 | t.Fatalf("watch exited %d after SIGTERM: %s", res.ExitCode, res.Stderr) |
| 296 | } |
| 297 | once.waitFor(once.exited, "exit") |
| 298 | res := once.wait() |
| 299 | if prs, _ := parseWatchBatch(t, "klaus watch --once", res.Stdout); res.ExitCode != 0 || strings.Join(prs, " ") != "8" { |
| 300 | t.Fatalf("watch --once exited %d with PRs %v, want 0 with [8]\n%s%s", res.ExitCode, prs, res.Stdout, res.Stderr) |
| 301 | } |
| 302 | |
| 303 | start := time.Now() |
| 304 | res = h.RunKlaus("watch", "--session-id", "session-unknown") |
| 305 | if res.ExitCode == 0 || !strings.Contains(res.Stderr, "unknown session session-unknown") || time.Since(start) > 5*time.Second { |
| 306 | t.Fatalf("watch on an unknown session exited %d after %s: %s", res.ExitCode, time.Since(start), res.Stderr) |
| 307 | } |
| 308 | } |