The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Merge the share-command fixes, and use the active entry only when it is newest
Claude0effb7aab8a6
diff --cc CLAUDE.mdindex f7fe7dc7,26236fe0..2bc07703--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -69,7 -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), 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`.-- 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.++- 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`.- 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.- 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/share.goindex 8a2eebd5,28bf3b07..58a83bea--- a/cli/beacon/cmd/share.go+++ b/cli/beacon/cmd/share.go@@@ -485,95 -458,53 +485,117 @@@ func resolveShareSubject(harness, id stsources := handoffSources(dirs)switch {case id != "":- session, findErr := handoff.Find(sources, harness, id)- if findErr == nil {- return shareSubject{session: session}, nil- }- // Not in any store, or a store could not be read: the runtime log may have the session.- var notFound *handoff.NotFoundError- isNotFound := errors.As(findErr, ¬Found)- logPath := shareLogPath()- session, events, found, err := handoff.LogSession(logPath, id, harness)- if err != nil {- if !isNotFound {- return shareSubject{}, findErr- }- return shareSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)- }- if !found || (harness != "" && session.Harness != harness) {- if !isNotFound {- return shareSubject{}, findErr- }- return shareSubject{}, fmt.Errorf("%w; not in the runtime log %s either (`beacon share --list` shows what is available)", notFound, logPath)- }- return shareSubject{session: session, fromLog: true, logEvents: events}, nil+ subject, err := resolveShareID(sources, harness, id)+ subject.selectedBy = "session"+ return subject, errcase strings.TrimSpace(shareOpts.sourcePath) != "":- return resolveShareSourcePath(sources, harness, shareOpts.sourcePath)+ subject, err := resolveShareSourcePath(sources, harness, shareOpts.sourcePath)+ subject.selectedBy = "source_path"+ return subject, errdefault:- dir, err := shareDirectory()- if err != nil {- return shareSubject{}, err+ return resolveShareCurrent(sources, harness)+ }+}++// resolveShareID finds a session by id or unique prefix: in the runtimes' stores, then in the+// runtime log.+func resolveShareID(sources []handoff.Source, harness, id string) (shareSubject, error) {+ session, findErr := handoff.Find(sources, harness, id)+ if findErr == nil {+ return shareSubject{session: session}, nil+ }++ // Not in any store, or a store could not be read: the runtime log may have the session.+ var notFound *handoff.NotFoundError- if !errors.As(findErr, ¬Found) {- return shareSubject{}, findErr- }++ isNotFound := errors.As(findErr, ¬Found)+ logPath := shareLogPath()+ session, events, found, err := handoff.LogSession(logPath, id, harness)+ if err != nil {++ if !isNotFound {++ return shareSubject{}, findErr+ }- candidates, err := shareCandidateList(sources, harness, dir, 1)- if err != nil {- return shareSubject{}, err+ return shareSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)+ }+ if !found || (harness != "" && session.Harness != harness) {++ if !isNotFound {++ return shareSubject{}, findErr+ }- if len(candidates) == 0 {- return shareSubject{}, fmt.Errorf("no agent session found in %s; pass --session, or --cwd for another directory (`beacon share --list --cwd DIR`)", dir)+ return shareSubject{}, fmt.Errorf("%w; not in the runtime log %s either (`beacon share --list` shows what is available)", notFound, logPath)+ }+ return shareSubject{session: session, fromLog: true, logEvents: events}, nil+}++// resolveShareCurrent finds the session this command runs inside, in order:+//+// 1. BEACON_SESSION_ID (with BEACON_HARNESS), which the Claude Code hook exports to the agent's+// shell. Skipped under --cwd, which names another directory, and when --harness names another+// runtime (a Codex started from a Claude Code shell inherits Claude's variables). An id that is+// set but cannot be found is an error rather than a reason to share some other session.+// 2. The session a Beacon hook last saw in the directory, from the active-session record.+// 3. The most recent session in the directory.+func resolveShareCurrent(sources []handoff.Source, harness string) (shareSubject, error) {+ dir, err := shareDirectory()+ if err != nil {+ return shareSubject{}, err+ }+ if strings.TrimSpace(shareOpts.cwd) == "" {+ if id := strings.TrimSpace(shareGetenv(shareSessionEnv)); id != "" {+ envHarness, herr := handoff.ParseHarness(shareGetenv(shareHarnessEnv))+ if herr == nil && (harness == "" || envHarness == "" || envHarness == harness) {+ if envHarness == "" {+ envHarness = harness+ }+ subject, err := resolveShareID(sources, envHarness, id)+ if err != nil {+ return shareSubject{}, fmt.Errorf("%s=%s names this session, but it cannot be read yet: %w", shareSessionEnv, id, err)+ }+ subject.selectedBy = "env"+ return subject, nil+ }}- // A session listed by its runtime's store is read from that store; one the store has lost- // or cannot read since falls back to the log when its events are read (shareEvents). A- // session only the log listed is read from the log: its store may be unreadable.- candidate := candidates[0]- if !candidate.fromLog && handoff.ReadsStore(candidate.session.Harness) {- return shareSubject{session: candidate.session}, nil+ }- if entryHarness, entryID, ok := shareActiveSession(dir, harness); ok {++ candidates, err := shareCandidateList(sources, harness, dir, 1)++ if err != nil {++ return shareSubject{}, err++ }++ if entry, ok := shareActiveSession(dir, harness); ok && shareActiveIsNewest(entry, candidates) {+ // A record whose session cannot be read (a runtime Beacon reads only from the log, whose+ // events have rotated away) falls through to the directory's most recent session.- if subject, err := resolveShareID(sources, entryHarness, entryID); err == nil {++ if subject, err := resolveShareID(sources, entry.Harness, entry.SessionID); err == nil {+ subject.selectedBy = "active"+ return subject, nil}- return resolveShareLog(candidate.session)}- candidates, err := shareCandidates(sources, harness, dir, 1)- if err != nil {- return shareSubject{}, err- }+ if len(candidates) == 0 {+ return shareSubject{}, shareNoSessionError(sources, harness, dir)+ }- // A session of a runtime whose store Beacon reads is read from that store; one the store has- // lost since falls back to the log when its events are read (shareEvents).- session := candidates[0]- if handoff.ReadsStore(session.Harness) {- return shareSubject{session: session, selectedBy: "recent"}, nil++ // A session listed by its runtime's store is read from that store; one the store has lost or++ // cannot read since falls back to the log when its events are read (shareEvents). A session++ // only the log listed is read from the log: its store may be unreadable.++ candidate := candidates[0]++ if !candidate.fromLog && handoff.ReadsStore(candidate.session.Harness) {++ return shareSubject{session: candidate.session, selectedBy: "recent"}, nil+ }- subject, err := resolveShareLog(session)++ subject, err := resolveShareLog(candidate.session)+ subject.selectedBy = "recent"+ return subject, err+}+++// shareActiveIsNewest reports whether the active-session entry may stand for this directory's++// session: only hooks write the record, so a runtime Beacon sees only through OTLP or a store (an++// OTLP-only or poll runtime) never updates it, and an older entry would otherwise win over that++// runtime's newer session. The entry is used when it is the newest candidate itself, or was seen at++// least as recently as the newest candidate was updated.++func shareActiveIsNewest(entry activesession.Entry, candidates []shareCandidate) bool {++ if len(candidates) == 0 {++ return true++ }++ newest := candidates[0].session++ if newest.Harness == entry.Harness && newest.ID == entry.SessionID {++ return true++ }++ return !entry.LastSeen.Before(newest.UpdatedAt)+ }+func resolveShareLog(session handoff.Session) (shareSubject, error) {logPath := shareLogPath()found, events, ok, err := handoff.LogSession(logPath, session.ID, session.Harness)@@@ -618,57 -549,6 +640,58 @@@ func evalSymlinks(path string) stringreturn resolved}+// shareActiveSession is the session a Beacon hook last saw in dir, limited to harness when it is+// set, from the active-session record. Entries older than shareActiveMaxAge are ignored.- func shareActiveSession(dir, harness string) (entryHarness, sessionID string, ok bool) {++func shareActiveSession(dir, harness string) (activesession.Entry, bool) {+ entries, err := activesession.Read(shareActiveSessionsPath())+ if err != nil {- return "", "", false++ return activesession.Entry{}, false+ }+ dir = activesession.CleanDir(dir)+ now := shareNow()+ for _, e := range entries {+ if e.WorkingDirectory != dir || now.Sub(e.LastSeen) > shareActiveMaxAge {+ continue+ }+ name, err := handoff.ParseHarness(e.Harness)+ if err != nil || (harness != "" && name != harness) {+ continue+ }- return name, e.SessionID, true++ e.Harness = name++ return e, true+ }- return "", "", false++ return activesession.Entry{}, false+}++// shareNoSessionError explains that nothing ran in dir and names the most recent sessions anywhere,+// so the next command can name one.+func shareNoSessionError(sources []handoff.Source, harness, dir string) error {+ msg := fmt.Sprintf("no agent session found in %s", dir)+ stored, _ := handoff.List(sources, handoff.Filter{Harness: harness, Limit: 5})+ logged, _ := handoff.LogSessions(shareLogPath(), handoff.Filter{Harness: harness, Limit: 5})+ seen := map[string]bool{}+ var all []handoff.Session+ for _, s := range append(stored, logged...) {+ if key := s.Harness + "\x00" + s.ID; !seen[key] {+ seen[key] = true+ all = append(all, s)+ }+ }+ sort.SliceStable(all, func(i, j int) bool { return all[i].UpdatedAt.After(all[j].UpdatedAt) })+ if len(all) > 5 {+ all = all[:5]+ }+ if len(all) == 0 {+ return errors.New(msg + "; Beacon has no sessions recorded yet (is `beacon endpoint install` set up for this runtime?)")+ }+ var b strings.Builder+ b.WriteString(msg + "; recent sessions elsewhere (pass one with --session, or use --cwd DIR):")+ for _, s := range all {+ fmt.Fprintf(&b, "\n %s %s %s", s.Harness, s.ID, s.Directory)+ }+ return errors.New(b.String())+}+// shareCandidates lists the sessions in dir, newest first: those in the runtimes' own stores, then// sessions only Beacon's runtime log has. A store that cannot be read is skipped; the log still// answers for it.diff --cc cli/beacon/cmd/share_current_test.goindex c4754912,00000000..a690fa24mode 100644,000000..100644--- a/cli/beacon/cmd/share_current_test.go+++ b/cli/beacon/cmd/share_current_test.go@@@ -1,134 -1,0 +1,183 @@@+package cmd++import (+ "encoding/json"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/activesession"+)++// shareCurrentEnv adds a second, older Claude Code session and a Gemini CLI session (log only) in+// the project directory, so each resolution step can be told apart from "most recent".+func shareCurrentEnv(t *testing.T) *shareEnv {+ t.Helper()+ env := newShareEnv(t)+ recordPath := filepath.Join(env.home, "active.json")+ prev := shareActiveSessionsPath+ shareActiveSessionsPath = func() string { return recordPath }+ t.Cleanup(func() { shareActiveSessionsPath = prev })+ gem := schema.NewEvent(schema.NewEventOptions{Action: "prompt.submitted", Category: "prompt", Harness: schema.HarnessInfo{Name: "gemini_cli", CollectionMethod: schema.CollectionMethodHook}})+ gem.Timestamp = schema.FormatTimestamp(time.Now().Add(-time.Hour))+ gem.Session = &schema.SessionInfo{ID: "gem-session-1", WorkingDirectory: env.projectDir}+ gem.Prompt = &schema.PromptInfo{Text: "Add a flag"}+ if _, err := writer.AppendEvent(gem, writer.Options{Path: env.logPath, UserMode: true}); err != nil {+ t.Fatal(err)+ }+ return env+}++func sharePrintedExternalID(t *testing.T, stdout string) string {+ t.Helper()+ var payload sharePayload+ if err := json.Unmarshal([]byte(stdout), &payload); err != nil {+ t.Fatalf("payload is not JSON: %v\n%s", err, stdout)+ }+ return payload.ExternalID+}++func TestShareCurrentPrefersTheSessionEnvironment(t *testing.T) {+ env := shareCurrentEnv(t)+ t.Chdir(env.projectDir)+ shareGetenv = func(key string) string {+ switch key {+ case shareSessionEnv:+ return "gem-session-1"+ case shareHarnessEnv:+ return "gemini_cli"+ }+ return ""+ }+ stdout, _, err := runShareCommand(t, "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share: %v", err)+ }+ if got := sharePrintedExternalID(t, stdout); got != "gemini_cli:gem-session-1" {+ t.Fatalf("external id = %q, want the env session", got)+ }++ // --harness naming another runtime ignores inherited variables.+ stdout, _, err = runShareCommand(t, "--current", "--harness", "claude", "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share --harness claude: %v", err)+ }+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {+ t.Fatalf("external id = %q, want the claude session", got)+ }++ // An env id that cannot be found is an error, never some other session.+ shareGetenv = func(key string) string {+ if key == shareSessionEnv {+ return "missing-session"+ }+ return ""+ }+ if _, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath); err == nil || !strings.Contains(err.Error(), "BEACON_SESSION_ID=missing-session") {+ t.Fatalf("missing env session: err = %v", err)+ }+}++func TestShareCurrentUsesTheActiveSessionRecord(t *testing.T) {+ env := shareCurrentEnv(t)+ t.Chdir(env.projectDir)+ // The Claude session is the most recent; the hook last saw Gemini here.+ if err := activesession.Record(shareActiveSessionsPath(), "gemini_cli", "gem-session-1", env.projectDir, time.Now()); err != nil {+ t.Fatal(err)+ }+ stdout, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share --current: %v", err)+ }+ if got := sharePrintedExternalID(t, stdout); got != "gemini_cli:gem-session-1" {+ t.Fatalf("external id = %q, want the active session", got)+ }+ // A --harness hint passes over another runtime's entry.+ stdout, _, err = runShareCommand(t, "--harness", "claude_code", "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share --harness: %v", err)+ }+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {+ t.Fatalf("external id = %q", got)+ }+ // A stale entry is ignored.+ shareNow = func() time.Time { return time.Now().Add(48 * time.Hour) }+ t.Cleanup(func() { shareNow = time.Now })+ stdout, _, err = runShareCommand(t, "--print", "--log-path", env.logPath)+ if err != nil {+ t.Fatalf("share: %v", err)+ }+ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {+ t.Fatalf("stale record used: %q", got)+ }+}++func TestShareCurrentNamesCandidatesWhenNothingRanHere(t *testing.T) {+ env := shareCurrentEnv(t)+ empty := t.TempDir()+ t.Chdir(empty)+ _, _, err := runShareCommand(t, "--current", "--print", "--log-path", env.logPath)+ if err == nil {+ t.Fatal("want an error")+ }+ for _, want := range []string{"no agent session found", shareTestSession, "gem-session-1", "--session"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("error %q lacks %q", err, want)+ }+ }+ if _, _, err := runShareCommand(t, "--current", "--session", shareTestSession, "--print"); err == nil {+ t.Fatal("--current with --session accepted")+ }+}++++func TestShareCurrentPassesOverAnOlderActiveEntry(t *testing.T) {++ env := newShareEnv(t)++ t.Chdir(env.projectDir)++ recordPath := filepath.Join(env.home, "active.json")++ prev := shareActiveSessionsPath++ shareActiveSessionsPath = func() string { return recordPath }++ t.Cleanup(func() { shareActiveSessionsPath = prev })++ hourAgo := time.Now().Add(-time.Hour)++ stubHandoffSources(t, stubHandoffSource{++ harness: handoff.HarnessClaude,++ sessions: []handoff.Session{{++ Harness: handoff.HarnessClaude, ID: shareTestSession, Directory: env.projectDir, UpdatedAt: hourAgo,++ }},++ events: shareFixtureEvents(env.projectDir),++ })++ // The hook saw Claude Code here an hour ago; Copilot CLI, which only exports OTLP and never++ // writes the record, has worked here since.++ if err := activesession.Record(recordPath, handoff.HarnessClaude, shareTestSession, env.projectDir, hourAgo); err != nil {++ t.Fatal(err)++ }++ copilot := schema.NewEvent(schema.NewEventOptions{Action: "prompt.submitted", Category: "prompt", Harness: schema.HarnessInfo{Name: handoff.HarnessCopilot, CollectionMethod: schema.CollectionMethodOTLP}})++ copilot.Timestamp = schema.FormatTimestamp(time.Now().Add(-5 * time.Minute))++ copilot.Session = &schema.SessionInfo{ID: "copilot-session-1", WorkingDirectory: env.projectDir}++ copilot.Prompt = &schema.PromptInfo{Text: "Bump the version"}++ if _, err := writer.AppendEvent(copilot, writer.Options{Path: env.logPath, UserMode: true}); err != nil {++ t.Fatal(err)++ }++ stdout, _, err := runShareCommand(t, "--print", "--log-path", env.logPath)++ if err != nil {++ t.Fatalf("share: %v", err)++ }++ if got := sharePrintedExternalID(t, stdout); got != handoff.HarnessCopilot+":copilot-session-1" {++ t.Fatalf("external id = %q, want the newer Copilot session", got)++ }++++ // Once the hook sees Claude Code again, its entry is the newest and is chosen.++ if err := activesession.Record(recordPath, handoff.HarnessClaude, shareTestSession, env.projectDir, time.Now()); err != nil {++ t.Fatal(err)++ }++ stdout, _, err = runShareCommand(t, "--json", "--print", "--log-path", env.logPath)++ if err != nil {++ t.Fatalf("share: %v", err)++ }++ if got := sharePrintedExternalID(t, stdout); got != "claude_code:"+shareTestSession {++ t.Fatalf("external id = %q, want the active Claude Code session", got)++ }++}diff --cc docs/cli/share.mdxindex 5847ade3,8293e2b4..8b9fb181--- a/docs/cli/share.mdx+++ b/docs/cli/share.mdx@@@ -48,16 -43,6 +48,16 @@@ beacon share --session 5f0c1d2Sessions are read the way [`beacon handoff`](/cli/handoff) reads them: from the runtime's own session store when Beacon reads that runtime's store, which keeps the most of each step, and otherwise from Beacon's runtime log. `--store-dir <runtime>=<path>` reads a store from another location, and `--log-path` reads another runtime log.+## Sharing this session++An agent asked to "share this session" runs `beacon share` from its own shell, where it does not know its session id. `--current`, which is also what `beacon share` does with no selector, finds it in this order:++1. **`BEACON_SESSION_ID`** (with `BEACON_HARNESS`). Beacon's Claude Code `SessionStart` hook appends `export BEACON_SESSION_ID=<id>` and `export BEACON_HARNESS=claude_code` to the file Claude Code names in `CLAUDE_ENV_FILE`, which Claude Code runs before each shell command of the session, so every command the agent runs carries its session id. Any other launcher may set the two variables too. The step is skipped under `--cwd`, and when `--harness` names another runtime, because a runtime started from a Claude Code shell inherits Claude Code's variables. An id that is set but cannot be read is an error, never a reason to share another session.- 2. **The active-session record.** Every Beacon hook notes, per runtime and working directory, the session it last saw, in `~/.beacon/endpoint/active-sessions.json` (0600 under a 0700 directory). The record holds session ids, runtime names, directories and times, never content, and nothing in it leaves the machine. It keeps at most 256 entries and drops any not seen for 14 days; `--current` uses an entry seen within the last day.++2. **The active-session record.** Every Beacon hook notes, per runtime and working directory, the session it last saw, in `~/.beacon/endpoint/active-sessions.json` (0600 under a 0700 directory). The record holds session ids, runtime names, directories and times, never content, and nothing in it leaves the machine. It keeps at most 256 entries and drops any not seen for 14 days; `--current` uses an entry seen within the last day, and only when it was seen at least as recently as the directory's newest session was updated: only hooks write the record, so a runtime Beacon sees only through OTLP or its session store (GitHub Copilot CLI, fx) never updates it, and its newer session wins over an older entry.+3. **The most recent session** that ran in the directory.++`--harness` narrows every step to one runtime, which matters when two runtimes worked in the same directory. When nothing ran in the directory, the error names the most recent sessions elsewhere so one can be passed with `--session`. `--json` reports how the session was chosen in `selected_by`: `env`, `active`, `recent`, `session` or `source_path`.+## What is uploadedA shared trace is a `beacon.trace.v1` trace: the same projection of the session's Beacon events that the local [dashboard](/cli/dashboard) and [lenses](/concepts/lenses) read. It has two parts: