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
add grok build session support
Justin D'Souza38ae53c81df4
diff --git a/cli/beacon/cmd/endpoint_grok.go b/cli/beacon/cmd/endpoint_grok.gonew file mode 100644index 00000000..6dbfe30f--- /dev/null+++ b/cli/beacon/cmd/endpoint_grok.go@@ -0,0 +1,170 @@+package cmd++import (+ "context"+ "encoding/json"+ "fmt"+ "time"++ "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"+)++var endpointGrokCmd = &cobra.Command{+ Use: "grok",+ Short: "Collect telemetry from Grok Build sessions",+ Long: `Collect endpoint telemetry from Grok Build's local session store.++The live Grok hook integration remains available through+'beacon endpoint hooks install --harness grok'. This command reads committed+session files under ~/.grok/sessions and converts them into endpoint events+marked harness.collection_method=poll, so it can backfill historical sessions+but cannot hold, allow, or deny tool calls.`,+}++var endpointGrokSyncCmd = &cobra.Command{+ Use: "sync",+ Short: "Read new Grok Build session records into the runtime log",+ SilenceUsage: true,+ RunE: runEndpointGrokSync,+}++var endpointGrokStatusCmd = &cobra.Command{+ Use: "status",+ Short: "Show Grok Build sessions on this machine and how much has been collected",+ SilenceUsage: true,+ RunE: runEndpointGrokStatus,+}++var endpointGrokOpts struct {+ sessionsDir string+ statePath string+ logPath string+ print bool+ watch bool+ interval time.Duration+}++func init() {+ endpointCmd.AddCommand(endpointGrokCmd)+ endpointGrokCmd.AddCommand(endpointGrokSyncCmd)+ endpointGrokCmd.AddCommand(endpointGrokStatusCmd)++ for _, c := range []*cobra.Command{endpointGrokSyncCmd, endpointGrokStatusCmd} {+ f := c.Flags()+ f.StringVar(&endpointGrokOpts.sessionsDir, "sessions-dir", "", "Grok session directory (default ~/.grok/sessions)")+ f.StringVar(&endpointGrokOpts.statePath, "state", "", "Collector cursor file (default ~/.beacon/endpoint/state/grok-sessions.json)")+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")+ }++ sync := endpointGrokSyncCmd.Flags()+ sync.StringVar(&endpointGrokOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")+ sync.BoolVar(&endpointGrokOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")+ sync.BoolVar(&endpointGrokOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")+ sync.DurationVar(&endpointGrokOpts.interval, "interval", time.Minute, "Sweep interval for --watch")+}++func runEndpointGrokSync(cmd *cobra.Command, args []string) error {+ userMode := endpointUserMode()+ opts := groksession.CollectOptions{+ SessionsDir: endpointGrokOpts.sessionsDir,+ Print: endpointGrokOpts.print,+ Out: cmd.OutOrStdout(),+ Write: !endpointGrokOpts.print,+ UserMode: userMode,+ }+ if !endpointGrokOpts.print {+ opts.StatePath = resolveGrokStatePath(endpointGrokOpts.statePath)+ opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointGrokOpts.logPath).EffectiveLogPath+ }++ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ if endpointGrokOpts.watch && !endpointGrokOpts.print {+ return watchGrok(ctx, cmd, opts)+ }+ summary, err := groksession.CollectOnce(opts)+ reportGrokSweep(cmd, summary)+ return err+}++func watchGrok(ctx context.Context, cmd *cobra.Command, opts groksession.CollectOptions) error {+ interval := endpointGrokOpts.interval+ if interval < 5*time.Second {+ interval = 5 * time.Second+ }+ for {+ summary, err := groksession.CollectOnce(opts)+ if err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "grok sync error: %v\n", err)+ }+ reportGrokSweep(cmd, summary)+ select {+ case <-ctx.Done():+ return nil+ case <-time.After(interval):+ }+ }+}++func reportGrokSweep(cmd *cobra.Command, summary groksession.SummaryResult) {+ if endpointGrokOpts.print {+ return+ }+ if endpointOpts.jsonOutput {+ _ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)+ return+ }+ fmt.Fprintf(cmd.OutOrStdout(), "grok sync: %d sessions, %d changed, %d events, %d errors\n",+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)+ if summary.MalformedLines > 0 {+ fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in Grok session logs\n", summary.MalformedLines)+ }+}++func runEndpointGrokStatus(cmd *cobra.Command, args []string) error {+ store, err := groksession.NewStore(endpointGrokOpts.sessionsDir)+ if err != nil {+ return err+ }+ refs, err := store.List()+ if err != nil {+ return err+ }+ state, err := groksession.LoadState(resolveGrokStatePath(endpointGrokOpts.statePath))+ if err != nil {+ return err+ }+ type status struct {+ Sessions int `json:"sessions"`+ Collected int `json:"collected"`+ StatePath string `json:"state_path"`+ }+ out := status{Sessions: len(refs), StatePath: resolveGrokStatePath(endpointGrokOpts.statePath)}+ for _, ref := range refs {+ cursor := state.Sessions[ref.ID]+ if cursor != nil && cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {+ out.Collected+++ }+ }+ if endpointOpts.jsonOutput {+ return json.NewEncoder(cmd.OutOrStdout()).Encode(out)+ }+ fmt.Fprintf(cmd.OutOrStdout(), "grok sessions: %d found, %d collected\n", out.Sessions, out.Collected)+ if out.Collected < out.Sessions {+ fmt.Fprintln(cmd.OutOrStdout(), " run `beacon endpoint grok sync` to collect new committed sessions")+ }+ return nil+}++func resolveGrokStatePath(path string) string {+ if path != "" {+ return path+ }+ return groksession.DefaultStatePath()+}diff --git a/cli/beacon/internal/endpoint/harness/grok.go b/cli/beacon/internal/endpoint/harness/grok.gonew file mode 100644index 00000000..0a099e1f--- /dev/null+++ b/cli/beacon/internal/endpoint/harness/grok.go@@ -0,0 +1,57 @@+package harness++import (+ "fmt"+ "os"+ "path/filepath"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/groksession"+)++const GrokName = groksession.Harness++func DiscoverGrok() Harness {+ h := Harness{Name: GrokName, DisplayName: "Grok Build", Capability: "hooks+session_log"}+ detectExecutable(&h, "grok")+ home, _ := os.UserHomeDir()+ sessionsDir := filepath.Join(home, ".grok", "sessions")+ h.ConfigPath = sessionsDir+ if !h.Detected && dirExists(filepath.Join(home, ".grok")) {+ h.Detected = true+ }+ h.TelemetryStatus, h.Message = grokCollectionStatus(sessionsDir)+ return h+}++func grokCollectionStatus(sessionsDir string) (TelemetryStatus, string) {+ store := &groksession.Store{Dir: sessionsDir}+ if !store.Exists() {+ return TelemetryMissing, "Grok Build has written no sessions on this machine"+ }+ refs, err := store.List()+ if err != nil {+ return TelemetryMissing, "Grok Build sessions could not be read: " + err.Error()+ }+ if len(refs) == 0 {+ return TelemetryMissing, "Grok Build has written no sessions on this machine"+ }+ state, err := groksession.LoadState(groksession.DefaultStatePath())+ if err != nil {+ return TelemetryMisconfigured, "Grok Build collector state could not be read: " + err.Error()+ }+ collected := 0+ for _, 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))+ }+}diff --git a/cli/beacon/internal/endpoint/harness/harness.go b/cli/beacon/internal/endpoint/harness/harness.goindex a9b6618d..3170f375 100644--- a/cli/beacon/internal/endpoint/harness/harness.go+++ b/cli/beacon/internal/endpoint/harness/harness.go@@ -60,6 +60,7 @@ func DiscoverAll() []Harness {DiscoverPi(),DiscoverOmp(),DiscoverOpenClaw(),+ DiscoverGrok(),DiscoverPrime(),DiscoverOmo(),DiscoverFx(),diff --git a/cli/beacon/internal/groksession/collect.go b/cli/beacon/internal/groksession/collect.gonew file mode 100644index 00000000..eb09b899--- /dev/null+++ b/cli/beacon/internal/groksession/collect.go@@ -0,0 +1,196 @@+package groksession++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"+)++const StateVersion = 1++type Cursor struct {+ UpdatedAtMS int64 `json:"updated_at_ms,omitempty"`+ Events int `json:"events,omitempty"`+}++type State struct {+ Version int `json:"version"`+ Sessions map[string]*Cursor `json:"sessions"`+}++func DefaultStatePath() string {+ base := filepath.Join(os.TempDir(), "beacon")+ if home, err := os.UserHomeDir(); err == nil && strings.TrimSpace(home) != "" {+ base = filepath.Join(home, ".beacon")+ }+ return filepath.Join(base, "endpoint", "state", "grok-sessions.json")+}++func LoadState(path string) (*State, error) {+ state := &State{Version: StateVersion, Sessions: map[string]*Cursor{}}+ if path == "" {+ return state, nil+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return state, nil+ }+ return nil, err+ }+ var stored State+ if err := json.Unmarshal(data, &stored); err != nil {+ return nil, fmt.Errorf("read Grok session collector state %s: %w", path, err)+ }+ if stored.Version != StateVersion || stored.Sessions == nil {+ return state, nil+ }+ return &stored, nil+}++func (s *State) Save(path string) error {+ if path == "" {+ return nil+ }+ if s.Sessions == nil {+ s.Sessions = map[string]*Cursor{}+ }+ s.Version = StateVersion+ data, err := json.MarshalIndent(s, "", " ")+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return err+ }+ tmp := path + ".tmp"+ if err := os.WriteFile(tmp, data, 0o600); err != nil {+ return err+ }+ return os.Rename(tmp, path)+}++func (s *State) cursor(id string) *Cursor {+ if s.Sessions == nil {+ s.Sessions = map[string]*Cursor{}+ }+ c := s.Sessions[id]+ if c == nil {+ c = &Cursor{}+ s.Sessions[id] = c+ }+ return c+}++type CollectOptions struct {+ SessionsDir string+ StatePath string+ LogPath string+ Write bool+ UserMode bool+ Print bool+ Out io.Writer+}++type SummaryResult struct {+ Sessions int `json:"sessions"`+ SessionsChanged int `json:"sessions_changed"`+ EventsEmitted int `json:"events_emitted"`+ Errors int `json:"errors"`+ MalformedLines int `json:"malformed_lines"`+}++func CollectOnce(opts CollectOptions) (summary SummaryResult, err error) {+ if opts.Print && !opts.Write {+ opts.StatePath = ""+ }+ store, err := NewStore(opts.SessionsDir)+ if err != nil {+ return summary, err+ }+ refs, err := store.List()+ if err != nil {+ return summary, err+ }+ summary.Sessions = len(refs)+ if len(refs) == 0 {+ return summary, nil+ }+ state, err := LoadState(opts.StatePath)+ if err != nil {+ return summary, err+ }+ defer func() {+ if saveErr := state.Save(opts.StatePath); saveErr != nil && err == nil {+ err = fmt.Errorf("save Grok session collector state: %w", saveErr)+ }+ }()++ var errs []error+ for _, ref := range refs {+ changed, collectErr := collectSession(store, ref, state, opts, &summary)+ if collectErr != nil {+ summary.Errors+++ errs = append(errs, fmt.Errorf("Grok session %s: %w", ref.ID, collectErr))+ continue+ }+ if changed {+ summary.SessionsChanged+++ }+ }+ if len(errs) > 0 {+ return summary, errors.Join(errs...)+ }+ return summary, nil+}++func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *SummaryResult) (bool, error) {+ cursor := state.cursor(ref.ID)+ if cursor.UpdatedAtMS >= ref.ModTimeUnixMS && cursor.Events > 0 {+ return false, nil+ }+ data, stats, err := store.Read(ref)+ summary.MalformedLines += stats.Malformed+ if err != nil {+ return false, err+ }+ mapped := MapSession(data)+ if len(mapped) == 0 {+ cursor.UpdatedAtMS = ref.ModTimeUnixMS+ return false, nil+ }+ for _, item := range mapped {+ if err := emit(item.Event, opts); err != nil {+ return true, err+ }+ summary.EventsEmitted+++ }+ cursor.UpdatedAtMS = ref.ModTimeUnixMS+ cursor.Events = len(mapped)+ return true, nil+}++func emit(event schema.Event, opts CollectOptions) error {+ if opts.Print && opts.Out != nil {+ data, err := json.Marshal(event)+ if err != nil {+ return err+ }+ if _, err := opts.Out.Write(append(data, '\n')); err != nil {+ return err+ }+ }+ if opts.Write {+ if _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode}); err != nil {+ return err+ }+ }+ return nil+}diff --git a/cli/beacon/internal/groksession/collect_test.go b/cli/beacon/internal/groksession/collect_test.gonew file mode 100644index 00000000..7739df74--- /dev/null+++ b/cli/beacon/internal/groksession/collect_test.go@@ -0,0 +1,193 @@+package groksession++import (+ "bufio"+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestStoreListsAndMapsGrokSession(t *testing.T) {+ root := t.TempDir()+ sessionDir := writeFixtureSession(t, root, "/tmp/grok project", "session-1")++ store, err := NewStore(root)+ if err != nil {+ t.Fatalf("NewStore returned error: %v", err)+ }+ refs, err := store.List()+ if err != nil {+ t.Fatalf("List returned error: %v", err)+ }+ if len(refs) != 1 {+ t.Fatalf("refs = %d, want 1", len(refs))+ }+ if refs[0].Workspace != "/tmp/grok project" {+ t.Fatalf("workspace = %q, want decoded path", refs[0].Workspace)+ }+ if refs[0].SourcePath != sessionDir {+ t.Fatalf("source path = %q, want %q", refs[0].SourcePath, sessionDir)+ }++ data, stats, err := store.Read(refs[0])+ if err != nil {+ t.Fatalf("Read returned error: %v", err)+ }+ if stats.Malformed != 0 {+ t.Fatalf("Malformed = %d, want 0", stats.Malformed)+ }+ events := MapSession(data)+ if len(events) == 0 {+ t.Fatal("MapSession returned no events")+ }+ byAction := map[string]jsonEvent{}+ for _, item := range events {+ byAction[item.Event.Event.Action] = jsonEventFromSchema(t, item.Event)+ }+ prompt := byAction["prompt.submitted"]+ if prompt.Harness.CollectionMethod != "poll" {+ t.Fatalf("collection method = %q, want poll", prompt.Harness.CollectionMethod)+ }+ if prompt.Prompt.Text != "run ls token=secret" {+ t.Fatalf("prompt = %q", prompt.Prompt.Text)+ }+ cmd := byAction["command.executed"]+ if cmd.Command.Command != "ls -la" {+ t.Fatalf("command = %q, want ls -la", cmd.Command.Command)+ }+ if cmd.Command.Output != "total 0\n" {+ t.Fatalf("command output = %q, want terminal log", cmd.Command.Output)+ }+ if byAction["approval.allowed"].Approval.Decision != "allowed" {+ t.Fatalf("approval event = %#v", byAction["approval.allowed"].Approval)+ }+}++func TestCollectOnceIsIdempotentAndPrintDoesNotAdvanceState(t *testing.T) {+ root := t.TempDir()+ writeFixtureSession(t, root, "/tmp/grok project", "session-1")+ statePath := filepath.Join(t.TempDir(), "state.json")+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")++ var printed bytes.Buffer+ printSummary, err := CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, Print: true, Out: &printed})+ if err != nil {+ t.Fatalf("print CollectOnce returned error: %v", err)+ }+ if printSummary.EventsEmitted == 0 || printed.Len() == 0 {+ t.Fatalf("print emitted nothing: summary=%+v output=%q", printSummary, printed.String())+ }+ if _, err := os.Stat(statePath); !os.IsNotExist(err) {+ t.Fatalf("--print advanced state or unexpected stat error: %v", err)+ }++ first, err := CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true})+ if err != nil {+ t.Fatalf("CollectOnce returned error: %v", err)+ }+ if first.EventsEmitted == 0 {+ t.Fatal("first CollectOnce emitted no events")+ }+ second, err := CollectOnce(CollectOptions{SessionsDir: root, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true})+ if err != nil {+ t.Fatalf("second CollectOnce returned error: %v", err)+ }+ if second.EventsEmitted != 0 || second.SessionsChanged != 0 {+ t.Fatalf("second summary = %+v, want no new work", second)+ }+ if lines := countLines(t, logPath); lines != first.EventsEmitted {+ t.Fatalf("runtime lines = %d, want %d", lines, first.EventsEmitted)+ }+}++func writeFixtureSession(t *testing.T, root, workspace, sessionID string) string {+ t.Helper()+ sessionDir := filepath.Join(root, urlPathEscape(workspace), sessionID)+ if err := os.MkdirAll(filepath.Join(sessionDir, "terminal"), 0o755); err != nil {+ t.Fatalf("mkdir session: %v", err)+ }+ writeFile(t, filepath.Join(sessionDir, "summary.json"), `{+ "created_at":"2026-05-21T16:49:22.269243Z",+ "updated_at":"2026-05-21T16:50:25.853796Z",+ "generated_title":"Fixture session",+ "current_model_id":"grok-build",+ "num_messages":6,+ "num_chat_messages":4+}`)+ writeFile(t, filepath.Join(sessionDir, "prompt_context.json"), `{"working_directory":"`+workspace+`","os_name":"macos","shell_path":"/bin/bash"}`)+ writeFile(t, filepath.Join(sessionDir, "events.jsonl"),+ `{"ts":"2026-05-21T16:49:25.601Z","type":"turn_started","session_id":"`+sessionID+`","turn_number":0,"model_id":"grok-build"}`+"\n"++ `{"ts":"2026-05-21T16:49:27.545Z","type":"permission_requested","tool_name":"run_terminal_command"}`+"\n"++ `{"ts":"2026-05-21T16:49:27.545Z","type":"permission_resolved","tool_name":"run_terminal_command","decision":"allow","wait_ms":0}`+"\n"++ `{"ts":"2026-05-21T16:49:27.552Z","type":"tool_completed","tool_name":"run_terminal_command","duration_ms":6,"outcome":"success"}`+"\n"++ `{"ts":"2026-05-21T16:50:25.814Z","type":"turn_ended","outcome":"success"}`+"\n")+ writeFile(t, filepath.Join(sessionDir, "chat_history.jsonl"),+ `{"type":"user","content":[{"type":"text","text":"run ls token=secret"}]}`+"\n"++ `{"type":"assistant","content":"","reasoning":{"text":"Need to inspect files"},"tool_calls":[{"id":"call-abc","name":"run_terminal_command","arguments":"{\"command\":\"ls -la\",\"description\":\"list files\"}"}],"model_id":"grok-build"}`+"\n"++ `{"type":"tool_result","tool_call_id":"call-abc","content":"fallback output"}`+"\n"++ `{"type":"assistant","content":"done","model_id":"grok-build"}`+"\n")+ writeFile(t, filepath.Join(sessionDir, "terminal", "call-abc-1.log"), "total 0\n")+ return sessionDir+}++func writeFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func countLines(t *testing.T, path string) int {+ t.Helper()+ f, err := os.Open(path)+ if err != nil {+ t.Fatalf("open %s: %v", path, err)+ }+ defer f.Close()+ n := 0+ scanner := bufio.NewScanner(f)+ for scanner.Scan() {+ n+++ }+ if err := scanner.Err(); err != nil {+ t.Fatalf("scan %s: %v", path, err)+ }+ return n+}++type jsonEvent struct {+ Harness struct {+ CollectionMethod string `json:"collection_method"`+ } `json:"harness"`+ Prompt struct {+ Text string `json:"text"`+ } `json:"prompt"`+ Command struct {+ Command string `json:"command"`+ Output string `json:"output"`+ } `json:"command"`+ Approval struct {+ Decision string `json:"decision"`+ } `json:"approval"`+}++func jsonEventFromSchema(t *testing.T, event interface{}) jsonEvent {+ t.Helper()+ data, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal event: %v", err)+ }+ var out jsonEvent+ if err := json.Unmarshal(data, &out); err != nil {+ t.Fatalf("unmarshal event: %v", err)+ }+ return out+}++func urlPathEscape(path string) string {+ replacer := strings.NewReplacer("/", "%2F", " ", "%20")+ return replacer.Replace(path)+}diff --git a/cli/beacon/internal/groksession/mapper.go b/cli/beacon/internal/groksession/mapper.gonew file mode 100644index 00000000..8307cdd2--- /dev/null+++ b/cli/beacon/internal/groksession/mapper.go@@ -0,0 +1,421 @@+package groksession++import (+ "encoding/json"+ "sort"+ "strings"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"+)++func MapSession(data SessionData) []MappedEvent {+ m := &mapper{+ data: data,+ toolByID: map[string]ToolCall{},+ toolOutput: map[string]string{},+ }+ for _, msg := range data.Chat {+ if msg.Type == "assistant" {+ for _, call := range msg.ToolCalls {+ m.toolByID[call.ID] = call+ }+ }+ }+ m.emitLifecycleStart()+ for _, item := range m.orderedItems() {+ switch v := item.value.(type) {+ case ChatMessage:+ m.consumeChat(v)+ case LifecycleEvent:+ m.consumeLifecycle(v)+ }+ }+ return m.out+}++type mapper struct {+ data SessionData+ out []MappedEvent+ toolByID map[string]ToolCall+ toolOutput map[string]string+}++type orderedItem struct {+ ts time.Time+ seq int+ value interface{}+}++func (m *mapper) orderedItems() []orderedItem {+ items := make([]orderedItem, 0, len(m.data.Chat)+len(m.data.Lifecycle))+ for _, msg := range m.data.Chat {+ items = append(items, orderedItem{seq: msg.Index * 100, value: msg})+ }+ for _, ev := range m.data.Lifecycle {+ if ev.Type == "turn_started" {+ continue+ }+ items = append(items, orderedItem{ts: parseTime(ev.TS), seq: ev.Index*100 + 50, value: ev})+ }+ sort.SliceStable(items, func(i, j int) bool {+ if !items[i].ts.IsZero() && !items[j].ts.IsZero() && !items[i].ts.Equal(items[j].ts) {+ return items[i].ts.Before(items[j].ts)+ }+ return items[i].seq < items[j].seq+ })+ return items+}++func (m *mapper) consumeChat(msg ChatMessage) {+ switch msg.Type {+ case "user":+ text := contentText(msg.Content)+ if text == "" || msg.SyntheticReason != "" {+ return+ }+ 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)+ case "assistant":+ model := firstNonEmpty(msg.ModelID, m.summary().CurrentModelID)+ if msg.Reasoning != nil && msg.Reasoning.Text != "" {+ ev := m.base("", "agent.reasoning", "agent", schema.SeverityInfo, schema.FidelityObserved, "Grok assistant reasoning")+ ev.Model = model+ ev.GenAI = &schema.GenAIInfo{+ Output: &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{+ "role": "assistant",+ "content": []map[string]string{{+ "type": "reasoning",+ "text": msg.Reasoning.Text,+ }},+ }}},+ }+ ev.Content = contentMarker(msg.Reasoning.Text)+ m.append(ev, msg.Index)+ }+ if text := contentText(msg.Content); text != "" {+ ev := m.base("", "agent.message", "agent", schema.SeverityInfo, schema.FidelityObserved, "Grok assistant message")+ ev.Model = model+ ev.GenAI = &schema.GenAIInfo{Output: &schema.GenAIOutputInfo{Messages: []map[string]interface{}{{"role": "assistant", "content": text}}}}+ ev.Content = contentMarker(text)+ m.append(ev, msg.Index)+ }+ for _, call := range msg.ToolCalls {+ ev := m.toolCallEvent(call, msg.Index)+ ev.Model = model+ m.append(ev, msg.Index)+ }+ case "tool_result":+ call := m.toolByID[msg.ToolCallID]+ output := contentText(msg.Content)+ if log := m.data.TerminalLogs[msg.ToolCallID]; log != "" {+ output = log+ }+ m.toolOutput[msg.ToolCallID] = output+ ev := m.toolResultEvent(call, msg.ToolCallID, output)+ m.append(ev, msg.Index)+ }+}++func (m *mapper) consumeLifecycle(ev LifecycleEvent) {+ switch ev.Type {+ case "permission_requested":+ 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)+ 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}+ out.Approval = &schema.ApprovalInfo{Required: true, Decision: normalizeDecision(ev.Decision)}+ if ev.WaitMS > 0 {+ out.Raw = map[string]interface{}{"grok": map[string]interface{}{"approval_wait_ms": ev.WaitMS}}+ }+ m.append(out, 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.+ if strings.EqualFold(ev.Outcome, "success") {+ return+ }+ out := m.base(ev.TS, "tool.failed", "tool", schema.SeverityHigh, schema.FidelityObserved, "Grok tool failed")+ out.Tool = &schema.ToolInfo{Name: ev.ToolName}+ 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)+ 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)+ 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}}+ }+ m.append(out, ev.Index)+ }+}++func (m *mapper) emitLifecycleStart() {+ ts := ""+ for _, ev := range m.data.Lifecycle {+ if ev.Type == "turn_started" {+ ts = ev.TS+ break+ }+ }+ if ts == "" {+ ts = m.summary().CreatedAt+ }+ ev := m.base(ts, "session.started", "session", schema.SeverityInfo, schema.FidelityObserved, "Grok session started")+ 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)+}++func (m *mapper) toolCallEvent(call ToolCall, seq int) schema.Event {+ args := decodeArgs(call.Arguments)+ action := actionForTool(call.Name, false)+ ev := m.base("", action, categoryForAction(action), schema.SeverityInfo, schema.FidelityObserved, "Grok tool invoked")+ ev.Tool = &schema.ToolInfo{Name: call.Name}+ if command := stringArg(args, "command"); command != "" {+ ev.Tool.Command = command+ ev.Command = &schema.CommandInfo{Command: command}+ }+ if path := pathArg(call.Name, args); path != "" {+ ev.Tool.Path = path+ ev.File = &schema.FileInfo{Path: path, Operation: fileOperation(call.Name)}+ }+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{+ Name: call.Name,+ Call: &schema.GenAIToolCallInfo{ID: call.ID, Arguments: args},+ }}+ return ev+}++func (m *mapper) toolResultEvent(call ToolCall, callID, output string) schema.Event {+ args := decodeArgs(call.Arguments)+ action := actionForTool(call.Name, true)+ ev := m.base("", action, categoryForAction(action), schema.SeverityInfo, schema.FidelityObserved, "Grok tool completed")+ ev.Tool = &schema.ToolInfo{Name: call.Name}+ if command := stringArg(args, "command"); command != "" {+ ev.Tool.Command = command+ ev.Command = &schema.CommandInfo{Command: command, Output: output}+ ev.Content = contentMarker(output)+ }+ if path := pathArg(call.Name, args); path != "" {+ ev.Tool.Path = path+ ev.File = &schema.FileInfo{Path: path, Operation: fileOperation(call.Name)}+ }+ ev.GenAI = &schema.GenAIInfo{Tool: &schema.GenAIToolInfo{+ Name: call.Name,+ Call: &schema.GenAIToolCallInfo{ID: callID, Arguments: args, Result: output},+ }}+ return ev+}++func (m *mapper) base(ts, action, category string, severity schema.Severity, fidelity, message string) schema.Event {+ ev := schema.NewEvent(schema.NewEventOptions{+ Action: action,+ Category: category,+ Severity: severity,+ Fidelity: fidelity,+ Message: message,+ Origin: schema.OriginLocal,+ Harness: schema.HarnessInfo{+ Name: Harness,+ CollectionMethod: schema.CollectionMethodPoll,+ },+ })+ if ts != "" {+ ev.Timestamp = normalizeTimestamp(ts)+ }+ ev.Session = &schema.SessionInfo{ID: m.data.Ref.ID, WorkingDirectory: m.data.Ref.Workspace}+ if model := m.summary().CurrentModelID; model != "" {+ ev.Model = asymptoteobserve.NormalizeModelName(model)+ }+ if m.summary().HeadBranch != "" {+ ev.Branch = m.summary().HeadBranch+ }+ return ev+}++func (m *mapper) append(ev schema.Event, sourceSeq int) {+ m.out = append(m.out, MappedEvent{Event: ev, SourceSeq: sourceSeq})+}++func (m *mapper) summary() Summary {+ if m.data.Ref.Summary == nil {+ return Summary{}+ }+ return *m.data.Ref.Summary+}++func contentText(raw json.RawMessage) string {+ if len(raw) == 0 || string(raw) == "null" {+ return ""+ }+ var s string+ if err := json.Unmarshal(raw, &s); err == nil {+ return s+ }+ var parts []struct {+ Type string `json:"type"`+ Text string `json:"text"`+ }+ if err := json.Unmarshal(raw, &parts); err == nil {+ var b strings.Builder+ for _, part := range parts {+ if part.Text == "" {+ continue+ }+ if b.Len() > 0 {+ b.WriteString("\n")+ }+ b.WriteString(part.Text)+ }+ return b.String()+ }+ return ""+}++func decodeArgs(raw json.RawMessage) map[string]interface{} {+ if len(raw) == 0 {+ return nil+ }+ var encoded string+ if err := json.Unmarshal(raw, &encoded); err == nil {+ var out map[string]interface{}+ if err := json.Unmarshal([]byte(encoded), &out); err == nil {+ return out+ }+ return map[string]interface{}{"raw": encoded}+ }+ var out map[string]interface{}+ if err := json.Unmarshal(raw, &out); err == nil {+ return out+ }+ return nil+}++func actionForTool(name string, completed bool) string {+ switch strings.ToLower(name) {+ case "run_terminal_command":+ if completed {+ return "command.executed"+ }+ return "tool.invoked"+ case "read_file", "list_dir", "grep":+ if completed {+ return "file.read"+ }+ return "tool.invoked"+ case "search_replace", "write_file":+ if completed {+ return "file.modified"+ }+ return "tool.invoked"+ default:+ if completed {+ return "tool.completed"+ }+ return "tool.invoked"+ }+}++func categoryForAction(action string) string {+ switch {+ case strings.HasPrefix(action, "command."):+ return "command"+ case strings.HasPrefix(action, "file."):+ return "file"+ default:+ return "tool"+ }+}++func pathArg(tool string, args map[string]interface{}) string {+ switch strings.ToLower(tool) {+ case "read_file":+ return stringArg(args, "target_file", "path", "file")+ case "list_dir":+ return stringArg(args, "target_directory", "path", "directory")+ case "grep":+ return stringArg(args, "path", "glob")+ case "search_replace", "write_file":+ return stringArg(args, "target_file", "path", "file")+ default:+ return stringArg(args, "path", "target_file", "target_directory")+ }+}++func fileOperation(tool string) string {+ switch strings.ToLower(tool) {+ case "search_replace":+ return "modify"+ case "write_file":+ return "write"+ default:+ return "read"+ }+}++func stringArg(args map[string]interface{}, keys ...string) string {+ for _, key := range keys {+ if v, ok := args[key].(string); ok {+ return v+ }+ }+ return ""+}++func normalizeDecision(decision string) string {+ switch strings.ToLower(strings.TrimSpace(decision)) {+ case "allow", "allowed", "approve", "approved":+ return "allowed"+ case "deny", "denied", "block", "blocked":+ return "denied"+ default:+ if decision == "" {+ return "unknown"+ }+ return strings.ToLower(decision)+ }+}++func contentMarker(text string) *schema.ContentInfo {+ return asymptoteobserve.RetainedContent(text, 0)+}++func normalizeTimestamp(ts string) string {+ t := parseTime(ts)+ if t.IsZero() {+ return schema.FormatTimestamp(time.Now())+ }+ return schema.FormatTimestamp(t)+}++func parseTime(ts string) time.Time {+ if ts == "" {+ return time.Time{}+ }+ t, err := time.Parse(time.RFC3339Nano, ts)+ if err != nil {+ return time.Time{}+ }+ return t+}++func firstNonEmpty(values ...string) string {+ for _, value := range values {+ if strings.TrimSpace(value) != "" {+ return value+ }+ }+ return ""+}diff --git a/cli/beacon/internal/groksession/store.go b/cli/beacon/internal/groksession/store.gonew file mode 100644index 00000000..6dfb4826--- /dev/null+++ b/cli/beacon/internal/groksession/store.go@@ -0,0 +1,193 @@+package groksession++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "net/url"+ "os"+ "path/filepath"+ "sort"+ "strings"+)++type Store struct {+ Dir string+}++func DefaultSessionsDir() string {+ home, err := os.UserHomeDir()+ if err != nil || strings.TrimSpace(home) == "" {+ return filepath.Join(".", ".grok", "sessions")+ }+ return filepath.Join(home, ".grok", "sessions")+}++func NewStore(dir string) (*Store, error) {+ if strings.TrimSpace(dir) == "" {+ dir = DefaultSessionsDir()+ }+ return &Store{Dir: dir}, nil+}++func (s *Store) Exists() bool {+ info, err := os.Stat(s.Dir)+ return err == nil && info.IsDir()+}++func (s *Store) List() ([]SessionRef, error) {+ entries, err := os.ReadDir(s.Dir)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil, nil+ }+ return nil, err+ }+ var refs []SessionRef+ for _, project := range entries {+ if !project.IsDir() {+ continue+ }+ workspace, err := url.PathUnescape(project.Name())+ if err != nil {+ workspace = project.Name()+ }+ projectDir := filepath.Join(s.Dir, project.Name())+ sessions, err := os.ReadDir(projectDir)+ if err != nil {+ continue+ }+ for _, session := range sessions {+ if !session.IsDir() {+ continue+ }+ sourcePath := filepath.Join(projectDir, session.Name())+ if !fileExists(filepath.Join(sourcePath, "summary.json")) || !fileExists(filepath.Join(sourcePath, "chat_history.jsonl")) {+ continue+ }+ ref := SessionRef{ID: session.Name(), Workspace: workspace, SourcePath: sourcePath}+ if info, err := os.Stat(sourcePath); err == nil {+ ref.ModTimeUnixMS = info.ModTime().UnixMilli()+ }+ if summary, err := readJSONFile[Summary](filepath.Join(sourcePath, "summary.json")); err == nil {+ ref.Summary = summary+ if ts := parseMillis(summary.UpdatedAt); ts > ref.ModTimeUnixMS {+ ref.ModTimeUnixMS = ts+ }+ if summary.CurrentModelID == "" && summary.SessionSummary == "" && summary.GeneratedTitle == "" {+ ref.Summary = nil+ }+ }+ refs = append(refs, ref)+ }+ }+ sort.Slice(refs, func(i, j int) bool {+ if refs[i].ModTimeUnixMS == refs[j].ModTimeUnixMS {+ return refs[i].ID < refs[j].ID+ }+ return refs[i].ModTimeUnixMS < refs[j].ModTimeUnixMS+ })+ return refs, nil+}++func (s *Store) Read(ref SessionRef) (SessionData, Stats, error) {+ data := SessionData{Ref: ref, TerminalLogs: map[string]string{}}+ var stats Stats+ if prompt, err := readJSONFile[PromptContext](filepath.Join(ref.SourcePath, "prompt_context.json")); err == nil {+ data.Prompt = prompt+ if prompt.WorkingDirectory != "" {+ data.Ref.Workspace = prompt.WorkingDirectory+ }+ }+ data.Chat, stats.Malformed = readJSONLines[ChatMessage](filepath.Join(ref.SourcePath, "chat_history.jsonl"))+ lifecycle, malformed := readJSONLines[LifecycleEvent](filepath.Join(ref.SourcePath, "events.jsonl"))+ stats.Malformed += malformed+ data.Lifecycle = lifecycle+ if ref.Summary == nil {+ if summary, err := readJSONFile[Summary](filepath.Join(ref.SourcePath, "summary.json")); err == nil {+ data.Ref.Summary = summary+ }+ }+ if err := readTerminalLogs(filepath.Join(ref.SourcePath, "terminal"), data.TerminalLogs); err != nil {+ return data, stats, err+ }+ return data, stats, nil+}++func readJSONFile[T any](path string) (*T, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, err+ }+ var out T+ if err := json.Unmarshal(data, &out); err != nil {+ return nil, fmt.Errorf("parse %s: %w", path, err)+ }+ return &out, nil+}++func readJSONLines[T any](path string) ([]T, int) {+ f, err := os.Open(path)+ if err != nil {+ return nil, 0+ }+ defer f.Close()+ var out []T+ malformed := 0+ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var item T+ if err := json.Unmarshal([]byte(line), &item); err != nil {+ malformed+++ continue+ }+ switch v := any(&item).(type) {+ case *ChatMessage:+ v.Index = len(out) + 1+ case *LifecycleEvent:+ v.Index = len(out) + 1+ }+ out = append(out, item)+ }+ if err := scanner.Err(); err != nil {+ malformed+++ }+ return out, malformed+}++func readTerminalLogs(dir string, logs map[string]string) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ return err+ }+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".log") {+ continue+ }+ path := filepath.Join(dir, entry.Name())+ data, err := os.ReadFile(path)+ if err != nil {+ continue+ }+ callID := strings.TrimSuffix(entry.Name(), ".log")+ if idx := strings.LastIndex(callID, "-"); idx > len("call-") {+ callID = callID[:idx]+ }+ logs[callID] = string(data)+ }+ return nil+}++func fileExists(path string) bool {+ info, err := os.Stat(path)+ return err == nil && !info.IsDir()+}diff --git a/cli/beacon/internal/groksession/types.go b/cli/beacon/internal/groksession/types.gonew file mode 100644index 00000000..fb5e4ad9--- /dev/null+++ b/cli/beacon/internal/groksession/types.go@@ -0,0 +1,112 @@+package groksession++import (+ "encoding/json"+ "time"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+)++const Harness = "grok"++type SessionRef struct {+ ID string+ Workspace string+ SourcePath string+ ModTimeUnixMS int64+ Summary *Summary+}++type Summary struct {+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+ GeneratedTitle string `json:"generated_title"`+ SessionSummary string `json:"session_summary"`+ CurrentModelID string `json:"current_model_id"`+ HeadBranch string `json:"head_branch"`+ HeadCommit string `json:"head_commit"`+ SessionKind string `json:"session_kind"`+ NumMessages int `json:"num_messages"`+ NumChatMessages int `json:"num_chat_messages"`+ ChatFormat int `json:"chat_format_version"`+ LastActiveAt string `json:"last_active_at"`+ RequestID string `json:"request_id"`+ GrokHome string `json:"grok_home"`+}++type PromptContext struct {+ WorkingDirectory string `json:"working_directory"`+ OSName string `json:"os_name"`+ ShellPath string `json:"shell_path"`+ Version int `json:"version"`+ PromptMode string `json:"prompt_mode"`+ IsNonInteractive bool `json:"is_non_interactive"`+}++type ChatMessage struct {+ Type string `json:"type"`+ Content json.RawMessage `json:"content"`+ Reasoning *Reasoning `json:"reasoning,omitempty"`+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`+ ToolCallID string `json:"tool_call_id,omitempty"`+ ModelID string `json:"model_id,omitempty"`+ ModelFingerprint string `json:"model_fingerprint,omitempty"`+ SyntheticReason string `json:"synthetic_reason,omitempty"`+ Index int `json:"-"`+}++type Reasoning struct {+ Text string `json:"text,omitempty"`+ Encrypted string `json:"encrypted,omitempty"`+ ID string `json:"id,omitempty"`+}++type ToolCall struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Arguments json.RawMessage `json:"arguments"`+}++type LifecycleEvent struct {+ Type string `json:"type"`+ TS string `json:"ts"`+ SessionID string `json:"session_id,omitempty"`+ TurnNumber int `json:"turn_number,omitempty"`+ ModelID string `json:"model_id,omitempty"`+ ToolName string `json:"tool_name,omitempty"`+ Decision string `json:"decision,omitempty"`+ WaitMS int64 `json:"wait_ms,omitempty"`+ DurationMS int64 `json:"duration_ms,omitempty"`+ Outcome string `json:"outcome,omitempty"`+ CancellationCategory string `json:"cancellation_category,omitempty"`+ ConversationMessageCount int `json:"conversation_message_count,omitempty"`+ Index int `json:"-"`+}++type SessionData struct {+ Ref SessionRef+ Prompt *PromptContext+ Chat []ChatMessage+ Lifecycle []LifecycleEvent+ TerminalLogs map[string]string+}++type MappedEvent struct {+ Event schema.Event+ SourceSeq int+}++type Stats struct {+ Malformed int+}++func parseMillis(s string) int64 {+ if s == "" {+ return 0+ }+ t, err := time.Parse(time.RFC3339Nano, s)+ if err != nil {+ return 0+ }+ return t.UnixMilli()+}diff --git a/docs/runtimes/grok-build.mdx b/docs/runtimes/grok-build.mdxindex 2e913111..b3904cc2 100644--- a/docs/runtimes/grok-build.mdx+++ b/docs/runtimes/grok-build.mdx@@ -17,15 +17,18 @@ Before enabling Grok Build hooks, make sure:- Project-level hooks are trusted with `/hooks-trust` in Grok before you expect them to execute.- Grok is restarted after hook install or removal so new sessions load the updated hook file.-## Collection path+## Collection paths-Grok Build invokes Asymptote's hook adapter from Asymptote's owned hook file. The adapter writes normalized endpoint events to the configured runtime JSONL log.+Grok Build has two local collection paths:++- Live hooks: Grok invokes Asymptote's hook adapter from Asymptote's owned hook file. The adapter writes normalized endpoint events to the configured runtime JSONL log and can participate in Beacon's external policy seam.+- Session sync: `beacon endpoint grok sync` reads committed sessions under `~/.grok/sessions/<url-escaped-working-directory>/<session-id>` and writes endpoint events marked `harness.collection_method=poll`. This backfills historical or unhooked sessions after Grok has written them, so it cannot hold, allow, or deny a tool call.## Discovery and statusAsymptote checks for its managed Grok hook file at `~/.grok/hooks/beacon-endpoint.json` for user-level installs or `./.grok/hooks/beacon-endpoint.json` for project-level installs.-Use `beacon endpoint hooks status --harness grok` to inspect Grok Build hook status.+Use `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.## Install or configuration support@@ -41,12 +44,25 @@ For project-level hooks, run:beacon endpoint hooks install --harness grok --level project```+Backfill committed Grok Build sessions:++```bash title="Sync committed Grok Build sessions"+beacon endpoint grok sync+```++Preview what the session sync would collect without writing the runtime log or advancing the cursor:++```bash title="Preview Grok Build session sync"+beacon endpoint grok sync --print+```+## Telemetry coverage| Area | Support ||------|---------|-| Prompt telemetry | Supported through `UserPromptSubmit` hooks |-| Command, tool, and file telemetry | Supported for session, prompt, pre-tool, post-tool, failed tool, stop, session-end, command, and file telemetry where Grok exposes payloads |+| 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 || 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 |@@ -54,6 +70,8 @@ beacon endpoint hooks install --harness grok --level projectProject-level Grok Build hooks require `/hooks-trust` in Grok before they execute. Grok tool failures normalize to `tool.failed` with high severity.+Session 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`.+Restart Grok after installing or removing hooks so new sessions pick up the updated hook configuration.## Related