GitLabgitlab-org

cli

main
ply8 git calls323 ms108 KiB6 cachedprotocol v2
1726 lines70 KiBRaw
1//go:build !integration
3package setup
5import (
6 "context"
7 "encoding/json"
8 "errors"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "testing"
16 "time"
18 "github.com/stretchr/testify/assert"
19 "github.com/stretchr/testify/require"
20 "go.uber.org/mock/gomock"
22 "gitlab.com/gitlab-org/cli/internal/api"
23 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/claudehooks"
24 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/fallbacksync"
25 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/gaig"
26 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/opencodeplugin"
27 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/syncstate"
28 "gitlab.com/gitlab-org/cli/internal/iostreams"
29 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
30 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
33func TestNewCmd(t *testing.T) {
34 t.Parallel()
35 ios, _, _, _ := cmdtest.TestIOStreams()
36 f := cmdtest.NewTestFactory(ios)
37 cmd := NewCmd(f)
39 assert.Equal(t, "setup", cmd.Name())
40 assert.NotNil(t, cmd.Flags().Lookup("yes"))
41 assert.NotNil(t, cmd.Flags().Lookup("no-fallback-sync"))
42 assert.NotNil(t, cmd.Flags().Lookup("uninstall"))
45func TestInstallClaudeHooks(t *testing.T) {
46 t.Run("creates settings file with hooks when none exists", func(t *testing.T) {
47 dir := t.TempDir()
48 path := filepath.Join(dir, ".claude", "settings.json")
50 ios, _, _, _ := cmdtest.TestIOStreams()
51 opts := &options{io: ios, settingsPathOverride: path}
53 err := installClaudeHooks(opts)
54 require.NoError(t, err)
56 data, err := os.ReadFile(path)
57 require.NoError(t, err)
59 var raw map[string]json.RawMessage
60 require.NoError(t, json.Unmarshal(data, &raw))
61 hooks, err := claudehooks.HooksFromRaw(raw)
62 require.NoError(t, err)
64 assert.Len(t, hooks["Stop"], 1)
65 assert.Len(t, hooks["SessionEnd"], 1)
66 assert.Equal(t, claudehooks.StopHookCommand, hooks["Stop"][0].Hooks[0].Command)
67 assert.Equal(t, claudehooks.SessionEndHookCommand, hooks["SessionEnd"][0].Hooks[0].Command)
68 })
70 t.Run("is idempotent -- does not duplicate hooks", func(t *testing.T) {
71 dir := t.TempDir()
72 path := filepath.Join(dir, ".claude", "settings.json")
74 ios, _, _, _ := cmdtest.TestIOStreams()
75 opts := &options{io: ios, settingsPathOverride: path}
77 require.NoError(t, installClaudeHooks(opts))
78 require.NoError(t, installClaudeHooks(opts))
79 require.NoError(t, installClaudeHooks(opts))
81 data, err := os.ReadFile(path)
82 require.NoError(t, err)
84 var raw map[string]json.RawMessage
85 require.NoError(t, json.Unmarshal(data, &raw))
86 hooks, err := claudehooks.HooksFromRaw(raw)
87 require.NoError(t, err)
89 assert.Len(t, hooks["Stop"], 1, "Stop hook should not be duplicated")
90 assert.Len(t, hooks["SessionEnd"], 1, "SessionEnd hook should not be duplicated")
91 })
93 t.Run("preserves existing hooks in the file", func(t *testing.T) {
94 dir := t.TempDir()
95 path := filepath.Join(dir, ".claude", "settings.json")
97 // Write existing settings with a different hook
98 existingHooks := map[string][]claudehooks.HookGroup{
99 "PreToolUse": {
100 {Hooks: []claudehooks.HookEntry{{Type: "command", Command: "echo pre-tool"}}},
101 },
102 }
103 hooksJSON, err := json.Marshal(existingHooks)
104 require.NoError(t, err)
106 existing := map[string]json.RawMessage{"hooks": hooksJSON}
108 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
109 require.NoError(t, claudehooks.WriteSettings(path, existing))
111 ios, _, _, _ := cmdtest.TestIOStreams()
112 opts := &options{io: ios, settingsPathOverride: path}
114 require.NoError(t, installClaudeHooks(opts))
116 data2, err2 := os.ReadFile(path)
117 require.NoError(t, err2)
119 var raw2 map[string]json.RawMessage
120 require.NoError(t, json.Unmarshal(data2, &raw2))
122 hooks2, err := claudehooks.HooksFromRaw(raw2)
123 require.NoError(t, err)
125 assert.Len(t, hooks2["PreToolUse"], 1, "existing PreToolUse hook should be preserved")
126 assert.Len(t, hooks2["Stop"], 1, "Stop hook should be added")
127 assert.Len(t, hooks2["SessionEnd"], 1, "SessionEnd hook should be added")
128 })
131func TestRunSetup_YesSkipsPrompt(t *testing.T) {
132 dir := t.TempDir()
133 t.Setenv("HOME", dir)
134 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
135 path := filepath.Join(dir, ".claude", "settings.json")
137 ios, _, stdout, _ := cmdtest.TestIOStreams()
138 opts := &options{
139 io: ios,
140 executor: expectLinuxInstall(t, "/usr/local/bin/glab"),
141 buildInfo: testBuild,
142 goos: "linux",
143 yes: true,
144 settingsPathOverride: path,
145 }
147 err := runSetup(t.Context(), opts)
148 require.NoError(t, err)
150 _, err = os.Stat(path)
151 require.NoError(t, err, "settings file should have been created")
152 assert.Contains(t, stdout.String(), "Fallback periodic sync installed: a systemd user timer")
153 assert.FileExists(t, filepath.Join(dir, ".config", "systemd", "user", "glab-govern-audit-sync.timer"))
155 service, err := os.ReadFile(filepath.Join(dir, ".config", "systemd", "user", "glab-govern-audit-sync.service"))
156 require.NoError(t, err)
157 assert.Contains(t, string(service), `Environment="GLAB_CONFIG_DIR=`+filepath.Join(dir, "glab")+`"`, "the job uses the same config directory as setup")
160// testBuild is the build the tests pretend is running setup.
161var testBuild = api.BuildInfo{Version: "v1.121.0", Commit: "abc1234"}
163// expectGlabOnPath makes glabPath the glab on PATH, reporting versionOutput
164// from `glab version`.
165func expectGlabOnPath(mExec *cmdtest.MockExecutor, glabPath, versionOutput string) {
166 mExec.EXPECT().LookPath("glab").Return(glabPath, nil)
167 mExec.EXPECT().
168 ExecWithIO(gomock.Any(), glabPath, []string{"version"}, nil, nil, gomock.Any(), gomock.Any()).
169 DoAndReturn(func(_ context.Context, _ string, _, _ []string, _ io.Reader, stdout, _ io.Writer) error {
170 _, err := io.WriteString(stdout, versionOutput)
171 return err
172 })
175// expectLinuxInstall returns an executor that expects the fallback periodic
176// sync to be installed with systemd, running glabPath.
177func expectLinuxInstall(t *testing.T, glabPath string) *cmdtest.MockExecutor {
178 t.Helper()
179 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
180 expectGlabOnPath(mExec, glabPath, "glab 1.121.0 (abc1234)\n")
181 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "daemon-reload"}, nil).Return(nil, nil)
182 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "enable", "--now", "glab-govern-audit-sync.timer"}, nil).Return(nil, nil)
183 return mExec
186func TestRunSetup_FallbackSyncFailureIsAWarning(t *testing.T) {
187 dir := t.TempDir()
188 t.Setenv("HOME", dir)
190 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
191 expectGlabOnPath(mExec, "/usr/bin/glab", "glab 1.121.0 (abc1234)\n")
192 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", gomock.Any(), nil).Return([]byte("Failed to connect to bus"), errors.New("exit status 1"))
194 ios, _, stdout, stderr := cmdtest.TestIOStreams()
195 opts := &options{
196 io: ios,
197 executor: mExec,
198 buildInfo: testBuild,
199 goos: "linux",
200 yes: true,
201 settingsPathOverride: filepath.Join(dir, ".claude", "settings.json"),
202 }
204 require.NoError(t, runSetup(t.Context(), opts))
205 assert.Contains(t, stderr.String(), "warning: could not install fallback periodic sync")
206 assert.Contains(t, stderr.String(), "Any previous fallback periodic sync job has been removed.")
207 assert.Contains(t, stdout.String(), "Setup complete")
210func TestSetup_NoFallbackSync(t *testing.T) {
211 dir := t.TempDir()
212 t.Setenv("HOME", dir)
214 // The executor has no expectations, so any attempt to install the job fails the test.
215 exec := cmdtest.SetupCmdForTest(t, NewCmd, false,
216 cmdtest.WithExecutor(cmdtest.NewMockExecutor(gomock.NewController(t))),
217 )
219 out, err := exec("--yes --no-fallback-sync")
220 require.NoError(t, err)
222 assert.FileExists(t, filepath.Join(dir, ".claude", "settings.json"))
223 assert.NotContains(t, out.String(), "Fallback periodic sync")
224 assert.Contains(t, out.String(), "Hooks installed")
227func TestSetup_Agents(t *testing.T) {
228 dir := t.TempDir()
229 t.Setenv("HOME", dir)
230 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
232 run := func(t *testing.T, args string) (string, error) {
233 t.Helper()
234 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
235 mExec.EXPECT().LookPath("glab").Return("", errors.New("not found")).AnyTimes()
236 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), gomock.Any(), gomock.Any(), nil).Return(nil, nil).AnyTimes()
237 exec := cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithExecutor(mExec))
238 out, err := exec("--yes " + args)
239 if out == nil {
240 return "", err
241 }
242 return out.String(), err
243 }
245 out, err := run(t, "--agents claude-code,codex,cursor")
246 require.NoError(t, err)
247 assert.Contains(t, out, "Syncing sessions from: codex, cursor.")
248 agents, err := fallbacksync.DiscoveredAgents()
249 require.NoError(t, err)
250 assert.Equal(t, []string{"codex", "cursor"}, agents)
251 hookAgents, _, err := fallbacksync.RecordedHookAgents()
252 require.NoError(t, err)
253 assert.Equal(t, []string{"claude-code"}, hookAgents)
255 _, err = run(t, "")
256 require.NoError(t, err)
257 agents, err = fallbacksync.DiscoveredAgents()
258 require.NoError(t, err)
259 assert.Equal(t, []string{"codex", "cursor"}, agents, "setup without --agents keeps the earlier choice")
261 _, err = run(t, "--agents opencode")
262 require.NoError(t, err)
263 agents, err = fallbacksync.DiscoveredAgents()
264 require.NoError(t, err)
265 assert.Equal(t, []string{"codex", "cursor"}, agents, "--agents adds to the earlier choice")
266 hookAgents, _, err = fallbacksync.RecordedHookAgents()
267 require.NoError(t, err)
268 assert.Equal(t, []string{"claude-code", "opencode"}, hookAgents)
271func TestSetup_AgentsValidation(t *testing.T) {
272 t.Parallel()
274 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
276 _, err := exec("--yes --agents claude")
277 require.Error(t, err)
278 assert.Contains(t, err.Error(), `unsupported agent "claude" in --agents; use claude-code, opencode, codex, cursor`)
280 _, err = exec(`--yes --agents ""`)
281 require.Error(t, err)
282 assert.Contains(t, err.Error(), "--agents needs at least one agent; to remove everything setup installed, use --uninstall")
284 _, err = exec("--yes --agents opencode,codex --no-fallback-sync")
285 require.Error(t, err)
286 assert.Contains(t, err.Error(), "codex sessions are only synced by the fallback periodic sync")
288 _, err = exec("--yes --agents codex --uninstall")
289 require.Error(t, err)
290 assert.Contains(t, err.Error(), "none of the others can be")
293func TestSetup_UninstallConflictsWithNoFallbackSync(t *testing.T) {
294 t.Parallel()
296 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
297 _, err := exec("--uninstall --no-fallback-sync")
298 require.Error(t, err)
299 assert.Contains(t, err.Error(), "none of the others can be")
302func TestRunUninstall(t *testing.T) {
303 dir := t.TempDir()
304 t.Setenv("HOME", dir)
305 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
306 path := filepath.Join(dir, ".claude", "settings.json")
308 ios, _, stdout, _ := cmdtest.TestIOStreams()
309 opts := &options{
310 io: ios,
311 executor: expectLinuxInstall(t, "/usr/bin/glab"),
312 buildInfo: testBuild,
313 goos: "linux",
314 yes: true,
315 settingsPathOverride: path,
316 }
317 require.NoError(t, runSetup(t.Context(), opts))
319 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
320 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "disable", "--now", "glab-govern-audit-sync.timer"}, nil).Return(nil, nil)
321 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "daemon-reload"}, nil).Return(nil, nil)
322 opts.executor = mExec
323 writeSessionState(t)
324 setups, err := fallbacksync.ReadAgentSetups()
325 require.NoError(t, err)
326 require.Contains(t, setups, "claude-code")
328 require.NoError(t, runUninstall(t.Context(), opts))
330 assert.NoFileExists(t, filepath.Join(dir, ".config", "systemd", "user", "glab-govern-audit-sync.timer"))
331 assert.Contains(t, stdout.String(), "Fallback periodic sync removed")
332 assert.NoDirExists(t, gaig.StateDir())
333 setups, err = fallbacksync.ReadAgentSetups()
334 require.NoError(t, err)
335 assert.Empty(t, setups, "the next setup uploads from when it runs")
336 assert.Contains(t, stdout.String(), "Local records of your agent sessions removed")
338 raw, err := claudehooks.LoadRawSettings(path)
339 require.NoError(t, err)
340 hooks, err := claudehooks.HooksFromRaw(raw)
341 require.NoError(t, err)
342 assert.False(t, claudehooks.HookPresent(hooks, "Stop", claudehooks.StopHookCommand))
343 assert.False(t, claudehooks.HookPresent(hooks, "SessionEnd", claudehooks.SessionEndHookCommand))
344 assert.Contains(t, stdout.String(), "Hooks removed")
347func TestRunUninstall_HooksOnly(t *testing.T) {
348 dir := t.TempDir()
349 t.Setenv("HOME", dir)
350 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
351 path := filepath.Join(dir, ".claude", "settings.json")
352 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
353 require.NoError(t, os.WriteFile(path, []byte(`{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo user-hook"}]}]}}`), 0o644))
355 ios, _, stdout, _ := cmdtest.TestIOStreams()
356 opts := &options{io: ios, yes: true, noFallbackSync: true, settingsPathOverride: path}
357 require.NoError(t, runSetup(t.Context(), opts))
359 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
360 mExec.EXPECT().
361 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
362 Return(nil, &exec.ExitError{})
363 opts.executor = mExec
364 opts.goos = "linux"
366 require.NoError(t, runUninstall(t.Context(), opts), "hooks without a job are still removed")
367 assert.Contains(t, stdout.String(), "Hooks removed")
368 assert.NotContains(t, stdout.String(), "Fallback periodic sync removed")
370 raw, err := claudehooks.LoadRawSettings(path)
371 require.NoError(t, err)
372 hooks, err := claudehooks.HooksFromRaw(raw)
373 require.NoError(t, err)
374 assert.False(t, claudehooks.HookPresent(hooks, "Stop", claudehooks.StopHookCommand))
375 assert.False(t, claudehooks.HookPresent(hooks, "SessionEnd", claudehooks.SessionEndHookCommand))
376 assert.True(t, claudehooks.HookPresent(hooks, "Stop", "echo user-hook"))
377 assert.JSONEq(t, `"opus"`, string(raw["model"]))
380func TestRunSetup_ReplacesHooksFromBeforeTheRename(t *testing.T) {
381 dir := t.TempDir()
382 t.Setenv("HOME", dir)
383 path := filepath.Join(dir, ".claude", "settings.json")
384 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
385 require.NoError(t, os.WriteFile(path, []byte(`{"hooks":{
386 "Stop":[{"hooks":[{"type":"command","command":"glab govern audit sync --silent >/dev/null 2>&1 &"}]}],
387 "SessionEnd":[{"hooks":[{"type":"command","command":"glab govern audit sync --silent --complete >/dev/null 2>&1 &"}]}]
388 }}`), 0o644))
390 ios, _, _, _ := cmdtest.TestIOStreams()
391 opts := &options{io: ios, yes: true, noFallbackSync: true, settingsPathOverride: path}
392 require.NoError(t, runSetup(t.Context(), opts))
394 raw, err := claudehooks.LoadRawSettings(path)
395 require.NoError(t, err)
396 hooks, err := claudehooks.HooksFromRaw(raw)
397 require.NoError(t, err)
398 assert.False(t, claudehooks.LegacyHookPresent(hooks))
399 require.Len(t, hooks["Stop"], 1, "sessions must not be synced twice")
400 require.Len(t, hooks["SessionEnd"], 1)
401 assert.Equal(t, claudehooks.StopHookCommand, hooks["Stop"][0].Hooks[0].Command)
402 assert.Equal(t, claudehooks.SessionEndHookCommand, hooks["SessionEnd"][0].Hooks[0].Command)
405func TestRunSetup_KeepsOneHookWhenBothFormsArePresent(t *testing.T) {
406 dir := t.TempDir()
407 t.Setenv("HOME", dir)
408 path := filepath.Join(dir, ".claude", "settings.json")
409 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
410 require.NoError(t, os.WriteFile(path, []byte(`{"hooks":{
411 "Stop":[
412 {"hooks":[{"type":"command","command":"glab minder audit sync --silent >/dev/null 2>&1 &"}]},
413 {"hooks":[{"type":"command","command":"glab govern audit sync --silent >/dev/null 2>&1 &"}]}
414 ]
415 }}`), 0o644))
417 ios, _, _, _ := cmdtest.TestIOStreams()
418 opts := &options{io: ios, yes: true, noFallbackSync: true, settingsPathOverride: path}
419 require.NoError(t, runSetup(t.Context(), opts))
421 raw, err := claudehooks.LoadRawSettings(path)
422 require.NoError(t, err)
423 hooks, err := claudehooks.HooksFromRaw(raw)
424 require.NoError(t, err)
425 require.Len(t, hooks["Stop"], 1, "sessions must not be synced twice")
426 assert.Equal(t, claudehooks.StopHookCommand, hooks["Stop"][0].Hooks[0].Command)
427 require.Len(t, hooks["SessionEnd"], 1)
430func TestRunUninstall_RemovesHooksFromBeforeTheRename(t *testing.T) {
431 dir := t.TempDir()
432 t.Setenv("HOME", dir)
433 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
434 path := filepath.Join(dir, ".claude", "settings.json")
435 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
436 require.NoError(t, os.WriteFile(path, []byte(`{"model":"opus","hooks":{
437 "Stop":[{"hooks":[{"type":"command","command":"glab govern audit sync --silent >/dev/null 2>&1 &"}]}],
438 "SessionEnd":[{"hooks":[{"type":"command","command":"glab govern audit sync --silent --complete >/dev/null 2>&1 &"}]}]
439 }}`), 0o644))
441 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
442 mExec.EXPECT().
443 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
444 Return(nil, &exec.ExitError{})
445 ios, _, stdout, _ := cmdtest.TestIOStreams()
446 opts := &options{io: ios, yes: true, executor: mExec, goos: "linux", settingsPathOverride: path}
448 require.NoError(t, runUninstall(t.Context(), opts))
449 assert.Contains(t, stdout.String(), "Hooks removed")
451 raw, err := claudehooks.LoadRawSettings(path)
452 require.NoError(t, err)
453 assert.NotContains(t, raw, "hooks")
454 assert.JSONEq(t, `"opus"`, string(raw["model"]))
457func TestRunUninstall_RemovesEmptiedHooksKey(t *testing.T) {
458 dir := t.TempDir()
459 t.Setenv("HOME", dir)
460 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
461 path := filepath.Join(dir, ".claude", "settings.json")
463 ios, _, _, _ := cmdtest.TestIOStreams()
464 opts := &options{io: ios, yes: true, noFallbackSync: true, settingsPathOverride: path}
465 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
466 require.NoError(t, os.WriteFile(path, []byte(`{"model":"opus"}`), 0o644))
467 require.NoError(t, runSetup(t.Context(), opts))
469 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
470 mExec.EXPECT().
471 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
472 Return(nil, &exec.ExitError{})
473 opts.executor = mExec
474 opts.goos = "linux"
476 require.NoError(t, runUninstall(t.Context(), opts))
478 raw, err := claudehooks.LoadRawSettings(path)
479 require.NoError(t, err)
480 assert.NotContains(t, raw, "hooks", "a hooks key emptied by uninstall is removed, not left as {}")
481 assert.JSONEq(t, `"opus"`, string(raw["model"]))
484func TestRunUninstall_CorruptSettings(t *testing.T) {
485 writeCorruptSettings := func(t *testing.T, dir string) string {
486 t.Helper()
487 path := filepath.Join(dir, ".claude", "settings.json")
488 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
489 require.NoError(t, os.WriteFile(path, []byte("{not json"), 0o644))
490 return path
491 }
492 expectNoJob := func(t *testing.T) *cmdtest.MockExecutor {
493 t.Helper()
494 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
495 mExec.EXPECT().
496 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
497 Return(nil, &exec.ExitError{})
498 return mExec
499 }
501 t.Run("nothing else to remove fails before prompting", func(t *testing.T) {
502 dir := t.TempDir()
503 t.Setenv("HOME", dir)
504 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
505 path := writeCorruptSettings(t, dir)
507 ios, _, _, _ := cmdtest.TestIOStreams()
508 // Without --yes and without a terminal, prompting would fail differently.
509 err := runUninstall(t.Context(), &options{io: ios, executor: expectNoJob(t), goos: "linux", settingsPathOverride: path})
510 require.Error(t, err)
511 assert.Contains(t, err.Error(), "the agent session hooks were not removed")
512 })
514 t.Run("keeps the session records while the hooks may still write them", func(t *testing.T) {
515 dir := t.TempDir()
516 t.Setenv("HOME", dir)
517 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
518 path := writeCorruptSettings(t, dir)
519 writeSessionState(t)
521 ios, _, stdout, _ := cmdtest.TestIOStreams()
522 // Without --yes and without a terminal, prompting would fail differently.
523 err := runUninstall(t.Context(), &options{io: ios, executor: expectNoJob(t), goos: "linux", settingsPathOverride: path})
524 require.Error(t, err)
525 assert.Contains(t, err.Error(), "the agent session hooks were not removed", "records that are kept don't make it prompt")
526 assert.DirExists(t, gaig.StateDir())
527 assert.NotContains(t, stdout.String(), "Local records of your agent sessions removed")
528 })
530 t.Run("the rest is removed and the error says what is left", func(t *testing.T) {
531 dir := t.TempDir()
532 t.Setenv("HOME", dir)
533 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
534 path := writeCorruptSettings(t, dir)
535 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"codex"}))
536 setups := fallbacksync.AgentSetups{"claude-code": {SetUpAt: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)}}
537 require.NoError(t, fallbacksync.SetAgentSetups(setups))
539 ios, _, stdout, stderr := cmdtest.TestIOStreams()
540 err := runUninstall(t.Context(), &options{io: ios, executor: expectNoJob(t), goos: "linux", yes: true, settingsPathOverride: path})
541 require.Error(t, err)
542 assert.Contains(t, err.Error(), "run 'glab minder setup --uninstall' again")
543 assert.Contains(t, stderr.String(), "its hooks will not be removed", "the user is warned before confirming")
544 assert.Contains(t, stdout.String(), "Stopped syncing codex sessions.")
546 agents, err := fallbacksync.DiscoveredAgents()
547 require.NoError(t, err)
548 assert.Empty(t, agents)
549 kept, err := fallbacksync.ReadAgentSetups()
550 require.NoError(t, err)
551 assert.Equal(t, setups, kept, "hooks that stay installed still upload only from when they were set up")
552 })
555func TestRunUninstall_UnreadableOpenCodePlugin(t *testing.T) {
556 setUp := func(t *testing.T) {
557 t.Helper()
558 dir := t.TempDir()
559 t.Setenv("HOME", dir)
560 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
561 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName), 0o755))
562 }
563 expectNoJob := func(t *testing.T) *cmdtest.MockExecutor {
564 t.Helper()
565 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
566 mExec.EXPECT().
567 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
568 Return(nil, &exec.ExitError{})
569 return mExec
570 }
572 t.Run("nothing else to remove fails", func(t *testing.T) {
573 setUp(t)
575 ios, _, stdout, stderr := cmdtest.TestIOStreams()
576 err := runUninstall(t.Context(), &options{io: ios, executor: expectNoJob(t), goos: "linux"})
577 require.Error(t, err)
578 assert.Contains(t, err.Error(), "the OpenCode plugin may still be installed")
579 assert.NotContains(t, stdout.String(), "Nothing to uninstall")
580 assert.Empty(t, stderr.String(), "the error says it once")
581 })
583 t.Run("the rest is removed and the error says what is left", func(t *testing.T) {
584 setUp(t)
585 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"codex"}))
587 ios, _, stdout, stderr := cmdtest.TestIOStreams()
588 err := runUninstall(t.Context(), &options{io: ios, executor: expectNoJob(t), goos: "linux", yes: true})
589 require.Error(t, err)
590 assert.Contains(t, err.Error(), "the OpenCode plugin may still be installed")
591 assert.Contains(t, stderr.String(), "so it will not be removed", "the user is warned before confirming")
592 assert.Contains(t, stdout.String(), "Stopped syncing codex sessions.")
593 })
596// writeSessionState writes the records that syncing leaves in glab's
597// configuration directory.
598func writeSessionState(t *testing.T) {
599 t.Helper()
600 for _, name := range []string{"cursors/sess-1", "cursors/sess-1.meta", "identities/42_claude-code.json", "fallback-sync-status.json"} {
601 path := filepath.Join(gaig.StateDir(), name)
602 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
603 require.NoError(t, os.WriteFile(path, []byte("{}"), 0o600))
604 }
607func TestRunUninstall_OnlySessionState(t *testing.T) {
608 dir := t.TempDir()
609 t.Setenv("HOME", dir)
610 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
611 writeSessionState(t)
613 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
614 mExec.EXPECT().
615 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
616 Return(nil, &exec.ExitError{})
618 ios, _, stdout, _ := cmdtest.TestIOStreams()
619 opts := &options{io: ios, executor: mExec, goos: "linux", yes: true}
621 require.NoError(t, runUninstall(t.Context(), opts))
623 assert.NotContains(t, stdout.String(), "Nothing to uninstall", "records left by an earlier uninstall are still removed")
624 assert.NoDirExists(t, gaig.StateDir())
627func TestRunUninstall_UnreadableSessionStateFails(t *testing.T) {
628 if runtime.GOOS == "windows" || os.Geteuid() == 0 {
629 t.Skip("needs a directory that can't be listed")
630 }
631 dir := t.TempDir()
632 t.Setenv("HOME", dir)
633 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
634 // An execute-only directory can't be listed, but files in it can be opened,
635 // so only the records check fails.
636 require.NoError(t, os.MkdirAll(gaig.StateDir(), 0o700))
637 require.NoError(t, os.Chmod(gaig.StateDir(), 0o100))
638 t.Cleanup(func() { _ = os.Chmod(gaig.StateDir(), 0o700) })
640 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
641 mExec.EXPECT().
642 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
643 Return(nil, &exec.ExitError{})
645 ios, _, stdout, _ := cmdtest.TestIOStreams()
646 opts := &options{io: ios, executor: mExec, goos: "linux"}
648 err := runUninstall(t.Context(), opts)
650 require.ErrorContains(t, err, "glab's local records of your agent sessions were not removed")
651 assert.NotContains(t, stdout.String(), "Nothing to uninstall")
652 assert.DirExists(t, gaig.StateDir())
655func TestRunUninstall_NothingInstalled(t *testing.T) {
656 dir := t.TempDir()
657 t.Setenv("HOME", dir)
658 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
660 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
661 mExec.EXPECT().
662 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
663 Return(nil, &exec.ExitError{})
665 ios, _, stdout, _ := cmdtest.TestIOStreams()
666 opts := &options{
667 io: ios,
668 executor: mExec,
669 goos: "linux",
670 // Without --yes and without a terminal, prompting would fail.
671 yes: false,
672 }
674 require.NoError(t, runUninstall(t.Context(), opts), "nothing to remove means nothing to confirm")
675 assert.Contains(t, stdout.String(), "Nothing to uninstall")
678func TestRunUninstall_LoadedJobWithoutFiles(t *testing.T) {
679 dir := t.TempDir()
680 t.Setenv("HOME", dir)
681 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
683 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
684 gomock.InOrder(
685 mExec.EXPECT().
686 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
687 Return(nil, nil),
688 mExec.EXPECT().
689 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "show", "glab-govern-audit-sync.service", "--property=ExecMainStartTimestampMonotonic,ExecMainStatus"}, nil).
690 Return([]byte("ExecMainStartTimestampMonotonic=0\nExecMainStatus=0\n"), nil),
691 mExec.EXPECT().
692 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "disable", "--now", "glab-govern-audit-sync.timer"}, nil).
693 Return(nil, nil),
694 )
696 ios, _, _, _ := cmdtest.TestIOStreams()
697 opts := &options{io: ios, executor: mExec, goos: "linux", yes: true}
699 require.NoError(t, runUninstall(t.Context(), opts), "a loaded job is unloaded even when its files are gone")
702func TestGlabBinaryPath(t *testing.T) {
703 t.Parallel()
705 running, err := os.Executable()
706 require.NoError(t, err)
708 t.Run("keeps the PATH entry when it is the running build", func(t *testing.T) {
709 t.Parallel()
710 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
711 expectGlabOnPath(mExec, "/home/me/.local/share/mise/shims/glab", "glab 1.121.0 (abc1234)\n")
713 got, err := glabBinaryPath(t.Context(), mExec, testBuild)
714 require.NoError(t, err)
715 assert.Equal(t, "/home/me/.local/share/mise/shims/glab", got, "the shim or symlink is kept, not resolved")
716 })
718 t.Run("uses the running binary when PATH has a different build", func(t *testing.T) {
719 t.Parallel()
720 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
721 expectGlabOnPath(mExec, "/usr/local/bin/glab", "glab 1.120.0 (34ea62162)\n")
723 got, err := glabBinaryPath(t.Context(), mExec, testBuild)
724 require.NoError(t, err)
725 assert.Equal(t, running, got)
726 })
728 t.Run("uses the running binary when the PATH entry does not run", func(t *testing.T) {
729 t.Parallel()
730 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
731 mExec.EXPECT().LookPath("glab").Return("/usr/local/bin/glab", nil)
732 mExec.EXPECT().
733 ExecWithIO(gomock.Any(), "/usr/local/bin/glab", []string{"version"}, nil, nil, gomock.Any(), gomock.Any()).
734 Return(errors.New("exec format error"))
736 got, err := glabBinaryPath(t.Context(), mExec, testBuild)
737 require.NoError(t, err)
738 assert.Equal(t, running, got)
739 })
741 t.Run("uses the running binary when glab is not in PATH", func(t *testing.T) {
742 t.Parallel()
743 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
744 mExec.EXPECT().LookPath("glab").Return("", errors.New("not found"))
746 got, err := glabBinaryPath(t.Context(), mExec, testBuild)
747 require.NoError(t, err)
748 assert.Equal(t, running, got)
749 })
752func TestRunSetup_NonInteractiveWithoutYesFlag(t *testing.T) {
753 dir := t.TempDir()
754 t.Setenv("HOME", dir)
755 path := filepath.Join(dir, ".claude", "settings.json")
756 ios, _, _, _ := cmdtest.TestIOStreams()
758 opts := &options{
759 io: ios,
760 yes: false,
761 settingsPathOverride: path,
762 }
763 err := runSetup(t.Context(), opts)
765 require.Error(t, err)
766 assert.Contains(t, err.Error(), "non-interactive")
768 _, statErr := os.Stat(path)
769 assert.True(t, os.IsNotExist(statErr), "settings file should not have been created")
772func TestInstallClaudeHooks_PreservesExistingHookFields(t *testing.T) {
773 dir := t.TempDir()
774 path := filepath.Join(dir, ".claude", "settings.json")
775 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
776 existing := `{
777 "hooks": {
778 "PostToolUse": [
779 {
780 "matcher": "Bash",
781 "hooks": [
782 {
783 "type": "command",
784 "command": "~/.claude/hooks/print-mr-link.sh",
785 "if": "Bash(git push*)",
786 "statusMessage": "Checking for MR link"
787 }
788 ]
789 }
790 ]
791 }
792}`
793 require.NoError(t, os.WriteFile(path, []byte(existing), 0o644))
795 ios, _, _, _ := cmdtest.TestIOStreams()
796 require.NoError(t, installClaudeHooks(&options{io: ios, settingsPathOverride: path}))
798 data, err := os.ReadFile(path)
799 require.NoError(t, err)
800 var settings struct {
801 Hooks map[string][]struct {
802 Matcher string `json:"matcher"`
803 Hooks []map[string]any `json:"hooks"`
804 } `json:"hooks"`
805 }
806 require.NoError(t, json.Unmarshal(data, &settings))
808 entry := settings.Hooks["PostToolUse"][0].Hooks[0]
809 assert.Equal(t, "Bash(git push*)", entry["if"], "dropping if would run the hook after every Bash call")
810 assert.Equal(t, "Checking for MR link", entry["statusMessage"])
811 assert.Len(t, settings.Hooks["Stop"], 1)
812 assert.Contains(t, string(data), `>/dev/null 2>&1 &`)
815func TestInstallClaudeHooks_PreservesAllSettingsKeys(t *testing.T) {
816 dir := t.TempDir()
817 path := filepath.Join(dir, ".claude", "settings.json")
818 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
820 existing := `{
821 "model": "claude-opus-4-5",
822 "env": {"MY_VAR": "value"},
823 "permissions": {
824 "allow": ["Bash"],
825 "deny": ["WebSearch"]
826 },
827 "hooks": {
828 "PreToolUse": [
829 {
830 "matcher": "Bash",
831 "hooks": [{"type": "command", "command": "echo pre-tool", "timeout": 5}]
832 }
833 ]
834 }
835}`
836 require.NoError(t, os.WriteFile(path, []byte(existing), 0o644))
838 ios, _, _, _ := cmdtest.TestIOStreams()
839 opts := &options{io: ios, yes: true, settingsPathOverride: path}
840 require.NoError(t, installClaudeHooks(opts))
842 data, err := os.ReadFile(path)
843 require.NoError(t, err)
845 var raw map[string]json.RawMessage
846 require.NoError(t, json.Unmarshal(data, &raw))
848 assert.Contains(t, raw, "model", "model key should be preserved")
849 assert.Contains(t, raw, "env", "env key should be preserved")
850 assert.Contains(t, raw, "permissions", "permissions key should be preserved")
852 hooks, err := claudehooks.HooksFromRaw(raw)
853 require.NoError(t, err)
854 require.Len(t, hooks["PreToolUse"], 1)
855 assert.Equal(t, "Bash", hooks["PreToolUse"][0].Matcher, "matcher should be preserved")
856 assert.Equal(t, 5, hooks["PreToolUse"][0].Hooks[0].Timeout, "timeout should be preserved")
858 assert.Len(t, hooks["Stop"], 1)
859 assert.Len(t, hooks["SessionEnd"], 1)
862func TestMCPDestructiveAnnotation(t *testing.T) {
863 t.Parallel()
864 ios, _, _, _ := cmdtest.TestIOStreams()
865 f := cmdtest.NewTestFactory(ios)
866 cmd := NewCmd(f)
867 assert.Equal(t, "true", cmd.Annotations[mcpannotations.Destructive])
870func TestSetupPrompt(t *testing.T) {
871 t.Parallel()
873 assert.Equal(t,
874 "glab will install agent session hooks in ~/.claude/settings.json and a systemd user timer (~/.config/systemd/user/glab-govern-audit-sync.timer) that syncs sessions in the background every 30 minutes, replacing any existing job. "+
875 "Agent sessions will be uploaded to the GitLab project of the repository they run in, including your prompts and each tool call's arguments, such as commands and the contents of files the agent writes. Common token and key formats are replaced first, but other secrets in them are uploaded as they are. "+
876 "glab also keeps a local record of each agent session in its configuration directory, with the session ID, the agent, the transcript path and how far it was synced, including sessions outside GitLab repositories, which are never uploaded. "+
877 "Only activity from now on will be uploaded, not earlier sessions or the earlier turns of sessions you resume. Do you wish to continue?",
878 setupPrompt("linux", false, plan{claudeHooks: true, uploads: uploadScope{fromNow: []string{"claude-code"}}}), "every setup says what is uploaded and what is kept, not only --agents")
880 withAgents := setupPrompt("linux", false, plan{claudeHooks: true, discovered: []string{"codex", "cursor"}, uploads: uploadScope{fromNow: []string{"claude-code", "codex", "cursor"}}})
881 assert.Contains(t, withAgents, "including your prompts and each tool call's arguments, such as commands and the contents of files the agent writes. Common token and key formats are replaced first, but other secrets in them are uploaded as they are")
882 assert.Contains(t, withAgents, "The job will also upload your codex and cursor sessions the same way. Only activity from now on will be uploaded, not earlier sessions or the earlier turns of sessions you resume. Do you wish to continue?")
884 hooksOnly := setupPrompt("linux", true, plan{claudeHooks: true, discovered: []string{"codex"}})
885 assert.Contains(t, hooksOnly, "including your prompts and each tool call's arguments")
886 assert.NotContains(t, hooksOnly, "codex", "without the job, enabled agents are not synced")
888 assert.Contains(t, setupPrompt("linux", false, plan{claudeHooks: true, openCodePlugin: "/h/.config/opencode/plugins/glab-govern.js"}),
889 "glab will install agent session hooks in ~/.claude/settings.json, an OpenCode plugin in /h/.config/opencode/plugins/glab-govern.js that runs for all your OpenCode sessions, and a systemd user timer")
890 assert.Contains(t, setupPrompt("linux", true, plan{openCodePlugin: "/p.js"}),
891 "glab will install an OpenCode plugin in /p.js that runs for all your OpenCode sessions. Agent sessions")
894func TestUninstallPrompt(t *testing.T) {
895 t.Parallel()
897 assert.Equal(t, "glab will remove the agent session hooks from ~/.claude/settings.json and the fallback periodic sync job. Do you wish to continue?", uninstallPrompt(true, "", true, nil, false))
898 assert.Equal(t, "glab will remove the fallback periodic sync job. Do you wish to continue?", uninstallPrompt(false, "", true, nil, false))
899 assert.Equal(t, "glab will remove the agent session hooks from ~/.claude/settings.json and the fallback periodic sync job. It will also stop syncing codex and cursor sessions. Do you wish to continue?",
900 uninstallPrompt(true, "", true, []string{"codex", "cursor"}, false))
901 assert.Equal(t, "glab will remove the agent session hooks from ~/.claude/settings.json, the OpenCode plugin at /p.js, and the fallback periodic sync job. It will also stop syncing codex sessions. Do you wish to continue?",
902 uninstallPrompt(true, "/p.js", true, []string{"codex"}, false))
903 assert.Equal(t, "glab will remove the fallback periodic sync job and glab's local records of your agent sessions. Do you wish to continue?",
904 uninstallPrompt(false, "", true, nil, true))
905 assert.Equal(t, "glab will remove glab's local records of your agent sessions. Do you wish to continue?",
906 uninstallPrompt(false, "", false, nil, true), "a job that isn't installed isn't listed")
907 assert.Equal(t, "glab will stop syncing codex sessions. Do you wish to continue?",
908 uninstallPrompt(false, "", false, []string{"codex"}, false))
909 assert.Equal(t, "glab will turn off session discovery. Do you wish to continue?",
910 uninstallPrompt(false, "", false, nil, false))
913func TestRunSetup_NamesAgentsEnabledEarlier(t *testing.T) {
914 dir := t.TempDir()
915 t.Setenv("HOME", dir)
916 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
917 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"cursor"}))
919 // Not a terminal and no --yes, so setup stops at the prompt it would show.
920 ios, _, _, _ := cmdtest.TestIOStreams()
921 err := runSetup(t.Context(), &options{io: ios, goos: "linux", settingsPathOverride: filepath.Join(dir, ".claude", "settings.json")})
922 require.Error(t, err)
924 agents, err := fallbacksync.DiscoveredAgents()
925 require.NoError(t, err)
926 assert.Equal(t, []string{"cursor"}, agents, "a plain setup keeps the earlier choice, which its prompt names")
929func TestRunUninstall_StopsDiscovery(t *testing.T) {
930 dir := t.TempDir()
931 t.Setenv("HOME", dir)
932 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
933 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"codex", "cursor"}))
935 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
936 mExec.EXPECT().
937 ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "is-active", "--quiet", "glab-govern-audit-sync.timer"}, nil).
938 Return(nil, &exec.ExitError{})
940 ios, _, stdout, _ := cmdtest.TestIOStreams()
941 require.NoError(t, runUninstall(t.Context(), &options{io: ios, executor: mExec, goos: "linux", yes: true}))
943 agents, err := fallbacksync.DiscoveredAgents()
944 require.NoError(t, err)
945 assert.Empty(t, agents, "a later setup does not bring discovery back on its own")
946 assert.Contains(t, stdout.String(), "Stopped syncing codex, cursor sessions.")
949func TestRunUninstall_CorruptAgentList(t *testing.T) {
950 dir := t.TempDir()
951 t.Setenv("HOME", dir)
952 configDir := filepath.Join(dir, "glab")
953 t.Setenv("GLAB_CONFIG_DIR", configDir)
954 opts := &options{executor: expectLinuxInstall(t, "/usr/bin/glab"), buildInfo: testBuild, goos: "linux", yes: true}
955 ios, _, stdout, _ := cmdtest.TestIOStreams()
956 opts.io = ios
957 opts.settingsPathOverride = filepath.Join(dir, ".claude", "settings.json")
958 require.NoError(t, runSetup(t.Context(), opts))
960 agentsFile := filepath.Join(configDir, "gaig", "discovered-agents.json")
961 require.NoError(t, os.MkdirAll(filepath.Dir(agentsFile), 0o755))
962 require.NoError(t, os.WriteFile(agentsFile, []byte("{not json"), 0o600))
964 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
965 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "disable", "--now", "glab-govern-audit-sync.timer"}, nil).Return(nil, nil)
966 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "daemon-reload"}, nil).Return(nil, nil)
967 opts.executor = mExec
969 require.NoError(t, runUninstall(t.Context(), opts), "a corrupt agent list does not block uninstall")
971 assert.Contains(t, stdout.String(), "Fallback periodic sync removed")
972 agents, err := fallbacksync.DiscoveredAgents()
973 require.NoError(t, err, "the list is reset")
974 assert.Empty(t, agents)
977// hookOnlyOptions returns options for a setup without the fallback periodic
978// sync, for the agents given, or for the earlier choice when there are none.
979func hookOnlyOptions(ios *iostreams.IOStreams, dir string, agents ...string) *options {
980 return &options{
981 io: ios,
982 yes: true,
983 noFallbackSync: true,
984 agents: agents,
985 agentsChanged: len(agents) > 0,
986 settingsPathOverride: filepath.Join(dir, ".claude", "settings.json"),
987 }
990func TestRunSetup_InstallsOpenCodePlugin(t *testing.T) {
991 dir := t.TempDir()
992 t.Setenv("HOME", dir)
993 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
995 ios, _, stdout, _ := cmdtest.TestIOStreams()
996 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode")))
998 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
999 state, err := opencodeplugin.Check(plugin)
1000 require.NoError(t, err)
1001 assert.Equal(t, opencodeplugin.Current, state)
1002 assert.Contains(t, stdout.String(), "OpenCode plugin installed in ~/.config/opencode/plugins/glab-govern.js")
1003 assert.NoFileExists(t, filepath.Join(dir, ".claude", "settings.json"), "Claude Code was not chosen")
1006func TestRunSetup_DoesNotInstallOpenCodePluginByDefault(t *testing.T) {
1007 dir := t.TempDir()
1008 t.Setenv("HOME", dir)
1009 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1010 require.NoError(t, os.MkdirAll(filepath.Join(dir, ".config", "opencode"), 0o755))
1012 ios, _, stdout, _ := cmdtest.TestIOStreams()
1013 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir)))
1015 assert.NoDirExists(t, filepath.Join(dir, ".config", "opencode", "plugins"), "OpenCode is synced only when chosen")
1016 assert.NotContains(t, stdout.String(), "OpenCode")
1017 assert.FileExists(t, filepath.Join(dir, ".claude", "settings.json"))
1020func TestRunSetup_AgentsAddToEarlierSetup(t *testing.T) {
1021 dir := t.TempDir()
1022 t.Setenv("HOME", dir)
1023 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1024 settings := filepath.Join(dir, ".claude", "settings.json")
1025 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
1027 ios, _, _, _ := cmdtest.TestIOStreams()
1028 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir)))
1029 installed, err := claudehooks.SyncHookInstalled(settings)
1030 require.NoError(t, err)
1031 require.True(t, installed)
1033 ios, _, _, _ = cmdtest.TestIOStreams()
1034 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode")))
1035 installed, err = claudehooks.SyncHookInstalled(settings)
1036 require.NoError(t, err)
1037 assert.True(t, installed, "setting up another agent keeps the Claude Code hooks")
1038 assert.FileExists(t, plugin)
1040 ios, _, stdout, _ := cmdtest.TestIOStreams()
1041 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir)))
1042 assert.Contains(t, stdout.String(), "Hooks installed", "a plain setup keeps both agents")
1043 assert.Contains(t, stdout.String(), "OpenCode plugin installed")
1046func TestRunSetup_OnlyTheAgentsPassed(t *testing.T) {
1047 dir := t.TempDir()
1048 t.Setenv("HOME", dir)
1049 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1051 ios, _, _, _ := cmdtest.TestIOStreams()
1052 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode")))
1053 ios, _, stdout, _ := cmdtest.TestIOStreams()
1054 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir)))
1056 assert.NoFileExists(t, filepath.Join(dir, ".claude", "settings.json"), "Claude Code was never set up")
1057 assert.Contains(t, stdout.String(), "OpenCode plugin installed")
1060func TestRunSetup_KeepsHooksFromOlderGlab(t *testing.T) {
1061 dir := t.TempDir()
1062 t.Setenv("HOME", dir)
1063 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1064 settings := filepath.Join(dir, ".claude", "settings.json")
1066 // An older glab installed the hooks without recording its choice.
1067 ios, _, _, _ := cmdtest.TestIOStreams()
1068 require.NoError(t, installClaudeHooks(hookOnlyOptions(ios, dir)))
1070 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode")))
1071 hookAgents, _, err := fallbacksync.RecordedHookAgents()
1072 require.NoError(t, err)
1073 assert.Equal(t, []string{"claude-code", "opencode"}, hookAgents)
1074 installed, err := claudehooks.SyncHookInstalled(settings)
1075 require.NoError(t, err)
1076 assert.True(t, installed)
1079func TestRunSetup_ForeignOpenCodePlugin(t *testing.T) {
1080 dir := t.TempDir()
1081 t.Setenv("HOME", dir)
1082 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1083 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
1084 require.NoError(t, os.MkdirAll(filepath.Dir(plugin), 0o755))
1085 require.NoError(t, os.WriteFile(plugin, []byte("// the user's own plugin\n"), 0o644))
1087 ios, _, _, _ := cmdtest.TestIOStreams()
1088 err := runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode"))
1089 require.Error(t, err)
1090 assert.Contains(t, err.Error(), "~/.config/opencode/plugins/glab-govern.js was not installed by glab")
1092 data, err := os.ReadFile(plugin)
1093 require.NoError(t, err)
1094 assert.Equal(t, "// the user's own plugin\n", string(data))
1096 _, recorded, err := fallbacksync.RecordedHookAgents()
1097 require.NoError(t, err)
1098 assert.False(t, recorded, "a failed setup records nothing")
1101func TestRunUninstall_RemovesOpenCodePlugin(t *testing.T) {
1102 dir := t.TempDir()
1103 t.Setenv("HOME", dir)
1104 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1105 plugins := filepath.Join(dir, ".config", "opencode", "plugins")
1106 require.NoError(t, os.MkdirAll(plugins, 0o755))
1107 other := filepath.Join(plugins, "other.js")
1108 require.NoError(t, os.WriteFile(other, []byte("// another plugin\n"), 0o644))
1110 ios, _, stdout, _ := cmdtest.TestIOStreams()
1111 opts := hookOnlyOptions(ios, dir, "claude-code", "opencode")
1112 require.NoError(t, runSetup(t.Context(), opts))
1113 require.FileExists(t, filepath.Join(plugins, opencodeplugin.FileName))
1115 require.NoError(t, runUninstall(t.Context(), opts))
1117 assert.NoFileExists(t, filepath.Join(plugins, opencodeplugin.FileName))
1118 assert.FileExists(t, other, "other OpenCode plugins are kept")
1119 assert.Contains(t, stdout.String(), "OpenCode plugin removed from ~/.config/opencode/plugins/glab-govern.js")
1120 _, recorded, err := fallbacksync.RecordedHookAgents()
1121 require.NoError(t, err)
1122 assert.False(t, recorded, "uninstall forgets the chosen agents")
1125func TestRunUninstall_OnlyOpenCodePlugin(t *testing.T) {
1126 dir := t.TempDir()
1127 t.Setenv("HOME", dir)
1128 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1129 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
1130 _, err := opencodeplugin.Install(plugin)
1131 require.NoError(t, err)
1133 ios, _, stdout, _ := cmdtest.TestIOStreams()
1134 require.NoError(t, runUninstall(t.Context(), hookOnlyOptions(ios, dir)))
1136 assert.NoFileExists(t, plugin)
1137 assert.Contains(t, stdout.String(), "OpenCode plugin removed from ~/.config/opencode/plugins/glab-govern.js")
1140func TestRunSetup_UpdatesOutdatedOpenCodePlugin(t *testing.T) {
1141 dir := t.TempDir()
1142 t.Setenv("HOME", dir)
1143 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1144 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
1145 require.NoError(t, os.MkdirAll(filepath.Dir(plugin), 0o755))
1146 require.NoError(t, os.WriteFile(plugin, []byte("// Installed by glab govern setup.\n// an older version\n"), 0o644))
1148 ios, _, _, _ := cmdtest.TestIOStreams()
1149 require.NoError(t, runSetup(t.Context(), hookOnlyOptions(ios, dir)))
1151 data, err := os.ReadFile(plugin)
1152 require.NoError(t, err)
1153 assert.Equal(t, opencodeplugin.Source, data, "a plain setup keeps and updates a plugin glab installed")
1156func TestRunSetup_NoOpenCodePluginOnWindows(t *testing.T) {
1157 dir := t.TempDir()
1158 t.Setenv("HOME", dir)
1159 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1161 ios, _, _, _ := cmdtest.TestIOStreams()
1162 opts := hookOnlyOptions(ios, dir, "opencode")
1163 opts.goos = "windows"
1164 err := runSetup(t.Context(), opts)
1165 require.Error(t, err)
1166 assert.Contains(t, err.Error(), "not supported on Windows")
1169func TestRunUninstall_KeepsForeignOpenCodePlugin(t *testing.T) {
1170 dir := t.TempDir()
1171 t.Setenv("HOME", dir)
1172 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1173 plugin := filepath.Join(dir, ".config", "opencode", "plugins", opencodeplugin.FileName)
1174 require.NoError(t, os.MkdirAll(filepath.Dir(plugin), 0o755))
1175 require.NoError(t, os.WriteFile(plugin, []byte("// the user's own plugin\n"), 0o644))
1177 ios, _, stdout, _ := cmdtest.TestIOStreams()
1178 require.NoError(t, runUninstall(t.Context(), hookOnlyOptions(ios, dir)))
1180 assert.FileExists(t, plugin)
1181 assert.Contains(t, stdout.String(), "Nothing to uninstall")
1184func TestRunSetup_DoesNotAddClaudeCodeForCodexOnlySetup(t *testing.T) {
1185 dir := t.TempDir()
1186 t.Setenv("HOME", dir)
1187 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1188 // An older glab set up Codex, and the user then removed the Claude Code hooks.
1189 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"codex"}))
1191 hookAgents, discovered, err := chosenAgents(hookOnlyOptions(nil, dir))
1192 require.NoError(t, err)
1193 assert.Empty(t, hookAgents)
1194 assert.Equal(t, []string{"codex"}, discovered)
1196 ios, _, _, _ := cmdtest.TestIOStreams()
1197 err = runSetup(t.Context(), hookOnlyOptions(ios, dir))
1198 require.Error(t, err, "with --no-fallback-sync there is nothing to set up")
1199 assert.Contains(t, err.Error(), "codex sessions are only synced by the fallback periodic sync")
1202func TestRunSetup_DiscoveredAgentsAdd(t *testing.T) {
1203 dir := t.TempDir()
1204 t.Setenv("HOME", dir)
1205 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1207 require.NoError(t, fallbacksync.SetDiscoveredAgents([]string{"codex"}))
1208 opts := hookOnlyOptions(nil, dir, "cursor", "opencode", "opencode")
1209 hookAgents, discovered, err := chosenAgents(opts)
1210 require.NoError(t, err)
1211 assert.Equal(t, []string{"codex", "cursor"}, discovered)
1212 assert.Equal(t, []string{"opencode"}, hookAgents, "an agent passed twice is set up once")
1215func TestRunSetup_UnreadableAgentsSuggestsUninstall(t *testing.T) {
1216 dir := t.TempDir()
1217 t.Setenv("HOME", dir)
1218 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1219 path := filepath.Join(dir, "glab", "gaig", "hook-agents.json")
1220 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
1221 require.NoError(t, os.WriteFile(path, []byte("{not json"), 0o600))
1223 for _, agents := range [][]string{nil, {"opencode"}} {
1224 ios, _, _, _ := cmdtest.TestIOStreams()
1225 err := runSetup(t.Context(), hookOnlyOptions(ios, dir, agents...))
1226 require.Error(t, err)
1227 assert.Contains(t, err.Error(), "run 'glab minder setup --uninstall' to start again")
1231func TestRunSetup_UnreadableClaudeSettingsIsNotRecorded(t *testing.T) {
1232 dir := t.TempDir()
1233 t.Setenv("HOME", dir)
1234 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1235 settings := filepath.Join(dir, ".claude", "settings.json")
1236 require.NoError(t, os.MkdirAll(filepath.Dir(settings), 0o755))
1237 require.NoError(t, os.WriteFile(settings, []byte("{not json"), 0o644))
1239 ios, _, _, _ := cmdtest.TestIOStreams()
1240 err := runSetup(t.Context(), hookOnlyOptions(ios, dir, "opencode"))
1241 require.Error(t, err)
1242 assert.Contains(t, err.Error(), settings)
1243 assert.Contains(t, err.Error(), "fix it, then run 'glab minder setup' again")
1244 assert.NotContains(t, err.Error(), "--uninstall", "uninstalling doesn't change the settings file, so it doesn't help")
1245 _, recorded, err := fallbacksync.RecordedHookAgents()
1246 require.NoError(t, err)
1247 assert.False(t, recorded, "Claude Code must not be recorded as not set up when its settings cannot be read")
1250func TestRunSetup_ClaudeCodeOnWindowsFailsBeforePrompt(t *testing.T) {
1251 dir := t.TempDir()
1252 t.Setenv("HOME", dir)
1253 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1255 // Not a terminal and no --yes, so reaching the prompt would fail differently.
1256 ios, _, _, _ := cmdtest.TestIOStreams()
1257 opts := hookOnlyOptions(ios, dir)
1258 opts.yes = false
1259 opts.goos = "windows"
1260 err := runSetup(t.Context(), opts)
1261 require.Error(t, err)
1262 assert.Contains(t, err.Error(), "hook installation is not supported on Windows")
1265func TestRunSetup_DiscoveredAgentsWithoutJobFailBeforePrompt(t *testing.T) {
1266 tests := map[string]struct {
1267 goos string
1268 agents []string
1269 recorded []string
1270 }{
1271 "Windows": {goos: "windows", agents: []string{"codex", "cursor"}},
1272 "FreeBSD": {goos: "freebsd", agents: []string{"codex", "cursor"}},
1273 "rerun with recorded list": {goos: "windows", recorded: []string{"codex", "cursor"}},
1275 for name, tc := range tests {
1276 t.Run(name, func(t *testing.T) {
1277 dir := t.TempDir()
1278 t.Setenv("HOME", dir)
1279 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1280 if tc.recorded != nil {
1281 require.NoError(t, fallbacksync.SetDiscoveredAgents(tc.recorded))
1284 // Not a terminal and no --yes, so reaching the prompt would fail differently.
1285 ios, _, _, _ := cmdtest.TestIOStreams()
1286 opts := hookOnlyOptions(ios, dir, tc.agents...)
1287 opts.yes = false
1288 opts.noFallbackSync = false
1289 opts.goos = tc.goos
1290 err := runSetup(t.Context(), opts)
1291 require.ErrorIs(t, err, fallbacksync.ErrUnsupportedOS)
1292 assert.Contains(t, err.Error(), "codex and cursor sessions need the fallback periodic sync: fallback periodic sync is supported only on macOS and Linux")
1293 })
1297func TestSetupPrompt_JobOnly(t *testing.T) {
1298 t.Parallel()
1300 assert.Contains(t, setupPrompt("linux", false, plan{discovered: []string{"codex"}}),
1301 "glab will install a systemd user timer (~/.config/systemd/user/glab-govern-audit-sync.timer) that syncs sessions")
1304func TestUploadScopePrompt(t *testing.T) {
1305 t.Parallel()
1307 tests := map[string]struct {
1308 scope uploadScope
1309 want string
1310 }{
1311 "first setup": {
1312 scope: uploadScope{fromNow: []string{"claude-code", "codex"}},
1313 want: ". Only activity from now on will be uploaded, not earlier sessions or the earlier turns of sessions you resume",
1314 },
1315 "setup again": {
1316 scope: uploadScope{fromEarlier: []string{"claude-code"}},
1317 want: ". Only activity from when you first set up each agent will be uploaded, not earlier sessions or the earlier turns of sessions you resume",
1318 },
1319 "history": {
1320 scope: uploadScope{history: []string{"claude-code", "cursor"}},
1321 want: ". Activity from the last 89 days and from now on will be uploaded, including earlier sessions and the earlier turns of sessions you resume",
1322 },
1323 "agent added to an earlier setup": {
1324 scope: uploadScope{fromNow: []string{"codex"}, fromEarlier: []string{"claude-code"}},
1325 want: ". For codex, only activity from now on will be uploaded, not earlier sessions or the earlier turns of sessions you resume" +
1326 ". For claude-code, only activity from when you first set it up will be uploaded, not earlier sessions or the earlier turns of sessions you resume",
1327 },
1328 "agents added with history to an earlier setup": {
1329 scope: uploadScope{fromEarlier: []string{"claude-code", "opencode"}, history: []string{"codex", "cursor"}},
1330 want: ". For claude-code and opencode, only activity from when you first set them up will be uploaded, not earlier sessions or the earlier turns of sessions you resume" +
1331 ". For codex and cursor, activity from the last 89 days and from now on will be uploaded, including earlier sessions and the earlier turns of sessions you resume",
1332 },
1333 "all three": {
1334 scope: uploadScope{fromNow: []string{"codex"}, fromEarlier: []string{"claude-code"}, history: []string{"opencode"}},
1335 want: ". For codex, only activity from now on will be uploaded, not earlier sessions or the earlier turns of sessions you resume" +
1336 ". For claude-code, only activity from when you first set it up will be uploaded, not earlier sessions or the earlier turns of sessions you resume" +
1337 ". For opencode, activity from the last 89 days and from now on will be uploaded, including earlier sessions and the earlier turns of sessions you resume",
1338 },
1340 for name, tc := range tests {
1341 t.Run(name, func(t *testing.T) {
1342 t.Parallel()
1343 assert.Equal(t, tc.want, tc.scope.prompt())
1344 })
1348func TestPlanUploads(t *testing.T) {
1349 t.Parallel()
1351 earlier := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
1352 now := time.Date(2026, 11, 20, 10, 0, 0, 0, time.UTC)
1354 tests := map[string]struct {
1355 recorded fallbacksync.AgentSetups
1356 agents []string
1357 history bool
1358 wantUploads uploadScope
1359 wantSetups fallbacksync.AgentSetups
1360 }{
1361 "first setup": {
1362 agents: []string{"claude-code", "codex"},
1363 wantUploads: uploadScope{fromNow: []string{"claude-code", "codex"}},
1364 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: now}, "codex": {SetUpAt: now}},
1365 },
1366 "first setup with history": {
1367 agents: []string{"claude-code"},
1368 history: true,
1369 wantUploads: uploadScope{history: []string{"claude-code"}},
1370 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: now, History: true}},
1371 },
1372 "setup again keeps when an agent was first set up": {
1373 recorded: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}},
1374 agents: []string{"claude-code", "cursor"},
1375 wantUploads: uploadScope{fromNow: []string{"cursor"}, fromEarlier: []string{"claude-code"}},
1376 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}, "cursor": {SetUpAt: now}},
1377 },
1378 "history opted in to earlier is kept": {
1379 recorded: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier, History: true}},
1380 agents: []string{"claude-code"},
1381 wantUploads: uploadScope{history: []string{"claude-code"}},
1382 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier, History: true}},
1383 },
1384 "history applies only to agents set up for the first time": {
1385 recorded: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}},
1386 agents: []string{"claude-code", "codex"},
1387 history: true,
1388 wantUploads: uploadScope{fromEarlier: []string{"claude-code"}, history: []string{"codex"}},
1389 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}, "codex": {SetUpAt: now, History: true}},
1390 },
1391 "agents this setup does not sync are kept": {
1392 recorded: fallbacksync.AgentSetups{"codex": {SetUpAt: earlier}},
1393 agents: []string{"claude-code"},
1394 wantUploads: uploadScope{fromNow: []string{"claude-code"}},
1395 wantSetups: fallbacksync.AgentSetups{"claude-code": {SetUpAt: now}, "codex": {SetUpAt: earlier}},
1396 },
1398 for name, tc := range tests {
1399 t.Run(name, func(t *testing.T) {
1400 t.Parallel()
1401 uploads := planUploads(tc.recorded, tc.agents, tc.history)
1402 assert.Equal(t, tc.wantUploads, uploads)
1403 assert.Equal(t, tc.wantSetups, uploads.setups(tc.recorded, now))
1404 })
1408func TestSetup_IncludeHistoryOnARerun(t *testing.T) {
1409 earlier := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
1410 dir := t.TempDir()
1411 t.Setenv("HOME", dir)
1412 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1413 require.NoError(t, fallbacksync.SetAgentSetups(fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}}))
1415 ios, _, _, _ := cmdtest.TestIOStreams()
1416 opts := hookOnlyOptions(ios, dir)
1417 opts.includeHistory = true
1418 err := runSetup(t.Context(), opts)
1419 require.ErrorContains(t, err, "--include-history applies only to agents set up for the first time, and every agent this setup syncs (claude-code) is set up already")
1420 assert.Contains(t, err.Error(), "run 'glab minder setup --uninstall'")
1421 assert.NoFileExists(t, filepath.Join(dir, ".claude", "settings.json"), "nothing is installed")
1423 ios, _, _, _ = cmdtest.TestIOStreams()
1424 opts = hookOnlyOptions(ios, dir, "opencode")
1425 opts.includeHistory = true
1426 require.NoError(t, runSetup(t.Context(), opts))
1427 setups, err := fallbacksync.ReadAgentSetups()
1428 require.NoError(t, err)
1429 assert.Equal(t, fallbacksync.AgentSetup{SetUpAt: earlier}, setups["claude-code"], "an agent set up earlier keeps what it uploads")
1430 assert.True(t, setups["opencode"].History)
1433func TestSetup_RecordsAgentSetups(t *testing.T) {
1434 earlier := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
1436 tests := map[string]struct {
1437 recorded fallbacksync.AgentSetups
1438 // olderGlab installs the Claude Code hooks without recording which
1439 // agents are set up, as glab versions before setups were recorded did.
1440 olderGlab bool
1441 args string
1442 // want lists the agents and whether they upload history. Agents with
1443 // a time in wantEarlier keep it, and the others are set up now.
1444 want map[string]bool
1445 wantEarlier map[string]time.Time
1446 }{
1447 "first setup": {
1448 args: "",
1449 want: map[string]bool{"claude-code": false},
1450 },
1451 "history": {
1452 args: "--include-history",
1453 want: map[string]bool{"claude-code": true},
1454 },
1455 "discovered agents": {
1456 args: "--agents codex,cursor",
1457 want: map[string]bool{"codex": false, "cursor": false},
1458 },
1459 "setup again keeps when an agent was first set up": {
1460 recorded: fallbacksync.AgentSetups{"claude-code": {SetUpAt: earlier}},
1461 args: "--agents opencode",
1462 want: map[string]bool{"claude-code": false, "opencode": false},
1463 wantEarlier: map[string]time.Time{"claude-code": earlier},
1464 },
1465 "set up with an older glab": {
1466 olderGlab: true,
1467 args: "",
1468 want: map[string]bool{"claude-code": false},
1469 },
1470 "without the fallback sync, discovered agents are not set up": {
1471 recorded: fallbacksync.AgentSetups{"codex": {SetUpAt: earlier}},
1472 args: "--no-fallback-sync --agents claude-code",
1473 want: map[string]bool{"claude-code": false, "codex": false},
1474 wantEarlier: map[string]time.Time{"codex": earlier},
1475 },
1477 for name, tc := range tests {
1478 t.Run(name, func(t *testing.T) {
1479 dir := t.TempDir()
1480 t.Setenv("HOME", dir)
1481 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1482 if tc.recorded != nil {
1483 require.NoError(t, fallbacksync.SetAgentSetups(tc.recorded))
1485 if tc.olderGlab {
1486 require.NoError(t, installClaudeHooks(&options{}))
1488 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
1489 mExec.EXPECT().LookPath("glab").Return("", errors.New("not found")).AnyTimes()
1490 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), gomock.Any(), gomock.Any(), nil).Return(nil, nil).AnyTimes()
1491 exec := cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithExecutor(mExec))
1493 before := time.Now()
1494 _, err := exec(strings.TrimSpace("--yes " + tc.args))
1495 require.NoError(t, err)
1496 after := time.Now()
1498 setups, err := fallbacksync.ReadAgentSetups()
1499 require.NoError(t, err)
1500 require.Len(t, setups, len(tc.want))
1501 for agent, history := range tc.want {
1502 setup, ok := setups[agent]
1503 require.True(t, ok, agent)
1504 assert.Equal(t, history, setup.History, agent)
1505 if at, ok := tc.wantEarlier[agent]; ok {
1506 assert.True(t, at.Equal(setup.SetUpAt), "%s keeps when it was first set up", agent)
1507 continue
1509 assert.False(t, setup.SetUpAt.Before(before) || setup.SetUpAt.After(after), "%s is set up now, at %s", agent, setup.SetUpAt)
1511 })
1515func TestSetup_CancelledRecordsNoAgentSetups(t *testing.T) {
1516 dir := t.TempDir()
1517 t.Setenv("HOME", dir)
1518 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1520 // Not a terminal and no --yes, so setup stops at the prompt.
1521 ios, _, _, _ := cmdtest.TestIOStreams()
1522 require.Error(t, runSetup(t.Context(), &options{io: ios, goos: "linux", includeHistory: true, settingsPathOverride: filepath.Join(dir, ".claude", "settings.json")}))
1524 setups, err := fallbacksync.ReadAgentSetups()
1525 require.NoError(t, err)
1526 assert.Empty(t, setups)
1529func TestSetup_UnreadableAgentSetupsSuggestsUninstall(t *testing.T) {
1530 dir := t.TempDir()
1531 t.Setenv("HOME", dir)
1532 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1533 path := filepath.Join(dir, "glab", "gaig", "agent-setups.json")
1534 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
1535 require.NoError(t, os.WriteFile(path, []byte("{not json"), 0o600))
1537 ios, _, _, _ := cmdtest.TestIOStreams()
1538 err := runSetup(t.Context(), hookOnlyOptions(ios, dir))
1539 require.Error(t, err)
1540 assert.Contains(t, err.Error(), "run 'glab minder setup --uninstall' to start again")
1541 assert.NoFileExists(t, filepath.Join(dir, ".claude", "settings.json"), "nothing is installed")
1544func TestSetup_IncludeHistoryConflictsWithUninstall(t *testing.T) {
1545 t.Parallel()
1547 exec := cmdtest.SetupCmdForTest(t, NewCmd, false)
1548 _, err := exec("--uninstall --include-history")
1549 require.Error(t, err)
1550 assert.Contains(t, err.Error(), "none of the others can be")
1553// cursorTurn is a line of a Cursor transcript.
1554const cursorTurn = `{"role":"user"}` + "\n"
1556// writeCursorTranscript writes a Cursor transcript with one turn under home,
1557// and returns its path.
1558func writeCursorTranscript(t *testing.T, home, id string) string {
1559 t.Helper()
1560 path := filepath.Join(home, ".cursor", "projects", "work-repo", "agent-transcripts", id, id+".jsonl")
1561 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
1562 require.NoError(t, os.WriteFile(path, []byte(cursorTurn), 0o644))
1563 return path
1566func assertSyncStartsAt(t *testing.T, sessionID string, want int64) {
1567 t.Helper()
1568 cursor, err := syncstate.ReadPosition(sessionID)
1569 require.NoError(t, err)
1570 assert.Equal(t, want, cursor)
1571 uploaded, err := syncstate.HasUploads(sessionID, cursor)
1572 require.NoError(t, err)
1573 assert.False(t, uploaded)
1576func TestSetup_RecordsWhereCursorSessionsEnd(t *testing.T) {
1577 tests := map[string]struct {
1578 runs []string
1579 // want is where syncing starts, or 0 when setup records nothing.
1580 want int64
1581 }{
1582 "first setup": {runs: []string{"--agents cursor"}, want: int64(len(cursorTurn))},
1583 "setup again": {runs: []string{"--agents cursor", "", "--agents codex"}, want: int64(len(cursorTurn))},
1584 "history": {runs: []string{"--agents cursor --include-history"}},
1585 "history, then setup again": {runs: []string{"--agents cursor --include-history", ""}},
1586 "added to an earlier setup": {runs: []string{"", "--agents cursor"}, want: int64(2 * len(cursorTurn))},
1587 "without the fallback sync": {runs: []string{"--no-fallback-sync"}},
1589 for name, tc := range tests {
1590 t.Run(name, func(t *testing.T) {
1591 dir := t.TempDir()
1592 t.Setenv("HOME", dir)
1593 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1594 path := writeCursorTranscript(t, dir, "conv-1")
1596 for i, args := range tc.runs {
1597 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
1598 mExec.EXPECT().LookPath("glab").Return("", errors.New("not found")).AnyTimes()
1599 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), gomock.Any(), gomock.Any(), nil).Return(nil, nil).AnyTimes()
1600 exec := cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithExecutor(mExec))
1601 _, err := exec(strings.TrimSpace("--yes " + args))
1602 require.NoError(t, err)
1603 if i == 0 {
1604 // Turns added after the first setup are uploaded, so a
1605 // later setup must not skip them.
1606 f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)
1607 require.NoError(t, err)
1608 _, err = f.WriteString(cursorTurn)
1609 require.NoError(t, errors.Join(err, f.Close()))
1613 if tc.want == 0 {
1614 cp, err := syncstate.PositionPath("conv-1")
1615 require.NoError(t, err)
1616 assert.NoFileExists(t, cp, "the whole transcript may be uploaded")
1617 return
1619 assertSyncStartsAt(t, "conv-1", tc.want)
1620 })
1624func TestRunUninstall_RemovesWhereCursorSessionsEnd(t *testing.T) {
1625 dir := t.TempDir()
1626 t.Setenv("HOME", dir)
1627 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1628 writeCursorTranscript(t, dir, "conv-1")
1630 ios, _, _, _ := cmdtest.TestIOStreams()
1631 opts := &options{
1632 io: ios,
1633 executor: expectLinuxInstall(t, "/usr/bin/glab"),
1634 buildInfo: testBuild,
1635 goos: "linux",
1636 yes: true,
1637 agents: []string{"cursor"},
1638 agentsChanged: true,
1639 settingsPathOverride: filepath.Join(dir, ".claude", "settings.json"),
1641 require.NoError(t, runSetup(t.Context(), opts))
1642 cp, err := syncstate.PositionPath("conv-1")
1643 require.NoError(t, err)
1644 require.FileExists(t, cp)
1646 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
1647 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "disable", "--now", "glab-govern-audit-sync.timer"}, nil).Return(nil, nil)
1648 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), "systemctl", []string{"--user", "daemon-reload"}, nil).Return(nil, nil)
1649 opts.executor = mExec
1650 opts.agents, opts.agentsChanged = nil, false
1652 require.NoError(t, runUninstall(t.Context(), opts))
1654 assert.NoFileExists(t, cp)
1655 start, err := syncstate.StartPath("conv-1")
1656 require.NoError(t, err)
1657 assert.NoFileExists(t, start)
1660// setUpCursor runs setup for Cursor, with args added.
1661func setUpCursor(t *testing.T, args string) error {
1662 t.Helper()
1663 mExec := cmdtest.NewMockExecutor(gomock.NewController(t))
1664 mExec.EXPECT().LookPath("glab").Return("", errors.New("not found")).AnyTimes()
1665 mExec.EXPECT().ExecWithCombinedOutput(gomock.Any(), gomock.Any(), gomock.Any(), nil).Return(nil, nil).AnyTimes()
1666 exec := cmdtest.SetupCmdForTest(t, NewCmd, false, cmdtest.WithExecutor(mExec))
1667 _, err := exec(strings.TrimSpace("--yes --agents cursor " + args))
1668 return err
1671func TestSetup_HistoryRecordsWhereOnlyOldCursorSessionsEnd(t *testing.T) {
1672 dir := t.TempDir()
1673 t.Setenv("HOME", dir)
1674 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1675 recent := writeCursorTranscript(t, dir, "conv-recent")
1676 old := writeCursorTranscript(t, dir, "conv-old")
1677 long := time.Now().Add(-100 * 24 * time.Hour)
1678 require.NoError(t, os.Chtimes(old, long, long))
1680 require.NoError(t, setUpCursor(t, "--include-history"))
1682 cp, err := syncstate.PositionPath("conv-recent")
1683 require.NoError(t, err)
1684 assert.NoFileExists(t, cp, "the history of %s is uploaded", recent)
1685 assertSyncStartsAt(t, "conv-old", int64(len(cursorTurn)))
1688func TestSetup_FollowsSymlinkedCursorWorkspaces(t *testing.T) {
1689 dir := t.TempDir()
1690 t.Setenv("HOME", dir)
1691 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1692 elsewhere := filepath.Join(t.TempDir(), "workspace")
1693 path := filepath.Join(elsewhere, "agent-transcripts", "conv-1", "conv-1.jsonl")
1694 require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
1695 require.NoError(t, os.WriteFile(path, []byte(cursorTurn), 0o644))
1696 projects := filepath.Join(dir, ".cursor", "projects")
1697 require.NoError(t, os.MkdirAll(projects, 0o755))
1698 require.NoError(t, os.Symlink(elsewhere, filepath.Join(projects, "work-repo")))
1700 require.NoError(t, setUpCursor(t, ""))
1702 assertSyncStartsAt(t, "conv-1", int64(len(cursorTurn)))
1705func TestSetup_UnreadableCursorWorkspaceFails(t *testing.T) {
1706 if runtime.GOOS == "windows" || os.Geteuid() == 0 {
1707 t.Skip("needs a directory that can't be listed")
1709 dir := t.TempDir()
1710 t.Setenv("HOME", dir)
1711 t.Setenv("GLAB_CONFIG_DIR", filepath.Join(dir, "glab"))
1712 path := writeCursorTranscript(t, dir, "conv-1")
1713 transcripts := filepath.Dir(filepath.Dir(path))
1714 require.NoError(t, os.Chmod(transcripts, 0o100))
1715 t.Cleanup(func() { _ = os.Chmod(transcripts, 0o755) })
1717 err := setUpCursor(t, "")
1718 require.ErrorContains(t, err, "failed to record how far your Cursor sessions go")
1720 setups, err := fallbacksync.ReadAgentSetups()
1721 require.NoError(t, err)
1722 assert.Empty(t, setups, "Cursor is not set up, so a later setup tries again")
1723 agents, err := fallbacksync.DiscoveredAgents()
1724 require.NoError(t, err)
1725 assert.Empty(t, agents, "Cursor sessions are not synced")
Diagnostics8 git calls · 323 ms
CallStatusSizeTime0323 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
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 · hit9 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=9
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 · 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=4273
git.response.cache=HIT
git.response.duration_ms=3
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=3
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 · 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=261
git.response.cache=HIT
git.response.duration_ms=3
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:0200198 B · hit8 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=8
git.response.bytes=198
git.response.cache=HIT
git.response.duration_ms=8
git.fetch.filter=tree:0
git.fetch.wants=a2b28db4d943a407ac72661e73be16d6e3d0cc25
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=198
git.pkt.payload.max=171
git.sideband.band1.bytes=171
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=171
git.pack.trailer=230772abb145f332cba4850a222435de3a0d1655
Open pack map
fetch20011 KiB298 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=298
git.response.bytes=11445
git.response.cache=MISS
git.response.duration_ms=298
git.fetch.wants=7171bfa7c0a1109907d80359e512df07b24e67b9
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=11445
git.pkt.payload.max=11418
git.sideband.band1.bytes=11418
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
a5e2a04a7ffa1293
Request
b0dae930…
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