//go:build !integration package sync import ( "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "maps" "math" "net/http" "os" "path/filepath" "slices" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" gitlab "gitlab.com/gitlab-org/api/client-go/v3" gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing" "gitlab.com/gitlab-org/cli/internal/api" "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/claudehooks" "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/syncstate" "gitlab.com/gitlab-org/cli/internal/glrepo" "gitlab.com/gitlab-org/cli/internal/mcpannotations" "gitlab.com/gitlab-org/cli/internal/testing/cmdtest" ) func TestDeterministicUUID(t *testing.T) { t.Parallel() t.Run("same input produces same UUID", func(t *testing.T) { t.Parallel() id := "toolu_01QY5JDwbgF8AuLRsEMrYyyn" first := deterministicUUID(id) second := deterministicUUID(id) assert.Equal(t, first, second) }) t.Run("different inputs produce different UUIDs", func(t *testing.T) { t.Parallel() assert.NotEqual(t, deterministicUUID("id-1"), deterministicUUID("id-2")) }) t.Run("is a stable SHA-256 UUIDv8", func(t *testing.T) { t.Parallel() assert.Equal(t, "e7c71be9-dd76-8834-9de1-8119c8141268", deterministicUUID("toolu_01QY5JDwbgF8AuLRsEMrYyyn"), "GitLab deduplicates audit events by this ID, so changing it duplicates re-synced events") }) t.Run("output is valid UUID format", func(t *testing.T) { t.Parallel() uuid := deterministicUUID("toolu_01QY5JDwbgF8AuLRsEMrYyyn") assert.Regexp(t, `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, uuid) }) } func TestCwdToProjectHash(t *testing.T) { t.Parallel() sep := string(filepath.Separator) input1 := sep + filepath.Join("Users", "jean", "demo-gaig") input2 := sep + filepath.Join("home", "jean", "project") assert.Equal(t, strings.ReplaceAll(input1, sep, "-"), cwdToProjectHash(input1)) assert.Equal(t, strings.ReplaceAll(input2, sep, "-"), cwdToProjectHash(input2)) } func TestParseTranscript(t *testing.T) { t.Parallel() makeEntry := func(entryType string, extra map[string]any) []byte { entry := map[string]any{"type": entryType} maps.Copy(entry, extra) data, _ := json.Marshal(entry) return data } t.Run("extracts goal from first user message", func(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "session.jsonl") lines := [][]byte{ makeEntry("user", map[string]any{ "promptId": "p1", "sessionId": "sess-123", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "text", "text": "list the files in this project"}, }, }, }), makeEntry("assistant", map[string]any{ "sessionId": "sess-123", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "tool_use", "id": "toolu_abc123", "name": "Bash"}, }, }, }), } var content []byte for _, line := range lines { content = append(content, line...) content = append(content, '\n') } require.NoError(t, os.WriteFile(path, content, 0o644)) data, offset, err := parseTranscript(path, 0) require.NoError(t, err) assert.Equal(t, "list the files in this project", data.Goal) assert.Equal(t, "sess-123", data.SessionID) assert.Len(t, data.ToolCalls, 1) assert.Equal(t, "Bash", data.ToolCalls[0].Name) assert.Equal(t, "toolu_abc123", data.ToolCalls[0].ID) assert.Positive(t, offset) }) t.Run("skips entries before cursor offset", func(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "session.jsonl") line := makeEntry("assistant", map[string]any{ "sessionId": "sess-456", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "tool_use", "id": "toolu_skip", "name": "Read"}, }, }, }) require.NoError(t, os.WriteFile(path, append(line, '\n'), 0o644)) // Start after the first line -- should find no tool calls data, _, err := parseTranscript(path, int64(len(line)+1)) require.NoError(t, err) assert.Empty(t, data.ToolCalls) }) t.Run("handles empty file", func(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "empty.jsonl") require.NoError(t, os.WriteFile(path, []byte{}, 0o644)) data, offset, err := parseTranscript(path, 0) require.NoError(t, err) assert.Empty(t, data.ToolCalls) assert.Equal(t, int64(0), offset) }) t.Run("skips malformed lines", func(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "session.jsonl") content := []byte("not valid json\n") content = append(content, makeEntry("assistant", map[string]any{ "sessionId": "sess-789", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "tool_use", "id": "toolu_valid", "name": "Edit"}, }, }, })...) content = append(content, '\n') require.NoError(t, os.WriteFile(path, content, 0o644)) data, _, err := parseTranscript(path, 0) require.NoError(t, err) assert.Len(t, data.ToolCalls, 1) assert.Equal(t, "Edit", data.ToolCalls[0].Name) }) t.Run("reads an entry that was still being written on the next sync", func(t *testing.T) { t.Parallel() path := filepath.Join(t.TempDir(), "session.jsonl") toolUse := func(id string) []byte { return makeEntry("assistant", map[string]any{ "sessionId": "sess-partial", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "tool_use", "id": id, "name": "Bash"}, }, }, }) } first := append(toolUse("toolu_first"), '\n') second := append(toolUse("toolu_second"), '\n') half := len(second) / 2 require.NoError(t, os.WriteFile(path, append(slices.Clone(first), second[:half]...), 0o644)) data, offset, err := parseTranscript(path, 0) require.NoError(t, err) require.Len(t, data.ToolCalls, 1) assert.Equal(t, "toolu_first", data.ToolCalls[0].ID) assert.Equal(t, int64(len(first)), offset) f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0) require.NoError(t, err) _, err = f.Write(second[half:]) require.NoError(t, err) require.NoError(t, f.Close()) data, offset, err = parseTranscript(path, offset) require.NoError(t, err) require.Len(t, data.ToolCalls, 1) assert.Equal(t, "toolu_second", data.ToolCalls[0].ID) assert.Equal(t, int64(len(first)+len(second)), offset) }) t.Run("reads entries longer than 1 MB", func(t *testing.T) { t.Parallel() path := filepath.Join(t.TempDir(), "session.jsonl") line := makeEntry("assistant", map[string]any{ "sessionId": "sess-large", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ { "type": "tool_use", "id": "toolu_large", "name": "Write", "input": map[string]any{"content": strings.Repeat("a", 2<<20)}, }, }, }, }) require.NoError(t, os.WriteFile(path, append(line, '\n'), 0o644)) data, offset, err := parseTranscript(path, 0) require.NoError(t, err) require.Len(t, data.ToolCalls, 1) assert.Equal(t, "toolu_large", data.ToolCalls[0].ID) assert.Equal(t, int64(len(line)+1), offset) }) } func TestTranscriptSHA256(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "session.jsonl") content := []byte(`{"type":"user","message":"hello"}` + "\n") require.NoError(t, os.WriteFile(path, content, 0o644)) hash := sha256.Sum256(content) expected := hex.EncodeToString(hash[:]) actual, err := sha256File(path) require.NoError(t, err) assert.Equal(t, expected, actual) } func TestSyncSession_NoTranscript(t *testing.T) { t.Parallel() dir := t.TempDir() ios, _, stdout, _ := cmdtest.TestIOStreams() opts := &options{io: ios} err := syncSession(t.Context(), target{}, "test-session", claudeTranscript{path: filepath.Join(dir, "nonexistent.jsonl")}, opts) require.NoError(t, err) assert.Contains(t, stdout.String(), "No transcript found") } func TestSyncSession_NoNewEntries(t *testing.T) { t.Parallel() dir := t.TempDir() path := filepath.Join(dir, "session.jsonl") require.NoError(t, os.WriteFile(path, []byte{}, 0o644)) ios, _, stdout, _ := cmdtest.TestIOStreams() opts := &options{io: ios} err := syncSession(t.Context(), target{}, "test-session", claudeTranscript{path: path}, opts) require.NoError(t, err) assert.Contains(t, stdout.String(), "No new entries to sync") } func TestSyncSession_CursorNotAdvancedOnSessionFailure(t *testing.T) { dir := t.TempDir() t.Setenv("HOME", dir) t.Setenv("GLAB_CONFIG_DIR", dir) path := filepath.Join(dir, "session.jsonl") // Write a transcript with a tool call entry := map[string]any{ "type": "assistant", "sessionId": "sess-test", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{ "content": []map[string]any{ {"type": "tool_use", "id": "toolu_abc", "name": "Bash"}, }, }, } data, _ := json.Marshal(entry) require.NoError(t, os.WriteFile(path, append(data, '\n'), 0o644)) // nil client will cause ensureSession to fail ios, _, _, _ := cmdtest.TestIOStreams() opts := &options{io: ios, silent: true} _ = syncSession(t.Context(), target{}, "sess-test", claudeTranscript{path: path}, opts) // Cursor should NOT have advanced since session creation failed cursor, err := syncstate.ReadPosition("sess-test") require.NoError(t, err) assert.Equal(t, int64(0), cursor, "cursor should not advance when session creation fails") } func TestRunSync_RepoOverrideReachesResolveProject(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) t.Setenv("CLAUDE_CODE_SESSION_ID", "") t.Setenv("OPENCODE_SESSION_ID", "") ctrl := gomock.NewController(t) tc := gitlabtesting.NewTestClientWithCtrl(ctrl, gitlab.WithBaseURL("https://gitlab.example.com")) tc.MockProjects.EXPECT(). GetProject(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil, nil, errors.New("project my-group/my-project not found")) exec := cmdtest.SetupCmdForTest( t, NewCmd, false, cmdtest.WithApiClient(cmdtest.NewTestAuthSourceApiClient( t, nil, gitlab.AccessTokenAuthSource{Token: "test-token"}, "gitlab.example.com", api.WithGitLabClient(tc.Client), )), ) _, err := exec("--silent -R my-group/my-project") require.Error(t, err) assert.Contains(t, err.Error(), "my-group/my-project") } func TestMCPDestructiveAnnotation(t *testing.T) { t.Parallel() ios, _, _, _ := cmdtest.TestIOStreams() f := cmdtest.NewTestFactory(ios) cmd := NewCmd(f) assert.Equal(t, "true", cmd.Annotations[mcpannotations.Destructive]) } func TestFindTranscriptForSession(t *testing.T) { dir := t.TempDir() t.Setenv("HOME", dir) // Create a transcript in a project subdirectory projectDir := filepath.Join(dir, ".claude", "projects", "-Users-jean-code-gaig-test") require.NoError(t, os.MkdirAll(projectDir, 0o755)) transcriptPath := filepath.Join(projectDir, "test-session-123.jsonl") require.NoError(t, os.WriteFile(transcriptPath, []byte("{}"), 0o644)) found, err := findTranscriptForSession("test-session-123") require.NoError(t, err) assert.Equal(t, transcriptPath, found) } func TestFindTranscriptForSession_NotFound(t *testing.T) { dir := t.TempDir() t.Setenv("HOME", dir) found, err := findTranscriptForSession("nonexistent-session") require.NoError(t, err) assert.Empty(t, found) } func TestWriteReadSessionMeta(t *testing.T) { dir := t.TempDir() t.Setenv("GLAB_CONFIG_DIR", dir) meta := sessionMeta{ AgentType: "claude-code", PathWithNamespace: "my-group/my-project", Host: "gitlab.com", } require.NoError(t, writeSessionMeta("test-session", meta)) got, err := readSessionMeta("test-session") require.NoError(t, err) require.NotNil(t, got) assert.Equal(t, "claude-code", got.AgentType) assert.Equal(t, "my-group/my-project", got.PathWithNamespace) assert.Equal(t, "gitlab.com", got.Host) } func TestReadSessionMeta_NotFound(t *testing.T) { dir := t.TempDir() t.Setenv("GLAB_CONFIG_DIR", dir) _, err := readSessionMeta("nonexistent-session") require.ErrorIs(t, err, errNoSessionMeta) } func TestAuditEventBatches(t *testing.T) { small := auditEventRequest{EventName: eventToolInvoked, Details: map[string]any{"tool_name": "Bash"}} large := auditEventRequest{EventName: eventToolInvoked, Details: map[string]any{}} for i := range maxElementsPerRequest { large.Details[fmt.Sprintf("k%d", i)] = i } assert.Empty(t, auditEventBatches(nil)) events := slices.Repeat([]auditEventRequest{small}, 1000) events[10] = large batches := auditEventBatches(events) total := 0 for _, batch := range batches { total += len(batch) assert.LessOrEqual(t, len(batch), maxEventsPerRequest) if len(batch) == 1 && batch[0].Details["k0"] != nil { continue } elements := auditEventsRequestElements for _, event := range batch { elements += auditEventElements(event) } assert.LessOrEqual(t, elements, maxElementsPerRequest) } assert.Equal(t, len(events), total) assert.Contains(t, batches, []auditEventRequest{large}, "an event over the budget is posted on its own") } func TestAuditEventBatchesBytes(t *testing.T) { // GitLab accepts up to 32 KB of details per event, and the element budget // alone would put about 400 of these in one request. event := auditEventRequest{ EventName: eventToolInvoked, Details: map[string]any{"content": strings.Repeat("a", 30*1024)}, } events := slices.Repeat([]auditEventRequest{event}, 300) batches := auditEventBatches(events) require.Len(t, batches, 3, "about 130 of these fit in the byte budget") total := 0 for _, batch := range batches { total += len(batch) body := auditEventsRequest{SessionID: math.MaxInt, Events: batch} assert.LessOrEqual(t, encodedLen(body), maxBytesPerRequest) } assert.Equal(t, len(events), total) } func TestRateLimitWait(t *testing.T) { rateLimited := func(retryAfter string) error { header := http.Header{} if retryAfter != "" { header.Set("Retry-After", retryAfter) } return &gitlab.ErrorResponse{StatusCode: http.StatusTooManyRequests, Response: &http.Response{Header: header}} } tests := []struct { name string err error wantWait time.Duration wantLimited bool }{ {"no error", nil, 0, false}, {"other status", &gitlab.ErrorResponse{StatusCode: http.StatusBadRequest}, 0, false}, {"retry after", rateLimited("30"), 30 * time.Second, true}, {"no retry after", rateLimited(""), time.Minute, true}, {"zero retry after", rateLimited("0"), 0, true}, {"date retry after", rateLimited("Wed, 21 Oct 2026 07:28:00 GMT"), time.Minute, true}, {"long retry after", rateLimited("3600"), maxRateLimitWait, true}, {"no response", &gitlab.ErrorResponse{StatusCode: http.StatusTooManyRequests}, time.Minute, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { wait, limited := rateLimitWait(tt.err) assert.Equal(t, tt.wantLimited, limited) assert.Equal(t, tt.wantWait, wait) }) } } func TestRecordSessionMeta_WithoutGitLabRemote(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }} require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/transcripts/sess-1.jsonl")) meta, err := readSessionMeta("sess-1") require.NoError(t, err) assert.Equal(t, sessionMeta{AgentType: "claude-code", Transcript: "/transcripts/sess-1.jsonl"}, *meta) } func TestRecordSessionMeta_WithoutGitLabRemoteKeepsProject(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) recorded := sessionMeta{AgentType: "claude-code", PathWithNamespace: "my-group/my-project", Host: "gitlab.com", Transcript: "/t.jsonl"} require.NoError(t, writeSessionMeta("sess-1", recorded)) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }} require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl")) meta, err := readSessionMeta("sess-1") require.NoError(t, err) assert.Equal(t, recorded, *meta) } func TestRecordSessionMeta_RemoteReplacesSessionWithoutProject(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) t.Setenv("HOME", t.TempDir()) path := filepath.Join(t.TempDir(), "sess-1.jsonl") content := claudeTranscriptLines(t, "sess-1", "toolu_1") require.NoError(t, os.WriteFile(path, content, 0o644)) require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: path})) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil }} require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", path)) meta, err := readSessionMeta("sess-1") require.NoError(t, err) assert.Equal(t, sessionMeta{AgentType: "claude-code", PathWithNamespace: "my-group/my-project", Host: "gitlab.com", Transcript: path}, *meta) assertCursorAt(t, "sess-1", int64(len(content))) } func TestRecordSessionMeta_KeepsSessionWithoutProjectWhenSkipFails(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) t.Setenv("HOME", t.TempDir()) missing := filepath.Join(t.TempDir(), "gone.jsonl") require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: missing})) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil }} require.ErrorIs(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", missing), errEarlierActivityNotSkipped, "the hook stops rather than syncing from the start") meta, err := readSessionMeta("sess-1") require.NoError(t, err) assert.Empty(t, meta.PathWithNamespace, "the next hook call retries the skip") assertCursorAt(t, "sess-1", 0) } func TestRecordSessionMeta_NewSessionWithRemoteUploadsFromTheStart(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil }} path := filepath.Join(t.TempDir(), "sess-1.jsonl") require.NoError(t, os.WriteFile(path, claudeTranscriptLines(t, "sess-1", "toolu_1"), 0o644)) require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", path)) assertCursorAt(t, "sess-1", 0) } func TestSkipToEnd(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) path := filepath.Join(t.TempDir(), "sess-1.jsonl") content := claudeTranscriptLines(t, "sess-1", "toolu_1", "toolu_2") require.NoError(t, os.WriteFile(path, append(content, []byte(`{"type":"assistant"`)...), 0o644)) require.NoError(t, syncstate.WritePosition("sess-1", 10)) require.NoError(t, skipToEnd(t.Context(), "sess-1", claudeTranscript{path: path})) assertCursorAt(t, "sess-1", int64(len(content))) } func TestRecordSessionMeta_WithoutGitLabRemoteKeepsUnreadableRecord(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) path, err := metaPath("sess-1") require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600)) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }} require.Error(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl")) data, err := os.ReadFile(path) require.NoError(t, err) assert.Equal(t, "not json", string(data), "a record that may hold a project is not replaced") } func TestRecordSessionMeta_RemoteReplacesUnreadableRecord(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) path, err := metaPath("sess-1") require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600)) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil }} require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl")) meta, err := readSessionMeta("sess-1") require.NoError(t, err) assert.Equal(t, "my-group/my-project", meta.PathWithNamespace) } func TestRecordSessionMeta_SkipsUsingTheRecordedTranscript(t *testing.T) { t.Setenv("GLAB_CONFIG_DIR", t.TempDir()) t.Setenv("HOME", t.TempDir()) path := filepath.Join(t.TempDir(), "sess-1.jsonl") content := claudeTranscriptLines(t, "sess-1", "toolu_1") require.NoError(t, os.WriteFile(path, content, 0o644)) require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: path})) opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil }} // The hook ran from another folder after the agent changed directory. hookPath := filepath.Join(t.TempDir(), "elsewhere", "sess-1.jsonl") require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", hookPath)) assertCursorAt(t, "sess-1", int64(len(content))) } func TestParseTranscript_Dirs(t *testing.T) { t.Parallel() path := filepath.Join(t.TempDir(), "session.jsonl") line := func(entry map[string]any) string { data, err := json.Marshal(entry) require.NoError(t, err) return string(data) + "\n" } content := line(map[string]any{ "type": "user", "promptId": "p1", "uuid": "u1", "cwd": "/work/a/", "timestamp": "2026-10-09T01:00:00Z", "message": map[string]any{"content": "clone b"}, }) + line(map[string]any{ "type": "assistant", "cwd": "/work/a", "timestamp": "2026-10-09T01:00:01Z", "message": map[string]any{"id": "msg_1", "content": []any{map[string]any{"type": "tool_use", "id": "toolu_1", "name": "Bash"}}}, }) + line(map[string]any{ "type": "assistant", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:01Z", "message": map[string]any{"id": "msg_1", "content": []any{}}, }) + line(map[string]any{ "type": "user", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:02Z", "message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": "toolu_1"}}}, }) + line(map[string]any{ "type": "user", "promptId": "p2", "uuid": "u2", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:03Z", "message": map[string]any{"content": "now in b"}, }) require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) data, _, err := parseTranscript(path, 0) require.NoError(t, err) require.Len(t, data.Prompts, 2) assert.Equal(t, "/work/a", data.Prompts[0].CWD, "folders are cleaned, so a trailing slash makes no difference") assert.Equal(t, "/work/b", data.Prompts[1].CWD, "Claude Code records the folder after a cd") require.Len(t, data.ToolCalls, 1) assert.Equal(t, "/work/a", data.ToolCalls[0].CWD) require.Len(t, data.Responses, 1) assert.Equal(t, "/work/a", data.Responses[0].CWD, "a streamed response keeps its first entry's folder") require.Len(t, data.ToolResults, 1) assert.Equal(t, "/work/a", data.ToolResults[0].CWD, "a result runs where its call did") } func TestRunSync_SkipsASessionWhoseHooksWereRemoved(t *testing.T) { for name, args := range map[string]string{ "from the hook": "-R my-group/my-project --silent", "run by hand": "-R my-group/my-project", } { t.Run(name, func(t *testing.T) { env := newSyncAllEnv(t, false) t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1") cwd, err := currentCWD() require.NoError(t, err) path, err := transcriptPath("sess-1", cwd) require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(t, os.WriteFile(path, claudeTranscriptLines(t, "sess-1", "toolu_1"), 0o644)) out, err := env.exec(args) require.NoError(t, err) assert.Empty(t, env.fake.sessionRequests, "an open session must not upload after uninstall") assert.Empty(t, env.fake.events) _, err = readSessionMeta("sess-1") require.ErrorIs(t, err, errNoSessionMeta, "uninstall removed the records, so they must not come back") if strings.Contains(args, "--silent") { assert.Empty(t, out.String()) } else { assert.Contains(t, out.String(), "Not syncing the claude-code session: the glab Stop hook is not installed") } }) } } func TestRunSync_FailsWhenItCannotTellWhetherSyncingIsPaused(t *testing.T) { env := newSyncAllEnv(t, false) t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1") settings, err := claudehooks.SettingsPath() require.NoError(t, err) require.NoError(t, os.MkdirAll(filepath.Dir(settings), 0o755)) require.NoError(t, os.WriteFile(settings, []byte("{not json"), 0o600)) _, err = env.exec("-R my-group/my-project --silent") require.ErrorContains(t, err, "could not check whether syncing is paused") assert.Empty(t, env.fake.sessionRequests) _, err = readSessionMeta("sess-1") require.ErrorIs(t, err, errNoSessionMeta) } func TestGoalFromText_RedactsBeforeShortening(t *testing.T) { t.Parallel() token := fake("glpat-", 20) goal := goalFromText(strings.Repeat("x", 250) + " " + token) assert.NotContains(t, goal, "glpat-", "a token cut in half is still a leak") } func TestRunSync_RedactsSecretsBeforeUpload(t *testing.T) { env := newSyncAllEnv(t, true) t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1") token := fake("glpat-", 20) cwd, err := currentCWD() require.NoError(t, err) path, err := transcriptPath("sess-1", cwd) require.NoError(t, err) lines := jsonLines(t, map[string]any{ "type": "user", "sessionId": "sess-1", "uuid": "u-1", "promptId": "p-1", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{"role": "user", "content": "use " + token + " to call the API"}, }, map[string]any{ "type": "assistant", "sessionId": "sess-1", "timestamp": time.Now().Format(time.RFC3339), "message": map[string]any{"content": []map[string]any{{ "type": "tool_use", "id": "toolu_1", "name": "Bash", "input": map[string]any{"command": `curl -H "PRIVATE-TOKEN: ` + token + `" https://gitlab.com/api/v4/user`}, }}}, }, ) require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(t, os.WriteFile(path, []byte(lines), 0o644)) _, err = env.exec("-R my-group/my-project --silent") require.NoError(t, err) require.Len(t, env.fake.sessionRequests, 1) assert.Equal(t, "use [REDACTED:gitlab_token] to call the API", env.fake.sessionRequests[0].Goal) uploaded, err := json.Marshal(env.fake.events) require.NoError(t, err) assert.NotContains(t, string(uploaded), token) assert.Contains(t, string(uploaded), "use [REDACTED:gitlab_token] to call the API") assert.Contains(t, string(uploaded), `PRIVATE-TOKEN: [REDACTED:gitlab_token]`) }