gunk-dev/the-valley

wire_names_test.go

sourcec14b0e68e9c3main's published tip history
11.0 KiB
1package cmd
2
3import (
4 "bytes"
5 "context"
6 "os"
7 "path/filepath"
8 "strings"
9 "testing"
10
11 "the-valley/flow/internal/backend"
12 "the-valley/flow/internal/config"
13 "the-valley/flow/internal/consult"
14 "the-valley/flow/internal/event"
15 "the-valley/flow/internal/flowenv"
16 "the-valley/flow/internal/run"
17 "github.com/spf13/cobra"
18)
19
20// The names flow sets for the processes it starts, as tests set them.
21var (
22 sessionIDEnv = flowenv.SessionID.Legacy
23 runIDEnv = flowenv.RunID.Legacy
24 runEventsEnv = flowenv.RunEvents.Legacy
25 scratchEnv = flowenv.Scratch.Legacy
26 socketEnv = flowenv.TmuxSocket.Legacy
27)
28
29func unsetFlowEnv(t *testing.T, v flowenv.Var) {
30 t.Helper()
31 t.Setenv(v.New, "")
32 t.Setenv(v.Legacy, "")
33 _ = os.Unsetenv(v.New)
34 _ = os.Unsetenv(v.Legacy)
35}
36
37func TestFinalizeFromLog_ExitEventBothSpellings(t *testing.T) {
38 tests := []struct {
39 name string
40 logContent string
41 wantReason string
42 wantSub string
43 }{
44 {
45 name: "legacy klaus_exit nonzero",
46 logContent: `{"type":"klaus_exit","exit_code":2}` + "\n",
47 wantReason: "codex exited with status 2",
48 wantSub: "error_during_execution",
49 },
50 {
51 name: "new flow_exit nonzero",
52 logContent: `{"type":"flow_exit","exit_code":2}` + "\n",
53 wantReason: "codex exited with status 2",
54 wantSub: "error_during_execution",
55 },
56 {
57 name: "both klaus_exit and flow_exit normalize to one result",
58 logContent: "{\"type\":\"klaus_exit\",\"exit_code\":2}\n{\"type\":\"flow_exit\",\"exit_code\":2}\n",
59 wantReason: "codex exited with status 2",
60 wantSub: "error_during_execution",
61 },
62 {
63 name: "flow_exit zero after result leaves no failure",
64 logContent: "{\"type\":\"result\",\"subtype\":\"success\"}\n{\"type\":\"flow_exit\",\"exit_code\":0}\n",
65 wantReason: "",
66 wantSub: "success",
67 },
68 }
69
70 for _, tt := range tests {
71 t.Run(tt.name, func(t *testing.T) {
72 state, store := setupFinalizeTest(t, tt.logContent)
73 state.Backend = string(backend.Codex)
74 sub, err := finalizeFromLog(store, state)
75 if err != nil {
76 t.Fatalf("finalizeFromLog: %v", err)
77 }
78 if sub != tt.wantSub {
79 t.Errorf("subtype = %q, want %q", sub, tt.wantSub)
80 }
81 gotReason := ""
82 if state.FailureReason != nil {
83 gotReason = *state.FailureReason
84 }
85 if gotReason != tt.wantReason {
86 t.Errorf("FailureReason = %q, want %q", gotReason, tt.wantReason)
87 }
88 })
89 }
90}
91
92func TestSessionIDReadersAcceptBothSpellings(t *testing.T) {
93 home := t.TempDir()
94 t.Setenv("HOME", home)
95
96 // Prepare two sessions so sessionStore can open either.
97 for _, id := range []string{"sess-old", "sess-new"} {
98 st, err := run.NewHomeDirStore(id)
99 if err != nil {
100 t.Fatal(err)
101 }
102 if err := st.EnsureDirs(); err != nil {
103 t.Fatal(err)
104 }
105 pane := "%9"
106 if err := st.Save(&run.State{ID: id, Type: "session", CoordinatorPane: &pane}); err != nil {
107 t.Fatal(err)
108 }
109 }
110
111 t.Run("legacy only", func(t *testing.T) {
112 unsetFlowEnv(t, flowenv.SessionID)
113 t.Setenv(flowenv.SessionID.Legacy, "sess-old")
114
115 if got := agentsSessionName(); got != "klaus-agents-sess-old" {
116 t.Errorf("agentsSessionName() = %q", got)
117 }
118 if got := tmuxSessionEnvPrefix(); got != "unset VALLEY_FLOW_SESSION_ID; export KLAUS_SESSION_ID='sess-old'; " {
119 t.Errorf("tmuxSessionEnvPrefix() = %q", got)
120 }
121 st, err := sessionStore()
122 if err != nil {
123 t.Fatalf("sessionStore(): %v", err)
124 }
125 if got := filepath.Base(st.(*run.HomeDirStore).BaseDir()); got != "sess-old" {
126 t.Errorf("sessionStore base = %q, want sess-old", got)
127 }
128 if !defaultIsRunActive(&run.State{ID: "sess-old", Type: "session"}, &fakeTmux{}) {
129 t.Error("defaultIsRunActive should see current session from KLAUS_SESSION_ID")
130 }
131 m := dashboardModel{store: st}
132 if got := m.coordinatorPane(); got != "%9" {
133 t.Errorf("coordinatorPane() = %q, want %%9", got)
134 }
135 })
136
137 t.Run("new only", func(t *testing.T) {
138 unsetFlowEnv(t, flowenv.SessionID)
139 t.Setenv(flowenv.SessionID.New, "sess-new")
140
141 if got := agentsSessionName(); got != "klaus-agents-sess-new" {
142 t.Errorf("agentsSessionName() = %q", got)
143 }
144 // Writers export KLAUS_SESSION_ID, with the value read from VALLEY_FLOW_SESSION_ID, and drop the new spelling.
145 if got := tmuxSessionEnvPrefix(); got != "unset VALLEY_FLOW_SESSION_ID; export KLAUS_SESSION_ID='sess-new'; " {
146 t.Errorf("tmuxSessionEnvPrefix() = %q", got)
147 }
148 st, err := sessionStore()
149 if err != nil {
150 t.Fatalf("sessionStore(): %v", err)
151 }
152 if got := filepath.Base(st.(*run.HomeDirStore).BaseDir()); got != "sess-new" {
153 t.Errorf("sessionStore base = %q, want sess-new", got)
154 }
155 if !defaultIsRunActive(&run.State{ID: "sess-new", Type: "session"}, &fakeTmux{}) {
156 t.Error("defaultIsRunActive should see current session from VALLEY_FLOW_SESSION_ID")
157 }
158 m := dashboardModel{store: st}
159 if got := m.coordinatorPane(); got != "%9" {
160 t.Errorf("coordinatorPane() = %q, want %%9", got)
161 }
162 })
163
164 t.Run("new empty overrides legacy", func(t *testing.T) {
165 unsetFlowEnv(t, flowenv.SessionID)
166 t.Setenv(flowenv.SessionID.Legacy, "sess-old")
167 t.Setenv(flowenv.SessionID.New, "")
168
169 if got := agentsSessionName(); got != "klaus-agents" {
170 t.Errorf("agentsSessionName() = %q, want klaus-agents", got)
171 }
172 if got := tmuxSessionEnvPrefix(); got != "" {
173 t.Errorf("tmuxSessionEnvPrefix() = %q, want empty", got)
174 }
175 })
176}
177
178func TestResolveAgentBackend_EnvSpellings(t *testing.T) {
179 home := t.TempDir()
180 t.Setenv("HOME", home)
181 unsetFlowEnv(t, flowenv.SessionID)
182
183 newCmd := func() *cobra.Command {
184 c := &cobra.Command{}
185 c.Flags().String("backend", "", "")
186 return c
187 }
188
189 t.Run("legacy only", func(t *testing.T) {
190 unsetFlowEnv(t, flowenv.AgentBackend)
191 t.Setenv(flowenv.AgentBackend.Legacy, "codex")
192 got, err := resolveAgentBackend(newCmd(), config.Config{})
193 if err != nil || got != backend.Codex {
194 t.Errorf("resolveAgentBackend() = %q, %v; want codex", got, err)
195 }
196 })
197
198 t.Run("new only", func(t *testing.T) {
199 unsetFlowEnv(t, flowenv.AgentBackend)
200 t.Setenv(flowenv.AgentBackend.New, "agy")
201 got, err := resolveAgentBackend(newCmd(), config.Config{})
202 if err != nil || got != backend.Agy {
203 t.Errorf("resolveAgentBackend() = %q, %v; want agy", got, err)
204 }
205 })
206
207 t.Run("both set prefers new", func(t *testing.T) {
208 unsetFlowEnv(t, flowenv.AgentBackend)
209 t.Setenv(flowenv.AgentBackend.Legacy, "codex")
210 t.Setenv(flowenv.AgentBackend.New, "agy")
211 got, err := resolveAgentBackend(newCmd(), config.Config{})
212 if err != nil || got != backend.Agy {
213 t.Errorf("resolveAgentBackend() = %q, %v; want agy", got, err)
214 }
215 })
216
217 t.Run("new empty overrides legacy and falls through to config", func(t *testing.T) {
218 unsetFlowEnv(t, flowenv.AgentBackend)
219 t.Setenv(flowenv.AgentBackend.Legacy, "codex")
220 t.Setenv(flowenv.AgentBackend.New, "")
221 got, err := resolveAgentBackend(newCmd(), config.Config{DefaultAgentBackend: "agy"})
222 if err != nil || got != backend.Agy {
223 t.Errorf("resolveAgentBackend() = %q, %v; want agy", got, err)
224 }
225 })
226}
227
228func TestRunIDAndRunEventsReadersAcceptBothSpellings(t *testing.T) {
229 home := t.TempDir()
230 t.Setenv("HOME", home)
231 unsetFlowEnv(t, flowenv.SessionID)
232 t.Setenv(flowenv.SessionID.New, "sess-run-test")
233
234 st, err := run.NewHomeDirStore("sess-run-test")
235 if err != nil {
236 t.Fatal(err)
237 }
238 if err := st.EnsureDirs(); err != nil {
239 t.Fatal(err)
240 }
241
242 t.Run("currentPaneRun reads VALLEY_FLOW_RUN_ID", func(t *testing.T) {
243 unsetFlowEnv(t, flowenv.RunID)
244 t.Setenv(flowenv.RunID.New, "run-new")
245 p := currentPaneRun()
246 if p == nil || p.id != "run-new" {
247 t.Fatalf("currentPaneRun() = %+v, want id=run-new", p)
248 }
249 })
250
251 t.Run("currentPaneRun reads KLAUS_RUN_ID", func(t *testing.T) {
252 unsetFlowEnv(t, flowenv.RunID)
253 t.Setenv(flowenv.RunID.Legacy, "run-old")
254 p := currentPaneRun()
255 if p == nil || p.id != "run-old" {
256 t.Fatalf("currentPaneRun() = %+v, want id=run-old", p)
257 }
258 })
259
260 t.Run("startPreReviewCheck routes sandbox output with VALLEY_FLOW_*", func(t *testing.T) {
261 unsetFlowEnv(t, flowenv.RunID)
262 unsetFlowEnv(t, flowenv.RunEvents)
263 t.Setenv(flowenv.RunID.New, "run-sandbox")
264 t.Setenv(flowenv.RunEvents.New, runEventsOutput)
265 c := startPreReviewCheck()
266 if c.report == nil {
267 t.Error("expected sandbox report writer when VALLEY_FLOW_RUN_ID and VALLEY_FLOW_RUN_EVENTS=output are set")
268 }
269 })
270
271 t.Run("startPreReviewCheck empty VALLEY_FLOW_RUN_EVENTS overrides KLAUS_RUN_EVENTS", func(t *testing.T) {
272 unsetFlowEnv(t, flowenv.RunID)
273 unsetFlowEnv(t, flowenv.RunEvents)
274 t.Setenv(flowenv.RunID.Legacy, "run-sandbox")
275 t.Setenv(flowenv.RunEvents.Legacy, runEventsOutput)
276 t.Setenv(flowenv.RunEvents.New, "")
277 c := startPreReviewCheck()
278 if c.report != nil {
279 t.Error("expected empty VALLEY_FLOW_RUN_EVENTS to override KLAUS_RUN_EVENTS=output")
280 }
281 })
282}
283
284func TestConsultSkipsBackendFromValleyFlowEnv(t *testing.T) {
285 home := t.TempDir()
286 t.Setenv("HOME", home)
287 unsetFlowEnv(t, flowenv.SessionID)
288 unsetFlowEnv(t, flowenv.Backend)
289 t.Setenv(flowenv.Backend.Legacy, "claude")
290 t.Setenv(flowenv.Backend.New, "codex")
291
292 stubDir := t.TempDir()
293 claudeStub := filepath.Join(stubDir, "claude")
294 codexStub := filepath.Join(stubDir, "codex")
295 if err := os.WriteFile(claudeStub, []byte("#!/bin/sh\necho '{\"type\":\"result\",\"result\":\"from-claude\"}'\n"), 0700); err != nil {
296 t.Fatal(err)
297 }
298 if err := os.WriteFile(codexStub, []byte("#!/bin/sh\necho from-codex\n"), 0700); err != nil {
299 t.Fatal(err)
300 }
301 oldLookup := consult.LookupBinary
302 t.Cleanup(func() { consult.LookupBinary = oldLookup })
303 consult.LookupBinary = func(name string) (string, error) {
304 switch name {
305 case "claude":
306 return claudeStub, nil
307 case "codex":
308 return codexStub, nil
309 default:
310 return "", os.ErrNotExist
311 }
312 }
313
314 c := newConsultCmd()
315 var out bytes.Buffer
316 c.SetOut(&out)
317 c.SetErr(&bytes.Buffer{})
318 c.SetArgs([]string{"--dir", t.TempDir(), "hello"})
319 if err := c.Execute(); err != nil {
320 t.Fatalf("consult execute: %v", err)
321 }
322 if !strings.Contains(out.String(), "from-claude") {
323 t.Errorf("consult output = %q, want claude (codex excluded by VALLEY_FLOW_BACKEND)", out.String())
324 }
325}
326
327func TestWatchReadsValleyFlowSessionID(t *testing.T) {
328 home := t.TempDir()
329 t.Setenv("HOME", home)
330 unsetFlowEnv(t, flowenv.SessionID)
331 t.Setenv(flowenv.SessionID.New, "sess-watch-new")
332
333 st, err := run.NewHomeDirStore("sess-watch-new")
334 if err != nil {
335 t.Fatal(err)
336 }
337 if err := st.EnsureDirs(); err != nil {
338 t.Fatal(err)
339 }
340 evLog := event.NewLog(st.BaseDir())
341 if err := evLog.Emit(event.New("run-1", event.AgentNeedsAttention, map[string]interface{}{"reason": "test"})); err != nil {
342 t.Fatal(err)
343 }
344
345 var out bytes.Buffer
346 watchCmd.SetOut(&out)
347 watchCmd.SetErr(&bytes.Buffer{})
348 t.Cleanup(func() {
349 watchCmd.SetOut(os.Stdout)
350 watchCmd.SetErr(os.Stderr)
351 _ = watchCmd.Flags().Set("once", "false")
352 _ = watchCmd.Flags().Set("since-start", "false")
353 _ = watchCmd.Flags().Set("session-id", "")
354 })
355 _ = watchCmd.Flags().Set("once", "true")
356 _ = watchCmd.Flags().Set("since-start", "true")
357 _ = watchCmd.Flags().Set("session-id", "")
358 watchCmd.SetContext(context.Background())
359 if err := watchCmd.RunE(watchCmd, nil); err != nil {
360 t.Fatalf("watchCmd: %v", err)
361 }
362 if !strings.Contains(out.String(), "run-1") {
363 t.Errorf("watch output = %q, want run-1 event", out.String())
364 }
365}