Skip to content

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

List each store once per push, and name the pre-push sharing exception

Claude1c44e94b60a9
diff --git a/CLAUDE.md b/CLAUDE.md
index 9928b730..f562ab25 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,7 +26,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc
- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.
- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.
-- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the session's own base URL to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused; hooks, plugins and background jobs never make them. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.
+- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the session's own base URL to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused. Hooks, plugins and background jobs never make them, with one exception: the git pre-push hook, only when the person opted in with `beacon git setup --share-sessions` (public needs confirmation), may make the three share requests during a push the person started, within the hook's budget and never failing the push. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.
- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.
- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields and joins `endpointBackfillRunners`. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.
- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.
@@ -69,7 +69,7 @@ Supported runtime surfaces today:
- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. 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 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; 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 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`.
+- 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 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.
- 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_sessions.go b/cli/beacon/cmd/git_share_sessions.go
index a4a67cd5..353481f3 100644
--- a/cli/beacon/cmd/git_share_sessions.go
+++ b/cli/beacon/cmd/git_share_sessions.go
@@ -54,13 +54,52 @@ var (
gitShareLogSessions = func(logPath string) ([]handoff.Session, error) {
return handoff.LogSessions(logPath, handoff.Filter{})
}
+ // gitShareListStore lists one runtime's stored sessions; tests replace it to count listings.
+ gitShareListStore = func(sources []handoff.Source, harness string) ([]handoff.Session, error) {
+ return handoff.List(sources, handoff.Filter{Harness: harness, IncludeSubagents: true})
+ }
)
-// gitShareMaxResolve bounds how many linked sessions one push tries to find on this machine,
-// counting the ones that are not here (teammates' sessions), so a note full of them cannot use up
-// the budget.
+// gitShareMaxResolve bounds how many linked sessions without a URL one push looks up, counting the
+// ones that are not on this machine (teammates' sessions). Each runtime's store is listed at most
+// once per push and the runtime log read at most once, so the cap bounds the per-link work that
+// follows (matching, and reading a log session's events), not the number of store listings.
const gitShareMaxResolve = 50
+// gitShareStoreIndex finds linked sessions in the runtimes' stores, listing each runtime's store at
+// most once per push, on the first link of that runtime. A link names a session by its full id, so
+// only an exact, unique id match counts: a prefix match (which handoff.Find would also accept) is
+// another session.
+type gitShareStoreIndex struct {
+ sources []handoff.Source
+ byID map[string]map[string][]handoff.Session // harness -> id -> sessions
+}
+
+func newGitShareStoreIndex(sources []handoff.Source) *gitShareStoreIndex {
+ return &gitShareStoreIndex{sources: sources, byID: map[string]map[string][]handoff.Session{}}
+}
+
+// find returns the stored session of harness with exactly id. ctx is checked before a listing.
+func (x *gitShareStoreIndex) find(ctx context.Context, harness, id string) (handoff.Session, bool) {
+ index, listed := x.byID[harness]
+ if !listed {
+ if ctx.Err() != nil {
+ return handoff.Session{}, false
+ }
+ index = map[string][]handoff.Session{}
+ // A store that cannot be read lists what it can; the runtime log still answers for it.
+ sessions, _ := gitShareListStore(x.sources, harness)
+ for _, s := range sessions {
+ index[s.ID] = append(index[s.ID], s)
+ }
+ x.byID[harness] = index
+ }
+ if matches := index[id]; len(matches) == 1 {
+ return matches[0], true
+ }
+ return handoff.Session{}, false
+}
+
// gitAllowShareHosts admits the configured Beacon service's host besides beacon.sh.
func gitAllowShareHosts() {
for _, raw := range []string{account.ResolveBaseURL("")} {
@@ -186,7 +225,7 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
// 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.
- sources := handoffSources(handoff.StoreDirs{})
+ stores := newGitShareStoreIndex(handoffSources(handoff.StoreDirs{}))
logPath := shareLogPath()
var inLog map[string]bool // read once, on the first link the stores do not have
for i, link := range toShare {
@@ -197,12 +236,13 @@ func gitShareSessionsOnPush(parent context.Context, repo gitlink.Repo, remote, s
if err != nil {
continue
}
- if session, err := handoff.Find(sources, harness, link.SessionID); err == nil {
- if session.ID == link.SessionID {
- subjects = append(subjects, linkedSubject{link: link, subject: shareSubject{session: session}})
- }
+ if session, ok := stores.find(ctx, harness, link.SessionID); ok {
+ subjects = append(subjects, linkedSubject{link: link, subject: shareSubject{session: session}})
continue
}
+ if ctx.Err() != nil {
+ break
+ }
if inLog == nil {
inLog = map[string]bool{}
if sessions, err := gitShareLogSessions(logPath); err == nil {
diff --git a/cli/beacon/cmd/git_share_sessions_test.go b/cli/beacon/cmd/git_share_sessions_test.go
index 8e2a565b..b2b441eb 100644
--- a/cli/beacon/cmd/git_share_sessions_test.go
+++ b/cli/beacon/cmd/git_share_sessions_test.go
@@ -308,7 +308,8 @@ func TestGitShareOnPushWritesFinishedURLsWhenUploadsRunOutOfTime(t *testing.T) {
}
// 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.
+// ahead of one's own do not use up its slots. Each runtime's store is listed once per push and the
+// runtime log read once, however many links there are.
func TestGitShareOnPushCapsOnlySessionsThatResolve(t *testing.T) {
root, _ := gitCommandTeam(t)
env := newShareEnv(t)
@@ -324,6 +325,13 @@ func TestGitShareOnPushCapsOnlySessionsThatResolve(t *testing.T) {
return prevLogSessions(logPath)
}
t.Cleanup(func() { gitShareLogSessions = prevLogSessions })
+ storeListings := 0
+ prevListStore := gitShareListStore
+ gitShareListStore = func(sources []handoff.Source, harness string) ([]handoff.Session, error) {
+ storeListings++
+ return prevListStore(sources, harness)
+ }
+ t.Cleanup(func() { gitShareListStore = prevListStore })
var uploaded []string
prevUpload := gitShareUpload
gitShareUpload = func(ctx context.Context, _ *account.ShareClient, subject shareSubject, _ shareUploadOptions) (shareResult, shareSubject, error) {
@@ -354,6 +362,9 @@ func TestGitShareOnPushCapsOnlySessionsThatResolve(t *testing.T) {
if logReads != 1 {
t.Fatalf("runtime log read %d times for the teammates' links, want once", logReads)
}
+ if storeListings != 1 {
+ t.Fatalf("the Claude Code store was listed %d times for %d links, want once per push", storeListings, len(lines))
+ }
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 --git a/cli/beacon/cmd/share.go b/cli/beacon/cmd/share.go
index e0513a4e..d4321671 100644
--- a/cli/beacon/cmd/share.go
+++ b/cli/beacon/cmd/share.go
@@ -110,7 +110,8 @@ you; public lists the trace in Discover for anyone, and asks for confirmation fi
a session updates the same trace and keeps its visibility unless --visibility is given.
Sharing needs ` + "`beacon login`" + ` (with the traces:write permission) or a Beacon API key in --key or
-BEACON_API_KEY. Hooks never upload anything; ` + "`beacon share auto`" + ` asks Beacon Cloud to publish new sessions
+BEACON_API_KEY. Hooks never upload anything, except the git pre-push hook after
+` + "`beacon git setup --share-sessions`" + `; ` + "`beacon share auto`" + ` asks Beacon Cloud to publish new sessions
from the events it already receives.`,
Args: cobra.NoArgs,
SilenceUsage: true,
diff --git a/docs/cli/account-auth.mdx b/docs/cli/account-auth.mdx
index bd9d94d1..178c5292 100644
--- a/docs/cli/account-auth.mdx
+++ b/docs/cli/account-auth.mdx
@@ -98,7 +98,7 @@ The CLI uses the versioned `2026-09-01` grant contract:
- `GET /cli/auth?state=...&port=...&scopes=...` authenticates the person, lists every requested scope (space-separated in `scopes`), and redirects to the loopback callback with `state` and a one-time `exchange_code`.
- `POST /api/cli/auth/exchange` accepts the exchange code, state, and PKCE verifier. It returns a scoped access token, expiry, user identity, organization memberships, and optional active organization.
- `POST /api/cli/mcp/tokens` accepts `{"name": ..., "expires_in_days": ...}` with the access token as a Bearer credential and returns a personal Beacon Cloud MCP token (`token`, `access_token` metadata, `mcp_url`). It requires `mcp:token:create`.
-- `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` create a shared trace from its `beacon.trace.v1` summary, upsert its trace events, and read it back (with the id of the last event held) for [`beacon share`](/cli/share), with the access token (or a `bcn_api_` API key) as a Bearer credential. They require `traces:write`.
+- `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` create a shared trace from its `beacon.trace.v1` summary, upsert its trace events, and read it back (with the id of the last event held) for [`beacon share`](/cli/share) (and for the git pre-push hook, only after you opt in with [`beacon git setup --share-sessions`](/cli/git#sharing-sessions-on-push)), with the access token (or a `bcn_api_` API key) as a Bearer credential. They require `traces:write`.
- `POST /api/cli/auth/revoke` accepts the access token as a Bearer credential and revokes it.
`beacon login` requests `profile:read`, `device:enroll`, `mcp:token:create` and `traces:write`. A later `beacon endpoint connect` can use `device:enroll` to mint a device-specific ingest key without treating the account token as an ingest credential, and `beacon mcp token create` uses `mcp:token:create` to mint a personal MCP token. beacon.sh approves the sign-in only when the permissions its page showed match the ones the CLI registered, so a crafted link cannot hide one. `beacon share` uses `traces:write` to upload a session you choose to share. A session from an older `beacon login` lacks `mcp:token:create` or `traces:write`; run `beacon login` again to create MCP tokens or share traces from the CLI.
diff --git a/docs/cli/git.mdx b/docs/cli/git.mdx
index 568eacf8..fd8b52b2 100644
--- a/docs/cli/git.mdx
+++ b/docs/cli/git.mdx
@@ -129,7 +129,7 @@ beacon git setup --share-sessions # new traces are direc
beacon git setup --share-sessions --share-visibility private
```
-With `--share-sessions`, the pre-push hook also shares the sessions linked to the commits being pushed that have no share URL in their note yet, then writes their URLs into the notes before pushing `refs/notes/beacon`. A session already shared from this machine only gets its URL written. A session this machine does not have (a teammate's) is skipped. It is the same upload as [`beacon share`](/cli/share#what-is-uploaded), with the same redaction, and an existing trace keeps its visibility. Which commits are being pushed comes from the refs git hands the hook on stdin. Beacon's hook block copies them for Beacon and replays them to the rest of the repository's hook, so `git lfs pre-push` and similar steps still see them. Called through the `beacon git hook pre-push "$@" || true` line added to a hook manager or a hook in another language, Beacon leaves stdin alone and shares no sessions (it cannot tell which refs are being pushed); it still shares the commit links and prints a one-line note.
+With `--share-sessions`, the pre-push hook also shares the sessions linked to the commits being pushed (the one hook that uploads session content, and only because you opted in; it uses the same credential as `beacon share`, never copied anywhere) that have no share URL in their note yet, then writes their URLs into the notes before pushing `refs/notes/beacon`. A session already shared from this machine only gets its URL written. A session this machine does not have (a teammate's) is skipped. It is the same upload as [`beacon share`](/cli/share#what-is-uploaded), with the same redaction, and an existing trace keeps its visibility. Which commits are being pushed comes from the refs git hands the hook on stdin. Beacon's hook block copies them for Beacon and replays them to the rest of the repository's hook, so `git lfs pre-push` and similar steps still see them. Called through the `beacon git hook pre-push "$@" || true` line added to a hook manager or a hook in another language, Beacon leaves stdin alone and shares no sessions (it cannot tell which refs are being pushed); it still shares the commit links and prints a one-line note.
- 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.
diff --git a/docs/cli/share.mdx b/docs/cli/share.mdx
index d4750788..543a0596 100644
--- a/docs/cli/share.mdx
+++ b/docs/cli/share.mdx
@@ -30,7 +30,7 @@ beacon share --current --harness claude_code --json
beacon share --print
```
-Sharing is always something you ask for. Hooks, plugins and background jobs never upload a session, and nothing else in Beacon uploads session content to beacon.sh except [Beacon Cloud forwarding](/cli/endpoint-connect) when you connect an endpoint. [Auto-share](#auto-share), which you turn on, asks Beacon Cloud to publish sessions from the events forwarding already sends.
+Sharing is always something you ask for. Hooks, plugins and background jobs never upload a session, with one exception you turn on yourself: after [`beacon git setup --share-sessions`](/cli/git#sharing-sessions-on-push), the git pre-push hook shares the sessions linked to the commits you push, during that push, within the hook's time budget and never failing it. Nothing else in Beacon uploads session content to beacon.sh except [Beacon Cloud forwarding](/cli/endpoint-connect) when you connect an endpoint. [Auto-share](#auto-share), which you turn on, asks Beacon Cloud to publish sessions from the events forwarding already sends.
## Choosing the session