From ac38b743f643cf280b14016bc0d050ec79c59eac Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 15:01:15 +0000 Subject: [PATCH 1/2] feat(cli): install Cursor and Antigravity hooks globally with --global `shelltime cursor install --global` and `shelltime agy install --global` write ~/.cursor/hooks.json and a `shelltime-global` group of ~/.gemini/config/hooks.json, which the agents run in every folder (never in their cloud runs). The global command is the project's self-contained one without --project, so a moved or removed shelltime never fails a hook, and it rewrites what older versions left there (absolute binary paths, the global `shelltime` group) in place. A project's hook still leaves an event to the global hooks when they record it: userHooksRecord now also counts the --global command (AgentHooksStatus.GlobalEvents), which finds the binaries wherever the project's does. The global Antigravity group is named apart from the project's in case a workspace group replaces a global one of the same name. `uninstall --global` cleans only the global file. doctor checks the global file in and outside repositories: an older version's hooks with a missing binary fail and a copied project command warns, both fixed by `install --global`, and a repository without hooks of its own is only a note while global hooks are installed. init mentions --global. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRfhTSPrQA29S15UhWm --- CLAUDE.md | 2 +- README.md | 10 +- agenthook/event.go | 2 +- commands/agent_hooks_cmd_test.go | 118 +++++++++++++++++- commands/agent_hooks_install.go | 111 +++++++++++------ commands/agy.go | 26 +++- commands/cursor.go | 26 +++- commands/doctor_checks.go | 197 +++++++++++++++++++----------- commands/doctor_test.go | 84 ++++++++++--- commands/hook_ingest.go | 31 +++-- commands/hook_ingest_test.go | 60 +++++++++ commands/init.go | 6 +- commands/init_output_test.go | 4 +- daemon/agent_hooks.go | 2 +- docs/CONFIG.md | 2 +- model/agent_hooks_common.go | 69 +++++++---- model/agent_hooks_project_test.go | 102 ++++++++++++++-- model/antigravity_hooks.go | 132 ++++++++++++++------ model/cursor_hooks.go | 48 +++++--- 19 files changed, 785 insertions(+), 247 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index cc2f478..9977a66 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -109,7 +109,7 @@ Optional daemon services (feature-gated via config): - **AICodeOtelServer**: gRPC OTEL collector for AI coding CLI metrics, logs and traces (Claude Code, Codex). Spans (`claude_code.interaction`, `llm_request`, `tool`, ...) go to the same `/api/v1/cc/otel` endpoint in `spans`; a span without `session.id` takes it from another span of its trace in the same export. `shelltime cc install` turns traces on (`CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, `OTEL_TRACES_EXPORTER=otlp`). In a Claude Code cloud session (`CLAUDE_CODE_REMOTE=true`, where the SessionStart hook starts the daemon) it adds the VM's `CLAUDE_CODE_REMOTE_SESSION_ID` as the `ccr.session.id` attribute to Claude Code records that lack it; the server marks those sessions as cloud sessions. `daemon/main_test.go` clears both variables so tests behave the same inside a cloud session - **Git repositories** (`model/git_repository.go`): the server groups coding agent sessions into projects by git repository, not folder, so a renamed or moved clone, a worktree or a subfolder stays one project. `GitRepositoryResolver` asks the git CLI (found through `CommandService`, so the daemon's limited PATH reaches Homebrew) for a directory's top level and its `origin` remote (else `upstream`, else the first by name; `remote get-url`, so `insteadOf` applies) without optional locks, within one 2 s budget per lookup, since the daemon resolves on the OTLP export path. Concurrent lookups of one directory share one run, which goes on its own goroutine: a stat or git blocked in the kernel (a hung network mount) ignores the context, so the lookup is given up on after the budget (plus `gitRepositoryGrace`), or when its caller's context ends, and the directory gets no other until it returns (its answer is kept then). git runs with `LC_ALL=C`, since its messages are read; a remote's path segments are decoded and escaped again (`url.PathEscape`), like the server's. A migration run stops asking after `projectMigrationMaxUnanswered` folders' stats timed out (a hung mount; git refusing a folder doesn't count), and a folder that doesn't exist counts as missing, one it can't stat otherwise as unchecked. git refusing a repository it doesn't trust (`safe.directory`) or killed by a signal is no answer about the directory; a git binary not found is looked for again every 30 s. It keeps definitive answers, negative ones too (10 min in the daemon), and a timeout or git failing to start for 30 s only, reported as unknown by `Lookup` (`Resolve` drops the flag). `CanonicalRepositoryURL` turns any remote into `https:///` without credentials, port or `.git`, the form Claude Code reports; a local path is no repository. The repository travels as `vcs.repository.url.full` (`model.AICodeRepositoryAttribute`): the OTEL processor adds it to metrics and log events whose resource has a `pwd` and that don't name one (not to spans: the server keys a session from its events), and never when the resource names one (Claude Code's own value wins; git isn't asked then), the socket's `session_project` handler sends it with the statusline's directory, and backfill adds it to uploaded events (Codex's `session_meta.git.repository_url` first, since it was true when the session ran, else the transcript directory's). `aiCodeOtel.sendRepository: false` (`ShellTimeConfig.SendsRepository`) turns all of it off: no resolver in the processor or the socket, the processor removes the attribute from every record (the agent's own too), backfill attaches none, and neither the daemon nor `cc projects` migrates - **Project migration** (`daemon/project_migration.go`, `model/project_migration.go`): sessions recorded before the repository was sent are folder projects on the server. A while after start the daemon runs `MigrateProjectRepositories` once, never in AI cloud only mode (marker `~/.shelltime/project-repositories.v1`, written only when the run is `Complete`: a 404 from an older server, a failure, more pages than one run goes through (50), a folder git couldn't answer for, or a machine without a host name of its own leaves none, so the next start tries again): it lists the folder projects of this machine's names (`ProjectMigrationHosts`: the host name, without its domain, and the `machine.name` in `~/.claude/settings.json`, leaving out names many machines share, like `localhost`, `genericHostNames`) from `POST /api/v1/cc/projects/unresolved`, a page at a time by the last project of the page (`after`), and posts the folders that still exist and are clones to `POST /api/v1/cc/projects/repositories`. `shelltime cc projects` / `shelltime codex projects` run it by hand (`--dry-run` lists what would move; skipped in AI cloud only mode) -- **Agent hooks (Cursor, Antigravity)**: neither has OTEL, so `shelltime cursor install` / `shelltime agy install` (`commands/agent_hooks_install.go`; `model/cursor_hooks.go`, `model/antigravity_hooks.go`, on the ordered-JSON kit of `model/aicode_otel_claude_settings.go`) register the hidden `shelltime hook-ingest --agent cursor|agy --event --project` in the current repository's `.cursor/hooks.json` and in a `shelltime` group of its `.agents/hooks.json` (`model.ProjectHooksRoot`: the nearest folder up with `.git` below the home folder, else the folder itself, never the home folder, `ErrHomeIsNotAProject`), the only files Cursor Cloud Agents and the Antigravity agent's Gemini API sandbox run (never PreToolUse: a reply without a decision denies the tool; a file with a BOM, comments or invalid JSON is refused, never rewritten). Installing into a user-level file is refused (`ErrUserHooksRetired`), and so is Windows (`ErrProjectHooksUnsupported`: no daemon there); install leaves what older versions put in `~/.cursor/hooks.json` / `~/.gemini/config/hooks.json` (they still record every other folder) and says so, uninstall removes it (a user file it can't read is a warning, never a failure), and doctor's fix removes it when its binary is gone. The file is committed and the agents disagree on the folder a hook runs in, so each command is self-contained POSIX sh (`projectHookCommand`): it adds `model.ProjectHookSearchDirs` (`~/.shelltime/bin`, `/opt/homebrew/bin`, `/usr/local/bin`; doctor checks the same) to PATH, runs hook-ingest only when `shelltime` and `shelltime-daemon` are both found, and echoes the pass-through reply otherwise or when hook-ingest fails (a `shelltime` from before it exits non-zero; its stdout is dropped). A `--project` run whose event an older version's user-level hook records too (`userHooksRecord`: the user file registers that event with an absolute, executable binary, `AgentHooksStatus.EventBinaries`; Antigravity hooks and groups marked `"enabled": false` don't count) and that isn't cloud goes to the daemon with `YieldToUserHooks`, and the batcher drops it unless its session is cloud (Cloud Agents run no user-level hooks; Cursor marks only `sessionStart`); without a daemon hook-ingest drops it. The mark never reaches the server (`prepareAgentHookEvents` clears it). `hook-ingest` writes nothing to stdout but `agenthook.PassThrough` (`{"continue":true}` for Cursor's beforeSubmitPrompt, `{"decision":"allow"}` for Antigravity's Stop, else `{}`), exactly once, even on a panic, and exits 0. The `agenthook` package (no dependency on `model`) normalizes the payloads into `agenthook.Event`; for successful `gh pr create` or GitHub MCP `create_pull_request` tool calls (`agenthook/pr.go`), it also extracts normalized PR URLs from Cursor `tool_output` (or Antigravity `transcript.jsonl` / output fields) into daemon-only `PullRequestURLs` without keeping raw tool output. Each event's `cloud` names what showed it ran in a cloud agent's VM (`agenthook.cloudSignal`): Cursor's `is_background_agent` (only in `sessionStart`) or, for Antigravity, the OS user `antigravity` (`agenthook.InAntigravitySandbox`: the user database, else `USER`/`LOGNAME`), else `SHELLTIME_CLOUD=true` or `CLAUDE_CODE_REMOTE=true` in the hook's environment (`agenthook.CloudEnvSignal`), and an explicit `SHELLTIME_CLOUD=false` overrides them all (`agenthook.CloudEnvExplicit`); neither agent marks every hook of a cloud run, and Cursor's `CURSOR_CODE_REMOTE` (any remote workspace, the user's SSH hosts too) is only `metadata.remote_workspace`. An Antigravity remote agent (antigravity.google.com/remote) runs outside its VM and runs no hook there: it sends each command in as `bash -l -c ` with `JULES_SESSION_ID` set, so `cloud.bash` (installation repo) adds a login profile script that pipes each command to `shelltime hook-ingest --agent agy --event ShellCommand --session --exit-code [--duration-ms ]` when its shell exits. That mode (`agenthook.NormalizeShellCommand`, Antigravity only) records the command as a `run_command` call (`tool_failure` with `exit status ` when non-zero; `metadata.exit_code`, `metadata.source = login_shell`), the working directory as the workspace, writes nothing to stdout and drops the command on a usage error. hook-ingest hands it to the daemon (`agent_hook` socket message, acknowledged within 50 ms) or, without one, applies `model.ApplyAgentHookPrivacy` and appends it to `~/.shelltime/agent-hooks.pending.jsonl`; a payload over 4 MiB is recorded from its first 4 MiB, marked `truncated` (`agenthook.NormalizeTruncated`: the top-level fields before the cut). `AgentHookBatcher` (`daemon/agent_hooks.go`) marks the later events of a session an event showed was cloud (for an hour after its last event, `fillCloudLocked`) and sends batches to `POST /api/v1/agent-hooks` every 2 s or 100 events (stripping `PullRequestURLs` from the wire payload and dispatching `model.SendSessionPullRequests` to `POST /api/v1/cc/session-pull-requests` once a chunk succeeds, deduplicated per session+URL within `agentHookSessionTTL` and honoring `Exclude`), readied by `prepareAgentHookEvents` (the workspace's repository under `aiCodeOtel.sendRepository`, and the privacy settings, `agentHooks.sendContent` included, from the config on disk), and saves what can be sent later (no token, the failures `agentHookSendCanWait` names, a 404/405 from a server without the endpoint among them) for `AgentHookResyncService` (30-min interval), which readies saved events and dispatches their saved `PullRequestURLs` the same way; both run in AI cloud only mode too. hook-ingest and the daemon share the pending file under `agent-hooks.pending.lock`, an advisory flock like the command store's: appends hold it shared and the resync's read-and-rewrite exclusively, nobody waits more than 50 ms (an append then goes ahead, a rewrite returns `ErrAgentHookPendingBusy` and the pass changes nothing), and a rewrite carries over the lines appended since its read +- **Agent hooks (Cursor, Antigravity)**: neither has OTEL, so `shelltime cursor install` / `shelltime agy install` (`commands/agent_hooks_install.go`; `model/cursor_hooks.go`, `model/antigravity_hooks.go`, on the ordered-JSON kit of `model/aicode_otel_claude_settings.go`) register the hidden `shelltime hook-ingest --agent cursor|agy --event --project` in the current repository's `.cursor/hooks.json` and in a `shelltime` group of its `.agents/hooks.json` (`model.ProjectHooksRoot`: the nearest folder up with `.git` below the home folder, else the folder itself, never the home folder, `ErrHomeIsNotAProject`), the only files Cursor Cloud Agents and the Antigravity agent's Gemini API sandbox run (never PreToolUse: a reply without a decision denies the tool; a file with a BOM, comments or invalid JSON is refused, never rewritten). With `--global` they write the user-level `~/.cursor/hooks.json` / a `shelltime-global` group of `~/.gemini/config/hooks.json` instead (`NewCursorHooksService`, `NewAntigravityHooksService`; named apart from the project's group in case Antigravity lets a workspace group replace a global one of the same name), which the agents run in every folder but never in their cloud runs, with the same command minus `--project`; that install rewrites what older versions put there (an absolute binary path, and the global `shelltime` group) in place. Windows is refused (`ErrProjectHooksUnsupported`: no daemon there). Project install says when global hooks are installed; `uninstall` cleans both files (a global file it can't read is a warning, never a failure), `uninstall --global` only the global one. doctor checks the global file in and outside repositories: an older version's hooks whose binary is gone fail, a project's command copied there warns (it would count events twice), both with `install --global` as the fix, and a repository without its own hooks is only a note while global hooks are installed. A project's file is committed, a global one may be synced to other machines with the home folder, and the agents disagree on the folder a hook runs in, so each command is self-contained POSIX sh (`hookCommand`): it adds `model.ProjectHookSearchDirs` (`~/.shelltime/bin`, `/opt/homebrew/bin`, `/usr/local/bin`; doctor checks the same) to PATH, runs hook-ingest only when `shelltime` and `shelltime-daemon` are both found, and echoes the pass-through reply otherwise or when hook-ingest fails (a `shelltime` from before it exits non-zero; its stdout is dropped). A `--project` run whose event the global hook file records too (`userHooksRecord`: the file registers that event with the `--global` command, `AgentHooksStatus.GlobalEvents`, which finds the binaries wherever the project's does, or with an older version's absolute, executable binary, `AgentHooksStatus.EventBinaries`; a project's command copied there never counts, and Antigravity hooks and groups marked `"enabled": false` don't either) and that isn't cloud goes to the daemon with `YieldToUserHooks`, and the batcher drops it unless its session is cloud (Cloud Agents run no user-level hooks; Cursor marks only `sessionStart`); without a daemon hook-ingest drops it. The mark never reaches the server (`prepareAgentHookEvents` clears it). `hook-ingest` writes nothing to stdout but `agenthook.PassThrough` (`{"continue":true}` for Cursor's beforeSubmitPrompt, `{"decision":"allow"}` for Antigravity's Stop, else `{}`), exactly once, even on a panic, and exits 0. The `agenthook` package (no dependency on `model`) normalizes the payloads into `agenthook.Event`; for successful `gh pr create` or GitHub MCP `create_pull_request` tool calls (`agenthook/pr.go`), it also extracts normalized PR URLs from Cursor `tool_output` (or Antigravity `transcript.jsonl` / output fields) into daemon-only `PullRequestURLs` without keeping raw tool output. Each event's `cloud` names what showed it ran in a cloud agent's VM (`agenthook.cloudSignal`): Cursor's `is_background_agent` (only in `sessionStart`) or, for Antigravity, the OS user `antigravity` (`agenthook.InAntigravitySandbox`: the user database, else `USER`/`LOGNAME`), else `SHELLTIME_CLOUD=true` or `CLAUDE_CODE_REMOTE=true` in the hook's environment (`agenthook.CloudEnvSignal`), and an explicit `SHELLTIME_CLOUD=false` overrides them all (`agenthook.CloudEnvExplicit`); neither agent marks every hook of a cloud run, and Cursor's `CURSOR_CODE_REMOTE` (any remote workspace, the user's SSH hosts too) is only `metadata.remote_workspace`. An Antigravity remote agent (antigravity.google.com/remote) runs outside its VM and runs no hook there: it sends each command in as `bash -l -c ` with `JULES_SESSION_ID` set, so `cloud.bash` (installation repo) adds a login profile script that pipes each command to `shelltime hook-ingest --agent agy --event ShellCommand --session --exit-code [--duration-ms ]` when its shell exits. That mode (`agenthook.NormalizeShellCommand`, Antigravity only) records the command as a `run_command` call (`tool_failure` with `exit status ` when non-zero; `metadata.exit_code`, `metadata.source = login_shell`), the working directory as the workspace, writes nothing to stdout and drops the command on a usage error. hook-ingest hands it to the daemon (`agent_hook` socket message, acknowledged within 50 ms) or, without one, applies `model.ApplyAgentHookPrivacy` and appends it to `~/.shelltime/agent-hooks.pending.jsonl`; a payload over 4 MiB is recorded from its first 4 MiB, marked `truncated` (`agenthook.NormalizeTruncated`: the top-level fields before the cut). `AgentHookBatcher` (`daemon/agent_hooks.go`) marks the later events of a session an event showed was cloud (for an hour after its last event, `fillCloudLocked`) and sends batches to `POST /api/v1/agent-hooks` every 2 s or 100 events (stripping `PullRequestURLs` from the wire payload and dispatching `model.SendSessionPullRequests` to `POST /api/v1/cc/session-pull-requests` once a chunk succeeds, deduplicated per session+URL within `agentHookSessionTTL` and honoring `Exclude`), readied by `prepareAgentHookEvents` (the workspace's repository under `aiCodeOtel.sendRepository`, and the privacy settings, `agentHooks.sendContent` included, from the config on disk), and saves what can be sent later (no token, the failures `agentHookSendCanWait` names, a 404/405 from a server without the endpoint among them) for `AgentHookResyncService` (30-min interval), which readies saved events and dispatches their saved `PullRequestURLs` the same way; both run in AI cloud only mode too. hook-ingest and the daemon share the pending file under `agent-hooks.pending.lock`, an advisory flock like the command store's: appends hold it shared and the resync's read-and-rewrite exclusively, nobody waits more than 50 ms (an append then goes ahead, a rewrite returns `ErrAgentHookPendingBusy` and the pass changes nothing), and a rewrite carries over the lines appended since its read - **HeartbeatResyncService**: Periodic resync of failed heartbeats (30-min interval) - **CleanupTimerService**: Periodic log file cleanup (24-hour interval) diff --git a/README.md b/README.md index 9e8afd7..cf4a667 100644 --- a/README.md +++ b/README.md @@ -211,14 +211,18 @@ Besides tokens and cost, both tools then send your prompts, tool details (shell Cursor and Google Antigravity have no OpenTelemetry export, so ShellTime reads their native hooks instead: the agent runs `shelltime hook-ingest` for each event with the event's JSON on stdin, and ShellTime answers with the reply that lets the agent carry on. It never blocks, denies or changes anything the agent does. -The hooks go into each project's repository, the only place the agents' cloud runs read them from (Cursor Cloud Agents never read `~/.cursor/hooks.json`, and Antigravity runs a workspace's hooks ahead of its global file). Run the install in the repository, then commit the file: +The hooks go into each project's repository by default, the only place the agents' cloud runs read them from (Cursor Cloud Agents never read `~/.cursor/hooks.json`, and the Antigravity agent's Gemini API sandbox reads only the repository's `.agents/hooks.json`). Run the install in the repository, then commit the file: - **Cursor**: `shelltime cursor install` registers `beforeSubmitPrompt`, `postToolUse`, `postToolUseFailure`, `afterAgentResponse`, `stop`, `sessionStart` and `sessionEnd` in `.cursor/hooks.json` at the repository's root. Your other hooks stay as they are. - **Antigravity**: `shelltime agy install` adds a `shelltime` hook group (`SessionStart`, `PreInvocation`, `PostToolUse`, `PostInvocation`, `Stop`) to `.agents/hooks.json` at the repository's root. Antigravity ignores the whole file when it isn't strict JSON, so a file with comments, trailing commas or a byte order mark is left alone with an error, never rewritten. -Outside a repository the current folder counts as the project, but never your home folder. Hooks older versions put in `~/.cursor/hooks.json` or `~/.gemini/config/hooks.json` stay and keep tracking your other folders; a repository's own hooks leave events to them, so nothing is counted twice. `uninstall` takes ShellTime out of the repository's file and those. Restart the agent after installing. The hooks need macOS or Linux: `shelltime-daemon` doesn't run on Windows, and the install refuses there (a committed hook file fails on a Windows collaborator's machine, which Cursor logs and carries on from). +Outside a repository the current folder counts as the project, but never your home folder. -Each hook is one self-contained shell command, the same on every machine that checks the repository out: it records the event only where `shelltime` and `shelltime-daemon` are installed (on `PATH`, or in `~/.shelltime/bin`, `/opt/homebrew/bin` or `/usr/local/bin`, which an app started from the Dock may not have on its `PATH`), each to that machine's ShellTime account, and anywhere else just lets the agent carry on, so collaborators without ShellTime see no failing hooks. Events go to the daemon, which sends them in batches; while it isn't running they wait in `~/.shelltime/agent-hooks.pending.jsonl` until it sends them. The hooks send your prompts, the agent's responses, tool names and inputs (shell commands, file paths), per-turn token counts and the workspace folder; tool output is never read. Data masking and your exclude patterns apply (an event whose shell command matches one is sent without the command, prompt, response, tool input or error), and `shelltime config disable agentHooks.sendContent` keeps the text of prompts, responses, tool input and errors, and the paths of files attached to prompts, out, so only the activity and token usage are sent. `shelltime doctor`, run in a repository, checks its hook file and that the hooks can find both binaries. +To track every folder on this machine instead, add `--global`: `shelltime cursor install --global` writes `~/.cursor/hooks.json`, and `shelltime agy install --global` writes a `shelltime-global` group to `~/.gemini/config/hooks.json`, both of which the agent runs wherever you open it. Nothing is committed, and the cloud runs above don't read these files, so a repository whose cloud agents you want tracked still needs its own hooks. You can have both: a repository's hooks leave events to the global ones, so nothing is counted twice. `--global` also rewrites the hooks older versions put in those files (which named the `shelltime` binary by its path) into the self-contained command below. + +`uninstall` takes ShellTime out of the repository's file and the global one; `uninstall --global` only out of the global one. Restart the agent after installing. The hooks need macOS or Linux: `shelltime-daemon` doesn't run on Windows, and the install refuses there (a committed hook file fails on a Windows collaborator's machine, which Cursor logs and carries on from). + +Each hook is one self-contained shell command, the same on every machine that checks the repository out: it records the event only where `shelltime` and `shelltime-daemon` are installed (on `PATH`, or in `~/.shelltime/bin`, `/opt/homebrew/bin` or `/usr/local/bin`, which an app started from the Dock may not have on its `PATH`), each to that machine's ShellTime account, and anywhere else just lets the agent carry on, so collaborators without ShellTime see no failing hooks. Events go to the daemon, which sends them in batches; while it isn't running they wait in `~/.shelltime/agent-hooks.pending.jsonl` until it sends them. The hooks send your prompts, the agent's responses, tool names and inputs (shell commands, file paths), per-turn token counts and the workspace folder; tool output is never read. Data masking and your exclude patterns apply (an event whose shell command matches one is sent without the command, prompt, response, tool input or error), and `shelltime config disable agentHooks.sendContent` keeps the text of prompts, responses, tool input and errors, and the paths of files attached to prompts, out, so only the activity and token usage are sent. `shelltime doctor` checks the global hook files and, run in a repository, the repository's, and that the hooks can find both binaries. Token usage (used to calculate estimated USD cost on the server) is captured per turn: Cursor reports token counts directly on its `stop` hook payload, while Google Antigravity's `PostInvocation` hook reads completed model steps from the local `.jsonl` transcript file referenced by `transcriptPath` (when the file is missing, unreadable, or has no matching completed steps, activity is still recorded without token counts). diff --git a/agenthook/event.go b/agenthook/event.go index 81a9c10..639c492 100644 --- a/agenthook/event.go +++ b/agenthook/event.go @@ -88,7 +88,7 @@ type Event struct { Metadata map[string]any `json:"metadata,omitempty"` // YieldToUserHooks travels from hook-ingest to the daemon only, never to the server: the - // event came from a project's hook while an older version's user-level hook records it too, + // event came from a project's hook while the agent's user-level (global) hook records it too, // so the daemon drops it unless the session is a cloud run (whose agent runs no user-level // hooks), which only the daemon remembers across events. YieldToUserHooks bool `json:"yield_to_user_hooks,omitempty"` diff --git a/commands/agent_hooks_cmd_test.go b/commands/agent_hooks_cmd_test.go index beafc43..bbaecc4 100644 --- a/commands/agent_hooks_cmd_test.go +++ b/commands/agent_hooks_cmd_test.go @@ -42,8 +42,8 @@ func TestCursorInstallAndUninstallCommands(t *testing.T) { require.NoError(t, app.Run([]string{"t", "cursor", "install"})) text := stripANSI(out.String()) assert.Contains(t, text, "Cursor hooks installed in "+path) - assert.Contains(t, text, "The ShellTime hooks an older version put in "+userPath+" stay and keep recording your other folders") - assert.Contains(t, text, "`shelltime cursor uninstall` removes both.") + assert.Contains(t, text, "The ShellTime hooks in "+userPath+" keep recording your other folders") + assert.Contains(t, text, "nothing is counted twice. `shelltime cursor uninstall` removes both.") assert.Contains(t, text, "Commit it: Cursor Cloud Agents run only the hooks in the repository.") assert.Contains(t, text, "Restart Cursor") assert.Contains(t, text, "SHELLTIME_CLOUD=true") @@ -104,8 +104,118 @@ func TestCursorInstallCommand_RefusesTheHomeFolder(t *testing.T) { out := captureColor(t) err := app.Run([]string{"t", "cursor", "install"}) assert.ErrorIs(t, err, model.ErrHomeIsNotAProject) - assert.Contains(t, stripANSI(out.String()), "Failed to find the project") - assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json"), "Cursor's user-level file is never written") + text := stripANSI(out.String()) + assert.Contains(t, text, "Failed to find the project") + assert.Contains(t, text, "To track Cursor in every folder on this machine, run `shelltime cursor install --global`.") + assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json"), "Cursor's user-level file isn't written without --global") +} + +func TestCursorInstallCommand_Global(t *testing.T) { + home, repo := setupAgentHooksCommand(t) + t.Chdir(home) + userPath := filepath.Join(home, ".cursor", "hooks.json") + // What an older version installed there, next to the user's own hook + installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "/usr/local/bin/shelltime") + var file map[string]any + require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &file)) + file["hooks"].(map[string]any)["stop"] = append([]any{map[string]any{"command": "say done"}}, file["hooks"].(map[string]any)["stop"].([]any)...) + data, err := json.Marshal(file) + require.NoError(t, err) + require.NoError(t, os.WriteFile(userPath, data, 0644)) + app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}} + + out := captureColor(t) + require.NoError(t, app.Run([]string{"t", "cursor", "install", "--global"})) + text := stripANSI(out.String()) + assert.Contains(t, text, "Cursor hooks installed in "+userPath) + assert.Contains(t, text, "They record Cursor in every folder on this machine") + assert.Contains(t, text, "Cursor Cloud Agents run only a repository's .cursor/hooks.json") + assert.Contains(t, text, "Restart Cursor") + assert.Contains(t, text, "Privacy: the Cursor hooks send your prompts") + assert.NotContains(t, text, "Commit it", "nothing to commit") + + status, err := model.NewCursorHooksService().Status() + require.NoError(t, err) + assert.Empty(t, status.MissingEvents) + assert.Equal(t, agenthook.CursorEvents, status.GlobalEvents) + assert.Equal(t, []string{model.ProjectHookCLI}, status.Binaries, "the older version's absolute path is replaced") + require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &file)) + stop := file["hooks"].(map[string]any)["stop"].([]any) + require.Len(t, stop, 2) + assert.Equal(t, "say done", stop[0].(map[string]any)["command"], "the user's own hook stays first") + assert.Equal(t, model.CursorGlobalHookCommand("stop"), stop[1].(map[string]any)["command"]) + + // Both can be installed; --global uninstall leaves the repository's file + t.Chdir(repo) + out.Reset() + require.NoError(t, app.Run([]string{"t", "cursor", "install"})) + assert.Contains(t, stripANSI(out.String()), "The ShellTime hooks in "+userPath+" keep recording your other folders") + out.Reset() + require.NoError(t, app.Run([]string{"t", "cursor", "uninstall", "-g"})) + assert.Contains(t, stripANSI(out.String()), "Cursor hooks removed from "+userPath) + status, err = model.NewCursorHooksService().Status() + require.NoError(t, err) + assert.False(t, status.Present) + assert.JSONEq(t, `{"version":1,"hooks":{"stop":[{"command":"say done"}]}}`, string(mustReadFile(t, userPath))) + projectStatus, err := model.NewCursorProjectHooksService(repo).Status() + require.NoError(t, err) + assert.True(t, projectStatus.Installed, "the repository's hooks stay") + + out.Reset() + require.NoError(t, app.Run([]string{"t", "cursor", "uninstall", "--global"})) + assert.Contains(t, stripANSI(out.String()), "No ShellTime hooks for Cursor to remove in "+userPath) +} + +func TestCursorInstallCommand_GlobalRefusesWindows(t *testing.T) { + home, _ := setupAgentHooksCommand(t) + orig := agentHooksGOOS + agentHooksGOOS = "windows" + t.Cleanup(func() { agentHooksGOOS = orig }) + app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}} + + captureColor(t) + assert.ErrorIs(t, app.Run([]string{"t", "cursor", "install", "--global"}), model.ErrProjectHooksUnsupported) + assert.NoFileExists(t, filepath.Join(home, ".cursor", "hooks.json")) +} + +func TestCursorUninstallCommand_GlobalInvalidFileIsAnError(t *testing.T) { + home, _ := setupAgentHooksCommand(t) + userPath := filepath.Join(home, ".cursor", "hooks.json") + require.NoError(t, os.MkdirAll(filepath.Dir(userPath), 0755)) + require.NoError(t, os.WriteFile(userPath, []byte(`{"hooks":`), 0644)) + app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}} + + out := captureColor(t) + assert.ErrorIs(t, app.Run([]string{"t", "cursor", "uninstall", "--global"}), model.ErrHookFileInvalid) + assert.Contains(t, stripANSI(out.String()), "Failed to remove the Cursor hooks from "+userPath) +} + +func TestAgyInstallCommand_Global(t *testing.T) { + home, _ := setupAgentHooksCommand(t) + userPath := filepath.Join(home, ".gemini", "config", "hooks.json") + require.NoError(t, os.MkdirAll(filepath.Dir(userPath), 0755)) + // An older version's group between two of the user's + require.NoError(t, os.WriteFile(userPath, []byte(`{"a":{},"shelltime":{"Stop":[{"type":"command","command":"/usr/local/bin/shelltime hook-ingest --agent agy --event Stop","timeout":15}]},"z":{}}`), 0644)) + app := &cli.App{Name: "t", Commands: []*cli.Command{AgyCommand}} + + out := captureColor(t) + require.NoError(t, app.Run([]string{"t", "agy", "install", "--global"})) + text := stripANSI(out.String()) + assert.Contains(t, text, "Antigravity hooks installed in "+userPath) + assert.Contains(t, text, "They record Antigravity in every folder on this machine") + assert.Contains(t, text, "Gemini API sandbox reads only a repository's .agents/hooks.json") + assert.Contains(t, text, "Privacy: the Antigravity hooks send") + + var root map[string]json.RawMessage + require.NoError(t, json.Unmarshal(mustReadFile(t, userPath), &root)) + assert.NotContains(t, root, model.AntigravityHookGroup, "the older version's group is replaced") + assert.Contains(t, root, model.AntigravityGlobalHookGroup) + status, err := model.NewAntigravityHooksService().Status() + require.NoError(t, err) + assert.Equal(t, agenthook.AntigravityEvents, status.GlobalEvents) + + require.NoError(t, app.Run([]string{"t", "agy", "uninstall", "--global"})) + assert.JSONEq(t, `{"a":{},"z":{}}`, string(mustReadFile(t, userPath))) } func TestCursorUninstallCommand_OutsideAProjectCleansTheUserFile(t *testing.T) { diff --git a/commands/agent_hooks_install.go b/commands/agent_hooks_install.go index fd2c87e..ab548e1 100644 --- a/commands/agent_hooks_install.go +++ b/commands/agent_hooks_install.go @@ -8,6 +8,7 @@ import ( "github.com/gookit/color" "github.com/malamtime/cli/model" + "github.com/urfave/cli/v2" ) // agentHooksFile is an agent's hook file ShellTime registers in or removes itself from. @@ -24,13 +25,16 @@ var agentHooksGOOS = runtime.GOOS // agentHooks describes one agent for ` install` and ` uninstall`. type agentHooks struct { name string // the agent, as messages name it - // project is the hook file of the project at root, the one ShellTime installs into + // project is the hook file of the project at root, the one ShellTime installs into by default project func(root string) agentHooksFile - // user is the agent's user-level hook file, where older versions installed the hooks; read - // when called, since it lives under $HOME - user func() agentHooksFile + // global is the agent's user-level hook file, which it runs in every folder on the machine + // (`install --global`; older versions installed there too); read when called, since it lives + // under $HOME + global func() agentHooksFile // commit says why the project file is committed commit string + // cloud says what the global file doesn't reach and what to run for it + cloud string // restart says what to restart for the hooks to apply restart string // command is the install command @@ -40,8 +44,9 @@ type agentHooks struct { var cursorHooks = agentHooks{ name: "Cursor", project: func(root string) agentHooksFile { return model.NewCursorProjectHooksService(root) }, - user: func() agentHooksFile { return model.NewCursorHooksService() }, + global: func() agentHooksFile { return model.NewCursorHooksService() }, commit: "Commit it: Cursor Cloud Agents run only the hooks in the repository.", + cloud: "Cursor Cloud Agents run only a repository's .cursor/hooks.json: run `shelltime cursor install` in the repository for those.", restart: "Restart Cursor (the IDE and any running cursor-agent sessions) to apply them.", command: "shelltime cursor install", } @@ -49,27 +54,40 @@ var cursorHooks = agentHooks{ var antigravityHooks = agentHooks{ name: "Antigravity", project: func(root string) agentHooksFile { return model.NewAntigravityProjectHooksService(root) }, - user: func() agentHooksFile { return model.NewAntigravityHooksService() }, + global: func() agentHooksFile { return model.NewAntigravityHooksService() }, commit: "Commit it: the Antigravity agent reads .agents/hooks.json from the repository its Gemini API sandbox mounts.", + cloud: "The Antigravity agent's Gemini API sandbox reads only a repository's .agents/hooks.json: run `shelltime agy install` in the repository for it.", restart: "Restart Antigravity (the app and any running agy sessions) to apply them.", command: "shelltime agy install", } +// globalFlag reports whether the command was run with --global. doctor runs the install +// actions with its own context, which has no such flag. +func globalFlag(c *cli.Context) bool { + return c != nil && c.Bool("global") +} + // installAgentHooks registers ShellTime in the hook file of the project the working directory -// is in. Hooks an older version installed in the agent's user-level file are left in place: they -// still record every other folder on this machine, and the project's hooks leave events to them, -// so nothing is counted twice. Windows is refused: the hook command is POSIX sh, and the daemon -// it records through doesn't run there. -func installAgentHooks(a agentHooks) error { +// is in, or with global in the agent's user-level file, which it runs in every folder on this +// machine. Both can be installed: a project's hooks leave events to the global ones, so nothing +// is counted twice. Windows is refused: the hook command is POSIX sh, and the daemon it records +// through doesn't run there. +func installAgentHooks(a agentHooks, global bool) error { color.Yellow.Printf("Installing %s hooks...\n", a.name) if agentHooksGOOS == "windows" { color.Red.Printf("Failed to install the %s hooks: %v\n", a.name, model.ErrProjectHooksUnsupported) return model.ErrProjectHooksUnsupported } + if global { + return installGlobalAgentHooks(a) + } root, err := currentProjectRoot() if err != nil { color.Red.Printf("Failed to find the project: %v\n", err) + if errors.Is(err, model.ErrHomeIsNotAProject) { + color.Yellow.Printf("To track %s in every folder on this machine, run `%s --global`.\n", a.name, a.command) + } return err } svc := a.project(root) @@ -78,9 +96,9 @@ func installAgentHooks(a agentHooks) error { return err } color.Green.Printf("%s hooks installed in %s\n", a.name, svc.Path()) - if status, err := a.user().Status(); err == nil && status.Installed { - color.Gray.Printf("The ShellTime hooks an older version put in %s stay and keep recording your other folders;\n", a.user().Path()) - color.Gray.Printf("this project's hooks leave events to them. `%s uninstall` removes both.\n", strings.TrimSuffix(a.command, " install")) + if status, err := a.global().Status(); err == nil && status.Installed { + color.Gray.Printf("The ShellTime hooks in %s keep recording your other folders; this project's hooks\n", a.global().Path()) + color.Gray.Printf("leave events to them, so nothing is counted twice. `%s` removes both.\n", uninstallCommand(a)) } color.Yellow.Println(a.commit) @@ -89,32 +107,37 @@ func installAgentHooks(a agentHooks) error { return nil } -// removeUserAgentHooks removes the ShellTime hooks an older version installed in the agent's -// user-level file (doctor's fix for ones whose binary is gone). A file it can't read is reported -// and left alone. -func removeUserAgentHooks(a agentHooks) error { - user := a.user() - status, err := user.Status() - if err == nil && !status.Present { - return nil - } - if err == nil { - err = user.Uninstall() - } - if err != nil { - color.Yellow.Printf("Couldn't remove the ShellTime hooks an older version put in %s: %v\n", user.Path(), err) +// installGlobalAgentHooks registers ShellTime in the agent's user-level hook file, replacing in +// place what an older version wrote there. +func installGlobalAgentHooks(a agentHooks) error { + svc := a.global() + if err := svc.Install(); err != nil { + color.Red.Printf("Failed to install the %s hooks: %v\n", a.name, err) return err } - color.Green.Printf("Removed the ShellTime hooks an older version put in %s\n", user.Path()) + color.Green.Printf("%s hooks installed in %s\n", a.name, svc.Path()) + color.Gray.Printf("They record %s in every folder on this machine; projects with ShellTime hooks of their own\n", a.name) + color.Gray.Println("leave events to them, so nothing is counted twice.") + color.Yellow.Println(a.cloud) + color.Yellow.Println(a.restart) return nil } +// uninstallCommand is the agent's uninstall command. +func uninstallCommand(a agentHooks) string { + return strings.TrimSuffix(a.command, " install") + " uninstall" +} + // uninstallAgentHooks removes ShellTime from the hook file of the project the working directory -// is in, and from the agent's user-level file. Outside a project only the user-level file is -// cleaned. A user-level file it can't read is reported and left alone, as install does: the -// project's file is what this command is for. -func uninstallAgentHooks(a agentHooks) error { +// is in, and from the agent's user-level file, or with global from the user-level file only. +// Outside a project only the user-level file is cleaned. Without global, a user-level file it +// can't read is reported and left alone, as install does: the project's file is what this +// command is for. +func uninstallAgentHooks(a agentHooks, global bool) error { color.Yellow.Printf("Removing %s hooks...\n", a.name) + if global { + return uninstallGlobalAgentHooks(a) + } // A project file that can't be cleaned is reported last: the user-level file is cleaned // whatever happens to it @@ -143,7 +166,7 @@ func uninstallAgentHooks(a agentHooks) error { projectErr = err } - user := a.user() + user := a.global() status, err := user.Status() switch { case err != nil: @@ -160,6 +183,26 @@ func uninstallAgentHooks(a agentHooks) error { return projectErr } +// uninstallGlobalAgentHooks removes ShellTime from the agent's user-level hook file only, which +// is what `uninstall --global` is for, so a file it can't read is an error. +func uninstallGlobalAgentHooks(a agentHooks) error { + svc := a.global() + status, err := svc.Status() + if err == nil && !status.Present { + color.Yellow.Printf("No ShellTime hooks for %s to remove in %s.\n", a.name, svc.Path()) + return nil + } + if err == nil { + err = svc.Uninstall() + } + if err != nil { + color.Red.Printf("Failed to remove the %s hooks from %s: %v\n", a.name, svc.Path(), err) + return err + } + color.Green.Printf("%s hooks removed from %s\n", a.name, svc.Path()) + return nil +} + // currentProjectRoot is the root of the project the working directory is in, where agents look // for project hook files. func currentProjectRoot() (string, error) { diff --git a/commands/agy.go b/commands/agy.go index 646b4cd..a060e54 100644 --- a/commands/agy.go +++ b/commands/agy.go @@ -18,19 +18,33 @@ var AgyCommand = &cli.Command{ var AgyInstallCommand = &cli.Command{ Name: "install", Aliases: []string{"i"}, - Usage: "Install the ShellTime hooks into the current repository's .agents/hooks.json (Antigravity app, agy CLI and its Gemini API sandbox)", - Action: commandAgyInstall, + Usage: "Install the ShellTime hooks into the current repository's .agents/hooks.json (Antigravity app, agy CLI and its Gemini API sandbox), or with --global into ~/.gemini/config/hooks.json", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "global", + Aliases: []string{"g"}, + Usage: "install into ~/.gemini/config/hooks.json, which Antigravity runs in every workspace on this machine (its Gemini API sandbox reads only a repository's hooks)", + }, + }, + Action: commandAgyInstall, } var AgyUninstallCommand = &cli.Command{ Name: "uninstall", Aliases: []string{"u"}, - Usage: "Remove the ShellTime hooks from the current repository's .agents/hooks.json and ~/.gemini/config/hooks.json", - Action: commandAgyUninstall, + Usage: "Remove the ShellTime hooks from the current repository's .agents/hooks.json and ~/.gemini/config/hooks.json, or with --global from ~/.gemini/config/hooks.json only", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "global", + Aliases: []string{"g"}, + Usage: "remove only the ShellTime hooks in ~/.gemini/config/hooks.json, leaving the repository's", + }, + }, + Action: commandAgyUninstall, } func commandAgyInstall(c *cli.Context) error { - if err := installAgentHooks(antigravityHooks); err != nil { + if err := installAgentHooks(antigravityHooks, globalFlag(c)); err != nil { return err } printAgentHooksPrivacyNote("Antigravity") @@ -38,5 +52,5 @@ func commandAgyInstall(c *cli.Context) error { } func commandAgyUninstall(c *cli.Context) error { - return uninstallAgentHooks(antigravityHooks) + return uninstallAgentHooks(antigravityHooks, globalFlag(c)) } diff --git a/commands/cursor.go b/commands/cursor.go index 7151422..67492ee 100644 --- a/commands/cursor.go +++ b/commands/cursor.go @@ -17,19 +17,33 @@ var CursorCommand = &cli.Command{ var CursorInstallCommand = &cli.Command{ Name: "install", Aliases: []string{"i"}, - Usage: "Install the ShellTime hooks into the current repository's .cursor/hooks.json (Cursor IDE, cursor-agent and Cloud Agents)", - Action: commandCursorInstall, + Usage: "Install the ShellTime hooks into the current repository's .cursor/hooks.json (Cursor IDE, cursor-agent and Cloud Agents), or with --global into ~/.cursor/hooks.json", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "global", + Aliases: []string{"g"}, + Usage: "install into ~/.cursor/hooks.json, which Cursor runs in every folder on this machine (Cloud Agents run only a repository's hooks)", + }, + }, + Action: commandCursorInstall, } var CursorUninstallCommand = &cli.Command{ Name: "uninstall", Aliases: []string{"u"}, - Usage: "Remove the ShellTime hooks from the current repository's .cursor/hooks.json and ~/.cursor/hooks.json", - Action: commandCursorUninstall, + Usage: "Remove the ShellTime hooks from the current repository's .cursor/hooks.json and ~/.cursor/hooks.json, or with --global from ~/.cursor/hooks.json only", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "global", + Aliases: []string{"g"}, + Usage: "remove only the ShellTime hooks in ~/.cursor/hooks.json, leaving the repository's", + }, + }, + Action: commandCursorUninstall, } func commandCursorInstall(c *cli.Context) error { - if err := installAgentHooks(cursorHooks); err != nil { + if err := installAgentHooks(cursorHooks, globalFlag(c)); err != nil { return err } printAgentHooksPrivacyNote("Cursor") @@ -37,5 +51,5 @@ func commandCursorInstall(c *cli.Context) error { } func commandCursorUninstall(c *cli.Context) error { - return uninstallAgentHooks(cursorHooks) + return uninstallAgentHooks(cursorHooks, globalFlag(c)) } diff --git a/commands/doctor_checks.go b/commands/doctor_checks.go index 296a91f..65ee3a4 100644 --- a/commands/doctor_checks.go +++ b/commands/doctor_checks.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "maps" "net" "net/url" "os" @@ -12,6 +13,7 @@ import ( "path/filepath" "regexp" "runtime" + "slices" "strings" "time" @@ -1039,35 +1041,49 @@ func doctorCheckAntigravity(env *doctorEnv) []doctorResult { } // doctorCheckAgentHooks checks an agent's hooks: the git repository doctor runs in has them for -// every event and this machine has what they record with, and the hooks an older version -// installed in the agent's user-level file still work, if there are any. Outside a repository -// there is nothing to check, so doctor never offers to write a hook file into whatever folder it -// was run from. +// every event, or the agent's global hook file records it, the global hooks work, and this +// machine has what they record with. Outside a repository there is no project to check, so +// doctor never offers to write a hook file into whatever folder it was run from. func doctorCheckAgentHooks(a doctorAgentHooks) []doctorResult { if agentHooksGOOS == "windows" { return []doctorResult{{ID: a.id + ".hooks", Status: doctorSkip, Message: fmt.Sprintf("%s's hooks need shelltime-daemon, which runs on macOS and Linux only.", a.name)}} } + global := a.hooks.global() + globalStatus, globalErr := global.Status() + globalInstalled := globalErr == nil && globalStatus.Installed + var results []doctorResult + projectInstalled := false root, err := currentProjectRoot() if err == nil { if _, statErr := os.Stat(filepath.Join(root, ".git")); statErr != nil { err = statErr } } - if err != nil { + switch { + case err == nil: + var project []doctorResult + project, projectInstalled = doctorCheckProjectHooks(a, a.hooks.project(root), globalInstalled) + results = append(results, project...) + case !globalInstalled: results = append(results, doctorResult{ ID: a.id + ".hooks", Status: doctorSkip, - Message: fmt.Sprintf("%s's hooks are installed into each project; run `shelltime doctor` in a project's repository to check them.", a.name), + Message: fmt.Sprintf("%s's hooks are installed into each project, or with `%s --global` into every folder on this machine; run `shelltime doctor` in a project's repository to check a project's.", a.name, a.command), }) - } else { - results = append(results, doctorCheckProjectHooks(a, a.hooks.project(root))...) } - return append(results, doctorCheckUserHooks(a)...) + results = append(results, doctorCheckGlobalHooks(a, global, globalStatus, globalErr)...) + if projectInstalled || (globalErr == nil && len(globalStatus.GlobalEvents) > 0) { + results = append(results, doctorCheckHookTools(a)...) + } + return results } -// doctorCheckProjectHooks checks the hook file of the project doctor runs in. -func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile) []doctorResult { +// doctorCheckProjectHooks checks the hook file of the project doctor runs in, and reports +// whether it has ShellTime hooks. A project without them is recorded all the same while the +// agent's global hooks are installed, so it is only a note then: only the agent's cloud runs +// need the project's own. +func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile, globalInstalled bool) ([]doctorResult, bool) { fixHint := fmt.Sprintf("Run `%s` in this repository, commit %s, then restart %s.", a.command, file.Path(), a.name) status, err := file.Status() switch { @@ -1077,17 +1093,24 @@ func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile) []doctorRe Status: doctorFail, Message: fmt.Sprintf("%s can't be read, so %s activity in this project isn't reported: %v", file.Path(), a.name, err), Fix: fmt.Sprintf("Fix the JSON in %s (no comments, trailing commas or byte order mark), then run `%s`.", file.Path(), a.command), - }} + }}, false case err != nil: - return []doctorResult{{ID: a.id + ".hooks", Status: doctorSkip, Message: fmt.Sprintf("Couldn't read %s: %v", file.Path(), err)}} + return []doctorResult{{ID: a.id + ".hooks", Status: doctorSkip, Message: fmt.Sprintf("Couldn't read %s: %v", file.Path(), err)}}, false + case !status.Installed && globalInstalled: + return []doctorResult{{ + ID: a.id + ".hooks", + Status: doctorInfo, + Message: fmt.Sprintf("This project has no ShellTime hooks of its own; your global hooks record %s in it.", a.name), + Fix: a.hooks.cloud, + }}, false case !status.Installed: return []doctorResult{{ ID: a.id + ".hooks", Status: doctorWarn, Message: fmt.Sprintf("This project has no ShellTime hooks for %s, so your %s sessions in it won't show up.", a.name, a.name), - Fix: fixHint, + Fix: fmt.Sprintf("%s Or run `%s --global` to record %s in every folder on this machine.", fixHint, a.command, a.name), AutoFix: a.fix, - }} + }}, false } results := []doctorResult{{ID: a.id + ".hooks", Status: doctorOK, Message: fmt.Sprintf("This project's ShellTime hooks for %s are installed (%s).", a.name, file.Path())}} @@ -1100,21 +1123,27 @@ func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile) []doctorRe AutoFix: a.fix, }) } + return results, true +} + +// doctorCheckHookTools checks that the hook commands find shelltime and shelltime-daemon, which +// they record with. +func doctorCheckHookTools(a doctorAgentHooks) []doctorResult { var missing []string for _, bin := range []string{model.ProjectHookCLI, model.ProjectHookDaemon} { if !projectHookToolFound(bin) { missing = append(missing, bin) } } - if len(missing) > 0 { - results = append(results, doctorResult{ - ID: a.id + ".hook_tools", - Status: doctorWarn, - Message: fmt.Sprintf("The %s hooks find %s neither on PATH nor in ~/.shelltime/bin, /opt/homebrew/bin or /usr/local/bin, so they skip every event on this machine.", a.name, joinWithAnd(missing)), - Fix: "Reinstall ShellTime, or add the folder that holds shelltime and shelltime-daemon to PATH.", - }) + if len(missing) == 0 { + return nil } - return results + return []doctorResult{{ + ID: a.id + ".hook_tools", + Status: doctorWarn, + Message: fmt.Sprintf("The %s hooks find %s neither on PATH nor in ~/.shelltime/bin, /opt/homebrew/bin or /usr/local/bin, so they skip every event on this machine.", a.name, joinWithAnd(missing)), + Fix: "Reinstall ShellTime, or add the folder that holds shelltime and shelltime-daemon to PATH.", + }} } // projectHookToolFound reports whether a project hook command finds bin: on PATH, or in one of @@ -1136,70 +1165,102 @@ func projectHookToolFound(bin string) bool { return false } -// doctorCheckUserHooks reports the ShellTime hooks an older version installed in the agent's -// user-level file, which name their binary by its absolute path. Working ones still record -// every project's events, and the projects' hooks leave those events to them; ones whose binary -// is gone fail on every event. A project's command copied into the file isn't one of them. -func doctorCheckUserHooks(a doctorAgentHooks) []doctorResult { - user := a.hooks.user() - status, err := user.Status() +// doctorCheckGlobalHooks checks the ShellTime hooks in the agent's user-level hook file, which +// the agent runs in every folder (status and err are its Status). `install --global` writes +// self-contained commands, like a project's; older versions wrote the binary's absolute path, +// which fails every event once that binary is gone. Any other ShellTime command there (a +// project's, copied) records too, but next to a project's hooks, which leave events only to the +// global ones, so those count events twice. +func doctorCheckGlobalHooks(a doctorAgentHooks, file agentHooksFile, status model.AgentHooksStatus, err error) []doctorResult { + id := a.id + ".global_hooks" if err != nil { - // A missing file is no error. A file ShellTime can't parse is reported only when an older - // version's hooks are in it, which can then be neither checked nor removed; the rest of + // A missing file is no error. A file ShellTime can't parse is reported only when + // ShellTime hooks are in it, which can then be neither checked nor removed; the rest of // such a file is the user's own business - if data, readErr := os.ReadFile(user.Path()); readErr != nil || !errors.Is(err, model.ErrHookFileInvalid) || + if data, readErr := os.ReadFile(file.Path()); readErr != nil || !errors.Is(err, model.ErrHookFileInvalid) || !strings.Contains(string(data), model.HookIngestSubcommand) { return nil } return []doctorResult{{ - ID: a.id + ".user_hooks", + ID: id, Status: doctorWarn, - Message: fmt.Sprintf("ShellTime can't check or remove the hooks an older version left in %s: %v", user.Path(), err), - Fix: fmt.Sprintf("Fix %s as the error says, or delete its ShellTime hooks by hand.", user.Path()), + Message: fmt.Sprintf("ShellTime can't check or update its hooks in %s: %v", file.Path(), err), + Fix: fmt.Sprintf("Fix %s as the error says, or delete its ShellTime hooks by hand.", file.Path()), }} } if !status.Installed { return nil } - var binaries []string - for _, bin := range status.Binaries { - if filepath.IsAbs(bin) { - binaries = append(binaries, bin) - } - } - if len(binaries) == 0 { - return nil - } - remove := &doctorFix{ - Key: a.id + ".user_hooks", - Label: fmt.Sprintf("Remove the ShellTime hooks an older version put in %s", user.Path()), - Run: func(*cli.Context) error { return removeUserAgentHooks(a.hooks) }, + rewrite := &doctorFix{ + Key: id, + Label: fmt.Sprintf("Rewrite the ShellTime hooks in %s (%s --global)", file.Path(), a.command), + Run: func(*cli.Context) error { return installAgentHooks(a.hooks, true) }, } - for _, bin := range binaries { - var problem string - switch info, err := os.Stat(bin); { - case err != nil: - problem = "doesn't exist" - case info.IsDir(): - problem = "is a folder" - case runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0: - problem = "isn't executable" - default: + rewriteHint := fmt.Sprintf("Run `%s --global` to rewrite them, or `%s --global` to remove them.", a.command, uninstallCommand(a.hooks)) + + legacy, other := false, false + for _, event := range slices.Sorted(maps.Keys(status.EventBinaries)) { + if slices.Contains(status.GlobalEvents, event) { continue } + for _, bin := range status.EventBinaries[event] { + if !filepath.IsAbs(bin) { + other = true + continue + } + legacy = true + var problem string + switch info, err := os.Stat(bin); { + case err != nil: + problem = "doesn't exist" + case info.IsDir(): + problem = "is a folder" + case runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0: + problem = "isn't executable" + default: + continue + } + return []doctorResult{{ + ID: id, + Status: doctorFail, + Message: fmt.Sprintf("The ShellTime hooks an older version put in %s run %s, which %s, so %s reports a failed hook on every event.", file.Path(), bin, problem, a.name), + Fix: rewriteHint, + AutoFix: rewrite, + }} + } + } + if other { return []doctorResult{{ - ID: a.id + ".user_hooks", - Status: doctorFail, - Message: fmt.Sprintf("The ShellTime hooks an older version put in %s run %s, which %s, so %s reports a failed hook on every event.", user.Path(), bin, problem, a.name), - Fix: fmt.Sprintf("Remove them: ShellTime's hooks go into each project now (`%s` in its repository).", a.command), - AutoFix: remove, + ID: id, + Status: doctorWarn, + Message: fmt.Sprintf("%s holds ShellTime hooks `%s --global` didn't write (a project's, copied there?), so %s events in projects with hooks of their own are counted twice.", file.Path(), a.command, a.name), + Fix: rewriteHint, + AutoFix: rewrite, }} } - return []doctorResult{{ - ID: a.id + ".user_hooks", - Status: doctorInfo, - Message: fmt.Sprintf("%s still has the ShellTime hooks of an older version; they record %s in every folder, and projects with their own hooks leave events to them. ShellTime installs hooks into each project now (`%s`); `%s uninstall` removes these.", user.Path(), a.name, a.command, strings.TrimSuffix(a.command, " install")), + if legacy && len(status.GlobalEvents) == 0 { + return []doctorResult{{ + ID: id, + Status: doctorInfo, + Message: fmt.Sprintf("The ShellTime hooks an older version put in %s record %s in every folder; they fail once that shelltime binary moves. `%s --global` rewrites them to find it wherever it is.", file.Path(), a.name, a.command), + }} + } + + results := []doctorResult{{ + ID: id, + Status: doctorOK, + Message: fmt.Sprintf("Your global ShellTime hooks for %s are installed (%s); they record %s in every folder on this machine.", a.name, file.Path(), a.name), }} + if len(status.MissingEvents) > 0 { + results = append(results, doctorResult{ + ID: a.id + ".global_hook_events", + Status: doctorWarn, + Message: fmt.Sprintf("Your global ShellTime hooks for %s are out of date (missing %s), so some session details aren't reported.", a.name, strings.Join(status.MissingEvents, ", ")), + Fix: fmt.Sprintf("Run `%s --global`, then restart %s.", a.command, a.name), + AutoFix: rewrite, + }) + } + return results } // --- AI usage receiver -------------------------------------------------------- diff --git a/commands/doctor_test.go b/commands/doctor_test.go index 7cc5a89..24bdbe3 100644 --- a/commands/doctor_test.go +++ b/commands/doctor_test.go @@ -12,6 +12,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "strings" "sync" "sync/atomic" @@ -713,7 +714,7 @@ func TestDoctorCheckCursor(t *testing.T) { require.NoError(t, os.WriteFile(daemonBin, []byte("#!/bin/sh\n"), 0755)) results = doctorCheckCursor(env) assert.False(t, hasDoctorResult(results, "cursor.hook_tools")) - assert.False(t, hasDoctorResult(results, "cursor.user_hooks")) + assert.False(t, hasDoctorResult(results, "cursor.global_hooks")) assert.Len(t, results, 1) // An older install of this project's hooks, without some events @@ -726,37 +727,83 @@ func TestDoctorCheckCursor(t *testing.T) { // What an older version left in ~/.cursor/hooks.json: working, then with its binary gone exe, err := os.Executable() require.NoError(t, err) - installUserHooksFor(t, model.NewCursorHooksService().Path(), "cursor", agenthook.CursorEvents, exe) - user := findDoctorResult(t, doctorCheckCursor(env), "cursor.user_hooks") + userPath := model.NewCursorHooksService().Path() + installUserHooksFor(t, userPath, "cursor", agenthook.CursorEvents, exe) + user := findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hooks") assert.Equal(t, doctorInfo, user.Status) assert.Contains(t, user.Message, "older version") + assert.Contains(t, user.Message, "shelltime cursor install --global") assert.Nil(t, user.AutoFix, "working hooks aren't taken away") - installUserHooksFor(t, model.NewCursorHooksService().Path(), "cursor", agenthook.CursorEvents, "/gone/shelltime") - user = findDoctorResult(t, doctorCheckCursor(env), "cursor.user_hooks") + installUserHooksFor(t, userPath, "cursor", agenthook.CursorEvents, "/gone/shelltime") + user = findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hooks") assert.Equal(t, doctorFail, user.Status) assert.Contains(t, user.Message, "/gone/shelltime") assert.Contains(t, user.Message, "doesn't exist") + assert.Contains(t, user.Fix, "shelltime cursor uninstall --global") require.NotNil(t, user.AutoFix) - assert.Equal(t, "cursor.user_hooks", user.AutoFix.Key) + assert.Equal(t, "cursor.global_hooks", user.AutoFix.Key) captureColor(t) require.NoError(t, user.AutoFix.Run(nil)) - assert.False(t, hasDoctorResult(doctorCheckCursor(env), "cursor.user_hooks"), "the fix removed them") + user = findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hooks") + assert.Equal(t, doctorOK, user.Status, "the fix rewrote them into the global hooks") + assert.Contains(t, user.Message, "record Cursor in every folder") + globalStatus, err := model.NewCursorHooksService().Status() + require.NoError(t, err) + assert.Equal(t, agenthook.CursorEvents, globalStatus.GlobalEvents) - // A project's command copied into the user file isn't an older version's hook - userPath := model.NewCursorHooksService().Path() + // Global hooks of a version that registered fewer events + require.NoError(t, os.WriteFile(userPath, []byte(`{"version":1,"hooks":{"stop":[{"command":`+strconv.Quote(model.CursorGlobalHookCommand("stop"))+`}]}}`), 0644)) + events = findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hook_events") + assert.Equal(t, doctorWarn, events.Status) + assert.Contains(t, events.Message, "beforeSubmitPrompt") + require.NotNil(t, events.AutoFix) + require.NoError(t, events.AutoFix.Run(nil)) + assert.False(t, hasDoctorResult(doctorCheckCursor(env), "cursor.global_hook_events")) + + // A project's command copied into the global file records next to the project's, so events + // in projects with their own hooks count twice copied, err := json.Marshal(map[string]any{"version": 1, "hooks": map[string]any{ "stop": []any{map[string]any{"command": model.CursorProjectHookCommand("stop")}}, }}) require.NoError(t, err) require.NoError(t, os.WriteFile(userPath, copied, 0644)) - assert.False(t, hasDoctorResult(doctorCheckCursor(env), "cursor.user_hooks")) + user = findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hooks") + assert.Equal(t, doctorWarn, user.Status) + assert.Contains(t, user.Message, "counted twice") + require.NotNil(t, user.AutoFix) + require.NoError(t, user.AutoFix.Run(nil)) + assert.Equal(t, doctorOK, findDoctorResult(t, doctorCheckCursor(env), "cursor.global_hooks").Status) + + // With global hooks, a project without its own is still recorded: a note, and no fix that + // writes a hook file into it + require.NoError(t, model.NewCursorProjectHooksService(repo).Uninstall()) + hooks = findDoctorResult(t, doctorCheckCursor(env), "cursor.hooks") + assert.Equal(t, doctorInfo, hooks.Status) + assert.Contains(t, hooks.Message, "your global hooks record Cursor in it") + assert.Contains(t, hooks.Fix, "Cloud Agents") + assert.Nil(t, hooks.AutoFix) + + // Outside a project the global hooks are checked, with what they record with + t.Chdir(home) + results = doctorCheckCursor(env) + assert.False(t, hasDoctorResult(results, "cursor.hooks"), "nothing to say about projects") + assert.Equal(t, doctorOK, findDoctorResult(t, results, "cursor.global_hooks").Status) + assert.False(t, hasDoctorResult(results, "cursor.hook_tools")) + require.NoError(t, os.Remove(daemonBin)) + tools = findDoctorResult(t, doctorCheckCursor(env), "cursor.hook_tools") + assert.Equal(t, doctorWarn, tools.Status) + assert.Contains(t, tools.Message, "shelltime-daemon") + require.NoError(t, os.WriteFile(daemonBin, []byte("#!/bin/sh\n"), 0755)) + require.NoError(t, model.NewCursorHooksService().Uninstall()) + require.NoError(t, model.NewCursorProjectHooksService(repo).Install()) // Outside a project there is no project file to check t.Chdir(home) hooks = findDoctorResult(t, doctorCheckCursor(env), "cursor.hooks") assert.Equal(t, doctorSkip, hooks.Status) assert.Contains(t, hooks.Message, "run `shelltime doctor` in a project's repository") + assert.Contains(t, hooks.Message, "`shelltime cursor install --global`") // Nor in a folder outside a repository: doctor never offers to write a hook file there t.Chdir(t.TempDir()) @@ -823,20 +870,27 @@ func TestDoctorCheckAntigravity(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(home, ".gemini", "config"), 0755)) userPath := model.NewAntigravityHooksService().Path() require.NoError(t, os.WriteFile(userPath, []byte("{,"), 0644)) - assert.False(t, hasDoctorResult(doctorCheckAntigravity(env), "antigravity.user_hooks")) + assert.False(t, hasDoctorResult(doctorCheckAntigravity(env), "antigravity.global_hooks")) - // unless an older version's hooks are in it, which can then be neither checked nor removed + // unless ShellTime's hooks are in it, which can then be neither checked nor removed require.NoError(t, os.WriteFile(userPath, []byte(`{"shelltime":{"Stop":[{"command":"/a/shelltime hook-ingest --agent agy --event Stop"}]},}`), 0644)) - user := findDoctorResult(t, doctorCheckAntigravity(env), "antigravity.user_hooks") + user := findDoctorResult(t, doctorCheckAntigravity(env), "antigravity.global_hooks") assert.Equal(t, doctorWarn, user.Status) - assert.Contains(t, user.Message, "can't check or remove") + assert.Contains(t, user.Message, "can't check or update") assert.Contains(t, user.Fix, "delete its ShellTime hooks by hand") assert.Nil(t, user.AutoFix) // One that is no JSON problem (a folder in its place) says nothing it can't back up require.NoError(t, os.Remove(userPath)) require.NoError(t, os.Mkdir(userPath, 0755)) - assert.False(t, hasDoctorResult(doctorCheckAntigravity(env), "antigravity.user_hooks")) + assert.False(t, hasDoctorResult(doctorCheckAntigravity(env), "antigravity.global_hooks")) + + // Global hooks + require.NoError(t, os.Remove(userPath)) + require.NoError(t, model.NewAntigravityHooksService().Install()) + global := findDoctorResult(t, doctorCheckAntigravity(env), "antigravity.global_hooks") + assert.Equal(t, doctorOK, global.Status) + assert.Contains(t, global.Message, "record Antigravity in every folder") } func TestCommandDoctor_FixInstallsAgentHooks(t *testing.T) { diff --git a/commands/hook_ingest.go b/commands/hook_ingest.go index 17e8127..615acf5 100644 --- a/commands/hook_ingest.go +++ b/commands/hook_ingest.go @@ -8,6 +8,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "time" @@ -90,12 +91,13 @@ var HookIngestCommand = &cli.Command{ // one takes it, else in the pending file the daemon resends from. Nothing else ever reaches // stdout, and a panic still answers. // -// project is set when a project's hook file runs it. An older version may have left its hooks -// in the agent's user-level file, which the agent runs next to the project's, so the event is -// left to those when they record it too, unless it ran in a cloud VM: Cursor Cloud Agents never -// run the user's hooks, even where a setup script wrote some. Cursor names a cloud run only in -// sessionStart, which the daemon remembers for the session's later events, so a daemon makes -// that call (YieldToUserHooks); without one the event is left to the user's hook. +// project is set when a project's hook file runs it. The agent runs its user-level (global) +// hook file next to the project's, so the event is left to the global hooks when they record it +// too (`install --global`, or what an older version installed there), unless it ran in a cloud +// VM: Cursor Cloud Agents never run the user's hooks, even where a setup script wrote some. +// Cursor names a cloud run only in sessionStart, which the daemon remembers for the session's +// later events, so a daemon makes that call (YieldToUserHooks); without one the event is left +// to the global hook. func runHookIngest(ctx context.Context, agent, event string, project bool) { if ctx == nil { ctx = context.Background() @@ -266,11 +268,13 @@ func hookIngestFlagsFromArgs(args []string) (agent, event string, project bool) return agent, event, project } -// userHooksRecord reports whether the agent's user-level hook file still holds a ShellTime hook -// an older version installed for event, with a binary that is still there, so the agent records -// the event through it. Those name the binary by its absolute path; a project's commands name -// it by PATH, and one copied into the user file counts as not recording, like anything this -// can't read, so the project hook records the event instead. +// userHooksRecord reports whether the agent's user-level hook file holds a ShellTime hook for +// event that records it, so the project's hook can leave the event to it: the command +// `install --global` writes, which looks for the same binaries in the same places as the +// project's (so it records wherever the project's does), or one an older version wrote, which +// names its binary by an absolute path, while that binary is still there. A project's command +// copied into the user file counts as not recording, since it would leave the event to itself, +// and so does anything this can't read: the project hook records the event then. func userHooksRecord(agent, event string) bool { var events []string var status model.AgentHooksStatus @@ -288,11 +292,14 @@ func userHooksRecord(agent, event string) bool { if err != nil || !status.Installed { return false } - // The binaries of this event's commands: another event's binary says nothing about it + // This event's commands: another event's say nothing about it for _, managed := range events { if !strings.EqualFold(managed, event) { continue } + if slices.Contains(status.GlobalEvents, managed) { + return true + } for _, bin := range status.EventBinaries[managed] { if hookBinaryExists(bin) { return true diff --git a/commands/hook_ingest_test.go b/commands/hook_ingest_test.go index 4b534d7..40f690d 100644 --- a/commands/hook_ingest_test.go +++ b/commands/hook_ingest_test.go @@ -475,6 +475,42 @@ func TestHookIngest_UserHookRecordsNextToProjectHook(t *testing.T) { assert.Len(t, pendingHookEvents(t), 1) } +func TestHookIngest_ProjectHookLeavesTheEventToGlobalHooks(t *testing.T) { + for _, tc := range []struct { + agent, event, payload, reply string + }{ + {"cursor", "stop", cursorStopPayload, `{}`}, + {"agy", "Stop", `{"conversationId":"a1","terminationReason":"completed"}`, `{"decision":"allow"}`}, + } { + t.Run(tc.agent, func(t *testing.T) { + h := setupHookIngest(t, strings.NewReader(tc.payload)) + h.config.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{}, nil) + // The services read HOME, which setupHookIngest set, when they are made + if tc.agent == "cursor" { + require.NoError(t, model.NewCursorHooksService().Install()) + } else { + require.NoError(t, model.NewAntigravityHooksService().Install()) + } + + h.run(t, "--agent", tc.agent, "--event", tc.event, "--project") + + h.assertOnlyReply(t, tc.reply) + assert.Empty(t, pendingHookEvents(t), "`install --global`'s hook records it") + }) + } +} + +func TestHookIngest_GlobalHookRecordsNextToProjectHook(t *testing.T) { + h := setupHookIngest(t, strings.NewReader(cursorStopPayload)) + h.config.On("ReadConfigFile", mock.Anything).Return(model.ShellTimeConfig{}, nil) + require.NoError(t, model.NewCursorHooksService().Install()) + + h.run(t, "--agent", "cursor", "--event", "stop") + + h.assertOnlyReply(t, `{}`) + assert.Len(t, pendingHookEvents(t), 1) +} + func TestHookIngest_ProjectHookRecordsWhenUserHooksCantRun(t *testing.T) { t.Run("their binary is gone", func(t *testing.T) { h := setupHookIngest(t, strings.NewReader(cursorStopPayload)) @@ -595,6 +631,30 @@ func TestUserHooksRecord_ChecksTheEventsOwnBinary(t *testing.T) { assert.False(t, userHooksRecord(agenthook.AgentCursor, "postToolUse"), "not registered at all") } +func TestUserHooksRecord_GlobalHooks(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + require.NoError(t, model.NewCursorHooksService().Install()) + for _, event := range agenthook.CursorEvents { + assert.True(t, userHooksRecord(agenthook.AgentCursor, event), event) + } + assert.False(t, userHooksRecord(agenthook.AgentAntigravity, "Stop"), "another agent's file") + + require.NoError(t, model.NewAntigravityHooksService().Install()) + for _, event := range agenthook.AntigravityEvents { + assert.True(t, userHooksRecord(agenthook.AgentAntigravity, event), event) + } + + // A disabled group runs nothing + path := model.NewAntigravityHooksService().Path() + var root map[string]map[string]any + require.NoError(t, json.Unmarshal(mustReadFile(t, path), &root)) + root[model.AntigravityGlobalHookGroup]["enabled"] = false + data, err := json.Marshal(root) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, data, 0644)) + assert.False(t, userHooksRecord(agenthook.AgentAntigravity, "Stop")) +} + func TestUserHooksRecord_ProjectCommandsInTheUserFile(t *testing.T) { t.Setenv("HOME", t.TempDir()) path := model.NewCursorHooksService().Path() diff --git a/commands/init.go b/commands/init.go index 008baf9..6dac728 100644 --- a/commands/init.go +++ b/commands/init.go @@ -121,7 +121,8 @@ func runInitStep(verbose bool, step func() error) error { } // printProjectAgentHooksHint says how to track the detected agents whose hooks go into each -// project's repository: Cursor and Antigravity. Not on Windows, where their install refuses. +// project's repository, or with --global into every folder: Cursor and Antigravity. Not on +// Windows, where their install refuses. func printProjectAgentHooksHint(lookPath func(string) (string, error)) { if agentHooksGOOS == "windows" { return @@ -138,7 +139,8 @@ func printProjectAgentHooksHint(lookPath func(string) (string, error)) { if len(agents) == 0 { return } - color.Yellow.Printf("To track %s, run %s in each project's repository and commit the hook file.\n", joinWithAnd(agents), joinWithAnd(commands)) + color.Yellow.Printf("To track %s, run %s in each project's repository and commit the hook file,\n", joinWithAnd(agents), joinWithAnd(commands)) + color.Yellow.Println("or add --global to track every folder on this machine (cloud agents run only a repository's hooks).") } // printAgentTelemetrySummary reports the coding agent steps: a line per failure, and, diff --git a/commands/init_output_test.go b/commands/init_output_test.go index 534ff64..e1e1e63 100644 --- a/commands/init_output_test.go +++ b/commands/init_output_test.go @@ -279,7 +279,7 @@ func TestPrintProjectAgentHooksHint(t *testing.T) { assert.Empty(t, out.String(), "nothing to say without the agents") printProjectAgentHooksHint(found("cursor-agent")) - assert.Equal(t, "To track Cursor, run `shelltime cursor install` in each project's repository and commit the hook file.", stripANSI(out.String())) + assert.Equal(t, "To track Cursor, run `shelltime cursor install` in each project's repository and commit the hook file,\nor add --global to track every folder on this machine (cloud agents run only a repository's hooks).", stripANSI(out.String())) out.Reset() orig := agentHooksGOOS @@ -289,7 +289,7 @@ func TestPrintProjectAgentHooksHint(t *testing.T) { assert.Empty(t, out.String(), "Windows can't install them") printProjectAgentHooksHint(found("cursor", "agy")) - assert.Equal(t, "To track Cursor and Antigravity, run `shelltime cursor install` and `shelltime agy install` in each project's repository and commit the hook file.", stripANSI(out.String())) + assert.Equal(t, "To track Cursor and Antigravity, run `shelltime cursor install` and `shelltime agy install` in each project's repository and commit the hook file,\nor add --global to track every folder on this machine (cloud agents run only a repository's hooks).", stripANSI(out.String())) } // --- gc ---------------------------------------------------------------------------- diff --git a/daemon/agent_hooks.go b/daemon/agent_hooks.go index b662e53..2c07290 100644 --- a/daemon/agent_hooks.go +++ b/daemon/agent_hooks.go @@ -117,7 +117,7 @@ func (b *AgentHookBatcher) SetConfigService(cs model.ConfigService) { // Add queues an event. An event without a session id gets the last one an event carried for // its agent and workspace within agentHookSessionTTL (Cursor sometimes sends tool events with // an empty conversation_id), and one of a cloud session is marked as cloud. An event that -// yields to an older version's user-level hook is dropped unless its session is a cloud run, +// yields to the agent's user-level (global) hook is dropped unless its session is a cloud run, // whose agent runs no user-level hooks. After Shutdown the event is saved for the resync service // instead. func (b *AgentHookBatcher) Add(ev agenthook.Event) { diff --git a/docs/CONFIG.md b/docs/CONFIG.md index 497a730..62227a0 100644 --- a/docs/CONFIG.md +++ b/docs/CONFIG.md @@ -341,7 +341,7 @@ You don't need to set it in a Claude Code cloud environment ([cloud.bash](https: ## Cursor and Antigravity Hooks -`shelltime cursor install` and `shelltime agy install` register ShellTime in the native hooks of Cursor (`.cursor/hooks.json`) and Google Antigravity (`.agents/hooks.json`) of the current repository, which is committed: the hooks record only on machines where `shelltime` and `shelltime-daemon` are installed. Each event goes to the daemon, which applies data masking and your exclude patterns before sending it. An event whose shell command matches an exclude pattern is sent without the command, its prompt, tool input, response or error. Cursor reports per-turn token counts on its `stop` hook; Antigravity's `PostInvocation` hook reads completed model steps from the local `.jsonl` transcript file referenced by `transcriptPath` (silently falling back to activity-only tracking if the file is unavailable or has no matching completed step). +`shelltime cursor install` and `shelltime agy install` register ShellTime in the native hooks of Cursor (`.cursor/hooks.json`) and Google Antigravity (`.agents/hooks.json`) of the current repository, which is committed: the hooks record only on machines where `shelltime` and `shelltime-daemon` are installed. With `--global` they go into `~/.cursor/hooks.json` and `~/.gemini/config/hooks.json` instead, which the agents run in every folder on this machine (cloud agents run only a repository's hooks). Each event goes to the daemon, which applies data masking and your exclude patterns before sending it. An event whose shell command matches an exclude pattern is sent without the command, its prompt, tool input, response or error. Cursor reports per-turn token counts on its `stop` hook; Antigravity's `PostInvocation` hook reads completed model steps from the local `.jsonl` transcript file referenced by `transcriptPath` (silently falling back to activity-only tracking if the file is unavailable or has no matching completed step). | Option | Type | Default | Description | |--------|------|---------|-------------| diff --git a/model/agent_hooks_common.go b/model/agent_hooks_common.go index 1ef8d84..b28f599 100644 --- a/model/agent_hooks_common.go +++ b/model/agent_hooks_common.go @@ -15,51 +15,66 @@ import ( // HookIngestSubcommand is what every agent hook command runs: `… shelltime hook-ingest --agent …`. const HookIngestSubcommand = "hook-ingest" -// The binaries a project hook command looks for before it records anything. +// The binaries a hook command looks for before it records anything. const ( ProjectHookCLI = "shelltime" ProjectHookDaemon = "shelltime-daemon" ) const ( - // ProjectHookFlag marks the hook-ingest runs of a project's hook file. An older version may - // have left its hooks in the user's own hook file, which the agent runs next to the - // project's, so such a run leaves the event to those when they record it too. + // ProjectHookFlag marks the hook-ingest runs of a project's hook file. The agent runs the + // user's global hook file next to the project's, so such a run leaves the event to the + // global hooks when they record it too. ProjectHookFlag = "--project" - // projectHookPath is added to the PATH a project hook command searches: where the install - // script puts shelltime and shelltime-daemon when it doesn't use Homebrew, then Homebrew's - // folders, which an app started from the Dock may not have on its PATH. + // projectHookPath is added to the PATH a hook command searches: where the install script + // puts shelltime and shelltime-daemon when it doesn't use Homebrew, then Homebrew's folders, + // which an app started from the Dock may not have on its PATH. projectHookPath = "$HOME/.shelltime/bin:/opt/homebrew/bin:/usr/local/bin" ) -// ProjectHookSearchDirs are the folders a project hook command searches after PATH, for home. +// ProjectHookSearchDirs are the folders a hook command searches after PATH, for home. func ProjectHookSearchDirs(home string) []string { return []string{filepath.Join(home, COMMAND_BASE_STORAGE_FOLDER, "bin"), "/opt/homebrew/bin", "/usr/local/bin"} } -// ErrProjectHooksUnsupported is returned for installing project hooks on Windows: their command -// is POSIX sh, and shelltime-daemon, which they record through, runs on macOS and Linux only. +// ErrProjectHooksUnsupported is returned for installing the hooks on Windows: their command is +// POSIX sh, and shelltime-daemon, which they record through, runs on macOS and Linux only. var ErrProjectHooksUnsupported = errors.New("the Cursor and Antigravity hooks need shelltime-daemon, which runs on macOS and Linux only") // ErrHomeIsNotAProject is returned for a project root that is the user's home folder, whose // .cursor/hooks.json is Cursor's user-level hook file, not a project's. var ErrHomeIsNotAProject = errors.New("the home folder isn't a project; run this inside the project's repository") -// projectHookCommand is the command a project's hook file runs for an agent's event (agent is -// the --agent value). The file is committed and runs on every machine that checks the -// repository out, a cloud agent's VM included, and the agents disagree on the folder a hook -// runs in, so the command is self-contained POSIX sh: where the shelltime CLI and its daemon are -// installed (on PATH, or in ProjectHookSearchDirs) it hands the event to hook-ingest; anywhere -// else it answers with the reply that lets the agent carry on, so the hook never fails. A -// shelltime from before hook-ingest exits non-zero with its error on stderr; its stdout is -// dropped and the reply answers instead. -func projectHookCommand(agent, event string) string { - return fmt.Sprintf("PATH=${PATH:+$PATH:}%s; command -v %s >/dev/null 2>&1 && command -v %s >/dev/null 2>&1 && out=$(%s %s --agent %s --event %s %s) && printf '%%s\\n' \"$out\" || echo '%s'", +// hookCommand is the command a hook file runs for an agent's event (agent is the --agent +// value), with ProjectHookFlag in a project's file. A project's file is committed and runs on +// every machine that checks the repository out, a cloud agent's VM included, a global one may +// be synced to machines without ShellTime along with the rest of a home folder, and the agents +// disagree on the folder a hook runs in, so the command is self-contained POSIX sh: where the +// shelltime CLI and its daemon are installed (on PATH, or in ProjectHookSearchDirs) it hands the +// event to hook-ingest; anywhere else it answers with the reply that lets the agent carry on, so +// the hook never fails, also once ShellTime moves or is removed. A shelltime from before +// hook-ingest exits non-zero with its error on stderr; its stdout is dropped and the reply +// answers instead. +func hookCommand(agent, event string, project bool) string { + args := fmt.Sprintf("%s --agent %s --event %s", HookIngestSubcommand, agent, event) + if project { + args += " " + ProjectHookFlag + } + return fmt.Sprintf("PATH=${PATH:+$PATH:}%s; command -v %s >/dev/null 2>&1 && command -v %s >/dev/null 2>&1 && out=$(%s %s) && printf '%%s\\n' \"$out\" || echo '%s'", projectHookPath, ProjectHookCLI, ProjectHookDaemon, - ProjectHookCLI, HookIngestSubcommand, agent, event, ProjectHookFlag, + ProjectHookCLI, args, agenthook.PassThrough(agent, event)) } +// isGlobalHookCommand reports whether command is one `install --global` writes: the +// self-contained command (hookCommand) without ProjectHookFlag. It records an event wherever a +// project's command for it does, since both look for the same binaries in the same places. +func isGlobalHookCommand(command string) bool { + return strings.Contains(command, "command -v "+ProjectHookDaemon+" ") && + hookCommandBinary(command) == ProjectHookCLI && + !strings.Contains(command, " "+ProjectHookFlag) +} + // ProjectHooksRoot returns the root of the project dir is in, where its agents look for project // hook files: the nearest folder up from dir that holds .git (a folder, or a file in a worktree // or submodule), else dir itself. The user's home folder is no project (ErrHomeIsNotAProject), @@ -102,6 +117,18 @@ type AgentHooksStatus struct { Binaries []string // EventBinaries are the binaries each managed event's commands run, by event. EventBinaries map[string][]string + // GlobalEvents are the managed events registered with the command `install --global` writes + // (isGlobalHookCommand), in install order. Older versions wrote the binary's absolute path + // instead, which only EventBinaries shows. + GlobalEvents []string +} + +// addCommand records command, a ShellTime command registered for event. +func (s *AgentHooksStatus) addCommand(event, command string) { + s.addBinary(event, hookCommandBinary(command)) + if isGlobalHookCommand(command) && !containsString(s.GlobalEvents, event) { + s.GlobalEvents = append(s.GlobalEvents, event) + } } // addBinary records bin as run by event's commands. diff --git a/model/agent_hooks_project_test.go b/model/agent_hooks_project_test.go index eda04a5..8b4349d 100644 --- a/model/agent_hooks_project_test.go +++ b/model/agent_hooks_project_test.go @@ -1,9 +1,12 @@ package model import ( + "encoding/json" + "maps" "os" "os/exec" "path/filepath" + "slices" "strings" "testing" @@ -90,6 +93,11 @@ func TestProjectHookCommand(t *testing.T) { assert.True(t, strings.HasSuffix(CursorProjectHookCommand("stop"), `--event stop --project) && printf '%s\n' "$out" || echo '{}'`)) assert.True(t, strings.HasSuffix(AntigravityProjectHookCommand("Stop"), `--agent agy --event Stop --project) && printf '%s\n' "$out" || echo '{"decision":"allow"}'`)) assert.True(t, strings.HasSuffix(AntigravityProjectHookCommand("PostToolUse"), `--event PostToolUse --project) && printf '%s\n' "$out" || echo '{}'`)) + + // The global file's are the same without --project + assert.Equal(t, strings.Replace(CursorProjectHookCommand("beforeSubmitPrompt"), " --project)", ")", 1), CursorGlobalHookCommand("beforeSubmitPrompt")) + assert.True(t, strings.HasSuffix(AntigravityGlobalHookCommand("Stop"), `--agent agy --event Stop) && printf '%s\n' "$out" || echo '{"decision":"allow"}'`)) + assert.NotContains(t, CursorGlobalHookCommand("stop"), "--project") } // runProjectHookCommand runs a project hook command in sh the way the agents do, with PATH and @@ -170,6 +178,10 @@ func TestProjectHookCommand_RunsHookIngestOnlyWithTheCLIAndDaemon(t *testing.T) fake(shelltimeBin, "shelltime", cli) fake(shelltimeBin, "shelltime-daemon", "") assert.Equal(t, "ran hook-ingest --agent agy --event Stop --project\n", runProjectHookCommand(t, AntigravityProjectHookCommand("Stop"), sysPath, home, "{}")) + + // The global file's command looks in the same places + assert.Equal(t, "ran hook-ingest --agent cursor --event stop\n", runProjectHookCommand(t, CursorGlobalHookCommand("stop"), sysPath, home, "{}")) + assert.Equal(t, "{\"decision\":\"allow\"}\n", runProjectHookCommand(t, AntigravityGlobalHookCommand("Stop"), sysPath, t.TempDir(), "{}"), "ShellTime moved away: the agent carries on") } func TestCursorProjectHooks(t *testing.T) { @@ -272,30 +284,98 @@ func TestStatus_EventBinaries(t *testing.T) { assert.Equal(t, map[string][]string{"Stop": {"/c/shelltime"}}, status.EventBinaries) } -func TestUserHooksAreOnlyCleaned(t *testing.T) { +func TestGlobalCursorHooks(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) - cursor := NewCursorHooksService() assert.Equal(t, filepath.Join(home, ".cursor", "hooks.json"), cursor.Path()) - assert.ErrorIs(t, cursor.Install(), ErrUserHooksRetired) - assert.NoFileExists(t, cursor.Path()) - agy := NewAntigravityHooksService() - assert.Equal(t, filepath.Join(home, ".gemini", "config", "hooks.json"), agy.Path()) - assert.ErrorIs(t, agy.Install(), ErrUserHooksRetired) - assert.NoFileExists(t, agy.Path()) - - // What an older version left there is still read and removed - writeFile(t, cursor.Path(), `{"version":1,"hooks":{"stop":[{"command":"say done"},{"command":"`+legacyHookCommand("/usr/local/bin/shelltime", "cursor", "stop")+`"}]}}`, 0644) + // What an older version left there is replaced in place, next to the user's own hook + writeFile(t, cursor.Path(), `{"version":1,"hooks":{"stop":[{"command":"say done"},{"command":"`+legacyHookCommand("/usr/local/bin/shelltime", "cursor", "stop")+`","timeout":5}]}}`, 0644) status, err := cursor.Status() require.NoError(t, err) assert.True(t, status.Installed) + assert.Empty(t, status.GlobalEvents, "an older version's command names its binary by path") assert.Equal(t, []string{"/usr/local/bin/shelltime"}, status.Binaries) + + require.NoError(t, cursor.Install()) + status, err = cursor.Status() + require.NoError(t, err) + assert.Empty(t, status.MissingEvents) + assert.Equal(t, agenthook.CursorEvents, status.GlobalEvents) + assert.Equal(t, []string{ProjectHookCLI}, status.Binaries) + stop := readCursorHooks(t, cursor.Path()).Hooks["stop"] + require.Len(t, stop, 2) + assert.Equal(t, "say done", stop[0]["command"]) + assert.Equal(t, CursorGlobalHookCommand("stop"), stop[1]["command"]) + assert.EqualValues(t, 5, stop[1]["timeout"], "the entry's other keys stay") + + data := mustRead(t, cursor.Path()) + require.NoError(t, cursor.Install()) + assert.Equal(t, string(data), string(mustRead(t, cursor.Path())), "installing again changes nothing") + require.NoError(t, cursor.Uninstall()) assert.JSONEq(t, `{"version":1,"hooks":{"stop":[{"command":"say done"}]}}`, string(mustRead(t, cursor.Path()))) } +func TestGlobalAntigravityHooks(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + agy := NewAntigravityHooksService() + assert.Equal(t, filepath.Join(home, ".gemini", "config", "hooks.json"), agy.Path()) + + require.NoError(t, agy.Install()) + status, err := agy.Status() + require.NoError(t, err) + assert.Empty(t, status.MissingEvents) + assert.Equal(t, agenthook.AntigravityEvents, status.GlobalEvents) + var root map[string]map[string][]map[string]any + require.NoError(t, json.Unmarshal(mustRead(t, agy.Path()), &root)) + assert.Equal(t, []string{AntigravityGlobalHookGroup}, slices.Collect(maps.Keys(root))) + assert.Equal(t, AntigravityGlobalHookCommand("Stop"), root[AntigravityGlobalHookGroup]["Stop"][0]["command"]) + + // The group an older version wrote is replaced where it was + writeFile(t, agy.Path(), `{"a":{},"shelltime":{"Stop":[{"type":"command","command":"`+legacyHookCommand("/usr/local/bin/shelltime", "agy", "Stop")+`","timeout":15}]},"z":{}}`, 0644) + status, err = agy.Status() + require.NoError(t, err) + assert.True(t, status.Installed, "the older version's group is read") + assert.Equal(t, []string{"/usr/local/bin/shelltime"}, status.Binaries) + require.NoError(t, agy.Install()) + data := string(mustRead(t, agy.Path())) + assert.Regexp(t, `(?s)^\{\s*"a".*"shelltime-global".*"z"`, data) + assert.NotContains(t, data, `"shelltime":`) + + // Both groups are ShellTime's: Status reads them and Uninstall removes them + writeFile(t, agy.Path(), `{"shelltime":{"enabled":false},"shelltime-global":{"enabled":false},"mine":{}}`, 0644) + status, err = agy.Status() + require.NoError(t, err) + assert.True(t, status.Present) + assert.False(t, status.Installed, "disabled groups run nothing") + require.NoError(t, agy.Uninstall()) + assert.JSONEq(t, `{"mine":{}}`, string(mustRead(t, agy.Path()))) + + // A project's file has only its own group + repo := t.TempDir() + project := NewAntigravityProjectHooksService(repo) + globalGroup, err := json.Marshal(map[string]any{AntigravityGlobalHookGroup: map[string]any{ + "Stop": []any{map[string]any{"type": "command", "command": AntigravityGlobalHookCommand("Stop")}}, + }}) + require.NoError(t, err) + writeFile(t, project.Path(), string(globalGroup), 0644) + status, err = project.Status() + require.NoError(t, err) + assert.False(t, status.Present) +} + +func TestIsGlobalHookCommand(t *testing.T) { + assert.True(t, isGlobalHookCommand(CursorGlobalHookCommand("stop"))) + assert.True(t, isGlobalHookCommand(AntigravityGlobalHookCommand("Stop"))) + assert.False(t, isGlobalHookCommand(CursorProjectHookCommand("stop")), "a project's command leaves events to the global hooks") + assert.False(t, isGlobalHookCommand(legacyHookCommand("/usr/local/bin/shelltime", "cursor", "stop")), "an older version's names its binary by path") + assert.False(t, isGlobalHookCommand("shelltime hook-ingest --agent cursor --event stop"), "without the search, it may not find what a project's command finds") + assert.False(t, isGlobalHookCommand("say done")) +} + func TestAntigravityProjectHooks(t *testing.T) { t.Setenv("HOME", t.TempDir()) repo := t.TempDir() diff --git a/model/antigravity_hooks.go b/model/antigravity_hooks.go index 22bde00..2548b31 100644 --- a/model/antigravity_hooks.go +++ b/model/antigravity_hooks.go @@ -12,8 +12,14 @@ import ( ) const ( - // AntigravityHookGroup is the named hook group ShellTime owns in an Antigravity hook file. + // AntigravityHookGroup is the named hook group ShellTime owns in a project's Antigravity hook + // file, and the one older versions wrote into the global file. AntigravityHookGroup = "shelltime" + // AntigravityGlobalHookGroup is the named hook group ShellTime owns in the global hook file. + // It is named apart from the project's group: should Antigravity ever let a workspace group + // replace a global group of the same name, the project's hooks, which leave events to the + // global ones, would otherwise record nothing. + AntigravityGlobalHookGroup = "shelltime-global" // AntigravityHookTimeoutSeconds bounds each hook run, in whole seconds as Antigravity wants. AntigravityHookTimeoutSeconds = 15 // antigravityHookAgent is the --agent value written into the commands. @@ -21,11 +27,12 @@ const ( ) // AntigravityHooksService registers `shelltime hook-ingest` for Antigravity's hook events in a -// project's .agents/hooks.json, which the app and the agy CLI run in that workspace (ahead of -// the global file) and the Antigravity agent reads in its Gemini API sandbox. The file's root is -// an object of named hook groups; ShellTime owns the "shelltime" group and leaves the others -// alone. The global ~/.gemini/config/hooks.json, where older versions installed the hooks, is -// only read and cleaned. +// hook file: a project's .agents/hooks.json, which the app and the agy CLI run in that workspace +// and the Antigravity agent reads in its Gemini API sandbox, or the user's global +// ~/.gemini/config/hooks.json, which they run in every workspace on the machine. The file's root +// is an object of named hook groups; ShellTime owns the "shelltime" group of a project's file +// and the "shelltime-global" group of the global one (where older versions wrote "shelltime", +// which install replaces), and leaves the others alone. // // Antigravity's parser is strict: a byte order mark, a comment or a trailing comma makes it // drop the whole file. A file like that is refused, never rewritten, and the file is always @@ -35,8 +42,7 @@ type AntigravityHooksService struct { project bool } -// NewAntigravityHooksService manages the global ~/.gemini/config/hooks.json: Status and -// Uninstall only. +// NewAntigravityHooksService manages the user's global ~/.gemini/config/hooks.json. func NewAntigravityHooksService() *AntigravityHooksService { return &AntigravityHooksService{path: os.ExpandEnv("$HOME/.gemini/config/hooks.json")} } @@ -52,9 +58,32 @@ func (s *AntigravityHooksService) Path() string { } // AntigravityProjectHookCommand is the command a project's hook file runs for an Antigravity -// hook event (see projectHookCommand). +// hook event (see hookCommand). func AntigravityProjectHookCommand(event string) string { - return projectHookCommand(antigravityHookAgent, event) + return hookCommand(antigravityHookAgent, event, true) +} + +// AntigravityGlobalHookCommand is the command the global hook file runs for an Antigravity hook +// event (see hookCommand). +func AntigravityGlobalHookCommand(event string) string { + return hookCommand(antigravityHookAgent, event, false) +} + +// group is the hook group ShellTime installs into this file. +func (s *AntigravityHooksService) group() string { + if s.project { + return AntigravityHookGroup + } + return AntigravityGlobalHookGroup +} + +// groups are the hook groups of ShellTime's in this file: what Status reads and Uninstall +// removes. The global file's include the one older versions wrote. +func (s *AntigravityHooksService) groups() []string { + if s.project { + return []string{AntigravityHookGroup} + } + return []string{AntigravityGlobalHookGroup, AntigravityHookGroup} } type antigravityHookHandler struct { @@ -68,15 +97,15 @@ type antigravityHookMatcher struct { Hooks []antigravityHookHandler `json:"hooks"` } -// antigravityHookGroupValue builds the "shelltime" group. Tool events take matchers, the -// others a flat list of handlers. PreToolUse is never registered: a reply without a decision -// denies the tool call. -func antigravityHookGroupValue() (json.RawMessage, error) { +// antigravityHookGroupValue builds ShellTime's group, with the commands of a project's file or +// of the global one. Tool events take matchers, the others a flat list of handlers. PreToolUse +// is never registered: a reply without a decision denies the tool call. +func antigravityHookGroupValue(project bool) (json.RawMessage, error) { var group []jsonField for _, event := range agenthook.AntigravityEvents { handler := antigravityHookHandler{ Type: "command", - Command: AntigravityProjectHookCommand(event), + Command: hookCommand(antigravityHookAgent, event, project), Timeout: AntigravityHookTimeoutSeconds, } var value any = []antigravityHookHandler{handler} @@ -92,12 +121,9 @@ func antigravityHookGroupValue() (json.RawMessage, error) { return encodeOrderedObject(group), nil } -// Install sets the "shelltime" group of a project's file, in place when it is already there. It -// creates the file when missing. +// Install sets ShellTime's group, in place when it is already there. In the global file it +// takes the place of the group older versions wrote. It creates the file when missing. func (s *AntigravityHooksService) Install() error { - if !s.project { - return ErrUserHooksRetired - } data, mode, err := readJSONFileWithMode(s.path) if err != nil { return err @@ -106,16 +132,30 @@ func (s *AntigravityHooksService) Install() error { if err != nil { return err } - group, err := antigravityHookGroupValue() + group, err := antigravityHookGroupValue(s.project) if err != nil { return err } - root = setField(root, AntigravityHookGroup, group) + name := s.group() + if _, ok := getField(root, name); !ok { + // Where the group an older version wrote was + for i := range root { + if containsString(s.groups(), root[i].Key) { + root[i].Key = name + break + } + } + } + root = setField(root, name, group) + for _, legacy := range s.groups() { + if legacy != name { + root, _ = deleteField(root, legacy) + } + } return s.write(root, data, mode) } -// Uninstall removes the "shelltime" group. A missing file, or one without the group, is left -// alone. +// Uninstall removes ShellTime's groups. A missing file, or one without them, is left alone. func (s *AntigravityHooksService) Uninstall() error { data, mode, err := readJSONFileWithMode(s.path) if err != nil || data == nil { @@ -125,15 +165,20 @@ func (s *AntigravityHooksService) Uninstall() error { if err != nil { return err } - root, removed := deleteField(root, AntigravityHookGroup) - if !removed { + removedAny := false + for _, name := range s.groups() { + var removed bool + root, removed = deleteField(root, name) + removedAny = removedAny || removed + } + if !removedAny { return nil } return s.write(root, data, mode) } -// Status reports which managed events the "shelltime" group registers hook-ingest for and -// which binaries those commands run. +// Status reports which managed events ShellTime's groups register hook-ingest for and which +// binaries those commands run. func (s *AntigravityHooksService) Status() (AgentHooksStatus, error) { status := AgentHooksStatus{} data, _, err := readJSONFileWithMode(s.path) @@ -144,29 +189,36 @@ func (s *AntigravityHooksService) Status() (AgentHooksStatus, error) { if err != nil { return status, err } - var group []jsonField - if raw, ok := getField(root, AntigravityHookGroup); ok { + var groups [][]jsonField + for _, name := range s.groups() { + raw, ok := getField(root, name) + if !ok { + continue + } // Uninstall removes the whole group, whatever it holds status.Present = true - group, _ = decodeOrderedObject(raw) - } - if raw, ok := getField(group, "enabled"); ok && string(bytes.TrimSpace(raw)) == "false" { - // A disabled group runs none of its hooks - group = nil + group, _ := decodeOrderedObject(raw) + if raw, ok := getField(group, "enabled"); ok && string(bytes.TrimSpace(raw)) == "false" { + // A disabled group runs none of its hooks + continue + } + groups = append(groups, group) } for _, event := range agenthook.AntigravityEvents { var commands []string - if raw, ok := getField(group, event); ok { - var value any - if json.Unmarshal(raw, &value) == nil { - commands = collectHookCommands(value, commands) + for _, group := range groups { + if raw, ok := getField(group, event); ok { + var value any + if json.Unmarshal(raw, &value) == nil { + commands = collectHookCommands(value, commands) + } } } found := false for _, command := range commands { if strings.Contains(command, HookIngestSubcommand) { found = true - status.addBinary(event, hookCommandBinary(command)) + status.addCommand(event, command) } } if !found { diff --git a/model/cursor_hooks.go b/model/cursor_hooks.go index 75b71bb..e3eb75b 100644 --- a/model/cursor_hooks.go +++ b/model/cursor_hooks.go @@ -23,23 +23,20 @@ var utf8BOM = []byte("\xEF\xBB\xBF") // form a version wrote. const cursorHookMarker = HookIngestSubcommand + " --agent cursor" -// ErrUserHooksRetired is returned for installing into an agent's user-level hook file: ShellTime -// installs its hooks into projects only, and only removes the ones older versions left there. -var ErrUserHooksRetired = errors.New("ShellTime hooks are installed into projects, not the user's hook file") - -// CursorHooksService registers `shelltime hook-ingest` for Cursor's hook events in a project's -// .cursor/hooks.json, which Cursor runs in that project and Cloud Agents run as the only one: +// CursorHooksService registers `shelltime hook-ingest` for Cursor's hook events in a hook file: +// a project's .cursor/hooks.json, which Cursor runs in that project and Cloud Agents run as the +// only one, or the user's global ~/.cursor/hooks.json, which Cursor runs in every folder on the +// machine (never in a Cloud Agent): // // {"version": 1, "hooks": {"": [{"command": "…"}]}} // -// Every other hook and key stays as the user wrote it, in its order. The user's own -// ~/.cursor/hooks.json, where older versions installed the hooks, is only read and cleaned. +// Every other hook and key stays as the user wrote it, in its order. type CursorHooksService struct { path string project bool } -// NewCursorHooksService manages the user's ~/.cursor/hooks.json: Status and Uninstall only. +// NewCursorHooksService manages the user's global ~/.cursor/hooks.json. func NewCursorHooksService() *CursorHooksService { return &CursorHooksService{path: os.ExpandEnv("$HOME/.cursor/hooks.json")} } @@ -55,18 +52,31 @@ func (s *CursorHooksService) Path() string { } // CursorProjectHookCommand is the command a project's hook file runs for a Cursor hook event -// (see projectHookCommand). +// (see hookCommand). func CursorProjectHookCommand(event string) string { - return projectHookCommand(agenthook.AgentCursor, event) + return hookCommand(agenthook.AgentCursor, event, true) } -// Install registers CursorProjectHookCommand for every managed event of a project's file. It -// creates the file when missing, sets "version": 1 only when absent, and replaces a ShellTime -// command already there in place (an older form), so running it again changes nothing else. -func (s *CursorHooksService) Install() error { - if !s.project { - return ErrUserHooksRetired +// CursorGlobalHookCommand is the command the global hook file runs for a Cursor hook event (see +// hookCommand). +func CursorGlobalHookCommand(event string) string { + return hookCommand(agenthook.AgentCursor, event, false) +} + +// command is the command this file runs for event. +func (s *CursorHooksService) command(event string) string { + if s.project { + return CursorProjectHookCommand(event) } + return CursorGlobalHookCommand(event) +} + +// Install registers ShellTime's command (CursorProjectHookCommand in a project's file, +// CursorGlobalHookCommand in the global one) for every managed event. It creates the file when +// missing, sets "version": 1 only when absent, and replaces a ShellTime command already there +// in place (an older form, such as the absolute path older versions wrote into the global +// file), so running it again changes nothing else. +func (s *CursorHooksService) Install() error { data, mode, err := readJSONFileWithMode(s.path) if err != nil { return err @@ -113,7 +123,7 @@ func (s *CursorHooksService) Install() error { return fmt.Errorf("%w: hooks.%s in %s isn't an array", ErrHookFileInvalid, event, s.path) } } - entries, err = upsertCursorHookEntry(entries, CursorProjectHookCommand(event)) + entries, err = upsertCursorHookEntry(entries, s.command(event)) if err != nil { return err } @@ -181,7 +191,7 @@ func (s *CursorHooksService) Status() (AgentHooksStatus, error) { for _, entry := range entries { if _, command, ok := commandField(entry); ok && strings.Contains(command, cursorHookMarker) { found = true - status.addBinary(event, hookCommandBinary(command)) + status.addCommand(event, command) } } } From cf00d5dcf4193d916c06847b7677c32275a9fdee Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 17:23:03 +0000 Subject: [PATCH 2/2] fix(cli): only working global hooks stand in for a project's doctor and project install treated any ShellTime hook in the global file as recording, also an older version's whose binary is gone, which records nothing: a project without hooks of its own then got a note instead of the warning. globalHooksRecord counts the --global command or an older version's existing binary. isGlobalHookCommand now reads --project from hook-ingest's own arguments (hookIngestArgs), so text elsewhere in a hand-edited command doesn't count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014EpZRfhTSPrQA29S15UhWm --- commands/agent_hooks_cmd_test.go | 10 ++++++++-- commands/agent_hooks_install.go | 2 +- commands/doctor_checks.go | 16 +++++++++------- commands/doctor_test.go | 9 +++++++++ commands/hook_ingest.go | 13 +++++++++++++ commands/hook_ingest_test.go | 18 ++++++++++++++++++ model/agent_hooks_common.go | 24 +++++++++++++++++++++--- model/agent_hooks_project_test.go | 11 +++++++++++ 8 files changed, 90 insertions(+), 13 deletions(-) diff --git a/commands/agent_hooks_cmd_test.go b/commands/agent_hooks_cmd_test.go index bbaecc4..4075c6a 100644 --- a/commands/agent_hooks_cmd_test.go +++ b/commands/agent_hooks_cmd_test.go @@ -33,13 +33,19 @@ func TestCursorInstallAndUninstallCommands(t *testing.T) { path := filepath.Join(repo, ".cursor", "hooks.json") require.NoError(t, os.MkdirAll(filepath.Dir(path), 0755)) require.NoError(t, os.WriteFile(path, []byte(`{"version":1,"hooks":{"stop":[{"command":"say done"}]}}`), 0644)) - // What an older version installed in the user's own file + // What an older version installed in the user's own file, first with its binary gone, which + // records nothing userPath := filepath.Join(home, ".cursor", "hooks.json") - installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "/usr/local/bin/shelltime") + installUserHooksFor(t, userPath, "cursor", []string{"stop"}, filepath.Join(home, "gone", "shelltime")) app := &cli.App{Name: "t", Commands: []*cli.Command{CursorCommand}} out := captureColor(t) require.NoError(t, app.Run([]string{"t", "cursor", "install"})) + assert.NotContains(t, stripANSI(out.String()), "keep recording your other folders") + + installUserHooksFor(t, userPath, "cursor", []string{"stop"}, "") + out.Reset() + require.NoError(t, app.Run([]string{"t", "cursor", "install"})) text := stripANSI(out.String()) assert.Contains(t, text, "Cursor hooks installed in "+path) assert.Contains(t, text, "The ShellTime hooks in "+userPath+" keep recording your other folders") diff --git a/commands/agent_hooks_install.go b/commands/agent_hooks_install.go index ab548e1..ed53dd0 100644 --- a/commands/agent_hooks_install.go +++ b/commands/agent_hooks_install.go @@ -96,7 +96,7 @@ func installAgentHooks(a agentHooks, global bool) error { return err } color.Green.Printf("%s hooks installed in %s\n", a.name, svc.Path()) - if status, err := a.global().Status(); err == nil && status.Installed { + if status, err := a.global().Status(); err == nil && globalHooksRecord(status) { color.Gray.Printf("The ShellTime hooks in %s keep recording your other folders; this project's hooks\n", a.global().Path()) color.Gray.Printf("leave events to them, so nothing is counted twice. `%s` removes both.\n", uninstallCommand(a)) } diff --git a/commands/doctor_checks.go b/commands/doctor_checks.go index 65ee3a4..48bba93 100644 --- a/commands/doctor_checks.go +++ b/commands/doctor_checks.go @@ -1050,7 +1050,9 @@ func doctorCheckAgentHooks(a doctorAgentHooks) []doctorResult { } global := a.hooks.global() globalStatus, globalErr := global.Status() - globalInstalled := globalErr == nil && globalStatus.Installed + // Global hooks that are broken (an older version's binary gone) record nothing, so they + // don't stand in for a project's + globalRecords := globalErr == nil && globalHooksRecord(globalStatus) var results []doctorResult projectInstalled := false @@ -1063,9 +1065,9 @@ func doctorCheckAgentHooks(a doctorAgentHooks) []doctorResult { switch { case err == nil: var project []doctorResult - project, projectInstalled = doctorCheckProjectHooks(a, a.hooks.project(root), globalInstalled) + project, projectInstalled = doctorCheckProjectHooks(a, a.hooks.project(root), globalRecords) results = append(results, project...) - case !globalInstalled: + case !globalRecords: results = append(results, doctorResult{ ID: a.id + ".hooks", Status: doctorSkip, @@ -1081,9 +1083,9 @@ func doctorCheckAgentHooks(a doctorAgentHooks) []doctorResult { // doctorCheckProjectHooks checks the hook file of the project doctor runs in, and reports // whether it has ShellTime hooks. A project without them is recorded all the same while the -// agent's global hooks are installed, so it is only a note then: only the agent's cloud runs -// need the project's own. -func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile, globalInstalled bool) ([]doctorResult, bool) { +// agent's global hooks record (globalRecords), so it is only a note then: only the agent's cloud +// runs need the project's own. +func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile, globalRecords bool) ([]doctorResult, bool) { fixHint := fmt.Sprintf("Run `%s` in this repository, commit %s, then restart %s.", a.command, file.Path(), a.name) status, err := file.Status() switch { @@ -1096,7 +1098,7 @@ func doctorCheckProjectHooks(a doctorAgentHooks, file agentHooksFile, globalInst }}, false case err != nil: return []doctorResult{{ID: a.id + ".hooks", Status: doctorSkip, Message: fmt.Sprintf("Couldn't read %s: %v", file.Path(), err)}}, false - case !status.Installed && globalInstalled: + case !status.Installed && globalRecords: return []doctorResult{{ ID: a.id + ".hooks", Status: doctorInfo, diff --git a/commands/doctor_test.go b/commands/doctor_test.go index 24bdbe3..9756c85 100644 --- a/commands/doctor_test.go +++ b/commands/doctor_test.go @@ -784,6 +784,15 @@ func TestDoctorCheckCursor(t *testing.T) { assert.Contains(t, hooks.Fix, "Cloud Agents") assert.Nil(t, hooks.AutoFix) + // Global hooks that record nothing don't stand in for the project's + installUserHooksFor(t, userPath, "cursor", agenthook.CursorEvents, "/gone/shelltime") + results = doctorCheckCursor(env) + hooks = findDoctorResult(t, results, "cursor.hooks") + assert.Equal(t, doctorWarn, hooks.Status, "the global hooks' binary is gone") + assert.NotNil(t, hooks.AutoFix) + assert.Equal(t, doctorFail, findDoctorResult(t, results, "cursor.global_hooks").Status) + require.NoError(t, model.NewCursorHooksService().Install()) + // Outside a project the global hooks are checked, with what they record with t.Chdir(home) results = doctorCheckCursor(env) diff --git a/commands/hook_ingest.go b/commands/hook_ingest.go index 615acf5..f7cde03 100644 --- a/commands/hook_ingest.go +++ b/commands/hook_ingest.go @@ -309,6 +309,19 @@ func userHooksRecord(agent, event string) bool { return false } +// globalHooksRecord reports whether an agent's user-level hook file, with status, records +// events: with the command `install --global` writes, or with an older version's whose binary is +// still there. Like userHooksRecord, but for any event. +func globalHooksRecord(status model.AgentHooksStatus) bool { + if !status.Installed { + return false + } + if len(status.GlobalEvents) > 0 { + return true + } + return slices.ContainsFunc(status.Binaries, hookBinaryExists) +} + // hookBinaryExists reports whether an older version's hook command runs a binary that is still // there: an absolute path to a file the agent can execute. func hookBinaryExists(bin string) bool { diff --git a/commands/hook_ingest_test.go b/commands/hook_ingest_test.go index 40f690d..c2be2af 100644 --- a/commands/hook_ingest_test.go +++ b/commands/hook_ingest_test.go @@ -600,6 +600,24 @@ func TestUserHooksRecord(t *testing.T) { assert.False(t, userHooksRecord(agenthook.AgentAntigravity, "Stop"), "another agent's file") } +func TestGlobalHooksRecord(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + status := func() model.AgentHooksStatus { + s, err := model.NewCursorHooksService().Status() + require.NoError(t, err) + return s + } + assert.False(t, globalHooksRecord(status()), "no hook file") + + installUserCursorHooks(t, "") + assert.True(t, globalHooksRecord(status()), "an older version's, whose binary is there") + installUserCursorHooks(t, filepath.Join(t.TempDir(), "shelltime")) + assert.False(t, globalHooksRecord(status()), "an older version's, whose binary is gone") + + require.NoError(t, model.NewCursorHooksService().Install()) + assert.True(t, globalHooksRecord(status())) +} + func TestHookBinaryExists(t *testing.T) { exe, err := os.Executable() require.NoError(t, err) diff --git a/model/agent_hooks_common.go b/model/agent_hooks_common.go index b28f599..4b82116 100644 --- a/model/agent_hooks_common.go +++ b/model/agent_hooks_common.go @@ -7,6 +7,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "github.com/malamtime/cli/agenthook" @@ -70,9 +71,26 @@ func hookCommand(agent, event string, project bool) string { // self-contained command (hookCommand) without ProjectHookFlag. It records an event wherever a // project's command for it does, since both look for the same binaries in the same places. func isGlobalHookCommand(command string) bool { - return strings.Contains(command, "command -v "+ProjectHookDaemon+" ") && - hookCommandBinary(command) == ProjectHookCLI && - !strings.Contains(command, " "+ProjectHookFlag) + if !strings.Contains(command, "command -v "+ProjectHookDaemon+" ") || hookCommandBinary(command) != ProjectHookCLI { + return false + } + return !slices.ContainsFunc(hookIngestArgs(command), func(arg string) bool { + return arg == ProjectHookFlag || strings.HasPrefix(arg, ProjectHookFlag+"=") + }) +} + +// hookIngestArgs returns the arguments a hook command passes to hook-ingest: the words after +// " hook-ingest" up to the end of that invocation (the ")" closing hookCommand's "$(", or a +// shell operator), so text elsewhere in a hand-edited command doesn't count. +func hookIngestArgs(command string) []string { + _, rest, ok := strings.Cut(command, " "+HookIngestSubcommand) + if !ok { + return nil + } + if i := strings.IndexAny(rest, ");|&"); i >= 0 { + rest = rest[:i] + } + return strings.Fields(rest) } // ProjectHooksRoot returns the root of the project dir is in, where its agents look for project diff --git a/model/agent_hooks_project_test.go b/model/agent_hooks_project_test.go index 8b4349d..dc3c34f 100644 --- a/model/agent_hooks_project_test.go +++ b/model/agent_hooks_project_test.go @@ -374,6 +374,17 @@ func TestIsGlobalHookCommand(t *testing.T) { assert.False(t, isGlobalHookCommand(legacyHookCommand("/usr/local/bin/shelltime", "cursor", "stop")), "an older version's names its binary by path") assert.False(t, isGlobalHookCommand("shelltime hook-ingest --agent cursor --event stop"), "without the search, it may not find what a project's command finds") assert.False(t, isGlobalHookCommand("say done")) + + // Only hook-ingest's own arguments say whether it is a project's + assert.True(t, isGlobalHookCommand(CursorGlobalHookCommand("stop")+"; echo ' --project'"), "the flag outside the invocation") + assert.False(t, isGlobalHookCommand(strings.Replace(CursorGlobalHookCommand("stop"), "--event stop)", "--event stop --project=true)", 1))) +} + +func TestHookIngestArgs(t *testing.T) { + assert.Equal(t, []string{"--agent", "cursor", "--event", "stop", "--project"}, hookIngestArgs(CursorProjectHookCommand("stop"))) + assert.Equal(t, []string{"--agent", "agy", "--event", "Stop"}, hookIngestArgs(AntigravityGlobalHookCommand("Stop"))) + assert.Equal(t, []string{"--agent", "cursor", "--event", "stop"}, hookIngestArgs(legacyHookCommand("/usr/local/bin/shelltime", "cursor", "stop"))) + assert.Nil(t, hookIngestArgs("say done")) } func TestAntigravityProjectHooks(t *testing.T) {