-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.go
More file actions
839 lines (698 loc) · 25.5 KB
/
Copy pathhooks.go
File metadata and controls
839 lines (698 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
//go:build integration
package integration
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/GrayCodeAI/trace/cli/strategy"
"github.com/GrayCodeAI/trace/cli/testutil"
)
// HookRunner executes CLI hooks in the test environment.
type HookRunner struct {
RepoDir string
ClaudeProjectDir string
T interface {
Helper()
Fatalf(format string, args ...interface{})
Logf(format string, args ...interface{})
}
}
// NewHookRunner creates a new hook runner for the given repo directory.
func NewHookRunner(repoDir, claudeProjectDir string, t interface {
Helper()
Fatalf(format string, args ...interface{})
Logf(format string, args ...interface{})
},
) *HookRunner {
return &HookRunner{
RepoDir: repoDir,
ClaudeProjectDir: claudeProjectDir,
T: t,
}
}
// HookResponse represents the JSON response from Claude Code hooks.
type HookResponse struct {
Continue bool `json:"continue"`
StopReason string `json:"stopReason,omitempty"`
}
// SimulateUserPromptSubmit simulates the UserPromptSubmit hook.
// This captures pre-prompt state (untracked files).
func (r *HookRunner) SimulateUserPromptSubmit(sessionID string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "", // Not used for user-prompt-submit
}
return r.runHookWithInput("user-prompt-submit", input)
}
// SimulateUserPromptSubmitWithPrompt simulates the UserPromptSubmit hook
// with an explicit user prompt. The prompt is passed to the lifecycle handler
// and appended to the filesystem prompt.txt.
func (r *HookRunner) SimulateUserPromptSubmitWithPrompt(sessionID, prompt string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
"prompt": prompt,
}
return r.runHookWithInput("user-prompt-submit", input)
}
func (r *HookRunner) SimulateUserPromptSubmitWithReviewEnvVars(sessionID, prompt string, extraEnv []string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
"prompt": prompt,
}
inputJSON, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshal hook input: %w", err)
}
out := r.runAgentHookWithOutput("claude-code", "user-prompt-submit", inputJSON, extraEnv...)
if out.Err != nil {
return fmt.Errorf("hook user-prompt-submit failed: %w\nInput: %s\nOutput: %s%s", out.Err, inputJSON, out.Stdout, out.Stderr)
}
return nil
}
// SimulateUserPromptSubmitWithTranscriptPath simulates the UserPromptSubmit hook
// with an explicit transcript path. This is needed for mid-session commit detection
// which reads the live transcript to detect ongoing sessions.
func (r *HookRunner) SimulateUserPromptSubmitWithTranscriptPath(sessionID, transcriptPath string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": transcriptPath,
}
return r.runHookWithInput("user-prompt-submit", input)
}
// SimulateUserPromptSubmitWithPromptAndTranscriptPath simulates the UserPromptSubmit
// hook with both an explicit prompt and transcript path. This combines the behavior
// of SimulateUserPromptSubmitWithPrompt and SimulateUserPromptSubmitWithTranscriptPath.
func (r *HookRunner) SimulateUserPromptSubmitWithPromptAndTranscriptPath(sessionID, prompt, transcriptPath string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": transcriptPath,
"prompt": prompt,
}
return r.runHookWithInput("user-prompt-submit", input)
}
// SimulateUserPromptSubmitWithResponse simulates the UserPromptSubmit hook
// and returns the parsed hook response (for testing blocking behavior).
func (r *HookRunner) SimulateUserPromptSubmitWithResponse(sessionID string) (*HookResponse, error) {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "", // Not used for user-prompt-submit
}
inputJSON, err := json.Marshal(input)
if err != nil {
return nil, fmt.Errorf("failed to marshal hook input: %w", err)
}
output := r.runHookWithOutput("user-prompt-submit", inputJSON)
// If hook failed with an error, return the error
if output.Err != nil {
return nil, fmt.Errorf("hook failed: %w\nStderr: %s\nStdout: %s",
output.Err, output.Stderr, output.Stdout)
}
// Parse JSON response from stdout
var resp HookResponse
if len(output.Stdout) > 0 {
if err := json.Unmarshal(output.Stdout, &resp); err != nil {
return nil, fmt.Errorf("failed to parse hook response: %w\nStdout: %s",
err, output.Stdout)
}
}
return &resp, nil
}
// SimulateStop simulates the Stop hook with session transcript info.
func (r *HookRunner) SimulateStop(sessionID, transcriptPath string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": transcriptPath,
}
return r.runHookWithInput("stop", input)
}
// SimulateSessionEnd simulates the Claude Code session-end hook.
// This transitions a session from IDLE (or ACTIVE) to ENDED phase.
func (r *HookRunner) SimulateSessionEnd(sessionID string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
}
return r.runHookWithInput("session-end", input)
}
// PreTaskInput contains the input for PreToolUse[Task] hook.
type PreTaskInput struct {
SessionID string
TranscriptPath string
ToolUseID string
SubagentType string // Optional: type of subagent (e.g., "dev", "reviewer")
Description string // Optional: task description
}
// SimulatePreTask simulates the PreToolUse[Task] hook.
func (r *HookRunner) SimulatePreTask(sessionID, transcriptPath, toolUseID string) error {
r.T.Helper()
return r.SimulatePreTaskWithInput(PreTaskInput{
SessionID: sessionID,
TranscriptPath: transcriptPath,
ToolUseID: toolUseID,
})
}
// SimulatePreTaskWithInput simulates the PreToolUse[Task] hook with full input.
func (r *HookRunner) SimulatePreTaskWithInput(input PreTaskInput) error {
r.T.Helper()
hookInput := map[string]interface{}{
"session_id": input.SessionID,
"transcript_path": input.TranscriptPath,
"tool_use_id": input.ToolUseID,
"tool_input": map[string]string{
"subagent_type": input.SubagentType,
"description": input.Description,
},
}
return r.runHookWithInput("pre-task", hookInput)
}
// PostTaskInput contains the input for PostToolUse[Task] hook.
type PostTaskInput struct {
SessionID string
TranscriptPath string
ToolUseID string
AgentID string
}
// SimulatePostTask simulates the PostToolUse[Task] hook.
func (r *HookRunner) SimulatePostTask(input PostTaskInput) error {
r.T.Helper()
hookInput := map[string]interface{}{
"session_id": input.SessionID,
"transcript_path": input.TranscriptPath,
"tool_use_id": input.ToolUseID,
"tool_input": map[string]string{},
"tool_response": map[string]string{
"agentId": input.AgentID,
},
}
return r.runHookWithInput("post-task", hookInput)
}
func (r *HookRunner) runHookWithInput(flag string, input interface{}) error {
r.T.Helper()
inputJSON, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshal hook input: %w", err)
}
return r.runHookInRepoDir(flag, inputJSON)
}
func (r *HookRunner) runHookInRepoDir(hookName string, inputJSON []byte) error {
// Run using the shared test binary
// Command structure: trace hooks claude-code <hook-name>
cmd := exec.Command(getTestBinary(), "hooks", "claude-code", hookName)
cmd.Dir = r.RepoDir
cmd.Stdin = bytes.NewReader(inputJSON)
cmd.Env = append(
testutil.GitIsolatedEnv(),
"TRACE_TEST_CLAUDE_PROJECT_DIR="+r.ClaudeProjectDir,
)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("hook %s failed: %w\nInput: %s\nOutput: %s",
hookName, err, inputJSON, output)
}
r.T.Logf("Hook %s output: %s", hookName, output)
return nil
}
// Session represents a simulated Claude Code session.
type Session struct {
ID string // Raw model session ID (e.g., "test-session-1")
TranscriptPath string
TranscriptBuilder *TranscriptBuilder
env *TestEnv
}
// FileChange represents a file modification in a session.
type FileChange struct {
Path string
Content string
}
// NewSession creates a new simulated session.
func (env *TestEnv) NewSession() *Session {
env.T.Helper()
env.SessionCounter++
sessionID := fmt.Sprintf("test-session-%d", env.SessionCounter)
transcriptPath := filepath.Join(env.RepoDir, ".trace", "tmp", sessionID+".jsonl")
return &Session{
ID: sessionID,
TranscriptPath: transcriptPath,
TranscriptBuilder: NewTranscriptBuilder(),
env: env,
}
}
// CreateTranscript builds and writes a transcript for the session.
func (s *Session) CreateTranscript(prompt string, changes []FileChange) string {
s.TranscriptBuilder.AddUserMessage(prompt)
s.TranscriptBuilder.AddAssistantMessage("I'll help you with that.")
for _, change := range changes {
toolID := s.TranscriptBuilder.AddToolUse("mcp__acp__Write", change.Path, change.Content)
s.TranscriptBuilder.AddToolResult(toolID)
}
s.TranscriptBuilder.AddAssistantMessage("Done!")
if err := s.TranscriptBuilder.WriteToFile(s.TranscriptPath); err != nil {
s.env.T.Fatalf("failed to write transcript: %v", err)
}
return s.TranscriptPath
}
// SimulateUserPromptSubmit is a convenience method on TestEnv.
func (env *TestEnv) SimulateUserPromptSubmit(sessionID string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmit(sessionID)
}
// SimulateUserPromptSubmitWithPrompt is a convenience method on TestEnv.
func (env *TestEnv) SimulateUserPromptSubmitWithPrompt(sessionID, prompt string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithPrompt(sessionID, prompt)
}
func (env *TestEnv) SimulateUserPromptSubmitWithReviewEnvVars(sessionID, prompt string, extraEnv []string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithReviewEnvVars(sessionID, prompt, extraEnv)
}
// SimulateUserPromptSubmitWithTranscriptPath is a convenience method on TestEnv.
// This is needed for mid-session commit detection which reads the live transcript.
func (env *TestEnv) SimulateUserPromptSubmitWithTranscriptPath(sessionID, transcriptPath string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithTranscriptPath(sessionID, transcriptPath)
}
// SimulateUserPromptSubmitWithPromptAndTranscriptPath is a convenience method on TestEnv.
func (env *TestEnv) SimulateUserPromptSubmitWithPromptAndTranscriptPath(sessionID, prompt, transcriptPath string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithPromptAndTranscriptPath(sessionID, prompt, transcriptPath)
}
// SimulateUserPromptSubmitWithResponse is a convenience method on TestEnv.
func (env *TestEnv) SimulateUserPromptSubmitWithResponse(sessionID string) (*HookResponse, error) {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithResponse(sessionID)
}
// SimulateStop is a convenience method on TestEnv.
func (env *TestEnv) SimulateStop(sessionID, transcriptPath string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateStop(sessionID, transcriptPath)
}
// SimulateSessionEnd is a convenience method on TestEnv.
func (env *TestEnv) SimulateSessionEnd(sessionID string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateSessionEnd(sessionID)
}
// SimulatePreTask is a convenience method on TestEnv.
func (env *TestEnv) SimulatePreTask(sessionID, transcriptPath, toolUseID string) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulatePreTask(sessionID, transcriptPath, toolUseID)
}
// SimulatePostTask is a convenience method on TestEnv.
func (env *TestEnv) SimulatePostTask(input PostTaskInput) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulatePostTask(input)
}
// Todo represents a single todo item in the PostTodoInput.
type Todo struct {
Content string `json:"content"`
Status string `json:"status"`
ActiveForm string `json:"activeForm"`
}
// PostTodoInput contains the input for PostToolUse[TodoWrite] hook.
type PostTodoInput struct {
SessionID string
TranscriptPath string
ToolUseID string // The TodoWrite tool use ID
Todos []Todo // The todo list
}
// SimulatePostTodo simulates the PostToolUse[TodoWrite] hook.
func (r *HookRunner) SimulatePostTodo(input PostTodoInput) error {
r.T.Helper()
hookInput := map[string]interface{}{
"session_id": input.SessionID,
"transcript_path": input.TranscriptPath,
"tool_name": "TodoWrite",
"tool_use_id": input.ToolUseID,
"tool_input": map[string]interface{}{
"todos": input.Todos,
},
"tool_response": map[string]interface{}{},
}
return r.runHookWithInput("post-todo", hookInput)
}
// SimulatePostTodo is a convenience method on TestEnv.
func (env *TestEnv) SimulatePostTodo(input PostTodoInput) error {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulatePostTodo(input)
}
// ClearSessionState removes the session state file for the given session ID.
// This simulates what happens when a user commits their changes (session is "completed").
// Used in tests to allow sequential sessions to run without triggering concurrent session warnings.
func (env *TestEnv) ClearSessionState(sessionID string) error {
env.T.Helper()
// Session state is stored in .git/trace-sessions/<session-id>.json
stateFile := filepath.Join(env.RepoDir, ".git", "trace-sessions", sessionID+".json")
if err := os.Remove(stateFile); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to clear session state: %w", err)
}
return nil
}
// HookOutput contains the result of running a hook.
type HookOutput struct {
Stdout []byte
Stderr []byte
Err error
}
// runAgentHookWithOutput runs a hook for the given agent and returns stdout/stderr separately.
func (r *HookRunner) runAgentHookWithOutput(agentName, hookName string, inputJSON []byte, extraEnv ...string) HookOutput {
cmd := exec.Command(getTestBinary(), "hooks", agentName, hookName)
cmd.Dir = r.RepoDir
cmd.Stdin = bytes.NewReader(inputJSON)
cmd.Env = append(
testutil.GitIsolatedEnv(),
"TRACE_TEST_CLAUDE_PROJECT_DIR="+r.ClaudeProjectDir,
"GOCACHE=/tmp/go-build",
)
cmd.Env = append(cmd.Env, extraEnv...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return HookOutput{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
Err: err,
}
}
// runShellHookCommandWithOutput runs an installed hook shell command exactly as written
// in the hook file and returns stdout/stderr separately.
func (r *HookRunner) runShellHookCommandWithOutput(command string, inputJSON []byte, extraEnv ...string) HookOutput {
cmd := exec.Command("/bin/sh", "-c", command)
cmd.Dir = r.RepoDir
cmd.Stdin = bytes.NewReader(inputJSON)
cmd.Env = append(
testutil.GitIsolatedEnv(),
"TRACE_TEST_CLAUDE_PROJECT_DIR="+r.ClaudeProjectDir,
"GOCACHE=/tmp/go-build",
)
cmd.Env = append(cmd.Env, extraEnv...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return HookOutput{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
Err: err,
}
}
// runHookWithOutput runs a hook and returns both stdout and stderr separately.
func (r *HookRunner) runHookWithOutput(hookName string, inputJSON []byte) HookOutput {
return r.runAgentHookWithOutput("claude-code", hookName, inputJSON)
}
// SimulateUserPromptSubmitWithOutput simulates the UserPromptSubmit hook and returns the output.
func (r *HookRunner) SimulateUserPromptSubmitWithOutput(sessionID string) HookOutput {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
}
inputJSON, err := json.Marshal(input)
if err != nil {
return HookOutput{Err: fmt.Errorf("failed to marshal hook input: %w", err)}
}
return r.runHookWithOutput("user-prompt-submit", inputJSON)
}
// SimulateUserPromptSubmitWithOutput is a convenience method on TestEnv.
func (env *TestEnv) SimulateUserPromptSubmitWithOutput(sessionID string) HookOutput {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateUserPromptSubmitWithOutput(sessionID)
}
// SimulateSessionStartWithOutput simulates the SessionStart hook and returns the output.
func (r *HookRunner) SimulateSessionStartWithOutput(sessionID string) HookOutput {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
}
inputJSON, err := json.Marshal(input)
if err != nil {
return HookOutput{Err: fmt.Errorf("failed to marshal hook input: %w", err)}
}
return r.runHookWithOutput("session-start", inputJSON)
}
// SimulateSessionStartWithOutput is a convenience method on TestEnv.
func (env *TestEnv) SimulateSessionStartWithOutput(sessionID string) HookOutput {
env.T.Helper()
runner := NewHookRunner(env.RepoDir, env.ClaudeProjectDir, env.T)
return runner.SimulateSessionStartWithOutput(sessionID)
}
// GetSessionState reads and returns the session state for the given session ID.
func (env *TestEnv) GetSessionState(sessionID string) (*strategy.SessionState, error) {
env.T.Helper()
stateFile := filepath.Join(env.RepoDir, ".git", "trace-sessions", sessionID+".json")
data, err := os.ReadFile(stateFile)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("failed to read session state: %w", err)
}
var state strategy.SessionState
if err := json.Unmarshal(data, &state); err != nil {
return nil, fmt.Errorf("failed to parse session state: %w", err)
}
return &state, nil
}
// WriteSessionState writes the session state for the given session ID.
// This is useful for tests that need to manipulate session state directly.
func (env *TestEnv) WriteSessionState(sessionID string, state *strategy.SessionState) error {
env.T.Helper()
stateDir := filepath.Join(env.RepoDir, ".git", "trace-sessions")
if err := os.MkdirAll(stateDir, 0o755); err != nil {
return fmt.Errorf("failed to create session state dir: %w", err)
}
stateFile := filepath.Join(stateDir, sessionID+".json")
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal session state: %w", err)
}
if err := os.WriteFile(stateFile, data, 0o644); err != nil {
return fmt.Errorf("failed to write session state: %w", err)
}
return nil
}
// GeminiHookRunner executes Gemini CLI hooks in the test environment.
type GeminiHookRunner struct {
RepoDir string
GeminiProjectDir string
T interface {
Helper()
Fatalf(format string, args ...interface{})
Logf(format string, args ...interface{})
}
}
// NewGeminiHookRunner creates a new Gemini hook runner for the given repo directory.
func NewGeminiHookRunner(repoDir, geminiProjectDir string, t interface {
Helper()
Fatalf(format string, args ...interface{})
Logf(format string, args ...interface{})
},
) *GeminiHookRunner {
return &GeminiHookRunner{
RepoDir: repoDir,
GeminiProjectDir: geminiProjectDir,
T: t,
}
}
// runGeminiHookWithInput runs a Gemini hook with the given input.
func (r *GeminiHookRunner) runGeminiHookWithInput(hookName string, input interface{}) error {
r.T.Helper()
inputJSON, err := json.Marshal(input)
if err != nil {
return fmt.Errorf("failed to marshal hook input: %w", err)
}
return r.runGeminiHookInRepoDir(hookName, inputJSON)
}
func (r *GeminiHookRunner) runGeminiHookInRepoDir(hookName string, inputJSON []byte) error {
// Run using the shared test binary
// Command structure: trace hooks gemini <hook-name>
cmd := exec.Command(getTestBinary(), "hooks", "gemini", hookName)
cmd.Dir = r.RepoDir
cmd.Stdin = bytes.NewReader(inputJSON)
cmd.Env = append(
testutil.GitIsolatedEnv(),
"TRACE_TEST_GEMINI_PROJECT_DIR="+r.GeminiProjectDir,
)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("hook %s failed: %w\nInput: %s\nOutput: %s",
hookName, err, inputJSON, output)
}
r.T.Logf("Gemini hook %s output: %s", hookName, output)
return nil
}
// runGeminiHookWithOutput runs a Gemini hook and returns both stdout and stderr separately.
func (r *GeminiHookRunner) runGeminiHookWithOutput(hookName string, inputJSON []byte) HookOutput {
cmd := exec.Command(getTestBinary(), "hooks", "gemini", hookName)
cmd.Dir = r.RepoDir
cmd.Stdin = bytes.NewReader(inputJSON)
cmd.Env = append(
testutil.GitIsolatedEnv(),
"TRACE_TEST_GEMINI_PROJECT_DIR="+r.GeminiProjectDir,
)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
return HookOutput{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
Err: err,
}
}
// SimulateGeminiBeforeAgent simulates the BeforeAgent hook for Gemini CLI.
// This is equivalent to Claude Code's UserPromptSubmit.
func (r *GeminiHookRunner) SimulateGeminiBeforeAgent(sessionID string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
"cwd": r.RepoDir,
"hook_event_name": "BeforeAgent",
"timestamp": "2025-01-01T00:00:00Z",
"prompt": "test prompt",
}
return r.runGeminiHookWithInput("before-agent", input)
}
// SimulateGeminiBeforeAgentWithOutput simulates the BeforeAgent hook and returns the output.
func (r *GeminiHookRunner) SimulateGeminiBeforeAgentWithOutput(sessionID string) HookOutput {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": "",
"cwd": r.RepoDir,
"hook_event_name": "BeforeAgent",
"timestamp": "2025-01-01T00:00:00Z",
"prompt": "test prompt",
}
inputJSON, err := json.Marshal(input)
if err != nil {
return HookOutput{Err: fmt.Errorf("failed to marshal hook input: %w", err)}
}
return r.runGeminiHookWithOutput("before-agent", inputJSON)
}
// SimulateGeminiAfterAgent simulates the AfterAgent hook for Gemini CLI.
// This is the primary checkpoint creation hook, equivalent to Claude Code's Stop hook.
func (r *GeminiHookRunner) SimulateGeminiAfterAgent(sessionID, transcriptPath string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": transcriptPath,
"cwd": r.RepoDir,
"hook_event_name": "AfterAgent",
"timestamp": "2025-01-01T00:00:00Z",
}
return r.runGeminiHookWithInput("after-agent", input)
}
// SimulateGeminiSessionEnd simulates the SessionEnd hook for Gemini CLI.
// This is a cleanup/fallback hook that fires on explicit exit.
func (r *GeminiHookRunner) SimulateGeminiSessionEnd(sessionID, transcriptPath string) error {
r.T.Helper()
input := map[string]string{
"session_id": sessionID,
"transcript_path": transcriptPath,
"cwd": r.RepoDir,
"hook_event_name": "SessionEnd",
"timestamp": "2025-01-01T00:00:00Z",
"reason": "exit",
}
return r.runGeminiHookWithInput("session-end", input)
}
// GeminiSession represents a simulated Gemini CLI session.
type GeminiSession struct {
ID string // Raw model session ID (e.g., "gemini-session-1")
TranscriptPath string
env *TestEnv
}
// NewGeminiSession creates a new simulated Gemini session.
func (env *TestEnv) NewGeminiSession() *GeminiSession {
env.T.Helper()
env.SessionCounter++
sessionID := fmt.Sprintf("gemini-session-%d", env.SessionCounter)
transcriptPath := filepath.Join(env.RepoDir, ".trace", "tmp", sessionID+".json")
return &GeminiSession{
ID: sessionID,
TranscriptPath: transcriptPath,
env: env,
}
}
// CreateGeminiTranscript creates a Gemini JSON transcript file for the session.
func (s *GeminiSession) CreateGeminiTranscript(prompt string, changes []FileChange) string {
// Build Gemini-format transcript (JSON, not JSONL)
messages := []map[string]interface{}{
{
"type": "user",
"content": prompt,
},
{
"type": "assistant",
"content": "I'll help you with that.",
},
}
for _, change := range changes {
messages = append(messages, map[string]interface{}{
"type": "tool_use",
"name": "write_file",
"input": map[string]string{
"path": change.Path,
"content": change.Content,
},
})
messages = append(messages, map[string]interface{}{
"type": "tool_result",
"output": "File written successfully",
})
}
messages = append(messages, map[string]interface{}{
"type": "assistant",
"content": "Done!",
})
transcript := map[string]interface{}{
"sessionId": s.ID,
"messages": messages,
}
// Ensure directory exists
if err := os.MkdirAll(filepath.Dir(s.TranscriptPath), 0o755); err != nil {
s.env.T.Fatalf("failed to create transcript dir: %v", err)
}
// Write transcript
data, err := json.MarshalIndent(transcript, "", " ")
if err != nil {
s.env.T.Fatalf("failed to marshal transcript: %v", err)
}
if err := os.WriteFile(s.TranscriptPath, data, 0o644); err != nil {
s.env.T.Fatalf("failed to write transcript: %v", err)
}
return s.TranscriptPath
}
// SimulateGeminiBeforeAgent is a convenience method on TestEnv.
func (env *TestEnv) SimulateGeminiBeforeAgent(sessionID string) error {
env.T.Helper()
runner := NewGeminiHookRunner(env.RepoDir, env.GeminiProjectDir, env.T)
return runner.SimulateGeminiBeforeAgent(sessionID)
}