GitLabgitlab-org

cli

main
ply8 git calls299 ms106 KiB5 cachedprotocol v2
821 lines31 KiBRaw
1package setup
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io/fs"
8 "maps"
9 "os"
10 "path/filepath"
11 "runtime"
12 "slices"
13 "strings"
14 "time"
16 "github.com/MakeNowJust/heredoc/v2"
17 "github.com/spf13/cobra"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/cmdutils"
21 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/claudehooks"
22 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/fallbacksync"
23 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/gaig"
24 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/opencodeplugin"
25 "gitlab.com/gitlab-org/cli/internal/commands/govern/internal/syncstate"
26 "gitlab.com/gitlab-org/cli/internal/config"
27 "gitlab.com/gitlab-org/cli/internal/dbg"
28 "gitlab.com/gitlab-org/cli/internal/iostreams"
29 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
30 "gitlab.com/gitlab-org/cli/internal/text"
33type options struct {
34 io *iostreams.IOStreams
35 executor cmdutils.Executor
36 buildInfo api.BuildInfo
37 goos string
38 yes bool
39 noFallbackSync bool
40 includeHistory bool
41 agents []string
42 agentsChanged bool
43 uninstall bool
44 settingsPathOverride string
47func NewCmd(f cmdutils.Factory) *cobra.Command {
48 opts := &options{
49 io: f.IO(),
50 executor: f.Executor(),
51 buildInfo: f.BuildInfo(),
52 goos: runtime.GOOS,
53 }
55 cmd := &cobra.Command{
56 Use: "setup",
57 Short: "Configure this machine to record AI agent sessions. (EXPERIMENTAL)",
58 Long: heredoc.Docf(`
59 Configure the current machine for AI governance session capture.
61 Choose the agents to sync with %[1]s--agents%[1]s. Without it, setup syncs the agents set up by an earlier run, or Claude Code if there are none. For each agent, setup installs:
63 - Claude Code (%[1]sclaude-code%[1]s): a Stop hook in %[1]s~/.claude/settings.json%[1]s, which syncs the session after every agent turn, and a SessionEnd hook, which syncs the session and marks it completed.
64 - OpenCode (%[1]sopencode%[1]s), version 1.4 or later: a plugin in %[1]s~/.config/opencode/plugins/glab-govern.js%[1]s (under %[1]s$XDG_CONFIG_HOME%[1]s when it is set), which syncs the session every time it goes idle. OpenCode loads it for all your sessions, in every project. Later setups keep it up to date.
65 - Codex (%[1]scodex%[1]s) and Cursor (%[1]scursor%[1]s): nothing. The fallback periodic sync finds their sessions by scanning their transcripts in %[1]s~/.codex/sessions%[1]s and %[1]s~/.cursor/projects%[1]s, and uploads those from repositories on GitLab hosts you are logged in to with glab. Their sessions are marked completed once they have been idle for 24 hours.
67 Setup also installs the fallback periodic sync: a launchd agent (%[1]s~/Library/LaunchAgents/com.gitlab.glab-govern-audit-sync.plist%[1]s) on macOS, or a systemd user timer (%[1]s~/.config/systemd/user/glab-govern-audit-sync.timer%[1]s) on Linux.
69 The fallback periodic sync runs %[1]sglab minder audit sync --all%[1]s every 30 minutes, and on Linux also 5 minutes after boot, until you remove it. It uploads anything the hooks missed for sessions they have already recorded (see %[1]sglab minder audit sync --help%[1]s for what is uploaded), using your stored glab credentials and the glab configuration directory in use when you run setup. Each session goes to the project and host of the Git repository the agent ran in. It also marks sessions completed once they have been idle for 24 hours. It pauses sessions from agents that use hooks while those hooks are not installed. Pass %[1]s--no-fallback-sync%[1]s to install only the hooks and plugin, which Codex and Cursor cannot be synced without. The fallback periodic sync is not available on Windows.
71 By default, glab uploads only what each agent does after you first set it up: not its sessions from before, and not the earlier turns of a session from before that you resume.
73 Cursor records no times, so setup notes where each existing Cursor transcript ends, and only what is added to it afterwards is uploaded. A chat that Cursor copies under a new ID, for example when you duplicate it, counts as a new session and is uploaded in full.
75 Pass %[1]s--include-history%[1]s to also upload activity from the last 89 days, including those sessions and turns, for the agents this setup sets up for the first time. For Cursor, that is every transcript changed in the last 89 days. An agent set up earlier keeps what it uploads, so to add its history, run %[1]s--uninstall%[1]s first. If you set up an agent with an earlier glab version, which did not record when, its activity from the last 89 days is still uploaded until you run setup again.
77 Run setup again with %[1]s--agents%[1]s to add agents. Agents set up by an earlier run stay set up, so to stop syncing an agent, run %[1]s--uninstall%[1]s and then set up the agents you want. Every setup prompt names the agents that are synced.
79 Safe to run multiple times: existing hooks are not duplicated, and an existing fallback periodic sync job is replaced. Run %[1]sglab minder doctor%[1]s afterwards to verify the setup.
81 Run %[1]sglab minder setup --uninstall%[1]s to remove everything setup installed: the hooks, the OpenCode plugin, the fallback periodic sync job, and Codex and Cursor session syncing. It also removes glab's local records of your agent sessions and forgets the agents you set up and when, so the next setup starts with Claude Code again. Other hooks and settings in %[1]s~/.claude/settings.json%[1]s, and other OpenCode plugins, are left unchanged.
82 `, "`") + text.ExperimentalString,
83 Example: heredoc.Doc(`
84 # Sync Claude Code sessions, or the agents set up earlier
85 $ glab minder setup
87 # Sync OpenCode sessions
88 $ glab minder setup --agents opencode
90 # Sync Claude Code, OpenCode, and Codex sessions
91 $ glab minder setup --agents claude-code,opencode,codex
93 # Also upload activity from the last 89 days, including sessions from before setup
94 $ glab minder setup --include-history
96 # Install only the hooks and plugin, without the fallback periodic sync
97 $ glab minder setup --no-fallback-sync
99 # Remove everything setup installed
100 $ glab minder setup --uninstall
101 `),
102 Args: cobra.NoArgs,
103 ValidArgsFunction: cobra.NoFileCompletions,
104 Annotations: map[string]string{
105 mcpannotations.Destructive: "true",
106 },
107 RunE: func(cmd *cobra.Command, args []string) error {
108 opts.agentsChanged = cmd.Flags().Changed("agents")
109 if err := validateAgents(opts.agents, opts.agentsChanged, opts.noFallbackSync); err != nil {
110 return err
111 }
112 if opts.uninstall {
113 return runUninstall(cmd.Context(), opts)
114 }
115 return runSetup(cmd.Context(), opts)
116 },
117 }
119 fl := cmd.Flags()
120 fl.BoolVarP(&opts.yes, "yes", "y", false, "Skip the confirmation prompt, and agree to what it would describe: the changes and, for setup, the uploads.")
121 fl.BoolVar(&opts.noFallbackSync, "no-fallback-sync", false, "Install only the hooks and plugin, without the fallback periodic sync job.")
122 fl.BoolVar(&opts.includeHistory, "include-history", false, "Also upload the activity from the last 89 days of the agents set up for the first time, including sessions from before setup and the earlier turns of sessions you resume.")
123 fl.BoolVar(&opts.uninstall, "uninstall", false, "Remove the hooks, the OpenCode plugin, the fallback periodic sync job, and the local session records, and stop syncing Codex and Cursor sessions.")
124 fl.StringSliceVar(&opts.agents, "agents", nil, fmt.Sprintf("Agents to sync sessions from: %s. Added to the agents set up by an earlier run. The OpenCode plugin runs for all your OpenCode sessions. Multiple agents can be comma-separated or specified by repeating the flag.", strings.Join(allAgents(), ", ")))
125 cmd.MarkFlagsMutuallyExclusive("uninstall", "no-fallback-sync")
126 cmd.MarkFlagsMutuallyExclusive("agents", "uninstall")
127 cmd.MarkFlagsMutuallyExclusive("include-history", "uninstall")
129 return cmd
132// plan is what a setup run installs.
133type plan struct {
134 claudeHooks bool
135 // openCodePlugin is the path to install the OpenCode plugin at, or empty.
136 openCodePlugin string
137 // discovered are the agents the fallback periodic sync discovers.
138 discovered []string
139 // recorded are the agent setups recorded by earlier setups.
140 recorded fallbacksync.AgentSetups
141 uploads uploadScope
144// uploadScope groups the agents a setup syncs by how far back their activity
145// is uploaded.
146type uploadScope struct {
147 fromNow []string
148 // fromEarlier are the agents an earlier setup recorded.
149 fromEarlier []string
150 history []string
153// planUploads groups agents by how far back their activity is uploaded after
154// a setup. An agent set up earlier keeps the time it was first set up and its
155// history choice, because a later setup cannot bring back what was skipped.
156func planUploads(recorded fallbacksync.AgentSetups, agents []string, history bool) uploadScope {
157 var scope uploadScope
158 for _, a := range agents {
159 setup, earlier := recorded[a]
160 switch {
161 case setup.History, !earlier && history:
162 scope.history = append(scope.history, a)
163 case earlier:
164 scope.fromEarlier = append(scope.fromEarlier, a)
165 default:
166 scope.fromNow = append(scope.fromNow, a)
167 }
168 }
169 return scope
172// setups returns the agent setups to record for a setup at now: recorded, and
173// the agents set up for the first time.
174func (s uploadScope) setups(recorded fallbacksync.AgentSetups, now time.Time) fallbacksync.AgentSetups {
175 setups := maps.Clone(recorded)
176 if setups == nil {
177 setups = fallbacksync.AgentSetups{}
178 }
179 for _, a := range s.fromNow {
180 setups[a] = fallbacksync.AgentSetup{SetUpAt: now}
181 }
182 for _, a := range s.history {
183 if _, earlier := setups[a]; !earlier {
184 setups[a] = fallbacksync.AgentSetup{SetUpAt: now, History: true}
185 }
186 }
187 return setups
190// isNew reports whether a setup recording s sets up agent for the first time.
191func (s uploadScope) isNew(recorded fallbacksync.AgentSetups, agent string) bool {
192 _, earlier := recorded[agent]
193 return !earlier && (slices.Contains(s.fromNow, agent) || slices.Contains(s.history, agent))
196const (
197 notEarlier = "not earlier sessions or the earlier turns of sessions you resume"
198 withEarlier = "including earlier sessions and the earlier turns of sessions you resume"
201// prompt says what the setup prompt agrees to upload. Agents are named only
202// when they are uploaded from different times.
203func (s uploadScope) prompt() string {
204 groups := 0
205 for _, g := range [][]string{s.fromNow, s.fromEarlier, s.history} {
206 if len(g) > 0 {
207 groups++
208 }
209 }
210 if groups == 1 {
211 switch {
212 case len(s.fromNow) > 0:
213 return ". Only activity from now on will be uploaded, " + notEarlier
214 case len(s.fromEarlier) > 0:
215 return ". Only activity from when you first set up each agent will be uploaded, " + notEarlier
216 default:
217 return ". Activity from the last 89 days and from now on will be uploaded, " + withEarlier
218 }
219 }
220 var prompt string
221 if len(s.fromNow) > 0 {
222 prompt += fmt.Sprintf(". For %s, only activity from now on will be uploaded, %s", joinAnd(s.fromNow), notEarlier)
223 }
224 if len(s.fromEarlier) > 0 {
225 pronoun := "them"
226 if len(s.fromEarlier) == 1 {
227 pronoun = "it"
228 }
229 prompt += fmt.Sprintf(". For %s, only activity from when you first set %s up will be uploaded, %s", joinAnd(s.fromEarlier), pronoun, notEarlier)
230 }
231 if len(s.history) > 0 {
232 prompt += fmt.Sprintf(". For %s, activity from the last 89 days and from now on will be uploaded, %s", joinAnd(s.history), withEarlier)
233 }
234 return prompt
237func setupPrompt(goos string, noFallbackSync bool, p plan) string {
238 var items []string
239 if p.claudeHooks {
240 items = append(items, "agent session hooks in ~/.claude/settings.json")
241 }
242 if p.openCodePlugin != "" {
243 items = append(items, "an OpenCode plugin in "+opencodeplugin.Display(p.openCodePlugin)+" that runs for all your OpenCode sessions")
244 }
245 if !noFallbackSync {
246 items = append(items, fmt.Sprintf("%s that syncs sessions in the background every %d minutes, replacing any existing job", fallbacksync.Description(goos), int(fallbacksync.Interval.Minutes())))
247 }
248 prompt := "glab will install " + joinAnd(items)
249 prompt += ". 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"
250 prompt += ". 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"
251 if !noFallbackSync && len(p.discovered) > 0 {
252 prompt += fmt.Sprintf(". The job will also upload your %s sessions the same way", strings.Join(p.discovered, " and "))
253 }
254 return prompt + p.uploads.prompt() + ". Do you wish to continue?"
257func uninstallPrompt(hooks bool, openCodePlugin string, job bool, agents []string, sessionState bool) string {
258 var items []string
259 if hooks {
260 items = append(items, "the agent session hooks from ~/.claude/settings.json")
261 }
262 if openCodePlugin != "" {
263 items = append(items, "the OpenCode plugin at "+opencodeplugin.Display(openCodePlugin))
264 }
265 if job {
266 items = append(items, "the fallback periodic sync job")
267 }
268 if sessionState {
269 items = append(items, "glab's local records of your agent sessions")
270 }
271 var prompt string
272 switch {
273 case len(items) > 0:
274 prompt = "glab will remove " + joinAnd(items)
275 if len(agents) > 0 {
276 prompt += fmt.Sprintf(". It will also stop syncing %s sessions", strings.Join(agents, " and "))
277 }
278 case len(agents) > 0:
279 prompt = fmt.Sprintf("glab will stop syncing %s sessions", strings.Join(agents, " and "))
280 default:
281 prompt = "glab will turn off session discovery"
282 }
283 return prompt + ". Do you wish to continue?"
286func joinAnd(items []string) string {
287 switch len(items) {
288 case 0:
289 return ""
290 case 1:
291 return items[0]
292 case 2:
293 return items[0] + " and " + items[1]
294 default:
295 return strings.Join(items[:len(items)-1], ", ") + ", and " + items[len(items)-1]
296 }
299func allAgents() []string {
300 return slices.Concat(fallbacksync.HookAgents, fallbacksync.DiscoverableAgents)
303func validateAgents(agents []string, changed, noFallbackSync bool) error {
304 if changed && len(agents) == 0 {
305 return cmdutils.FlagError{Err: errors.New("--agents needs at least one agent; to remove everything setup installed, use --uninstall")}
306 }
307 for _, a := range agents {
308 switch {
309 case !slices.Contains(allAgents(), a):
310 return cmdutils.FlagError{Err: fmt.Errorf("unsupported agent %q in --agents; use %s", a, strings.Join(allAgents(), ", "))}
311 case noFallbackSync && slices.Contains(fallbacksync.DiscoverableAgents, a):
312 return cmdutils.FlagError{Err: fmt.Errorf("%s sessions are only synced by the fallback periodic sync, so --agents %s cannot be used with --no-fallback-sync", a, a)}
313 }
314 }
315 return nil
318func confirm(ctx context.Context, opts *options, prompt string) (bool, error) {
319 io := opts.io
320 switch {
321 case opts.yes:
322 return true, nil
323 case !io.CanPrompt():
324 return false, fmt.Errorf("cannot prompt for confirmation in non-interactive mode; pass --yes to skip")
325 }
326 var confirmed bool
327 if err := io.Confirm(ctx, &confirmed, prompt); err != nil {
328 return false, err
329 }
330 return confirmed, nil
333func runSetup(ctx context.Context, opts *options) error {
334 io := opts.io
335 c := io.Color()
337 hookAgents, discovered, err := chosenAgents(opts)
338 if err != nil {
339 return err
340 }
341 p, err := setupPlan(opts, hookAgents, discovered)
342 if err != nil {
343 return err
344 }
346 confirmed, err := confirm(ctx, opts, setupPrompt(opts.goos, opts.noFallbackSync, p))
347 if err != nil {
348 return err
349 }
350 if !confirmed {
351 io.LogInfo("Setup cancelled.")
352 return nil
353 }
355 if p.uploads.isNew(p.recorded, "cursor") {
356 if err := startCursorSessionsAtEnd(slices.Contains(p.uploads.history, "cursor")); err != nil {
357 return fmt.Errorf("failed to record how far your Cursor sessions go: %w", err)
358 }
359 }
360 // Recorded before anything is installed, so that no hook uploads more
361 // than the user just agreed to.
362 if err := fallbacksync.SetAgentSetups(p.uploads.setups(p.recorded, time.Now())); err != nil {
363 return fmt.Errorf("failed to record when the agents were set up: %w", err)
364 }
366 if p.claudeHooks {
367 io.LogInfo("Installing agent session hooks...")
368 if err := installClaudeHooks(opts); err != nil {
369 return fmt.Errorf("failed to install agent session hooks: %w", err)
370 }
371 io.LogInfof("%s Hooks installed in ~/%s\n", c.GreenCheck(), claudehooks.SettingsFile)
372 }
373 if p.openCodePlugin != "" {
374 if _, err := opencodeplugin.Install(p.openCodePlugin); err != nil {
375 return fmt.Errorf("failed to install the OpenCode plugin: %w", err)
376 }
377 io.LogInfof("%s OpenCode plugin installed in %s\n", c.GreenCheck(), opencodeplugin.Display(p.openCodePlugin))
378 }
379 if err := fallbacksync.SetHookAgents(hookAgents); err != nil {
380 return fmt.Errorf("failed to record which agents are synced: %w", err)
381 }
383 if !opts.noFallbackSync {
384 if err := installFallbackSync(ctx, opts); err != nil {
385 io.LogErrorf("warning: could not install fallback periodic sync: %v\nAny previous fallback periodic sync job has been removed. Run 'glab minder setup' again once this is fixed.\n", err)
386 } else {
387 io.LogInfof("%s Fallback periodic sync installed: %s.\n", c.GreenCheck(), fallbacksync.Description(opts.goos))
388 }
389 }
391 if opts.agentsChanged {
392 if err := fallbacksync.SetDiscoveredAgents(discovered); err != nil {
393 return fmt.Errorf("failed to enable session discovery: %w", err)
394 }
395 if len(discovered) > 0 {
396 io.LogInfof("%s Syncing sessions from: %s.\n", c.GreenCheck(), strings.Join(discovered, ", "))
397 }
398 }
400 io.LogInfo("\nSetup complete. Run 'glab minder doctor' to verify.")
401 return nil
404// chosenAgents returns the agents to install a hook or plugin for, and the
405// agents for the fallback periodic sync to discover: those set up by an
406// earlier run, and those passed with --agents.
407func chosenAgents(opts *options) ([]string, []string, error) {
408 discovered, err := fallbacksync.DiscoveredAgents()
409 if err != nil {
410 return nil, nil, agentsReadError(err)
411 }
412 settings, err := settingsPath(opts)
413 if err != nil {
414 return nil, nil, err
415 }
416 hookAgents, err := fallbacksync.ResolvedHookAgents(settings)
417 if err != nil {
418 return nil, nil, agentsReadError(err)
419 }
420 if !opts.agentsChanged {
421 return fallbacksync.DefaultHookAgents(hookAgents, discovered), discovered, nil
422 }
424 hookAgents, discovered = slices.Clone(hookAgents), slices.Clone(discovered)
425 for _, a := range opts.agents {
426 switch {
427 case slices.Contains(hookAgents, a) || slices.Contains(discovered, a):
428 case slices.Contains(fallbacksync.HookAgents, a):
429 hookAgents = append(hookAgents, a)
430 default:
431 discovered = append(discovered, a)
432 }
433 }
434 return hookAgents, discovered, nil
437// startCursorSessionsAtEnd makes the syncing of each Cursor session start at
438// the end of its transcript as it is now. Cursor records no times, so this is
439// how sync tells a session's turns from before setup from those after. With
440// history, it does so only for transcripts last changed longer ago than glab
441// uploads, whose turns sync would otherwise time by a later change.
442func startCursorSessionsAtEnd(history bool) error {
443 transcripts, err := gaig.CursorTranscripts()
444 if err != nil {
445 return err
446 }
447 for _, t := range transcripts {
448 if history && time.Since(t.ModTime) <= gaig.MaxEventAge {
449 continue
450 }
451 if _, err := syncstate.PositionPath(t.ID); err != nil {
452 dbg.Debugf("skipping %s, which glab cannot sync: %v", t.Path, err)
453 continue
454 }
455 if err := syncstate.StartAt(t.ID, t.Size); err != nil {
456 return err
457 }
458 }
459 return nil
462func agentsReadError(err error) error {
463 return fmt.Errorf("could not tell which agents are set up: %w; %s", err, fallbacksync.AgentsReadFix(err))
466// setupPlan works out what to install for the chosen agents.
467func setupPlan(opts *options, hookAgents, discovered []string) (plan, error) {
468 p := plan{
469 claudeHooks: slices.Contains(hookAgents, "claude-code"),
470 discovered: discovered,
471 }
472 switch {
473 case opts.noFallbackSync && len(hookAgents) == 0:
474 return plan{}, cmdutils.FlagError{Err: fmt.Errorf("%s sessions are only synced by the fallback periodic sync, so they cannot be set up with --no-fallback-sync", strings.Join(discovered, " and "))}
475 case len(discovered) > 0 && !fallbacksync.Supported(opts.goos):
476 return plan{}, fmt.Errorf("%s sessions need the fallback periodic sync: %w", strings.Join(discovered, " and "), fallbacksync.ErrUnsupportedOS)
477 case p.claudeHooks && opts.goos == "windows":
478 return plan{}, errors.New("hook installation is not supported on Windows")
479 }
480 recorded, err := fallbacksync.ReadAgentSetups()
481 if err != nil {
482 return plan{}, agentsReadError(err)
483 }
484 synced := hookAgents
485 if !opts.noFallbackSync {
486 synced = slices.Concat(hookAgents, discovered)
487 }
488 if opts.includeHistory && !slices.ContainsFunc(synced, func(a string) bool { _, earlier := recorded[a]; return !earlier }) {
489 return plan{}, cmdutils.FlagError{Err: fmt.Errorf("--include-history applies only to agents set up for the first time, and every agent this setup syncs (%s) is set up already. To upload history from before an earlier setup, run 'glab minder setup --uninstall', then set up again with --include-history", strings.Join(synced, ", "))}
490 }
491 p.recorded = recorded
492 p.uploads = planUploads(recorded, synced, opts.includeHistory)
493 if !slices.Contains(hookAgents, "opencode") {
494 return p, nil
495 }
496 if opts.goos == "windows" {
497 return plan{}, errors.New("the OpenCode plugin is not supported on Windows")
498 }
499 path, err := opencodeplugin.Path()
500 if err != nil {
501 return plan{}, err
502 }
503 switch state, err := opencodeplugin.Check(path); {
504 case err != nil:
505 return plan{}, fmt.Errorf("could not read the OpenCode plugin: %w", err)
506 case state == opencodeplugin.Foreign:
507 return plan{}, opencodeplugin.ForeignError(path)
508 }
509 p.openCodePlugin = path
510 return p, nil
513func runUninstall(ctx context.Context, opts *options) error {
514 io := opts.io
515 c := io.Color()
517 home, err := os.UserHomeDir()
518 if err != nil {
519 return err
520 }
521 // An unreadable list must not block uninstall, which is the way to
522 // recover from it. It is reset with the rest.
523 agents, err := fallbacksync.DiscoveredAgents()
524 unreadable := err != nil
525 if unreadable {
526 dbg.Debugf("could not read which agents are synced: %v", err)
527 }
528 jobPresent := jobMayBePresent(ctx, opts, home)
529 // An unreadable settings file must not block removing the rest, but the
530 // user is told before confirming that its hooks will stay.
531 hooksPresent, hooksErr := claudeHooksInstalled(opts)
532 openCodePlugin, pluginErr := installedOpenCodePlugin()
533 statePresent, stateErr := sessionStatePresent()
534 // Hooks or a plugin that could not be read stay installed and would write
535 // new records, so the records are kept for a later uninstall to remove.
536 removeState := statePresent && hooksErr == nil && pluginErr == nil
537 if !jobPresent && !hooksPresent && openCodePlugin == "" && len(agents) == 0 && !unreadable && !removeState {
538 if hooksErr != nil || pluginErr != nil || stateErr != nil {
539 return errors.Join(uninstallReadErrors(hooksErr, pluginErr, stateErr)...)
540 }
541 forgetHookAgents()
542 io.LogInfo("Nothing to uninstall: no hooks, OpenCode plugin, or fallback periodic sync job found.")
543 return nil
544 }
545 if hooksErr != nil {
546 io.LogErrorf("warning: could not read ~/%s, so its hooks will not be removed: %v\n", claudehooks.SettingsFile, hooksErr)
547 }
548 if pluginErr != nil {
549 io.LogErrorf("warning: could not check for the OpenCode plugin, so it will not be removed: %v\n", pluginErr)
550 }
551 if stateErr != nil {
552 io.LogErrorf("warning: could not check glab's local records of your agent sessions, so they will not be removed: %v\n", stateErr)
553 }
555 confirmed, err := confirm(ctx, opts, uninstallPrompt(hooksPresent, openCodePlugin, jobPresent, agents, removeState))
556 if err != nil {
557 return err
558 }
559 if !confirmed {
560 io.LogInfo("Uninstall cancelled.")
561 return nil
562 }
563 forgetHookAgents()
565 // Discovery is turned off too, so a later setup does not bring it back
566 // without the user choosing it again.
567 if len(agents) > 0 || unreadable {
568 if err := fallbacksync.SetDiscoveredAgents(nil); err != nil {
569 return fmt.Errorf("failed to turn off session discovery: %w", err)
570 }
571 }
572 if len(agents) > 0 {
573 io.LogInfof("%s Stopped syncing %s sessions.\n", c.GreenCheck(), strings.Join(agents, ", "))
574 }
576 if openCodePlugin != "" {
577 removed, err := opencodeplugin.Remove(openCodePlugin)
578 switch {
579 case err != nil:
580 return fmt.Errorf("failed to remove the OpenCode plugin: %w", err)
581 case removed:
582 io.LogInfof("%s OpenCode plugin removed from %s\n", c.GreenCheck(), opencodeplugin.Display(openCodePlugin))
583 default:
584 io.LogInfo("No OpenCode plugin found.")
585 }
586 }
588 if jobPresent {
589 removed, err := fallbacksync.Uninstall(ctx, opts.executor, opts.goos, home, os.Getuid())
590 switch {
591 case err != nil:
592 return fmt.Errorf("failed to remove fallback periodic sync: %w", err)
593 case removed:
594 io.LogInfof("%s Fallback periodic sync removed.\n", c.GreenCheck())
595 default:
596 io.LogInfo("No fallback periodic sync job found.")
597 }
598 }
600 if hooksPresent {
601 removed, err := removeClaudeHooks(opts)
602 switch {
603 case err != nil:
604 return fmt.Errorf("failed to remove agent session hooks: %w", err)
605 case removed:
606 io.LogInfof("%s Hooks removed from ~/%s\n", c.GreenCheck(), claudehooks.SettingsFile)
607 default:
608 io.LogInfo("No agent session hooks found.")
609 }
610 }
612 // Removed last, after the job and the hooks that write to it.
613 if removeState {
614 if err := os.RemoveAll(gaig.StateDir()); err != nil {
615 return fmt.Errorf("failed to remove the local records of your agent sessions: %w", err)
616 }
617 io.LogInfof("%s Local records of your agent sessions removed.\n", c.GreenCheck())
618 }
619 return errors.Join(uninstallReadErrors(hooksErr, pluginErr, stateErr)...)
622func sessionStatePresent() (bool, error) {
623 entries, err := os.ReadDir(gaig.StateDir())
624 switch {
625 case errors.Is(err, fs.ErrNotExist):
626 return false, nil
627 case err != nil:
628 return false, err
629 }
630 return len(entries) > 0, nil
633// uninstallReadErrors reports what uninstall left in place because it could
634// not be read.
635func uninstallReadErrors(hooksErr, pluginErr, stateErr error) []error {
636 var errs []error
637 if hooksErr != nil {
638 errs = append(errs, fmt.Errorf("the agent session hooks were not removed; fix ~/%s and run 'glab minder setup --uninstall' again: %w", claudehooks.SettingsFile, hooksErr))
639 }
640 if pluginErr != nil {
641 errs = append(errs, fmt.Errorf("the OpenCode plugin may still be installed; fix it and run 'glab minder setup --uninstall' again: %w", pluginErr))
642 }
643 if stateErr != nil {
644 errs = append(errs, fmt.Errorf("glab's local records of your agent sessions were not removed; fix %s and run 'glab minder setup --uninstall' again: %w", gaig.StateDir(), stateErr))
645 }
646 return errs
649// forgetHookAgents forgets the agents chosen by an earlier setup, so that a
650// later setup starts from the default agents again.
651func forgetHookAgents() {
652 if err := fallbacksync.ForgetHookAgents(); err != nil {
653 dbg.Debugf("could not forget which agents are synced: %v", err)
654 }
657// installedOpenCodePlugin returns the path of the OpenCode plugin glab
658// installed, or an empty string when there is none.
659func installedOpenCodePlugin() (string, error) {
660 path, err := opencodeplugin.Path()
661 if err != nil {
662 return "", err
663 }
664 state, err := opencodeplugin.Check(path)
665 if err != nil || state == opencodeplugin.NotInstalled || state == opencodeplugin.Foreign {
666 return "", err
667 }
668 return path, nil
671func claudeHooksInstalled(opts *options) (bool, error) {
672 path, err := settingsPath(opts)
673 if err != nil {
674 return false, err
675 }
676 raw, err := claudehooks.LoadRawSettings(path)
677 if err != nil {
678 return false, err
679 }
680 hooks, err := claudehooks.HooksFromRaw(raw)
681 if err != nil {
682 return false, err
683 }
684 return claudehooks.GlabHookPresent(hooks, "Stop") || claudehooks.GlabHookPresent(hooks, "SessionEnd"), nil
687// jobMayBePresent reports whether uninstall has anything to remove: the job's
688// files, or a job still loaded after its files were deleted. When either
689// check fails, it errs towards true so that uninstall still runs.
690func jobMayBePresent(ctx context.Context, opts *options, home string) bool {
691 _, err := fallbacksync.InstalledBinary(opts.goos, home)
692 switch {
693 case errors.Is(err, fallbacksync.ErrUnsupportedOS):
694 return false
695 case !errors.Is(err, fallbacksync.ErrNotInstalled):
696 return true
697 }
698 state, err := fallbacksync.State(ctx, opts.executor, opts.goos, os.Getuid())
699 if err != nil {
700 dbg.Debugf("could not check whether the fallback job is loaded: %v", err)
701 return true
702 }
703 return state.Loaded
706func settingsPath(opts *options) (string, error) {
707 if opts != nil && opts.settingsPathOverride != "" {
708 return opts.settingsPathOverride, nil
709 }
710 return claudehooks.SettingsPath()
713func installClaudeHooks(opts *options) error {
714 if runtime.GOOS == "windows" {
715 return fmt.Errorf("hook installation is not supported on Windows")
716 }
718 path, err := settingsPath(opts)
719 if err != nil {
720 return err
721 }
723 raw, err := claudehooks.LoadRawSettings(path)
724 if err != nil {
725 return err
726 }
728 hooks, err := claudehooks.HooksFromRaw(raw)
729 if err != nil {
730 return err
731 }
733 if !claudehooks.InstallGlabHooks(hooks) {
734 return nil
735 }
737 hooksJSON, err := claudehooks.MarshalHooks(hooks)
738 if err != nil {
739 return fmt.Errorf("could not serialise hooks: %w", err)
740 }
741 raw["hooks"] = hooksJSON
743 return claudehooks.WriteSettings(path, raw)
746func removeClaudeHooks(opts *options) (bool, error) {
747 path, err := settingsPath(opts)
748 if err != nil {
749 return false, err
750 }
752 raw, err := claudehooks.LoadRawSettings(path)
753 if err != nil {
754 return false, err
755 }
757 hooks, err := claudehooks.HooksFromRaw(raw)
758 if err != nil {
759 return false, err
760 }
762 if !claudehooks.RemoveGlabHooks(hooks) {
763 return false, nil
764 }
766 if len(hooks) == 0 {
767 delete(raw, "hooks")
768 return true, claudehooks.WriteSettings(path, raw)
769 }
771 hooksJSON, err := claudehooks.MarshalHooks(hooks)
772 if err != nil {
773 return false, fmt.Errorf("could not serialise hooks: %w", err)
774 }
775 raw["hooks"] = hooksJSON
777 return true, claudehooks.WriteSettings(path, raw)
780func installFallbackSync(ctx context.Context, opts *options) error {
781 home, err := os.UserHomeDir()
782 if err != nil {
783 return err
784 }
785 glabPath, err := glabBinaryPath(ctx, opts.executor, opts.buildInfo)
786 if err != nil {
787 return err
788 }
789 job := fallbacksync.Job{GlabPath: glabPath, ConfigDir: config.ConfigDir()}
790 return fallbacksync.Install(ctx, opts.executor, opts.goos, home, job, os.Getuid())
793// glabBinaryPath returns the path the scheduled job should run: the glab on
794// PATH if it is the same build as the running glab, otherwise the running
795// glab. Symlinks are deliberately left unresolved: package managers such as
796// Homebrew, asdf, and mise point a stable path (or shim) at a versioned
797// install directory that is deleted on upgrade. Builds are compared by
798// version rather than by file, because a shim is a different file from the
799// binary it runs.
800func glabBinaryPath(ctx context.Context, executor cmdutils.Executor, running api.BuildInfo) (string, error) {
801 want := fallbacksync.BuildVersion(running)
802 onPath, err := executor.LookPath("glab")
803 if err != nil {
804 dbg.Debugf("glab is not in PATH, scheduling the running glab: %v", err)
805 } else {
806 got, err := fallbacksync.BinaryVersion(ctx, executor, onPath)
807 switch {
808 case err != nil:
809 dbg.Debugf("could not run %s version, scheduling the running glab: %v", onPath, err)
810 case got != want:
811 dbg.Debugf("%s reports %q, not %q, scheduling the running glab", onPath, got, want)
812 default:
813 return filepath.Abs(onPath)
814 }
815 }
816 path, err := os.Executable()
817 if err != nil {
818 return "", fmt.Errorf("could not find glab binary: %w", err)
819 }
820 return filepath.Abs(path)
Diagnostics8 git calls · 299 ms
CallStatusSizeTime0299 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
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 KiB2 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=UPDATING
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
fetchtree:0 · deepen 1020032 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=32926
git.response.cache=HIT
git.response.duration_ms=2
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
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=4
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:02001.8 KiB · hit4 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=1857
git.response.cache=HIT
git.response.duration_ms=4
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 · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=282
git.response.bytes=198
git.response.cache=HIT
git.response.duration_ms=4
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
fetch2008.5 KiB282 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=8673
git.response.cache=MISS
git.response.duration_ms=282
git.fetch.wants=7a80a6b6f49ee61a5581e12672894e61a796cbda
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=8673
git.pkt.payload.max=8646
git.sideband.band1.bytes=8646
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
a5e224e4e9aaa87d
Request
a77ab674…
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