diff --git a/CLAUDE.md b/CLAUDE.md index af13374..920d764 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`; 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`. 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, 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 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). 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`. 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 b002821..ea99600 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,9 @@ shelltime cc pr --session-id https://github.com/owner/r The command hands the URLs to the daemon, and the daemon sends them to ShellTime, where they appear on the session. If no daemon is running, the CLI sends them itself. A session can link any number of PRs. Sending the same URL again does nothing. The command does nothing if you are not logged in. -For Codex, and for Claude Code sessions without the mod, the ShellTime server looks for opened PRs in the OTEL data the daemon forwards. It confirms them through the ShellTime GitHub App, so this needs the app connected in your ShellTime settings. +For **Cursor** and **Google Antigravity**, `shelltime hook-ingest` watches successful `gh pr create` and GitHub MCP `create_pull_request` calls (`postToolUse` / `PostToolUse`, reading the Antigravity `transcript.jsonl` step when present) and extracts only the created pull request URLs — raw tool output is never stored or uploaded — so the daemon links them via `/api/v1/cc/session-pull-requests`. + +For Codex, Claude Code sessions without the mod, and Cursor or Antigravity calls whose output was not visible locally, the ShellTime server also looks for opened PRs in the telemetry the daemon forwards. It confirms them through the ShellTime GitHub App, so this needs the app connected in your ShellTime settings. ## Security and Privacy diff --git a/agenthook/antigravity.go b/agenthook/antigravity.go index e313903..61f68db 100644 --- a/agenthook/antigravity.go +++ b/agenthook/antigravity.go @@ -54,6 +54,9 @@ func normalizeAntigravity(ev *Event, event string, p payload) { } else { ev.EventType = EventToolUse ev.Status = StatusOK + if isPRCreateToolCall(ev.ToolName, ev.Command) { + ev.PullRequestURLs = extractAntigravityToolPRURLs(p, transcript) + } } case strings.ToLower(AntigravityPostInvocation): ev.EventType = EventAgentResponse diff --git a/agenthook/antigravity_transcript.go b/agenthook/antigravity_transcript.go index 01dee9b..54b2b99 100644 --- a/agenthook/antigravity_transcript.go +++ b/agenthook/antigravity_transcript.go @@ -82,38 +82,91 @@ func applyAntigravityTranscriptUsage(ev *Event, transcriptPath string, p payload } } -// readAntigravityInvocationUsage scans path backwards in bounded chunks from EOF, collecting -// the latest completed model row for each step_index >= startStep (and <= maxStep when maxStep >= 0). -// Non-usage lines are filtered cheaply without full JSON unmarshalling. If the 4 MiB scan cap is -// reached before finding the invocation boundary, it returns false rather than reporting partial counts. -func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigravityStepUsage, bool) { +// scanJSONLBackwards scans a regular .jsonl file backwards from EOF in bounded chunks +// (at most maxAntigravityTranscriptBytes), invoking processLine on each complete line from +// newest to oldest until processLine returns true or BOF is reached. reachedBoundary is true +// when the scan stopped early via processLine or reached BOF; ok is false if the file is +// missing, unreadable, non-regular, empty, or not a .jsonl file. +func scanJSONLBackwards(path string, processLine func(line []byte) (stop bool)) (reachedBoundary bool, ok bool) { + path = expandHomePath(path) + if !strings.EqualFold(filepath.Ext(path), ".jsonl") { + return false, false + } // Stat before Open so a FIFO or device node named *.jsonl can never block Open. statInfo, err := os.Stat(path) if err != nil || !statInfo.Mode().IsRegular() || statInfo.Size() == 0 { - return antigravityStepUsage{}, false + return false, false } - f, err := os.Open(path) if err != nil { - return antigravityStepUsage{}, false + return false, false } defer f.Close() info, err := f.Stat() if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { - return antigravityStepUsage{}, false + return false, false } - steps := map[int]antigravityStepUsage{} - latestStep := -1 - latestModel := "" - pos := info.Size() var scanned int64 var carry []byte + stop := false + + for pos > 0 && scanned < maxAntigravityTranscriptBytes && !stop { + chunkSize := int64(antigravityTranscriptChunkBytes) + if chunkSize > pos { + chunkSize = pos + } + if remaining := int64(maxAntigravityTranscriptBytes) - scanned; chunkSize > remaining { + chunkSize = remaining + } + pos -= chunkSize + buf := make([]byte, chunkSize) + if _, err := f.ReadAt(buf, pos); err != nil && err != io.EOF { + break + } + scanned += chunkSize + + if len(carry) > 0 { + buf = append(buf, carry...) + carry = nil + } + + // Split lines from the end of buf; keep the leading fragment in carry when pos > 0. + end := len(buf) + for { + nl := bytes.LastIndexByte(buf[:end], '\n') + if nl < 0 { + if pos == 0 { + stop = processLine(buf[:end]) + } else { + carry = append([]byte(nil), buf[:end]...) + } + break + } + if processLine(buf[nl+1 : end]) { + stop = true + break + } + end = nl + } + } + + return pos == 0 || stop, true +} + +// readAntigravityInvocationUsage scans path backwards in bounded chunks from EOF, collecting +// the latest completed model row for each step_index >= startStep (and <= maxStep when maxStep >= 0). +// Non-usage lines are filtered cheaply without full JSON unmarshalling. If the 4 MiB scan cap is +// reached before finding the invocation boundary, it returns false rather than reporting partial counts. +func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigravityStepUsage, bool) { + steps := map[int]antigravityStepUsage{} + latestStep := -1 + latestModel := "" consecutiveBelow := 0 - processLine := func(line []byte) (stop bool) { + reachedBoundary, ok := scanJSONLBackwards(path, func(line []byte) (stop bool) { line = bytes.TrimSpace(line) if len(line) == 0 { return false @@ -177,52 +230,11 @@ func readAntigravityInvocationUsage(path string, startStep, maxStep int) (antigr latestModel = u.model } return false - } - - stop := false - for pos > 0 && scanned < maxAntigravityTranscriptBytes && !stop { - chunkSize := int64(antigravityTranscriptChunkBytes) - if chunkSize > pos { - chunkSize = pos - } - if remaining := int64(maxAntigravityTranscriptBytes) - scanned; chunkSize > remaining { - chunkSize = remaining - } - pos -= chunkSize - buf := make([]byte, chunkSize) - if _, err := f.ReadAt(buf, pos); err != nil && err != io.EOF { - break - } - scanned += chunkSize - - if len(carry) > 0 { - buf = append(buf, carry...) - carry = nil - } - - // Split lines from the end of buf; keep the leading fragment in carry when pos > 0. - end := len(buf) - for { - nl := bytes.LastIndexByte(buf[:end], '\n') - if nl < 0 { - if pos == 0 { - stop = processLine(buf[:end]) - } else { - carry = append([]byte(nil), buf[:end]...) - } - break - } - if processLine(buf[nl+1 : end]) { - stop = true - break - } - end = nl - } - } + }) // If we hit the scan cap before reaching BOF or an earlier invocation boundary, // omit usage rather than reporting a truncated partial sum as exact. - if pos > 0 && !stop { + if !ok || !reachedBoundary { return antigravityStepUsage{}, false } diff --git a/agenthook/cursor.go b/agenthook/cursor.go index 750ca61..9fd8e7f 100644 --- a/agenthook/cursor.go +++ b/agenthook/cursor.go @@ -64,7 +64,11 @@ func normalizeCursor(ev *Event, event string, p payload, getenv func(string) str applyToolInput(ev, p.str("tool_name"), p["tool_input"]) ev.DurationMs = durationMs(p.number("duration")) p.setStringMetadata(ev, "tool_use_id", "tool_use_id") - // tool_output is never collected: it can be large and hold anything the tool read + // tool_output is never collected: it can be large and hold anything the tool read. + // For PR-creating tool calls we only extract normalized PR URLs for the daemon to link. + if isPRCreateToolCall(ev.ToolName, ev.Command) { + ev.PullRequestURLs = extractCursorToolPRURLs(p) + } case strings.ToLower(CursorPostToolUseFailure): ev.EventType = EventToolFailure applyToolInput(ev, p.str("tool_name"), p["tool_input"]) diff --git a/agenthook/event.go b/agenthook/event.go index 711a279..81a9c10 100644 --- a/agenthook/event.go +++ b/agenthook/event.go @@ -92,6 +92,12 @@ type Event struct { // 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"` + + // PullRequestURLs travels from hook-ingest to the daemon (and the pending file) only, + // never to POST /api/v1/agent-hooks: it holds normalized pull request URLs opened by a + // successful `gh pr create` or GitHub MCP `create_pull_request` tool call so the daemon + // can link them via POST /api/v1/cc/session-pull-requests. + PullRequestURLs []string `json:"pull_request_urls,omitempty"` } // SetMetadata sets one metadata key, creating the map when needed. diff --git a/agenthook/pr.go b/agenthook/pr.go new file mode 100644 index 0000000..b110b75 --- /dev/null +++ b/agenthook/pr.go @@ -0,0 +1,302 @@ +package agenthook + +import ( + "bytes" + "encoding/json" + "net/url" + "regexp" + "sort" + "strconv" + "strings" +) + +const maxPullRequestURLsPerEvent = 20 + +var ( + // ghPRCreatePattern finds `gh pr create` in a shell command, including when chained + // or invoked via a shell `-c` wrapper (`bash -lc "gh pr create ..."`), without matching + // arbitrary quoted text such as `echo "gh pr create"`. + ghPRCreatePattern = regexp.MustCompile(`(?:^|[\s;&|(]|-[a-zA-Z]*c\s+["'])gh\s+pr\s+create\b`) + // prURLPattern finds pull request URLs in tool output text. + prURLPattern = regexp.MustCompile(`https?://[^\s"'<>)\]]+/[^\s"'<>)\]]+/[^\s"'<>)\]]+/pull/\d+`) +) + +// prCanonicalURLKeys name fields on a structured PR-creation response (such as GitHub MCP +// `create_pull_request`) that carry the created pull request's canonical URL directly. +// When any of these holds a PR URL, sibling prose fields like `body` are never scanned. +var prCanonicalURLKeys = []string{ + "html_url", + "htmlUrl", + "pull_request_url", + "pullRequestUrl", + "pr_url", + "prUrl", + "url", +} + +// prOutputIgnoredKeys are JSON object keys that hold tool inputs, stderr, or prose fields +// rather than created-PR output, so URLs mentioned in PR bodies or `gh` stderr notices are ignored. +var prOutputIgnoredKeys = map[string]bool{ + "stderr": true, + "error": true, + "command": true, + "commandline": true, + "args": true, + "input": true, + "tool_input": true, + "toolinput": true, + "tool_call": true, + "toolcall": true, + "body": true, + "description": true, + "title": true, +} + +// antigravityTranscriptOutputKeys name the fields on a transcript.jsonl tool step row +// that may hold tool output (never command args or stderr). +var antigravityTranscriptOutputKeys = []string{ + "output", + "result", + "response", + "tool_output", + "toolOutput", + "tool_result", + "toolResult", + "tool_response", + "toolResponse", + "command_output", + "commandOutput", + "combined_output", + "combinedOutput", + "run_command_output", + "runCommandOutput", + "content", +} + +// isPRCreateToolCall reports whether a completed tool call ran `gh pr create` or called a +// GitHub MCP `create_pull_request` tool. +func isPRCreateToolCall(toolName, command string) bool { + if strings.HasSuffix(strings.ToLower(strings.TrimSpace(toolName)), "create_pull_request") { + return true + } + return command != "" && ghPRCreatePattern.MatchString(command) +} + +func extractCursorToolPRURLs(p payload) []string { + for _, key := range []string{"tool_output", "tool_response"} { + if raw, ok := p[key]; ok { + if urls := extractPullRequestURLsFromRaw(raw); len(urls) > 0 { + return urls + } + } + } + return nil +} + +func extractAntigravityToolPRURLs(p payload, transcriptPath string) []string { + for _, key := range []string{"toolOutput", "toolResult", "toolResponse", "result", "output"} { + if raw, ok := p[key]; ok { + if urls := extractPullRequestURLsFromRaw(raw); len(urls) > 0 { + return urls + } + } + } + if transcriptPath == "" { + return nil + } + stepIdx, ok := p.nonNegInt("stepIdx") + if !ok { + return nil + } + return extractAntigravityTranscriptPRURLs(transcriptPath, stepIdx) +} + +// extractPullRequestURLsFromRaw extracts distinct normalized pull request URLs from a +// JSON tool output value (string, object, or array). A structured object that reports an +// error or non-zero exit code yields none; one with a canonical PR URL field (`html_url`, +// `url`, ...) uses that alone; one with a `stdout` field scans `stdout` alone so `gh` +// stderr notices about existing PRs are never linked. +func extractPullRequestURLsFromRaw(raw json.RawMessage) []string { + var out []string + seen := map[string]bool{} + collectPullRequestURLsFromRaw(raw, seen, &out) + return out +} + +func collectPullRequestURLsFromRaw(raw json.RawMessage, seen map[string]bool, out *[]string) { + if len(*out) >= maxPullRequestURLsPerEvent { + return + } + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return + } + switch raw[0] { + case '"': + var s string + if err := json.Unmarshal(raw, &s); err != nil { + return + } + trimmed := strings.TrimSpace(s) + if (strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[")) && json.Valid([]byte(trimmed)) { + collectPullRequestURLsFromRaw(json.RawMessage(trimmed), seen, out) + return + } + appendPullRequestURLs(s, seen, out) + case '{': + var obj payload + if err := json.Unmarshal(raw, &obj); err != nil || obj == nil { + return + } + if payloadIndicatesToolError(obj) { + return + } + // Prefer the canonical URL of a structured PR response (e.g. GitHub MCP + // `create_pull_request`) so URLs referenced in sibling fields like `body` are ignored. + for _, key := range prCanonicalURLKeys { + if s := obj.str(key); s != "" { + if norm, ok := normalizePullRequestURL(s); ok { + if !seen[norm] { + seen[norm] = true + *out = append(*out, norm) + } + return + } + } + } + if stdout, ok := obj["stdout"]; ok { + collectPullRequestURLsFromRaw(stdout, seen, out) + return + } + keys := make([]string, 0, len(obj)) + for k := range obj { + if prOutputIgnoredKeys[strings.ToLower(k)] { + continue + } + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + collectPullRequestURLsFromRaw(obj[k], seen, out) + if len(*out) >= maxPullRequestURLsPerEvent { + return + } + } + case '[': + var items []json.RawMessage + if err := json.Unmarshal(raw, &items); err != nil { + return + } + for _, item := range items { + collectPullRequestURLsFromRaw(item, seen, out) + if len(*out) >= maxPullRequestURLsPerEvent { + return + } + } + } +} + +func payloadIndicatesToolError(obj payload) bool { + for _, key := range []string{"isError", "is_error"} { + if b, ok := obj.boolean(key); ok && b { + return true + } + } + for _, key := range []string{"exitCode", "exit_code"} { + if n, ok := obj.number(key); ok && n != 0 { + return true + } + } + if errText := obj.text("error"); errText != "" { + return true + } + return false +} + +func appendPullRequestURLs(text string, seen map[string]bool, out *[]string) { + if text == "" || len(*out) >= maxPullRequestURLsPerEvent { + return + } + for _, raw := range prURLPattern.FindAllString(text, -1) { + norm, ok := normalizePullRequestURL(raw) + if !ok || seen[norm] { + continue + } + seen[norm] = true + *out = append(*out, norm) + if len(*out) >= maxPullRequestURLsPerEvent { + return + } + } +} + +// normalizePullRequestURL normalizes a pull request URL to scheme://host/owner/repo/pull/number, +// matching the server's ParsePullRequestURL. +func normalizePullRequestURL(raw string) (string, bool) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + return "", false + } + parts := strings.Split(strings.TrimPrefix(u.Path, "/"), "/") + if len(parts) < 4 || parts[0] == "" || parts[1] == "" || parts[2] != "pull" { + return "", false + } + number, err := strconv.Atoi(parts[3]) + if err != nil || number <= 0 { + return "", false + } + return u.Scheme + "://" + strings.ToLower(u.Host) + "/" + parts[0] + "/" + parts[1] + "/pull/" + strconv.Itoa(number), true +} + +// extractAntigravityTranscriptPRURLs scans Antigravity's transcript.jsonl backwards from EOF +// for step_index == stepIdx and extracts pull request URLs from its output fields (never its +// command arguments or stderr). Missing, unreadable, non-regular, or unflushed transcripts +// return nil so hook recording never fails or blocks. +func extractAntigravityTranscriptPRURLs(transcriptPath string, stepIdx int) []string { + consecutiveBelow := 0 + var found []string + + scanJSONLBackwards(transcriptPath, func(line []byte) (stop bool) { + line = bytes.TrimSpace(line) + if len(line) == 0 { + return false + } + idx, ok := extractJSONNonNegInt(line, antigravityStepIndexNeedle) + if !ok { + return false + } + if idx < stepIdx { + consecutiveBelow++ + return consecutiveBelow >= antigravityLowerStepThreshold + } + consecutiveBelow = 0 + if idx != stepIdx { + return false + } + var row payload + if err := json.Unmarshal(line, &row); err != nil || row == nil { + return false + } + if payloadIndicatesToolError(row) { + return true + } + if stdout, ok := row["stdout"]; ok { + found = extractPullRequestURLsFromRaw(stdout) + return true + } + var urls []string + seen := map[string]bool{} + for _, key := range antigravityTranscriptOutputKeys { + if raw, ok := row[key]; ok { + collectPullRequestURLsFromRaw(raw, seen, &urls) + } + } + if len(urls) > 0 { + found = urls + return true + } + return false + }) + + return found +} diff --git a/agenthook/pr_test.go b/agenthook/pr_test.go new file mode 100644 index 0000000..646c7bf --- /dev/null +++ b/agenthook/pr_test.go @@ -0,0 +1,166 @@ +package agenthook + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNormalize_CursorPullRequests(t *testing.T) { + common := `"conversation_id":"conv-1","model":"claude-4.5-sonnet","workspace_roots":["/repo"]` + + t.Run("extracts PR URL from gh pr create plain tool_output without keeping tool_output", func(t *testing.T) { + body := `{` + common + `,"tool_name":"Shell","tool_input":{"command":"git push && gh pr create --fill"},"tool_output":"Creating pull request for feat into main\nSECRET_LINE\nhttps://GitHub.com/acme/web/pull/42/files?w=1\nhttps://github.com/acme/web/pull/42\n"}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/web/pull/42"}, ev.PullRequestURLs) + assert.NotContains(t, mustJSON(t, ev), "SECRET_LINE", "raw tool_output must never be stored") + }) + + t.Run("handles bash -lc quoted gh pr create", func(t *testing.T) { + body := `{` + common + `,"tool_name":"Shell","tool_input":{"command":"bash -lc \"gh pr create --title test\""},"tool_output":"https://github.com/acme/cli/pull/101"}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/cli/pull/101"}, ev.PullRequestURLs) + }) + + t.Run("structured output scans stdout only and ignores stderr existing-PR notice", func(t *testing.T) { + body := `{` + common + `,"tool_name":"Shell","tool_input":{"command":"gh pr create --fill"},"tool_output":{"stdout":"https://github.com/acme/web/pull/99\n","stderr":"a pull request for branch already exists: https://github.com/acme/web/pull/10","exit_code":0}}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/web/pull/99"}, ev.PullRequestURLs) + }) + + t.Run("structured output with non-zero exit_code or isError extracts nothing", func(t *testing.T) { + for _, out := range []string{ + `{"stdout":"https://github.com/acme/web/pull/99","exit_code":1}`, + `{"isError":true,"content":[{"type":"text","text":"https://github.com/acme/web/pull/99"}]}`, + `{"error":"already exists","output":"https://github.com/acme/web/pull/99"}`, + } { + body := `{` + common + `,"tool_name":"Shell","tool_input":{"command":"gh pr create --fill"},"tool_output":` + out + `}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Empty(t, ev.PullRequestURLs, out) + } + }) + + t.Run("extracts PR URL from GitHub MCP create_pull_request", func(t *testing.T) { + for _, tc := range []struct { + name string + toolName string + output string + }{ + { + name: "stringified JSON tool_output", + toolName: "mcp__github__create_pull_request", + output: `"{\"id\":1,\"html_url\":\"https://github.com/acme/server/pull/55\"}"`, + }, + { + name: "MCP content array tool_output", + toolName: "MCP:github:create_pull_request", + output: `{"content":[{"type":"text","text":"Created https://github.com/acme/server/pull/55"}]}`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + body := `{` + common + `,"tool_name":"` + tc.toolName + `","tool_input":{"owner":"acme","repo":"server","head":"feat"},"tool_output":` + tc.output + `}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/server/pull/55"}, ev.PullRequestURLs) + }) + } + }) + + t.Run("structured MCP response prefers canonical html_url and ignores PRs referenced in body", func(t *testing.T) { + body := `{` + common + `,"tool_name":"mcp__github__create_pull_request","tool_input":{"owner":"acme","repo":"server"},"tool_output":{"html_url":"https://github.com/acme/server/pull/42","body":"Follow-up to https://github.com/acme/server/pull/10","title":"Fix https://github.com/acme/server/pull/9"}}` + ev, err := Normalize("cursor", CursorPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/server/pull/42"}, ev.PullRequestURLs) + }) + + t.Run("ignores non-create commands, quoted text mentions, PR URLs in command body, and postToolUseFailure", func(t *testing.T) { + cases := []struct { + event string + body string + }{ + { + event: CursorPostToolUse, + body: `{` + common + `,"tool_name":"Shell","tool_input":{"command":"gh pr view 12"},"tool_output":"https://github.com/acme/web/pull/12"}`, + }, + { + event: CursorPostToolUse, + body: `{` + common + `,"tool_name":"Shell","tool_input":{"command":"echo \"gh pr create\""},"tool_output":"https://github.com/acme/web/pull/12"}`, + }, + { + event: CursorPostToolUse, + body: `{` + common + `,"tool_name":"Shell","tool_input":{"command":"grep -rn \"gh pr create\" docs/"},"tool_output":"https://github.com/acme/web/pull/12"}`, + }, + { + event: CursorPostToolUse, + body: `{` + common + `,"tool_name":"Shell","tool_input":{"command":"gh pr create --body \"see https://github.com/acme/web/pull/1\""},"tool_output":"ok"}`, + }, + { + event: CursorPostToolUse, + body: `{` + common + `,"tool_name":"Read","tool_input":{"file_path":"/repo/README.md"},"tool_output":"https://github.com/acme/web/pull/12"}`, + }, + { + event: CursorPostToolUseFailure, + body: `{` + common + `,"tool_name":"Shell","tool_input":{"command":"gh pr create --fill"},"tool_output":"https://github.com/acme/web/pull/12","error_message":"exit 1"}`, + }, + } + for _, tc := range cases { + ev, err := Normalize("cursor", tc.event, []byte(tc.body), testNow, nil) + require.NoError(t, err) + assert.Empty(t, ev.PullRequestURLs) + } + }) +} + +func TestNormalize_AntigravityPullRequests(t *testing.T) { + t.Run("reads PR URL from transcript.jsonl for matching stepIdx without reading args or stderr", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + lines := "" + + `{"step_index":3,"source":"TOOL","status":"DONE","output":"https://github.com/acme/web/pull/1"}` + "\n" + + `{"step_index":5,"source":"TOOL","status":"DONE","args":{"CommandLine":"gh pr create --body https://github.com/acme/web/pull/2"},"stderr":"https://github.com/acme/web/pull/3","output":"Creating pull request...\nhttps://github.com/acme/web/pull/77\n"}` + "\n" + require.NoError(t, os.WriteFile(transcript, []byte(lines), 0o600)) + + body := `{"conversationId":"agy-1","workspacePaths":["/repo"],"transcriptPath":"` + filepath.ToSlash(transcript) + `","stepIdx":5,"toolCall":{"name":"run_command","args":{"CommandLine":"gh pr create --fill"}}}` + ev, err := Normalize("agy", AntigravityPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/web/pull/77"}, ev.PullRequestURLs) + }) + + t.Run("reads direct toolOutput when present on stdin payload", func(t *testing.T) { + body := `{"conversationId":"agy-1","workspacePaths":["/repo"],"stepIdx":2,"toolCall":{"name":"mcp__github__create_pull_request","args":{"owner":"acme","repo":"api"}},"toolOutput":{"html_url":"https://github.com/acme/api/pull/88"}}` + ev, err := Normalize("agy", AntigravityPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://github.com/acme/api/pull/88"}, ev.PullRequestURLs) + }) + + t.Run("ignores failed PostToolUse and failed transcript rows", func(t *testing.T) { + dir := t.TempDir() + transcript := filepath.Join(dir, "transcript.jsonl") + lines := `{"step_index":5,"source":"TOOL","status":"DONE","exit_code":1,"output":"https://github.com/acme/web/pull/77"}` + "\n" + require.NoError(t, os.WriteFile(transcript, []byte(lines), 0o600)) + + bodyFailedRow := `{"conversationId":"agy-1","workspacePaths":["/repo"],"transcriptPath":"` + filepath.ToSlash(transcript) + `","stepIdx":5,"toolCall":{"name":"run_command","args":{"CommandLine":"gh pr create --fill"}}}` + ev, err := Normalize("agy", AntigravityPostToolUse, []byte(bodyFailedRow), testNow, nil) + require.NoError(t, err) + assert.Empty(t, ev.PullRequestURLs) + + bodyHookErr := `{"conversationId":"agy-1","workspacePaths":["/repo"],"stepIdx":5,"error":"exit status 1","toolCall":{"name":"run_command","args":{"CommandLine":"gh pr create --fill"}},"toolOutput":"https://github.com/acme/web/pull/77"}` + ev, err = Normalize("agy", AntigravityPostToolUse, []byte(bodyHookErr), testNow, nil) + require.NoError(t, err) + assert.Empty(t, ev.PullRequestURLs) + }) + + t.Run("missing or unflushed transcript returns no URLs and never fails", func(t *testing.T) { + body := `{"conversationId":"agy-1","workspacePaths":["/repo"],"transcriptPath":"/no/such/transcript.jsonl","stepIdx":5,"toolCall":{"name":"run_command","args":{"CommandLine":"gh pr create --fill"}}}` + ev, err := Normalize("agy", AntigravityPostToolUse, []byte(body), testNow, nil) + require.NoError(t, err) + assert.Empty(t, ev.PullRequestURLs) + }) +} diff --git a/daemon/agent_hooks.go b/daemon/agent_hooks.go index 7e44a1b..b662e53 100644 --- a/daemon/agent_hooks.go +++ b/daemon/agent_hooks.go @@ -41,15 +41,17 @@ type AgentHookBatcher struct { repos *model.GitRepositoryResolver // Replaced in tests - send func(ctx context.Context, cfg model.ShellTimeConfig, events []agenthook.Event) error - now func() time.Time - flushInterval time.Duration - maxBatch int + send func(ctx context.Context, cfg model.ShellTimeConfig, events []agenthook.Event) error + sendPullRequests func(ctx context.Context, cfg model.ShellTimeConfig, sessionID string, urls []string) error + now func() time.Time + flushInterval time.Duration + maxBatch int mu sync.Mutex pending []agenthook.Event sessions map[agentHookSessionKey]agentHookSession clouds map[agentHookCloudKey]agentHookCloud + sentPRs map[agentHookPRKey]time.Time started bool closed bool @@ -74,6 +76,10 @@ type agentHookCloudKey struct { agent, sessionID string } +type agentHookPRKey struct { + sessionID, url string +} + // agentHookCloud is a session an event showed was a cloud run, with that event's signal. type agentHookCloud struct { signal string @@ -85,18 +91,20 @@ type agentHookCloud struct { func NewAgentHookBatcher(cfg model.ShellTimeConfig, repos *model.GitRepositoryResolver) *AgentHookBatcher { ctx, cancel := context.WithCancel(context.Background()) return &AgentHookBatcher{ - config: cfg, - repos: repos, - send: model.SendAgentHookEvents, - now: time.Now, - flushInterval: agentHookFlushInterval, - maxBatch: agentHookMaxBatch, - sessions: make(map[agentHookSessionKey]agentHookSession), - clouds: make(map[agentHookCloudKey]agentHookCloud), - flushCh: make(chan struct{}, 1), - ctx: ctx, - cancel: cancel, - done: make(chan struct{}), + config: cfg, + repos: repos, + send: model.SendAgentHookEvents, + sendPullRequests: model.SendSessionPullRequests, + now: time.Now, + flushInterval: agentHookFlushInterval, + maxBatch: agentHookMaxBatch, + sessions: make(map[agentHookSessionKey]agentHookSession), + clouds: make(map[agentHookCloudKey]agentHookCloud), + sentPRs: make(map[agentHookPRKey]time.Time), + flushCh: make(chan struct{}, 1), + ctx: ctx, + cancel: cancel, + done: make(chan struct{}), } } @@ -232,6 +240,11 @@ func (b *AgentHookBatcher) pruneSessionsLocked() { delete(b.clouds, key) } } + for key, seen := range b.sentPRs { + if now.Sub(seen) >= agentHookSessionTTL { + delete(b.sentPRs, key) + } + } } // flush sends the queued events, chunk by chunk. After a chunk fails in a way that can work @@ -261,9 +274,14 @@ func (b *AgentHookBatcher) flush(ctx context.Context) { sent, dropped := 0, 0 chunks := model.SplitAgentHookEvents(events, model.AgentHookMaxEventsPerRequest, model.AgentHookMaxRequestBytes) for i, chunk := range chunks { - err := b.send(ctx, cfg, chunk) + err := b.send(ctx, cfg, stripDaemonOnlyHookEvents(chunk)) if err == nil { sent += len(chunk) + if failedPRs := b.dispatchPullRequests(ctx, cfg, collectSessionPullRequests(chunk)); len(failedPRs) > 0 { + if retryEvents := eventsWithFailedPullRequests(chunk, failedPRs); len(retryEvents) > 0 { + b.save(retryEvents, "pull request link failed") + } + } continue } if ctx.Err() != nil || agentHookSendCanWait(err) { @@ -283,10 +301,183 @@ func (b *AgentHookBatcher) flush(ctx context.Context) { slog.Debug("Agent hook events sent", slog.Int("sent", sent), slog.Int("dropped", dropped)) } +const maxSessionPullRequestsPerRequest = 20 + +type sessionPullRequestBatch struct { + sessionID string + urls []string +} + +// collectSessionPullRequests groups unique pull request URLs carried by events by session id, +// preserving order. Events without a session id or without PR URLs are skipped. +func collectSessionPullRequests(events []agenthook.Event) []sessionPullRequestBatch { + var batches []sessionPullRequestBatch + bySession := map[string]int{} + seen := map[agentHookPRKey]bool{} + for _, ev := range events { + if ev.SessionID == "" || len(ev.PullRequestURLs) == 0 { + continue + } + for _, u := range ev.PullRequestURLs { + if u == "" { + continue + } + key := agentHookPRKey{sessionID: ev.SessionID, url: u} + if seen[key] { + continue + } + seen[key] = true + idx, ok := bySession[ev.SessionID] + if !ok { + idx = len(batches) + bySession[ev.SessionID] = idx + batches = append(batches, sessionPullRequestBatch{sessionID: ev.SessionID}) + } + batches[idx].urls = append(batches[idx].urls, u) + } + } + return batches +} + +// stripDaemonOnlyHookEvents returns events without daemon-only fields so POST /api/v1/agent-hooks +// never sees them, while leaving the original slice intact in case it must be saved to pending. +func stripDaemonOnlyHookEvents(events []agenthook.Event) []agenthook.Event { + dirty := false + for i := range events { + if events[i].YieldToUserHooks || len(events[i].PullRequestURLs) > 0 { + dirty = true + break + } + } + if !dirty { + return events + } + out := make([]agenthook.Event, len(events)) + copy(out, events) + for i := range out { + out[i].YieldToUserHooks = false + out[i].PullRequestURLs = nil + } + return out +} + +// eventsWithFailedPullRequests returns copies of events in chunk that carry retryable failed +// PR links, narrowed to only the URLs that still need linking (each (session, url) kept once). +// Re-sending the event through AgentHookResyncService is safe because POST /api/v1/agent-hooks +// deduplicates by event id. +func eventsWithFailedPullRequests(chunk []agenthook.Event, failed map[agentHookPRKey]bool) []agenthook.Event { + var retry []agenthook.Event + kept := map[agentHookPRKey]bool{} + for _, ev := range chunk { + if ev.SessionID == "" || len(ev.PullRequestURLs) == 0 { + continue + } + var urls []string + for _, u := range ev.PullRequestURLs { + key := agentHookPRKey{sessionID: ev.SessionID, url: u} + if failed[key] && !kept[key] { + kept[key] = true + urls = append(urls, u) + } + } + if len(urls) > 0 { + ev.PullRequestURLs = urls + retry = append(retry, ev) + } + } + return retry +} + +func (b *AgentHookBatcher) dispatchPullRequests(ctx context.Context, cfg model.ShellTimeConfig, batches []sessionPullRequestBatch) map[agentHookPRKey]bool { + if b.sendPullRequests == nil || len(batches) == 0 { + return nil + } + now := b.now() + var retryable map[agentHookPRKey]bool + for _, batch := range batches { + var fresh []string + b.mu.Lock() + for _, u := range batch.urls { + key := agentHookPRKey{sessionID: batch.sessionID, url: u} + if seen, ok := b.sentPRs[key]; ok && now.Sub(seen) < agentHookSessionTTL { + continue + } + fresh = append(fresh, u) + } + b.mu.Unlock() + if len(fresh) == 0 { + continue + } + for start := 0; start < len(fresh); start += maxSessionPullRequestsPerRequest { + end := min(start+maxSessionPullRequestsPerRequest, len(fresh)) + part := fresh[start:end] + if err := b.sendPullRequests(ctx, cfg, batch.sessionID, part); err != nil { + slog.Warn("Failed to send agent hook session pull requests", + slog.String("sessionId", batch.sessionID), slog.Int("count", len(part)), slog.Any("err", err)) + if ctx.Err() != nil || agentHookSendCanWait(err) { + if retryable == nil { + retryable = make(map[agentHookPRKey]bool) + } + for _, u := range part { + retryable[agentHookPRKey{sessionID: batch.sessionID, url: u}] = true + } + } + continue + } + b.mu.Lock() + if b.sentPRs == nil { + b.sentPRs = make(map[agentHookPRKey]time.Time) + } + for _, u := range part { + b.sentPRs[agentHookPRKey{sessionID: batch.sessionID, url: u}] = b.now() + } + b.mu.Unlock() + slog.Debug("agent hook session_pull_requests sent", + slog.String("sessionId", batch.sessionID), slog.Int("count", len(part))) + } + } + return retryable +} + +func dispatchSessionPullRequests( + ctx context.Context, + cfg model.ShellTimeConfig, + send func(ctx context.Context, cfg model.ShellTimeConfig, sessionID string, urls []string) error, + batches []sessionPullRequestBatch, +) map[agentHookPRKey]bool { + if send == nil || len(batches) == 0 { + return nil + } + var retryable map[agentHookPRKey]bool + for _, batch := range batches { + for start := 0; start < len(batch.urls); start += maxSessionPullRequestsPerRequest { + end := min(start+maxSessionPullRequestsPerRequest, len(batch.urls)) + part := batch.urls[start:end] + if err := send(ctx, cfg, batch.sessionID, part); err != nil { + slog.Warn("Failed to send resynced agent hook session pull requests", + slog.String("sessionId", batch.sessionID), slog.Int("count", len(part)), slog.Any("err", err)) + if ctx.Err() != nil || agentHookSendCanWait(err) { + if retryable == nil { + retryable = make(map[agentHookPRKey]bool) + } + for _, u := range part { + retryable[agentHookPRKey{sessionID: batch.sessionID, url: u}] = true + } + } + continue + } + slog.Debug("resynced agent hook session_pull_requests sent", + slog.String("sessionId", batch.sessionID), slog.Int("count", len(part))) + } + } + return retryable +} + // prepareAgentHookEvents readies events to leave the machine under cfg, for the batcher and // the resync service alike: with aiCodeOtel.sendRepository on, an event with a workspace and -// no repository gets the workspace's (repos nil adds none); off, every repository is removed. -// Then the privacy settings apply. It can run more than once on the same events. +// no repository gets the workspace's (repos nil adds none); off, every repository (and any +// pull request URLs, which name owner/repo) is removed. Then the privacy settings apply. It +// can run more than once on the same events. func prepareAgentHookEvents(ctx context.Context, cfg model.ShellTimeConfig, repos *model.GitRepositoryResolver, events []agenthook.Event) { sendsRepository := cfg.SendsRepository() repositories := map[string]string{} @@ -297,6 +488,7 @@ func prepareAgentHookEvents(ctx context.Context, cfg model.ShellTimeConfig, repo switch { case !sendsRepository: ev.Repository = "" + ev.PullRequestURLs = nil case repos != nil && ev.Repository == "" && ev.Workspace != "": url, ok := repositories[ev.Workspace] if !ok { diff --git a/daemon/agent_hooks_resync.go b/daemon/agent_hooks_resync.go index 8f8c21b..69412df 100644 --- a/daemon/agent_hooks_resync.go +++ b/daemon/agent_hooks_resync.go @@ -33,20 +33,22 @@ type AgentHookResyncService struct { // repos resolves the repository of events saved without one (hook-ingest has no git // lookup); nil adds none, like the batcher's when aiCodeOtel.sendRepository is off. repos *model.GitRepositoryResolver - // send is replaced in tests - send func(ctx context.Context, cfg model.ShellTimeConfig, events []agenthook.Event) error - ticker *time.Ticker - stopChan chan struct{} - stopOnce sync.Once - wg sync.WaitGroup + // send and sendPullRequests are replaced in tests + send func(ctx context.Context, cfg model.ShellTimeConfig, events []agenthook.Event) error + sendPullRequests func(ctx context.Context, cfg model.ShellTimeConfig, sessionID string, urls []string) error + ticker *time.Ticker + stopChan chan struct{} + stopOnce sync.Once + wg sync.WaitGroup } func NewAgentHookResyncService(config model.ShellTimeConfig) *AgentHookResyncService { return &AgentHookResyncService{ - config: config, - repos: socketRepositoryResolver(config), - send: model.SendAgentHookEvents, - stopChan: make(chan struct{}), + config: config, + repos: socketRepositoryResolver(config), + send: model.SendAgentHookEvents, + sendPullRequests: model.SendSessionPullRequests, + stopChan: make(chan struct{}), } } @@ -135,9 +137,20 @@ func (s *AgentHookResyncService) resync(ctx context.Context) { sent, dropped := 0, 0 for start := 0; start < len(events); start += agentHookResyncChunkSize { end := min(start+agentHookResyncChunkSize, len(events)) - err := s.send(ctx, cfg, events[start:end]) + chunk := events[start:end] + err := s.send(ctx, cfg, stripDaemonOnlyHookEvents(chunk)) if err == nil { sent += end - start + if failedPRs := dispatchSessionPullRequests(ctx, cfg, s.sendPullRequests, collectSessionPullRequests(chunk)); len(failedPRs) > 0 { + for j, ev := range chunk { + for _, u := range ev.PullRequestURLs { + if failedPRs[agentHookPRKey{sessionID: ev.SessionID, url: u}] { + kept = append(kept, eventLines[start+j]) + break + } + } + } + } continue } if ctx.Err() != nil || agentHookSendCanWait(err) { diff --git a/daemon/agent_hooks_test.go b/daemon/agent_hooks_test.go index e7c8e2b..df66677 100644 --- a/daemon/agent_hooks_test.go +++ b/daemon/agent_hooks_test.go @@ -693,3 +693,235 @@ func TestAgentHookResync_StartStop(t *testing.T) { s.Stop() s.Stop() } + +func TestAgentHookBatcher_LinksPullRequestsAndStripsFromHookPayload(t *testing.T) { + isolateAgentHookHome(t) + + var ( + mu sync.Mutex + hookReqs []model.AgentHookRequest + prCalls []struct { + SessionID string + URLs []string + } + ) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + switch r.URL.Path { + case "/api/v1/agent-hooks": + var req model.AgentHookRequest + require.NoError(t, json.NewDecoder(r.Body).Decode(&req)) + hookReqs = append(hookReqs, req) + _ = json.NewEncoder(w).Encode(model.AgentHookResponse{Success: true, EventsProcessed: len(req.Events)}) + case "/api/v1/cc/session-pull-requests": + var req struct { + SessionID string `json:"sessionId"` + URLs []string `json:"urls"` + } + require.NoError(t, json.NewDecoder(r.Body).Decode(&req)) + prCalls = append(prCalls, struct { + SessionID string + URLs []string + }{req.SessionID, req.URLs}) + w.WriteHeader(http.StatusNoContent) + default: + t.Errorf("unexpected path %s", r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + + b := NewAgentHookBatcher(model.ShellTimeConfig{ + APIEndpoint: srv.URL, + Token: "tok", + // PR linking still works when prompt/response content is disabled + AgentHooks: &model.AgentHooksConfig{SendContent: new(false)}, + }, nil) + b.flushInterval = time.Hour + + // Seed session for workspace, then send a Cursor postToolUse with empty conversation_id. + b.Add(hookEvent("s0", "cursor-sess-1", "/repo")) + prEv := agenthook.Event{ + ID: "t1", + Agent: agenthook.AgentCursor, + EventType: agenthook.EventToolUse, + Workspace: "/repo", + ToolName: "Shell", + Command: "gh pr create --fill", + PullRequestURLs: []string{"https://github.com/acme/web/pull/12"}, + } + b.Add(prEv) + b.flush(context.Background()) + + // Sending the same (session, url) again within TTL is deduplicated. + prEv.ID = "t2" + b.Add(prEv) + b.flush(context.Background()) + + mu.Lock() + defer mu.Unlock() + require.Len(t, hookReqs, 2) + for _, req := range hookReqs { + for _, ev := range req.Events { + assert.Empty(t, ev.PullRequestURLs, "pull_request_urls must never be sent to /api/v1/agent-hooks") + } + } + require.Len(t, prCalls, 1) + assert.Equal(t, "cursor-sess-1", prCalls[0].SessionID, "lent session id is used for PR linking") + assert.Equal(t, []string{"https://github.com/acme/web/pull/12"}, prCalls[0].URLs) +} + +func TestAgentHookBatcher_ExcludedCommandDoesNotLinkPullRequest(t *testing.T) { + isolateAgentHookHome(t) + srv := newAgentHookServer(t, http.StatusOK) + + var linked int + b := NewAgentHookBatcher(model.ShellTimeConfig{ + APIEndpoint: srv.URL, + Token: "tok", + Exclude: []string{"gh pr create"}, + }, nil) + b.flushInterval = time.Hour + b.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, _ string, _ []string) error { + linked++ + return nil + } + + b.Add(agenthook.Event{ + ID: "t1", + Agent: agenthook.AgentAntigravity, + SessionID: "agy-sess-1", + EventType: agenthook.EventToolUse, + Workspace: "/repo", + ToolName: "run_command", + Command: "gh pr create --fill", + PullRequestURLs: []string{"https://github.com/acme/web/pull/12"}, + }) + b.flush(context.Background()) + + assert.Equal(t, 1, srv.requestCount()) + assert.Zero(t, linked, "excluded command must not link its PR") +} + +func TestAgentHookResync_DispatchesSavedPullRequests(t *testing.T) { + isolateAgentHookHome(t) + + // First fail during batcher flush so the event is persisted with its PullRequestURLs. + failing := newAgentHookServer(t, http.StatusServiceUnavailable) + b := NewAgentHookBatcher(model.ShellTimeConfig{APIEndpoint: failing.URL, Token: "tok"}, nil) + b.flushInterval = time.Hour + b.Add(agenthook.Event{ + ID: "t1", + Agent: agenthook.AgentAntigravity, + SessionID: "agy-sess-2", + EventType: agenthook.EventToolUse, + Workspace: "/repo", + ToolName: "run_command", + Command: "gh pr create --fill", + PullRequestURLs: []string{"https://github.com/acme/cli/pull/99"}, + }) + b.flush(context.Background()) + + saved := savedAgentHookEvents(t) + require.Len(t, saved, 1) + assert.Equal(t, []string{"https://github.com/acme/cli/pull/99"}, saved[0].PullRequestURLs) + + // Now resync against a healthy server. + okSrv := newAgentHookServer(t, http.StatusOK) + var linkedSession string + var linkedURLs []string + s := NewAgentHookResyncService(model.ShellTimeConfig{APIEndpoint: okSrv.URL, Token: "tok"}) + s.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, sessionID string, urls []string) error { + linkedSession = sessionID + linkedURLs = append([]string(nil), urls...) + return nil + } + s.resync(context.Background()) + + req := waitAgentHookRequest(t, okSrv) + require.Len(t, req.Events, 1) + assert.Empty(t, req.Events[0].PullRequestURLs, "stripped before /api/v1/agent-hooks") + assert.Equal(t, "agy-sess-2", linkedSession) + assert.Equal(t, []string{"https://github.com/acme/cli/pull/99"}, linkedURLs) + assert.NoFileExists(t, model.GetAgentHooksPendingFilePath()) +} + +func TestAgentHookBatcher_SendRepositoryFalseSuppressesPullRequestLinking(t *testing.T) { + isolateAgentHookHome(t) + srv := newAgentHookServer(t, http.StatusOK) + + var linked int + b := NewAgentHookBatcher(model.ShellTimeConfig{ + APIEndpoint: srv.URL, + Token: "tok", + AICodeOtel: &model.AICodeOtel{SendRepository: new(false)}, + }, nil) + b.flushInterval = time.Hour + b.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, _ string, _ []string) error { + linked++ + return nil + } + + b.Add(agenthook.Event{ + ID: "t1", + Agent: agenthook.AgentCursor, + SessionID: "cursor-sess-norepo", + EventType: agenthook.EventToolUse, + Workspace: "/repo", + ToolName: "Shell", + Command: "gh pr create --fill", + PullRequestURLs: []string{"https://github.com/acme/web/pull/12"}, + }) + b.flush(context.Background()) + + assert.Equal(t, 1, srv.requestCount()) + assert.Zero(t, linked, "aiCodeOtel.sendRepository: false must suppress PR links too") +} + +func TestAgentHookBatcher_PreservesRetryablePullRequestFailuresForResync(t *testing.T) { + isolateAgentHookHome(t) + srv := newAgentHookServer(t, http.StatusOK) + + b := NewAgentHookBatcher(model.ShellTimeConfig{APIEndpoint: srv.URL, Token: "tok"}, nil) + b.flushInterval = time.Hour + b.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, _ string, _ []string) error { + return &model.HTTPStatusError{StatusCode: http.StatusServiceUnavailable} + } + + b.Add(agenthook.Event{ + ID: "t1", + Agent: agenthook.AgentCursor, + SessionID: "cursor-sess-retry", + EventType: agenthook.EventToolUse, + Workspace: "/repo", + ToolName: "Shell", + Command: "gh pr create --fill", + PullRequestURLs: []string{"https://github.com/acme/web/pull/77"}, + }) + b.flush(context.Background()) + + assert.Equal(t, 1, srv.requestCount()) + saved := savedAgentHookEvents(t) + require.Len(t, saved, 1, "retryable PR-link failure must be saved for resync") + assert.Equal(t, []string{"https://github.com/acme/web/pull/77"}, saved[0].PullRequestURLs) + + // Resync also keeps the pending line if PR linking still fails with a retryable error. + s := NewAgentHookResyncService(model.ShellTimeConfig{APIEndpoint: srv.URL, Token: "tok"}) + s.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, _ string, _ []string) error { + return &model.HTTPStatusError{StatusCode: http.StatusBadGateway} + } + s.resync(context.Background()) + require.Len(t, savedAgentHookEvents(t), 1, "still kept when resync PR-link fails retryably") + + // Next resync succeeds and clears the pending file. + var linkedURLs []string + s.sendPullRequests = func(_ context.Context, _ model.ShellTimeConfig, sessionID string, urls []string) error { + assert.Equal(t, "cursor-sess-retry", sessionID) + linkedURLs = append([]string(nil), urls...) + return nil + } + s.resync(context.Background()) + assert.Equal(t, []string{"https://github.com/acme/web/pull/77"}, linkedURLs) + assert.NoFileExists(t, model.GetAgentHooksPendingFilePath()) +} diff --git a/model/agent_hook_privacy.go b/model/agent_hook_privacy.go index 36156bc..96c175a 100644 --- a/model/agent_hook_privacy.go +++ b/model/agent_hook_privacy.go @@ -23,6 +23,7 @@ func ApplyAgentHookPrivacy(ev *agenthook.Event, cfg ShellTimeConfig) { ev.ToolInput = "" ev.Response = "" ev.Error = "" + ev.PullRequestURLs = nil ev.SetMetadata("excluded", true) } if cfg.DataMasking == nil || *cfg.DataMasking { diff --git a/model/agent_hooks_test.go b/model/agent_hooks_test.go index eda6c27..cba400e 100644 --- a/model/agent_hooks_test.go +++ b/model/agent_hooks_test.go @@ -57,6 +57,7 @@ func TestApplyAgentHookPrivacy_MaskingOff(t *testing.T) { func TestApplyAgentHookPrivacy_Exclude(t *testing.T) { ev := privacyTestEvent() + ev.PullRequestURLs = []string{"https://github.com/acme/web/pull/1"} ApplyAgentHookPrivacy(&ev, ShellTimeConfig{Exclude: []string{`^curl `}}) assert.Empty(t, ev.Command) @@ -64,6 +65,7 @@ func TestApplyAgentHookPrivacy_Exclude(t *testing.T) { assert.Empty(t, ev.Response) assert.Empty(t, ev.Error, "an error may repeat the command") assert.Empty(t, ev.Prompt, "so may the prompt") + assert.Empty(t, ev.PullRequestURLs, "excluded command drops PR links") assert.Equal(t, true, ev.Metadata["excluded"]) assert.Equal(t, "/repo/main.go", ev.FilePath) @@ -76,6 +78,7 @@ func TestApplyAgentHookPrivacy_Exclude(t *testing.T) { func TestApplyAgentHookPrivacy_NoContent(t *testing.T) { ev := privacyTestEvent() + ev.PullRequestURLs = []string{"https://github.com/acme/web/pull/2"} ev.SetMetadata("attachments", []string{"/repo/secret-plan.md"}) ev.SetMetadata("loop_count", 2) ApplyAgentHookPrivacy(&ev, ShellTimeConfig{AgentHooks: &AgentHooksConfig{SendContent: new(false)}}) @@ -84,6 +87,7 @@ func TestApplyAgentHookPrivacy_NoContent(t *testing.T) { assert.Empty(t, ev.Response) assert.Empty(t, ev.ToolInput) assert.Empty(t, ev.Error) + assert.Equal(t, []string{"https://github.com/acme/web/pull/2"}, ev.PullRequestURLs, "PR links stay when sendContent is off") assert.NotContains(t, ev.Metadata, "attachments") assert.Equal(t, 2, ev.Metadata["loop_count"], "other metadata stays") assert.NotEmpty(t, ev.Command, "activity is still sent") @@ -453,12 +457,17 @@ func TestSendAgentHookEvents(t *testing.T) { for i := range events { events[i] = agenthook.Event{ID: "id", Agent: agenthook.AgentCursor, EventType: agenthook.EventStop} } + events[0].PullRequestURLs = []string{"https://github.com/acme/web/pull/1"} + events[0].YieldToUserHooks = true cfg := ShellTimeConfig{APIEndpoint: srv.URL, Token: "tok"} require.NoError(t, SendAgentHookEvents(context.Background(), cfg, events)) require.Len(t, requests, 2) assert.Len(t, requests[0].Events, AgentHookMaxEventsPerRequest) assert.Len(t, requests[1].Events, 2) + assert.Empty(t, requests[0].Events[0].PullRequestURLs, "stripped on wire") + assert.False(t, requests[0].Events[0].YieldToUserHooks, "stripped on wire") + assert.Equal(t, []string{"https://github.com/acme/web/pull/1"}, events[0].PullRequestURLs, "caller slice is untouched") assert.NotEmpty(t, requests[0].Host) assert.Equal(t, "CLI tok", auth[0]) } diff --git a/model/api_agent_hooks.go b/model/api_agent_hooks.go index 60567cf..f2f9f19 100644 --- a/model/api_agent_hooks.go +++ b/model/api_agent_hooks.go @@ -43,7 +43,7 @@ func SendAgentHookEvents(ctx context.Context, cfg ShellTimeConfig, events []agen host = events[0].Hostname } endpoint := Endpoint{APIEndpoint: cfg.APIEndpoint, Token: cfg.Token} - for _, chunk := range SplitAgentHookEvents(events, AgentHookMaxEventsPerRequest, AgentHookMaxRequestBytes) { + for _, chunk := range SplitAgentHookEvents(stripDaemonOnlyAgentHookEvents(events), AgentHookMaxEventsPerRequest, AgentHookMaxRequestBytes) { var resp AgentHookResponse err := SendHTTPRequestJSON(HTTPRequestOptions[AgentHookRequest, AgentHookResponse]{ Context: ctx, @@ -61,6 +61,28 @@ func SendAgentHookEvents(ctx context.Context, cfg ShellTimeConfig, events []agen return nil } +// stripDaemonOnlyAgentHookEvents returns events without daemon-only fields so they never +// leave the machine in POST /api/v1/agent-hooks. +func stripDaemonOnlyAgentHookEvents(events []agenthook.Event) []agenthook.Event { + dirty := false + for i := range events { + if events[i].YieldToUserHooks || len(events[i].PullRequestURLs) > 0 { + dirty = true + break + } + } + if !dirty { + return events + } + out := make([]agenthook.Event, len(events)) + copy(out, events) + for i := range out { + out[i].YieldToUserHooks = false + out[i].PullRequestURLs = nil + } + return out +} + // SplitAgentHookEvents splits events, in order, into chunks of at most maxEvents events whose // encoded size stays within maxBytes. An event larger than maxBytes goes alone in its chunk // (its text fields are capped, so it stays far below the server's limit).