GitLabgitlab-org

cli

main
ply9 git calls279 ms104 KiB7 cachedprotocol v2
764 lines26 KiBRaw
1//go:build !integration
3package sync
5import (
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "maps"
12 "math"
13 "net/http"
14 "os"
15 "path/filepath"
16 "slices"
17 "strings"
18 "testing"
19 "time"
21 "github.com/stretchr/testify/assert"
22 "github.com/stretchr/testify/require"
23 "go.uber.org/mock/gomock"
25 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
26 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
28 "gitlab.com/gitlab-org/cli/internal/api"
29 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/claudehooks"
30 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/syncstate"
31 "gitlab.com/gitlab-org/cli/internal/glrepo"
32 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
33 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
36func TestDeterministicUUID(t *testing.T) {
37 t.Parallel()
39 t.Run("same input produces same UUID", func(t *testing.T) {
40 t.Parallel()
41 id := "toolu_01QY5JDwbgF8AuLRsEMrYyyn"
42 first := deterministicUUID(id)
43 second := deterministicUUID(id)
44 assert.Equal(t, first, second)
45 })
47 t.Run("different inputs produce different UUIDs", func(t *testing.T) {
48 t.Parallel()
49 assert.NotEqual(t, deterministicUUID("id-1"), deterministicUUID("id-2"))
50 })
52 t.Run("is a stable SHA-256 UUIDv8", func(t *testing.T) {
53 t.Parallel()
54 assert.Equal(t, "e7c71be9-dd76-8834-9de1-8119c8141268", deterministicUUID("toolu_01QY5JDwbgF8AuLRsEMrYyyn"),
55 "GitLab deduplicates audit events by this ID, so changing it duplicates re-synced events")
56 })
58 t.Run("output is valid UUID format", func(t *testing.T) {
59 t.Parallel()
60 uuid := deterministicUUID("toolu_01QY5JDwbgF8AuLRsEMrYyyn")
61 assert.Regexp(t, `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, uuid)
62 })
65func TestCwdToProjectHash(t *testing.T) {
66 t.Parallel()
68 sep := string(filepath.Separator)
69 input1 := sep + filepath.Join("Users", "jean", "demo-gaig")
70 input2 := sep + filepath.Join("home", "jean", "project")
72 assert.Equal(t, strings.ReplaceAll(input1, sep, "-"), cwdToProjectHash(input1))
73 assert.Equal(t, strings.ReplaceAll(input2, sep, "-"), cwdToProjectHash(input2))
76func TestParseTranscript(t *testing.T) {
77 t.Parallel()
79 makeEntry := func(entryType string, extra map[string]any) []byte {
80 entry := map[string]any{"type": entryType}
81 maps.Copy(entry, extra)
82 data, _ := json.Marshal(entry)
83 return data
84 }
86 t.Run("extracts goal from first user message", func(t *testing.T) {
87 t.Parallel()
88 dir := t.TempDir()
89 path := filepath.Join(dir, "session.jsonl")
91 lines := [][]byte{
92 makeEntry("user", map[string]any{
93 "promptId": "p1",
94 "sessionId": "sess-123",
95 "timestamp": time.Now().Format(time.RFC3339),
96 "message": map[string]any{
97 "content": []map[string]any{
98 {"type": "text", "text": "list the files in this project"},
99 },
100 },
101 }),
102 makeEntry("assistant", map[string]any{
103 "sessionId": "sess-123",
104 "timestamp": time.Now().Format(time.RFC3339),
105 "message": map[string]any{
106 "content": []map[string]any{
107 {"type": "tool_use", "id": "toolu_abc123", "name": "Bash"},
108 },
109 },
110 }),
111 }
113 var content []byte
114 for _, line := range lines {
115 content = append(content, line...)
116 content = append(content, '\n')
117 }
118 require.NoError(t, os.WriteFile(path, content, 0o644))
120 data, offset, err := parseTranscript(path, 0)
121 require.NoError(t, err)
123 assert.Equal(t, "list the files in this project", data.Goal)
124 assert.Equal(t, "sess-123", data.SessionID)
125 assert.Len(t, data.ToolCalls, 1)
126 assert.Equal(t, "Bash", data.ToolCalls[0].Name)
127 assert.Equal(t, "toolu_abc123", data.ToolCalls[0].ID)
128 assert.Positive(t, offset)
129 })
131 t.Run("skips entries before cursor offset", func(t *testing.T) {
132 t.Parallel()
133 dir := t.TempDir()
134 path := filepath.Join(dir, "session.jsonl")
136 line := makeEntry("assistant", map[string]any{
137 "sessionId": "sess-456",
138 "timestamp": time.Now().Format(time.RFC3339),
139 "message": map[string]any{
140 "content": []map[string]any{
141 {"type": "tool_use", "id": "toolu_skip", "name": "Read"},
142 },
143 },
144 })
145 require.NoError(t, os.WriteFile(path, append(line, '\n'), 0o644))
147 // Start after the first line -- should find no tool calls
148 data, _, err := parseTranscript(path, int64(len(line)+1))
149 require.NoError(t, err)
150 assert.Empty(t, data.ToolCalls)
151 })
153 t.Run("handles empty file", func(t *testing.T) {
154 t.Parallel()
155 dir := t.TempDir()
156 path := filepath.Join(dir, "empty.jsonl")
157 require.NoError(t, os.WriteFile(path, []byte{}, 0o644))
159 data, offset, err := parseTranscript(path, 0)
160 require.NoError(t, err)
161 assert.Empty(t, data.ToolCalls)
162 assert.Equal(t, int64(0), offset)
163 })
165 t.Run("skips malformed lines", func(t *testing.T) {
166 t.Parallel()
167 dir := t.TempDir()
168 path := filepath.Join(dir, "session.jsonl")
170 content := []byte("not valid json\n")
171 content = append(content, makeEntry("assistant", map[string]any{
172 "sessionId": "sess-789",
173 "timestamp": time.Now().Format(time.RFC3339),
174 "message": map[string]any{
175 "content": []map[string]any{
176 {"type": "tool_use", "id": "toolu_valid", "name": "Edit"},
177 },
178 },
179 })...)
180 content = append(content, '\n')
181 require.NoError(t, os.WriteFile(path, content, 0o644))
183 data, _, err := parseTranscript(path, 0)
184 require.NoError(t, err)
185 assert.Len(t, data.ToolCalls, 1)
186 assert.Equal(t, "Edit", data.ToolCalls[0].Name)
187 })
189 t.Run("reads an entry that was still being written on the next sync", func(t *testing.T) {
190 t.Parallel()
191 path := filepath.Join(t.TempDir(), "session.jsonl")
192 toolUse := func(id string) []byte {
193 return makeEntry("assistant", map[string]any{
194 "sessionId": "sess-partial",
195 "timestamp": time.Now().Format(time.RFC3339),
196 "message": map[string]any{
197 "content": []map[string]any{
198 {"type": "tool_use", "id": id, "name": "Bash"},
199 },
200 },
201 })
202 }
203 first := append(toolUse("toolu_first"), '\n')
204 second := append(toolUse("toolu_second"), '\n')
205 half := len(second) / 2
206 require.NoError(t, os.WriteFile(path, append(slices.Clone(first), second[:half]...), 0o644))
208 data, offset, err := parseTranscript(path, 0)
209 require.NoError(t, err)
210 require.Len(t, data.ToolCalls, 1)
211 assert.Equal(t, "toolu_first", data.ToolCalls[0].ID)
212 assert.Equal(t, int64(len(first)), offset)
214 f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
215 require.NoError(t, err)
216 _, err = f.Write(second[half:])
217 require.NoError(t, err)
218 require.NoError(t, f.Close())
220 data, offset, err = parseTranscript(path, offset)
221 require.NoError(t, err)
222 require.Len(t, data.ToolCalls, 1)
223 assert.Equal(t, "toolu_second", data.ToolCalls[0].ID)
224 assert.Equal(t, int64(len(first)+len(second)), offset)
225 })
227 t.Run("reads entries longer than 1 MB", func(t *testing.T) {
228 t.Parallel()
229 path := filepath.Join(t.TempDir(), "session.jsonl")
230 line := makeEntry("assistant", map[string]any{
231 "sessionId": "sess-large",
232 "timestamp": time.Now().Format(time.RFC3339),
233 "message": map[string]any{
234 "content": []map[string]any{
235 {
236 "type": "tool_use", "id": "toolu_large", "name": "Write",
237 "input": map[string]any{"content": strings.Repeat("a", 2<<20)},
238 },
239 },
240 },
241 })
242 require.NoError(t, os.WriteFile(path, append(line, '\n'), 0o644))
244 data, offset, err := parseTranscript(path, 0)
245 require.NoError(t, err)
246 require.Len(t, data.ToolCalls, 1)
247 assert.Equal(t, "toolu_large", data.ToolCalls[0].ID)
248 assert.Equal(t, int64(len(line)+1), offset)
249 })
252func TestTranscriptSHA256(t *testing.T) {
253 t.Parallel()
255 dir := t.TempDir()
256 path := filepath.Join(dir, "session.jsonl")
257 content := []byte(`{"type":"user","message":"hello"}` + "\n")
258 require.NoError(t, os.WriteFile(path, content, 0o644))
260 hash := sha256.Sum256(content)
261 expected := hex.EncodeToString(hash[:])
263 actual, err := sha256File(path)
264 require.NoError(t, err)
265 assert.Equal(t, expected, actual)
268func TestSyncSession_NoTranscript(t *testing.T) {
269 t.Parallel()
271 dir := t.TempDir()
272 ios, _, stdout, _ := cmdtest.TestIOStreams()
273 opts := &options{io: ios}
275 err := syncSession(t.Context(), target{}, "test-session", claudeTranscript{path: filepath.Join(dir, "nonexistent.jsonl")}, opts)
276 require.NoError(t, err)
277 assert.Contains(t, stdout.String(), "No transcript found")
280func TestSyncSession_NoNewEntries(t *testing.T) {
281 t.Parallel()
283 dir := t.TempDir()
284 path := filepath.Join(dir, "session.jsonl")
285 require.NoError(t, os.WriteFile(path, []byte{}, 0o644))
287 ios, _, stdout, _ := cmdtest.TestIOStreams()
288 opts := &options{io: ios}
290 err := syncSession(t.Context(), target{}, "test-session", claudeTranscript{path: path}, opts)
291 require.NoError(t, err)
292 assert.Contains(t, stdout.String(), "No new entries to sync")
295func TestSyncSession_CursorNotAdvancedOnSessionFailure(t *testing.T) {
296 dir := t.TempDir()
297 t.Setenv("HOME", dir)
298 t.Setenv("GLAB_CONFIG_DIR", dir)
299 path := filepath.Join(dir, "session.jsonl")
301 // Write a transcript with a tool call
302 entry := map[string]any{
303 "type": "assistant",
304 "sessionId": "sess-test",
305 "timestamp": time.Now().Format(time.RFC3339),
306 "message": map[string]any{
307 "content": []map[string]any{
308 {"type": "tool_use", "id": "toolu_abc", "name": "Bash"},
309 },
310 },
311 }
312 data, _ := json.Marshal(entry)
313 require.NoError(t, os.WriteFile(path, append(data, '\n'), 0o644))
315 // nil client will cause ensureSession to fail
316 ios, _, _, _ := cmdtest.TestIOStreams()
317 opts := &options{io: ios, silent: true}
319 _ = syncSession(t.Context(), target{}, "sess-test", claudeTranscript{path: path}, opts)
321 // Cursor should NOT have advanced since session creation failed
322 cursor, err := syncstate.ReadPosition("sess-test")
323 require.NoError(t, err)
324 assert.Equal(t, int64(0), cursor, "cursor should not advance when session creation fails")
327func TestRunSync_RepoOverrideReachesResolveProject(t *testing.T) {
328 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
329 t.Setenv("CLAUDE_CODE_SESSION_ID", "")
330 t.Setenv("OPENCODE_SESSION_ID", "")
332 ctrl := gomock.NewController(t)
333 tc := gitlabtesting.NewTestClientWithCtrl(ctrl, gitlab.WithBaseURL("https://gitlab.example.com"))
334 tc.MockProjects.EXPECT().
335 GetProject(gomock.Any(), gomock.Any(), gomock.Any()).
336 Return(nil, nil, errors.New("project my-group/my-project not found"))
338 exec := cmdtest.SetupCmdForTest(
339 t,
340 NewCmd,
341 false,
342 cmdtest.WithApiClient(cmdtest.NewTestAuthSourceApiClient(
343 t, nil, gitlab.AccessTokenAuthSource{Token: "test-token"}, "gitlab.example.com",
344 api.WithGitLabClient(tc.Client),
345 )),
346 )
348 _, err := exec("--silent -R my-group/my-project")
349 require.Error(t, err)
350 assert.Contains(t, err.Error(), "my-group/my-project")
353func TestMCPDestructiveAnnotation(t *testing.T) {
354 t.Parallel()
355 ios, _, _, _ := cmdtest.TestIOStreams()
356 f := cmdtest.NewTestFactory(ios)
357 cmd := NewCmd(f)
358 assert.Equal(t, "true", cmd.Annotations[mcpannotations.Destructive])
361func TestFindTranscriptForSession(t *testing.T) {
362 dir := t.TempDir()
363 t.Setenv("HOME", dir)
365 // Create a transcript in a project subdirectory
366 projectDir := filepath.Join(dir, ".claude", "projects", "-Users-jean-code-gaig-test")
367 require.NoError(t, os.MkdirAll(projectDir, 0o755))
368 transcriptPath := filepath.Join(projectDir, "test-session-123.jsonl")
369 require.NoError(t, os.WriteFile(transcriptPath, []byte("{}"), 0o644))
371 found, err := findTranscriptForSession("test-session-123")
372 require.NoError(t, err)
373 assert.Equal(t, transcriptPath, found)
376func TestFindTranscriptForSession_NotFound(t *testing.T) {
377 dir := t.TempDir()
378 t.Setenv("HOME", dir)
380 found, err := findTranscriptForSession("nonexistent-session")
381 require.NoError(t, err)
382 assert.Empty(t, found)
385func TestWriteReadSessionMeta(t *testing.T) {
386 dir := t.TempDir()
387 t.Setenv("GLAB_CONFIG_DIR", dir)
389 meta := sessionMeta{
390 AgentType: "claude-code",
391 PathWithNamespace: "my-group/my-project",
392 Host: "gitlab.com",
393 }
394 require.NoError(t, writeSessionMeta("test-session", meta))
396 got, err := readSessionMeta("test-session")
397 require.NoError(t, err)
398 require.NotNil(t, got)
399 assert.Equal(t, "claude-code", got.AgentType)
400 assert.Equal(t, "my-group/my-project", got.PathWithNamespace)
401 assert.Equal(t, "gitlab.com", got.Host)
404func TestReadSessionMeta_NotFound(t *testing.T) {
405 dir := t.TempDir()
406 t.Setenv("GLAB_CONFIG_DIR", dir)
408 _, err := readSessionMeta("nonexistent-session")
409 require.ErrorIs(t, err, errNoSessionMeta)
412func TestAuditEventBatches(t *testing.T) {
413 small := auditEventRequest{EventName: eventToolInvoked, Details: map[string]any{"tool_name": "Bash"}}
414 large := auditEventRequest{EventName: eventToolInvoked, Details: map[string]any{}}
415 for i := range maxElementsPerRequest {
416 large.Details[fmt.Sprintf("k%d", i)] = i
417 }
419 assert.Empty(t, auditEventBatches(nil))
421 events := slices.Repeat([]auditEventRequest{small}, 1000)
422 events[10] = large
423 batches := auditEventBatches(events)
425 total := 0
426 for _, batch := range batches {
427 total += len(batch)
428 assert.LessOrEqual(t, len(batch), maxEventsPerRequest)
429 if len(batch) == 1 && batch[0].Details["k0"] != nil {
430 continue
431 }
432 elements := auditEventsRequestElements
433 for _, event := range batch {
434 elements += auditEventElements(event)
435 }
436 assert.LessOrEqual(t, elements, maxElementsPerRequest)
437 }
438 assert.Equal(t, len(events), total)
439 assert.Contains(t, batches, []auditEventRequest{large}, "an event over the budget is posted on its own")
442func TestAuditEventBatchesBytes(t *testing.T) {
443 // GitLab accepts up to 32 KB of details per event, and the element budget
444 // alone would put about 400 of these in one request.
445 event := auditEventRequest{
446 EventName: eventToolInvoked,
447 Details: map[string]any{"content": strings.Repeat("a", 30*1024)},
448 }
449 events := slices.Repeat([]auditEventRequest{event}, 300)
451 batches := auditEventBatches(events)
453 require.Len(t, batches, 3, "about 130 of these fit in the byte budget")
454 total := 0
455 for _, batch := range batches {
456 total += len(batch)
457 body := auditEventsRequest{SessionID: math.MaxInt, Events: batch}
458 assert.LessOrEqual(t, encodedLen(body), maxBytesPerRequest)
459 }
460 assert.Equal(t, len(events), total)
463func TestRateLimitWait(t *testing.T) {
464 rateLimited := func(retryAfter string) error {
465 header := http.Header{}
466 if retryAfter != "" {
467 header.Set("Retry-After", retryAfter)
468 }
469 return &gitlab.ErrorResponse{StatusCode: http.StatusTooManyRequests, Response: &http.Response{Header: header}}
470 }
471 tests := []struct {
472 name string
473 err error
474 wantWait time.Duration
475 wantLimited bool
476 }{
477 {"no error", nil, 0, false},
478 {"other status", &gitlab.ErrorResponse{StatusCode: http.StatusBadRequest}, 0, false},
479 {"retry after", rateLimited("30"), 30 * time.Second, true},
480 {"no retry after", rateLimited(""), time.Minute, true},
481 {"zero retry after", rateLimited("0"), 0, true},
482 {"date retry after", rateLimited("Wed, 21 Oct 2026 07:28:00 GMT"), time.Minute, true},
483 {"long retry after", rateLimited("3600"), maxRateLimitWait, true},
484 {"no response", &gitlab.ErrorResponse{StatusCode: http.StatusTooManyRequests}, time.Minute, true},
485 }
486 for _, tt := range tests {
487 t.Run(tt.name, func(t *testing.T) {
488 wait, limited := rateLimitWait(tt.err)
489 assert.Equal(t, tt.wantLimited, limited)
490 assert.Equal(t, tt.wantWait, wait)
491 })
492 }
495func TestRecordSessionMeta_WithoutGitLabRemote(t *testing.T) {
496 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
497 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }}
499 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/transcripts/sess-1.jsonl"))
501 meta, err := readSessionMeta("sess-1")
502 require.NoError(t, err)
503 assert.Equal(t, sessionMeta{AgentType: "claude-code", Transcript: "/transcripts/sess-1.jsonl"}, *meta)
506func TestRecordSessionMeta_WithoutGitLabRemoteKeepsProject(t *testing.T) {
507 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
508 recorded := sessionMeta{AgentType: "claude-code", PathWithNamespace: "my-group/my-project", Host: "gitlab.com", Transcript: "/t.jsonl"}
509 require.NoError(t, writeSessionMeta("sess-1", recorded))
510 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }}
512 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl"))
514 meta, err := readSessionMeta("sess-1")
515 require.NoError(t, err)
516 assert.Equal(t, recorded, *meta)
519func TestRecordSessionMeta_RemoteReplacesSessionWithoutProject(t *testing.T) {
520 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
521 t.Setenv("HOME", t.TempDir())
522 path := filepath.Join(t.TempDir(), "sess-1.jsonl")
523 content := claudeTranscriptLines(t, "sess-1", "toolu_1")
524 require.NoError(t, os.WriteFile(path, content, 0o644))
525 require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: path}))
526 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) {
527 return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil
528 }}
530 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", path))
532 meta, err := readSessionMeta("sess-1")
533 require.NoError(t, err)
534 assert.Equal(t, sessionMeta{AgentType: "claude-code", PathWithNamespace: "my-group/my-project", Host: "gitlab.com", Transcript: path}, *meta)
535 assertCursorAt(t, "sess-1", int64(len(content)))
538func TestRecordSessionMeta_KeepsSessionWithoutProjectWhenSkipFails(t *testing.T) {
539 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
540 t.Setenv("HOME", t.TempDir())
541 missing := filepath.Join(t.TempDir(), "gone.jsonl")
542 require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: missing}))
543 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) {
544 return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil
545 }}
547 require.ErrorIs(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", missing),
548 errEarlierActivityNotSkipped, "the hook stops rather than syncing from the start")
550 meta, err := readSessionMeta("sess-1")
551 require.NoError(t, err)
552 assert.Empty(t, meta.PathWithNamespace, "the next hook call retries the skip")
553 assertCursorAt(t, "sess-1", 0)
556func TestRecordSessionMeta_NewSessionWithRemoteUploadsFromTheStart(t *testing.T) {
557 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
558 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) {
559 return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil
560 }}
562 path := filepath.Join(t.TempDir(), "sess-1.jsonl")
563 require.NoError(t, os.WriteFile(path, claudeTranscriptLines(t, "sess-1", "toolu_1"), 0o644))
565 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", path))
567 assertCursorAt(t, "sess-1", 0)
570func TestSkipToEnd(t *testing.T) {
571 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
572 path := filepath.Join(t.TempDir(), "sess-1.jsonl")
573 content := claudeTranscriptLines(t, "sess-1", "toolu_1", "toolu_2")
574 require.NoError(t, os.WriteFile(path, append(content, []byte(`{"type":"assistant"`)...), 0o644))
575 require.NoError(t, syncstate.WritePosition("sess-1", 10))
577 require.NoError(t, skipToEnd(t.Context(), "sess-1", claudeTranscript{path: path}))
579 assertCursorAt(t, "sess-1", int64(len(content)))
582func TestRecordSessionMeta_WithoutGitLabRemoteKeepsUnreadableRecord(t *testing.T) {
583 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
584 path, err := metaPath("sess-1")
585 require.NoError(t, err)
586 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
587 require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600))
588 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) { return nil, errors.New("no git remote") }}
590 require.Error(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl"))
592 data, err := os.ReadFile(path)
593 require.NoError(t, err)
594 assert.Equal(t, "not json", string(data), "a record that may hold a project is not replaced")
597func TestRecordSessionMeta_RemoteReplacesUnreadableRecord(t *testing.T) {
598 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
599 path, err := metaPath("sess-1")
600 require.NoError(t, err)
601 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
602 require.NoError(t, os.WriteFile(path, []byte("not json"), 0o600))
603 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) {
604 return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil
605 }}
607 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", "/t.jsonl"))
609 meta, err := readSessionMeta("sess-1")
610 require.NoError(t, err)
611 assert.Equal(t, "my-group/my-project", meta.PathWithNamespace)
614func TestRecordSessionMeta_SkipsUsingTheRecordedTranscript(t *testing.T) {
615 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
616 t.Setenv("HOME", t.TempDir())
617 path := filepath.Join(t.TempDir(), "sess-1.jsonl")
618 content := claudeTranscriptLines(t, "sess-1", "toolu_1")
619 require.NoError(t, os.WriteFile(path, content, 0o644))
620 require.NoError(t, writeSessionMeta("sess-1", sessionMeta{AgentType: "claude-code", Transcript: path}))
621 opts := &options{agentType: "claude-code", baseRepo: func() (glrepo.Interface, error) {
622 return glrepo.NewWithHost("my-group", "my-project", "gitlab.com"), nil
623 }}
625 // The hook ran from another folder after the agent changed directory.
626 hookPath := filepath.Join(t.TempDir(), "elsewhere", "sess-1.jsonl")
627 require.NoError(t, recordSessionMeta(t.Context(), opts, claudeCode{}, "sess-1", hookPath))
629 assertCursorAt(t, "sess-1", int64(len(content)))
632func TestParseTranscript_Dirs(t *testing.T) {
633 t.Parallel()
634 path := filepath.Join(t.TempDir(), "session.jsonl")
635 line := func(entry map[string]any) string {
636 data, err := json.Marshal(entry)
637 require.NoError(t, err)
638 return string(data) + "\n"
639 }
640 content := line(map[string]any{
641 "type": "user", "promptId": "p1", "uuid": "u1", "cwd": "/work/a/", "timestamp": "2026-10-09T01:00:00Z",
642 "message": map[string]any{"content": "clone b"},
643 }) + line(map[string]any{
644 "type": "assistant", "cwd": "/work/a", "timestamp": "2026-10-09T01:00:01Z",
645 "message": map[string]any{"id": "msg_1", "content": []any{map[string]any{"type": "tool_use", "id": "toolu_1", "name": "Bash"}}},
646 }) + line(map[string]any{
647 "type": "assistant", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:01Z",
648 "message": map[string]any{"id": "msg_1", "content": []any{}},
649 }) + line(map[string]any{
650 "type": "user", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:02Z",
651 "message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": "toolu_1"}}},
652 }) + line(map[string]any{
653 "type": "user", "promptId": "p2", "uuid": "u2", "cwd": "/work/b", "timestamp": "2026-10-09T01:00:03Z",
654 "message": map[string]any{"content": "now in b"},
655 })
656 require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
658 data, _, err := parseTranscript(path, 0)
659 require.NoError(t, err)
661 require.Len(t, data.Prompts, 2)
662 assert.Equal(t, "/work/a", data.Prompts[0].CWD, "folders are cleaned, so a trailing slash makes no difference")
663 assert.Equal(t, "/work/b", data.Prompts[1].CWD, "Claude Code records the folder after a cd")
664 require.Len(t, data.ToolCalls, 1)
665 assert.Equal(t, "/work/a", data.ToolCalls[0].CWD)
666 require.Len(t, data.Responses, 1)
667 assert.Equal(t, "/work/a", data.Responses[0].CWD, "a streamed response keeps its first entry's folder")
668 require.Len(t, data.ToolResults, 1)
669 assert.Equal(t, "/work/a", data.ToolResults[0].CWD, "a result runs where its call did")
672func TestRunSync_SkipsASessionWhoseHooksWereRemoved(t *testing.T) {
673 for name, args := range map[string]string{
674 "from the hook": "-R my-group/my-project --silent",
675 "run by hand": "-R my-group/my-project",
676 } {
677 t.Run(name, func(t *testing.T) {
678 env := newSyncAllEnv(t, false)
679 t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1")
680 cwd, err := currentCWD()
681 require.NoError(t, err)
682 path, err := transcriptPath("sess-1", cwd)
683 require.NoError(t, err)
684 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
685 require.NoError(t, os.WriteFile(path, claudeTranscriptLines(t, "sess-1", "toolu_1"), 0o644))
687 out, err := env.exec(args)
688 require.NoError(t, err)
690 assert.Empty(t, env.fake.sessionRequests, "an open session must not upload after uninstall")
691 assert.Empty(t, env.fake.events)
692 _, err = readSessionMeta("sess-1")
693 require.ErrorIs(t, err, errNoSessionMeta, "uninstall removed the records, so they must not come back")
694 if strings.Contains(args, "--silent") {
695 assert.Empty(t, out.String())
696 } else {
697 assert.Contains(t, out.String(), "Not syncing the claude-code session: the glab Stop hook is not installed")
698 }
699 })
700 }
703func TestRunSync_FailsWhenItCannotTellWhetherSyncingIsPaused(t *testing.T) {
704 env := newSyncAllEnv(t, false)
705 t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1")
706 settings, err := claudehooks.SettingsPath()
707 require.NoError(t, err)
708 require.NoError(t, os.MkdirAll(filepath.Dir(settings), 0o755))
709 require.NoError(t, os.WriteFile(settings, []byte("{not json"), 0o600))
711 _, err = env.exec("-R my-group/my-project --silent")
713 require.ErrorContains(t, err, "could not check whether syncing is paused")
714 assert.Empty(t, env.fake.sessionRequests)
715 _, err = readSessionMeta("sess-1")
716 require.ErrorIs(t, err, errNoSessionMeta)
719func TestGoalFromText_RedactsBeforeShortening(t *testing.T) {
720 t.Parallel()
722 token := fake("glpat-", 20)
723 goal := goalFromText(strings.Repeat("x", 250) + " " + token)
725 assert.NotContains(t, goal, "glpat-", "a token cut in half is still a leak")
728func TestRunSync_RedactsSecretsBeforeUpload(t *testing.T) {
729 env := newSyncAllEnv(t, true)
730 t.Setenv("CLAUDE_CODE_SESSION_ID", "sess-1")
732 token := fake("glpat-", 20)
733 cwd, err := currentCWD()
734 require.NoError(t, err)
735 path, err := transcriptPath("sess-1", cwd)
736 require.NoError(t, err)
737 lines := jsonLines(t,
738 map[string]any{
739 "type": "user", "sessionId": "sess-1", "uuid": "u-1", "promptId": "p-1",
740 "timestamp": time.Now().Format(time.RFC3339),
741 "message": map[string]any{"role": "user", "content": "use " + token + " to call the API"},
742 },
743 map[string]any{
744 "type": "assistant", "sessionId": "sess-1", "timestamp": time.Now().Format(time.RFC3339),
745 "message": map[string]any{"content": []map[string]any{{
746 "type": "tool_use", "id": "toolu_1", "name": "Bash",
747 "input": map[string]any{"command": `curl -H "PRIVATE-TOKEN: ` + token + `" https://gitlab.com/api/v4/user`},
748 }}},
749 },
750 )
751 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
752 require.NoError(t, os.WriteFile(path, []byte(lines), 0o644))
754 _, err = env.exec("-R my-group/my-project --silent")
755 require.NoError(t, err)
757 require.Len(t, env.fake.sessionRequests, 1)
758 assert.Equal(t, "use [REDACTED:gitlab_token] to call the API", env.fake.sessionRequests[0].Goal)
759 uploaded, err := json.Marshal(env.fake.events)
760 require.NoError(t, err)
761 assert.NotContains(t, string(uploaded), token)
762 assert.Contains(t, string(uploaded), "use [REDACTED:gitlab_token] to call the API")
763 assert.Contains(t, string(uploaded), `PRIVATE-TOKEN: [REDACTED:gitlab_token]`)
Diagnostics9 git calls · 279 ms
CallStatusSizeTime0279 ms
discover200185 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB · hit2 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=2
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchtree:02001.8 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1857
git.pkt.payload.max=1830
git.sideband.band1.bytes=1830
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1830
git.pack.trailer=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200261 B · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=261
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=3bb9946301aa8c0dc8d202b83bc9f84bf0400f6d
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=261
git.pkt.payload.max=234
git.sideband.band1.bytes=234
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=234
git.pack.trailer=e0a52f164f79506da6b0dcc275ed62911f5383bf
Open pack map
fetchtree:0200139 B · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=139
git.response.cache=HIT
git.response.duration_ms=1
git.fetch.filter=tree:0
git.fetch.wants=f91da6c620e9fe39086f689d1ae91b87356cda50
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=139
git.pkt.payload.max=112
git.sideband.band1.bytes=112
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=112
git.pack.trailer=a35549813b2a01d473947912b5773e993ce7c2e2
Open pack map
fetchtree:0200638 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=638
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=02089b627a9895becfd23127f25e46df629ce9b2
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=638
git.pkt.payload.max=611
git.sideband.band1.bytes=611
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=611
git.pack.trailer=f2a6246e346c2fa34e54ecb04cb1dd1c524f65bc
Open pack map
fetch2006.0 KiB267 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=267
git.response.bytes=6155
git.response.cache=MISS
git.response.duration_ms=267
git.fetch.wants=714c3d78d053d87e0f254b45de61b1a5baa0f90e
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=6155
git.pkt.payload.max=6128
git.sideband.band1.bytes=6128
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e2d13e8b7bcf3a
Request
28b48cf0…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format