Skip to content

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

Merge the trace.v1 share contract into git push sharing

Claude380b1b184172
diff --cc CLAUDE.md
index f881655d,e6054d1b..6e64b6dc
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -69,8 -69,8 +69,8 @@@ Supported runtime surfaces today
- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.
- 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 under the `beacon.share.v1` contract: the types, `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form) and the event-to-message projection `BuildShareMessages` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go`. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten before projection; a tool invocation and its completion become a `tool_call` and a `tool_result` message sharing one callId, and a call reported twice is written once. `--print` shows the exact payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), and a re-share upserts by stable message id. 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. 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), then the active-session record, 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 `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch and per-project choices by path; a project marker `<repo>/.beacon/share.json` may disable on its own 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` + `messagesAfter`), then write the URLs into the notes before pushing them.
+ - 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. 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), 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 and per-project choices by path; a project marker `<repo>/.beacon/share.json` may disable on its own 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.
++- 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.
- 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 --cc cli/beacon/cmd/git_share_sessions_test.go
index 440415e0,00000000..8e2a565b
mode 100644,000000..100644
--- a/cli/beacon/cmd/git_share_sessions_test.go
+++ b/cli/beacon/cmd/git_share_sessions_test.go
@@@ -1,360 -1,0 +1,360 @@@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/gitlink"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"
+)
+
+func writeSharedEvent(t *testing.T, logPath, harness, session, url string) {
+ t.Helper()
+ event := schema.NewEvent(schema.NewEventOptions{Action: SessionSharedAction, Category: "session", Harness: schema.HarnessInfo{Name: harness}})
+ event.Session = &schema.SessionInfo{ID: session}
+ event.Raw = map[string]interface{}{"shared_url": url}
+ line, _ := json.Marshal(event)
+ f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if _, err := f.Write(append(line, '\n')); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestGitHookPostCommitWritesAKnownShareURL(t *testing.T) {
+ root := gitCommandRepo(t)
+ top := mustGit(t, root, "rev-parse", "--show-toplevel")
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ for _, f := range []string{"x.go", "y.go"} {
+ if err := os.WriteFile(filepath.Join(root, f), []byte("package x\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeRuntimeEvent(t, logPath, top, "cur-1", "x.go")
+ writeRuntimeEvent(t, logPath, top, "cur-2", "y.go")
+ writeSharedEvent(t, logPath, "cursor", "cur-1", "https://beacon.sh/s/abc123")
+ writeSharedEvent(t, logPath, "cursor", "cur-2", "https://evil.example/s/abc123")
+ mustGit(t, root, "add", "-A")
+ mustGit(t, root, "commit", "-q", "-m", "x")
+ if out, err := runGit(t, "hook", "post-commit", "--cwd", root, "--log-path", logPath); err != nil || out != "" {
+ t.Fatalf("hook: %v %q", err, out)
+ }
+ note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", "HEAD")
+ if !strings.Contains(note, "beacon:cursor/cur-1 https://beacon.sh/s/abc123") || !strings.Contains(note, "beacon:cursor/cur-2") || strings.Contains(note, "evil.example") {
+ t.Fatalf("note %q", note)
+ }
+ out, err := runGit(t, "notes", "--cwd", root, "--json")
+ if err != nil || !strings.Contains(out, `"url": "https://beacon.sh/s/abc123"`) {
+ t.Fatalf("notes --json: %v\n%s", err, out)
+ }
+ out, _ = runGit(t, "notes", "--cwd", root)
+ if !strings.Contains(out, "cursor/cur-1 https://beacon.sh/s/abc123") {
+ t.Fatalf("notes:\n%s", out)
+ }
+}
+
+func TestGitPrePushSharesLinkedSessions(t *testing.T) {
+ t.Setenv(gitlink.HookStdinEnv, "1") // as Beacon's hook block runs it
+ 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 })
+
+ 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/"+shareTestSession+"\nbeacon:cursor/someone-else", sha)
+ if out, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil || !strings.Contains(out, "shares the agent sessions linked") {
+ t.Fatalf("setup: %v\n%s", err, out)
+ }
+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sessions on: pushes share linked sessions to beacon.sh (direct)") {
+ t.Fatalf("status:\n%s", out)
+ }
+
+ stdin := "refs/heads/main " + sha + " refs/heads/main " + old + "\n"
+ var stderr bytes.Buffer
+ rootCmd.SetIn(strings.NewReader(stdin))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {
+ t.Fatalf("pre-push: %v", err)
+ }
+ if stderr.Len() != 0 {
+ t.Fatalf("stderr %q", stderr.String())
+ }
- if len(srv.messages) != 4 {
- t.Fatalf("server messages = %d", len(srv.messages))
++ if len(srv.events) != 4 {
++ t.Fatalf("server events = %d", len(srv.events))
+ }
+ want := "beacon:claude_code/" + shareTestSession + " https://beacon.sh/s/k3xabc\nbeacon:cursor/someone-else"
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {
+ t.Fatalf("local note %q", note)
+ }
+ if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != want {
+ t.Fatalf("remote note %q", note)
+ }
+ if urls := localShareURLs(env.logPath); urls["claude_code/"+shareTestSession] != "https://beacon.sh/s/k3xabc" {
+ t.Fatalf("session.shared not recorded: %v", urls)
+ }
+
+ // A second push has nothing left to share and makes no share request.
+ before := len(srv.requests)
+ rootCmd.SetIn(strings.NewReader(stdin))
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || stderr.Len() != 0 {
+ t.Fatalf("second pre-push: %v %q", err, stderr.String())
+ }
+ if len(srv.requests) != before {
+ t.Fatalf("second push made share requests: %v", srv.requests[before:])
+ }
+}
+
+func TestGitPrePushWithoutCredentialsSharesNothingQuietly(t *testing.T) {
+ t.Setenv(gitlink.HookStdinEnv, "1") // as Beacon's hook block runs it
+ root, remote := gitCommandTeam(t)
+ env := newShareEnv(t) // signed out, and any request fails the test
+ prevOpts := shareOpts
+ shareOpts = shareOptions{logPath: env.logPath}
+ t.Cleanup(func() { shareOpts = prevOpts })
+ 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/"+shareTestSession, sha)
+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil {
+ t.Fatal(err)
+ }
+ var stderr bytes.Buffer
+ rootCmd.SetIn(strings.NewReader("refs/heads/main " + sha + " refs/heads/main " + old + "\n"))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ start := time.Now()
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || stderr.Len() != 0 {
+ t.Fatalf("pre-push: %v %q", err, stderr.String())
+ }
+ if time.Since(start) > gitShareBudget {
+ t.Fatal("pre-push exceeded its budget")
+ }
+ if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "beacon:claude_code/"+shareTestSession {
+ t.Fatalf("remote note %q", note)
+ }
+}
+
+func TestGitSetupShareSessionsRules(t *testing.T) {
+ root, _ := gitCommandTeam(t)
+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-notes=false"); err == nil {
+ t.Fatal("--share-sessions with --share-notes=false accepted")
+ }
+ prev := shareIsTTY
+ shareIsTTY = func() bool { return false }
+ t.Cleanup(func() { shareIsTTY = prev })
+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-visibility", "public"); err == nil || !strings.Contains(err.Error(), "--yes") {
+ t.Fatalf("public without --yes: %v", err)
+ }
+ if out, err := runGit(t, "setup", "--cwd", root, "--share-sessions", "--share-visibility", "public", "--yes"); err != nil || !strings.Contains(out, "beacon.shareVisibility = public") {
+ t.Fatalf("public --yes: %v\n%s", err, out)
+ }
+ if out, err := runGit(t, "setup", "--cwd", root, "--share-notes=false"); err != nil || !strings.Contains(out, "unset beacon.shareSessions") {
+ t.Fatalf("share-notes off: %v\n%s", err, out)
+ }
+ if out, _ := runGit(t, "status", "--cwd", root); !strings.Contains(out, "sessions off") {
+ t.Fatalf("status:\n%s", out)
+ }
+}
+
+// Called straight from a hook manager (gitlink.HookCall), without Beacon's block to copy and
+// replay stdin, the pre-push hook must leave stdin to the steps after it (`git lfs pre-push`).
+// Without the refs it cannot know what is being pushed (another branch, --tags, --delete), so it
+// shares no sessions, says so once, and still pushes the commit links.
+func TestGitPrePushWithoutTheBlockLeavesStdinAloneAndSharesNothing(t *testing.T) {
+ 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 })
+ t.Setenv(gitlink.HookStdinEnv, "")
+
+ 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/"+shareTestSession, sha)
+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil {
+ t.Fatal(err)
+ }
+ stdin := "refs/heads/main " + sha + " refs/heads/main " + old + "\n"
+ reader := strings.NewReader(stdin)
+ rootCmd.SetIn(reader)
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ var stderr bytes.Buffer
+ before := len(srv.requests)
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil {
+ t.Fatalf("pre-push: %v", err)
+ }
+ if reader.Len() != len(stdin) {
+ t.Fatalf("the hook read %d bytes of stdin that the next step needs", len(stdin)-reader.Len())
+ }
+ if len(srv.requests) != before {
+ t.Fatalf("shared sessions without knowing the pushed refs: %v", srv.requests[before:])
+ }
+ if !strings.Contains(stderr.String(), "commit links only") {
+ t.Fatalf("stderr %q, want the hint", stderr.String())
+ }
+ if note := mustGit(t, remote, "notes", "--ref="+gitlink.NotesRef, "show", sha); note != "beacon:claude_code/"+shareTestSession {
+ t.Fatalf("remote note %q, want the bare link pushed and nothing shared", note)
+ }
+}
+
+// Pre-push sharing to a trace that already exists keeps the title set on it earlier (with --title
+// or a rename on beacon.sh) and its visibility.
+func TestGitPrePushKeepsAnExistingTracesTitle(t *testing.T) {
+ root, remote := gitCommandTeam(t)
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ // Shared from elsewhere (another log, so this machine's log has no record of it), titled.
+ elsewhere := filepath.Join(t.TempDir(), "other.jsonl")
+ if _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--title", "Login fix", "--visibility", "private", "--log-path", elsewhere); err != nil {
+ t.Fatalf("share: %v\n%s", err, stderr)
+ }
+ prevOpts := shareOpts
+ shareOpts = shareOptions{logPath: env.logPath}
+ t.Cleanup(func() { shareOpts = prevOpts })
+ t.Setenv(gitlink.HookStdinEnv, "1")
+
+ 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/"+shareTestSession, sha)
+ if _, err := runGit(t, "setup", "--cwd", root, "--share-sessions"); err != nil {
+ t.Fatal(err)
+ }
+ rootCmd.SetIn(strings.NewReader("refs/heads/main " + sha + " refs/heads/main " + old + "\n"))
+ t.Cleanup(func() { rootCmd.SetIn(nil) })
+ var stderr bytes.Buffer
+ before := len(srv.requests)
+ if _, err := runGitStderr(t, &stderr, "hook", "pre-push", "--cwd", root, "origin", remote); err != nil || stderr.Len() != 0 {
+ t.Fatalf("pre-push: %v %q", err, stderr.String())
+ }
+ if len(srv.requests) == before {
+ t.Fatal("pre-push made no share request")
+ }
+ if srv.trace.Title != "Login fix" || srv.trace.Visibility != "private" {
+ t.Fatalf("trace title %q visibility %q, want the ones set earlier", srv.trace.Title, srv.trace.Visibility)
+ }
+}
+
+// When the uploads run out of their deadline, the URLs of the uploads that finished are still
+// written into the notes: the note updates run on their own short context.
+func TestGitShareOnPushWritesFinishedURLsWhenUploadsRunOutOfTime(t *testing.T) {
+ root, _ := 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-slow", Directory: env.projectDir, UpdatedAt: time.Now()},
+ },
+ events: shareFixtureEvents(env.projectDir),
+ })
+ 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
+ }
+ <-ctx.Done() // the second upload uses up the deadline
+ return shareResult{}, subject, ctx.Err()
+ }
+ 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-slow", sha)
+ repo, err := gitlink.OpenRepo(context.Background(), gitlink.Git{Dir: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), gitShareBudget)
+ defer cancel()
+ report, err := gitShareSessionsOnPush(ctx, repo, "origin", "refs/heads/main "+sha+" refs/heads/main "+old+"\n", "")
+ if err == nil {
+ t.Fatal("running out of time was not reported")
+ }
+ if report.Noted != 1 {
+ t.Fatalf("report %+v, want the note updated", 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)
+ }
+}
+
+// The per-push cap counts only sessions this machine has: links to teammates' or pruned sessions
+// ahead of one's own do not use up its slots.
+func TestGitShareOnPushCapsOnlySessionsThatResolve(t *testing.T) {
+ root, _ := gitCommandTeam(t)
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ prevOpts := shareOpts
+ shareOpts = shareOptions{logPath: env.logPath}
+ t.Cleanup(func() { shareOpts = prevOpts })
+ logReads := 0
+ prevLogSessions := gitShareLogSessions
+ gitShareLogSessions = func(logPath string) ([]handoff.Session, error) {
+ logReads++
+ return prevLogSessions(logPath)
+ }
+ t.Cleanup(func() { gitShareLogSessions = prevLogSessions })
+ var uploaded []string
+ prevUpload := gitShareUpload
+ gitShareUpload = func(ctx context.Context, _ *account.ShareClient, subject shareSubject, _ shareUploadOptions) (shareResult, shareSubject, error) {
+ uploaded = append(uploaded, subject.session.ID)
+ return shareResult{SharedURL: "https://beacon.sh/s/mine01"}, subject, nil
+ }
+ t.Cleanup(func() { gitShareUpload = prevUpload })
+
+ var lines []string
+ for i := 0; i < gitShareMaxSessions+2; i++ {
+ lines = append(lines, fmt.Sprintf("beacon:claude_code/teammate-%02d", i))
+ }
+ lines = append(lines, "beacon:claude_code/"+shareTestSession)
+ 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", strings.Join(lines, "\n"), sha)
+ repo, err := gitlink.OpenRepo(context.Background(), gitlink.Git{Dir: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := gitShareSessionsOnPush(context.Background(), repo, "origin", "refs/heads/main "+sha+" refs/heads/main "+old+"\n", ""); err != nil {
+ t.Fatal(err)
+ }
+ if len(uploaded) != 1 || uploaded[0] != shareTestSession {
+ t.Fatalf("uploaded %v, want only this machine's session", uploaded)
+ }
+ if logReads != 1 {
+ t.Fatalf("runtime log read %d times for the teammates' links, want once", logReads)
+ }
+ if note := mustGit(t, root, "notes", "--ref="+gitlink.NotesRef, "show", sha); !strings.Contains(note, "beacon:claude_code/"+shareTestSession+" https://beacon.sh/s/mine01") {
+ t.Fatalf("note %q lacks the URL", note)
+ }
+}
diff --cc cli/beacon/cmd/share.go
index ce441df3,ded6136a..c1e4e7c9
--- a/cli/beacon/cmd/share.go
+++ b/cli/beacon/cmd/share.go
@@@ -181,20 -183,22 +183,26 @@@ type shareResult struct
Uploaded int `json:"uploaded"`
// SelectedBy says how the session was chosen: session, source_path, env, active or recent.
SelectedBy string `json:"selected_by,omitempty"`
+ // SharedThrough is when the session was read for this upload: an event logged after it was
+ // not sent, however soon the upload finished. The session.shared record carries it as
+ // shared_through, which is what the dashboard compares later activity against.
+ SharedThrough time.Time `json:"-"`
+ // sharedAt is when beacon.sh created the trace, for a refresh or re-share to record as the
+ // share date (empty when unknown).
+ sharedAt string
}
- // sharePayload is what --print shows: the trace metadata of the PUT request and every message the
- // batch requests would carry, in order.
+ // sharePayload is what --print shows: the external id the requests go to, the body of the PUT
+ // request (trace) and every event the batch requests would carry (events), in order.
type sharePayload struct {
- ExternalID string `json:"external_id"`
- Trace asymptoteobserve.ShareTraceV1 `json:"trace"`
- Messages []asymptoteobserve.ShareMessageV1 `json:"messages"`
+ ExternalID string `json:"external_id"`
+ Trace asymptoteobserve.ShareTraceV1 `json:"trace"`
+ Events []asymptoteobserve.TraceEventV1 `json:"events"`
}
+ // harness is the normalized runtime name a trace's summary carries.
+ func (p sharePayload) harness() string { return p.Trace.Summary.Harness.Name }
+
func (o shareOptions) printOnly() bool { return o.print || o.dryRun }
func runShare(cmd *cobra.Command) error {
@@@ -252,25 -257,28 +262,29 @@@
if err != nil {
return err
}
- uploaded, err := client.PutMessages(ctx, payload.ExternalID, payload.Messages)
+ uploaded, err := client.PostEvents(ctx, payload.ExternalID, asymptoteobserve.ShareEventsBatchV1{Events: payload.Events})
if err != nil {
- return fmt.Errorf("the trace was created at %s, but uploading its messages failed (run the same command again to retry): %w", trace.URL, err)
+ return fmt.Errorf("the trace was created at %s, but uploading its events failed (run the same command again to retry): %w", trace.URL, err)
}
result := shareResult{
- TraceID: trace.ID,
- ExternalID: payload.ExternalID,
- SharedURL: trace.URL,
- Visibility: trace.Visibility,
- Harness: payload.harness(),
- EventCount: uploaded.EventCount,
- Uploaded: len(payload.Events),
- SelectedBy: subject.selectedBy,
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
- AgentID: payload.Trace.AgentID,
- MessageCount: uploaded.MessageCount,
- Uploaded: len(payload.Messages),
++ Harness: payload.harness(),
++ EventCount: uploaded.EventCount,
++ Uploaded: len(payload.Events),
+ SelectedBy: subject.selectedBy,
+ SharedThrough: readAt,
}
if uploaded.Batches == 0 {
- result.MessageCount = trace.MessageCount
+ result.EventCount = trace.EventCount
}
- if err := recordShareEvent(subject.session, result, false); err != nil {
+ // Sharing a trace that already exists updates it: the share date stays the trace's own.
+ if found {
+ result.sharedAt = state.CreatedAt
+ }
+ if err := recordShareEvent(subject.session, result, found); err != nil {
fmt.Fprintf(errOut, "warning: the session was shared, but the runtime log was not updated: %v\n", err)
}
return printShareResult(cmd, result)
@@@ -334,19 -341,19 +348,20 @@@ func runShareRefresh(cmd *cobra.Command
return err
}
result := shareResult{
- TraceID: trace.ID,
- ExternalID: payload.ExternalID,
- SharedURL: trace.URL,
- Visibility: trace.Visibility,
- Harness: payload.harness(),
- EventCount: state.EventCount,
- Uploaded: len(pending),
- SelectedBy: subject.selectedBy,
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
- AgentID: payload.Trace.AgentID,
- MessageCount: state.MessageCount,
++ Harness: payload.harness(),
++ EventCount: state.EventCount,
+ Uploaded: len(pending),
+ SelectedBy: subject.selectedBy,
+ SharedThrough: readAt,
}
if uploaded.Batches > 0 {
- result.MessageCount = uploaded.MessageCount
+ result.EventCount = uploaded.EventCount
}
+ result.sharedAt = state.CreatedAt
if err := recordShareEvent(subject.session, result, true); err != nil {
fmt.Fprintf(cmd.ErrOrStderr(), "warning: the trace was refreshed, but the runtime log was not updated: %v\n", err)
}
@@@ -962,10 -1001,11 +1009,14 @@@ func shareRecordEvent(session handoff.S
}
if !refresh {
event.Raw["shared_at"] = stamp
+ } else if created, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(result.sharedAt)); err == nil {
+ // A refresh keeps the share date: the trace's creation on beacon.sh, which also stands in
+ // for a first record that has rotated out of the log.
+ event.Raw["shared_at"] = created.UTC().Format(time.RFC3339)
}
+ if !result.SharedThrough.IsZero() {
+ event.Raw["shared_through"] = schema.FormatTimestamp(result.SharedThrough)
+ }
return event
}
diff --cc cli/beacon/cmd/share_test.go
index 9e9f1ced,6dd055fa..cc3c7539
--- a/cli/beacon/cmd/share_test.go
+++ b/cli/beacon/cmd/share_test.go
@@@ -606,60 -607,153 +608,211 @@@ func TestShareAlignSwitchesFromTheLogTo
}
}
+// The session.shared record says what the upload covered: shared_through is when the session was
+// read, which precedes the record's own timestamp (taken after the upload). Share, refresh and the
+// non-interactive upload path all write it.
+func TestShareRecordCarriesSharedThrough(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ base := time.Date(2026, 10, 2, 9, 0, 0, 0, time.UTC)
+ calls := 0
+ shareNow = func() time.Time { calls++; return base.Add(time.Duration(calls) * time.Minute) }
+ t.Cleanup(func() { shareNow = time.Now })
+
+ check := func(what string) {
+ t.Helper()
+ data, err := os.ReadFile(env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")
+ var event schema.Event
+ if err := json.Unmarshal([]byte(lines[len(lines)-1]), &event); err != nil {
+ t.Fatal(err)
+ }
+ through, _ := event.Raw["shared_through"].(string)
+ readAt, err := time.Parse(time.RFC3339Nano, through)
+ if err != nil {
+ t.Fatalf("%s: shared_through %q: %v", what, through, err)
+ }
+ recorded, err := time.Parse(time.RFC3339Nano, event.Timestamp)
+ if err != nil || !readAt.Before(recorded) {
+ t.Fatalf("%s: shared_through %s, record at %s: want the read before the record", what, through, event.Timestamp)
+ }
+ }
+ if _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {
+ t.Fatalf("share: %v\n%s", err, stderr)
+ }
+ check("share")
+ if _, _, err := runShareCommand(t, "refresh", "claude_code:"+shareTestSession, "--log-path", env.logPath); err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ check("refresh")
+ prevOpts := shareOpts
+ shareOpts = shareOptions{logPath: env.logPath}
+ t.Cleanup(func() { shareOpts = prevOpts })
+ subject, err := resolveShareSubject(handoff.HarnessClaude, shareTestSession)
+ if err != nil {
+ t.Fatal(err)
+ }
+ client, err := newShareClient()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := shareUpload(context.Background(), client, subject, shareUploadOptions{Record: true}); err != nil {
+ t.Fatalf("upload: %v", err)
+ }
+ check("upload")
+}
++
+ func TestSharePayloadRelatesAHandoff(t *testing.T) {
+ env := newShareEnv(t)
+ events := shareFixtureEvents(env.projectDir)
+ handoffEvent := events[0]
+ handoffEvent.Event.Action = "session.handoff"
+ handoffEvent.Event.Category = "session"
+ handoffEvent.Prompt = nil
+ handoffEvent.Handoff = &schema.HandoffInfo{SourceHarness: "codex", SourceSessionID: "rollout-1"}
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()}},
+ events: append([]schema.Event{handoffEvent}, events...),
+ })
+ stdout, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload sharePayload
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if payload.Trace.RelatedTo != asymptoteobserve.ShareExternalID("codex", "rollout-1") || payload.Trace.RelationshipType != asymptoteobserve.ShareRelationshipHandoff {
+ t.Fatalf("relation = %q %q", payload.Trace.RelatedTo, payload.Trace.RelationshipType)
+ }
+ }
+
+ // shareFixtureInLog writes the fixture session to the runtime log as hook events.
+ func shareFixtureInLog(t *testing.T, env *shareEnv) {
+ t.Helper()
+ for _, event := range shareFixtureEvents(env.projectDir) {
+ event.Harness.CollectionMethod = schema.CollectionMethodHook
+ if _, err := writer.AppendEvent(event, writer.Options{Path: env.logPath, UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+
+ func TestShareReadsTheLogWhenTheStoreCannotBeRead(t *testing.T) {
+ env := newShareEnv(t)
+ denied := fmt.Errorf("open store: %w", os.ErrPermission)
+ // The store cannot even list its sessions; the log has the session.
+ stubHandoffSources(t, stubHandoffSource{harness: handoff.HarnessClaude, err: denied, eventsErr: denied})
+ shareFixtureInLog(t, env)
+ for _, args := range [][]string{
+ {"--cwd", env.projectDir},
+ {"--session", shareTestSession},
+ {"refresh", shareTestSession},
+ } {
+ stdout, _, err := runShareCommand(t, append(args, "--print", "--log-path", env.logPath)...)
+ if err != nil {
+ t.Fatalf("share %v: %v", args, err)
+ }
+ var payload sharePayload
+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil || len(payload.Events) != 4 {
+ t.Fatalf("share %v: payload = %s (err %v)", args, stdout, err)
+ }
+ }
+
+ // The store lists the session but cannot read it: the log copy is shared.
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{{Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()}},
+ eventsErr: denied,
+ })
+ if _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", env.logPath); err != nil {
+ t.Fatalf("listed but unreadable: %v", err)
+ }
+
+ // With nothing in the log either, the store's error is the one reported.
+ empty := filepath.Join(env.home, "empty.jsonl")
+ _, _, err := runShareCommand(t, "--cwd", env.projectDir, "--print", "--log-path", empty)
+ if err == nil || !strings.Contains(err.Error(), "permission") {
+ t.Fatalf("err = %v, want the store's permission error", err)
+ }
+ stubHandoffSources(t, stubHandoffSource{harness: handoff.HarnessClaude, err: denied, eventsErr: denied})
+ _, _, err = runShareCommand(t, "--session", shareTestSession, "--print", "--log-path", empty)
+ if err == nil || !strings.Contains(err.Error(), "permission") {
+ t.Fatalf("--session err = %v, want the store's permission error", err)
+ }
+ }
+
+ func TestShareRefusesAnAmbiguousPrefix(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ twin := shareTestSession[:8] + "-ffff-4fff-8fff-000000000002"
+ stubHandoffSources(t, stubHandoffSource{
+ harness: handoff.HarnessClaude,
+ sessions: []handoff.Session{
+ {Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: time.Now()},
+ {Harness: handoff.HarnessClaude, ID: twin, Directory: env.projectDir, UpdatedAt: time.Now()},
+ },
+ events: shareFixtureEvents(env.projectDir),
+ })
+ // Only one of the two is in the runtime log.
+ shareFixtureInLog(t, env)
+ for _, args := range [][]string{
+ {"--session", shareTestSession[:8]},
+ {"refresh", shareTestSession[:8]},
+ } {
+ _, _, err := runShareCommand(t, append(args, "--log-path", env.logPath)...)
+ var ambiguous *handoff.AmbiguousError
+ if !errors.As(err, &ambiguous) {
+ t.Fatalf("share %v: err = %v, want the ambiguity", args, err)
+ }
+ }
+ if len(srv.requests) != 0 {
+ t.Fatalf("requests = %v", srv.requests)
+ }
+ }
+
+ func TestShareAgainKeepsTheShareDate(t *testing.T) {
+ env := newShareEnv(t)
+ srv := newFakeShareServer(t)
+ srv.signIn(account.ScopeTracesWrite)
+ first := time.Date(2026, 10, 2, 9, 0, 0, 0, time.UTC)
+ shareNow = func() time.Time { return first }
+ t.Cleanup(func() { shareNow = time.Now })
+ if _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {
+ t.Fatalf("share: %v\n%s", err, stderr)
+ }
+ later := first.Add(3 * time.Hour)
+ shareNow = func() time.Time { return later }
+ if _, stderr, err := runShareCommand(t, "--cwd", env.projectDir, "--log-path", env.logPath); err != nil {
+ t.Fatalf("share again: %v\n%s", err, stderr)
+ }
+ list, err := dashboard.ReadTraceList(env.logPath, dashboard.TraceQuery{State: "shared"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(list.Traces) != 1 {
+ t.Fatalf("shared traces = %+v", list.Traces)
+ }
+ sharing := list.Traces[0].Sharing
+ if sharing.SharedAt != first.Format(time.RFC3339) || sharing.LastRefreshedAt != later.Format(time.RFC3339) {
+ t.Fatalf("sharing = %+v, want shared_at %s and last_refreshed_at %s", sharing, first.Format(time.RFC3339), later.Format(time.RFC3339))
+ }
+ data, err := os.ReadFile(env.logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")
+ var second schema.Event
+ if err := json.Unmarshal([]byte(lines[len(lines)-1]), &second); err != nil {
+ t.Fatal(err)
+ }
+ if second.Raw["shared_at"] != first.Format(time.RFC3339) || !strings.Contains(second.Message, "refreshed") {
+ t.Fatalf("second record = %q %+v", second.Message, second.Raw)
+ }
+ }
diff --cc cli/beacon/cmd/share_upload.go
index cc9b13c8,00000000..6358ff10
mode 100644,000000..100644
--- a/cli/beacon/cmd/share_upload.go
+++ b/cli/beacon/cmd/share_upload.go
@@@ -1,87 -1,0 +1,89 @@@
+package cmd
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/account"
++ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// shareUploadOptions configures shareUpload.
+type shareUploadOptions struct {
+ // Visibility is applied when the trace is created. An existing trace keeps its own unless
+ // ExplicitVisibility says the person asked for this one (--visibility), as plain share does.
+ Visibility string
+ ExplicitVisibility bool
+ // ExplicitTitle keeps the payload's title for an existing trace (--title). Otherwise an
+ // existing trace keeps its title, so a --title or a rename on beacon.sh is not replaced by the
+ // derived one (keepSharedTitle).
+ ExplicitTitle bool
+ // Record writes the session.shared event after the upload.
+ Record bool
+}
+
+// shareUpload creates or updates subject's shared trace, sending only what beacon.sh lacks. It is
+// the path every non-interactive upload takes (the pre-push hook, --follow), so it applies the same
+// rules as `beacon share refresh`: an existing trace is checked against this copy of the session
- // (alignShareSource) and only the messages after the last one beacon.sh holds are sent
- // (messagesAfter), which re-sends open calls and that last message.
++// (alignShareSource) and only the events after the last one beacon.sh holds are sent
++// (ShareEventsAfter), which re-sends that last event and any tool call still open.
+func shareUpload(ctx context.Context, client *account.ShareClient, subject shareSubject, opts shareUploadOptions) (shareResult, shareSubject, error) {
+ readAt := shareNow()
+ payload, err := buildSharePayload(subject)
+ if err != nil {
+ return shareResult{}, subject, err
+ }
+ state, found, err := client.GetTrace(ctx, payload.ExternalID)
+ if err != nil {
+ return shareResult{}, subject, err
+ }
- pending := payload.Messages
++ pending := payload.Events
+ if found {
+ if subject, payload, err = alignShareSource(subject, payload, state); err != nil {
+ return shareResult{}, subject, err
+ }
+ if opts.ExplicitVisibility && opts.Visibility != "" {
+ payload.Trace.Visibility = opts.Visibility
+ } else {
+ payload.Trace.Visibility = ""
+ }
+ if !opts.ExplicitTitle {
+ payload.Trace.Title = ""
+ }
- pending = messagesAfter(payload.Messages, state.LastMessageID, state.MaxOrder)
++ pending = asymptoteobserve.ShareEventsAfter(payload.Events, state.LastEventID, state.MaxNumber)
+ } else if opts.Visibility != "" {
+ payload.Trace.Visibility = opts.Visibility
+ }
+ trace, err := client.PutTrace(ctx, payload.ExternalID, payload.Trace)
+ if err != nil {
+ return shareResult{}, subject, err
+ }
- uploaded, err := client.PutMessages(ctx, payload.ExternalID, pending)
++ uploaded, err := client.PostEvents(ctx, payload.ExternalID, asymptoteobserve.ShareEventsBatchV1{Events: pending})
+ if err != nil {
- return shareResult{}, subject, fmt.Errorf("upload messages to %s: %w", trace.URL, err)
++ return shareResult{}, subject, fmt.Errorf("upload events to %s: %w", trace.URL, err)
+ }
+ result := shareResult{
+ TraceID: trace.ID,
+ ExternalID: payload.ExternalID,
+ SharedURL: trace.URL,
+ Visibility: trace.Visibility,
- AgentID: payload.Trace.AgentID,
- MessageCount: trace.MessageCount,
++ Harness: payload.harness(),
++ EventCount: trace.EventCount,
+ Uploaded: len(pending),
+ SelectedBy: subject.selectedBy,
+ SharedThrough: readAt,
+ }
+ if found {
- result.MessageCount = state.MessageCount
++ result.EventCount = state.EventCount
++ result.sharedAt = state.CreatedAt
+ }
+ if uploaded.Batches > 0 {
- result.MessageCount = uploaded.MessageCount
++ result.EventCount = uploaded.EventCount
+ }
+ if opts.Record {
+ if err := recordShareEvent(subject.session, result, found); err != nil {
+ return result, subject, fmt.Errorf("shared, but the runtime log was not updated: %w", err)
+ }
+ }
+ return result, subject, nil
+}