Skip to content

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

Match beacon share only in command position; buffer only shared sessions

Claude225567028b97
diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.go
index ff9cd9f4..09db0028 100644
--- a/cli/beacon/internal/endpoint/dashboard/events.go
+++ b/cli/beacon/internal/endpoint/dashboard/events.go
@@ -233,7 +233,7 @@ type sessionClassification struct {
}
func sessionIDsForState(path string, query EventQuery, state string) (map[string]bool, error) {
- classifications, _, err := classifySessions(path, query)
+ classifications, _, err := classifySessions(path, query, false)
if err != nil {
return nil, err
}
@@ -253,7 +253,11 @@ func sessionIDsForState(path string, query EventQuery, state string) (map[string
// It also returns each shared session's sharing state, worked out from every event of the session
// whatever the filters are: a session.shared record outside the selected window or filters still
// marks the session shared, and activity outside them still makes the share stale.
-func classifySessions(path string, query EventQuery) (map[string]sessionClassification, map[string]*SessionSharing, error) {
+//
+// withSharing false skips the sharing work (sessionIDsForState needs only the states). With it,
+// only sessions that have a session.shared record are buffered: a cheap first pass, which parses
+// only the lines that mention session.shared, names them.
+func classifySessions(path string, query EventQuery, withSharing bool) (map[string]sessionClassification, map[string]*SessionSharing, error) {
// Session state is a property of the whole session, not the filtered slice.
// Only the selected time window scopes recurrence. The owner is part of the
// recurrence key; content, harness and individual-session filters must not
@@ -265,6 +269,12 @@ func classifySessions(path string, query EventQuery) (map[string]sessionClassifi
stats := map[string]*sessionStateStats{}
sessionRecords := map[string][]EventRecord{}
shared := map[string]bool{}
+ if withSharing {
+ var err error
+ if shared, err = sharedSessionIDs(path); err != nil {
+ return nil, nil, err
+ }
+ }
for _, source := range eventSources(path) {
if err := collectSessionStateStats(source, stateQuery, stats, sessionRecords, shared); err != nil {
return nil, nil, err
@@ -313,6 +323,52 @@ func classifySessions(path string, query EventQuery) (map[string]sessionClassifi
return classifications, sharing, nil
}
+// sharingRecordBuffered is called once per record classifySessions buffers for the sharing state;
+// tests replace it to count.
+var sharingRecordBuffered = func() {}
+
+var sessionSharedMarker = []byte(`"session.shared"`)
+
+// sharedSessionIDs names the sessions that have a session.shared record. It parses only the lines
+// that mention session.shared, so a log with no shares costs one read and no decoding.
+func sharedSessionIDs(path string) (map[string]bool, error) {
+ ids := map[string]bool{}
+ for _, source := range eventSources(path) {
+ file, err := os.Open(source.path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ continue
+ }
+ return nil, err
+ }
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if !bytes.Contains(line, sessionSharedMarker) {
+ continue
+ }
+ var probe struct {
+ Event struct {
+ Action string `json:"action"`
+ } `json:"event"`
+ Session *struct {
+ ID string `json:"id"`
+ } `json:"session"`
+ }
+ if json.Unmarshal(line, &probe) == nil && probe.Event.Action == "session.shared" && probe.Session != nil && probe.Session.ID != "" {
+ ids[probe.Session.ID] = true
+ }
+ }
+ err = scanner.Err()
+ file.Close()
+ if err != nil {
+ return nil, err
+ }
+ }
+ return ids, nil
+}
+
func collectSessionStateStats(source eventSource, query EventQuery, stats map[string]*sessionStateStats, sessionRecords map[string][]EventRecord, shared map[string]bool) error {
file, err := os.Open(source.path)
if err != nil {
@@ -349,10 +405,11 @@ func collectSessionStateStats(source eventSource, query EventQuery, stats map[st
if event.Session == nil || event.Session.ID == "" {
continue
}
- // Every session's records, slimmed to what the sharing state reads, whatever the filters.
- sessionRecords[event.Session.ID] = append(sessionRecords[event.Session.ID], shareRelevantRecord(record))
- if event.Event.Action == "session.shared" {
- shared[event.Session.ID] = true
+ // A shared session's records, slimmed to what the sharing state reads, whatever the
+ // filters. Sessions never shared are not buffered.
+ if shared[event.Session.ID] {
+ sessionRecords[event.Session.ID] = append(sessionRecords[event.Session.ID], shareRelevantRecord(record))
+ sharingRecordBuffered()
}
if !matchesQuery(record, query) {
continue
diff --git a/cli/beacon/internal/endpoint/dashboard/sessions.go b/cli/beacon/internal/endpoint/dashboard/sessions.go
index 4db678e4..dc22e8dd 100644
--- a/cli/beacon/internal/endpoint/dashboard/sessions.go
+++ b/cli/beacon/internal/endpoint/dashboard/sessions.go
@@ -77,7 +77,7 @@ type SessionDetail struct {
func ReadSessions(path string, query EventQuery) (SessionResult, error) {
limit := normalizeLimit(query.Limit)
- classifications, sharing, err := classifySessions(path, query)
+ classifications, sharing, err := classifySessions(path, query, true)
if err != nil {
return SessionResult{}, err
}
diff --git a/cli/beacon/internal/endpoint/dashboard/share_activity.go b/cli/beacon/internal/endpoint/dashboard/share_activity.go
index c57652fe..3aa55c6e 100644
--- a/cli/beacon/internal/endpoint/dashboard/share_activity.go
+++ b/cli/beacon/internal/endpoint/dashboard/share_activity.go
@@ -1,7 +1,6 @@
package dashboard
import (
- "regexp"
"strings"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
@@ -33,13 +32,90 @@ type shareActivity struct {
QuietSinceShare bool `json:"quiet_since_share,omitempty"`
}
-// beaconShareCommand matches a shell command that runs `beacon share`, with any subcommand or
-// flags, as a whole word (`beacon share`, `/opt/beacon/bin/beacon share refresh ...`, `x && beacon
-// share --current`).
-var beaconShareCommand = regexp.MustCompile(`(^|[\s/;&|(` + "`" + `'"])beacon(\.exe)?\s+share(\s|$|[;&|)'"])`)
-
+// isBeaconShareCommand reports whether a shell command runs `beacon share` (any subcommand or
+// flags): `beacon` must be in command position -- the start of the command or of a segment after
+// `;`, `&&`, `||`, `|`, `(` or a newline outside quotes -- optionally after environment assignments,
+// `sudo`, `exec` or `env`, and optionally with a path (`/opt/beacon/bin/beacon`, `./beacon`,
+// `beacon.exe`), followed by `share`. A mention inside an argument (`rg "beacon share"`,
+// `git commit -m 'beacon share ...'`, `echo beacon share`) is not a share call.
func isBeaconShareCommand(command string) bool {
- return command != "" && beaconShareCommand.MatchString(command)
+ if command == "" {
+ return false
+ }
+ for _, segment := range shellSegments(command) {
+ words := strings.Fields(segment)
+ i := 0
+ for i < len(words) && (isEnvAssignment(words[i]) || words[i] == "sudo" || words[i] == "exec" || words[i] == "env") {
+ i++
+ }
+ if i+1 < len(words) && isBeaconExecutable(words[i]) && words[i+1] == "share" {
+ return true
+ }
+ }
+ return false
+}
+
+// shellSegments splits a command at the separators that start a new command (`;`, `&`, `|`, `(`,
+// `)`, newline), outside single and double quotes. Quoted text stays inside its segment, so a
+// separator in an argument does not start one.
+func shellSegments(command string) []string {
+ var segments []string
+ var current strings.Builder
+ var quote rune
+ escaped := false
+ flush := func() {
+ if strings.TrimSpace(current.String()) != "" {
+ segments = append(segments, current.String())
+ }
+ current.Reset()
+ }
+ for _, r := range command {
+ switch {
+ case escaped:
+ escaped = false
+ current.WriteRune(r)
+ case r == '\\' && quote != '\'':
+ escaped = true
+ current.WriteRune(r)
+ case quote != 0:
+ if r == quote {
+ quote = 0
+ }
+ current.WriteRune(r)
+ case r == '\'' || r == '"':
+ quote = r
+ current.WriteRune(r)
+ case r == ';' || r == '&' || r == '|' || r == '(' || r == ')' || r == '\n':
+ flush()
+ default:
+ current.WriteRune(r)
+ }
+ }
+ flush()
+ return segments
+}
+
+func isEnvAssignment(word string) bool {
+ name, _, ok := strings.Cut(word, "=")
+ if !ok || name == "" {
+ return false
+ }
+ for i, r := range name {
+ if !(r == '_' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || i > 0 && r >= '0' && r <= '9') {
+ return false
+ }
+ }
+ return true
+}
+
+// isBeaconExecutable is the word `beacon`, or a path to it, as a command names it.
+func isBeaconExecutable(word string) bool {
+ word = strings.Trim(word, `"'`)
+ if i := strings.LastIndexAny(word, `/\`); i >= 0 {
+ word = word[i+1:]
+ }
+ word = strings.ToLower(word)
+ return word == "beacon" || word == "beacon.exe"
}
// counts reports whether event is activity that makes a share stale, and updates the state.
diff --git a/cli/beacon/internal/endpoint/dashboard/sharing_view_test.go b/cli/beacon/internal/endpoint/dashboard/sharing_view_test.go
index 6732f0da..1773c7ad 100644
--- a/cli/beacon/internal/endpoint/dashboard/sharing_view_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/sharing_view_test.go
@@ -367,3 +367,69 @@ func TestOpenCodeShareFromInsideTheSessionIsNotStale(t *testing.T) {
), "stale")
})
}
+
+func TestIsBeaconShareCommand(t *testing.T) {
+ for command, want := range map[string]bool{
+ `beacon share --current`: true,
+ `cd x && beacon share refresh --harness claude_code`: true,
+ `/opt/beacon/bin/beacon share`: true,
+ `BEACON_X=1 beacon share`: true,
+ `./beacon share --json`: true,
+ `C:\Tools\beacon.exe share`: true,
+ `sudo beacon share --session abc`: true,
+ "go test ./...\nbeacon share": true,
+ `rg "beacon share"`: false,
+ `git commit -m 'beacon share now records shared_through'`: false,
+ `git commit -m 'fix; beacon share'`: false,
+ `echo beacon share`: false,
+ `beacon shares`: false,
+ `beacon git setup --share-sessions`: false,
+ ``: false,
+ } {
+ if got := isBeaconShareCommand(command); got != want {
+ t.Errorf("isBeaconShareCommand(%q) = %v, want %v", command, got, want)
+ }
+ }
+}
+
+// The session list buffers records for the sharing state only for sessions that were shared, and
+// the session-state filter does no sharing work at all.
+func TestSharingBuffersOnlySharedSessions(t *testing.T) {
+ buffered := 0
+ prev := sharingRecordBuffered
+ sharingRecordBuffered = func() { buffered++ }
+ t.Cleanup(func() { sharingRecordBuffered = prev })
+ withoutHistory(t)
+
+ unshared := newTestLog(t, sharingLines(
+ `{"timestamp":"2026-06-11T10:00:00Z","event":{"id":"u1","action":"prompt.submitted","category":"prompt"},"harness":{"name":"claude_code"},"session":{"id":"nu1"},"prompt":{"text":"hello"}}`,
+ `{"timestamp":"2026-06-11T10:00:05Z","event":{"id":"u2","action":"command.executed","category":"command"},"harness":{"name":"claude_code"},"session":{"id":"nu1"},"command":{"command":"echo beacon share"}}`,
+ ))
+ if got := sessionSharing(t, unshared, EventQuery{}); got["nu1"] != nil {
+ t.Fatalf("unshared session sharing = %+v", got["nu1"])
+ }
+ if buffered != 0 {
+ t.Fatalf("buffered %d records for a log with no shares", buffered)
+ }
+
+ path := newTestLog(t, parityFixture())
+ if _, err := sessionIDsForState(path, EventQuery{}, "captured"); err != nil {
+ t.Fatal(err)
+ }
+ if buffered != 0 {
+ t.Fatalf("the session-state filter buffered %d records", buffered)
+ }
+ got := sessionSharing(t, path, EventQuery{})
+ if got["s7"] == nil || got["s8"] == nil {
+ t.Fatalf("shared sessions missing: %+v", got)
+ }
+ shared := 0
+ for _, line := range parityFixture() {
+ if strings.Contains(string(line), `"id":"s7"`) || strings.Contains(string(line), `"id":"s8"`) {
+ shared++
+ }
+ }
+ if buffered != shared {
+ t.Fatalf("buffered %d records, want only the shared sessions' %d", buffered, shared)
+ }
+}