Skip to content

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

Hold push-time sharing to the clock

Clauded868f97bbff7
diff --git a/CLAUDE.md b/CLAUDE.md
index 4f5449a9..a6612832 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -70,7 +70,7 @@ Supported runtime surfaces today:
- 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.
- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background, except the opted-in pre-push sharing below. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own (and an off marker wins over the user's entry for the same directory; the closest directory with an entry or marker decides) but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.
-- Commit-to-session links via `beacon git setup|status|remove|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 (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). 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. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, inside the 10 s budget less 3 s kept for the notes push, silent without credentials, never failing the push) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them.
+- Commit-to-session links via `beacon git setup|status|remove|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 (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). 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. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes on a fresh 1 s and pushes the notes ref on a fresh 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them.
- Beacon Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by an unattended install; the onboarding wizard runs it only after the person chose Beacon Cloud and left "Beacon Cloud MCP" selected (that screen is the confirmation), and otherwise the install only suggests it. It is refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.
- 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`.
diff --git a/cli/beacon/cmd/git_share.go b/cli/beacon/cmd/git_share.go
index dbd736e6..ae0a99a9 100644
--- a/cli/beacon/cmd/git_share.go
+++ b/cli/beacon/cmd/git_share.go
@@ -142,12 +142,15 @@ func runGitHookPrePush(cmd *cobra.Command, args []string) error {
fmt.Fprintln(cmd.ErrOrStderr(), "beacon: sessions are shared on push only through the hook `beacon git setup` installs; this push shares commit links only")
}
if stdin != "" {
- // Sharing sessions splits the budget itself (uploads, then writing their URLs into the
- // notes) and leaves gitShareNotesReserve for pushing the notes ref, so the links, with
- // whatever URLs it recorded, still reach the remote.
+ // Sharing sessions is held to the clock (uploads, then writing their URLs into the
+ // notes), and the notes ref is then pushed on a fresh 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 {
fmt.Fprintf(cmd.ErrOrStderr(), "beacon: linked sessions were not all shared: %s\n", gitlink.ErrorSummary(err))
}
+ pushCtx, cancelPush := context.WithTimeout(context.Background(), gitShareNotesReserve)
+ defer cancelPush()
+ ctx = pushCtx
}
}
if _, err := gitlink.PushNotes(ctx, repo, args[0]); err != nil {
diff --git a/cli/beacon/cmd/git_share_sessions.go b/cli/beacon/cmd/git_share_sessions.go
index 353481f3..96615647 100644
--- a/cli/beacon/cmd/git_share_sessions.go
+++ b/cli/beacon/cmd/git_share_sessions.go
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"strings"
+ "sync"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
@@ -170,21 +171,122 @@ type gitPushShareReport struct {
Skipped string `json:"skipped,omitempty"`
}
+// gitShareCollector receives what the share phase of a push finds and uploads, as it happens, so
+// the hook can take whatever is there when the upload deadline passes and move on. Once closed it
+// ignores further deliveries: an upload the hook abandoned can no longer reach the notes.
+type gitShareCollector struct {
+ mu sync.Mutex
+ closed bool
+ notes map[string]string // commit -> note, read before anything is uploaded
+ urls map[string]string // link key -> share URL
+ shared []string
+ subjects int
+ skipped string
+ err error
+}
+
+func (c *gitShareCollector) update(f func()) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if !c.closed {
+ f()
+ }
+}
+
+func (c *gitShareCollector) fail(err error) {
+ c.update(func() {
+ if c.err == nil {
+ c.err = err
+ }
+ })
+}
+
+// close stops deliveries and returns what was collected.
+func (c *gitShareCollector) close() gitShareCollector {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.closed = true
+ urls := make(map[string]string, len(c.urls))
+ for k, v := range c.urls {
+ urls[k] = v
+ }
+ return gitShareCollector{notes: c.notes, urls: urls, shared: append([]string(nil), c.shared...), subjects: c.subjects, skipped: c.skipped, err: c.err}
+}
+
// gitShareSessionsOnPush shares the sessions linked to the commits being pushed that have no share
// URL in their note yet, and writes the URLs into the notes, before the notes ref is pushed. A
// session already shared from this machine only has its URL written. Without a credential it does
-// nothing and says nothing. ctx bounds it; every error is returned for one line on stderr, never
-// to fail the push.
+// nothing and says nothing. Every error is returned for one line on stderr, never to fail the push.
+//
+// The budget is enforced by the clock, not by cooperation: reading the stores and the runtime log,
+// building a payload and recording the share do not all watch a context. The share phase runs in a
+// goroutine that delivers each URL as its upload finishes; the hook waits for it at most
+// gitShareUploadBudget, takes the URLs collected by then and moves on, abandoning the goroutine
+// (the hook process exits soon after). Only this function writes notes, and only from what was
+// collected, so an abandoned upload never touches them; it may still append its session.shared
+// record to the runtime log, which is harmless: that upload did happen. The note writes then get a
+// fresh gitShareNoteWriteBudget, and the caller pushes the notes ref on a fresh
+// gitShareNotesReserve, so neither is starved by the uploads.
func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, stdin, visibility string) (gitPushShareReport, error) {
var report gitPushShareReport
gitAllowShareHosts()
- // The uploads get their own deadline, so running out of it still leaves time to write the URLs
- // of the uploads that did finish; those run on a short context of their own.
- ctx, cancelUploads := context.WithTimeout(parent, gitShareUploadBudget)
+ // The uploads end gitShareUploadBudget from now, or earlier when the hook's own deadline leaves
+ // less than the note writes and the notes push need after them.
+ uploadDeadline := time.Now().Add(gitShareUploadBudget)
+ if d, ok := parent.Deadline(); ok {
+ if latest := d.Add(-gitShareNoteWriteBudget - gitShareNotesReserve); latest.Before(uploadDeadline) {
+ uploadDeadline = latest
+ }
+ }
+ ctx, cancelUploads := context.WithDeadline(parent, uploadDeadline)
defer cancelUploads()
+ collector := &gitShareCollector{urls: map[string]string{}}
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ gitShareFindAndUpload(ctx, collector, repo, remote, stdin, visibility)
+ }()
+ timedOut := false
+ select {
+ case <-done:
+ case <-ctx.Done():
+ timedOut = true
+ }
+ got := collector.close()
+ cancelUploads()
+ report.Shared = got.shared
+ report.Skipped = got.skipped
+ 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")
+ }
+ if len(got.notes) == 0 {
+ return report, shareErr
+ }
+ noteCtx, cancelNotes := context.WithTimeout(context.Background(), gitShareNoteWriteBudget)
+ defer cancelNotes()
+ 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 shareErr == nil {
+ shareErr = err
+ }
+ continue
+ }
+ if changed {
+ report.Noted++
+ }
+ }
+ return report, shareErr
+}
+
+// gitShareFindAndUpload is the share phase of a push: it reads the pushed commits' notes, finds the
+// linked sessions without a URL, and uploads them, delivering each result to c as it comes.
+func gitShareFindAndUpload(ctx context.Context, c *gitShareCollector, repo gitlink.Repo, remote, stdin, visibility string) {
commits, err := gitlink.PushedCommits(ctx, repo, remote, stdin, gitShareMaxCommits)
if err != nil {
- return report, err
+ c.fail(err)
+ return
}
var order []gitlink.Link
wanted := map[string]bool{}
@@ -203,19 +305,19 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
}
}
if len(order) == 0 {
- return report, nil
+ return
}
+ c.update(func() { c.notes = notes })
known := localShareURLs(shareLogPath())
- urls := map[string]string{}
var toShare []gitlink.Link
for _, link := range order {
if u := known[gitShareKey(link.Harness, link.SessionID)]; u != "" {
- urls[link.Key()] = u
+ key := link.Key()
+ c.update(func() { c.urls[key] = u })
} else {
toShare = append(toShare, link)
}
}
- var shareErr error
type linkedSubject struct {
link gitlink.Link
subject shareSubject
@@ -223,8 +325,7 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
var subjects []linkedSubject
if len(toShare) > 0 {
// Resolve first, cap after: a teammate's session, or one this machine no longer has,
- // must not use up a slot that one of this person's sessions needs. Resolving reads only
- // the local stores, inside the upload budget.
+ // must not use up a slot that one of this person's sessions needs.
stores := newGitShareStoreIndex(handoffSources(handoff.StoreDirs{}))
logPath := shareLogPath()
var inLog map[string]bool // read once, on the first link the stores do not have
@@ -261,49 +362,32 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
subjects = append(subjects, linkedSubject{link: link, subject: shareSubject{session: session, fromLog: true, logEvents: events}})
}
}
- if len(subjects) > 0 {
- client, err := newShareClient()
- if err != nil {
- report.Skipped = "no Beacon credential"
- } else {
- for _, ls := range subjects {
- if ctx.Err() != nil {
- break
- }
- key := ls.link.Key()
- result, _, err := gitShareUpload(ctx, client, ls.subject, shareUploadOptions{Visibility: visibility, Record: true})
- if err != nil && result.SharedURL == "" {
- if shareErr == nil {
- shareErr = fmt.Errorf("%s: %w", key, err)
- }
- continue
- }
- if gitlink.ValidShareURL(result.SharedURL) {
- urls[key] = result.SharedURL
- report.Shared = append(report.Shared, key)
- }
- }
- }
+ if len(subjects) == 0 {
+ return
}
- if ctx.Err() != nil && shareErr == nil && len(report.Shared) < len(subjects) {
- shareErr = errors.New("ran out of time before every linked session was shared; the next push shares the rest")
+ c.update(func() { c.subjects = len(subjects) })
+ client, err := newShareClient()
+ if err != nil {
+ c.update(func() { c.skipped = "no Beacon credential" })
+ return
}
- cancelUploads()
- noteCtx, cancelNotes := context.WithTimeout(parent, gitShareNoteWriteBudget)
- defer cancelNotes()
- for sha := range notes {
- changed, err := gitlink.UpdateNote(noteCtx, repo.Git, sha, func(note string) string { return gitlink.SetLinkURLs(note, urls) })
- if err != nil {
- if shareErr == nil {
- shareErr = err
- }
+ for _, ls := range subjects {
+ if ctx.Err() != nil {
+ return
+ }
+ key := ls.link.Key()
+ result, _, err := gitShareUpload(ctx, client, ls.subject, shareUploadOptions{Visibility: visibility, Record: true})
+ if err != nil && result.SharedURL == "" {
+ c.fail(fmt.Errorf("%s: %w", key, err))
continue
}
- if changed {
- report.Noted++
+ if gitlink.ValidShareURL(result.SharedURL) {
+ c.update(func() {
+ c.urls[key] = result.SharedURL
+ c.shared = append(c.shared, key)
+ })
}
}
- return report, shareErr
}
// 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 b2b441eb..43aee24d 100644
--- a/cli/beacon/cmd/git_share_sessions_test.go
+++ b/cli/beacon/cmd/git_share_sessions_test.go
@@ -369,3 +369,65 @@ func TestGitShareOnPushCapsOnlySessionsThatResolve(t *testing.T) {
t.Fatalf("note %q lacks the URL", note)
}
}
+
+// The share phase is held to the clock: an upload that never returns, and ignores its context, does
+// not hold up the push. The notes still get the URLs of the uploads that finished, the notes ref is
+// pushed with its full reserve, and the hook returns within its budget.
+func TestGitPrePushAbandonsAnUploadThatNeverReturns(t *testing.T) {
+ t.Setenv(gitlink.HookStdinEnv, "1")
+ root, remote := gitCommandTeam(t)
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ prevOpts := shareOpts
+ shareOpts = shareOptions{logPath: env.logPath}
+ t.Cleanup(func() { shareOpts = prevOpts })
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{
+ {Harness: handoff.HarnessClaude, ID: "sess-fast", Directory: env.projectDir, UpdatedAt: time.Now()},
+ {Harness: handoff.HarnessClaude, ID: "sess-stuck", Directory: env.projectDir, UpdatedAt: time.Now()},
+ },
+ events: shareFixtureEvents(env.projectDir),
+ })
+ release := make(chan struct{})
+ t.Cleanup(func() { close(release) })
+ prevUpload, prevBudget := gitShareUpload, gitShareUploadBudget
+ gitShareUploadBudget = 300 * time.Millisecond
+ gitShareUpload = func(ctx context.Context, _ *account.ShareClient, subject shareSubject, _ shareUploadOptions) (shareResult, shareSubject, error) {
+ if subject.session.ID == "sess-fast" {
+ return shareResult{SharedURL: "https://beacon.sh/s/fast01"}, subject, nil
+ }
+ <-release // stuck in local work that never looks at ctx
+ return shareResult{SharedURL: "https://beacon.sh/s/late01"}, subject, nil
+ }
+ t.Cleanup(func() { gitShareUpload, gitShareUploadBudget = prevUpload, prevBudget })
+
+ old := mustGit(t, root, "rev-parse", "HEAD")
+ mustGit(t, root, "commit", "-q", "--allow-empty", "-m", "agent work")
+ sha := mustGit(t, root, "rev-parse", "HEAD")
+ mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "add", "-m", "beacon:claude_code/sess-fast\nbeacon:claude_code/sess-stuck", sha)
+ if out, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil {
+ t.Fatalf("setup: %v\n%s", err, out)
+ }
+ rootCmd.SetIn(strings.NewReader("refs/heads/main " + sha + " refs/heads/main " + old + "\n"))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ var stderr bytes.Buffer
+ start := time.Now()
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {
+ t.Fatalf("pre-push: %v", err)
+ }
+ if elapsed := time.Since(start); elapsed > gitShareUploadBudget+gitShareNoteWriteBudget+gitShareNotesReserve {
+ t.Fatalf("pre-push took %s, past its budget", elapsed)
+ }
+ if !strings.Contains(stderr.String(), "ran out of time") {
+ t.Fatalf("stderr %q", stderr.String())
+ }
+ want := "beacon:claude_code/sess-fast https://beacon.sh/s/fast01\nbeacon:claude_code/sess-stuck"
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {
+ t.Fatalf("local note %q, want %q", note, want)
+ }
+ 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)
+ }
+}
diff --git a/docs/cli/git.mdx b/docs/cli/git.mdx
index fd8b52b2..8120fdd8 100644
--- a/docs/cli/git.mdx
+++ b/docs/cli/git.mdx
@@ -133,7 +133,7 @@ With `--share-sessions`, the pre-push hook also shares the sessions linked to th
- It runs only during a push you started, and reads at most 100 pushed commits and shares at most 10 sessions per push.
- It uses your `beacon login` sign-in (with `traces:write`) or `BEACON_API_KEY`. Without either it shares nothing and prints nothing.
-- It shares within the hook's ten seconds, keeping three of them for pushing the notes ref, and never fails the push; a failure prints one line.
+- It shares within the hook's ten seconds, held to the clock: uploads get six seconds, after which the hook writes the URLs of the uploads that finished into the notes (one second) and pushes the notes ref (three seconds), leaving anything still running behind. It never fails the push; a failure prints one line.
- `public` lists every session linked to a pushed commit in Discover, so `setup` asks first, and without a terminal needs `--yes`.
- The choice is stored in the repository's own config (`beacon.shareSessions`, `beacon.shareVisibility`), so it applies to this clone only. `BEACON_GIT_HOOKS=0 git push` skips it for one push.