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
fix(grok): collect sessions incrementally and report both collection paths
Claude21e8e183676f
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.goindex dff25c31..47bf6227 100644--- a/cli/beacon/cmd/endpoint_diagnostics.go+++ b/cli/beacon/cmd/endpoint_diagnostics.go@@ -1407,6 +1407,12 @@ func harnessAction(h harness.Harness, effectiveUserMode bool) string {// succeed for this harness.case "session_log":return "beacon endpoint fx sync"+ // Grok has both paths. This check only runs when neither is carrying telemetry, and the hooks+ // are the remedy worth naming: they capture live and cover sessions still open, where a sync+ // sweep can only read what Grok has already committed. The check's message names the sweep for+ // the cases where that is what is behind.+ case "hooks+session_log":+ return "beacon endpoint hooks install --harness " + h.Name}return ""}diff --git a/cli/beacon/cmd/endpoint_grok.go b/cli/beacon/cmd/endpoint_grok.goindex 6dbfe30f..a8fe7040 100644--- a/cli/beacon/cmd/endpoint_grok.go+++ b/cli/beacon/cmd/endpoint_grok.go@@ -4,8 +4,11 @@ import ("context""encoding/json""fmt"+ "path/filepath"+ "strings""time"+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/groksession""github.com/spf13/cobra"@@ -77,7 +80,7 @@ func runEndpointGrokSync(cmd *cobra.Command, args []string) error {UserMode: userMode,}if !endpointGrokOpts.print {- opts.StatePath = resolveGrokStatePath(endpointGrokOpts.statePath)+ opts.StatePath = resolveGrokStatePath(endpointGrokOpts.statePath, userMode)opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointGrokOpts.logPath).EffectiveLogPath}@@ -136,7 +139,8 @@ func runEndpointGrokStatus(cmd *cobra.Command, args []string) error {if err != nil {return err}- state, err := groksession.LoadState(resolveGrokStatePath(endpointGrokOpts.statePath))+ statePath := resolveGrokStatePath(endpointGrokOpts.statePath, endpointUserMode())+ state, err := groksession.LoadState(statePath)if err != nil {return err}@@ -145,7 +149,7 @@ func runEndpointGrokStatus(cmd *cobra.Command, args []string) error {Collected int `json:"collected"`StatePath string `json:"state_path"`}- out := status{Sessions: len(refs), StatePath: resolveGrokStatePath(endpointGrokOpts.statePath)}+ out := status{Sessions: len(refs), StatePath: statePath}for _, ref := range refs {cursor := state.Sessions[ref.ID]if cursor != nil && cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {@@ -162,9 +166,20 @@ func runEndpointGrokStatus(cmd *cobra.Command, args []string) error {return nil}-func resolveGrokStatePath(path string) string {- if path != "" {+// resolveGrokStatePath picks the cursor file for the mode the sweep is running in.+//+// --user and --system already choose which runtime log the events are written to, so the cursor has+// to follow. A system sweep that advanced the per-user cursor would record, in one operator's home+// directory, that sessions had been collected into the machine's log -- and the two modes would+// then each skip records the other wrote. A system sweep collects on behalf of the machine, so its+// cursor belongs beside the system state, the same split resolveClineStatePath and+// resolveFxStatePath make.+func resolveGrokStatePath(path string, userMode bool) string {+ if strings.TrimSpace(path) != "" {return path}- return groksession.DefaultStatePath()+ if userMode {+ return groksession.DefaultStatePath()+ }+ return filepath.Join(endpointconfig.BaseDir(false), "state", "grok-sessions.json")}diff --git a/cli/beacon/internal/endpoint/harness/grok.go b/cli/beacon/internal/endpoint/harness/grok.goindex 0a099e1f..2ff2771a 100644--- a/cli/beacon/internal/endpoint/harness/grok.go+++ b/cli/beacon/internal/endpoint/harness/grok.go@@ -5,53 +5,116 @@ import ("os""path/filepath"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/groksession")const GrokName = groksession.Harness+// DiscoverGrok reports whether Grok Build is present and which of its two collection paths is+// carrying telemetry.+//+// Grok is the first runtime here with both. Its capability is "hooks+session_log": Beacon owns a+// hook file that Grok calls live, *and* Grok commits session records that `beacon endpoint grok+// sync` can read afterwards. Either one alone is telemetry, so discovery has to look at both --+// reporting only the sync cursor would mark a machine with working hooks as disabled until someone+// ran a sweep it does not need, and reporting only the hook file would hide a backfill-only setup.+//+// The hooks are the stronger signal and are checked first: they are live, they can participate in+// the policy seam, and they cover sessions that are still open. Session sync is a poll path that+// sees records after the fact, so it is what discovery falls back to.func DiscoverGrok() Harness {h := Harness{Name: GrokName, DisplayName: "Grok Build", Capability: "hooks+session_log"}detectExecutable(&h, "grok")+home, _ := os.UserHomeDir()+ if home == "" {+ h.TelemetryStatus = TelemetryMissing+ h.Message = "Grok Build directory could not be resolved: no home directory"+ return h+ }sessionsDir := filepath.Join(home, ".grok", "sessions")- h.ConfigPath = sessionsDir++ // Grok installed through a version manager, a shell alias or a per-user bin directory may not be+ // on the PATH this process inherited while ~/.grok is still there. Treating that directory as+ // evidence keeps discovery from reporting "not detected" for a runtime the user is actively+ // running -- the same fallback the opencode, Cursor, Hermes, Pi and fx probes make.if !h.Detected && dirExists(filepath.Join(home, ".grok")) {h.Detected = true}- h.TelemetryStatus, h.Message = grokCollectionStatus(sessionsDir)++ // User level only. A project-level hook file lives at ./.grok/hooks/beacon-endpoint.json, so+ // resolving it here would read whatever repository the command happened to run from and report+ // it as the machine's state. DiscoverQwen, DiscoverCline and DiscoverPi guard the same way.+ hookStatus := hooks.GrokHookStatus(hooks.GrokOptions{Level: hooks.LevelUser})+ if hookStatus.HooksPath != "" {+ h.ConfigPath = hookStatus.HooksPath+ } else {+ h.ConfigPath = sessionsDir+ }++ h.TelemetryStatus, h.Message = grokCollectionStatus(hookStatus.Installed, sessionsDir)return h}-func grokCollectionStatus(sessionsDir string) (TelemetryStatus, string) {+// grokCollectionStatus classifies what is collecting Grok Build telemetry on this machine.+//+// Installed hooks settle it: telemetry is flowing live, and whether a backfill sweep has also run+// is a detail rather than a fault. Without hooks the question becomes what `grok sync` has read,+// and the answer follows the same four cases as fx -- no sessions to collect, sessions with no+// cursor, a cursor behind them, a cursor level with them -- because the remedy differs for each and+// a single "not configured" would send someone to fix the wrong thing.+func grokCollectionStatus(hooksInstalled bool, sessionsDir string) (TelemetryStatus, string) {+ collected, total, err := grokSessionProgress(sessionsDir)++ if hooksInstalled {+ msg := "Beacon Grok Build hooks are configured"+ if err == nil && total > collected {+ msg += fmt.Sprintf("; %d of %d committed session(s) not backfilled, run `beacon endpoint grok sync` to collect them", total-collected, total)+ }+ return TelemetryEnabled, msg+ }++ if err != nil {+ return TelemetryMisconfigured, "Grok Build hooks are not installed and the session collector state could not be read: " + err.Error()+ }+ switch {+ case total == 0:+ return TelemetryDisabled, "Grok Build endpoint hooks are not installed; run `beacon endpoint hooks install --harness grok`"+ case collected == 0:+ return TelemetryDisabled, fmt.Sprintf("Grok Build endpoint hooks are not installed and none of %d committed session(s) have been collected; run `beacon endpoint hooks install --harness grok`", total)+ case collected < total:+ return TelemetryEnabled, fmt.Sprintf("Grok Build session telemetry collected for %d of %d session(s); run `beacon endpoint grok sync` to catch up", collected, total)+ default:+ return TelemetryEnabled, fmt.Sprintf("Grok Build session telemetry collected for all %d session(s)", total)+ }+}++// grokSessionProgress reports how many of the committed sessions the sync cursor has read.+//+// A missing session directory is not an error: Grok may simply not have run here, or may run only+// under hooks. It reports zero sessions, which the caller reads as "nothing to backfill".+func grokSessionProgress(sessionsDir string) (collected, total int, err error) {store := &groksession.Store{Dir: sessionsDir}if !store.Exists() {- return TelemetryMissing, "Grok Build has written no sessions on this machine"+ return 0, 0, nil}refs, err := store.List()if err != nil {- return TelemetryMissing, "Grok Build sessions could not be read: " + err.Error()+ return 0, 0, err}if len(refs) == 0 {- return TelemetryMissing, "Grok Build has written no sessions on this machine"+ return 0, 0, nil}state, err := groksession.LoadState(groksession.DefaultStatePath())if err != nil {- return TelemetryMisconfigured, "Grok Build collector state could not be read: " + err.Error()+ return 0, len(refs), err}- collected := 0for _, ref := range refs {cursor := state.Sessions[ref.ID]if cursor != nil && cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {collected++}}- switch {- case collected == 0:- return TelemetryDisabled, fmt.Sprintf("%d Grok Build session(s) present and none collected; run `beacon endpoint grok sync`", len(refs))- case collected < len(refs):- return TelemetryEnabled, fmt.Sprintf("Grok Build session telemetry collected for %d of %d session(s); run `beacon endpoint grok sync` to catch up", collected, len(refs))- default:- return TelemetryEnabled, fmt.Sprintf("Grok Build session telemetry collected for all %d session(s)", len(refs))- }+ return collected, len(refs), nil}diff --git a/cli/beacon/internal/endpoint/harness/grok_test.go b/cli/beacon/internal/endpoint/harness/grok_test.gonew file mode 100644index 00000000..4791f55e--- /dev/null+++ b/cli/beacon/internal/endpoint/harness/grok_test.go@@ -0,0 +1,181 @@+package harness++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/groksession"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++func grokHome(t *testing.T) string {+ t.Helper()+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv("PATH", t.TempDir())+ return home+}++// writeGrokHooks lays down a Beacon-managed Grok hook file, as `endpoint hooks install --harness+// grok` leaves it: the managed marker plus at least one command naming the hook binary.+func writeGrokHooks(t *testing.T, home string) {+ t.Helper()+ dir := filepath.Join(home, ".grok", "hooks")+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ file := `{"beacon":"beacon-managed-grok-hooks:v1","hooks":{"SessionStart":[{"hooks":[{"type":"command",` ++ `"command":"'/opt/beacon/bin/beacon-hooks' --platform grok --log '/tmp/runtime.jsonl' session-start"}]}]}}`+ if err := os.WriteFile(filepath.Join(dir, "beacon-endpoint.json"), []byte(file), 0o600); err != nil {+ t.Fatal(err)+ }+}++// writeGrokSession lays out one committed session, as Grok leaves it under ~/.grok/sessions.+func writeGrokSession(t *testing.T, home, id string) {+ t.Helper()+ dir := filepath.Join(home, ".grok", "sessions", "%2Frepo", id)+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "summary.json"),+ []byte(`{"created_at":"2026-05-21T16:49:22Z","updated_at":"2026-05-21T16:50:25Z","generated_title":"t","current_model_id":"grok-build"}`), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "chat_history.jsonl"),+ []byte(`{"type":"user","content":"hello"}`+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+}++func writeGrokCursor(t *testing.T, id string, cursor groksession.Cursor) {+ t.Helper()+ state := &groksession.State{Version: groksession.StateVersion, Sessions: map[string]*groksession.Cursor{id: &cursor}}+ if err := state.Save(groksession.DefaultStatePath()); err != nil {+ t.Fatal(err)+ }+}++// The harness name discovery reports has to be the one the collector writes, or `endpoint discover`+// and the runtime log describe the same runtime under two names.+func TestDiscoverGrokUsesTheCanonicalHarnessName(t *testing.T) {+ if GrokName != groksession.Harness {+ t.Fatalf("discovery reports %q while the collector writes %q", GrokName, groksession.Harness)+ }+ if got := asymptoteobserve.NormalizeHarnessName(GrokName); got != GrokName {+ t.Fatalf("NormalizeHarnessName(%q) = %q", GrokName, got)+ }+}++// A runtime missing from DiscoverAll is invisible to `beacon endpoint discover`. It fails silently:+// the command succeeds and simply never mentions Grok Build.+func TestDiscoverAllIncludesGrok(t *testing.T) {+ grokHome(t)+ for _, h := range DiscoverAll() {+ if h.Name == GrokName {+ if h.Capability != "hooks+session_log" {+ t.Errorf("Capability = %q, want hooks+session_log", h.Capability)+ }+ return+ }+ }+ t.Fatalf("DiscoverAll does not include %q", GrokName)+}++// Installed hooks are telemetry. Reporting a machine as disabled until someone runs a backfill+// sweep it does not need would send them to fix something that is already working.+func TestDiscoverGrokReportsInstalledHooksAsEnabledWithoutASyncCursor(t *testing.T) {+ home := grokHome(t)+ writeGrokHooks(t, home)+ writeGrokSession(t, home, "session-1")++ h := DiscoverGrok()+ if h.TelemetryStatus != TelemetryEnabled {+ t.Fatalf("status = %q, want %q -- the hooks are installed", h.TelemetryStatus, TelemetryEnabled)+ }+ if !strings.Contains(h.Message, "hooks are configured") {+ t.Errorf("message = %q, want it to name the hooks", h.Message)+ }+ if want := filepath.Join(home, ".grok", "hooks", "beacon-endpoint.json"); h.ConfigPath != want {+ t.Errorf("ConfigPath = %q, want the managed hook file %q", h.ConfigPath, want)+ }+ if !h.Detected {+ t.Error("Grok was not detected despite its profile directory being present")+ }+}++// Without hooks the sync cursor is the only evidence telemetry is flowing, and sessions nobody has+// read are the case where "enabled" would be a lie.+func TestDiscoverGrokReportsNoHooksAndNoCollectionAsDisabled(t *testing.T) {+ home := grokHome(t)+ writeGrokSession(t, home, "session-1")++ h := DiscoverGrok()+ if h.TelemetryStatus != TelemetryDisabled {+ t.Fatalf("status = %q, want %q -- nothing is collecting", h.TelemetryStatus, TelemetryDisabled)+ }+ if !strings.Contains(h.Message, "hooks install --harness grok") {+ t.Errorf("message = %q, want it to name the command that fixes this", h.Message)+ }+}++// A backfill-only setup is real telemetry too: no hooks, but every committed session read.+func TestDiscoverGrokReportsCollectedSessionsAsEnabledWithoutHooks(t *testing.T) {+ home := grokHome(t)+ writeGrokSession(t, home, "session-1")++ store := &groksession.Store{Dir: filepath.Join(home, ".grok", "sessions")}+ refs, err := store.List()+ if err != nil || len(refs) != 1 {+ t.Fatalf("List() = %d refs, %v", len(refs), err)+ }+ writeGrokCursor(t, refs[0].ID, groksession.Cursor{UpdatedAtMS: refs[0].ModTimeUnixMS, Events: 3, Started: true})++ h := DiscoverGrok()+ if h.TelemetryStatus != TelemetryEnabled {+ t.Fatalf("status = %q, want %q", h.TelemetryStatus, TelemetryEnabled)+ }+ if !strings.Contains(h.Message, "all 1 session") {+ t.Errorf("message = %q", h.Message)+ }+}++// Grok that has never run here is not a broken install, and with no hooks the remedy is to install+// them rather than to sweep a session store that does not exist.+func TestDiscoverGrokOnAMachineWithNoSessionsAndNoHooks(t *testing.T) {+ home := grokHome(t)+ if err := os.MkdirAll(filepath.Join(home, ".grok"), 0o755); err != nil {+ t.Fatal(err)+ }++ h := DiscoverGrok()+ if h.TelemetryStatus != TelemetryDisabled {+ t.Fatalf("status = %q, want %q", h.TelemetryStatus, TelemetryDisabled)+ }+ if !strings.Contains(h.Message, "hooks install --harness grok") {+ t.Errorf("message = %q", h.Message)+ }+}++// Discovery is a read. It must not create Grok's directories, Beacon's state directory, or anything+// else in the home of someone who does not run Grok.+func TestDiscoverGrokWritesNothing(t *testing.T) {+ home := grokHome(t)++ DiscoverGrok()++ entries, err := os.ReadDir(home)+ if err != nil {+ t.Fatal(err)+ }+ if len(entries) != 0 {+ names := make([]string, 0, len(entries))+ for _, entry := range entries {+ names = append(names, entry.Name())+ }+ t.Fatalf("discovery created %v in a home that had nothing", names)+ }+}diff --git a/cli/beacon/internal/groksession/collect.go b/cli/beacon/internal/groksession/collect.goindex eb09b899..888f4114 100644--- a/cli/beacon/internal/groksession/collect.go+++ b/cli/beacon/internal/groksession/collect.go@@ -15,9 +15,27 @@ import (const StateVersion = 1+// Cursor records how far Beacon has read one Grok session.+//+// A Grok session directory holds two append-only logs that grow independently, so the cursor keeps+// a line position for each rather than a single "how far did we get" number. Remembering only the+// session's modification time and a total event count would make every sweep after the session grew+// -- a --watch tick, tomorrow's sync -- re-map the session from its first line and append a full+// duplicate set to the runtime log.type Cursor struct {+ // UpdatedAtMS is the session's last-seen modification time, used to skip sessions that cannot+ // have changed. It is a cheap pre-filter, not the record of what was written.UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`- Events int `json:"events,omitempty"`+ // Events is the running total written for this session, across all sweeps.+ Events int `json:"events,omitempty"`+ // ChatLine and LifecycleLine are the last line of chat_history.jsonl and events.jsonl whose+ // events were all written. Lines are physical line numbers, so a half-written line at the tail+ // of a live session does not shift the positions of the lines before it.+ ChatLine int `json:"chat_line,omitempty"`+ LifecycleLine int `json:"lifecycle_line,omitempty"`+ // Started records that session.started was written. It has no line of its own, being derived+ // from summary.json and the first turn_started row.+ Started bool `json:"started,omitempty"`}type State struct {@@ -161,22 +179,65 @@ func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptiif err != nil {return false, err}- mapped := MapSession(data)+ mapped := MapSession(data, MapOptions{+ MinChatLine: cursor.ChatLine,+ MinLifecycleLine: cursor.LifecycleLine,+ SkipStarted: cursor.Started,+ })if len(mapped) == 0 {cursor.UpdatedAtMS = ref.ModTimeUnixMSreturn false, nil}+ written := 0for _, item := range mapped {if err := emit(item.Event, opts); err != nil {+ commit(cursor, mapped, written)return true, err}+ written++summary.EventsEmitted++}+ commit(cursor, mapped, written)cursor.UpdatedAtMS = ref.ModTimeUnixMS- cursor.Events = len(mapped)return true, nil}+// commit advances the cursor over the events that were actually written.+//+// One source line can produce several events -- an assistant line yields reasoning, a message and+// one event per tool call -- so a line counts as collected only once every event it produced has+// been written. A line with an unwritten event left on it stays behind the cursor, and the next+// sweep re-emits the whole line rather than silently dropping its tail. On a clean pass there is+// nothing unwritten and every line advances.+func commit(cursor *Cursor, mapped []MappedEvent, written int) {+ blocked := map[SourceKind]int{}+ for _, item := range mapped[written:] {+ if line, seen := blocked[item.SourceKind]; !seen || item.SourceLine < line {+ blocked[item.SourceKind] = item.SourceLine+ }+ }+ for _, item := range mapped[:written] {+ if item.SourceKind == SourceSession {+ cursor.Started = true+ continue+ }+ if line, seen := blocked[item.SourceKind]; seen && item.SourceLine >= line {+ continue+ }+ switch item.SourceKind {+ case SourceChat:+ if item.SourceLine > cursor.ChatLine {+ cursor.ChatLine = item.SourceLine+ }+ case SourceLifecycle:+ if item.SourceLine > cursor.LifecycleLine {+ cursor.LifecycleLine = item.SourceLine+ }+ }+ }+ cursor.Events += written+}+func emit(event schema.Event, opts CollectOptions) error {if opts.Print && opts.Out != nil {data, err := json.Marshal(event)diff --git a/cli/beacon/internal/groksession/collect_test.go b/cli/beacon/internal/groksession/collect_test.goindex 7739df74..d74309b5 100644--- a/cli/beacon/internal/groksession/collect_test.go+++ b/cli/beacon/internal/groksession/collect_test.go@@ -8,6 +8,7 @@ import ("path/filepath""strings""testing"+ "time")func TestStoreListsAndMapsGrokSession(t *testing.T) {@@ -39,7 +40,7 @@ func TestStoreListsAndMapsGrokSession(t *testing.T) {if stats.Malformed != 0 {t.Fatalf("Malformed = %d, want 0", stats.Malformed)}- events := MapSession(data)+ events := MapSession(data, MapOptions{})if len(events) == 0 {t.Fatal("MapSession returned no events")}@@ -64,6 +65,111 @@ func TestStoreListsAndMapsGrokSession(t *testing.T) {if byAction["approval.allowed"].Approval.Decision != "allowed" {t.Fatalf("approval event = %#v", byAction["approval.allowed"].Approval)}+ // A turn is not a session. Grok keeps writing to the same session after turn_ended, so the+ // only session-lifecycle boundary this store can honestly report is the start.+ if _, ok := byAction["session.ended"]; ok {+ t.Fatal("turn_ended produced a session.ended event")+ }+ if _, ok := byAction["session.started"]; !ok {+ t.Fatal("no session.started event")+ }+}++// A Grok session directory is appended to while the session runs, so the same session is read+// again on the next sweep. Only the records that were added may be emitted: re-mapping the whole+// session would append a duplicate copy of everything already in the runtime log.+func TestCollectOnceEmitsOnlyNewRecordsWhenSessionGrows(t *testing.T) {+ root := t.TempDir()+ sessionDir := writeFixtureSession(t, root, "/tmp/grok project", "session-1")+ statePath := filepath.Join(t.TempDir(), "state.json")+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")++ opts := CollectOptions{SessionsDir: root, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true}+ first, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("first CollectOnce returned error: %v", err)+ }+ if first.EventsEmitted == 0 {+ t.Fatal("first CollectOnce emitted no events")+ }++ appendLine(t, filepath.Join(sessionDir, "chat_history.jsonl"),+ `{"type":"user","content":[{"type":"text","text":"second turn"}]}`)+ appendLine(t, filepath.Join(sessionDir, "events.jsonl"),+ `{"ts":"2026-05-21T16:52:10.000Z","type":"turn_ended","outcome":"success","turn_number":1}`)+ touchNewer(t, sessionDir)++ second, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("second CollectOnce returned error: %v", err)+ }+ if second.EventsEmitted != 2 {+ t.Fatalf("second sweep emitted %d events, want the 2 appended records", second.EventsEmitted)+ }+ if lines := countLines(t, logPath); lines != first.EventsEmitted+2 {+ t.Fatalf("runtime lines = %d, want %d", lines, first.EventsEmitted+2)+ }+ actions := logActions(t, logPath)+ if actions["session.started"] != 1 {+ t.Fatalf("session.started written %d times, want 1", actions["session.started"])+ }+ if actions["prompt.submitted"] != 2 {+ t.Fatalf("prompt.submitted written %d times, want 2", actions["prompt.submitted"])+ }+ if actions["command.executed"] != 1 {+ t.Fatalf("command.executed written %d times, want 1 (the first sweep's only command)", actions["command.executed"])+ }++ third, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("third CollectOnce returned error: %v", err)+ }+ if third.EventsEmitted != 0 {+ t.Fatalf("third sweep emitted %d events, want none", third.EventsEmitted)+ }+}++// A sweep can catch the tail of a live session mid-write: the last line is half flushed, counts as+// malformed, and completes before the next sweep. Numbering records by their position among the+// lines that parsed would renumber every later line once it landed and the cursor would start+// skipping records it had never read, so records are numbered by physical line instead.+func TestCollectOnceCollectsALineThatWasTornOnTheFirstSweep(t *testing.T) {+ root := t.TempDir()+ sessionDir := writeFixtureSession(t, root, "/tmp/grok project", "session-1")+ chatPath := filepath.Join(sessionDir, "chat_history.jsonl")+ statePath := filepath.Join(t.TempDir(), "state.json")+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")++ // Grok is midway through flushing the next chat line when the sweep reads the file.+ appendLine(t, chatPath, `{"type":"user","content":[{"type":"te`)++ opts := CollectOptions{SessionsDir: root, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true}+ first, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("first CollectOnce returned error: %v", err)+ }+ if first.MalformedLines != 1 {+ t.Fatalf("MalformedLines = %d, want 1", first.MalformedLines)+ }++ // The write lands, and the session continues past it.+ rewriteLine(t, chatPath, 5, `{"type":"user","content":[{"type":"text","text":"the completed line"}]}`)+ appendLine(t, chatPath, `{"type":"user","content":[{"type":"text","text":"and the next one"}]}`)+ touchNewer(t, sessionDir)++ second, err := CollectOnce(opts)+ if err != nil {+ t.Fatalf("second CollectOnce returned error: %v", err)+ }+ if second.MalformedLines != 0 {+ t.Fatalf("MalformedLines = %d on the second sweep, want 0", second.MalformedLines)+ }+ if second.EventsEmitted != 2 {+ t.Fatalf("second sweep emitted %d events, want the completed line and the one after it", second.EventsEmitted)+ }+ if actions := logActions(t, logPath); actions["prompt.submitted"] != 3 {+ t.Fatalf("prompt.submitted written %d times, want 3", actions["prompt.submitted"])+ }}func TestCollectOnceIsIdempotentAndPrintDoesNotAdvanceState(t *testing.T) {@@ -133,6 +239,71 @@ func writeFixtureSession(t *testing.T, root, workspace, sessionID string) stringreturn sessionDir}+func appendLine(t *testing.T, path, line string) {+ t.Helper()+ f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)+ if err != nil {+ t.Fatalf("open %s for append: %v", path, err)+ }+ defer f.Close()+ if _, err := f.WriteString(line + "\n"); err != nil {+ t.Fatalf("append to %s: %v", path, err)+ }+}++func rewriteLine(t *testing.T, path string, lineNo int, content string) {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")+ if lineNo < 1 || lineNo > len(lines) {+ t.Fatalf("line %d out of range for %s (%d lines)", lineNo, path, len(lines))+ }+ lines[lineNo-1] = content+ writeFile(t, path, strings.Join(lines, "\n")+"\n")+}++// touchNewer moves the session directory's modification time forward. The collector uses it as a+// cheap "could this have changed" filter, and a test that writes twice inside one filesystem+// timestamp tick would otherwise be skipped for reasons that have nothing to do with the cursor.+func touchNewer(t *testing.T, dir string) {+ t.Helper()+ info, err := os.Stat(dir)+ if err != nil {+ t.Fatalf("stat %s: %v", dir, err)+ }+ next := info.ModTime().Add(2 * time.Second)+ if err := os.Chtimes(dir, next, next); err != nil {+ t.Fatalf("chtimes %s: %v", dir, err)+ }+}++func logActions(t *testing.T, path string) map[string]int {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ counts := map[string]int{}+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {+ if strings.TrimSpace(line) == "" {+ continue+ }+ var record struct {+ Event struct {+ Action string `json:"action"`+ } `json:"event"`+ }+ if err := json.Unmarshal([]byte(line), &record); err != nil {+ t.Fatalf("unmarshal runtime line: %v", err)+ }+ counts[record.Event.Action]+++ }+ return counts+}+func writeFile(t *testing.T, path, content string) {t.Helper()if err := os.WriteFile(path, []byte(content), 0o644); err != nil {diff --git a/cli/beacon/internal/groksession/mapper.go b/cli/beacon/internal/groksession/mapper.goindex 8307cdd2..f7cd41e1 100644--- a/cli/beacon/internal/groksession/mapper.go+++ b/cli/beacon/internal/groksession/mapper.go@@ -10,9 +10,17 @@ import ("github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve")-func MapSession(data SessionData) []MappedEvent {+// MapSession converts one Grok session directory into endpoint events.+//+// It always walks the whole session, because a record only makes sense next to the ones around it:+// a tool_result line carries the result but names its call by id, and the arguments live on an+// assistant line that may already have been collected on an earlier sweep. What opts controls is+// what gets *emitted* -- everything at or below the cursor is rebuilt for context and dropped -- so+// a session that grew since the last sweep yields only the records that grew.+func MapSession(data SessionData, opts MapOptions) []MappedEvent {m := &mapper{data: data,+ opts: opts,toolByID: map[string]ToolCall{},toolOutput: map[string]string{},}@@ -37,6 +45,7 @@ func MapSession(data SessionData) []MappedEvent {type mapper struct {data SessionData+ opts MapOptionsout []MappedEventtoolByID map[string]ToolCalltoolOutput map[string]string@@ -78,7 +87,7 @@ func (m *mapper) consumeChat(msg ChatMessage) {ev := m.base("", "prompt.submitted", "prompt", schema.SeverityInfo, schema.FidelityObserved, "Grok prompt submitted")ev.Prompt = &schema.PromptInfo{Text: text}ev.Content = contentMarker(text)- m.append(ev, msg.Index)+ m.append(ev, SourceChat, msg.Index)case "assistant":model := firstNonEmpty(msg.ModelID, m.summary().CurrentModelID)if msg.Reasoning != nil && msg.Reasoning.Text != "" {@@ -94,19 +103,19 @@ func (m *mapper) consumeChat(msg ChatMessage) {}}},}ev.Content = contentMarker(msg.Reasoning.Text)- m.append(ev, msg.Index)+ m.append(ev, SourceChat, msg.Index)}if text := contentText(msg.Content); text != "" {ev := m.base("", "agent.message", "agent", schema.SeverityInfo, schema.FidelityObserved, "Grok assistant message")ev.Model = modelev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{"role": "assistant", "content": text}}}}ev.Content = contentMarker(text)- m.append(ev, msg.Index)+ m.append(ev, SourceChat, msg.Index)}for _, call := range msg.ToolCalls {ev := m.toolCallEvent(call, msg.Index)ev.Model = model- m.append(ev, msg.Index)+ m.append(ev, SourceChat, msg.Index)}case "tool_result":call := m.toolByID[msg.ToolCallID]@@ -116,7 +125,7 @@ func (m *mapper) consumeChat(msg ChatMessage) {}m.toolOutput[msg.ToolCallID] = outputev := m.toolResultEvent(call, msg.ToolCallID, output)- m.append(ev, msg.Index)+ m.append(ev, SourceChat, msg.Index)}}@@ -126,7 +135,7 @@ func (m *mapper) consumeLifecycle(ev LifecycleEvent) {out := m.base(ev.TS, "approval.requested", "approval", schema.SeverityInfo, schema.FidelityObserved, "Grok requested tool approval")out.Tool = &schema.ToolInfo{Name: ev.ToolName}out.Approval = &schema.ApprovalInfo{Required: true}- m.append(out, ev.Index)+ m.append(out, SourceLifecycle, ev.Index)case "permission_resolved":out := m.base(ev.TS, "approval."+normalizeDecision(ev.Decision), "approval", schema.SeverityInfo, schema.FidelityObserved, "Grok resolved tool approval")out.Tool = &schema.ToolInfo{Name: ev.ToolName}@@ -134,7 +143,7 @@ func (m *mapper) consumeLifecycle(ev LifecycleEvent) {if ev.WaitMS > 0 {out.Raw = map[string]interface{}{"grok": map[string]interface{}{"approval_wait_ms": ev.WaitMS}}}- m.append(out, ev.Index)+ m.append(out, SourceLifecycle, ev.Index)case "tool_completed":// chat_history carries the call arguments and result. The lifecycle row is kept only when// it adds failure/status detail that a tool_result row cannot express by itself.@@ -146,17 +155,33 @@ func (m *mapper) consumeLifecycle(ev LifecycleEvent) {if ev.DurationMS > 0 {out.Raw = map[string]interface{}{"grok": map[string]interface{}{"duration_ms": ev.DurationMS, "outcome": ev.Outcome}}}- m.append(out, ev.Index)+ m.append(out, SourceLifecycle, ev.Index)case "yolo_toggled":out := m.base(ev.TS, "session.context", "session", schema.SeverityInfo, schema.FidelityObserved, "Grok YOLO mode changed")out.Raw = map[string]interface{}{"grok": ev}- m.append(out, ev.Index)+ m.append(out, SourceLifecycle, ev.Index)case "turn_ended":- out := m.base(ev.TS, "session.ended", "session", schema.SeverityInfo, schema.FidelityObserved, "Grok session turn ended")- if ev.Outcome != "" || ev.CancellationCategory != "" {- out.Raw = map[string]interface{}{"grok": map[string]interface{}{"outcome": ev.Outcome, "cancellation_category": ev.CancellationCategory}}+ // A turn is not a session. Grok writes turn_ended once per assistant turn and keeps the+ // session open -- the next prompt appends to the same chat_history.jsonl -- so mapping it+ // to session.ended would close a session repeatedly while only one session.started was+ // ever written, and every duration and still-open count computed from the log would be+ // wrong. session.context is the action the Codex and fx integrations already use for+ // session metadata that is not a lifecycle boundary. Grok exposes no session-end record at+ // all, so Beacon writes no session.ended for this runtime rather than inventing one, the+ // same posture fx and Kiro take.+ out := m.base(ev.TS, "session.context", "session", schema.SeverityInfo, schema.FidelityObserved, "Grok turn ended")+ detail := map[string]interface{}{"lifecycle": "turn_ended"}+ if ev.Outcome != "" {+ detail["outcome"] = ev.Outcome}- m.append(out, ev.Index)+ if ev.CancellationCategory != "" {+ detail["cancellation_category"] = ev.CancellationCategory+ }+ if ev.TurnNumber > 0 {+ detail["turn_number"] = ev.TurnNumber+ }+ out.Raw = map[string]interface{}{"grok": detail}+ m.append(out, SourceLifecycle, ev.Index)}}@@ -175,7 +200,7 @@ func (m *mapper) emitLifecycleStart() {if title := firstNonEmpty(m.summary().GeneratedTitle, m.summary().SessionSummary); title != "" {ev.Raw = map[string]interface{}{"grok": map[string]interface{}{"title": title}}}- m.append(ev, 0)+ m.append(ev, SourceSession, 0)}func (m *mapper) toolCallEvent(call ToolCall, seq int) schema.Event {@@ -245,8 +270,28 @@ func (m *mapper) base(ts, action, category string, severity schema.Severity, fidreturn ev}-func (m *mapper) append(ev schema.Event, sourceSeq int) {- m.out = append(m.out, MappedEvent{Event: ev, SourceSeq: sourceSeq})+// append records an event unless the collector has already written it.+//+// The cursor is per source file and holds the last line written, so a line is skipped at or below+// it. session.started has no line of its own and is gated by its own flag.+func (m *mapper) append(ev schema.Event, kind SourceKind, line int) {+ if m.collected(kind, line) {+ return+ }+ m.out = append(m.out, MappedEvent{Event: ev, SourceKind: kind, SourceLine: line})+}++func (m *mapper) collected(kind SourceKind, line int) bool {+ switch kind {+ case SourceChat:+ return line <= m.opts.MinChatLine+ case SourceLifecycle:+ return line <= m.opts.MinLifecycleLine+ case SourceSession:+ return m.opts.SkipStarted+ default:+ return false+ }}func (m *mapper) summary() Summary {diff --git a/cli/beacon/internal/groksession/store.go b/cli/beacon/internal/groksession/store.goindex 6dfb4826..20e91757 100644--- a/cli/beacon/internal/groksession/store.go+++ b/cli/beacon/internal/groksession/store.go@@ -135,9 +135,16 @@ func readJSONLines[T any](path string) ([]T, int) {defer f.Close()var out []Tmalformed := 0+ lineNo := 0scanner := bufio.NewScanner(f)scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)for scanner.Scan() {+ // Index is the physical line number rather than the position among the lines that parsed.+ // Grok appends to these files while a session runs, so a sweep can catch a line that is only+ // half written; it is counted as malformed now and parses on the next sweep. Numbering by+ // parse position would renumber every line after it once it parsed, and the collector's+ // cursor -- which is a line number -- would skip or repeat records it had already read.+ lineNo++line := strings.TrimSpace(scanner.Text())if line == "" {continue@@ -149,9 +156,9 @@ func readJSONLines[T any](path string) ([]T, int) {}switch v := any(&item).(type) {case *ChatMessage:- v.Index = len(out) + 1+ v.Index = lineNocase *LifecycleEvent:- v.Index = len(out) + 1+ v.Index = lineNo}out = append(out, item)}diff --git a/cli/beacon/internal/groksession/types.go b/cli/beacon/internal/groksession/types.goindex fb5e4ad9..e8e7f221 100644--- a/cli/beacon/internal/groksession/types.go+++ b/cli/beacon/internal/groksession/types.go@@ -91,9 +91,42 @@ type SessionData struct {TerminalLogs map[string]string}+// SourceKind names where a mapped event came from, so the collector can keep one cursor per+// append-only source file instead of re-reading a session whole. A Grok session directory has two+// of them -- chat_history.jsonl and events.jsonl -- and they grow independently, so a single+// "how far did we get" number cannot describe both.+type SourceKind string++const (+ // SourceSession marks an event derived from the session as a whole (summary.json plus the+ // first turn_started row) rather than from a numbered line of either log. There is exactly+ // one, session.started, and the cursor records it as a flag rather than a position.+ SourceSession SourceKind = "session"+ // SourceChat marks an event mapped from a chat_history.jsonl line.+ SourceChat SourceKind = "chat"+ // SourceLifecycle marks an event mapped from an events.jsonl line.+ SourceLifecycle SourceKind = "lifecycle"+)++// MapOptions carries the collector's cursor into the mapper. The mapper always reads the whole+// session -- a tool_result line names a tool call recorded in an earlier assistant line, so the+// context has to be rebuilt every sweep -- but emits only what lies past the cursor.+type MapOptions struct {+ // MinChatLine is the last chat_history.jsonl line already written; lines at or below it are+ // skipped.+ MinChatLine int+ // MinLifecycleLine is the last events.jsonl line already written.+ MinLifecycleLine int+ // SkipStarted suppresses session.started once it has been written for this session.+ SkipStarted bool+}+type MappedEvent struct {- Event schema.Event- SourceSeq int+ Event schema.Event+ // SourceKind and SourceLine locate the record this event was mapped from, which is what the+ // collector advances its cursor over.+ SourceKind SourceKind+ SourceLine int}type Stats struct {diff --git a/docs/runtimes/grok-build.mdx b/docs/runtimes/grok-build.mdxindex b3904cc2..c9930085 100644--- a/docs/runtimes/grok-build.mdx+++ b/docs/runtimes/grok-build.mdx@@ -30,6 +30,8 @@ Asymptote checks for its managed Grok hook file at `~/.grok/hooks/beacon-endpoinUse `beacon endpoint hooks status --harness grok` to inspect Grok Build hook status. Use `beacon endpoint grok status` to inspect committed local sessions and whether Beacon has synced them.+`beacon endpoint discover` reports both paths together: installed hooks are enough to report Grok telemetry as enabled, and the session cursor is what it falls back to when the hooks are not installed.+## Install or configuration support`beacon endpoint install` prepares shared endpoint config and runtime log paths. Install Grok Build hooks separately:@@ -63,6 +65,7 @@ beacon endpoint grok sync --print| Prompt telemetry | Supported through `UserPromptSubmit` hooks and session sync || Command, tool, and file telemetry | Supported for live hook payloads and committed session records. Session sync reads `chat_history.jsonl`, `events.jsonl`, `summary.json`, `prompt_context.json`, and terminal logs where present || Approval telemetry | Live hooks can observe and enforce at pre-tool time; session sync can report committed Grok permission request/resolution records after the fact |+| Session lifecycle | `session.started` only. Grok's `turn_ended` record ends a turn, not a session — the next prompt appends to the same session — so session sync records it as `session.context` carrying the turn number and outcome. Grok exposes no session-end record, so Asymptote writes no `session.ended` for this runtime rather than inventing one || Local JSONL and dashboard | Supported || MDM deployment | Supported for the endpoint agent. Grok hooks are installed separately in the logged-in user's context or project context |@@ -72,6 +75,8 @@ Project-level Grok Build hooks require `/hooks-trust` in Grok before they executSession sync keeps its cursor in Beacon endpoint state rather than in `~/.grok`, and `--print` is a dry run: it prints mapped events without writing the runtime log or consuming the cursor. Because it reads committed records, every synced event is marked `harness.collection_method=poll`.+The cursor is a line position in each of a session's two append-only logs, so a session that is still being written is collected incrementally: a later sweep, including each `--watch` tick, emits only the records added since the last one. `--user` and `--system` keep separate cursors beside the runtime log each one writes to, so the two modes never claim each other's progress.+Restart Grok after installing or removing hooks so new sessions pick up the updated hook configuration.## Related