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
package groksession
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionwindow"
)
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 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 {
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")
}
var stateFile = sessionsync.StateFile[State]{
Name: "Grok session",
New: func() *State { return &State{Version: StateVersion, Sessions: map[string]*Cursor{}} },
Valid: func(s *State) bool { return s.Version == StateVersion && s.Sessions != nil },
Stamp: func(s *State) {
if s.Sessions == nil {
s.Sessions = map[string]*Cursor{}
}
s.Version = StateVersion
},
}
func LoadState(path string) (*State, error) { return stateFile.Load(path) }
func (s *State) Save(path string) error { return stateFile.Save(path, s) }
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
// Since, when set, limits the sweep to sessions modified at or after it, newest first. Older
// sessions are not read and their cursors do not move, so a later sync still collects them.
// The install-time backfill sets it; an ordinary sync leaves it zero.
Since time.Time
// Budget, when set, caps the bytes this sweep may append. The sweep stops at the first event
// that does not fit and returns writer.ErrBudgetSpent, with cursors past only what was written.
Budget *writer.Budget
// RotateBytes is the size the runtime log rotates at while this sweep writes it; zero is
// writer.DefaultRotateBytes.
RotateBytes int64
// guard keeps the sweep from rotating its own output out of the log; CollectOnce sets it.
guard *writer.RetentionGuard
}
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"`
sessionsync.Retention
}
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
}
refs = sessionwindow.Recent(refs, opts.Since, func(r SessionRef) int64 { return r.ModTimeUnixMS })
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
opts.guard = sessionsync.NewRetentionGuard(opts.Print, opts.Write)
var stopErr error
for _, ref := range refs {
changed, collectErr := collectSession(store, ref, state, opts, &summary)
if sessionsync.Stopped(collectErr) {
// Not a failed session: this one and the rest are left for a later sync, with cursors
// that have not moved past anything that was not written.
if changed {
summary.SessionsChanged++
}
stopErr = collectErr
errs = append(errs, collectErr)
break
}
if collectErr != nil {
summary.Errors++
errs = append(errs, fmt.Errorf("Grok session %s: %w", ref.ID, collectErr))
continue
}
if changed {
summary.SessionsChanged++
}
}
if rotatedOut := summary.Finish(opts.sink(), stopErr); rotatedOut != nil {
errs = append(errs, rotatedOut)
}
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
}
// A file that came back shorter than the cursor was rewritten, not appended to: Grok compacts a
// session and can migrate its chat format, and every line of the new file then sits at or below
// the cursor and would be skipped forever. Reset that file's position so the rewritten content
// is read; the Started flag is left alone, so session.started is not written a second time.
//
// The comparison is against the number of lines the file held, not the number of records that
// parsed out of it. They are different numbers -- one blank or half-written line makes the
// record count smaller than the line count -- and comparing the record count against a line
// cursor would read an ordinary malformed line as a rewrite and re-emit the whole file.
//
// A file that yielded no lines at all never resets anything. Zero is what an absent file reads
// as, and it is also what a file truncated to nothing reads as; treating that as a rewrite
// would throw away a good cursor over a log that has nothing in it to re-collect. Compaction
// is not missed by waiting: the check runs every sweep, so the first one that sees the
// rewritten file with content in it resets then.
minChat := cursor.ChatLine
minLifecycle := cursor.LifecycleLine
if data.ChatLines > 0 && data.ChatLines < cursor.ChatLine {
minChat = 0
cursor.ChatLine = 0
}
if data.LifecycleLines > 0 && data.LifecycleLines < cursor.LifecycleLine {
minLifecycle = 0
cursor.LifecycleLine = 0
}
mapped := MapSession(data, MapOptions{
MinChatLine: minChat,
MinLifecycleLine: minLifecycle,
SkipStarted: cursor.Started,
})
if len(mapped) == 0 {
cursor.UpdatedAtMS = ref.ModTimeUnixMS
return false, nil
}
written := 0
for _, item := range mapped {
if err := opts.sink().Emit(item.Event); err != nil {
commit(cursor, mapped, written)
return true, err
}
written++
summary.EventsEmitted++
}
commit(cursor, mapped, written)
cursor.UpdatedAtMS = ref.ModTimeUnixMS
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 (o CollectOptions) sink() sessionsync.Sink {
return sessionsync.Sink{Print: o.Print, Out: o.Out, Write: o.Write, Log: writer.Options{Path: o.LogPath, UserMode: o.UserMode, RotateSize: o.RotateBytes, Budget: o.Budget, Guard: o.guard}}
}