Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

Link git commits to the agent sessions that wrote them

Claudefdbd51c478a4
diff --git a/CLAUDE.md b/CLAUDE.md
index 5f5b2ade..1ae501b2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -66,6 +66,7 @@ Supported runtime surfaces today:
- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs.
- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.
- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.
+- Commit-to-session links via `beacon git link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes. Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim.
- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.
Current non-goals unless explicitly requested:
diff --git a/cli/beacon/cmd/git.go b/cli/beacon/cmd/git.go
new file mode 100644
index 00000000..7af8d877
--- /dev/null
+++ b/cli/beacon/cmd/git.go
@@ -0,0 +1,208 @@
+package cmd
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "strings"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+)
+
+type gitOptions struct {
+ dir string
+ logPath string
+ jsonOutput bool
+ dryRun bool
+ minLookback time.Duration
+ maxLookback time.Duration
+ limit int
+}
+
+var gitOpts gitOptions
+
+var gitCmd = &cobra.Command{
+ Use: "git",
+ Short: "Link git commits to the agent sessions that wrote them",
+ Long: `Link git commits to the agent sessions that wrote them.
+
+A link is a line in a git note under ` + gitlink.NotesRef + ` naming the session's harness and id.
+Which sessions to link is inferred from the local runtime log: a session is linked to a commit when
+it wrote, shortly before the commit, a file the commit changes. The note carries identifiers only;
+the session itself stays in the runtime log, and ` + "`beacon handoff export <session>`" + ` reads it back.`,
+}
+
+var gitLinkCmd = &cobra.Command{
+ Use: "link [<commit>]",
+ Short: "Link a commit (default HEAD) to the sessions that wrote its files",
+ Long: `Link a commit (default HEAD) to the sessions that wrote its files.
+
+The runtime log is read from the later of the parent commit and --max-lookback before the commit,
+but never less than --min-lookback before it, up to the commit itself. Every session that wrote a
+file the commit changes in that span is linked, most files first. Links already on the commit are
+kept, and running link again adds only what is new.`,
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: runGitLink,
+}
+
+var gitNotesCmd = &cobra.Command{
+ Use: "notes [<revision>]",
+ Short: "List recent commits linked to agent sessions",
+ Args: cobra.MaximumNArgs(1),
+ SilenceUsage: true,
+ RunE: runGitNotes,
+}
+
+func gitRepo(ctx context.Context) (gitlink.Repo, error) {
+ return gitlink.OpenRepo(ctx, gitlink.Git{Dir: gitOpts.dir})
+}
+
+func gitRuntimeLogPath() string {
+ return lifecycle.ResolveRuntimeLog(true, gitOpts.logPath).EffectiveLogPath
+}
+
+func runGitLink(cmd *cobra.Command, args []string) error {
+ ctx := cmd.Context()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return err
+ }
+ rev := ""
+ if len(args) == 1 {
+ rev = args[0]
+ }
+ result, err := gitlink.Attribute(ctx, repo, gitlink.Options{
+ Rev: rev,
+ LogPath: gitRuntimeLogPath(),
+ MinLookback: gitOpts.minLookback,
+ MaxLookback: gitOpts.maxLookback,
+ DryRun: gitOpts.dryRun,
+ })
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if gitOpts.jsonOutput {
+ return writeIndentedJSON(out, result)
+ }
+ printGitLinkResult(out, result)
+ return nil
+}
+
+func printGitLinkResult(out io.Writer, result gitlink.Result) {
+ fmt.Fprintf(out, "commit %s %s\n", shortSHA(result.Commit.SHA), result.Commit.Subject)
+ fmt.Fprintf(out, "window %s .. %s\n", result.Since.Local().Format(time.DateTime), result.Until.Local().Format(time.DateTime))
+ if result.ChangedFiles == 0 {
+ fmt.Fprintln(out, "The commit changes no files; nothing to link.")
+ return
+ }
+ if len(result.Candidates) == 0 {
+ fmt.Fprintf(out, "No session in the runtime log wrote any of the %d file(s) this commit changes.\n", result.ChangedFiles)
+ return
+ }
+ for _, c := range result.Candidates {
+ state := "linked"
+ switch {
+ case c.AlreadyLinked:
+ state = "already linked"
+ case !containsLink(result.Added, c.Link):
+ state = "skipped (limit)"
+ case result.DryRun:
+ state = "would link"
+ }
+ fmt.Fprintf(out, " %-15s %s/%s %d of %d file(s): %s\n", state, c.Harness, c.SessionID,
+ len(c.Files), result.ChangedFiles, summarizeFiles(c.Files, 3))
+ }
+ switch {
+ case result.DryRun:
+ fmt.Fprintln(out, "Dry run: the note was not written.")
+ case result.NoteUpdated:
+ fmt.Fprintf(out, "Wrote %d link(s) to %s.\n", len(result.Added), gitlink.NotesRef)
+ default:
+ fmt.Fprintln(out, "The note already had every link.")
+ }
+}
+
+func runGitNotes(cmd *cobra.Command, args []string) error {
+ ctx := cmd.Context()
+ repo, err := gitRepo(ctx)
+ if err != nil {
+ return err
+ }
+ rev := ""
+ if len(args) == 1 {
+ rev = args[0]
+ }
+ commits, err := gitlink.ListLinked(ctx, repo.Git, rev, gitOpts.limit)
+ if err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+ if gitOpts.jsonOutput {
+ if commits == nil {
+ commits = []gitlink.LinkedCommit{}
+ }
+ return writeIndentedJSON(out, commits)
+ }
+ if len(commits) == 0 {
+ fmt.Fprintf(out, "No linked commits in the last %d commit(s). `beacon git link` links one.\n", gitOpts.limit)
+ return nil
+ }
+ for _, c := range commits {
+ fmt.Fprintf(out, "%s %s %s\n", shortSHA(c.SHA), c.CommitTime.Local().Format(time.DateTime), c.Subject)
+ for _, link := range c.Links {
+ fmt.Fprintf(out, " %s/%s\n", link.Harness, link.SessionID)
+ }
+ }
+ return nil
+}
+
+func writeIndentedJSON(out io.Writer, value interface{}) error {
+ enc := json.NewEncoder(out)
+ enc.SetIndent("", " ")
+ return enc.Encode(value)
+}
+
+func shortSHA(sha string) string {
+ if len(sha) > 12 {
+ return sha[:12]
+ }
+ return sha
+}
+
+func containsLink(links []gitlink.Link, link gitlink.Link) bool {
+ for _, l := range links {
+ if l == link {
+ return true
+ }
+ }
+ return false
+}
+
+func summarizeFiles(files []string, max int) string {
+ if len(files) <= max {
+ return strings.Join(files, ", ")
+ }
+ return fmt.Sprintf("%s, +%d more", strings.Join(files[:max], ", "), len(files)-max)
+}
+
+func init() {
+ rootCmd.AddCommand(gitCmd)
+ gitCmd.AddCommand(gitLinkCmd, gitNotesCmd)
+ for _, c := range []*cobra.Command{gitLinkCmd, gitNotesCmd} {
+ c.Flags().StringVarP(&gitOpts.dir, "cwd", "C", "", "Repository to operate on (default the current directory)")
+ c.Flags().BoolVar(&gitOpts.jsonOutput, "json", false, "Print the result as JSON")
+ }
+ lf := gitLinkCmd.Flags()
+ lf.StringVar(&gitOpts.logPath, "log-path", "", "Runtime JSONL log to read sessions from (default the local runtime log)")
+ lf.BoolVar(&gitOpts.dryRun, "dry-run", false, "Show the links without writing the note")
+ lf.DurationVar(&gitOpts.minLookback, "min-lookback", gitlink.DefaultMinLookback, "Always read at least this far before the commit")
+ lf.DurationVar(&gitOpts.maxLookback, "max-lookback", gitlink.DefaultMaxLookback, "Never read further than this before the commit")
+ gitNotesCmd.Flags().IntVar(&gitOpts.limit, "limit", 20, "Number of commits to walk")
+}
diff --git a/cli/beacon/cmd/git_test.go b/cli/beacon/cmd/git_test.go
new file mode 100644
index 00000000..577ccd6a
--- /dev/null
+++ b/cli/beacon/cmd/git_test.go
@@ -0,0 +1,180 @@
+package cmd
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/spf13/pflag"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+)
+
+// runGit executes `beacon git ...` through the root command with fresh flag values.
+func runGit(t *testing.T, args ...string) (string, error) {
+ t.Helper()
+ gitOpts = gitOptions{}
+ for _, c := range gitCmd.Commands() {
+ c.Flags().VisitAll(func(f *pflag.Flag) {
+ _ = f.Value.Set(f.DefValue)
+ f.Changed = false
+ })
+ }
+ var stdout, stderr bytes.Buffer
+ rootCmd.SetOut(&stdout)
+ rootCmd.SetErr(&stderr)
+ rootCmd.SetArgs(append([]string{"git"}, args...))
+ t.Cleanup(func() {
+ rootCmd.SetOut(nil)
+ rootCmd.SetErr(nil)
+ rootCmd.SetArgs(nil)
+ })
+ err := rootCmd.Execute()
+ return stdout.String(), err
+}
+
+// gitCommandRepo makes a repository the command can reach through the process environment,
+// which is how a real invocation finds git's configuration.
+func gitCommandRepo(t *testing.T) string {
+ t.Helper()
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skip("git not installed")
+ }
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ for _, kv := range gitlink.IsolatedEnv(home) {
+ key, value, _ := strings.Cut(kv, "=")
+ t.Setenv(key, value)
+ }
+ root := filepath.Join(t.TempDir(), "repo")
+ if err := os.MkdirAll(root, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ mustGit(t, root, "init", "-q", "-b", "main")
+ mustGit(t, root, "config", "commit.gpgsign", "false")
+ return root
+}
+
+func mustGit(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ out, err := exec.Command("git", append([]string{"-C", dir}, args...)...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v: %v\n%s", args, err, out)
+ }
+ return strings.TrimSpace(string(out))
+}
+
+func TestGitLinkAndNotesCommands(t *testing.T) {
+ root := gitCommandRepo(t)
+ if err := os.WriteFile(filepath.Join(root, "main.go"), []byte("package main\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ mustGit(t, root, "add", "-A")
+ mustGit(t, root, "commit", "-q", "-m", "Add main")
+ sha := mustGit(t, root, "rev-parse", "HEAD")
+ top := mustGit(t, root, "rev-parse", "--show-toplevel")
+
+ event := schema.NewEvent(schema.NewEventOptions{Action: "file.created", Harness: schema.HarnessInfo{Name: "claude_code"}})
+ event.Timestamp = schema.FormatTimestamp(time.Now().Add(-5 * time.Minute))
+ event.Session = &schema.SessionInfo{ID: "sess-1", WorkingDirectory: top}
+ event.File = &schema.FileInfo{Path: filepath.Join(top, "main.go"), Operation: "create"}
+ line, _ := json.Marshal(event)
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(logPath, append(line, '\n'), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ out, err := runGit(t, "link", "--cwd", root, "--log-path", logPath, "--dry-run")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(out, "would link") || !strings.Contains(out, "claude_code/sess-1") || !strings.Contains(out, "Dry run") {
+ t.Fatalf("dry run output:\n%s", out)
+ }
+ if note := mustGitAllowFail(root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "" {
+ t.Fatalf("dry run wrote %q", note)
+ }
+
+ out, err = runGit(t, "link", "--cwd", root, "--log-path", logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(out, "Wrote 1 link(s)") {
+ t.Fatalf("link output:\n%s", out)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "beacon:claude_code/sess-1" {
+ t.Fatalf("note %q", note)
+ }
+
+ out, err = runGit(t, "notes", "--cwd", root, "--json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var commits []gitlink.LinkedCommit
+ if err := json.Unmarshal([]byte(out), &commits); err != nil {
+ t.Fatalf("notes --json: %v\n%s", err, out)
+ }
+ if len(commits) != 1 || commits[0].SHA != sha || commits[0].Links[0] != (gitlink.Link{Harness: "claude_code", SessionID: "sess-1"}) {
+ t.Fatalf("notes: %+v", commits)
+ }
+ out, err = runGit(t, "notes", "--cwd", root)
+ if err != nil || !strings.Contains(out, "claude_code/sess-1") || !strings.Contains(out, "Add main") {
+ t.Fatalf("notes text: %v\n%s", err, out)
+ }
+}
+
+func TestGitNotesJSONIsAnArrayWhenEmpty(t *testing.T) {
+ root := gitCommandRepo(t)
+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "empty")
+ out, err := runGit(t, "notes", "--cwd", root, "--json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.TrimSpace(out) != "[]" {
+ t.Fatalf("got %q", out)
+ }
+}
+
+func TestGitLinkOutsideRepository(t *testing.T) {
+ gitCommandRepo(t)
+ dir := t.TempDir()
+ t.Setenv("GIT_CEILING_DIRECTORIES", filepath.Dir(dir))
+ if _, err := runGit(t, "link", "--cwd", dir); err == nil || !strings.Contains(err.Error(), "not a git repository") {
+ t.Fatalf("got %v", err)
+ }
+}
+
+func mustGitAllowFail(dir string, args ...string) string {
+ out, _ := exec.Command("git", append([]string{"-C", dir}, args...)...).Output()
+ return strings.TrimSpace(string(out))
+}
+
+func TestPrintGitLinkResultLabelsTheLimit(t *testing.T) {
+ var out bytes.Buffer
+ a := gitlink.Link{Harness: "codex_cli", SessionID: "a"}
+ b := gitlink.Link{Harness: "codex_cli", SessionID: "b"}
+ c := gitlink.Link{Harness: "codex_cli", SessionID: "c"}
+ printGitLinkResult(&out, gitlink.Result{
+ ChangedFiles: 1,
+ DryRun: true,
+ Candidates: []gitlink.Candidate{
+ {Link: a, Files: []string{"x"}, AlreadyLinked: true},
+ {Link: b, Files: []string{"x"}},
+ {Link: c, Files: []string{"x"}},
+ },
+ Added: []gitlink.Link{b},
+ })
+ text := out.String()
+ for _, want := range []string{"already linked codex_cli/a", "would link codex_cli/b", "skipped (limit) codex_cli/c"} {
+ if !strings.Contains(text, want) {
+ t.Errorf("missing %q in:\n%s", want, text)
+ }
+ }
+}
diff --git a/cli/beacon/internal/gitlink/commit.go b/cli/beacon/internal/gitlink/commit.go
new file mode 100644
index 00000000..14b44ed7
--- /dev/null
+++ b/cli/beacon/internal/gitlink/commit.go
@@ -0,0 +1,99 @@
+package gitlink
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Commit is the part of a commit attribution reads.
+type Commit struct {
+ SHA string `json:"sha"`
+ Parents []string `json:"parents,omitempty"`
+ CommitTime time.Time `json:"commit_time"`
+ Subject string `json:"subject"`
+ // ParentTime is the first parent's commit time; zero for a root commit.
+ ParentTime time.Time `json:"parent_time,omitempty"`
+}
+
+// ResolveCommit reads rev (HEAD when empty) as a commit.
+func ResolveCommit(ctx context.Context, g Git, rev string) (Commit, error) {
+ if rev == "" {
+ rev = "HEAD"
+ }
+ out, err := g.Run(ctx, nil, "show", "-s", "--no-notes", "--format=%H%x00%P%x00%ct%x00%s", rev+"^{commit}", "--")
+ if err != nil {
+ return Commit{}, fmt.Errorf("resolve commit %s: %w", rev, err)
+ }
+ fields := strings.SplitN(out, "\x00", 4)
+ if len(fields) != 4 {
+ return Commit{}, fmt.Errorf("resolve commit %s: unexpected output", rev)
+ }
+ seconds, err := strconv.ParseInt(strings.TrimSpace(fields[2]), 10, 64)
+ if err != nil {
+ return Commit{}, fmt.Errorf("resolve commit %s: commit time %q", rev, fields[2])
+ }
+ commit := Commit{
+ SHA: strings.TrimSpace(fields[0]),
+ Parents: strings.Fields(fields[1]),
+ CommitTime: time.Unix(seconds, 0).UTC(),
+ Subject: fields[3],
+ }
+ if len(commit.Parents) > 0 {
+ parent, err := g.Run(ctx, nil, "show", "-s", "--no-notes", "--format=%ct", commit.Parents[0], "--")
+ if err == nil {
+ if seconds, err := strconv.ParseInt(strings.TrimSpace(parent), 10, 64); err == nil {
+ commit.ParentTime = time.Unix(seconds, 0).UTC()
+ }
+ }
+ }
+ return commit, nil
+}
+
+// ChangedFiles returns the repository-relative paths commit changes, compared with its first
+// parent. A rename or copy contributes both its source and its destination: an agent that moved a
+// file edited the path it moved from as much as the one it moved to.
+func ChangedFiles(ctx context.Context, g Git, commit string) ([]string, error) {
+ out, err := g.RunRaw(ctx, "diff-tree", "--no-commit-id", "--name-status", "-r", "-z", "-M", "--root",
+ "--diff-merges=first-parent", commit, "--")
+ if err != nil {
+ return nil, fmt.Errorf("list files changed by %s: %w", commit, err)
+ }
+ return parseNameStatusZ(out), nil
+}
+
+// parseNameStatusZ reads `--name-status -z` output: a status field and then one path, or two for a
+// rename (R) or copy (C).
+func parseNameStatusZ(out []byte) []string {
+ fields := strings.Split(string(out), "\x00")
+ var paths []string
+ seen := map[string]bool{}
+ add := func(path string) {
+ if path != "" && !seen[path] {
+ seen[path] = true
+ paths = append(paths, path)
+ }
+ }
+ for i := 0; i < len(fields); {
+ status := fields[i]
+ if status == "" {
+ i++
+ continue
+ }
+ if strings.HasPrefix(status, "R") || strings.HasPrefix(status, "C") {
+ if i+2 < len(fields) {
+ add(fields[i+1])
+ add(fields[i+2])
+ }
+ i += 3
+ continue
+ }
+ if i+1 < len(fields) {
+ add(fields[i+1])
+ }
+ i += 2
+ }
+ return paths
+}
diff --git a/cli/beacon/internal/gitlink/evidence.go b/cli/beacon/internal/gitlink/evidence.go
new file mode 100644
index 00000000..116def5e
--- /dev/null
+++ b/cli/beacon/internal/gitlink/evidence.go
@@ -0,0 +1,299 @@
+package gitlink
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// SessionEvidence is what the runtime log says one session did to the repository in the window.
+type SessionEvidence struct {
+ Link
+ WorkingDirectory string `json:"working_directory,omitempty"`
+ // Files maps each repository-relative path the session wrote to the time it last wrote it.
+ Files map[string]time.Time `json:"-"`
+}
+
+// writeOperations are the file.operation values that change a file. Reads and listings carry a
+// file path too, and a session that only read a file did not write the commit that changed it.
+var writeOperations = map[string]bool{
+ "create": true, "modify": true, "delete": true, "write": true, "edit": true, "rename": true, "move": true,
+}
+
+var writeActions = map[string]bool{
+ "file.created": true, "file.modified": true, "file.deleted": true, "file.edited": true,
+}
+
+// ReadEvidence scans the runtime log at logPath for sessions that wrote files inside repo between
+// since and until, both inclusive.
+//
+// The log rotates into numbered archives (runtime.jsonl.1 is the newest). They are read newest
+// first and the scan stops at the first file last modified before since: nothing in it or in any
+// older archive can fall inside the window. That keeps a hook's cost proportional to recent
+// activity rather than to how much history the endpoint keeps.
+func ReadEvidence(ctx context.Context, repo Repo, logPath string, since, until time.Time) (map[string]*SessionEvidence, error) {
+ sessions := map[string]*SessionEvidence{}
+ pending := map[string][]pendingPath{}
+ for _, path := range logFilesNewestFirst(logPath) {
+ info, err := os.Stat(path)
+ if err != nil {
+ continue
+ }
+ if info.ModTime().Before(since) {
+ break
+ }
+ if err := scanLogFile(ctx, path, repo, since, until, sessions, pending); err != nil {
+ return nil, err
+ }
+ }
+ // Relative paths wait for the session's working directory, which a later event may be the
+ // first to report.
+ for key, paths := range pending {
+ session := sessions[key]
+ if session == nil || session.WorkingDirectory == "" {
+ continue
+ }
+ for _, p := range paths {
+ if rel, ok := repo.RelPath(p.path, session.WorkingDirectory); ok {
+ session.recordFile(rel, p.at)
+ }
+ }
+ }
+ for key, session := range sessions {
+ if len(session.Files) == 0 {
+ delete(sessions, key)
+ }
+ }
+ return sessions, nil
+}
+
+type pendingPath struct {
+ path string
+ at time.Time
+}
+
+func (s *SessionEvidence) recordFile(rel string, at time.Time) {
+ if s.Files == nil {
+ s.Files = map[string]time.Time{}
+ }
+ if prev, ok := s.Files[rel]; !ok || at.After(prev) {
+ s.Files[rel] = at
+ }
+}
+
+// LastWrite is the latest time the session wrote any of paths, zero when it wrote none of them.
+func (s *SessionEvidence) LastWrite(paths []string) time.Time {
+ var last time.Time
+ for _, p := range paths {
+ if at, ok := s.Files[p]; ok && at.After(last) {
+ last = at
+ }
+ }
+ return last
+}
+
+func scanLogFile(ctx context.Context, path string, repo Repo, since, until time.Time,
+ sessions map[string]*SessionEvidence, pending map[string][]pendingPath) error {
+ file, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ defer file.Close()
+ reader := bufio.NewReaderSize(file, 64*1024)
+ sessionKey := []byte(`"session"`)
+ for n := 0; ; n++ {
+ if n%4096 == 0 && ctx.Err() != nil {
+ return ctx.Err()
+ }
+ line, err := readLine(reader, maxLineBytes)
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ // Most lines are not about a session at all (collector health, inventory, metrics). A
+ // substring check is far cheaper than decoding them to find that out.
+ if !bytes.Contains(line, sessionKey) {
+ continue
+ }
+ var event schema.Event
+ if err := json.Unmarshal(line, &event); err != nil {
+ continue
+ }
+ if event.Session == nil || strings.TrimSpace(event.Session.ID) == "" {
+ continue
+ }
+ at, err := schema.ParseTimestamp(event.Timestamp)
+ if err != nil || at.Before(since) || at.After(until) {
+ continue
+ }
+ link := Link{
+ Harness: asymptoteobserve.NormalizeHarnessName(event.Harness.Name),
+ SessionID: strings.TrimSpace(event.Session.ID),
+ }
+ if !link.Valid() {
+ continue
+ }
+ key := link.Key()
+ session := sessions[key]
+ if session == nil {
+ session = &SessionEvidence{Link: link}
+ sessions[key] = session
+ }
+ cwd := strings.TrimSpace(event.Session.WorkingDirectory)
+ if session.WorkingDirectory == "" && filepath.IsAbs(cwd) {
+ session.WorkingDirectory = filepath.Clean(cwd)
+ }
+ base := cwd
+ if base == "" {
+ base = session.WorkingDirectory
+ }
+ for _, written := range writtenPaths(event) {
+ if rel, ok := repo.RelPath(written, base); ok {
+ session.recordFile(rel, at)
+ } else if !filepath.IsAbs(written) && base == "" {
+ pending[key] = append(pending[key], pendingPath{path: written, at: at})
+ }
+ }
+ }
+}
+
+// maxLineBytes bounds one log line. Beacon's writers cap an event far below it; a longer line is
+// corrupt or foreign, and is skipped rather than allowed to end the scan.
+const maxLineBytes = 4 * 1024 * 1024
+
+// readLine returns the next line without its newline. A line longer than max is consumed and
+// returned empty, so the caller moves past it. io.EOF comes only once no bytes remain.
+func readLine(r *bufio.Reader, max int) ([]byte, error) {
+ var line []byte
+ tooLong := false
+ for {
+ chunk, err := r.ReadSlice('\n')
+ if !tooLong {
+ if len(line)+len(chunk) > max {
+ tooLong, line = true, nil
+ } else {
+ line = append(line, chunk...)
+ }
+ }
+ switch err {
+ case nil:
+ if tooLong {
+ return []byte{}, nil
+ }
+ return bytes.TrimRight(line, "\r\n"), nil
+ case bufio.ErrBufferFull:
+ continue
+ case io.EOF:
+ if len(line) == 0 && !tooLong {
+ return nil, io.EOF
+ }
+ if tooLong {
+ return []byte{}, nil
+ }
+ return line, nil
+ default:
+ return nil, err
+ }
+ }
+}
+
+// writtenPaths returns the paths an event says were written, as recorded (absolute, or relative
+// to the session's working directory).
+func writtenPaths(event schema.Event) []string {
+ var paths []string
+ if event.File != nil && event.File.Path != "" {
+ op := strings.ToLower(strings.TrimSpace(event.File.Operation))
+ if writeActions[event.Event.Action] || writeOperations[op] {
+ paths = append(paths, event.File.Path)
+ }
+ }
+ if event.Command != nil && event.Command.Command != "" {
+ paths = append(paths, ShellWrittenPaths(event.Command.Command)...)
+ } else if event.Tool != nil && event.Tool.Command != "" {
+ paths = append(paths, ShellWrittenPaths(event.Tool.Command)...)
+ }
+ if event.GenAI != nil && event.GenAI.Tool != nil && event.GenAI.Tool.Call != nil {
+ paths = append(paths, patchPathsIn(event.GenAI.Tool.Call.Arguments)...)
+ }
+ return paths
+}
+
+// patchPathsIn finds apply_patch envelopes anywhere in a tool call's arguments, which may arrive
+// as a decoded object or as the JSON text of one.
+func patchPathsIn(value interface{}) []string {
+ switch v := value.(type) {
+ case string:
+ if !strings.Contains(v, "*** Begin Patch") {
+ return nil
+ }
+ // JSON text of the arguments first: its patch is escaped, and read raw it is one line.
+ trimmed := strings.TrimSpace(v)
+ if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
+ var decoded interface{}
+ if json.Unmarshal([]byte(trimmed), &decoded) == nil {
+ return patchPathsIn(decoded)
+ }
+ }
+ return PatchPaths(v)
+ case map[string]interface{}:
+ var out []string
+ for _, item := range v {
+ out = append(out, patchPathsIn(item)...)
+ }
+ return out
+ case []interface{}:
+ var out []string
+ for _, item := range v {
+ out = append(out, patchPathsIn(item)...)
+ }
+ return out
+ }
+ return nil
+}
+
+// logFilesNewestFirst returns the active log followed by its numbered archives, newest first.
+func logFilesNewestFirst(logPath string) []string {
+ files := []string{logPath}
+ dir, base := filepath.Dir(logPath), filepath.Base(logPath)
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return files
+ }
+ type archive struct {
+ index int
+ path string
+ }
+ var archives []archive
+ for _, entry := range entries {
+ suffix, ok := strings.CutPrefix(entry.Name(), base+".")
+ if !ok {
+ continue
+ }
+ index, err := strconv.Atoi(suffix)
+ if err != nil || index <= 0 {
+ continue
+ }
+ archives = append(archives, archive{index: index, path: filepath.Join(dir, entry.Name())})
+ }
+ sort.Slice(archives, func(i, j int) bool { return archives[i].index < archives[j].index })
+ for _, a := range archives {
+ files = append(files, a.path)
+ }
+ return files
+}
diff --git a/cli/beacon/internal/gitlink/evidence_line_test.go b/cli/beacon/internal/gitlink/evidence_line_test.go
new file mode 100644
index 00000000..ba485c57
--- /dev/null
+++ b/cli/beacon/internal/gitlink/evidence_line_test.go
@@ -0,0 +1,54 @@
+package gitlink
+
+import (
+ "bufio"
+ "context"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestReadLineSkipsOversizedLines(t *testing.T) {
+ input := "short\n" + strings.Repeat("x", 300) + "\nafter\r\nlast-no-newline"
+ r := bufio.NewReaderSize(strings.NewReader(input), 16)
+ var got []string
+ for {
+ line, err := readLine(r, 100)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ got = append(got, string(line))
+ }
+ want := []string{"short", "", "after", "last-no-newline"}
+ if strings.Join(got, "|") != strings.Join(want, "|") {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestReadEvidenceSurvivesAnOversizedLine(t *testing.T) {
+ r := newTestRepo(t)
+ repo := r.open()
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ writeLog(t, logPath, logEvent{at: t0, harness: "codex", session: "s", cwd: repo.Root, action: "file.modified", filePath: filepath.Join(repo.Root, "x.go"), operation: "modify"})
+ f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A corrupt line longer than any event, then a valid one after it.
+ _, _ = f.WriteString(`{"session":"` + strings.Repeat("z", maxLineBytes+10) + "\n")
+ f.Close()
+ writeLogAppend(t, logPath, logEvent{at: t0, harness: "codex", session: "s2", cwd: repo.Root, action: "file.modified", filePath: filepath.Join(repo.Root, "y.go"), operation: "modify"})
+ got, err := ReadEvidence(context.Background(), repo, logPath, t0.Add(-time.Hour), t0.Add(time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got["codex_cli/s"] == nil || got["codex_cli/s2"] == nil {
+ t.Fatalf("sessions %v", got)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/git.go b/cli/beacon/internal/gitlink/git.go
new file mode 100644
index 00000000..63873c23
--- /dev/null
+++ b/cli/beacon/internal/gitlink/git.go
@@ -0,0 +1,224 @@
+// Package gitlink links git commits to the agent sessions that produced them.
+//
+// A link is a line in a git note on the commit, under NotesRef. The note names a session by its
+// harness and session id and carries nothing else: notes can travel to a shared remote, so the
+// commit says which session wrote it and the session's content stays in the local runtime log.
+//
+// Which sessions to link is an inference from the runtime log, never an observation. A session is
+// linked to a commit when it edited, within the lookback window, a file the commit changes. See
+// Attribute.
+package gitlink
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// Git runs git against one repository. Dir is any directory inside the work tree.
+type Git struct {
+ Dir string
+ // Env, when set, replaces the process environment for every git invocation. Tests use it to
+ // keep the caller's global git configuration out of the repository under test.
+ Env []string
+}
+
+// ErrNotRepository is returned when Dir is not inside a git work tree.
+var ErrNotRepository = errors.New("not a git repository")
+
+// Run runs git with args and returns its trimmed stdout. stdin, when non-nil, is written to git's
+// standard input.
+func (g Git) Run(ctx context.Context, stdin []byte, args ...string) (string, error) {
+ out, err := g.run(ctx, stdin, args...)
+ return strings.TrimRight(string(out), "\r\n"), err
+}
+
+// RunRaw is Run without trimming, for output whose trailing bytes are data (NUL-separated lists).
+func (g Git) RunRaw(ctx context.Context, args ...string) ([]byte, error) {
+ return g.run(ctx, nil, args...)
+}
+
+func (g Git) run(ctx context.Context, stdin []byte, args ...string) ([]byte, error) {
+ full := append([]string{"-C", g.dir()}, args...)
+ cmd := exec.CommandContext(ctx, "git", full...)
+ if g.Env != nil {
+ cmd.Env = g.Env
+ }
+ if stdin != nil {
+ cmd.Stdin = bytes.NewReader(stdin)
+ }
+ var stdout, stderr bytes.Buffer
+ cmd.Stdout = &stdout
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return nil, ctxErr
+ }
+ msg := strings.TrimSpace(stderr.String())
+ if msg == "" {
+ msg = err.Error()
+ }
+ return nil, &GitError{Args: args, Message: msg, Err: err}
+ }
+ return stdout.Bytes(), nil
+}
+
+func (g Git) dir() string {
+ if g.Dir == "" {
+ return "."
+ }
+ return g.Dir
+}
+
+// GitError is a git invocation that exited unsuccessfully.
+type GitError struct {
+ Args []string
+ Message string
+ Err error
+}
+
+func (e *GitError) Error() string {
+ return fmt.Sprintf("git %s: %s", strings.Join(e.Args, " "), e.Message)
+}
+
+func (e *GitError) Unwrap() error { return e.Err }
+
+// Repo is a resolved repository: the top of the work tree, the per-worktree git directory, and the
+// common directory worktrees share (where hooks and refs live).
+type Repo struct {
+ Git Git
+ Root string
+ GitDir string
+ CommonDir string
+}
+
+// OpenRepo resolves the repository containing g.Dir.
+func OpenRepo(ctx context.Context, g Git) (Repo, error) {
+ out, err := g.Run(ctx, nil, "rev-parse", "--show-toplevel", "--absolute-git-dir", "--git-common-dir")
+ if err != nil {
+ var gitErr *GitError
+ if errors.As(err, &gitErr) {
+ return Repo{}, fmt.Errorf("%w: %s", ErrNotRepository, g.dir())
+ }
+ return Repo{}, err
+ }
+ lines := strings.Split(out, "\n")
+ if len(lines) != 3 || strings.TrimSpace(lines[0]) == "" {
+ // A bare repository has no top level, and nothing in one was written by an agent.
+ return Repo{}, fmt.Errorf("%w (no work tree): %s", ErrNotRepository, g.dir())
+ }
+ root := filepath.Clean(strings.TrimSpace(lines[0]))
+ gitDir := filepath.Clean(strings.TrimSpace(lines[1]))
+ common := strings.TrimSpace(lines[2])
+ if !filepath.IsAbs(common) {
+ // --git-common-dir is relative to the directory git ran in, not to the top level.
+ base, err := filepath.Abs(g.dir())
+ if err != nil {
+ return Repo{}, err
+ }
+ common = filepath.Join(base, common)
+ }
+ return Repo{
+ Git: Git{Dir: root, Env: g.Env},
+ Root: root,
+ GitDir: gitDir,
+ CommonDir: filepath.Clean(common),
+ }, nil
+}
+
+// roots returns the spellings of the work tree root a recorded path may use: the one git reports
+// and, when it differs, the one with symlinks resolved (macOS reports /var for /private/var).
+func (r Repo) roots() []string {
+ roots := []string{r.Root}
+ if resolved, err := filepath.EvalSymlinks(r.Root); err == nil && resolved != r.Root {
+ roots = append(roots, resolved)
+ }
+ return roots
+}
+
+// RelPath returns path as a slash-separated path relative to the work tree root, and false when
+// path is not inside the work tree. A relative path is taken relative to base, which is where the
+// session that recorded it was running.
+func (r Repo) RelPath(path, base string) (string, bool) {
+ path = strings.TrimSpace(path)
+ if path == "" {
+ return "", false
+ }
+ path = strings.TrimPrefix(path, "file://")
+ if !filepath.IsAbs(path) {
+ if base == "" || !filepath.IsAbs(base) {
+ return "", false
+ }
+ path = filepath.Join(base, path)
+ }
+ path = filepath.Clean(path)
+ candidates := []string{path}
+ if resolved, ok := resolveExisting(path); ok && resolved != path {
+ candidates = append(candidates, resolved)
+ }
+ for _, root := range r.roots() {
+ for _, candidate := range candidates {
+ rel, err := filepath.Rel(root, candidate)
+ if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || filepath.IsAbs(rel) {
+ continue
+ }
+ rel = filepath.ToSlash(rel)
+ if rel == ".git" || strings.HasPrefix(rel, ".git/") {
+ return "", false
+ }
+ return rel, true
+ }
+ }
+ return "", false
+}
+
+// resolveExisting resolves symlinks in the longest prefix of path that exists, so a deleted file
+// under a symlinked directory still resolves.
+func resolveExisting(path string) (string, bool) {
+ suffix := ""
+ current := path
+ for {
+ if resolved, err := filepath.EvalSymlinks(current); err == nil {
+ if suffix == "" {
+ return resolved, true
+ }
+ return filepath.Join(resolved, suffix), true
+ }
+ parent := filepath.Dir(current)
+ if parent == current {
+ return "", false
+ }
+ if suffix == "" {
+ suffix = filepath.Base(current)
+ } else {
+ suffix = filepath.Join(filepath.Base(current), suffix)
+ }
+ current = parent
+ }
+}
+
+// IsolatedEnv is an environment for git that ignores the user's global and system configuration.
+// Tests use it; nothing in the shipping path does, because a user's hooks run with their config.
+func IsolatedEnv(home string) []string {
+ env := []string{
+ "HOME=" + home,
+ "GIT_CONFIG_NOSYSTEM=1",
+ "GIT_CONFIG_GLOBAL=" + filepath.Join(home, ".gitconfig"),
+ "GIT_AUTHOR_NAME=Beacon Test",
+ "GIT_COMMITTER_NAME=Beacon Test",
+ "GIT_TERMINAL_PROMPT=0",
+ }
+ for _, key := range []string{"PATH", "SYSTEMROOT", "TMPDIR", "TEMP", "TMP"} {
+ if value, ok := os.LookupEnv(key); ok {
+ env = append(env, key+"="+value)
+ }
+ }
+ return env
+}
diff --git a/cli/beacon/internal/gitlink/helpers_test.go b/cli/beacon/internal/gitlink/helpers_test.go
new file mode 100644
index 00000000..ce31464f
--- /dev/null
+++ b/cli/beacon/internal/gitlink/helpers_test.go
@@ -0,0 +1,161 @@
+package gitlink
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+// testRepo is a real repository in a temp dir, driven with an environment that ignores the
+// developer's git configuration.
+type testRepo struct {
+ t *testing.T
+ root string
+ env []string
+}
+
+func newTestRepo(t *testing.T) *testRepo {
+ t.Helper()
+ if _, err := exec.LookPath("git"); err != nil {
+ t.Skip("git not installed")
+ }
+ base := t.TempDir()
+ home := filepath.Join(base, "home")
+ root := filepath.Join(base, "repo")
+ for _, dir := range []string{home, root} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ r := &testRepo{t: t, root: root, env: IsolatedEnv(home)}
+ r.git("init", "-q", "-b", "main")
+ r.git("config", "commit.gpgsign", "false")
+ return r
+}
+
+func (r *testRepo) gitClient() Git { return Git{Dir: r.root, Env: r.env} }
+
+func (r *testRepo) open() Repo {
+ r.t.Helper()
+ repo, err := OpenRepo(context.Background(), r.gitClient())
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ return repo
+}
+
+func (r *testRepo) git(args ...string) string {
+ r.t.Helper()
+ out, err := r.gitClient().Run(context.Background(), nil, args...)
+ if err != nil {
+ r.t.Fatalf("git %s: %v", strings.Join(args, " "), err)
+ }
+ return out
+}
+
+func (r *testRepo) write(rel, content string) {
+ r.t.Helper()
+ path := filepath.Join(r.root, filepath.FromSlash(rel))
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ r.t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+// commitAt stages everything and commits with both dates pinned, returning the new sha.
+func (r *testRepo) commitAt(message string, at time.Time) string {
+ r.t.Helper()
+ r.git("add", "-A")
+ stamp := at.UTC().Format(time.RFC3339)
+ cmd := exec.Command("git", "-C", r.root, "commit", "-q", "--allow-empty", "-m", message)
+ cmd.Env = append(append([]string{}, r.env...), "GIT_AUTHOR_DATE="+stamp, "GIT_COMMITTER_DATE="+stamp)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ r.t.Fatalf("commit: %v\n%s", err, out)
+ }
+ return r.git("rev-parse", "HEAD")
+}
+
+// logEvent is the part of an event the tests vary.
+type logEvent struct {
+ at time.Time
+ harness string
+ session string
+ cwd string
+ action string
+ filePath string
+ operation string
+ command string
+ args interface{}
+}
+
+func (e logEvent) event() schema.Event {
+ ev := schema.NewEvent(schema.NewEventOptions{Action: e.action, Harness: schema.HarnessInfo{Name: e.harness}})
+ ev.Timestamp = schema.FormatTimestamp(e.at)
+ if e.session != "" || e.cwd != "" {
+ ev.Session = &schema.SessionInfo{ID: e.session, WorkingDirectory: e.cwd}
+ }
+ if e.filePath != "" {
+ ev.File = &schema.FileInfo{Path: e.filePath, Operation: e.operation}
+ }
+ if e.command != "" {
+ ev.Command = &schema.CommandInfo{Command: e.command}
+ }
+ if e.args != nil {
+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{Call: &schema.GenAIToolCallInfo{Arguments: e.args}}}
+ }
+ return ev
+}
+
+func writeLog(t *testing.T, path string, events ...logEvent) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ var b strings.Builder
+ for _, e := range events {
+ data, err := json.Marshal(e.event())
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.Write(data)
+ b.WriteByte('\n')
+ }
+ if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func writeLogAppend(t *testing.T, path string, events ...logEvent) {
+ t.Helper()
+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ for _, e := range events {
+ data, err := json.Marshal(e.event())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.Write(append(data, '\n')); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func keys(links []Link) []string {
+ out := make([]string, 0, len(links))
+ for _, l := range links {
+ out = append(out, l.Key())
+ }
+ return out
+}
diff --git a/cli/beacon/internal/gitlink/link.go b/cli/beacon/internal/gitlink/link.go
new file mode 100644
index 00000000..60536fb8
--- /dev/null
+++ b/cli/beacon/internal/gitlink/link.go
@@ -0,0 +1,171 @@
+package gitlink
+
+import (
+ "context"
+ "sort"
+ "time"
+)
+
+const (
+ // DefaultMinLookback is how far before a commit attribution always looks. It is the floor
+ // under the parent-commit bound below, so a commit made right after its parent still sees the
+ // edits that led up to both.
+ DefaultMinLookback = 2 * time.Hour
+ // DefaultMaxLookback caps how far back attribution looks, however old the parent commit is.
+ // It bounds the scan on a branch that sat untouched for a month.
+ DefaultMaxLookback = 24 * time.Hour
+ // commitTimeSlack admits events stamped just after the commit: commit times have one-second
+ // resolution and a hook's event can reach the log a moment after git wrote the commit.
+ commitTimeSlack = time.Minute
+ // MaxLinks bounds how many sessions one commit is linked to.
+ MaxLinks = 32
+)
+
+// Options configures Attribute.
+type Options struct {
+ // Rev is the commit to attribute, HEAD when empty.
+ Rev string
+ // LogPath is the runtime JSONL log to read sessions from.
+ LogPath string
+ MinLookback time.Duration
+ MaxLookback time.Duration
+ // DryRun computes the links without writing the note.
+ DryRun bool
+}
+
+// Candidate is a session that wrote at least one file the commit changes.
+type Candidate struct {
+ Link
+ // Files are the commit's files the session wrote, sorted.
+ Files []string `json:"files"`
+ LastWriteAt time.Time `json:"last_write_at"`
+ // AlreadyLinked is true when the commit's note already named the session.
+ AlreadyLinked bool `json:"already_linked,omitempty"`
+}
+
+// Result is the outcome of attributing one commit.
+type Result struct {
+ Commit Commit `json:"commit"`
+ RepoRoot string `json:"repo_root"`
+ Since time.Time `json:"since"`
+ Until time.Time `json:"until"`
+ ChangedFiles int `json:"changed_files"`
+ Candidates []Candidate `json:"candidates"`
+ // Added are the links this run wrote (or, on a dry run, would write).
+ Added []Link `json:"added"`
+ // NoteUpdated is true when the note on the commit changed.
+ NoteUpdated bool `json:"note_updated"`
+ DryRun bool `json:"dry_run,omitempty"`
+}
+
+// Window returns the span of runtime-log time attribution reads for commit: from the later of the
+// parent commit and maxLookback before the commit -- but never less than minLookback before it --
+// up to the commit plus a small slack.
+//
+// The parent is the natural lower bound: edits made since the previous commit are the ones this
+// commit can contain. The floor keeps work that straddled the parent, and the cap keeps a stale
+// parent from turning a hook into a scan of the endpoint's whole history.
+func Window(commit Commit, minLookback, maxLookback time.Duration) (since, until time.Time) {
+ if minLookback <= 0 {
+ minLookback = DefaultMinLookback
+ }
+ if maxLookback < minLookback {
+ maxLookback = minLookback
+ }
+ until = commit.CommitTime.Add(commitTimeSlack)
+ since = commit.CommitTime.Add(-maxLookback)
+ if !commit.ParentTime.IsZero() && commit.ParentTime.After(since) {
+ since = commit.ParentTime
+ }
+ if floor := commit.CommitTime.Add(-minLookback); since.After(floor) {
+ since = floor
+ }
+ return since, until
+}
+
+// Attribute links the commit to the sessions in the runtime log that wrote the files it changes.
+//
+// A session is a candidate when, inside Window, it wrote at least one file the commit changes.
+// Candidates are ranked by how many of the commit's files they wrote, then by how recently, and
+// the top MaxLinks are merged into the commit's note. The link is inferred from overlap and says
+// so everywhere it is reported: a session that edited a file a person then rewrote by hand is
+// still linked, which is the right default for "what produced this commit", and a session that
+// wrote nothing the commit kept is not.
+func Attribute(ctx context.Context, repo Repo, opts Options) (Result, error) {
+ commit, err := ResolveCommit(ctx, repo.Git, opts.Rev)
+ if err != nil {
+ return Result{}, err
+ }
+ since, until := Window(commit, opts.MinLookback, opts.MaxLookback)
+ result := Result{Commit: commit, RepoRoot: repo.Root, Since: since, Until: until, DryRun: opts.DryRun}
+
+ changed, err := ChangedFiles(ctx, repo.Git, commit.SHA)
+ if err != nil {
+ return Result{}, err
+ }
+ result.ChangedFiles = len(changed)
+ if len(changed) == 0 {
+ return result, nil
+ }
+ evidence, err := ReadEvidence(ctx, repo, opts.LogPath, since, until)
+ if err != nil {
+ return Result{}, err
+ }
+ note, err := ReadNote(ctx, repo.Git, commit.SHA)
+ if err != nil {
+ return Result{}, err
+ }
+ existing := map[string]bool{}
+ for _, link := range ParseNote(note) {
+ existing[link.Key()] = true
+ }
+
+ result.Candidates = rankCandidates(evidence, changed, existing)
+ for _, c := range result.Candidates {
+ if !c.AlreadyLinked && len(result.Added) < MaxLinks {
+ result.Added = append(result.Added, c.Link)
+ }
+ }
+ if len(result.Added) == 0 || opts.DryRun {
+ return result, nil
+ }
+ updated, err := AddLinks(ctx, repo.Git, commit.SHA, result.Added)
+ if err != nil {
+ return Result{}, err
+ }
+ result.NoteUpdated = updated
+ return result, nil
+}
+
+func rankCandidates(evidence map[string]*SessionEvidence, changed []string, existing map[string]bool) []Candidate {
+ var candidates []Candidate
+ for key, session := range evidence {
+ var files []string
+ for _, path := range changed {
+ if _, ok := session.Files[path]; ok {
+ files = append(files, path)
+ }
+ }
+ if len(files) == 0 {
+ continue
+ }
+ sort.Strings(files)
+ candidates = append(candidates, Candidate{
+ Link: session.Link,
+ Files: files,
+ LastWriteAt: session.LastWrite(files),
+ AlreadyLinked: existing[key],
+ })
+ }
+ sort.Slice(candidates, func(i, j int) bool {
+ a, b := candidates[i], candidates[j]
+ if len(a.Files) != len(b.Files) {
+ return len(a.Files) > len(b.Files)
+ }
+ if !a.LastWriteAt.Equal(b.LastWriteAt) {
+ return a.LastWriteAt.After(b.LastWriteAt)
+ }
+ return a.Key() < b.Key()
+ })
+ return candidates
+}
diff --git a/cli/beacon/internal/gitlink/link_test.go b/cli/beacon/internal/gitlink/link_test.go
new file mode 100644
index 00000000..251281e3
--- /dev/null
+++ b/cli/beacon/internal/gitlink/link_test.go
@@ -0,0 +1,272 @@
+package gitlink
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "testing"
+ "time"
+)
+
+func TestWindow(t *testing.T) {
+ commit := func(parentAgo time.Duration) Commit {
+ c := Commit{CommitTime: t0}
+ if parentAgo != 0 {
+ c.ParentTime = t0.Add(-parentAgo)
+ }
+ return c
+ }
+ for _, tc := range []struct {
+ name string
+ commit Commit
+ wantSince time.Duration // before t0
+ }{
+ {"parent a minute ago still sees the floor", commit(time.Minute), DefaultMinLookback},
+ {"parent five hours ago bounds the window", commit(5 * time.Hour), 5 * time.Hour},
+ {"parent a month ago is capped", commit(30 * 24 * time.Hour), DefaultMaxLookback},
+ {"root commit uses the cap", commit(0), DefaultMaxLookback},
+ {"parent after the commit (clock skew) keeps the floor", Commit{CommitTime: t0, ParentTime: t0.Add(time.Hour)}, DefaultMinLookback},
+ } {
+ since, until := Window(tc.commit, 0, DefaultMaxLookback)
+ if want := t0.Add(-tc.wantSince); !since.Equal(want) {
+ t.Errorf("%s: since %v, want %v", tc.name, since, want)
+ }
+ if !until.Equal(t0.Add(commitTimeSlack)) {
+ t.Errorf("%s: until %v", tc.name, until)
+ }
+ }
+}
+
+func TestReadEvidence(t *testing.T) {
+ r := newTestRepo(t)
+ repo := r.open()
+ root := repo.Root
+ logPath := filepath.Join(t.TempDir(), "logs", "runtime.jsonl")
+ since, until := t0.Add(-time.Hour), t0
+ in := t0.Add(-10 * time.Minute)
+ writeLog(t, logPath,
+ // Absolute path, file event.
+ logEvent{at: in, harness: "claude_code", session: "s1", cwd: root, action: "file.modified", filePath: filepath.Join(root, "a.go"), operation: "modify"},
+ // A read is not a write.
+ logEvent{at: in, harness: "claude_code", session: "s1", cwd: root, action: "tool.invoked", filePath: filepath.Join(root, "read-only.go"), operation: "read"},
+ // A write-type operation on a tool event counts.
+ logEvent{at: in, harness: "claude_code", session: "s1", cwd: root, action: "tool.invoked", filePath: filepath.Join(root, "b.go"), operation: "create"},
+ // Outside the window on either side.
+ logEvent{at: since.Add(-time.Second), harness: "claude_code", session: "s1", action: "file.modified", filePath: filepath.Join(root, "old.go"), operation: "modify"},
+ logEvent{at: until.Add(time.Second), harness: "claude_code", session: "s1", action: "file.modified", filePath: filepath.Join(root, "late.go"), operation: "modify"},
+ // Outside the repository, and inside .git.
+ logEvent{at: in, harness: "claude_code", session: "s1", action: "file.modified", filePath: filepath.Join(filepath.Dir(root), "elsewhere.go"), operation: "modify"},
+ logEvent{at: in, harness: "claude_code", session: "s1", action: "file.modified", filePath: filepath.Join(root, ".git", "config"), operation: "modify"},
+ // Relative path whose working directory only a later event reports.
+ logEvent{at: in, harness: "cursor", session: "c1", action: "file.modified", filePath: "rel/c.go", operation: "modify"},
+ logEvent{at: in.Add(time.Second), harness: "cursor", session: "c1", cwd: root, action: "session.started"},
+ // Shell and patch evidence, relative to the session's directory.
+ logEvent{at: in, harness: "codex", session: "x1", cwd: filepath.Join(root, "sub"), action: "command.executed", command: "rm stale.txt && echo ok > out.log"},
+ logEvent{at: in, harness: "codex", session: "x1", cwd: root, action: "tool.invoked", args: map[string]interface{}{"input": "*** Begin Patch\n*** Update File: p.go\n*** End Patch"}},
+ // A raw harness name is normalized, so both rows are one session.
+ logEvent{at: in, harness: "claude", session: "s1", cwd: root, action: "file.created", filePath: filepath.Join(root, "c.go")},
+ // A session that wrote nothing in the repository is not evidence.
+ logEvent{at: in, harness: "gemini_cli", session: "g1", cwd: root, action: "prompt.submitted"},
+ // No session id.
+ logEvent{at: in, harness: "claude_code", action: "file.modified", filePath: filepath.Join(root, "orphan.go"), operation: "modify"},
+ )
+ got, err := ReadEvidence(context.Background(), repo, logPath, since, until)
+ if err != nil {
+ t.Fatal(err)
+ }
+ files := map[string][]string{}
+ for key, s := range got {
+ for f := range s.Files {
+ files[key] = append(files[key], f)
+ }
+ sort.Strings(files[key])
+ }
+ want := map[string][]string{
+ "claude_code/s1": {"a.go", "b.go", "c.go"},
+ "cursor/c1": {"rel/c.go"},
+ "codex_cli/x1": {"p.go", "sub/out.log", "sub/stale.txt"},
+ }
+ if !reflect.DeepEqual(files, want) {
+ t.Fatalf("evidence\n got %v\nwant %v", files, want)
+ }
+ if !got["claude_code/s1"].Files["a.go"].Equal(in) {
+ t.Fatalf("write time %v", got["claude_code/s1"].Files["a.go"])
+ }
+}
+
+func TestReadEvidenceStopsAtArchivesOlderThanTheWindow(t *testing.T) {
+ r := newTestRepo(t)
+ repo := r.open()
+ dir := t.TempDir()
+ logPath := filepath.Join(dir, "runtime.jsonl")
+ in := t0.Add(-5 * time.Minute)
+ ev := func(session string) logEvent {
+ return logEvent{at: in, harness: "codex", session: session, cwd: repo.Root, action: "file.modified", filePath: filepath.Join(repo.Root, "f.go"), operation: "modify"}
+ }
+ writeLog(t, logPath, ev("active"))
+ writeLog(t, logPath+".1", ev("archive1"))
+ writeLog(t, logPath+".2", ev("archive2")) // in the window by timestamp, but the file is stale
+ writeLog(t, logPath+".x", ev("not-an-archive"))
+ touch := func(path string, at time.Time) {
+ if err := os.Chtimes(path, at, at); err != nil {
+ t.Fatal(err)
+ }
+ }
+ touch(logPath, t0)
+ touch(logPath+".1", t0.Add(-30*time.Minute))
+ touch(logPath+".2", t0.Add(-3*time.Hour))
+ touch(logPath+".x", t0)
+
+ got, err := ReadEvidence(context.Background(), repo, logPath, t0.Add(-time.Hour), t0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sessions []string
+ for key := range got {
+ sessions = append(sessions, key)
+ }
+ sort.Strings(sessions)
+ if !reflect.DeepEqual(sessions, []string{"codex_cli/active", "codex_cli/archive1"}) {
+ t.Fatalf("sessions %v", sessions)
+ }
+}
+
+func TestReadEvidenceMissingLogIsEmpty(t *testing.T) {
+ r := newTestRepo(t)
+ got, err := ReadEvidence(context.Background(), r.open(), filepath.Join(t.TempDir(), "absent.jsonl"), t0.Add(-time.Hour), t0)
+ if err != nil || len(got) != 0 {
+ t.Fatalf("got %v, %v", got, err)
+ }
+}
+
+func TestReadEvidenceThroughASymlinkedRoot(t *testing.T) {
+ r := newTestRepo(t)
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(r.root, link); err != nil {
+ t.Skip("symlinks unavailable:", err)
+ }
+ repo := r.open()
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ // The agent ran in the symlinked spelling of the repository.
+ writeLog(t, logPath, logEvent{at: t0, harness: "codex", session: "s", cwd: link, action: "file.modified", filePath: filepath.Join(link, "x.go"), operation: "modify"})
+ got, err := ReadEvidence(context.Background(), repo, logPath, t0.Add(-time.Hour), t0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if s := got["codex_cli/s"]; s == nil || s.Files["x.go"].IsZero() {
+ t.Fatalf("got %+v", got)
+ }
+}
+
+func TestAttributeLinksByOverlapAndRanks(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a.go", "1")
+ r.write("b.go", "1")
+ r.write("c.go", "1")
+ r.commitAt("base", t0.Add(-3*time.Hour))
+
+ root := r.open().Root
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ write := func(at time.Duration, harness, session, file string) logEvent {
+ return logEvent{at: t0.Add(-at), harness: harness, session: session, cwd: root, action: "file.modified", filePath: filepath.Join(root, file), operation: "modify"}
+ }
+ writeLog(t, logPath,
+ write(50*time.Minute, "claude_code", "two-files", "a.go"),
+ write(40*time.Minute, "claude_code", "two-files", "b.go"),
+ write(10*time.Minute, "codex", "one-file-recent", "c.go"),
+ write(30*time.Minute, "cursor", "one-file-older", "c.go"),
+ write(20*time.Minute, "cursor", "unrelated", "not-in-commit.go"),
+ // Before the parent commit: that work went into the parent.
+ write(4*time.Hour, "codex", "before-parent", "a.go"),
+ )
+ r.write("a.go", "2")
+ r.write("b.go", "2")
+ r.write("c.go", "2")
+ sha := r.commitAt("change", t0)
+ repo := r.open()
+
+ dry, err := Attribute(ctx, repo, Options{LogPath: logPath, DryRun: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantOrder := []string{"claude_code/two-files", "codex_cli/one-file-recent", "cursor/one-file-older"}
+ if got := keys(dry.Added); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("dry run links %v, want %v", got, wantOrder)
+ }
+ if dry.NoteUpdated || dry.Commit.SHA != sha || dry.ChangedFiles != 3 {
+ t.Fatalf("dry run result %+v", dry)
+ }
+ if note, _ := ReadNote(ctx, repo.Git, sha); note != "" {
+ t.Fatalf("dry run wrote a note: %q", note)
+ }
+ if got := dry.Candidates[0].Files; !reflect.DeepEqual(got, []string{"a.go", "b.go"}) {
+ t.Fatalf("candidate files %v", got)
+ }
+
+ res, err := Attribute(ctx, repo, Options{LogPath: logPath})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !res.NoteUpdated {
+ t.Fatal("note not updated")
+ }
+ note, _ := ReadNote(ctx, repo.Git, sha)
+ if got := keys(ParseNote(note)); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("note links %v", got)
+ }
+
+ // Running again finds the same sessions already linked and writes nothing.
+ again, err := Attribute(ctx, repo, Options{LogPath: logPath})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if again.NoteUpdated || len(again.Added) != 0 || len(again.Candidates) != 3 || !again.Candidates[0].AlreadyLinked {
+ t.Fatalf("second run %+v", again)
+ }
+}
+
+func TestAttributeEmptyCommitAndNoEvidence(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a", "1")
+ r.commitAt("base", t0.Add(-time.Hour))
+ r.commitAt("empty", t0)
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ res, err := Attribute(ctx, r.open(), Options{LogPath: logPath})
+ if err != nil || res.ChangedFiles != 0 || len(res.Added) != 0 {
+ t.Fatalf("empty commit: %+v %v", res, err)
+ }
+ r.write("a", "2")
+ r.commitAt("real", t0.Add(time.Minute))
+ res, err = Attribute(ctx, r.open(), Options{LogPath: logPath})
+ if err != nil || res.ChangedFiles != 1 || len(res.Candidates) != 0 || res.NoteUpdated {
+ t.Fatalf("no evidence: %+v %v", res, err)
+ }
+}
+
+func TestAttributeOlderCommitUsesItsOwnWindow(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a.go", "1")
+ r.commitAt("base", t0.Add(-48*time.Hour))
+ r.write("a.go", "2")
+ old := r.commitAt("old", t0.Add(-24*time.Hour))
+ r.write("a.go", "3")
+ r.commitAt("new", t0)
+ root := r.open().Root
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ writeLog(t, logPath,
+ logEvent{at: t0.Add(-25 * time.Hour), harness: "codex", session: "made-old", cwd: root, action: "file.modified", filePath: filepath.Join(root, "a.go"), operation: "modify"},
+ logEvent{at: t0.Add(-time.Hour), harness: "codex", session: "made-new", cwd: root, action: "file.modified", filePath: filepath.Join(root, "a.go"), operation: "modify"},
+ )
+ res, err := Attribute(ctx, r.open(), Options{LogPath: logPath, Rev: old, DryRun: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := keys(res.Added); !reflect.DeepEqual(got, []string{"codex_cli/made-old"}) {
+ t.Fatalf("old commit links %v", got)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/note.go b/cli/beacon/internal/gitlink/note.go
new file mode 100644
index 00000000..3f929114
--- /dev/null
+++ b/cli/beacon/internal/gitlink/note.go
@@ -0,0 +1,129 @@
+package gitlink
+
+import (
+ "regexp"
+ "sort"
+ "strings"
+)
+
+// NotesRef is the notes ref Beacon's links live under. It is a contract: `beacon git notes`, the
+// hooks, and anyone who fetched the ref from a teammate read it by this name.
+const NotesRef = "refs/notes/beacon"
+
+// linePrefix starts every line Beacon writes. Lines without it are someone else's -- a person who
+// ran `git notes append` by hand, or a tool that shares the ref -- and are kept as they are.
+const linePrefix = "beacon:"
+
+// MaxSessionIDLength bounds a session id in a note. Runtime session ids are UUIDs or short
+// tokens; anything longer is not one, and a note line has no business carrying it.
+const MaxSessionIDLength = 256
+
+var harnessPattern = regexp.MustCompile(`^[a-z0-9_]+$`)
+
+// Link names one session a commit is linked to.
+type Link struct {
+ Harness string `json:"harness"`
+ SessionID string `json:"session_id"`
+}
+
+// Key is the link's identity, harness and session together: two runtimes may reuse an id.
+func (l Link) Key() string { return l.Harness + "/" + l.SessionID }
+
+// Valid reports whether the link can be written as a note line and read back unchanged.
+func (l Link) Valid() bool {
+ if !harnessPattern.MatchString(l.Harness) {
+ return false
+ }
+ if l.SessionID == "" || len(l.SessionID) > MaxSessionIDLength {
+ return false
+ }
+ for _, r := range l.SessionID {
+ // No whitespace, since a line ends at it, and no control or non-ASCII characters, since a
+ // note is displayed by `git log` and must not be able to move the terminal's cursor.
+ if r <= ' ' || r >= 0x7f {
+ return false
+ }
+ }
+ return true
+}
+
+// Line is the note line for the link.
+func (l Link) Line() string { return linePrefix + l.Key() }
+
+// ParseLine reads one note line, returning false for a line that is not a Beacon link.
+func ParseLine(line string) (Link, bool) {
+ rest, ok := strings.CutPrefix(strings.TrimSpace(line), linePrefix)
+ if !ok {
+ return Link{}, false
+ }
+ // Anything after whitespace is reserved for later fields; readers today ignore it.
+ if i := strings.IndexAny(rest, " \t"); i >= 0 {
+ rest = rest[:i]
+ }
+ harness, session, ok := strings.Cut(rest, "/")
+ if !ok {
+ return Link{}, false
+ }
+ link := Link{Harness: harness, SessionID: session}
+ if !link.Valid() {
+ return Link{}, false
+ }
+ return link, true
+}
+
+// ParseNote returns the Beacon links in a note, in the order they first appear, without repeats.
+func ParseNote(note string) []Link {
+ var links []Link
+ seen := map[string]bool{}
+ for _, line := range strings.Split(note, "\n") {
+ link, ok := ParseLine(line)
+ if !ok || seen[link.Key()] {
+ continue
+ }
+ seen[link.Key()] = true
+ links = append(links, link)
+ }
+ return links
+}
+
+// MergeNote returns note with links added. Every existing line is kept verbatim and in place --
+// lines that are not Beacon links belong to a person or another tool, and a Beacon line carrying
+// fields this version does not know was written by a newer one -- except that blank lines and a
+// repeat of a link already seen are dropped. New links are appended in the order given. Merging
+// links a note already has returns it unchanged apart from that normalization.
+//
+// Links are never removed here. A note is shared history, and a teammate's link on the same commit
+// is as true as ours.
+func MergeNote(note string, links []Link) string {
+ var lines []string
+ seen := map[string]bool{}
+ for _, line := range strings.Split(note, "\n") {
+ line = strings.TrimRight(line, "\r")
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ if link, ok := ParseLine(line); ok {
+ if seen[link.Key()] {
+ continue
+ }
+ seen[link.Key()] = true
+ }
+ lines = append(lines, line)
+ }
+ for _, link := range links {
+ if !link.Valid() || seen[link.Key()] {
+ continue
+ }
+ seen[link.Key()] = true
+ lines = append(lines, link.Line())
+ }
+ if len(lines) == 0 {
+ return ""
+ }
+ return strings.Join(lines, "\n") + "\n"
+}
+
+// SortLinks orders links by key, for output that must not depend on note order.
+func SortLinks(links []Link) {
+ sort.Slice(links, func(i, j int) bool { return links[i].Key() < links[j].Key() })
+}
diff --git a/cli/beacon/internal/gitlink/note_test.go b/cli/beacon/internal/gitlink/note_test.go
new file mode 100644
index 00000000..43400c5e
--- /dev/null
+++ b/cli/beacon/internal/gitlink/note_test.go
@@ -0,0 +1,88 @@
+package gitlink
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestLinkLineRoundTrips(t *testing.T) {
+ for _, link := range []Link{
+ {Harness: "claude_code", SessionID: "0f8e2c1a-5b6d-4e7f-8a9b-0c1d2e3f4a5b"},
+ {Harness: "codex", SessionID: "rollout-2026-09-27T10:00:00"},
+ {Harness: "cursor", SessionID: "a/b"}, // only the first slash separates the harness
+ } {
+ got, ok := ParseLine(link.Line())
+ if !ok || got != link {
+ t.Fatalf("ParseLine(%q) = %+v, %v; want %+v", link.Line(), got, ok, link)
+ }
+ }
+}
+
+func TestParseLineRejectsWhatItCannotWriteBack(t *testing.T) {
+ for _, line := range []string{
+ "",
+ "traces:abc",
+ "beacon:",
+ "beacon:claude_code", // no session
+ "beacon:claude_code/", // empty session
+ "beacon:Claude/abc", // harness is lowercase snake case
+ "beacon:claude-code/abc", // ... with no dashes
+ "beacon:/abc", // empty harness
+ "beacon:codex/ab\x1b[2Jc", // terminal escape in the id
+ "beacon:codex/café", // non-ASCII
+ "beacon:codex/" + strings.Repeat("a", MaxSessionIDLength+1),
+ } {
+ if link, ok := ParseLine(line); ok {
+ t.Errorf("ParseLine(%q) = %+v, want rejection", line, link)
+ }
+ }
+}
+
+func TestParseLineIgnoresTrailingFields(t *testing.T) {
+ got, ok := ParseLine(" beacon:codex/abc future=field ")
+ if !ok || got != (Link{Harness: "codex", SessionID: "abc"}) {
+ t.Fatalf("got %+v, %v", got, ok)
+ }
+}
+
+func TestParseNoteDedupesInOrder(t *testing.T) {
+ note := "beacon:codex/b\nsomeone's text\nbeacon:claude_code/a\n\nbeacon:codex/b\n"
+ got := keys(ParseNote(note))
+ want := []string{"codex/b", "claude_code/a"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+}
+
+func TestMergeNoteKeepsOtherLinesAndAppends(t *testing.T) {
+ note := "Reviewed-by: a person\nbeacon:codex/a\nbeacon:v2 something newer\n"
+ got := MergeNote(note, []Link{{"codex", "a"}, {"claude_code", "b"}, {"BAD", "c"}})
+ want := "Reviewed-by: a person\nbeacon:codex/a\nbeacon:v2 something newer\nbeacon:claude_code/b\n"
+ if got != want {
+ t.Fatalf("got %q\nwant %q", got, want)
+ }
+}
+
+func TestMergeNoteIsIdempotent(t *testing.T) {
+ links := []Link{{"codex", "a"}, {"cursor", "b"}}
+ once := MergeNote("", links)
+ if twice := MergeNote(once, links); twice != once {
+ t.Fatalf("second merge changed the note:\n%q\n%q", once, twice)
+ }
+ if once != "beacon:codex/a\nbeacon:cursor/b\n" {
+ t.Fatalf("got %q", once)
+ }
+}
+
+func TestMergeNoteNormalizesBlankLinesAndRepeats(t *testing.T) {
+ // `git notes append` separates paragraphs with a blank line, and a note merged with the
+ // cat_sort_uniq strategy can hold a link twice if one copy carries CRLF.
+ got := MergeNote("beacon:codex/a\r\n\nbeacon:codex/a\n", nil)
+ if got != "beacon:codex/a\n" {
+ t.Fatalf("got %q", got)
+ }
+ if MergeNote("\n\n", nil) != "" {
+ t.Fatal("an empty note must stay empty")
+ }
+}
diff --git a/cli/beacon/internal/gitlink/notes.go b/cli/beacon/internal/gitlink/notes.go
new file mode 100644
index 00000000..91e499aa
--- /dev/null
+++ b/cli/beacon/internal/gitlink/notes.go
@@ -0,0 +1,214 @@
+package gitlink
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// txRefPrefix holds a notes transaction's working ref. It sits under refs/notes/ because `git
+// notes --ref` only operates on refs there, and it is deleted when the transaction ends.
+const txRefPrefix = "refs/notes/beacon-tx/"
+
+// noteAttempts is how many times a note update retries after losing the ref to a concurrent
+// writer (another worktree's hook committing at the same moment).
+const noteAttempts = 3
+
+// ReadNote returns the Beacon note on commit, "" when it has none.
+func ReadNote(ctx context.Context, g Git, commit string) (string, error) {
+ return readNote(ctx, g, NotesRef, commit)
+}
+
+func readNote(ctx context.Context, g Git, ref, commit string) (string, error) {
+ out, err := g.Run(ctx, nil, "notes", "--ref="+ref, "show", commit)
+ if err != nil {
+ var gitErr *GitError
+ if errors.As(err, &gitErr) && strings.Contains(strings.ToLower(gitErr.Message), "no note found") {
+ return "", nil
+ }
+ // A repository whose notes ref does not exist yet says the same thing on every git version
+ // Beacon supports, but older ones word it differently; an absent ref is the empty note.
+ if exists, existsErr := refExists(ctx, g, ref); existsErr == nil && !exists {
+ return "", nil
+ }
+ return "", err
+ }
+ return out, nil
+}
+
+// AddLinks merges links into commit's note and reports whether the note changed.
+//
+// The update is a compare-and-swap on NotesRef: the new notes commit is built on a private working
+// ref and then moved into place only if NotesRef still points where it did when the transaction
+// began. Two hooks committing at once in two worktrees of one repository therefore never lose each
+// other's links; the loser rebuilds on the winner and tries again.
+func AddLinks(ctx context.Context, g Git, commit string, links []Link) (bool, error) {
+ var valid []Link
+ for _, link := range links {
+ if link.Valid() {
+ valid = append(valid, link)
+ }
+ }
+ if len(valid) == 0 {
+ return false, nil
+ }
+ token, err := txToken()
+ if err != nil {
+ return false, err
+ }
+ var lastErr error
+ for attempt := 1; attempt <= noteAttempts; attempt++ {
+ changed, err := addLinksOnce(ctx, g, commit, valid, txRefPrefix+token+"-"+strconv.Itoa(attempt))
+ if err == nil {
+ return changed, nil
+ }
+ if !errors.Is(err, errRefMoved) {
+ return false, err
+ }
+ lastErr = err
+ }
+ return false, fmt.Errorf("update %s: %w", NotesRef, lastErr)
+}
+
+var errRefMoved = errors.New("notes ref moved during update")
+
+func addLinksOnce(ctx context.Context, g Git, commit string, links []Link, txRef string) (changed bool, err error) {
+ base, err := resolveRef(ctx, g, NotesRef)
+ if err != nil {
+ return false, err
+ }
+ if base != "" {
+ if _, err := g.Run(ctx, nil, "update-ref", txRef, base); err != nil {
+ return false, err
+ }
+ }
+ defer func() {
+ // Best effort, and on a fresh context: a transaction that timed out must still not leave
+ // its working ref behind.
+ cleanup, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ _, _ = g.Run(cleanup, nil, "update-ref", "-d", txRef)
+ }()
+
+ current, err := readNote(ctx, g, txRef, commit)
+ if err != nil {
+ return false, err
+ }
+ merged := MergeNote(current, links)
+ if merged == normalizeNote(current) {
+ return false, nil
+ }
+ if _, err := g.Run(ctx, []byte(merged), "notes", "--ref="+txRef, "add", "--force", "--file=-", commit); err != nil {
+ return false, err
+ }
+ next, err := resolveRef(ctx, g, txRef)
+ if err != nil {
+ return false, err
+ }
+ // update-ref with an old value is the swap: it fails if NotesRef moved since base was read. An
+ // empty old value asserts the ref does not exist yet.
+ if _, err := g.Run(ctx, nil, "update-ref", "-m", "beacon: link sessions", NotesRef, next, base); err != nil {
+ if moved, checkErr := refMoved(ctx, g, base); checkErr == nil && moved {
+ return false, errRefMoved
+ }
+ return false, err
+ }
+ return true, nil
+}
+
+func normalizeNote(note string) string { return MergeNote(note, nil) }
+
+func refMoved(ctx context.Context, g Git, base string) (bool, error) {
+ now, err := resolveRef(ctx, g, NotesRef)
+ if err != nil {
+ return false, err
+ }
+ return now != base, nil
+}
+
+// resolveRef returns the object ref points to, "" when it does not exist.
+func resolveRef(ctx context.Context, g Git, ref string) (string, error) {
+ exists, err := refExists(ctx, g, ref)
+ if err != nil || !exists {
+ return "", err
+ }
+ return g.Run(ctx, nil, "rev-parse", "--verify", "--quiet", ref)
+}
+
+func refExists(ctx context.Context, g Git, ref string) (bool, error) {
+ _, err := g.Run(ctx, nil, "show-ref", "--verify", "--quiet", ref)
+ if err == nil {
+ return true, nil
+ }
+ var gitErr *GitError
+ if errors.As(err, &gitErr) {
+ return false, nil
+ }
+ return false, err
+}
+
+func txToken() (string, error) {
+ var b [6]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ return "", err
+ }
+ return strconv.Itoa(os.Getpid()) + "-" + hex.EncodeToString(b[:]), nil
+}
+
+// LinkedCommit is a commit carrying Beacon links.
+type LinkedCommit struct {
+ SHA string `json:"sha"`
+ CommitTime time.Time `json:"commit_time"`
+ Subject string `json:"subject"`
+ Links []Link `json:"links"`
+}
+
+// ListLinked walks up to limit commits reachable from rev (HEAD when empty), newest first, and
+// returns those whose Beacon note names at least one session.
+func ListLinked(ctx context.Context, g Git, rev string, limit int) ([]LinkedCommit, error) {
+ if rev == "" {
+ rev = "HEAD"
+ }
+ if limit <= 0 {
+ limit = 20
+ }
+ if exists, err := refExists(ctx, g, NotesRef); err != nil || !exists {
+ return nil, err
+ }
+ // Records end in RS and fields are split by NUL, so a note or subject containing newlines
+ // cannot shift fields. --no-notes first clears any notes.displayRef the user configured.
+ out, err := g.RunRaw(ctx, "log", "--no-notes", "--notes="+NotesRef, "-n", strconv.Itoa(limit),
+ "--format=%H%x00%ct%x00%s%x00%N%x1e", rev, "--")
+ if err != nil {
+ return nil, err
+ }
+ var commits []LinkedCommit
+ for _, record := range strings.Split(string(out), "\x1e") {
+ record = strings.TrimLeft(record, "\r\n")
+ if record == "" {
+ continue
+ }
+ fields := strings.SplitN(record, "\x00", 4)
+ if len(fields) != 4 {
+ continue
+ }
+ links := ParseNote(fields[3])
+ if len(links) == 0 {
+ continue
+ }
+ seconds, _ := strconv.ParseInt(fields[1], 10, 64)
+ commits = append(commits, LinkedCommit{
+ SHA: fields[0],
+ CommitTime: time.Unix(seconds, 0).UTC(),
+ Subject: fields[2],
+ Links: links,
+ })
+ }
+ return commits, nil
+}
diff --git a/cli/beacon/internal/gitlink/notes_test.go b/cli/beacon/internal/gitlink/notes_test.go
new file mode 100644
index 00000000..38f2dbed
--- /dev/null
+++ b/cli/beacon/internal/gitlink/notes_test.go
@@ -0,0 +1,283 @@
+package gitlink
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sort"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+var t0 = time.Date(2026, 9, 27, 12, 0, 0, 0, time.UTC)
+
+func TestOpenRepoResolvesRootAndDirs(t *testing.T) {
+ r := newTestRepo(t)
+ r.write("sub/dir/x.txt", "x")
+ repo, err := OpenRepo(context.Background(), Git{Dir: filepath.Join(r.root, "sub", "dir"), Env: r.env})
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantRoot, _ := filepath.EvalSymlinks(r.root)
+ gotRoot, _ := filepath.EvalSymlinks(repo.Root)
+ if gotRoot != wantRoot {
+ t.Fatalf("root %q, want %q", repo.Root, r.root)
+ }
+ if filepath.Base(repo.GitDir) != ".git" || filepath.Base(repo.CommonDir) != ".git" {
+ t.Fatalf("git dir %q common %q", repo.GitDir, repo.CommonDir)
+ }
+ if !filepath.IsAbs(repo.CommonDir) {
+ t.Fatalf("common dir %q is not absolute", repo.CommonDir)
+ }
+}
+
+func TestOpenRepoOutsideRepository(t *testing.T) {
+ r := newTestRepo(t)
+ outside := t.TempDir()
+ _, err := OpenRepo(context.Background(), Git{Dir: outside, Env: append(r.env, "GIT_CEILING_DIRECTORIES="+filepath.Dir(outside))})
+ if !errors.Is(err, ErrNotRepository) {
+ t.Fatalf("got %v, want ErrNotRepository", err)
+ }
+}
+
+func TestOpenRepoInLinkedWorktreeSharesCommonDir(t *testing.T) {
+ r := newTestRepo(t)
+ r.write("a.txt", "a")
+ r.commitAt("init", t0)
+ wt := filepath.Join(filepath.Dir(r.root), "wt")
+ r.git("worktree", "add", "-q", "-b", "feature", wt)
+ repo, err := OpenRepo(context.Background(), Git{Dir: wt, Env: r.env})
+ if err != nil {
+ t.Fatal(err)
+ }
+ main := r.open()
+ same := func(a, b string) bool {
+ ra, _ := filepath.EvalSymlinks(a)
+ rb, _ := filepath.EvalSymlinks(b)
+ return ra == rb
+ }
+ if !same(repo.CommonDir, main.CommonDir) {
+ t.Fatalf("worktree common dir %q, main %q", repo.CommonDir, main.CommonDir)
+ }
+ if same(repo.GitDir, main.GitDir) {
+ t.Fatal("a linked worktree has its own git dir")
+ }
+}
+
+func TestChangedFilesCoversRenamesRootAndMerges(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a.go", "package a\n\nfunc A() {}\n")
+ r.write("dir/b.go", "package b\n")
+ root := r.commitAt("root", t0)
+ got, err := ChangedFiles(ctx, r.gitClient(), root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sort.Strings(got)
+ if !reflect.DeepEqual(got, []string{"a.go", "dir/b.go"}) {
+ t.Fatalf("root commit files %q", got)
+ }
+
+ r.git("mv", "a.go", "renamed.go")
+ r.write("dir/b.go", "package b\n\nvar X = 1\n")
+ rename := r.commitAt("rename", t0.Add(time.Minute))
+ got, _ = ChangedFiles(ctx, r.gitClient(), rename)
+ sort.Strings(got)
+ if !reflect.DeepEqual(got, []string{"a.go", "dir/b.go", "renamed.go"}) {
+ t.Fatalf("rename commit files %q", got)
+ }
+
+ // A merge is compared with its first parent: the files the merge brought in.
+ r.git("checkout", "-q", "-b", "side")
+ r.write("side.txt", "side")
+ r.commitAt("side", t0.Add(2*time.Minute))
+ r.git("checkout", "-q", "main")
+ r.write("main.txt", "main")
+ r.commitAt("main", t0.Add(3*time.Minute))
+ r.git("merge", "-q", "--no-ff", "--no-edit", "side")
+ merge := r.git("rev-parse", "HEAD")
+ got, _ = ChangedFiles(ctx, r.gitClient(), merge)
+ if !reflect.DeepEqual(got, []string{"side.txt"}) {
+ t.Fatalf("merge commit files %q", got)
+ }
+}
+
+func TestChangedFilesKeepsUnusualNames(t *testing.T) {
+ r := newTestRepo(t)
+ name := "sp ace/tab\tand\"quote.txt"
+ if strings.ContainsAny(name, "\t\"") && os.PathSeparator == '\\' {
+ t.Skip("name not representable on this filesystem")
+ }
+ r.write(name, "x")
+ sha := r.commitAt("odd", t0)
+ got, err := ChangedFiles(context.Background(), r.gitClient(), sha)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, []string{name}) {
+ t.Fatalf("got %q", got)
+ }
+}
+
+func TestResolveCommitReadsParentTime(t *testing.T) {
+ r := newTestRepo(t)
+ r.write("a", "1")
+ r.commitAt("first", t0)
+ r.write("a", "2")
+ sha := r.commitAt("second\n\nbody", t0.Add(90*time.Minute))
+ c, err := ResolveCommit(context.Background(), r.gitClient(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c.SHA != sha || c.Subject != "second" || !c.CommitTime.Equal(t0.Add(90*time.Minute)) || !c.ParentTime.Equal(t0) || len(c.Parents) != 1 {
+ t.Fatalf("got %+v", c)
+ }
+ if _, err := ResolveCommit(context.Background(), r.gitClient(), "does-not-exist"); err == nil {
+ t.Fatal("want an error for an unknown revision")
+ }
+}
+
+func TestAddLinksCreatesMergesAndIsIdempotent(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ r.write("a", "1")
+ sha := r.commitAt("c", t0)
+ g := r.gitClient()
+
+ if note, err := ReadNote(ctx, g, sha); err != nil || note != "" {
+ t.Fatalf("fresh repo note %q, %v", note, err)
+ }
+ changed, err := AddLinks(ctx, g, sha, []Link{{"codex", "s1"}})
+ if err != nil || !changed {
+ t.Fatalf("first add: %v %v", changed, err)
+ }
+ // A person's own note line on the same commit survives Beacon's update.
+ r.git("notes", "--ref="+NotesRef, "append", "-m", "Reviewed-by: someone", sha)
+ changed, err = AddLinks(ctx, g, sha, []Link{{"codex", "s1"}, {"claude_code", "s2"}})
+ if err != nil || !changed {
+ t.Fatalf("second add: %v %v", changed, err)
+ }
+ changed, err = AddLinks(ctx, g, sha, []Link{{"claude_code", "s2"}})
+ if err != nil || changed {
+ t.Fatalf("repeat add changed=%v err=%v", changed, err)
+ }
+ note, _ := ReadNote(ctx, g, sha)
+ want := "beacon:codex/s1\nReviewed-by: someone\nbeacon:claude_code/s2"
+ if note != want {
+ t.Fatalf("note %q, want %q", note, want)
+ }
+ if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {
+ t.Fatalf("leftover refs:\n%s", refs)
+ }
+ if changed, err := AddLinks(ctx, g, sha, []Link{{"Bad Harness", "x"}}); err != nil || changed {
+ t.Fatalf("invalid links must be ignored: %v %v", changed, err)
+ }
+}
+
+func TestAddLinksConcurrentWritersLoseNothing(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ var shas []string
+ for i := 0; i < 3; i++ {
+ r.write("f", fmt.Sprint(i))
+ shas = append(shas, r.commitAt(fmt.Sprint("c", i), t0.Add(time.Duration(i)*time.Minute)))
+ }
+ g := r.gitClient()
+ const writers = 6
+ var wg sync.WaitGroup
+ errs := make(chan error, writers*len(shas))
+ for w := 0; w < writers; w++ {
+ for _, sha := range shas {
+ wg.Add(1)
+ go func(w int, sha string) {
+ defer wg.Done()
+ // Retries are bounded, so a writer may legitimately give up under this much
+ // contention; it must then say so rather than drop the link silently.
+ for attempt := 0; attempt < 10; attempt++ {
+ _, err := AddLinks(ctx, g, sha, []Link{{"codex", fmt.Sprint("w", w)}})
+ if err == nil {
+ return
+ }
+ if !errors.Is(err, errRefMoved) {
+ errs <- err
+ return
+ }
+ }
+ errs <- fmt.Errorf("writer %d never landed on %s", w, sha)
+ }(w, sha)
+ }
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Fatal(err)
+ }
+ for _, sha := range shas {
+ note, err := ReadNote(ctx, g, sha)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := keys(ParseNote(note))
+ sort.Strings(got)
+ var want []string
+ for w := 0; w < writers; w++ {
+ want = append(want, fmt.Sprint("codex/w", w))
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("%s: links %v, want %v", sha[:7], got, want)
+ }
+ }
+ if refs := r.git("for-each-ref", "--format=%(refname)", "refs/notes/"); refs != NotesRef {
+ t.Fatalf("leftover transaction refs:\n%s", refs)
+ }
+}
+
+func TestListLinked(t *testing.T) {
+ r := newTestRepo(t)
+ ctx := context.Background()
+ g := r.gitClient()
+ if got, err := ListLinked(ctx, g, "", 10); err != nil || len(got) != 0 {
+ t.Fatalf("empty repo: %v %v", got, err)
+ }
+ r.write("a", "1")
+ first := r.commitAt("first", t0)
+ r.write("a", "2")
+ r.commitAt("second (unlinked)", t0.Add(time.Minute))
+ r.write("a", "3")
+ third := r.commitAt("third", t0.Add(2*time.Minute))
+ if _, err := AddLinks(ctx, g, first, []Link{{"cursor", "c1"}}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := AddLinks(ctx, g, third, []Link{{"codex", "x"}, {"claude_code", "y"}}); err != nil {
+ t.Fatal(err)
+ }
+ // A note on the ref that is not Beacon's is not a linked commit.
+ r.git("notes", "--ref="+NotesRef, "add", "-m", "just text", "HEAD~1")
+ // A displayRef the user configured must not leak into the parsed output.
+ r.git("notes", "--ref=refs/notes/commits", "add", "-m", "beacon:codex/forged", third)
+ r.git("config", "notes.displayRef", "refs/notes/commits")
+
+ got, err := ListLinked(ctx, g, "", 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(got) != 2 || got[0].SHA != third || got[1].SHA != first {
+ t.Fatalf("got %+v", got)
+ }
+ if !reflect.DeepEqual(keys(got[0].Links), []string{"codex/x", "claude_code/y"}) || got[0].Subject != "third" {
+ t.Fatalf("third: %+v", got[0])
+ }
+ if !got[1].CommitTime.Equal(t0) {
+ t.Fatalf("commit time %v", got[1].CommitTime)
+ }
+ // The limit counts commits walked, linked or not.
+ if got, _ := ListLinked(ctx, g, "", 2); len(got) != 1 || got[0].SHA != third {
+ t.Fatalf("limit 2: %+v", got)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/shell.go b/cli/beacon/internal/gitlink/shell.go
new file mode 100644
index 00000000..8c65c16b
--- /dev/null
+++ b/cli/beacon/internal/gitlink/shell.go
@@ -0,0 +1,301 @@
+package gitlink
+
+import (
+ "path/filepath"
+ "strings"
+)
+
+// ShellWrittenPaths returns the files a shell command line evidently writes: the operands of rm,
+// touch, truncate, mv, cp, install, tee, `git mv`/`git rm`, in-place sed/perl, and the targets of
+// output redirections. It is deliberately shallow. Anything it cannot read plainly -- variables,
+// subshells, a script that writes files itself -- contributes nothing, because a wrong path would
+// link a session to a commit it had no part in, and a missed one only leaves a link out.
+func ShellWrittenPaths(command string) []string {
+ var paths []string
+ moved := false
+ for _, segment := range splitShellSegments(command) {
+ words, redirected := stripRedirections(shellWords(segment))
+ found := append(redirected, commandTargets(words)...)
+ if moved {
+ // After a cd, a relative path is relative to somewhere this parser does not track.
+ found = absoluteOnly(found)
+ }
+ paths = append(paths, found...)
+ if len(words) > 0 && (words[0] == "cd" || words[0] == "pushd" || words[0] == "popd") {
+ moved = true
+ }
+ }
+ return dedupe(paths)
+}
+
+func commandTargets(words []string) []string {
+ // Skip environment assignments and the wrappers that run the real command.
+ for len(words) > 0 {
+ w := words[0]
+ if strings.Contains(w, "=") && !strings.HasPrefix(w, "=") && !strings.HasPrefix(w, "-") {
+ words = words[1:]
+ continue
+ }
+ if w == "sudo" || w == "command" || w == "exec" || w == "nohup" || w == "time" {
+ words = words[1:]
+ continue
+ }
+ break
+ }
+ if len(words) == 0 {
+ return nil
+ }
+ name := filepath.Base(words[0])
+ args := words[1:]
+ if name == "git" && len(args) > 0 && (args[0] == "mv" || args[0] == "rm") {
+ name, args = "git-"+args[0], args[1:]
+ }
+ operands, flags := splitFlags(args)
+ switch name {
+ case "rm", "unlink", "touch", "truncate", "git-rm":
+ return operands
+ case "mv", "git-mv":
+ // Every operand: the sources stop existing and the destination starts to.
+ return operands
+ case "cp", "install", "ln":
+ if len(operands) >= 2 {
+ return operands[len(operands)-1:]
+ }
+ case "tee":
+ return operands
+ case "sed", "perl", "gsed":
+ if hasInPlaceFlag(flags) && len(operands) >= 2 {
+ // The first operand is the script, unless it came in with -e.
+ return operands[1:]
+ }
+ }
+ return nil
+}
+
+func hasInPlaceFlag(flags []string) bool {
+ for _, f := range flags {
+ if f == "--in-place" || strings.HasPrefix(f, "--in-place=") {
+ return true
+ }
+ if strings.HasPrefix(f, "-") && !strings.HasPrefix(f, "--") && strings.Contains(f[1:], "i") {
+ return true
+ }
+ }
+ return false
+}
+
+// splitFlags separates operands from flags. Everything after `--` is an operand.
+func splitFlags(args []string) (operands, flags []string) {
+ for i, a := range args {
+ if a == "--" {
+ return append(operands, args[i+1:]...), flags
+ }
+ if strings.HasPrefix(a, "-") && a != "-" {
+ flags = append(flags, a)
+ continue
+ }
+ operands = append(operands, a)
+ }
+ return operands, flags
+}
+
+// stripRedirections removes output redirections from words and returns the remaining words and
+// the redirections' targets. Only an unquoted word can be a redirection: `echo '> x'` prints.
+func stripRedirections(words []shellWord) (rest, targets []string) {
+ for i := 0; i < len(words); i++ {
+ w := words[i]
+ op, target := "", ""
+ if !w.quoted {
+ op, target = redirection(w.text)
+ }
+ if op == "" {
+ if !w.expands {
+ rest = append(rest, w.text)
+ }
+ continue
+ }
+ if target == "" && i+1 < len(words) {
+ i++
+ if words[i].expands {
+ continue
+ }
+ target = words[i].text
+ }
+ if target != "" && !strings.HasPrefix(target, "&") && target != "/dev/null" && !strings.HasPrefix(target, "/dev/") {
+ targets = append(targets, target)
+ }
+ }
+ return rest, targets
+}
+
+// redirection recognizes `>`, `>>`, `>|`, `1>`, `2>`, `&>`, with the target attached or not. Input
+// redirection is not a write and is left in place.
+func redirection(word string) (op, target string) {
+ for _, prefix := range []string{"&>>", "&>", "1>>", "2>>", "1>", "2>", ">>", ">|", ">"} {
+ if strings.HasPrefix(word, prefix) {
+ return prefix, word[len(prefix):]
+ }
+ }
+ return "", ""
+}
+
+// splitShellSegments splits a command line into simple commands at ;, &&, ||, |, & and newlines,
+// outside quotes.
+func splitShellSegments(command string) []string {
+ var segments []string
+ var cur strings.Builder
+ quote := byte(0)
+ flush := func() {
+ if s := strings.TrimSpace(cur.String()); s != "" {
+ segments = append(segments, s)
+ }
+ cur.Reset()
+ }
+ for i := 0; i < len(command); i++ {
+ c := command[i]
+ switch {
+ case quote != 0:
+ if c == quote {
+ quote = 0
+ } else if c == '\\' && quote == '"' && i+1 < len(command) {
+ cur.WriteByte(c)
+ i++
+ c = command[i]
+ }
+ cur.WriteByte(c)
+ case c == '\'' || c == '"':
+ quote = c
+ cur.WriteByte(c)
+ case c == '\\' && i+1 < len(command):
+ cur.WriteByte(c)
+ i++
+ cur.WriteByte(command[i])
+ case c == '|' && i > 0 && command[i-1] == '>':
+ // `>|` is a clobbering redirection, not a pipe.
+ cur.WriteByte(c)
+ case c == ';' || c == '\n' || c == '|':
+ flush()
+ case c == '&':
+ // `&>` is a redirection, not a separator.
+ if i+1 < len(command) && command[i+1] == '>' {
+ cur.WriteByte(c)
+ continue
+ }
+ if i > 0 && command[i-1] == '>' {
+ cur.WriteByte(c)
+ continue
+ }
+ flush()
+ default:
+ cur.WriteByte(c)
+ }
+ }
+ flush()
+ return segments
+}
+
+// shellWord is one word of a simple command. quoted records that some of it was quoted, which
+// stops it being read as an operator; expands records that its value depends on an expansion ($,
+// `, a glob), which makes it unknown here -- such a word is never reported as a path.
+type shellWord struct {
+ text string
+ quoted bool
+ expands bool
+}
+
+// shellWords splits a simple command into words, honoring quotes and backslashes.
+func shellWords(segment string) []shellWord {
+ var words []shellWord
+ var cur strings.Builder
+ inWord, expands, quoted := false, false, false
+ quote := byte(0)
+ flush := func() {
+ if inWord {
+ words = append(words, shellWord{text: cur.String(), quoted: quoted, expands: expands})
+ }
+ cur.Reset()
+ inWord, expands, quoted = false, false, false
+ }
+ for i := 0; i < len(segment); i++ {
+ c := segment[i]
+ switch {
+ case quote == '\'':
+ if c == '\'' {
+ quote = 0
+ } else {
+ cur.WriteByte(c)
+ }
+ case quote == '"':
+ switch {
+ case c == '"':
+ quote = 0
+ case c == '\\' && i+1 < len(segment):
+ i++
+ cur.WriteByte(segment[i])
+ case c == '$' || c == '`':
+ expands = true
+ cur.WriteByte(c)
+ default:
+ cur.WriteByte(c)
+ }
+ case c == '\'' || c == '"':
+ quote, inWord, quoted = c, true, true
+ case c == '\\' && i+1 < len(segment):
+ i++
+ cur.WriteByte(segment[i])
+ inWord, quoted = true, true
+ case c == ' ' || c == '\t':
+ flush()
+ case c == '(' || c == ')' || c == '{' || c == '}':
+ flush()
+ default:
+ if c == '$' || c == '`' || c == '*' || c == '?' || c == '[' || c == '~' {
+ expands = true
+ }
+ cur.WriteByte(c)
+ inWord = true
+ }
+ }
+ flush()
+ return words
+}
+
+// PatchPaths returns the files an apply_patch envelope touches: Add, Update, Delete, and the
+// destination of a Move.
+func PatchPaths(patch string) []string {
+ var paths []string
+ for _, line := range strings.Split(patch, "\n") {
+ line = strings.TrimSpace(line)
+ for _, prefix := range []string{"*** Add File:", "*** Update File:", "*** Delete File:", "*** Move to:"} {
+ if rest, ok := strings.CutPrefix(line, prefix); ok {
+ if p := strings.TrimSpace(rest); p != "" {
+ paths = append(paths, p)
+ }
+ }
+ }
+ }
+ return dedupe(paths)
+}
+
+func absoluteOnly(paths []string) []string {
+ var out []string
+ for _, p := range paths {
+ if filepath.IsAbs(p) {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+func dedupe(values []string) []string {
+ seen := map[string]bool{}
+ out := values[:0]
+ for _, v := range values {
+ if v == "" || seen[v] {
+ continue
+ }
+ seen[v] = true
+ out = append(out, v)
+ }
+ return out
+}
diff --git a/cli/beacon/internal/gitlink/shell_test.go b/cli/beacon/internal/gitlink/shell_test.go
new file mode 100644
index 00000000..1cd9b13b
--- /dev/null
+++ b/cli/beacon/internal/gitlink/shell_test.go
@@ -0,0 +1,87 @@
+package gitlink
+
+import (
+ "reflect"
+ "testing"
+)
+
+func TestShellWrittenPaths(t *testing.T) {
+ for _, tc := range []struct {
+ command string
+ want []string
+ }{
+ {"rm -f a.txt b.txt", []string{"a.txt", "b.txt"}},
+ {"rm -rf -- -weird", []string{"-weird"}},
+ {"touch new.go && go test ./...", []string{"new.go"}},
+ {"mv old.go new.go", []string{"old.go", "new.go"}},
+ {"git mv src/a.go src/b.go", []string{"src/a.go", "src/b.go"}},
+ {"git rm --cached secret.env", []string{"secret.env"}},
+ {"cp -r template out/dir", []string{"out/dir"}},
+ {"echo hi > out.txt", []string{"out.txt"}},
+ {"echo hi >out.txt 2>&1", []string{"out.txt"}},
+ {"printf x >> log.txt; cat log.txt", []string{"log.txt"}},
+ {"cmd >| forced.txt", []string{"forced.txt"}},
+ {"go build &> build.log", []string{"build.log"}},
+ {"make 2>/dev/null", nil},
+ {"cat a.txt | tee copy.txt", []string{"copy.txt"}},
+ {"sed -i 's/a/b/' x.go y.go", []string{"x.go", "y.go"}},
+ {"sed -i.bak -e 's/a/b/' x.go", []string{"x.go"}},
+ {"sed 's/a/b/' x.go", nil}, // not in place: prints, writes nothing
+ {"perl -pi -e 's/a/b/' z.pl", []string{"z.pl"}},
+ {"FOO=1 sudo rm build/out", []string{"build/out"}},
+ {`rm "file with spaces.txt"`, []string{"file with spaces.txt"}},
+ {`rm file\ two.txt`, []string{"file two.txt"}},
+ {"echo '> not a redirect' ; ls", nil},
+ {"rm $TARGET", nil}, // unknown value
+ {"rm *.log", nil}, // glob
+ {"rm \"$(pwd)/x\"", nil}, // expansion inside quotes
+ {"(cd sub && rm x)", nil}, // x is sub/x, which this parser does not follow
+ {"cd /tmp && rm /abs/path.txt && rm rel.txt", []string{"/abs/path.txt"}},
+ {"rm before.txt; cd sub; rm after.txt", []string{"before.txt"}},
+ {"ls -la; go test ./...", nil},
+ {"cat <<EOF > gen.txt\nhello\nEOF", []string{"gen.txt"}},
+ } {
+ got := ShellWrittenPaths(tc.command)
+ if len(got) == 0 && len(tc.want) == 0 {
+ continue
+ }
+ if !reflect.DeepEqual(got, tc.want) {
+ t.Errorf("ShellWrittenPaths(%q) = %q, want %q", tc.command, got, tc.want)
+ }
+ }
+}
+
+func TestPatchPaths(t *testing.T) {
+ patch := `*** Begin Patch
+*** Update File: cli/main.go
+@@
+-old
++new
+*** Add File: docs/new.md
++hello
+*** Delete File: stale.txt
+*** Update File: a.go
+*** Move to: b.go
+*** End Patch`
+ want := []string{"cli/main.go", "docs/new.md", "stale.txt", "a.go", "b.go"}
+ if got := PatchPaths(patch); !reflect.DeepEqual(got, want) {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestPatchPathsInArguments(t *testing.T) {
+ patch := "*** Begin Patch\n*** Update File: x.go\n*** End Patch"
+ for name, args := range map[string]interface{}{
+ "object": map[string]interface{}{"input": patch},
+ "json text": `{"input":"*** Begin Patch\n*** Update File: x.go\n*** End Patch"}`,
+ "nested list": []interface{}{map[string]interface{}{"patch": patch}},
+ "bare string": patch,
+ } {
+ if got := patchPathsIn(args); !reflect.DeepEqual(got, []string{"x.go"}) {
+ t.Errorf("%s: got %q", name, got)
+ }
+ }
+ if got := patchPathsIn(map[string]interface{}{"content": "no patch here"}); len(got) != 0 {
+ t.Fatalf("got %q", got)
+ }
+}
diff --git a/docs/cli/git.mdx b/docs/cli/git.mdx
new file mode 100644
index 00000000..9881a74f
--- /dev/null
+++ b/docs/cli/git.mdx
@@ -0,0 +1,85 @@
+---
+title: "beacon git"
+description: "Link git commits to the agent sessions that wrote them"
+---
+
+## Command overview
+
+`beacon git` records which agent sessions produced a commit, as a git note on the commit.
+
+```bash title="Command syntax"
+beacon git link [<commit>] [flags]
+beacon git notes [<revision>] [flags]
+```
+
+A link names a session by its harness and session id, for example `beacon:claude_code/0f8e2c1a-…`. The note carries identifiers only, never prompts, output, or diffs: notes can be shared with a remote, and the session's content stays in the local runtime log. `beacon handoff export <session-id>` reads a linked session back.
+
+## How sessions are matched to a commit
+
+Beacon already records every file a supported runtime writes, so matching a commit to its sessions is a read of the local runtime log. No state file is kept and nothing touches the network.
+
+1. **Window.** Beacon reads the log from the parent commit's time up to the commit. The window always covers at least `--min-lookback` (2 hours) and never more than `--max-lookback` (24 hours) before the commit. Events after the commit are ignored, because they cannot have produced it.
+2. **Evidence.** A session wrote a file when the log has, for that session, a `file.created`, `file.modified` or `file.deleted` event, a tool event whose `file.operation` is a write, a shell command whose target is plain to read (`rm`, `mv`, `cp`, `touch`, `tee`, `sed -i`, `git mv`, output redirection), or an `apply_patch` envelope. Reads do not count.
+3. **Overlap.** Beacon compares those paths with the files the commit changes against its first parent, counting both sides of a rename. A session that wrote at least one of them is linked. Sessions are ordered by how many of the commit's files they wrote, then by how recently.
+
+A link is an inference, not an observation. A session that edited a file a person then rewrote by hand is still linked, and a session that wrote nothing the commit kept is not.
+
+## `beacon git link`
+
+Links a commit (default `HEAD`) and writes the note.
+
+```bash
+beacon git link
+beacon git link 3f6aa6c --dry-run
+```
+
+```text title="Example output"
+commit 3f6aa6c04b78 agent change
+window 2026-09-27 15:33:23 .. 2026-09-27 17:34:23
+ linked claude_code/sess-claude-e2e 3 of 3 file(s): keep.txt, src/app.go, stale.txt
+Wrote 1 link(s) to refs/notes/beacon.
+```
+
+Running `link` again adds only what is new. Links already on the commit, including a teammate's, are kept, as is any other text in the note.
+
+| Flag | Description |
+|------|-------------|
+| `--dry-run` | Show the links without writing the note |
+| `--min-lookback <duration>` | Always read at least this far before the commit (default `2h`) |
+| `--max-lookback <duration>` | Never read further than this before the commit (default `24h`) |
+| `--log-path <path>` | Runtime JSONL log to read (default the local runtime log) |
+| `-C`, `--cwd <dir>` | Repository to operate on |
+| `--json` | Print the result, with every candidate session and its matching files, as JSON |
+
+## `beacon git notes`
+
+Lists recent linked commits reachable from a revision (default `HEAD`).
+
+```bash
+beacon git notes --limit 50
+beacon git notes origin/main --json
+```
+
+| Flag | Description |
+|------|-------------|
+| `--limit <n>` | Number of commits to walk (default 20); commits without links are skipped |
+| `-C`, `--cwd <dir>` | Repository to operate on |
+| `--json` | Print commits and their links as JSON |
+
+## Note format
+
+Links live under `refs/notes/beacon`, one per line:
+
+```text
+beacon:<harness>/<session-id>
+```
+
+`<harness>` is Beacon's canonical harness name (`claude_code`, `codex_cli`, `cursor`, …). A session id has no whitespace, no control or non-ASCII characters, and at most 256 characters. Readers ignore anything after whitespace on a link line, which is reserved for later fields, and ignore lines that do not start with `beacon:`.
+
+Beacon updates the note with a compare-and-swap on the notes ref, so two commits made at the same moment in two worktrees of one repository never lose each other's links.
+
+To see links in `git log`:
+
+```bash
+git log --notes=beacon
+```
diff --git a/docs/docs.json b/docs/docs.json
index 10ca30a1..e485bf02 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -356,6 +356,7 @@
]
},
"cli/handoff",
+ "cli/git",
"cli/token-usage",
"cli/version"
]