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 contract into the local sharing views

Claude65e23e58bae6
diff --cc CLAUDE.md
index 90f48433,f4f0a2f8..ce957ed9
--- 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. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the projected messages' fingerprint changed, stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` once at the start and once at the end; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples. Local views show sharing read-only: the trace summary (`traceAggregate`, and the history through `traceAggregateState`, derivation version 5) and the dashboard's `SessionRecord.Sharing` mark a shared session `stale` when an event other than Beacon's bookkeeping (`session.shared`, `session.share_requested`, `session.commit_linked`) is newer than its last `session.shared` record, and carry `asymptoteobserve.ShareRefreshCommand` for the reader to copy; the session list/page, `beacon traces` TUI and plain list display them, and nothing in them shares.
+ - Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background, except the opted-in pre-push sharing below. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own (and an off marker wins over the user's entry for the same directory; the closest directory with an entry or marker decides) but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.
-- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes on a fresh 1 s and pushes the notes ref on a fresh 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples.
++- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes on a fresh 1 s and pushes the notes ref on a fresh 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples. Local views show sharing read-only: the trace summary (`traceFold`, which wraps `asymptoteobserve.TraceBuilder` with the local-only `traceStaleness`, and the history through `traceAggregateState`, derivation version 12) and the dashboard's `SessionRecord.Sharing` mark a shared session `stale` when an event `asymptoteobserve.ShareProjects` accepts (the one definition of what a share publishes) and that is not the share's own (`shareActivity`) is newer than what its last `session.shared` record covered (`shared_through`), and carry `asymptoteobserve.ShareRefreshCommand` for the reader to copy; the session list/page, `beacon traces` TUI and plain list display them, and nothing in them shares.
- 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/internal/endpoint/dashboard/history_ingest.go
index c3290e09,3208f072..6eb21c59
--- a/cli/beacon/internal/endpoint/dashboard/history_ingest.go
+++ b/cli/beacon/internal/endpoint/dashboard/history_ingest.go
@@@ -607,7 -607,7 +607,7 @@@ func (p *historyPass) foldTrace(traceKe
if err != nil {
return err
}
- var agg *traceAggregate
- var agg *asymptoteobserve.TraceBuilder
++ var agg *traceFold
base := 0
var existing []*historyEvent
if state.exists {
@@@ -728,17 -728,17 +728,17 @@@ func decodeStoredEvent(compressed []byt
type traceFolder struct {
pass *historyPass
traceKey string
- agg *traceAggregate
- agg *asymptoteobserve.TraceBuilder
++ agg *traceFold
seq int
}
func (f *traceFolder) fold(ev *historyEvent) error {
f.seq++
if f.agg == nil {
- f.agg = newTraceAggregate(f.traceKey, ev.event)
- f.agg = asymptoteobserve.NewTraceBuilder(f.traceKey, ev.event)
++ f.agg = newTraceFold(f.traceKey, ev.event)
}
te := traceEventFromRecord(EventRecord{ID: ev.recordID, Event: ev.event}, f.seq)
- f.agg.update(ev.event, te)
- f.agg.Fold(ev.event, te)
++ f.agg.fold(ev.event, te)
if ev.seq != f.seq {
if _, err := f.pass.updateSeq.Exec(f.seq, ev.id); err != nil {
return err
@@@ -760,9 -760,9 +760,9 @@@
func (f *traceFolder) finish(previous historyTraceState) error {
p := f.pass
- summary := f.agg.finishedSummary()
- summary := f.agg.Summary()
++ summary := f.agg.summary()
hay := strings.ToLower(traceSummaryHaystack(summary))
- state, err := json.Marshal(f.agg.State())
+ state, err := json.Marshal(f.agg.state())
if err != nil {
return err
}
@@@ -795,59 -795,15 +795,16 @@@
return err
}
- // traceAggregateState is a trace's running aggregate between catch-ups: the summary before finish()
- // and the sets finish() reads. finish() runs on a copy each time a summary is read, so it never
- // feeds back into the running state.
- type traceAggregateState struct {
- Summary TraceSummaryV1 `json:"summary"`
- Models []string `json:"models,omitempty"`
- Methods []string `json:"methods,omitempty"`
- TitlePriority int `json:"title_priority"`
- LastActivity string `json:"last_activity,omitempty"`
- LastShareRecord string `json:"last_share_record,omitempty"`
- Share shareActivity `json:"share,omitempty"`
- }
-
- func (a *traceAggregate) state() traceAggregateState {
- return traceAggregateState{
- Summary: a.summary,
- Models: sortedKeys(a.models),
- Methods: sortedKeys(a.methods),
- TitlePriority: a.titlePriority,
- LastActivity: a.lastActivity,
- LastShareRecord: a.lastShareRecord,
- Share: a.share,
- }
- }
-
- func decodeTraceAggregate(raw string) (*traceAggregate, error) {
-// The aggregate column and trace checkpoints hold asymptoteobserve.TraceBuilderState: a trace's
-// running state between catch-ups, the summary before Summary() finishes it and the sets finishing
-// reads. Summary() works on a copy, so reading a summary never feeds back into the running state.
-func decodeTraceAggregate(raw string) (*asymptoteobserve.TraceBuilder, error) {
- var state asymptoteobserve.TraceBuilderState
++// The aggregate column and trace checkpoints hold traceAggregateState: a trace's running state
++// between catch-ups (asymptoteobserve.TraceBuilderState, the summary before Summary() finishes it
++// and the sets finishing reads) and its sharing staleness. Finishing works on a copy, so reading a
++// summary never feeds back into the running state.
++func decodeTraceAggregate(raw string) (*traceFold, error) {
+ var state traceAggregateState
if err := json.Unmarshal([]byte(raw), &state); err != nil {
return nil, err
}
- agg := &traceAggregate{
- summary: state.Summary,
- spans: map[string]*TraceSpanV1{},
- models: map[string]bool{},
- methods: map[string]bool{},
- titlePriority: state.TitlePriority,
- lastActivity: state.LastActivity,
- lastShareRecord: state.LastShareRecord,
- share: state.Share,
- }
- for _, model := range state.Models {
- agg.models[model] = true
- }
- for _, method := range state.Methods {
- agg.methods[method] = true
- }
- return agg, nil
- }
-
- func (a *traceAggregate) finishedSummary() TraceSummaryV1 {
- copied := *a
- copied.finish()
- return copied.summary
- return asymptoteobserve.RestoreTraceBuilder(state), nil
++ return &traceFold{builder: asymptoteobserve.RestoreTraceBuilder(state.TraceBuilderState), stale: state.traceStaleness}, nil
}
func finishedSummaryFromState(raw string) (TraceSummaryV1, error) {
@@@ -855,7 -811,7 +812,7 @@@
if err != nil {
return TraceSummaryV1{}, err
}
- return agg.finishedSummary(), nil
- return agg.Summary(), nil
++ return agg.summary(), nil
}
// rebuildHistoryDerived recomputes every derived column, the search index and the summaries from
diff --cc cli/beacon/internal/endpoint/dashboard/history_store.go
index 4901dfe0,cdfcf46a..7745cbb7
--- a/cli/beacon/internal/endpoint/dashboard/history_store.go
+++ b/cli/beacon/internal/endpoint/dashboard/history_store.go
@@@ -41,7 -41,7 +41,7 @@@ const
// historyDerivationVersion covers everything computed from a stored line: trace keys, event
// numbers, types, summaries and search text. Bump it when that projection changes; the next
// catch-up recomputes it from the stored lines, so history survives the change.
- historyDerivationVersion = 11 // 2: trace events carry the event's policy block; 3: and its error; 4: usage carries the 1h cache-write split; 5: sharing goes stale on newer activity and carries a refresh command; 6: staleness compares against what a share covered (shared_through); 7: a share's own events (its command, the reply about it) do not make it stale; 8: only when the session holds the share call; 9: and the turn-end event after it; 10: events the share projection skips never count; 11: a share call is beacon share in command position
- historyDerivationVersion = 6 // 2: trace events carry the event's policy block; 3: and its error; 4: usage carries the 1h cache-write split; 5: agent.response is an agent message; 6: the summary names its project
++ historyDerivationVersion = 12 // 2: trace events carry the event's policy block; 3: and its error; 4: usage carries the 1h cache-write split; 5: agent.response is an agent message; 6: the summary names its project; 7-11 were the sharing-staleness steps on a parallel branch; 12: sharing goes stale on activity after what a share covered (shared_through), ignoring a share's own events and events the share projection skips, and carries a refresh command
defaultHistoryRetentionDays = 90
// maxHistoryRetentionDays is 100 years: a retention this long or longer means nothing expires.
diff --cc cli/beacon/internal/endpoint/dashboard/traces.go
index ecdeb818,5cd65b5e..6f8c19ca
--- a/cli/beacon/internal/endpoint/dashboard/traces.go
+++ b/cli/beacon/internal/endpoint/dashboard/traces.go
@@@ -59,46 -59,13 +59,115 @@@ type TraceQuery struct
After int
}
+ // traceAggregate is one projected trace as the JSONL scan answers from it: its finished summary
+ // and its events, built by asymptoteobserve.TraceBuilder.
type traceAggregate struct {
- summary TraceSummaryV1
- events []TraceEventV1
- spans map[string]*TraceSpanV1
- models map[string]bool
- methods map[string]bool
- titlePriority int
- // lastActivity is the newest timestamp of an event the session itself produced, and
- // lastShareRecord the newest point a session.shared record covered (its shared_through, else
- // its timestamp); a shared trace whose session has activity after that is stale.
- lastActivity string
- lastShareRecord string
- // share tells the share's own events (a share made from inside the session) from activity.
- share shareActivity
+ summary TraceSummaryV1
+ events []TraceEventV1
+ }
+
++// traceFold is a trace being folded: asymptoteobserve.TraceBuilder, which projects the summary
++// every reader shares, and the local view's sharing staleness, which only local views show. The
++// JSONL scan and the history fold both go through it, so they answer alike.
++type traceFold struct {
++ builder *asymptoteobserve.TraceBuilder
++ stale traceStaleness
++}
++
++func newTraceFold(id string, first schema.Event) *traceFold {
++ return &traceFold{builder: asymptoteobserve.NewTraceBuilder(id, first)}
++}
++
++// add numbers and keeps te, and folds event into the summary and the staleness.
++func (f *traceFold) add(event schema.Event, te TraceEventV1) {
++ f.builder.Add(event, te)
++ f.stale.observe(event)
++}
++
++// fold folds event without keeping its projection, for the history, which stores events itself.
++func (f *traceFold) fold(event schema.Event, te TraceEventV1) {
++ f.builder.Fold(event, te)
++ f.stale.observe(event)
++}
++
++// summary is the finished summary with the sharing staleness applied. Neither changes the fold.
++func (f *traceFold) summary() TraceSummaryV1 {
++ summary := f.builder.Summary()
++ f.stale.apply(&summary)
++ return summary
++}
++
++// traceAggregateState is what the history stores of a fold between catch-ups: the builder's state
++// and the staleness, in one JSON object.
++type traceAggregateState struct {
++ asymptoteobserve.TraceBuilderState
++ traceStaleness
++}
++
++func (f *traceFold) state() traceAggregateState {
++ return traceAggregateState{TraceBuilderState: f.builder.State(), traceStaleness: f.stale}
++}
++
++// traceStaleness tells whether a shared trace is behind its session: lastActivity is the newest
++// timestamp of an event the session itself produced, and lastShareRecord the newest point a
++// session.shared record covered (its shared_through, else its timestamp); a shared trace whose
++// session has activity after that is stale. share tells the share's own events (a share made from
++// inside the session) from activity.
++type traceStaleness struct {
++ LastActivity string `json:"last_activity,omitempty"`
++ LastShareRecord string `json:"last_share_record,omitempty"`
++ Share shareActivity `json:"share,omitempty"`
++}
++
++func (s *traceStaleness) observe(event schema.Event) {
++ if event.Event.Action == "session.shared" {
++ // What the upload covered (shared_through, when the session was read for it), or the
++ // record's own time for a record from before that field.
++ s.LastShareRecord = laterTimestamp(s.LastShareRecord, firstNonEmpty(rawString(event.Raw, "shared_through"), event.Timestamp))
++ }
++ if s.Share.counts(event) {
++ s.LastActivity = laterTimestamp(s.LastActivity, event.Timestamp)
++ }
++}
++
++// apply marks a shared summary stale when the session has activity after what the share covered,
++// and gives it the refresh command a reader can copy.
++func (s traceStaleness) apply(summary *TraceSummaryV1) {
++ if summary.Sharing.URL == "" {
++ return
++ }
++ if s.LastShareRecord != "" && s.LastActivity != "" && laterTimestamp(s.LastShareRecord, s.LastActivity) != s.LastShareRecord {
++ summary.Sharing.State = "stale"
++ }
++ if summary.Session != nil {
++ summary.Sharing.RefreshCommand = asymptoteobserve.ShareRefreshCommand(summary.Harness.Name, summary.Session.ID)
++ }
+}
+
+// shareBookkeeping is an event Beacon writes into a session's timeline about the session, rather
+// than activity of the session: it never makes a shared trace stale.
+func shareBookkeeping(action string) bool {
+ return action == "session.shared" || action == "session.share_requested" || action == "session.commit_linked"
+}
+
+func laterTimestamp(a, b string) string {
+ if b == "" {
+ return a
+ }
+ if a == "" {
+ return b
+ }
+ ta, errA := schema.ParseTimestamp(a)
+ tb, errB := schema.ParseTimestamp(b)
+ if errA != nil {
+ return b
+ }
+ if errB != nil || !tb.After(ta) {
+ return a
+ }
+ return b
+}
+
// The local history, once the user has opted in to it, answers the same
// question the JSONL scan below answers, over a longer window: it keeps what
// rotation deletes. Any error -- no history, a query it does not support, an
@@@ -272,21 -239,20 +341,20 @@@ func readTraceAggregates(path string, q
return nil, err
}
SortRecordsAppendOrder(result.Events)
- traces := map[string]*traceAggregate{}
- builders := map[string]*asymptoteobserve.TraceBuilder{}
++ folds := map[string]*traceFold{}
for _, record := range result.Events {
event := record.Event
id := traceProjectionID(event)
- agg := traces[id]
- if agg == nil {
- agg = newTraceAggregate(id, event)
- traces[id] = agg
- builder := builders[id]
- if builder == nil {
- builder = asymptoteobserve.NewTraceBuilder(id, event)
- builders[id] = builder
++ fold := folds[id]
++ if fold == nil {
++ fold = newTraceFold(id, event)
++ folds[id] = fold
}
- te := traceEventFromRecord(record, len(agg.events)+1)
- agg.events = append(agg.events, te)
- agg.update(event, te)
- builder.Add(event, traceEventFromRecord(record, 0))
++ fold.add(event, traceEventFromRecord(record, 0))
}
- for _, agg := range traces {
- agg.finish()
- traces := make(map[string]*traceAggregate, len(builders))
- for id, builder := range builders {
- traces[id] = &traceAggregate{summary: builder.Summary(), events: builder.Events()}
++ traces := make(map[string]*traceAggregate, len(folds))
++ for id, fold := range folds {
++ traces[id] = &traceAggregate{summary: fold.summary(), events: fold.builder.Events()}
}
return traces, nil
}
@@@ -573,318 -264,15 +366,25 @@@ func traceEventFromRecord(record EventR
}
func traceProjectionID(event schema.Event) string {
- if event.Trace != nil && strings.TrimSpace(event.Trace.ID) != "" {
- id := strings.TrimSpace(event.Trace.ID)
- if strings.HasPrefix(id, "session:") || strings.HasPrefix(id, "trace:") || strings.HasPrefix(id, "event:") {
- return id
- }
- return "trace:" + id
- }
- if event.Session != nil && strings.TrimSpace(event.Session.ID) != "" {
- harness := asymptoteobserve.NormalizeHarnessName(event.Harness.Name)
- if harness == "" {
- harness = strings.TrimSpace(event.Harness.Name)
- }
- return "session:" + harness + ":" + strings.TrimSpace(event.Session.ID)
- }
- if event.Event.ID != "" {
- return "event:" + event.Event.ID
- }
- return "event:" + event.Timestamp + ":" + event.Event.Action + ":" + event.Message
- }
-
- func traceEventType(event schema.Event) string {
- action := strings.ToLower(event.Event.Action)
- category := strings.ToLower(event.Event.Category)
- switch {
- case category == "prompt" || strings.HasPrefix(action, "prompt."):
- return "user_message"
- case action == "agent.reasoning" || strings.Contains(action, "reasoning"):
- return "agent_reasoning"
- case action == "agent.message" || action == "assistant.message":
- return "agent_message"
- case strings.HasPrefix(action, "tool.invoked") || action == "tool.started":
- return "tool_call"
- case strings.HasPrefix(action, "tool.") || category == "tool":
- return "tool_result"
- case category == "command" || event.Command != nil:
- return "command"
- case category == "file" || event.File != nil:
- return "file"
- case category == "mcp" || event.MCP != nil:
- return "mcp"
- case category == "approval" || event.Approval != nil || event.Policy != nil:
- return "approval"
- case category == "metric" && event.GenAI != nil && event.GenAI.Usage != nil:
- return "token_usage"
- case category == "session":
- return "session"
- case strings.Contains(action, "error") || event.Error != nil:
- return "error"
- default:
- return "other"
- }
- }
-
- func traceActor(event schema.Event) string {
- switch traceEventType(event) {
- case "user_message":
- return "user"
- case "agent_message", "agent_reasoning":
- return "assistant"
- case "tool_call", "tool_result", "command", "file", "mcp":
- return "tool"
- default:
- if strings.HasPrefix(event.Event.Action, "endpoint.") || strings.HasPrefix(event.Event.Action, "telemetry.") {
- return "beacon"
- }
- return "runtime"
- }
+ return asymptoteobserve.TraceProjectionID(event)
}
- // traceTitlePriority ranks an event as a source for the trace title and
- // preview. A trace usually opens on lifecycle noise (session.started,
- // session.context), so a later user prompt outranks it and takes the label;
- // ties keep the earlier event, so the first prompt names the trace. The
- // aggregate seeds this at -1 rather than 0, so a trace that only ever carries
- // lifecycle events is still named by its first one rather than falling back to
- // its raw trace ID in finish().
- func traceTitlePriority(event TraceEventV1) int {
- switch event.Type {
- case "user_message":
- return 2
- case "session", "other":
- return 0
- default:
- return 1
- }
- }
-
- func traceTitle(event schema.Event, traceEvent TraceEventV1) string {
- content := ""
- if traceEvent.Content != nil {
- content = traceEvent.Content.Text
- }
- for _, value := range []string{content, traceEvent.Title, traceEvent.Summary, event.Message} {
- if trimmed := strings.TrimSpace(value); trimmed != "" {
- return truncateString(trimmed, 80)
- }
- }
- return traceEvent.Type
- }
-
- func tracePreview(event TraceEventV1) string {
- if event.Content != nil && event.Content.Text != "" {
- return truncateString(event.Content.Text, 160)
- }
- return truncateString(firstNonEmpty(event.Summary, event.Title), 160)
- }
-
- func traceEventTitle(event schema.Event) string {
- switch {
- case event.Command != nil && event.Command.Command != "":
- return event.Command.Command
- case event.File != nil && event.File.Path != "":
- return event.File.Path
- case event.MCP != nil && (event.MCP.Server != "" || event.MCP.Tool != ""):
- return strings.Trim(strings.Join([]string{event.MCP.Server, event.MCP.Tool}, " "), " ")
- case event.Tool != nil && event.Tool.Name != "":
- return event.Tool.Name
- default:
- return event.Event.Action
- }
- }
-
- func eventContent(event schema.Event) *TraceContentV1 {
- if event.Prompt != nil && event.Prompt.Text != "" {
- return contentFromText(event.Prompt.Text, event.Content)
- }
- var partType string
- switch traceEventType(event) {
- case "agent_message":
- partType = asymptoteobserve.GenAIPartTypeText
- case "agent_reasoning":
- partType = asymptoteobserve.GenAIPartTypeReasoning
- }
- if partType != "" {
- // The retained turn text lives in gen_ai.output.messages; event.Message on
- // these events is usually a fixed label ("Codex assistant message"). The
- // label stays the event summary, and is the content only when no text was
- // retained.
- if text := retainedOutputText(event.GenAI, partType); text != "" {
- return retainedOutputContent(text, event.Content)
- }
- if event.Message != "" {
- return contentFromText(event.Message, event.Content)
- }
- }
- return contentFromContentInfo(event.Content)
- }
-
- // retainedOutputContent is contentFromText for text read back out of
- // gen_ai.output.messages. The writer already redacted and bounded each stored
- // part, but an event can carry several parts, so the joined text is held to the
- // same limit prompt.text is stored at and redacted again; the marker records
- // either change so a reader can still tell the copy was altered.
- func retainedOutputContent(text string, info *schema.ContentInfo) *TraceContentV1 {
- bounded := asymptoteobserve.TruncateString(text, asymptoteobserve.DefaultStringLimit)
- cleaned := asymptoteobserve.RedactString(bounded)
- content := contentFromText(cleaned, info)
- if bounded != text {
- content.Truncated = true
- }
- if cleaned != bounded {
- content.Redacted = true
- }
- return content
- }
-
- // RetainedOutputText is retainedOutputText for readers outside the dashboard, such as the handoff
- // brief, so every reader agrees on which parts are what the assistant said.
+ // RetainedOutputText is asymptoteobserve.RetainedOutputText, for readers that reach it through
+ // the dashboard, such as the handoff brief.
func RetainedOutputText(genAI *schema.GenAIInfo, partType string) string {
- return retainedOutputText(genAI, partType)
- }
-
- // retainedOutputText joins the assistant parts of partType in
- // gen_ai.output.messages, in order, as asymptoteobserve.GenAIText reads them.
- // Parts of another type -- reasoning on a message event, tool calls -- are
- // skipped, so an assistant message never shows its reasoning as what it said.
- func retainedOutputText(genAI *schema.GenAIInfo, partType string) string {
- if genAI == nil || genAI.Output == nil {
- return ""
- }
- return strings.Join(asymptoteobserve.GenAIText(genAI.Output.Messages, asymptoteobserve.RoleAssistant, partType), "\n\n")
- }
-
- func contentFromText(text string, info *schema.ContentInfo) *TraceContentV1 {
- content := contentFromContentInfo(info)
- if content == nil {
- content = &TraceContentV1{Retention: "full", Included: true}
- }
- content.Text = text
- if content.Retention == "" {
- content.Retention = "full"
- }
- content.Included = true
- return content
- }
-
- func contentFromContentInfo(info *schema.ContentInfo) *TraceContentV1 {
- if info == nil {
- return nil
- }
- return &TraceContentV1{
- Retention: info.Retention,
- Included: info.Included,
- Redacted: info.Redacted,
- Truncated: info.Truncated,
- Hash: info.Hash,
- Bytes: info.Bytes,
- }
- }
-
- func traceTool(event schema.Event) *TraceToolV1 {
- tool := &TraceToolV1{}
- if event.Tool != nil {
- tool.Name = event.Tool.Name
- tool.Command = event.Tool.Command
- tool.Path = event.Tool.Path
- }
- if event.GenAI != nil && event.GenAI.Tool != nil {
- if tool.Name == "" {
- tool.Name = event.GenAI.Tool.Name
- }
- if event.GenAI.Tool.Call != nil {
- tool.Arguments = event.GenAI.Tool.Call.Arguments
- tool.Result = event.GenAI.Tool.Call.Result
- }
- }
- return tool
- }
-
- func traceUsage(event schema.Event) *TraceUsageV1 {
- if event.GenAI == nil || event.GenAI.Usage == nil {
- return nil
- }
- usage := event.GenAI.Usage
- out := &TraceUsageV1{}
- if usage.InputTokens != nil {
- out.InputTokens = *usage.InputTokens
- }
- if usage.OutputTokens != nil {
- out.OutputTokens = *usage.OutputTokens
- }
- if usage.CacheRead != nil && usage.CacheRead.InputTokens != nil {
- out.CacheReadInputTokens = *usage.CacheRead.InputTokens
- }
- if usage.CacheCreation != nil && usage.CacheCreation.InputTokens != nil {
- out.CacheCreationInputTokens = *usage.CacheCreation.InputTokens
- out.CacheCreation1hInputTokens = usage.CacheCreation.OneHourInputTokens()
- }
- if usage.Reasoning != nil && usage.Reasoning.OutputTokens != nil {
- out.ReasoningOutputTokens = *usage.Reasoning.OutputTokens
- }
- if usage.CostUSD != nil {
- out.CostUSD = *usage.CostUSD
- }
- if traceUsageEmpty(*out) {
- return nil
- }
- return out
- }
-
- func traceUsageEmpty(u TraceUsageV1) bool {
- return u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadInputTokens == 0 && u.CacheCreationInputTokens == 0 && u.ReasoningOutputTokens == 0 && u.CostUSD == 0
- }
-
- func addTraceUsage(u *TraceUsageV1, delta TraceUsageV1) {
- u.InputTokens += delta.InputTokens
- u.OutputTokens += delta.OutputTokens
- u.CacheReadInputTokens += delta.CacheReadInputTokens
- u.CacheCreationInputTokens += delta.CacheCreationInputTokens
- u.CacheCreation1hInputTokens += delta.CacheCreation1hInputTokens
- u.ReasoningOutputTokens += delta.ReasoningOutputTokens
- u.CostUSD += delta.CostUSD
- }
-
- func updateContentSummary(summary *TraceContentSummaryV1, info *schema.ContentInfo) {
- if summary.Retention == "" {
- summary.Retention = "metadata"
- }
- if info == nil {
- return
- }
- switch {
- case info.Redacted:
- summary.HasRedactions = true
- case info.Truncated:
- summary.HasTruncations = true
- }
- if info.Truncated {
- summary.HasTruncations = true
- }
- if summary.Retention == "mixed" || info.Retention == "" {
- return
- }
- if summary.Retention == "metadata" && info.Retention != "metadata" {
- summary.Retention = info.Retention
- return
- }
- if summary.Retention != info.Retention {
- summary.Retention = "mixed"
- }
+ return asymptoteobserve.RetainedOutputText(genAI, partType)
}
+// sharingStateMatches is the --state filter. "stale" is a kind of "shared" (published, with newer
+// local activity), so asking for shared sessions includes stale ones and "stale" narrows to them.
+// The history query (sharingCondition) applies the same rule.
+func sharingStateMatches(state, want string) bool {
+ if strings.EqualFold(want, "shared") {
+ return strings.EqualFold(state, "shared") || strings.EqualFold(state, "stale")
+ }
+ return strings.EqualFold(state, want)
+}
+
func filterTraceSummaries(traces map[string]*traceAggregate, query TraceQuery) []TraceSummaryV1 {
out := make([]TraceSummaryV1, 0, len(traces))
for _, agg := range traces {
diff --cc pkg/asymptoteobserve/share.go
index 23301574,0a00f354..2d31ecff
--- a/pkg/asymptoteobserve/share.go
+++ b/pkg/asymptoteobserve/share.go
@@@ -29,25 -33,6 +33,22 @@@ type ShareInfo struct
Visibility string `json:"visibility,omitempty"`
}
+// ShareRefreshCommand is the command that refreshes harness's shared session: by external id when
+// that names the session plainly, and otherwise by session id and runtime.
+func ShareRefreshCommand(harness, sessionID string) string {
+ harness, sessionID = strings.TrimSpace(harness), strings.TrimSpace(sessionID)
+ if harness == "" || sessionID == "" {
+ return ""
+ }
+ if id := ShareExternalID(harness, sessionID); !strings.Contains(id, ":sha256-") {
+ return "beacon share refresh " + id
+ }
+ if strings.ContainsAny(sessionID, " \t\n'\"$`\\;&|<>()") {
+ return ""
+ }
+ return "beacon share refresh --harness " + NormalizeHarnessName(harness) + " " + sessionID
+}
+
- // ShareSchemaVersion names the wire contract.
- const ShareSchemaVersion = "beacon.share.v1"
-
// Visibility levels of a shared trace. Direct is the default: anyone with the link.
const (
ShareVisibilityPublic = "public"
diff --cc pkg/asymptoteobserve/share_test.go
index ab070415,940b4481..35ab3c67
--- a/pkg/asymptoteobserve/share_test.go
+++ b/pkg/asymptoteobserve/share_test.go
@@@ -617,45 -673,385 +673,438 @@@ func TestShareMessagesPairsPromptCaptur
}
}
- // ShareProjects agrees with BuildShareMessages: every event it rejects yields no message, even with
- // content that would otherwise be shared, and the events it accepts are the ones the projection
- // writes.
- func TestShareProjectsAgreesWithBuildShareMessages(t *testing.T) {
+ // shareFieldEvents is one session whose events put the sharer's home directory in every kind of
+ // field the trace projection reads.
+ func shareFieldEvents() []Event {
+ prompt := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ prompt.Event.ID = "f-prompt"
+ prompt.Prompt = &PromptInfo{ID: "p1", Text: "read /home/dev/notes/todo.md"}
+ prompt.Repository = "/home/dev/src/app"
+
+ cmd := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "command.executed", "command")
+ cmd.Event.ID = "f-cmd"
+ cmd = withCall(cmd, "toolu_c", "Bash", map[string]interface{}{"command": "cat /home/dev/.config/app.toml"}, nil)
+ cmd.Tool.Command = "cat /home/dev/.config/app.toml"
+ cmd.Command = &CommandInfo{Command: "cat /home/dev/.config/app.toml", ExitCode: intPtr(1), Output: "cat: /home/dev/.config/app.toml: No such file"}
+ cmd.Message = "ran cat /home/dev/.config/app.toml"
+
+ edit := shareEventAt("2026-10-01T10:00:02Z", "claude_code", CollectionMethodHook, "file.modified", "file")
+ edit.Event.ID = "f-edit"
+ edit = withCall(edit, "toolu_e", "Edit", map[string]interface{}{"file_path": "/home/dev/src/app/main.go", "nested": []interface{}{map[string]interface{}{"p": "/home/dev/x"}}}, map[string]interface{}{"path": "/home/dev/src/app/main.go"})
+ edit.Tool.Path = "/home/dev/src/app/main.go"
+ edit.File = &FileInfo{Path: "/home/dev/src/app/main.go", Operation: "modify", Diff: "--- /home/dev/src/app/main.go\n+++ /home/dev/src/app/main.go\n"}
+
+ mcp := shareEventAt("2026-10-01T10:00:03Z", "claude_code", CollectionMethodHook, "mcp.tool_invoked", "mcp")
+ mcp.Event.ID = "f-mcp"
+ mcp = withCall(mcp, "toolu_m", "mcp__fs__read", map[string]interface{}{"path": "/home/dev/secret.txt"}, []interface{}{map[string]interface{}{"type": "text", "text": "from /home/dev/secret.txt"}})
+ mcp.MCP = &MCPInfo{Server: "fs", Tool: "read", Resource: &MCPResourceInfo{URI: "file:///home/dev/secret.txt"}}
+
+ approval := shareEventAt("2026-10-01T10:00:04Z", "claude_code", CollectionMethodHook, "approval.denied", "approval")
+ approval.Event.ID = "f-approval"
+ approval.Approval = &ApprovalInfo{Required: true, Decision: "deny", Reason: "writes to /home/dev/.ssh"}
+ approval.Policy = &PolicyInfo{Name: "home /home/dev guard", Decision: "deny", Reason: "path /home/dev/.ssh is protected"}
+
+ failure := shareEventAt("2026-10-01T10:00:05Z", "claude_code", CollectionMethodHook, "session.error", "session")
+ failure.Event.ID = "f-error"
+ failure.Message = "open /home/dev/src/app/go.mod: permission denied"
+ failure.Error = &ErrorInfo{Type: "/home/dev/bin/tool exited"}
+
+ answer := shareEventAt("2026-10-01T10:00:06Z", "claude_code", CollectionMethodHook, "agent.message", "agent")
+ answer.Event.ID = "f-answer"
+ answer.GenAI = &GenAIInfo{Output: &GenAIOutputInfo{Messages: TextOutputMessages("I changed /home/dev/src/app/main.go")}}
+ answer.Raw = map[string]interface{}{"cwd": "/home/dev/src/app"}
+
+ return []Event{prompt, cmd, edit, mcp, approval, failure, answer}
+ }
+
+ // Every field the shared bundle carries is scrubbed of the sharer's home and session directory:
+ // command lines and output, file paths and diffs, tool arguments and results, MCP fields, approval
+ // and policy text, errors, retained text, the working directory and the repository.
+ func TestShareBundleScrubsEveryFieldType(t *testing.T) {
+ events := shareFieldEvents()
+ bundle := BuildShareBundle(events, shareTestOpts)
+ data, err := json.Marshal(bundle)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(data), "/home/dev") {
+ t.Fatalf("a local path reached the bundle: %s", data)
+ }
+ messages, err := json.Marshal(TraceMessages(bundle))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(messages), "/home/dev") {
+ t.Fatalf("a local path reached the messages: %s", messages)
+ }
+ byID := map[string]TraceEventV1{}
+ for _, event := range bundle.Events {
+ byID[event.ID] = event
+ }
+ checks := map[string]string{
+ "prompt": byID["f-prompt"].Content.Text,
+ "command": byID["f-cmd"].Command.Command,
+ "command output": byID["f-cmd"].Command.Output.Text,
+ "tool command": byID["f-cmd"].Tool.Command,
+ "tool argument": fmt.Sprint(byID["f-cmd"].Tool.Arguments),
+ "message": byID["f-cmd"].Summary,
+ "file path": byID["f-edit"].File.Path,
+ "file title": byID["f-edit"].Title,
+ "tool path": byID["f-edit"].Tool.Path,
+ "diff": byID["f-edit"].File.Diff.Text,
+ "nested argument": fmt.Sprint(byID["f-edit"].Tool.Arguments),
+ "tool result": fmt.Sprint(byID["f-edit"].Tool.Result),
+ "mcp argument": fmt.Sprint(byID["f-mcp"].Tool.Arguments),
+ "mcp result": fmt.Sprint(byID["f-mcp"].Tool.Result),
+ "mcp resource": byID["f-mcp"].MCP.ResourceURI,
+ "approval reason": byID["f-approval"].Approval.Reason,
+ "policy name": byID["f-approval"].Policy.Name,
+ "policy reason": byID["f-approval"].Policy.Reason,
+ "error message": byID["f-error"].Summary,
+ "error type": byID["f-error"].Error.Type,
+ "assistant text": byID["f-answer"].Content.Text,
+ }
+ want := map[string]string{
+ "prompt": "read ~/notes/todo.md",
+ "command": "cat ~/.config/app.toml",
+ "command output": "cat: ~/.config/app.toml: No such file",
+ "file path": "main.go",
+ "tool path": "main.go",
+ "mcp resource": "file://~/secret.txt",
+ "error message": "open ./go.mod: permission denied",
+ "approval reason": "writes to ~/.ssh",
+ "assistant text": "I changed ./main.go",
+ }
+ for name, got := range checks {
+ if strings.Contains(got, "/home/dev") || got == "" {
+ t.Errorf("%s = %q", name, got)
+ }
+ if w, ok := want[name]; ok && got != w {
+ t.Errorf("%s = %q, want %q", name, got, w)
+ }
+ }
+ if repo := bundle.Summary.Repository; repo != nil && repo.Path != "" {
+ t.Errorf("repository = %+v", repo)
+ }
+ if project := bundle.Summary.Project; project == nil || project.Name != "app" {
+ t.Errorf("project = %+v", project)
+ }
+ // The caller's events are not rewritten.
+ if events[1].Command.Command != "cat /home/dev/.config/app.toml" || events[2].File.Path != "/home/dev/src/app/main.go" ||
+ events[3].GenAI.Tool.Call.Arguments.(map[string]interface{})["path"] != "/home/dev/secret.txt" {
+ t.Fatal("BuildShareBundle changed the caller's events")
+ }
+ }
+
+ func TestShareProjects(t *testing.T) {
+ event := func(action, category string) Event {
+ return shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, action, category)
+ }
+ usage := event("token.usage", "metric")
+ usage.GenAI = &GenAIInfo{Usage: &GenAIUsageInfo{InputTokens: int64Ptr(3)}}
+ metricWithoutUsage := event("", "metric")
+ metricWithoutUsage.Raw = map[string]interface{}{"metric_name": "claude_code.lines_of_code.count"}
+ cases := []struct {
+ name string
+ event Event
+ want bool
+ }{
+ {"prompt", event("prompt.submitted", "prompt"), true},
+ {"tool", event("tool.invoked", "tool"), true},
+ {"command", event("command.executed", ""), true},
+ {"session start", event("session.started", "session"), true},
+ {"handoff", event("session.handoff", "session"), true},
+ {"reasoning", event("agent.reasoning", "agent"), true},
+ {"token usage", usage, true},
+ {"metric without usage", metricWithoutUsage, false},
+ {"shared record", event("session.shared", "session"), false},
+ {"share request", event("session.share_requested", "session"), false},
+ {"commit link", event("session.commit_linked", "session"), false},
+ {"heartbeat", event("endpoint.heartbeat", "health"), false},
+ {"inventory", event("inventory.snapshot", "inventory"), false},
+ {"idle", event("session.idle", "session"), false},
+ {"tool listing", event("mcp.tool_listed", "mcp"), false},
+ {"no action", event("", ""), false},
+ }
+ for _, tc := range cases {
+ if got := ShareProjects(tc.event); got != tc.want {
+ t.Errorf("ShareProjects(%s) = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+ // The bundle carries exactly what ShareProjects accepts.
+ var events []Event
+ accepted := 0
+ for i, tc := range cases {
+ e := tc.event
+ e.Event.ID = fmt.Sprintf("e-%02d", i)
+ events = append(events, e)
+ if tc.want {
+ accepted++
+ }
+ }
+ if bundle := BuildShareBundle(events, shareTestOpts); len(bundle.Events) != accepted || bundle.Summary.EventCount != accepted {
+ t.Fatalf("bundle carries %d events (summary %d), ShareProjects accepts %d", len(bundle.Events), bundle.Summary.EventCount, accepted)
+ }
+ }
+
+ func TestShareBundleOrdersNumbersAndDeduplicates(t *testing.T) {
+ pre := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "tool.invoked", "tool")
+ pre.Event.ID = "z-pre"
+ pre = withCall(pre, "toolu_1", "Bash", map[string]interface{}{"command": "ls"}, nil)
+ post := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "command.executed", "command")
+ post.Event.ID = "a-post"
+ post = withCall(post, "toolu_1", "Bash", nil, nil)
+ post.Command = &CommandInfo{Command: "ls", ExitCode: intPtr(0)}
+ prompt := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ prompt.Prompt = &PromptInfo{Text: "list"}
+ untimed := shareEventAt("not a time", "claude_code", CollectionMethodHook, "session.ended", "session")
+ untimed.Event.ID = "u"
+
+ bundle := BuildShareBundle([]Event{untimed, post, pre, prompt, post}, shareTestOpts)
+ var got []string
+ for i, event := range bundle.Events {
+ if event.Number != i+1 {
+ t.Fatalf("event %d is numbered %d", i, event.Number)
+ }
+ got = append(got, event.ID)
+ }
+ // The invocation sorts ahead of its completion at one instant, the duplicate is carried once,
+ // and the untimed event comes last.
+ if want := ShareEventID(prompt) + ",z-pre,a-post,u"; strings.Join(got, ",") != want {
+ t.Fatalf("events = %v, want %s", got, want)
+ }
+ if bundle.Spans != nil && len(bundle.Spans) != 0 {
+ t.Fatalf("spans = %+v", bundle.Spans)
+ }
+ if again := BuildShareBundle([]Event{untimed, post, pre, prompt, post}, ShareOptions{HomeDirectory: "/home/dev", NoHomeLookup: true, GeneratedAt: time.Unix(0, 0)}); again.Events[0].ID != got[0] {
+ t.Fatal("derived event id is not stable")
+ }
+ if empty := BuildShareBundle(nil, shareTestOpts); empty.Events == nil || len(empty.Events) != 0 || empty.Summary.EventCount != 0 {
+ t.Fatalf("empty bundle = %+v", empty)
+ }
+ }
+
+ // TraceMessages reads any bundle, including the local dashboard's, which still holds bookkeeping
+ // and status events: they are never messages.
+ func TestTraceMessagesSkipsBookkeepingInALocalBundle(t *testing.T) {
+ builder := NewTraceBuilder("session:claude_code:sess-1", Event{})
+ for i, e := range []Event{
+ shareEventAt("2026-10-01T10:00:00Z", "claude_code", "", "session.shared", "session"),
+ shareEventAt("2026-10-01T10:00:01Z", "claude_code", "", "session.share_requested", "session"),
+ shareEventAt("2026-10-01T10:00:02Z", "claude_code", "", "session.commit_linked", "session"),
+ shareEventAt("2026-10-01T10:00:03Z", "claude_code", CollectionMethodOTLP, "token.usage", "metric"),
+ shareEventAt("2026-10-01T10:00:04Z", "claude_code", CollectionMethodHook, "session.started", "session"),
+ } {
+ builder.Add(e, TraceEventFromEvent(e, fmt.Sprintf("line-%d", i), 0))
+ }
+ messages := TraceMessages(builder.Bundle(TraceProvenanceV1{}))
+ if got := partsOf(t, messages); strings.Join(got, ",") != "system/system_event" || messages[0].Kind != TraceMessageKindSystem {
+ t.Fatalf("parts = %v", got)
+ }
+ }
+
+ func TestTraceMessageRoundTrip(t *testing.T) {
+ messages := TraceMessages(BuildShareBundle(shareFieldEvents(), shareTestOpts))
+ kinds := map[string]bool{}
+ for _, m := range messages {
+ kinds[m.Kind] = true
+ }
+ for _, kind := range []string{TraceMessageKindPrompt, TraceMessageKindToolCall, TraceMessageKindToolResult, TraceMessageKindApproval, TraceMessageKindError, TraceMessageKindAssistant} {
+ if !kinds[kind] {
+ t.Fatalf("no %s message in %+v", kind, messages)
+ }
+ }
+ data, err := json.Marshal(messages)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var decoded []TraceMessageV1
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ t.Fatal(err)
+ }
+ again, err := json.Marshal(decoded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(again) != string(data) {
+ t.Fatalf("messages changed in a round trip:\n%s\n%s", data, again)
+ }
+ if _, ok := decoded[1].Parts[0].Content.(*TraceToolCallContentV1); !ok {
+ t.Fatalf("tool call decoded as %T", decoded[1].Parts[0].Content)
+ }
+ want := `{"id":"m1","role":"assistant","kind":"tool_call","order":1,"timestamp":"t","model":"m","text":"x","parts":[` +
+ `{"type":"tool_call","order":1,"content":{"callId":"c","toolName":"Bash","toolKind":"terminal_command","args":{},"command":"ls","filePath":"a","diff":"d"}},` +
+ `{"type":"tool_result","order":2,"content":{"callId":"c","toolName":"Bash","output":"o","status":"success","exitCode":0,"durationMs":3}},` +
+ `{"type":"text","order":3,"content":{"text":"x"}},` +
+ `{"type":"error","order":4,"content":{"message":"e"}},` +
+ `{"type":"system_event","order":5,"content":{"subtype":"session.started"}}],` +
+ `"token_usage":{"input_tokens":1}}`
+ pinned := TraceMessageV1{ID: "m1", Role: TraceRoleAssistant, Kind: TraceMessageKindToolCall, Order: 1, Timestamp: "t", Model: "m", Text: "x",
+ Parts: []TraceMessagePartV1{
+ {Type: TracePartToolCall, Order: 1, Content: &TraceToolCallContentV1{CallID: "c", ToolName: "Bash", ToolKind: TraceToolKindTerminalCommand, Args: map[string]interface{}{}, Command: "ls", FilePath: "a", Diff: "d"}},
+ {Type: TracePartToolResult, Order: 2, Content: &TraceToolResultContentV1{CallID: "c", ToolName: "Bash", Output: "o", Status: TraceToolStatusSuccess, ExitCode: intPtr(0), DurationMS: int64Ptr(3)}},
+ {Type: TracePartText, Order: 3, Content: TraceTextContentV1{Text: "x"}},
+ {Type: TracePartError, Order: 4, Content: TraceErrorContentV1{Message: "e"}},
+ {Type: TracePartSystemEvent, Order: 5, Content: map[string]interface{}{"subtype": "session.started"}},
+ },
+ TokenUsage: &TraceUsageV1{InputTokens: 1},
+ }
+ if got, _ := json.Marshal(pinned); string(got) != want {
+ t.Fatalf("message JSON drifted:\n got %s\nwant %s", got, want)
+ }
+ }
+
+ func TestShareEventIDAndBundleLeaveTheCallersTraceAlone(t *testing.T) {
+ event := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "tool.invoked", "tool")
+ event.Event.ID = ""
+ event.Trace = &TraceInfo{}
+ event.Tool = &ToolInfo{Name: "Bash"}
+ event.GenAI = &GenAIInfo{Tool: &GenAIToolInfo{Name: "Bash", Call: &GenAIToolCallInfo{ID: "toolu_1"}}}
+ events := []Event{event}
+
+ id := ShareEventID(events[0])
+ if id == "" {
+ t.Fatal("no id")
+ }
+ bundle := BuildShareBundle(events, shareTestOpts)
+ if got := events[0].Trace; got == nil || got.ID != "" || got.SpanID != "" {
+ t.Fatalf("caller's trace = %+v", got)
+ }
+ if len(bundle.Events) != 1 || bundle.Events[0].ID != id {
+ t.Fatalf("events = %+v", bundle.Events)
+ }
+ if tr := bundle.Events[0].Trace; tr != nil && (tr.ID != "" || tr.SpanID != "") {
+ t.Fatalf("bundle event trace = %+v", tr)
+ }
+ if len(bundle.Spans) != 0 {
+ t.Fatalf("spans = %+v", bundle.Spans)
+ }
+ }
+
+ func TestShareRelationComesFromTheHandoff(t *testing.T) {
+ plain := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ if related, kind := ShareRelation([]Event{plain}); related != "" || kind != "" {
+ t.Fatalf("relation = %q %q", related, kind)
+ }
+ handoff := shareEventAt("2026-10-01T10:00:01Z", "claude_code", CollectionMethodHook, "session.handoff", "session")
+ handoff.Handoff = &HandoffInfo{SourceHarness: "codex", SourceSessionID: "sess-9"}
+ related, kind := ShareRelation([]Event{plain, handoff})
+ if related != ShareExternalID("codex", "sess-9") || kind != ShareRelationshipHandoff {
+ t.Fatalf("relation = %q %q", related, kind)
+ }
+ trace := ShareTraceV1{RelatedTo: related, RelationshipType: kind}
+ data, _ := json.Marshal(trace)
+ if !strings.Contains(string(data), `"related_to":"codex_cli:sess-9","relationship_type":"handoff"`) {
+ t.Fatalf("wire = %s", data)
+ }
+ }
+
+ func TestTraceBuilderNamesTheProject(t *testing.T) {
+ event := shareEventAt("2026-10-01T10:00:00Z", "claude_code", CollectionMethodHook, "prompt.submitted", "prompt")
+ event.Session.WorkingDirectory = "/home/dev/src/app/sub"
+ b := NewTraceBuilder("t", event)
+ b.Add(event, TraceEventFromEvent(event, "e1", 0))
+ if p := b.Summary().Project; p == nil || p.Name != "sub" {
+ t.Fatalf("project = %+v", p)
+ }
+ event.Repository = "/home/dev/src/app"
+ b = NewTraceBuilder("t", event)
+ b.Add(event, TraceEventFromEvent(event, "e1", 0))
+ if p := b.Summary().Project; p == nil || p.Name != "app" {
+ t.Fatalf("project = %+v", p)
+ }
+ }
+
+ func TestShareEventsAfterResendsTheLastEventAndOpenCalls(t *testing.T) {
+ ev := func(id, action, callID string) TraceEventV1 {
+ return TraceEventV1{ID: id, Action: action, ToolCallID: callID}
+ }
+ events := []TraceEventV1{
+ ev("p1", "prompt.submitted", ""),
+ ev("c1", "tool.invoked", "a"),
+ ev("r1", "tool.completed", "a"),
+ ev("c2", "tool.invoked", "b"),
+ ev("m1", "agent.response", ""),
+ ev("r2", "tool.completed", "b"),
+ ev("m2", "agent.response", ""),
+ }
+ ids := func(in []TraceEventV1) string {
+ var out []string
+ for _, e := range in {
+ out = append(out, e.ID)
+ }
+ return strings.Join(out, ",")
+ }
+ cases := []struct {
+ last string
+ max int
+ want string
+ }{
+ {"r1", 0, "r1,c2,m1,r2,m2"},
+ {"m1", 0, "c2,m1,r2,m2"},
+ {"r2", 0, "r2,m2"},
+ {"m2", 0, "m2"},
+ {"gone", 0, "p1,c1,r1,c2,m1,r2,m2"},
+ {"", 3, "r1,c2,m1,r2,m2"},
+ {"", 0, "p1,c1,r1,c2,m1,r2,m2"},
+ {"", 99, "p1,c1,r1,c2,m1,r2,m2"},
+ }
+ for _, tc := range cases {
+ if got := ids(ShareEventsAfter(events, tc.last, tc.max)); got != tc.want {
+ t.Errorf("after %q/%d = %s, want %s", tc.last, tc.max, got, tc.want)
+ }
+ }
+ }
++
++// ShareProjects agrees with BuildShareBundle: every event it rejects is left out of the bundle, even
++// with content that would otherwise be shared, and the events it accepts are carried. Local views
++// rely on it to decide that a rejected event cannot make a shared trace out of date.
++func TestShareProjectsAgreesWithBuildShareBundle(t *testing.T) {
+ withText := func(e Event) Event {
+ e.Message = "something happened"
+ e.Prompt = &PromptInfo{Text: "a prompt-shaped field"}
+ e.GenAI = &GenAIInfo{Output: &GenAIOutputInfo{Messages: TextOutputMessages("assistant-shaped text")}}
+ return e
+ }
+ rejected := []Event{
+ shareEventAt("2026-10-01T10:00:00Z", "opencode", "plugin", "session.status", "session"),
+ shareEventAt("2026-10-01T10:00:01Z", "opencode", "plugin", "session.idle", "session"),
- shareEventAt("2026-10-01T10:00:02Z", "claude_code", "hook", "session.activity", "session"),
- shareEventAt("2026-10-01T10:00:03Z", "claude_code", "hook", "session.lock", "session"),
+ shareEventAt("2026-10-01T10:00:04Z", "claude_code", "otlp", "token.usage", "model"),
+ shareEventAt("2026-10-01T10:00:05Z", "claude_code", "otlp", "metric.point", "metric"),
+ shareEventAt("2026-10-01T10:00:06Z", "claude_code", "", "session.shared", "session"),
+ shareEventAt("2026-10-01T10:00:07Z", "claude_code", "", "session.share_requested", "session"),
- shareEventAt("2026-10-01T10:00:08Z", "cursor", "hook", "mcp.tool_listed", "mcp"),
++ shareEventAt("2026-10-01T10:00:08Z", "claude_code", "", "session.commit_linked", "session"),
+ }
+ for _, e := range rejected {
+ if ShareProjects(e) {
+ t.Fatalf("ShareProjects(%s) = true, want false", e.Event.Action)
+ }
- if got := BuildShareMessagesWithOptions([]Event{withText(e)}, shareTestOpts); len(got) != 0 {
- t.Fatalf("%s: ShareProjects rejects it, but BuildShareMessages wrote %d message(s)", e.Event.Action, len(got))
++ if got := BuildShareBundle([]Event{withText(e)}, shareTestOpts).Events; len(got) != 0 {
++ t.Fatalf("%s: ShareProjects rejects it, but the bundle carries %d event(s)", e.Event.Action, len(got))
+ }
+ }
+ prompt := shareEventAt("2026-10-01T10:01:00Z", "claude_code", "hook", "prompt.submitted", "prompt")
+ prompt.Prompt = &PromptInfo{Text: "fix the bug"}
+ reply := shareEventAt("2026-10-01T10:01:05Z", "claude_code", "hook", "agent.message", "agent")
+ reply.GenAI = &GenAIInfo{Output: &GenAIOutputInfo{Messages: TextOutputMessages("done")}}
+ for _, e := range []Event{prompt, reply} {
+ if !ShareProjects(e) {
+ t.Fatalf("ShareProjects(%s) = false, want true", e.Event.Action)
+ }
- if got := BuildShareMessagesWithOptions([]Event{e}, shareTestOpts); len(got) != 1 {
- t.Fatalf("%s: ShareProjects accepts it, but BuildShareMessages wrote %d message(s)", e.Event.Action, len(got))
++ if got := BuildShareBundle([]Event{e}, shareTestOpts).Events; len(got) != 1 {
++ t.Fatalf("%s: ShareProjects accepts it, but the bundle carries %d event(s)", e.Event.Action, len(got))
+ }
+ }
+}
++
++func TestShareRefreshCommand(t *testing.T) {
++ if got := ShareRefreshCommand("claude", "abc-123"); got != "beacon share refresh claude_code:abc-123" {
++ t.Fatalf("plain = %q", got)
++ }
++ if got := ShareRefreshCommand("claude_code", "has space"); got != "" {
++ t.Fatalf("unsafe id = %q", got)
++ }
++ if got := ShareRefreshCommand("", "x"); got != "" {
++ t.Fatalf("no harness = %q", got)
++ }
++}