Skip to content

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

feat(git-hooks): record git hook runs that run out of time (#874)

claude[bot]59053938aa81
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index 94ee8101..886bcb95 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -175,6 +175,9 @@ func buildDoctorResult(status lifecycle.Status, generatedAt time.Time) doctorRes
checks = append(checks, check)
}
}
+ if check, ok := gitHookBudgetCheck(status.LogPath, generatedAt); ok {
+ checks = append(checks, check)
+ }
result := doctorResult{
Status: aggregateCheckStatus(checks),
Checks: checks,
@@ -1584,6 +1587,10 @@ func planDoctorFixes(result doctorResult, status lifecycle.Status) doctorFixPlan
}
case "dsh_hook_capture":
addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
+ // The budget is fixed, so there is nothing to repair; a commit the hook left unlinked is
+ // linked by hand.
+ case "git_hook_budget":
+ addSkip(plannedAction{Action: "manual_fix", Target: check.Target, Message: check.Action})
}
}
return plan
diff --git a/cli/beacon/cmd/git_budget.go b/cli/beacon/cmd/git_budget.go
new file mode 100644
index 00000000..509e9517
--- /dev/null
+++ b/cli/beacon/cmd/git_budget.go
@@ -0,0 +1,63 @@
+package cmd
+
+import (
+ "context"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+// gitOverrunWindow is how far back `beacon git status` and `beacon endpoint doctor` count git hook
+// runs that ran out of time.
+const gitOverrunWindow = 7 * 24 * time.Hour
+
+// startGitHook begins measuring one run of a git hook and returns the hook's context: bounded by
+// budget, and counting every git process started under it. Tests replace it to pin the clock and
+// end the hook's time in a chosen phase without waiting for a real deadline.
+var startGitHook = func(parent context.Context, hook string, budget time.Duration) (*gitlink.HookRun, context.Context, context.CancelFunc) {
+ run := &gitlink.HookRun{Hook: hook, Budget: budget}
+ ctx, cancel := context.WithTimeout(parent, budget)
+ return run, run.Start(ctx), cancel
+}
+
+// finishGitHook records the run in the runtime log when it ran out of time: one
+// git.hook_budget_exceeded event, through the writer the link events use, and nothing on the
+// terminal. ctx is the hook's own context, so a deadline that passed after the last step counts
+// too, as a run that finished late. It spawns no git and makes no network request; a log the hook
+// cannot write loses only the record.
+func finishGitHook(ctx context.Context, run *gitlink.HookRun, repoRoot string) {
+ run.Check(ctx, nil)
+ if event, ok := run.Event(repoRoot, version.GetVersion()); ok {
+ _, _ = writer.AppendEvent(event, writer.Options{Path: gitRuntimeLogPath(), UserMode: true})
+ }
+}
+
+// gitHookBudgetCheck is doctor's view of the git hook runs that ran out of time in the last week,
+// across every repository. It appears only when there were some, so an endpoint whose hooks fit
+// their budget (or that never installed them) sees no new line. A run cut short warns: it is a
+// commit left unlinked, or a link event, note or share left unrecorded. Runs that only finished
+// late are reported as ok, because nothing was lost.
+func gitHookBudgetCheck(logPath string, now time.Time) (diagnostics.Check, bool) {
+ overruns := gitlink.ScanBudgetOverruns(logPath, "", now.Add(-gitOverrunWindow))
+ if overruns.Last == nil {
+ return diagnostics.Check{}, false
+ }
+ check := diagnostics.Check{
+ Name: "git_hook_budget",
+ Target: overruns.Last.Repository,
+ Status: diagnostics.StatusOK,
+ Severity: diagnostics.SeverityInfo,
+ Message: describeGitOverruns(overruns),
+ Evidence: "git_hook_finished_late",
+ }
+ if overruns.CutShort > 0 {
+ check.Status = diagnostics.StatusWarn
+ check.Severity = diagnostics.SeverityLow
+ check.Evidence = "git_hook_cut_short"
+ check.Action = "run `beacon git status` in the repository to see its overruns, and `beacon git link <commit>` to link a commit the hook left unlinked"
+ }
+ return check, true
+}
diff --git a/cli/beacon/cmd/git_budget_test.go b/cli/beacon/cmd/git_budget_test.go
new file mode 100644
index 00000000..683e2227
--- /dev/null
+++ b/cli/beacon/cmd/git_budget_test.go
@@ -0,0 +1,381 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+)
+
+// The hook budget tests never wait on the wall clock (#859 exists because tests that did flaked on
+// slow runners). The hook's clock is a fake the test moves, and its deadline is a context the test
+// ends at the start of a chosen phase, so every step after that point sees exactly what a real
+// deadline would give it.
+
+// manualDeadline is a context whose deadline passes when the test says so.
+type manualDeadline struct {
+ context.Context
+ done chan struct{}
+ once sync.Once
+}
+
+func newManualDeadline(parent context.Context) *manualDeadline {
+ return &manualDeadline{Context: parent, done: make(chan struct{})}
+}
+
+func (c *manualDeadline) Done() <-chan struct{} { return c.done }
+
+func (c *manualDeadline) Err() error {
+ select {
+ case <-c.done:
+ return context.DeadlineExceeded
+ default:
+ return nil
+ }
+}
+
+func (c *manualDeadline) expire() { c.once.Do(func() { close(c.done) }) }
+
+type fakeHookClock struct {
+ mu sync.Mutex
+ now time.Time
+}
+
+func (c *fakeHookClock) Now() time.Time {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.now
+}
+
+func (c *fakeHookClock) advance(d time.Duration) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.now = c.now.Add(d)
+}
+
+var hookClockEpoch = time.Date(2026, 10, 14, 9, 0, 0, 0, time.UTC)
+
+// stubGitHookTime makes each phase of the next hook runs take steps[phase] on the hook's clock, and
+// ends the hook's time as phase expireIn begins (never, when expireIn is empty). The budgets are
+// the production ones; nothing here waits for them.
+func stubGitHookTime(t *testing.T, steps map[string]time.Duration, expireIn string) {
+ t.Helper()
+ prev := startGitHook
+ startGitHook = func(parent context.Context, hook string, budget time.Duration) (*gitlink.HookRun, context.Context, context.CancelFunc) {
+ clock := &fakeHookClock{now: hookClockEpoch}
+ ctx := newManualDeadline(parent)
+ run := &gitlink.HookRun{Hook: hook, Budget: budget, Now: clock.Now}
+ run.OnPhase = func(phase string) {
+ clock.advance(steps[phase])
+ if phase == expireIn {
+ ctx.expire()
+ }
+ }
+ return run, run.Start(ctx), func() {}
+ }
+ t.Cleanup(func() { startGitHook = prev })
+}
+
+func budgetEventsIn(t *testing.T, logPath string) []schema.Event {
+ t.Helper()
+ data, err := os.ReadFile(logPath)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var events []schema.Event
+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
+ var e schema.Event
+ if json.Unmarshal([]byte(line), &e) == nil && e.Event.Action == gitlink.BudgetAction {
+ events = append(events, e)
+ }
+ }
+ return events
+}
+
+// onlyBudgetEvent returns the one budget event in the log and checks the parts every one carries.
+func onlyBudgetEvent(t *testing.T, logPath string) schema.VCSHookInfo {
+ t.Helper()
+ events := budgetEventsIn(t, logPath)
+ if len(events) != 1 {
+ t.Fatalf("got %d budget events, want 1: %+v", len(events), events)
+ }
+ e := events[0]
+ if e.Harness.Name != "beacon" || e.Event.Category != "system" || e.VCS == nil || e.VCS.Hook == nil {
+ t.Fatalf("budget event %+v", e)
+ }
+ if err := e.Validate(); err != nil {
+ t.Fatalf("budget event does not validate: %v", err)
+ }
+ return *e.VCS.Hook
+}
+
+// hookRepoRoot is the work tree as the hooks record it: gitlink's cleaned path, which on Windows
+// uses backslashes where `git rev-parse --show-toplevel` prints forward slashes.
+func hookRepoRoot(t *testing.T, root string) string {
+ t.Helper()
+ repo, err := gitlink.OpenRepo(context.Background(), gitlink.Git{Dir: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return repo.Root
+}
+
+// postCommitFixture is a repository whose HEAD a session in the runtime log wrote. repoRoot is
+// the work tree as the hooks record it.
+func postCommitFixture(t *testing.T) (root, repoRoot, logPath string) {
+ t.Helper()
+ root = gitCommandRepo(t)
+ top := mustGit(t, root, "rev-parse", "--show-toplevel")
+ logPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(filepath.Join(root, "x.go"), []byte("package x\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ writeRuntimeEvent(t, logPath, top, "cur-1", "x.go")
+ mustGit(t, root, "add", "-A")
+ mustGit(t, root, "commit", "-q", "-m", "x")
+ return root, hookRepoRoot(t, root), logPath
+}
+
+// A post-commit run inside its budget links the commit and records no budget event.
+func TestGitHookPostCommitWithinBudgetRecordsNoOverrun(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"open_repository": 20 * time.Millisecond, "attribute": 400 * time.Millisecond, "record_link_event": 30 * time.Millisecond}, "")
+ root, _, logPath := postCommitFixture(t)
+ if out, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil || out != "" {
+ t.Fatalf("hook: %v %q", err, out)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD"); note != "beacon:cursor/cur-1" {
+ t.Fatalf("note %q", note)
+ }
+ if got := budgetEventsIn(t, logPath); len(got) != 0 {
+ t.Fatalf("a run within its budget recorded %+v", got)
+ }
+}
+
+// Running out of time while attributing leaves the commit unlinked, and the hook says so in the
+// runtime log, with the phase, the budget, the time the run and the phase took, and the git
+// processes it started, while staying silent on the terminal.
+func TestGitHookPostCommitRecordsAnOverrunThatCutTheLinkShort(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"open_repository": 40 * time.Millisecond, "attribute": 3250 * time.Millisecond}, "attribute")
+ root, top, logPath := postCommitFixture(t)
+ var stderr bytes.Buffer
+ if out, err := runGitStderr(t, &stderr, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil || out != "" || stderr.Len() != 0 {
+ t.Fatalf("hook: %v, stdout %q, stderr %q (a hook must stay quiet)", err, out, stderr.String())
+ }
+ if note := mustGitAllowFail(root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD"); note != "" {
+ t.Fatalf("a hook out of time still linked the commit: %q", note)
+ }
+ if got := linkEventsIn(t, logPath); len(got) != 0 {
+ t.Fatalf("link events %+v", got)
+ }
+ hook := onlyBudgetEvent(t, logPath)
+ if hook.Name != "post-commit" || hook.Phase != "attribute" || !hook.CutShort {
+ t.Fatalf("overrun %+v, want post-commit cut short in attribute", hook)
+ }
+ if hook.BudgetMS != gitHookBudget.Milliseconds() || hook.BudgetMS != 3000 {
+ t.Fatalf("budget %dms, want the production 3000ms", hook.BudgetMS)
+ }
+ if hook.ElapsedMS != 3290 || hook.PhaseElapsedMS != 3250 {
+ t.Fatalf("elapsed %dms (phase %dms), want 3290ms and 3250ms", hook.ElapsedMS, hook.PhaseElapsedMS)
+ }
+ if hook.GitSpawns < 1 {
+ t.Fatalf("counted %d git spawns; opening the repository alone spawns git", hook.GitSpawns)
+ }
+ if e := budgetEventsIn(t, logPath)[0]; e.Repository != top || e.Severity != schema.SeverityLow {
+ t.Fatalf("event repository %q severity %s, want %q low", e.Repository, e.Severity, top)
+ }
+}
+
+// A deadline that passes only in the last step, after the note is written, is recorded as a run
+// that finished late, not one that was cut short: the commit is linked.
+func TestGitHookPostCommitRecordsARunThatFinishedLate(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"attribute": 2900 * time.Millisecond, "record_link_event": 200 * time.Millisecond}, "record_link_event")
+ root, _, logPath := postCommitFixture(t)
+ if _, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil {
+ t.Fatal(err)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD"); note != "beacon:cursor/cur-1" {
+ t.Fatalf("note %q", note)
+ }
+ hook := onlyBudgetEvent(t, logPath)
+ if hook.Phase != "record_link_event" || hook.CutShort || hook.ElapsedMS != 3100 || hook.PhaseElapsedMS != 200 {
+ t.Fatalf("overrun %+v, want record_link_event finished late after 3100ms", hook)
+ }
+}
+
+// Running out of time before the repository is even resolved is still recorded, without a
+// repository.
+func TestGitHookPostCommitRecordsAnOverrunBeforeTheRepository(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"open_repository": 3500 * time.Millisecond}, "open_repository")
+ root, _, logPath := postCommitFixture(t)
+ if _, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil {
+ t.Fatal(err)
+ }
+ hook := onlyBudgetEvent(t, logPath)
+ if hook.Phase != "open_repository" || !hook.CutShort || hook.GitSpawns != 0 || hook.ElapsedMS != 3500 {
+ t.Fatalf("overrun %+v, want open_repository cut short with no git started", hook)
+ }
+ if e := budgetEventsIn(t, logPath)[0]; e.Repository != "" {
+ t.Fatalf("repository %q for a run that never resolved one", e.Repository)
+ }
+}
+
+func TestGitHookPostRewriteRecordsAnOverrun(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"normalize_notes": 3 * time.Second}, "normalize_notes")
+ root := gitCommandRepo(t)
+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "c")
+ sha := mustGit(t, root, "rev-parse", "HEAD")
+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:codex_cli/a\n\nbeacon:codex_cli/a", sha)
+ rootCmd.SetIn(strings.NewReader("0000000000000000000000000000000000000000 " + sha + "\n"))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ if _, err := runGit(t, "hook", "post-rewrite", "amend", "--cwd", root); err != nil {
+ t.Fatal(err)
+ }
+ // After runGit, which resets the flags a previous test may have left set.
+ hook := onlyBudgetEvent(t, gitRuntimeLogPath())
+ if hook.Name != "post-rewrite" || hook.Phase != "normalize_notes" || !hook.CutShort || hook.BudgetMS != 3000 || hook.ElapsedMS != 3000 {
+ t.Fatalf("overrun %+v, want post-rewrite cut short in normalize_notes", hook)
+ }
+}
+
+// The pre-push hook records running out of time in its notes push against its own budget, and the
+// push still never fails.
+func TestGitHookPrePushRecordsAnOverrunInThePush(t *testing.T) {
+ stubGitHookTime(t, map[string]time.Duration{"open_repository": 100 * time.Millisecond, "push_notes": 9900 * time.Millisecond}, "push_notes")
+ root, remote := gitCommandTeam(t)
+ sha := mustGit(t, root, "rev-parse", "HEAD")
+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:cursor/c1", sha)
+ var stderr bytes.Buffer
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {
+ t.Fatalf("pre-push must not fail: %v", err)
+ }
+ if !strings.HasPrefix(stderr.String(), "beacon: commit links were not shared with origin") {
+ t.Fatalf("stderr %q", stderr.String())
+ }
+ hook := onlyBudgetEvent(t, gitRuntimeLogPath())
+ if hook.Name != "pre-push" || hook.Phase != "push_notes" || !hook.CutShort || hook.BudgetMS != gitShareBudget.Milliseconds() || hook.ElapsedMS != 10000 || hook.PhaseElapsedMS != 9900 {
+ t.Fatalf("overrun %+v, want pre-push cut short in push_notes after 10000ms", hook)
+ }
+}
+
+// A pre-push that shares nothing and pushes in time records no overrun.
+func TestGitHookPrePushWithinBudgetRecordsNoOverrun(t *testing.T) {
+ stubGitHookTime(t, nil, "")
+ root, remote := gitCommandTeam(t)
+ if _, err := runGit(t, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {
+ t.Fatal(err)
+ }
+ if got := budgetEventsIn(t, gitRuntimeLogPath()); len(got) != 0 {
+ t.Fatalf("budget events %+v", got)
+ }
+}
+
+func appendBudgetEvent(t *testing.T, logPath, hook, repoRoot string, at time.Time, cutShort bool) {
+ t.Helper()
+ at = at.Truncate(time.Millisecond)
+ clock := &fakeHookClock{now: at.Add(-3200 * time.Millisecond)}
+ run := &gitlink.HookRun{Hook: hook, Budget: gitHookBudget, Now: clock.Now}
+ ctx := newManualDeadline(context.Background())
+ run.Start(ctx)
+ run.Phase("attribute")
+ clock.advance(3200 * time.Millisecond)
+ ctx.expire()
+ var err error
+ if cutShort {
+ err = context.DeadlineExceeded
+ }
+ run.Check(ctx, err)
+ event, _ := run.Event(repoRoot, "")
+ line, _ := json.Marshal(event)
+ if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ f, ferr := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
+ if ferr != nil {
+ t.Fatal(ferr)
+ }
+ defer f.Close()
+ if _, err := f.Write(append(line, '\n')); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestGitStatusCountsRecentOverruns(t *testing.T) {
+ root := gitCommandRepo(t)
+ top := hookRepoRoot(t, root)
+ out, err := runGit(t, "status", "--cwd", root)
+ if err != nil || !strings.Contains(out, "overruns none in the last 7 days\n") {
+ t.Fatalf("status without overruns: %v\n%s", err, out)
+ }
+ logPath := gitRuntimeLogPath()
+ now := time.Now()
+ appendBudgetEvent(t, logPath, "post-commit", top, now.Add(-8*24*time.Hour), true) // too old to count
+ appendBudgetEvent(t, logPath, "post-commit", top, now.Add(-2*time.Hour), true)
+ last := now.Add(-time.Hour)
+ appendBudgetEvent(t, logPath, "post-rewrite", top, last, false)
+ appendBudgetEvent(t, logPath, "post-commit", filepath.Join(t.TempDir(), "elsewhere"), now.Add(-time.Minute), true) // another repository
+
+ out, err = runGit(t, "status", "--cwd", root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := "overruns 2 hook run(s) ran out of time in the last 7 days, 1 cut short; last " +
+ schema.FormatTimestamp(last.Truncate(time.Millisecond)) + ": post-rewrite in attribute, 3.2s of 3s, finished late\n"
+ if !strings.Contains(out, want) {
+ t.Fatalf("status:\n%s\nwant line %q", out, want)
+ }
+ out, err = runGit(t, "status", "--cwd", root, "--json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var st struct {
+ BudgetOverruns gitlink.BudgetOverruns `json:"budget_overruns"`
+ }
+ if err := json.Unmarshal([]byte(out), &st); err != nil {
+ t.Fatalf("status json %v: %s", err, out)
+ }
+ if o := st.BudgetOverruns; o.Count != 2 || o.CutShort != 1 || o.Last == nil || o.Last.Name != "post-rewrite" || o.Last.Repository != top || o.Last.ElapsedMS != 3200 {
+ t.Fatalf("budget_overruns %+v (last %+v)", o, o.Last)
+ }
+}
+
+func TestDoctorReportsGitHookOverruns(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ now := hookClockEpoch.Add(24 * time.Hour)
+ if _, ok := gitHookBudgetCheck(logPath, now); ok {
+ t.Fatal("doctor reported git hook overruns on an empty log")
+ }
+ appendBudgetEvent(t, logPath, "post-rewrite", "/work/a", now.Add(-time.Hour), false)
+ check, ok := gitHookBudgetCheck(logPath, now)
+ if !ok || check.Status != diagnostics.StatusOK || check.Evidence != "git_hook_finished_late" || check.Action != "" {
+ t.Fatalf("finished late only: %+v (%v), want ok with no action", check, ok)
+ }
+ appendBudgetEvent(t, logPath, "post-commit", "/work/b", now.Add(-time.Minute), true)
+ check, ok = gitHookBudgetCheck(logPath, now)
+ if !ok || check.Name != "git_hook_budget" || check.Status != diagnostics.StatusWarn || check.Severity != diagnostics.SeverityLow ||
+ check.Evidence != "git_hook_cut_short" || check.Target != "/work/b" || !strings.Contains(check.Message, "2 hook run(s)") || !strings.Contains(check.Message, "1 cut short") ||
+ !strings.Contains(check.Action, "beacon git link") {
+ t.Fatalf("cut short: %+v (%v)", check, ok)
+ }
+ // --fix has nothing to repair, and says so rather than staying silent.
+ plan := planDoctorFixes(doctorResult{Checks: []diagnostics.Check{check}}, lifecycle.Status{})
+ if len(plan.Fixes) != 0 || len(plan.Skipped) != 1 || plan.Skipped[0].Action != "manual_fix" || plan.Skipped[0].Message != check.Action {
+ t.Fatalf("fix plan %+v", plan)
+ }
+ // Outside the window nothing counts.
+ if _, ok := gitHookBudgetCheck(logPath, now.Add(8*24*time.Hour)); ok {
+ t.Fatal("doctor counted overruns older than the window")
+ }
+}
diff --git a/cli/beacon/cmd/git_hooks.go b/cli/beacon/cmd/git_hooks.go
index b5c0b845..16350331 100644
--- a/cli/beacon/cmd/git_hooks.go
+++ b/cli/beacon/cmd/git_hooks.go
@@ -233,12 +233,14 @@ func runGitStatus(cmd *cobra.Command, _ []string) error {
if err != nil {
return err
}
+ overruns := gitlink.ScanBudgetOverruns(gitRuntimeLogPath(), repo.Root, time.Now().Add(-gitOverrunWindow))
out := cmd.OutOrStdout()
if gitOpts.jsonOutput {
return writeIndentedJSON(out, struct {
gitlink.Status
- Installed bool `json:"installed"`
- }{status, status.Installed()})
+ Installed bool `json:"installed"`
+ BudgetOverruns gitlink.BudgetOverruns `json:"budget_overruns"`
+ }{status, status.Installed(), overruns})
}
fmt.Fprintf(out, "repository %s\n", repo.Root)
fmt.Fprintf(out, "hooks %s\n", status.Hooks.Dir)
@@ -281,38 +283,66 @@ func runGitStatus(cmd *cobra.Command, _ []string) error {
sessions = "on: pushes share linked sessions to beacon.sh (" + vis + ")"
}
fmt.Fprintf(out, "sessions %s\n", sessions)
+ fmt.Fprintf(out, "overruns %s\n", describeGitOverruns(overruns))
return nil
}
+// describeGitOverruns is the status line for the hook runs in this repository that ran out of time
+// recently. A run cut short is a commit left unlinked (or a link event, note or share left
+// unrecorded), which nothing else on the terminal ever says.
+func describeGitOverruns(o gitlink.BudgetOverruns) string {
+ days := int(gitOverrunWindow / (24 * time.Hour))
+ if o.Last == nil {
+ return fmt.Sprintf("none in the last %d days", days)
+ }
+ return fmt.Sprintf("%d hook run(s) ran out of time in the last %d days, %d cut short; last %s: %s",
+ o.Count, days, o.CutShort, o.Last.Timestamp, o.Last.Describe())
+}
+
// runGitHookPostCommit is the post-commit hook. It never returns an error: git ignores a
// post-commit hook's exit status anyway, and a hook that printed a stack of errors on every commit
-// in a repository with no agent activity would be worse than one that stayed quiet.
+// in a repository with no agent activity would be worse than one that stayed quiet. A run that
+// runs out of its budget records one git.hook_budget_exceeded event, still silently.
func runGitHookPostCommit(cmd *cobra.Command, _ []string) error {
if os.Getenv(gitlink.DisableEnv) == "0" {
return nil
}
- ctx, cancel := context.WithTimeout(cmd.Context(), gitHookBudget)
+ run, ctx, cancel := startGitHook(cmd.Context(), "post-commit", gitHookBudget)
defer cancel()
- result, ran := gitPostCommit(ctx)
+ result, repoRoot, ran := gitPostCommit(ctx, run)
+ finishGitHook(ctx, run, repoRoot)
if gitOpts.jsonOutput && ran {
_ = writeIndentedJSON(cmd.OutOrStdout(), result)
}
return nil
}
-func gitPostCommit(ctx context.Context) (gitlink.Result, bool) {
+// gitPostCommit links HEAD and records the link events, marking each step on run. It returns the
+// repository's work tree for the budget event, empty when the repository was never resolved.
+func gitPostCommit(ctx context.Context, run *gitlink.HookRun) (gitlink.Result, string, bool) {
+ run.Phase("open_repository")
repo, err := gitRepo(ctx)
- if err != nil || gitlink.ReplayInProgress(ctx, repo) {
- return gitlink.Result{}, false
+ if err == nil && gitlink.ReplayInProgress(ctx, repo) {
+ return gitlink.Result{}, repo.Root, false
+ }
+ if err == nil {
+ // The replay check reads its answers through git and treats a failed read as "no replay",
+ // so a deadline that passed during it shows only on the context.
+ err = ctx.Err()
}
+ if run.Check(ctx, err); err != nil {
+ return gitlink.Result{}, repo.Root, false
+ }
+ run.Phase("attribute")
result, err := gitlink.Attribute(ctx, repo, gitlink.Options{LogPath: gitRuntimeLogPath(), ShareURL: gitShareURLLookup(gitRuntimeLogPath())})
- if err != nil {
- return gitlink.Result{}, false
+ if run.Check(ctx, err); err != nil {
+ return gitlink.Result{}, repo.Root, false
}
// The note is the link; the event is its echo in the session's timeline. A log the hook cannot
// write (a system-mode log this user may not append to) costs only the echo.
- _ = recordLinkEvents(ctx, repo, result)
- return result, true
+ run.Phase("record_link_event")
+ run.Check(ctx, recordLinkEvents(ctx, repo, result))
+ return result, repo.Root, true
}
// runGitHookPostRewrite reads git's `<old-sha> <new-sha> [<extra>]` lines and normalizes the note
@@ -321,15 +351,19 @@ func runGitHookPostRewrite(cmd *cobra.Command, _ []string) error {
if os.Getenv(gitlink.DisableEnv) == "0" {
return nil
}
- ctx, cancel := context.WithTimeout(cmd.Context(), gitHookBudget)
+ run, ctx, cancel := startGitHook(cmd.Context(), "post-rewrite", gitHookBudget)
defer cancel()
+ var repo gitlink.Repo
+ defer func() { finishGitHook(ctx, run, repo.Root) }()
+ run.Phase("open_repository")
repo, err := gitRepo(ctx)
- if err != nil {
+ if run.Check(ctx, err); err != nil {
return nil
}
// Normalizing reads the share URLs in notes; a self-hosted or staging Beacon's links must
// count as URLs here as they do everywhere else.
gitAllowShareHosts()
+ run.Phase("normalize_notes")
scanner := bufio.NewScanner(cmd.InOrStdin())
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
@@ -337,6 +371,7 @@ func runGitHookPostRewrite(cmd *cobra.Command, _ []string) error {
continue
}
if _, err := gitlink.NormalizeNote(ctx, repo.Git, fields[1]); err != nil && ctx.Err() != nil {
+ run.Check(ctx, err)
return nil
}
}
diff --git a/cli/beacon/cmd/git_share.go b/cli/beacon/cmd/git_share.go
index 797df820..f9ac40b8 100644
--- a/cli/beacon/cmd/git_share.go
+++ b/cli/beacon/cmd/git_share.go
@@ -118,15 +118,20 @@ func runGitNotesFetch(cmd *cobra.Command, args []string) error {
// runGitHookPrePush is the pre-push hook. It never fails the push: sharing links is a courtesy to
// teammates, and the person's code reaching the remote matters more. A failure is one line on
-// stderr, which git shows alongside its own output.
+// stderr, which git shows alongside its own output. A run that runs out of time, in the share phase
+// or the notes push, also records one git.hook_budget_exceeded event.
func runGitHookPrePush(cmd *cobra.Command, args []string) error {
if os.Getenv(gitlink.DisableEnv) == "0" {
return nil
}
- ctx, cancel := context.WithTimeout(cmd.Context(), gitShareBudget)
+ run, hookCtx, cancel := startGitHook(cmd.Context(), "pre-push", gitShareBudget)
defer cancel()
+ var repo gitlink.Repo
+ defer func() { finishGitHook(hookCtx, run, repo.Root) }()
+ ctx := hookCtx
+ run.Phase("open_repository")
repo, err := gitRepo(ctx)
- if err != nil {
+ if run.Check(ctx, err); err != nil {
return nil
}
// A hook has no terminal to ask for credentials on; git's own push has already authenticated,
@@ -149,7 +154,12 @@ func runGitHookPrePush(cmd *cobra.Command, args []string) error {
// notes), and the notes ref is then pushed with what is left of the hook's budget, never
// less than gitShareNotesReserve, so the links, with whatever URLs were recorded, still
// reach the remote in time.
- if _, err := gitShareSessionsOnPush(ctx, repo, args[0], stdin, visibility); err != nil {
+ run.Phase("share_sessions")
+ report, err := gitShareSessionsOnPush(ctx, repo, args[0], stdin, visibility)
+ if report.OutOfTime {
+ run.RanOut(err != nil)
+ }
+ if err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "beacon: linked sessions were not all shared: %s\n", gitlink.ErrorSummary(err))
}
pushCtx, cancelPush := gitShareAfterContext(ctx, 0, gitShareNotesReserve)
@@ -157,7 +167,9 @@ func runGitHookPrePush(cmd *cobra.Command, args []string) error {
ctx = pushCtx
}
}
+ run.Phase("push_notes")
if _, err := gitPushNotes(ctx, repo, args[0]); err != nil {
+ run.Check(ctx, err)
fmt.Fprintf(cmd.ErrOrStderr(), "beacon: commit links were not shared with %s: %s\n", args[0], gitlink.ErrorSummary(err))
}
return nil
diff --git a/cli/beacon/cmd/git_share_sessions.go b/cli/beacon/cmd/git_share_sessions.go
index 2415e344..198081d0 100644
--- a/cli/beacon/cmd/git_share_sessions.go
+++ b/cli/beacon/cmd/git_share_sessions.go
@@ -169,6 +169,9 @@ type gitPushShareReport struct {
Shared []string `json:"shared,omitempty"`
Noted int `json:"noted"`
Skipped string `json:"skipped,omitempty"`
+ // OutOfTime is true when the uploads or the note writes ran past their deadline (not when the
+ // hook was cancelled).
+ OutOfTime bool `json:"out_of_time,omitempty"`
}
// gitShareCollector receives what the share phase of a push finds and uploads, as it happens, so
@@ -256,6 +259,7 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
cancelUploads()
report.Shared = got.shared
report.Skipped = got.skipped
+ report.OutOfTime = timedOut && errors.Is(ctx.Err(), context.DeadlineExceeded)
shareErr := got.err
if timedOut && shareErr == nil && (got.notes == nil || len(got.shared) < got.subjects) {
shareErr = errors.New("ran out of time before every linked session was shared; the next push shares the rest")
@@ -270,6 +274,9 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
for sha := range got.notes {
changed, err := gitlink.UpdateNote(noteCtx, repo.Git, sha, func(note string) string { return gitlink.SetLinkURLs(note, got.urls) })
if err != nil {
+ if errors.Is(noteCtx.Err(), context.DeadlineExceeded) {
+ report.OutOfTime = true
+ }
if shareErr == nil {
shareErr = err
}
@@ -395,7 +402,8 @@ func gitShareFindAndUpload(ctx context.Context, c *gitShareCollector, repo gitli
// gitShareAfterContext is a fresh context for work after the share phase: it gets what is left of
// parent's deadline less keep (time a later step needs), or floor when that is less, so an upload
// that overran cannot starve it and a share phase that returned at once leaves it the full budget.
-// It does not inherit parent's cancellation, only the time.
+// It does not inherit parent's cancellation, only the time and parent's values (among them the
+// hook's git spawn counter).
func gitShareAfterContext(parent context.Context, keep, floor time.Duration) (context.Context, context.CancelFunc) {
budget := floor
if deadline, ok := parent.Deadline(); ok {
@@ -403,7 +411,7 @@ func gitShareAfterContext(parent context.Context, keep, floor time.Duration) (co
budget = remaining
}
}
- return context.WithTimeout(context.Background(), budget)
+ return context.WithTimeout(context.WithoutCancel(parent), budget)
}
// readHookStdin reads what git passes a pre-push hook on stdin, bounded.
diff --git a/cli/beacon/cmd/git_share_sessions_test.go b/cli/beacon/cmd/git_share_sessions_test.go
index 61829871..52d34c99 100644
--- a/cli/beacon/cmd/git_share_sessions_test.go
+++ b/cli/beacon/cmd/git_share_sessions_test.go
@@ -306,6 +306,9 @@ func TestGitShareOnPushWritesFinishedURLsWhenUploadsRunOutOfTime(t *testing.T) {
if report.Noted != 1 {
t.Fatalf("report %+v, want the note updated", report)
}
+ if report.OutOfTime {
+ t.Fatalf("report %+v: a cancelled hook is not one that ran out of time", report)
+ }
want := "beacon:claude_code/sess-fast https://beacon.sh/s/fast01\nbeacon:claude_code/sess-slow"
if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {
t.Fatalf("note %q, want %q", note, want)
@@ -441,6 +444,15 @@ func TestGitPrePushAbandonsAnUploadThatNeverReturns(t *testing.T) {
if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {
t.Fatalf("remote note %q: the notes ref was not pushed", note)
}
+ // The abandoned upload is recorded as the share phase running out of time, against the hook's
+ // production budget. The times are lower bounds only: the upload deadline cannot pass early.
+ hook := onlyBudgetEvent(t, gitRuntimeLogPath())
+ if hook.Name != "pre-push" || hook.Phase != "share_sessions" || !hook.CutShort || hook.BudgetMS != gitShareBudget.Milliseconds() {
+ t.Fatalf("overrun %+v, want pre-push cut short in share_sessions", hook)
+ }
+ if hook.PhaseElapsedMS < gitShareUploadBudget.Milliseconds() || hook.ElapsedMS < hook.PhaseElapsedMS || hook.GitSpawns < 1 {
+ t.Fatalf("overrun %+v, want the share phase to have run its %s upload budget", hook, gitShareUploadBudget)
+ }
}
// A share phase that returns at once leaves the notes push the rest of the hook's budget, not just
diff --git a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
index e7709d44..3c5acbf3 100644
--- a/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
+++ b/cli/beacon/internal/endpoint/asymptote/metadata_fields_test.go
@@ -79,6 +79,8 @@ var metadataOnlyKept = []string{
"user_agent.name", "user_agent.version",
"vcs.ref.head.revision", "vcs.ref.head.name", "vcs.ref.head.type",
"vcs.repository.url.full", "vcs.attribution.method",
+ // Beacon's own git hook timing record: the hook's name and the step it was in.
+ "vcs.hook.name", "vcs.hook.phase",
"gen_ai.agent.id", "gen_ai.agent.name", "gen_ai.agent.version",
"gen_ai.conversation.id",
"gen_ai.data_source.id",
diff --git a/cli/beacon/internal/endpoint/elastic/pack/component-template-mappings.json b/cli/beacon/internal/endpoint/elastic/pack/component-template-mappings.json
index 846dc3f6..792bfdf4 100644
--- a/cli/beacon/internal/endpoint/elastic/pack/component-template-mappings.json
+++ b/cli/beacon/internal/endpoint/elastic/pack/component-template-mappings.json
@@ -147,7 +147,8 @@
"properties": {
"ref": { "properties": { "head": { "properties": { "revision": { "type": "keyword" }, "name": { "type": "keyword" }, "type": { "type": "keyword" } } } } },
"repository": { "properties": { "url": { "properties": { "full": { "type": "keyword" } } } } },
- "attribution": { "properties": { "method": { "type": "keyword" }, "changed_files": { "type": "long" }, "matched_files": { "type": "long" } } }
+ "attribution": { "properties": { "method": { "type": "keyword" }, "changed_files": { "type": "long" }, "matched_files": { "type": "long" } } },
+ "hook": { "properties": { "name": { "type": "keyword" }, "phase": { "type": "keyword" }, "budget_ms": { "type": "long" }, "elapsed_ms": { "type": "long" }, "phase_elapsed_ms": { "type": "long" }, "git_spawns": { "type": "long" }, "cut_short": { "type": "boolean" } } }
}
},
"otel": {
diff --git a/cli/beacon/internal/endpoint/schema/event.go b/cli/beacon/internal/endpoint/schema/event.go
index 82a34cc5..da7c8484 100644
--- a/cli/beacon/internal/endpoint/schema/event.go
+++ b/cli/beacon/internal/endpoint/schema/event.go
@@ -98,6 +98,7 @@ type VCSRefHeadInfo = asymptoteobserve.VCSRefHeadInfo
type VCSRepositoryInfo = asymptoteobserve.VCSRepositoryInfo
type VCSRepositoryURLInfo = asymptoteobserve.VCSRepositoryURLInfo
type VCSAttributionInfo = asymptoteobserve.VCSAttributionInfo
+type VCSHookInfo = asymptoteobserve.VCSHookInfo
type PolicyInfo = asymptoteobserve.PolicyInfo
type PromptInfo = asymptoteobserve.PromptInfo
type SystemContextInfo = asymptoteobserve.SystemContextInfo
diff --git a/cli/beacon/internal/gitlink/budget.go b/cli/beacon/internal/gitlink/budget.go
new file mode 100644
index 00000000..8842f5ff
--- /dev/null
+++ b/cli/beacon/internal/gitlink/budget.go
@@ -0,0 +1,229 @@
+package gitlink
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "sync/atomic"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// BudgetAction is the event action recorded in the runtime log when one of Beacon's git hooks runs
+// out of its time budget. The hooks give up quietly when that happens (a post-commit hook that runs
+// out leaves the commit unlinked), so the event is the only record of it.
+const BudgetAction = "git.hook_budget_exceeded"
+
+type spawnCounterKey struct{}
+
+// countSpawn adds one to the git spawn counter ctx carries, when it carries one.
+func countSpawn(ctx context.Context) {
+ if counter, ok := ctx.Value(spawnCounterKey{}).(*atomic.Int64); ok {
+ counter.Add(1)
+ }
+}
+
+// HookRun measures one run of a git hook against its time budget: how long it took, which step it
+// was in when its time ran out, and how many git processes it started, which is what decides
+// whether the budget fits a slow machine.
+//
+// A hook calls Start once, Phase as each step begins and Check after each step, then reads Overrun.
+// Measuring costs a clock read per step and an atomic add per git process; it spawns nothing and
+// touches no file. Only the hook's own goroutine calls its methods; the spawn count is safe to add
+// to from any goroutine, so an abandoned upload in pre-push is still counted.
+type HookRun struct {
+ // Hook is the hook's name: post-commit, post-rewrite or pre-push.
+ Hook string
+ // Budget is the time the hook allows itself.
+ Budget time.Duration
+ // Now is the clock; nil means time.Now. Tests pin it.
+ Now func() time.Time
+ // OnPhase, when set, is called as each phase begins, after the phase's start is read. Tests use
+ // it to move the clock and end the hook's time in a chosen phase.
+ OnPhase func(phase string)
+
+ spawns atomic.Int64
+ start time.Time
+ phase string
+ phaseStart time.Time
+ ranOut string
+ ranOutAfter time.Duration
+ cutShort bool
+}
+
+func (r *HookRun) now() time.Time {
+ if r.Now != nil {
+ return r.Now()
+ }
+ return time.Now()
+}
+
+// Start begins the run and returns ctx carrying its git spawn counter: every git process started
+// with the returned context, or one derived from it, is counted.
+func (r *HookRun) Start(ctx context.Context) context.Context {
+ r.start = r.now()
+ return context.WithValue(ctx, spawnCounterKey{}, &r.spawns)
+}
+
+// Phase marks the start of the run's next step.
+func (r *HookRun) Phase(name string) {
+ r.phase, r.phaseStart = name, r.now()
+ if r.OnPhase != nil {
+ r.OnPhase(name)
+ }
+}
+
+// Check records that the current phase ran out of time when ctx's deadline has passed, and reports
+// whether it had. err is the step's own result: a step that failed once its deadline had passed was
+// cut short by it, and one that succeeded finished late. Cancellation that is not a deadline (an
+// interrupted git) is not a budget overrun and is not recorded.
+func (r *HookRun) Check(ctx context.Context, err error) bool {
+ if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ return false
+ }
+ r.RanOut(err != nil)
+ return true
+}
+
+// RanOut records that the current phase ran out of time; lost says whether that left the hook's
+// work undone. The first phase to run out is the one recorded, because the steps after it run on
+// what is left; lost accumulates over every call.
+func (r *HookRun) RanOut(lost bool) {
+ if r.ranOut == "" {
+ r.ranOut = r.phase
+ r.ranOutAfter = r.now().Sub(r.phaseStart)
+ }
+ r.cutShort = r.cutShort || lost
+}
+
+// Overrun returns what the run recorded, and false when it never ran out of time. Elapsed time and
+// the spawn count are read now, so they cover the whole run up to the call.
+func (r *HookRun) Overrun() (schema.VCSHookInfo, bool) {
+ if r.ranOut == "" {
+ return schema.VCSHookInfo{}, false
+ }
+ return schema.VCSHookInfo{
+ Name: r.Hook,
+ Phase: r.ranOut,
+ BudgetMS: r.Budget.Milliseconds(),
+ ElapsedMS: r.now().Sub(r.start).Milliseconds(),
+ PhaseElapsedMS: r.ranOutAfter.Milliseconds(),
+ GitSpawns: r.spawns.Load(),
+ CutShort: r.cutShort,
+ }, true
+}
+
+// Event returns the git.hook_budget_exceeded event for the run, and false when it never ran out of
+// time. repoRoot is the repository's work tree, empty when the hook ran out before resolving it.
+// The event is Beacon's own (harness beacon) and carries the hook's name, phase, timings and git
+// spawn count only: no path but the repository's, no command and no commit content.
+func (r *HookRun) Event(repoRoot, agentVersion string) (schema.Event, bool) {
+ hook, ok := r.Overrun()
+ if !ok {
+ return schema.Event{}, false
+ }
+ severity := schema.SeverityInfo
+ outcome := "it finished late"
+ if hook.CutShort {
+ severity = schema.SeverityLow
+ outcome = "its work was cut short"
+ }
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: BudgetAction,
+ Category: "system",
+ Severity: severity,
+ AgentVersion: agentVersion,
+ Harness: schema.HarnessInfo{Name: "beacon"},
+ Fidelity: asymptoteobserve.FidelityObserved,
+ Message: fmt.Sprintf("%s hook ran out of time in %s: %s of its %s budget, %d git process(es); %s",
+ hook.Name, hook.Phase, formatMS(hook.ElapsedMS), formatMS(hook.BudgetMS), hook.GitSpawns, outcome),
+ })
+ event.Timestamp = schema.FormatTimestamp(r.now())
+ event.Event.Kind = "beacon_system"
+ event.Repository = repoRoot
+ event.VCS = &schema.VCSInfo{Hook: &hook}
+ return event, true
+}
+
+// formatMS renders milliseconds as seconds for a person: 3200 is 3.2s.
+func formatMS(ms int64) string {
+ return (time.Duration(ms) * time.Millisecond).Round(100 * time.Millisecond).String()
+}
+
+// BudgetOverrun is one git.hook_budget_exceeded event read back from the runtime log.
+type BudgetOverrun struct {
+ Timestamp string `json:"timestamp"`
+ Repository string `json:"repository,omitempty"`
+ schema.VCSHookInfo
+}
+
+// BudgetOverruns counts the git hook runs that ran out of time since a point in time.
+type BudgetOverruns struct {
+ Since string `json:"since"`
+ Count int `json:"count"`
+ CutShort int `json:"cut_short"`
+ // Last is the most recent overrun, nil exactly when Count is 0.
+ Last *BudgetOverrun `json:"last,omitempty"`
+}
+
+// ScanBudgetOverruns reads the git.hook_budget_exceeded events recorded at or after since in the
+// runtime log at logPath and the rotated archives kept beside it, since a busy log rotates more
+// often than the window covers. repoRoot, when set, keeps only the events of that work tree. Only
+// lines that mention the action are decoded; a file that cannot be read counts nothing.
+func ScanBudgetOverruns(logPath, repoRoot string, since time.Time) BudgetOverruns {
+ summary := BudgetOverruns{Since: schema.FormatTimestamp(since)}
+ var lastAt time.Time
+ for _, path := range writer.RetainedLogPaths(logPath) {
+ scanBudgetOverrunFile(path, repoRoot, since, &summary, &lastAt)
+ }
+ return summary
+}
+
+func scanBudgetOverrunFile(path, repoRoot string, since time.Time, summary *BudgetOverruns, lastAt *time.Time) {
+ f, err := os.Open(path)
+ if err != nil {
+ return
+ }
+ defer f.Close()
+ marker := []byte(`"` + BudgetAction + `"`)
+ reader := bufio.NewReaderSize(f, 256*1024)
+ for {
+ line, err := reader.ReadBytes('\n')
+ if len(line) > 0 && bytes.Contains(line, marker) {
+ var event schema.Event
+ if json.Unmarshal(line, &event) == nil && event.Event.Action == BudgetAction && event.VCS != nil && event.VCS.Hook != nil &&
+ (repoRoot == "" || event.Repository == repoRoot) {
+ if at, perr := asymptoteobserve.ParseTimestamp(event.Timestamp); perr == nil && !at.Before(since) {
+ summary.Count++
+ if event.VCS.Hook.CutShort {
+ summary.CutShort++
+ }
+ if summary.Last == nil || !at.Before(*lastAt) {
+ *lastAt = at
+ summary.Last = &BudgetOverrun{Timestamp: event.Timestamp, Repository: event.Repository, VCSHookInfo: *event.VCS.Hook}
+ }
+ }
+ }
+ }
+ if err != nil {
+ return
+ }
+ }
+}
+
+// Describe is the overrun in a few words for a person: "post-commit in attribute, 3.2s of 3s,
+// cut short".
+func (o BudgetOverrun) Describe() string {
+ outcome := "finished late"
+ if o.CutShort {
+ outcome = "cut short"
+ }
+ return fmt.Sprintf("%s in %s, %s of %s, %s", o.Name, o.Phase, formatMS(o.ElapsedMS), formatMS(o.BudgetMS), outcome)
+}
diff --git a/cli/beacon/internal/gitlink/budget_test.go b/cli/beacon/internal/gitlink/budget_test.go
new file mode 100644
index 00000000..67cddb7b
--- /dev/null
+++ b/cli/beacon/internal/gitlink/budget_test.go
@@ -0,0 +1,291 @@
+package gitlink
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// testClock is a clock that moves only when a test moves it.
+type testClock struct{ now time.Time }
+
+func (c *testClock) Now() time.Time { return c.now }
+func (c *testClock) advance(d time.Duration) { c.now = c.now.Add(d) }
+
+var budgetEpoch = time.Date(2026, 10, 14, 9, 0, 0, 0, time.UTC)
+
+// expiredContext has a deadline that has already passed, so it reports DeadlineExceeded without
+// any wall-clock wait.
+func expiredContext(t *testing.T) context.Context {
+ t.Helper()
+ ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0))
+ t.Cleanup(cancel)
+ if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ t.Fatalf("context not expired: %v", ctx.Err())
+ }
+ return ctx
+}
+
+func TestHookRunUnderBudgetRecordsNothing(t *testing.T) {
+ clock := &testClock{now: budgetEpoch}
+ run := &HookRun{Hook: "post-commit", Budget: 3 * time.Second, Now: clock.Now}
+ ctx := run.Start(context.Background())
+ for _, phase := range []string{"open_repository", "attribute", "record_link_event"} {
+ run.Phase(phase)
+ clock.advance(900 * time.Millisecond)
+ // A step that failed for its own reasons is not a budget overrun.
+ if run.Check(ctx, errors.New("not a repository")) {
+ t.Fatalf("%s: a live context was reported as out of time", phase)
+ }
+ }
+ if hook, ok := run.Overrun(); ok {
+ t.Fatalf("a run within its budget recorded %+v", hook)
+ }
+ if _, ok := run.Event("/work/repo", "1.0.0"); ok {
+ t.Fatal("a run within its budget produced an event")
+ }
+}
+
+// The phase that ran out, the time the whole run took and the time spent in that phase all come
+// from the injected clock, so they are exact.
+func TestHookRunRecordsTheOverrunPhaseAndTimes(t *testing.T) {
+ clock := &testClock{now: budgetEpoch}
+ run := &HookRun{Hook: "post-commit", Budget: 3 * time.Second, Now: clock.Now}
+ live := run.Start(context.Background())
+ run.Phase("open_repository")
+ clock.advance(40 * time.Millisecond)
+ run.Check(live, nil)
+ run.Phase("attribute")
+ clock.advance(3250 * time.Millisecond)
+ if !run.Check(expiredContext(t), context.DeadlineExceeded) {
+ t.Fatal("an expired deadline was not reported")
+ }
+ clock.advance(10 * time.Millisecond) // the hook winds down before it records the run
+ hook, ok := run.Overrun()
+ if !ok {
+ t.Fatal("the overrun was not recorded")
+ }
+ want := schema.VCSHookInfo{Name: "post-commit", Phase: "attribute", BudgetMS: 3000, ElapsedMS: 3300, PhaseElapsedMS: 3250, CutShort: true}
+ if hook != want {
+ t.Fatalf("overrun %+v, want %+v", hook, want)
+ }
+}
+
+// A step that succeeded although its deadline passed finished late: the run is recorded, but not
+// as cut short.
+func TestHookRunThatFinishedLateIsNotCutShort(t *testing.T) {
+ clock := &testClock{now: budgetEpoch}
+ run := &HookRun{Hook: "post-rewrite", Budget: 3 * time.Second, Now: clock.Now}
+ run.Start(context.Background())
+ run.Phase("normalize_notes")
+ clock.advance(3100 * time.Millisecond)
+ run.Check(expiredContext(t), nil)
+ hook, ok := run.Overrun()
+ if !ok || hook.CutShort || hook.Phase != "normalize_notes" || hook.ElapsedMS != 3100 {
+ t.Fatalf("overrun %+v (recorded %v), want normalize_notes finished late after 3100ms", hook, ok)
+ }
+}
+
+// The first phase to run out is the one recorded, because the later ones only ran on what was
+// left; any of them losing work marks the run cut short.
+func TestHookRunKeepsTheFirstPhaseAndAccumulatesLoss(t *testing.T) {
+ clock := &testClock{now: budgetEpoch}
+ run := &HookRun{Hook: "pre-push", Budget: 10 * time.Second, Now: clock.Now}
+ run.Start(context.Background())
+ run.Phase("share_sessions")
+ clock.advance(6 * time.Second)
+ run.RanOut(false)
+ run.Phase("push_notes")
+ clock.advance(3 * time.Second)
+ run.Check(expiredContext(t), errors.New("push failed"))
+ hook, _ := run.Overrun()
+ if hook.Phase != "share_sessions" || hook.PhaseElapsedMS != 6000 || hook.ElapsedMS != 9000 || !hook.CutShort {
+ t.Fatalf("overrun %+v, want share_sessions after 6000ms of a 9000ms run, cut short", hook)
+ }
+}
+
+// An interrupted hook (cancelled, not out of time) is not a budget overrun.
+func TestHookRunIgnoresCancellation(t *testing.T) {
+ run := &HookRun{Hook: "post-commit", Budget: 3 * time.Second}
+ ctx, cancel := context.WithCancel(run.Start(context.Background()))
+ cancel()
+ run.Phase("attribute")
+ if run.Check(ctx, ctx.Err()) {
+ t.Fatal("cancellation was reported as running out of time")
+ }
+ if _, ok := run.Overrun(); ok {
+ t.Fatal("cancellation was recorded as an overrun")
+ }
+}
+
+// Every git process started under the run's context is counted, through derived contexts and
+// detached ones too; a git that never starts, because its context has already ended, is not.
+func TestHookRunCountsGitSpawns(t *testing.T) {
+ r := newTestRepo(t)
+ g := r.gitClient()
+ run := &HookRun{Hook: "post-commit", Budget: 3 * time.Second}
+ ctx := run.Start(context.Background())
+ derived, cancel := context.WithTimeout(ctx, time.Minute)
+ defer cancel()
+ detached, cancelDetached := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
+ defer cancelDetached()
+ for _, c := range []context.Context{ctx, derived, detached} {
+ if _, err := g.Run(c, nil, "rev-parse", "--git-dir"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // A git that fails still started and counts.
+ if _, err := g.Run(ctx, nil, "rev-parse", "--verify", "--quiet", "refs/heads/missing"); err == nil {
+ t.Fatal("rev-parse of a missing ref succeeded")
+ }
+ ended, cancelEnded := context.WithCancel(ctx)
+ cancelEnded()
+ if _, err := g.Run(ended, nil, "rev-parse", "--git-dir"); err == nil {
+ t.Fatal("git ran on an ended context")
+ }
+ // A git outside the run is not counted.
+ if _, err := g.Run(context.Background(), nil, "rev-parse", "--git-dir"); err != nil {
+ t.Fatal(err)
+ }
+ run.Phase("attribute")
+ run.RanOut(true)
+ hook, _ := run.Overrun()
+ if hook.GitSpawns != 4 {
+ t.Fatalf("counted %d git spawns, want 4", hook.GitSpawns)
+ }
+}
+
+func TestHookRunEvent(t *testing.T) {
+ clock := &testClock{now: budgetEpoch}
+ run := &HookRun{Hook: "post-commit", Budget: 3 * time.Second, Now: clock.Now}
+ run.Start(context.Background())
+ run.Phase("attribute")
+ clock.advance(3200 * time.Millisecond)
+ run.Check(expiredContext(t), context.DeadlineExceeded)
+ event, ok := run.Event("/work/repo", "1.2.3")
+ if !ok {
+ t.Fatal("no event for an overrun")
+ }
+ if err := event.Validate(); err != nil {
+ t.Fatalf("event does not validate: %v", err)
+ }
+ if event.Event.Action != BudgetAction || event.Event.Category != "system" || event.Event.Kind != "beacon_system" ||
+ event.Event.Fidelity != asymptoteobserve.FidelityObserved || event.Harness.Name != "beacon" ||
+ event.Severity != schema.SeverityLow || event.Repository != "/work/repo" || event.Endpoint.AgentVersion != "1.2.3" {
+ t.Fatalf("event %+v", event)
+ }
+ if event.Timestamp != schema.FormatTimestamp(budgetEpoch.Add(3200*time.Millisecond)) {
+ t.Fatalf("timestamp %s does not come from the run's clock", event.Timestamp)
+ }
+ if event.VCS == nil || event.VCS.Hook == nil || event.VCS.Hook.Phase != "attribute" || event.VCS.Hook.ElapsedMS != 3200 {
+ t.Fatalf("vcs %+v", event.VCS)
+ }
+ if want := "post-commit hook ran out of time in attribute: 3.2s of its 3s budget, 0 git process(es); its work was cut short"; event.Message != want {
+ t.Fatalf("message %q, want %q", event.Message, want)
+ }
+ // Only the hook's own record: no session, command, file or content fields.
+ if event.Session != nil || event.Command != nil || event.File != nil || event.Tool != nil || event.Content != nil || event.Raw != nil {
+ t.Fatalf("event carries more than the hook's record: %+v", event)
+ }
+ line, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{`"hook":{"name":"post-commit","phase":"attribute","budget_ms":3000,"elapsed_ms":3200,"phase_elapsed_ms":3200,"cut_short":true}`} {
+ if !strings.Contains(string(line), want) {
+ t.Fatalf("event JSON %s lacks %s", line, want)
+ }
+ }
+
+ late := &HookRun{Hook: "post-rewrite", Budget: 3 * time.Second, Now: clock.Now}
+ late.Start(context.Background())
+ late.Phase("normalize_notes")
+ late.Check(expiredContext(t), nil)
+ if event, _ := late.Event("", ""); event.Severity != schema.SeverityInfo || !strings.HasSuffix(event.Message, "it finished late") {
+ t.Fatalf("finished-late event severity %s message %q", event.Severity, event.Message)
+ }
+}
+
+func writeBudgetEvent(t *testing.T, logPath, hook, repoRoot string, at time.Time, cutShort bool) {
+ t.Helper()
+ clock := &testClock{now: at.Add(-3200 * time.Millisecond)}
+ run := &HookRun{Hook: hook, Budget: 3 * time.Second, Now: clock.Now}
+ run.Start(context.Background())
+ run.Phase("attribute")
+ clock.advance(3200 * time.Millisecond)
+ var err error
+ if cutShort {
+ err = context.DeadlineExceeded
+ }
+ run.Check(expiredContext(t), err)
+ event, _ := run.Event(repoRoot, "")
+ line, _ := json.Marshal(event)
+ f, ferr := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
+ if ferr != nil {
+ t.Fatal(ferr)
+ }
+ defer f.Close()
+ if _, err := f.Write(append(line, '\n')); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestScanBudgetOverruns(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if got := ScanBudgetOverruns(logPath, "", budgetEpoch); got.Count != 0 || got.Last != nil {
+ t.Fatalf("a missing log counted %+v", got)
+ }
+ since := budgetEpoch.Add(-7 * 24 * time.Hour)
+ writeBudgetEvent(t, logPath, "post-commit", "/work/a", since.Add(-time.Minute), true) // too old
+ writeBudgetEvent(t, logPath, "post-commit", "/work/a", budgetEpoch.Add(-2*time.Hour), true)
+ writeBudgetEvent(t, logPath, "pre-push", "/work/b", budgetEpoch.Add(-time.Hour), false)
+ writeBudgetEvent(t, logPath, "post-rewrite", "/work/a", budgetEpoch.Add(-3*time.Hour), false)
+ // Lines that only mention the action, and a link event, count for nothing.
+ f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ link := schema.NewEvent(schema.NewEventOptions{Action: LinkAction, Harness: schema.HarnessInfo{Name: "cursor"}, Message: BudgetAction})
+ linkLine, _ := json.Marshal(link)
+ _, _ = f.Write([]byte(`not json "` + BudgetAction + `"` + "\n" + string(linkLine) + "\n"))
+ f.Close()
+
+ all := ScanBudgetOverruns(logPath, "", since)
+ if all.Count != 3 || all.CutShort != 1 || all.Last == nil || all.Last.Name != "pre-push" || all.Last.Repository != "/work/b" {
+ t.Fatalf("all repositories: %+v (last %+v)", all, all.Last)
+ }
+ if all.Since != schema.FormatTimestamp(since) {
+ t.Fatalf("since %q", all.Since)
+ }
+ a := ScanBudgetOverruns(logPath, "/work/a", since)
+ if a.Count != 2 || a.CutShort != 1 || a.Last == nil || a.Last.Name != "post-commit" || a.Last.Phase != "attribute" || !a.Last.CutShort {
+ t.Fatalf("repository a: %+v (last %+v)", a, a.Last)
+ }
+ if want := "post-commit in attribute, 3.2s of 3s, cut short"; a.Last.Describe() != want {
+ t.Fatalf("describe %q, want %q", a.Last.Describe(), want)
+ }
+ if got := ScanBudgetOverruns(logPath, "/work/none", since); got.Count != 0 || got.Last != nil {
+ t.Fatalf("an unrelated repository counted %+v", got)
+ }
+}
+
+// A busy runtime log rotates within the window, so an overrun in a rotated archive still counts.
+func TestScanBudgetOverrunsReadsRotatedArchives(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ since := budgetEpoch.Add(-7 * 24 * time.Hour)
+ writeBudgetEvent(t, logPath+".2", "post-commit", "/work/a", budgetEpoch.Add(-3*24*time.Hour), true)
+ writeBudgetEvent(t, logPath, "pre-push", "/work/a", budgetEpoch.Add(-time.Hour), false)
+
+ got := ScanBudgetOverruns(logPath, "/work/a", since)
+ if got.Count != 2 || got.CutShort != 1 || got.Last == nil || got.Last.Name != "pre-push" {
+ t.Fatalf("overruns across the live log and an archive: %+v (last %+v)", got, got.Last)
+ }
+}
diff --git a/cli/beacon/internal/gitlink/git.go b/cli/beacon/internal/gitlink/git.go
index 144ce18a..5c2357d8 100644
--- a/cli/beacon/internal/gitlink/git.go
+++ b/cli/beacon/internal/gitlink/git.go
@@ -70,7 +70,12 @@ func (g Git) run(ctx context.Context, stdin []byte, args ...string) ([]byte, err
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
- if err := cmd.Run(); err != nil {
+ err := cmd.Start()
+ if err == nil {
+ countSpawn(ctx)
+ err = cmd.Wait()
+ }
+ if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 1afe3f48..25c3bed0 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -19,6 +19,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
- **Cline plugin and sessions follow `CLINE_DIR`** · `beacon endpoint hooks install --harness cline`, `beacon endpoint discover`, inventory, `beacon endpoint cline status` and `sync`, and the session backfill now use `$CLINE_DIR` when `CLINE_DIR` is set, as Cline does. They previously always used `~/.cline`, so with `CLINE_DIR` set, the Beacon plugin went where Cline never loads it, live capture silently recorded nothing, and session sync found no sessions. A per-user install or repair also writes the resolved `CLINE_DIR` into the scheduled inventory job, as it does `CODEX_HOME`.
- **Gemini CLI settings follow `GEMINI_CLI_HOME`** · `beacon endpoint install`, `beacon endpoint discover`, inventory and `beacon mcp connect` now read and write `$GEMINI_CLI_HOME/.gemini/settings.json` when `GEMINI_CLI_HOME` is set, as Gemini CLI does. They previously always used `~/.gemini/settings.json`, so with `GEMINI_CLI_HOME` set, Gemini never saw Beacon's OTLP settings and live capture silently recorded nothing. A per-user install or repair also writes the resolved `GEMINI_CLI_HOME` into the scheduled inventory job, as it does `CODEX_HOME`.
- **Copilot CLI sessions follow `COPILOT_HOME`** · `beacon endpoint copilot status` and `sync`, the session backfill, `beacon handoff` and `beacon endpoint discover` now use `$COPILOT_HOME` when `COPILOT_HOME` is set, as Copilot CLI does. They previously always used `~/.copilot`, so with `COPILOT_HOME` set, session sync found no sessions. `--copilot-dir` still overrides.
+- **Git hooks record when they run out of time** · The post-commit, post-rewrite and pre-push hooks give up quietly when their three- or ten-second budget runs out, and a post-commit hook that gives up leaves the commit unlinked. Each run that runs out of time now writes one `git.hook_budget_exceeded` event to the runtime log, naming the hook, the step it was in, the budget, the elapsed time, how many git processes it started and whether its work was cut short (`vcs.hook.*`). `beacon git status` shows an `overruns` line for the repository's last seven days, and `beacon endpoint doctor` adds a `git_hook_budget` check, a warning when a run was cut short. The budgets themselves are unchanged.
### v1.3.40 · October 14, 2026
diff --git a/docs/cli/endpoint-doctor.mdx b/docs/cli/endpoint-doctor.mdx
index d830b7de..04b925da 100644
--- a/docs/cli/endpoint-doctor.mdx
+++ b/docs/cli/endpoint-doctor.mdx
@@ -27,6 +27,7 @@ Doctor verifies:
- Service definition: launchd plist on macOS, systemd unit on Linux
- Configured harness telemetry and recent observed events
- Whether DeepSeek Harness hooks are actually recording live events (`dsh_hook_capture`)
+- Whether Beacon's git hooks ran out of time recently (`git_hook_budget`)
- Whether a real user's agent runtime points at the collector (system mode only)
The runtime log itself can be missing before the first event is written. In that case, doctor reports a warning instead of a hard failure.
@@ -62,6 +63,18 @@ Doctor cannot reproduce the sandbox, because running the hook command from docto
This is a warning, not a failure. The sandbox mode is the operator's choice in `dsh`, and Beacon does not change it. `--fix` lists the check as a manual skip. See [Live hooks and the DeepSeek Harness sandbox](/runtimes/deepseek-harness#live-hooks-and-the-deepseek-harness-sandbox).
+### `git_hook_budget`
+
+This check appears only when one of Beacon's [git hooks](/cli/git#hook-runs-that-run-out-of-time) ran out of time in the last seven days, in any repository. It counts the `git.hook_budget_exceeded` events in the runtime log and names the most recent.
+
+```
+git_hook_budget: warn target=/work/my-repo (2 hook run(s) ran out of time in the last 7 days, 1 cut short;
+ last 2026-10-14T09:00:03Z: post-commit in attribute, 3.3s of 3s, cut short)
+ action="run `beacon git status` in the repository to see its overruns, and `beacon git link <commit>` to link a commit the hook left unlinked"
+```
+
+It warns when a run was cut short, because a commit may have been left unlinked; runs that only finished late are reported as ok. The budgets are fixed, so `--fix` lists the check as a manual skip.
+
## Fix mode
`beacon endpoint doctor --fix` plans and applies safe remediations for supported findings. It can create a missing runtime log, and recreate managed collector configuration and the service definition (a launchd plist or a systemd unit) when the endpoint configuration is valid. On a Windows system install it also resets the log directory ACL, from an elevated shell, when interactive users cannot append to the runtime log or when they hold more than append (an older install's Modify grant): the same ACL a fresh install applies, described in [Windows](/platforms/windows#what-the-install-does).
diff --git a/docs/cli/git.mdx b/docs/cli/git.mdx
index 578bc51f..8b6a238a 100644
--- a/docs/cli/git.mdx
+++ b/docs/cli/git.mdx
@@ -48,7 +48,7 @@ created /work/my-repo/.git/hooks/post-rewrite (calls beacon-post-rewrite)
set notes.rewriteRef = refs/notes/beacon
```
-- **post-commit** links the new commit, exactly as `beacon git link` would. It reads the local runtime log and writes a git note, typically in tens of milliseconds, and gives up after three seconds rather than hold a commit. It never prints, never touches the network, and never fails a commit.
+- **post-commit** links the new commit, exactly as `beacon git link` would. It reads the local runtime log and writes a git note, typically in tens of milliseconds, and gives up after three seconds rather than hold a commit, recording in the runtime log that it did ([see below](#hook-runs-that-run-out-of-time)). It never prints, never touches the network, and never fails a commit.
- **post-rewrite** runs after `git commit --amend` and `git rebase` and tidies the note on each rewritten commit, folding the note git copied from the old commit into the one the post-commit hook just wrote.
- **`notes.rewriteRef`** makes git copy a commit's links to the commit that replaces it when you amend or rebase.
@@ -86,7 +86,7 @@ Pass `--hooks-path` to install into that directory anyway.
## `beacon git status`
-Shows whether each hook is installed, reports an install that is broken (a hook calling a script that is gone, or the reverse), and says whether `notes.rewriteRef` is set. `--json` prints the same as JSON, with a top-level `installed` field.
+Shows whether each hook is installed, reports an install that is broken (a hook calling a script that is gone, or the reverse), and says whether `notes.rewriteRef` is set. The `overruns` line counts this repository's hook runs that [ran out of time](#hook-runs-that-run-out-of-time) in the last seven days, how many of them were cut short, and the most recent. `--json` prints the same as JSON, with a top-level `installed` field and the counts under `budget_overruns`.
## Sharing links with a team
@@ -219,6 +219,39 @@ match: >
e.vcs.attribution.matched_files == e.vcs.attribution.changed_files
```
+## Hook runs that run out of time
+
+The hooks hold up a command a person is waiting on, so each gives up when its budget runs out: three seconds for post-commit and post-rewrite, ten for pre-push. Giving up is silent on the terminal, and a post-commit hook that gives up leaves the commit unlinked. So each run that runs out of time writes one `git.hook_budget_exceeded` event to the runtime log.
+
+```json title="Example event (abridged)"
+{
+ "event": { "action": "git.hook_budget_exceeded", "category": "system", "kind": "beacon_system", "fidelity": "observed" },
+ "severity": "low",
+ "harness": { "name": "beacon" },
+ "repository": "/work/my-repo",
+ "vcs": {
+ "hook": {
+ "name": "post-commit",
+ "phase": "attribute",
+ "budget_ms": 3000,
+ "elapsed_ms": 3290,
+ "phase_elapsed_ms": 3250,
+ "git_spawns": 14,
+ "cut_short": true
+ }
+ },
+ "message": "post-commit hook ran out of time in attribute: 3.3s of its 3s budget, 14 git process(es); its work was cut short"
+}
+```
+
+- `vcs.hook.phase` is the step the hook was in when its time ran out. Post-commit runs `open_repository`, `attribute` (reading the runtime log and writing the note) and `record_link_event`; post-rewrite runs `open_repository` and `normalize_notes`; pre-push runs `open_repository`, `share_sessions` (with `--share-sessions`) and `push_notes`.
+- `vcs.hook.elapsed_ms` is the whole run and `vcs.hook.phase_elapsed_ms` the part of it spent in that phase, so a slow earlier step shows as the difference. Pre-push holds its share phase to six of its ten seconds, so a share phase that runs out records an elapsed time under the budget.
+- `vcs.hook.git_spawns` is how many git processes the run started. Each costs a few milliseconds on macOS and Linux, and can cost far more on a Windows machine that scans every new process.
+- `vcs.hook.cut_short` is true when running out of time left work undone: a commit left unlinked, a link event, note or share URL left unrecorded, or the notes ref left unpushed. It is false for a run whose last step finished after the deadline, which is recorded as `info` rather than `low`.
+- `repository` is empty when the hook ran out before it could resolve the repository.
+
+`beacon git status` counts these events for the repository, and [`beacon endpoint doctor`](/cli/endpoint-doctor#git_hook_budget) for every repository. A commit left unlinked can be linked with `beacon git link <commit>`.
+
## Note format
Links live under `refs/notes/beacon`, one per line:
diff --git a/docs/telemetry-schema/fields.mdx b/docs/telemetry-schema/fields.mdx
index 54a41248..4d5cf596 100644
--- a/docs/telemetry-schema/fields.mdx
+++ b/docs/telemetry-schema/fields.mdx
@@ -37,7 +37,7 @@ Beacon models each event as an action plus a set of typed entities. The [`event`
| `destination` | Output or validation destination state | `type`, `mode`, `status` |
| `health` | Endpoint or component health state | `component`, `status`, `reason` |
| `user_agent` | Browser that produced a browser chat event, as the browser names itself | `name`, `version` |
-| `vcs` | On a `session.commit_linked` event, the commit a session was [linked to](/cli/git), in the OpenTelemetry VCS shape | `ref.head.revision`, `ref.head.name`, `ref.head.type`, `repository.url.full`, `attribution.method`, `attribution.changed_files`, `attribution.matched_files` |
+| `vcs` | On a `session.commit_linked` event, the commit a session was [linked to](/cli/git), in the OpenTelemetry VCS shape. On a `git.hook_budget_exceeded` event, the [git hook run that ran out of time](/cli/git#hook-runs-that-run-out-of-time) | `ref.head.revision`, `ref.head.name`, `ref.head.type`, `repository.url.full`, `attribution.method`, `attribution.changed_files`, `attribution.matched_files`, `hook.name`, `hook.phase`, `hook.budget_ms`, `hook.elapsed_ms`, `hook.phase_elapsed_ms`, `hook.git_spawns`, `hook.cut_short` |
Top-level `sequence`, `model`, `repository`, `branch`, `message`, `raw`, and `field_truncated` fields add shared context that can apply across multiple entities. For example, a command event can include both `tool` and `command`; a file edit can include `file`, `session`, `repository`, and `branch`; a CI event can include `origin` and `run`; and a GenAI tool call can include both `tool` and nested `gen_ai.tool` metadata.
diff --git a/pkg/asymptoteobserve/event.go b/pkg/asymptoteobserve/event.go
index fdfddac8..4f49c0cb 100644
--- a/pkg/asymptoteobserve/event.go
+++ b/pkg/asymptoteobserve/event.go
@@ -570,12 +570,15 @@ type UserAgentInfo struct {
// VCSInfo is version-control context in the OpenTelemetry VCS semantic convention shape
// (vcs.ref.head.revision, vcs.ref.head.name, vcs.ref.head.type, vcs.repository.url.full).
// Attribution is Beacon's own and has no semconv equivalent: on a session.commit_linked event it
-// records how the commit was matched to the session. Everything here is metadata -- identifiers and
-// counts, never file contents or commit messages -- so it survives metadata-only retention.
+// records how the commit was matched to the session. Hook is Beacon's own too: on a
+// git.hook_budget_exceeded event it records a git hook run that ran out of time. Everything here is
+// metadata -- identifiers, names and counts, never file contents or commit messages -- so it
+// survives metadata-only retention.
type VCSInfo struct {
Ref *VCSRefInfo `json:"ref,omitempty"`
Repository *VCSRepositoryInfo `json:"repository,omitempty"`
Attribution *VCSAttributionInfo `json:"attribution,omitempty"`
+ Hook *VCSHookInfo `json:"hook,omitempty"`
}
type VCSRefInfo struct {
@@ -609,6 +612,22 @@ type VCSAttributionInfo struct {
MatchedFiles int `json:"matched_files,omitempty"`
}
+// VCSHookInfo is one run of a Beacon git hook that ran past its time budget. Name is the hook
+// (post-commit, post-rewrite, pre-push) and Phase the step it was in when its time ran out.
+// ElapsedMS is the whole run, PhaseElapsedMS the part of it spent in Phase, and GitSpawns how many
+// git processes the run started. CutShort is true when running out of time left the hook's work
+// undone (for post-commit, a commit left unlinked or a link event unrecorded); false means the
+// work finished, late.
+type VCSHookInfo struct {
+ Name string `json:"name,omitempty"`
+ Phase string `json:"phase,omitempty"`
+ BudgetMS int64 `json:"budget_ms,omitempty"`
+ ElapsedMS int64 `json:"elapsed_ms,omitempty"`
+ PhaseElapsedMS int64 `json:"phase_elapsed_ms,omitempty"`
+ GitSpawns int64 `json:"git_spawns,omitempty"`
+ CutShort bool `json:"cut_short,omitempty"`
+}
+
type HealthInfo struct {
Component string `json:"component,omitempty"`
Status string `json:"status,omitempty"`
diff --git a/spec/threat-rules/FIELDS.md b/spec/threat-rules/FIELDS.md
index 9eb912f1..7d40464b 100644
--- a/spec/threat-rules/FIELDS.md
+++ b/spec/threat-rules/FIELDS.md
@@ -162,6 +162,13 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.
| `e.vcs.attribution.changed_files` | int |
| `e.vcs.attribution.matched_files` | int |
| `e.vcs.attribution.method` | string |
+| `e.vcs.hook.budget_ms` | int |
+| `e.vcs.hook.cut_short` | bool |
+| `e.vcs.hook.elapsed_ms` | int |
+| `e.vcs.hook.git_spawns` | int |
+| `e.vcs.hook.name` | string |
+| `e.vcs.hook.phase` | string |
+| `e.vcs.hook.phase_elapsed_ms` | int |
| `e.vcs.ref.head.name` | string |
| `e.vcs.ref.head.revision` | string |
| `e.vcs.ref.head.type` | string |