Skip to content

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

fix(claude sync): stop before rotation discards the sweep's own output (#619)

Claude17bb1bb558b3
diff --git a/cli/beacon/cmd/endpoint_claude.go b/cli/beacon/cmd/endpoint_claude.go
index b867688e..0fa4d596 100644
--- a/cli/beacon/cmd/endpoint_claude.go
+++ b/cli/beacon/cmd/endpoint_claude.go
@@ -10,6 +10,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
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/endpoint/writer"
"github.com/spf13/cobra"
)
@@ -26,8 +27,16 @@ Beacon sees what Claude already wrote, so nothing here can hold or deny a tool c
}
var endpointClaudeSyncCmd = &cobra.Command{
- Use: "sync",
- Short: "Read new Claude Code session records into the runtime log",
+ Use: "sync",
+ Short: "Read new Claude Code session records into the runtime log",
+ Long: `Read new Claude Code session records into the runtime log.
+
+The runtime log keeps the live file plus five archives, 10 MiB each by default, and every
+rotation deletes the oldest. A sweep never rotates out its own output: when writing more would
+delete the file holding the sweep's first event, it stops, reports how many sessions are still
+pending, and leaves their cursors where they were, so the next sweep picks them up. Between
+sweeps, ship or copy the log files if you need to keep every event, or backfill a large history
+in one sweep with a larger --rotate-bytes.`,
SilenceUsage: true,
RunE: runEndpointClaudeSync,
}
@@ -46,6 +55,7 @@ var endpointClaudeOpts struct {
print bool
watch bool
interval time.Duration
+ rotateBytes int64
}
func init() {
@@ -67,9 +77,17 @@ func init() {
sync.BoolVar(&endpointClaudeOpts.print, "print", false, "Print mapped events as JSON without writing them or advancing the cursor (dry run)")
sync.BoolVar(&endpointClaudeOpts.watch, "watch", false, "Sweep continuously on --interval (default: one sweep then exit)")
sync.DurationVar(&endpointClaudeOpts.interval, "interval", time.Minute, "Sweep interval for --watch")
+ sync.Int64Var(&endpointClaudeOpts.rotateBytes, "rotate-bytes", 0,
+ "Rotate the runtime log at this many bytes while this sync writes it (default 10485760, the size every Beacon writer uses; must not be smaller)")
}
-func runEndpointClaudeSync(cmd *cobra.Command, args []string) error {
+// claudeSyncOptions turns the sync flags into collector options.
+func claudeSyncOptions(cmd *cobra.Command) (claudesession.CollectOptions, error) {
+ // Smaller than the shared size would only make this sync rotate more often than every other
+ // writer, shrinking what the log keeps for everyone.
+ if endpointClaudeOpts.rotateBytes != 0 && endpointClaudeOpts.rotateBytes < writer.DefaultRotateBytes {
+ return claudesession.CollectOptions{}, fmt.Errorf("--rotate-bytes must be at least %d, the size every Beacon writer rotates the runtime log at", writer.DefaultRotateBytes)
+ }
userMode := endpointUserMode()
opts := claudesession.CollectOptions{
ProjectsDir: endpointClaudeOpts.projectsDir,
@@ -77,11 +95,20 @@ func runEndpointClaudeSync(cmd *cobra.Command, args []string) error {
Out: cmd.OutOrStdout(),
Write: !endpointClaudeOpts.print,
UserMode: userMode,
+ RotateBytes: endpointClaudeOpts.rotateBytes,
}
if !endpointClaudeOpts.print {
opts.StatePath = resolveClaudeStatePath(endpointClaudeOpts.statePath, userMode)
opts.LogPath = lifecycle.ResolveRuntimeLog(userMode, endpointClaudeOpts.logPath).EffectiveLogPath
}
+ return opts, nil
+}
+
+func runEndpointClaudeSync(cmd *cobra.Command, args []string) error {
+ opts, err := claudeSyncOptions(cmd)
+ if err != nil {
+ return err
+ }
ctx := cmd.Context()
if ctx == nil {
@@ -123,8 +150,17 @@ func reportClaudeSweep(cmd *cobra.Command, summary claudesession.Summary) {
_ = json.NewEncoder(cmd.OutOrStdout()).Encode(summary)
return
}
- fmt.Fprintf(cmd.OutOrStdout(), "claude sync: %d sessions, %d changed, %d events, %d errors\n",
- summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.Errors)
+ fmt.Fprintf(cmd.OutOrStdout(), "claude sync: %d sessions, %d changed, %d events (%d retained), %d errors\n",
+ summary.Sessions, summary.SessionsChanged, summary.EventsEmitted, summary.EventsRetained, summary.Errors)
+ if summary.RetentionLimited {
+ fmt.Fprintf(cmd.OutOrStdout(), " stopped before log rotation would discard this sweep's own events; %d session(s) left pending for the next sweep.\n"+
+ " Ship or copy the runtime log before the next sweep to keep every event, or backfill in one sweep with a larger --rotate-bytes.\n",
+ summary.SessionsPending)
+ }
+ if summary.EventsRotatedOut > 0 {
+ fmt.Fprintf(cmd.OutOrStdout(), " %d event(s) this sweep wrote were rotated out of the runtime log by another writer before it finished\n",
+ summary.EventsRotatedOut)
+ }
if summary.MalformedLines > 0 {
fmt.Fprintf(cmd.OutOrStdout(), " %d unreadable line(s) in Claude session logs\n", summary.MalformedLines)
}
diff --git a/cli/beacon/cmd/endpoint_claude_test.go b/cli/beacon/cmd/endpoint_claude_test.go
new file mode 100644
index 00000000..8a208c6b
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_claude_test.go
@@ -0,0 +1,158 @@
+package cmd
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/claudesession"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+type claudeCommandFixture struct {
+ projectsDir string
+ statePath string
+ logPath string
+}
+
+func newClaudeCommandFixture(t *testing.T) claudeCommandFixture {
+ t.Helper()
+ root := t.TempDir()
+ f := claudeCommandFixture{
+ projectsDir: filepath.Join(root, "projects"),
+ statePath: filepath.Join(root, "state", "claude.json"),
+ logPath: filepath.Join(root, "logs", "runtime.jsonl"),
+ }
+ session := filepath.Join(f.projectsDir, "-tmp-repo", "sess-1.jsonl")
+ if err := os.MkdirAll(filepath.Dir(session), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ line := `{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"hello"},"uuid":"u1","timestamp":"2026-09-19T22:00:00.000Z","cwd":"/tmp/repo","sessionId":"sess-1","version":"2.1.154","gitBranch":"main"}`
+ if err := os.WriteFile(session, []byte(line+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ // Command flags are package-level, so each test sets every one it depends on.
+ endpointClaudeOpts.projectsDir = f.projectsDir
+ endpointClaudeOpts.statePath = f.statePath
+ endpointClaudeOpts.logPath = f.logPath
+ endpointClaudeOpts.print = false
+ endpointClaudeOpts.watch = false
+ endpointClaudeOpts.rotateBytes = 0
+ endpointOpts.jsonOutput = false
+ endpointOpts.userMode = true
+ endpointOpts.systemMode = false
+ t.Cleanup(func() {
+ endpointClaudeOpts.projectsDir = ""
+ endpointClaudeOpts.statePath = ""
+ endpointClaudeOpts.logPath = ""
+ endpointClaudeOpts.rotateBytes = 0
+ endpointOpts.jsonOutput = false
+ })
+ return f
+}
+
+func runClaudeSync(t *testing.T) (string, error) {
+ t.Helper()
+ var out bytes.Buffer
+ endpointClaudeSyncCmd.SetOut(&out)
+ endpointClaudeSyncCmd.SetErr(&out)
+ t.Cleanup(func() {
+ endpointClaudeSyncCmd.SetOut(nil)
+ endpointClaudeSyncCmd.SetErr(nil)
+ })
+ err := runEndpointClaudeSync(endpointClaudeSyncCmd, nil)
+ return out.String(), err
+}
+
+// A window smaller than the one every other Beacon writer rotates at would only shrink what the
+// log keeps, so it is refused before anything is written.
+func TestEndpointClaudeSyncRejectsARotateBytesBelowTheDefault(t *testing.T) {
+ f := newClaudeCommandFixture(t)
+ endpointClaudeOpts.rotateBytes = 1024
+
+ _, err := runClaudeSync(t)
+ if err == nil || !strings.Contains(err.Error(), "--rotate-bytes") {
+ t.Fatalf("err = %v, want a --rotate-bytes error", err)
+ }
+ if _, statErr := os.Stat(f.logPath); !os.IsNotExist(statErr) {
+ t.Error("a refused --rotate-bytes still wrote the runtime log")
+ }
+ if _, statErr := os.Stat(f.statePath); !os.IsNotExist(statErr) {
+ t.Error("a refused --rotate-bytes still advanced the cursor")
+ }
+}
+
+func TestEndpointClaudeSyncPassesRotateBytesToTheCollector(t *testing.T) {
+ newClaudeCommandFixture(t)
+ endpointClaudeOpts.rotateBytes = 4 * writer.DefaultRotateBytes
+
+ opts, err := claudeSyncOptions(endpointClaudeSyncCmd)
+ if err != nil {
+ t.Fatalf("claudeSyncOptions: %v", err)
+ }
+ if opts.RotateBytes != 4*writer.DefaultRotateBytes {
+ t.Fatalf("RotateBytes = %d, want %d", opts.RotateBytes, 4*writer.DefaultRotateBytes)
+ }
+ out, err := runClaudeSync(t)
+ if err != nil {
+ t.Fatalf("sync with a larger --rotate-bytes: %v\n%s", err, out)
+ }
+ if !strings.Contains(out, "2 events (2 retained)") {
+ t.Errorf("text summary does not report retained events:\n%s", out)
+ }
+}
+
+// The text summary is what a person reads after a backfill; a sweep the window stopped has to say
+// so, say what is left, and name the way out.
+func TestReportClaudeSweepWarnsWhenTheRotationWindowStoppedTheSweep(t *testing.T) {
+ newClaudeCommandFixture(t)
+ var out bytes.Buffer
+ endpointClaudeSyncCmd.SetOut(&out)
+ t.Cleanup(func() { endpointClaudeSyncCmd.SetOut(nil) })
+
+ reportClaudeSweep(endpointClaudeSyncCmd, claudesession.Summary{
+ Sessions: 3496, SessionsChanged: 400, EventsEmitted: 70000, EventsRetained: 70000,
+ RetentionLimited: true, SessionsPending: 3096,
+ })
+ text := out.String()
+ for _, want := range []string{"70000 retained", "3096 session(s) left pending", "--rotate-bytes"} {
+ if !strings.Contains(text, want) {
+ t.Errorf("summary missing %q:\n%s", want, text)
+ }
+ }
+}
+
+func TestReportClaudeSweepWarnsWhenEventsWereRotatedOut(t *testing.T) {
+ newClaudeCommandFixture(t)
+ var out bytes.Buffer
+ endpointClaudeSyncCmd.SetOut(&out)
+ t.Cleanup(func() { endpointClaudeSyncCmd.SetOut(nil) })
+
+ reportClaudeSweep(endpointClaudeSyncCmd, claudesession.Summary{EventsEmitted: 10, EventsRetained: 4, EventsRotatedOut: 6})
+ if !strings.Contains(out.String(), "6 event(s)") {
+ t.Errorf("summary does not report the rotated-out events:\n%s", out.String())
+ }
+}
+
+func TestReportClaudeSweepJSONCarriesTheRetentionFields(t *testing.T) {
+ newClaudeCommandFixture(t)
+ endpointOpts.jsonOutput = true
+ var out bytes.Buffer
+ endpointClaudeSyncCmd.SetOut(&out)
+ t.Cleanup(func() { endpointClaudeSyncCmd.SetOut(nil) })
+
+ reportClaudeSweep(endpointClaudeSyncCmd, claudesession.Summary{EventsEmitted: 2, EventsRetained: 2})
+ var decoded map[string]any
+ if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
+ t.Fatalf("decode %q: %v", out.String(), err)
+ }
+ for _, key := range []string{"events_emitted", "events_retained", "events_rotated_out", "retention_limited", "sessions_pending"} {
+ if _, ok := decoded[key]; !ok {
+ t.Errorf("JSON summary has no %q: %s", key, out.String())
+ }
+ }
+}
diff --git a/cli/beacon/internal/claudesession/collect.go b/cli/beacon/internal/claudesession/collect.go
index 8f75bb4f..ce069c1a 100644
--- a/cli/beacon/internal/claudesession/collect.go
+++ b/cli/beacon/internal/claudesession/collect.go
@@ -35,6 +35,11 @@ type CollectOptions struct {
UserMode bool
Print bool
Out io.Writer
+ // RotateBytes is the size at which this sweep rotates the runtime log; zero means the size
+ // every Beacon writer uses. The archive count is not configurable here: the hooks and the
+ // collector prune archives past the shared count on their next rotation, and readers only
+ // look that far, so a sweep that kept more would lose them anyway.
+ RotateBytes int64
}
type Summary struct {
@@ -44,6 +49,18 @@ type Summary struct {
Errors int `json:"errors"`
MalformedLines int `json:"malformed_lines"`
PartialSessions int `json:"partial_sessions"`
+ // EventsRetained is how many of the events this sweep wrote are still in the runtime log or
+ // its archives when it finishes. Events the writer suppressed as duplicates are in neither.
+ EventsRetained int `json:"events_retained"`
+ // EventsRotatedOut is how many events this sweep wrote that another writer's rotations
+ // discarded before it finished. The sweep never rotates out its own output.
+ EventsRotatedOut int `json:"events_rotated_out"`
+ // RetentionLimited is set when the sweep stopped because writing more would have rotated its
+ // own output out of the log. SessionsPending is how many sessions still have records to read:
+ // the one the sweep stopped inside (also counted in SessionsChanged when it wrote part of it)
+ // and every later one with new records. Their cursors were left where they were.
+ RetentionLimited bool `json:"retention_limited"`
+ SessionsPending int `json:"sessions_pending"`
}
func DefaultStatePath() string {
@@ -131,9 +148,25 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {
}
}()
+ var guard *writer.RetentionGuard
+ if opts.Write && !opts.Print {
+ guard = &writer.RetentionGuard{}
+ }
var errs []error
- for _, ref := range refs {
- changed, collectErr := collectSession(store, ref, state, opts, &summary)
+ for i, ref := range refs {
+ changed, collectErr := collectSession(store, ref, state, opts, guard, &summary)
+ if errors.Is(collectErr, writer.ErrRetentionWindowFull) {
+ // Not a failed session: this one and the rest are simply left for the next sweep,
+ // with cursors that have not moved past anything that was not written.
+ if changed {
+ summary.SessionsChanged++
+ }
+ summary.RetentionLimited = true
+ summary.SessionsPending = 1 + countChanged(refs[i+1:], state)
+ errs = append(errs, fmt.Errorf("stopped after %d events with %d Claude session(s) pending: %w",
+ summary.EventsEmitted, summary.SessionsPending, collectErr))
+ break
+ }
if collectErr != nil {
summary.Errors++
errs = append(errs, fmt.Errorf("Claude session %s: %w", ref.ID, collectErr))
@@ -143,13 +176,34 @@ func CollectOnce(opts CollectOptions) (summary Summary, err error) {
summary.SessionsChanged++
}
}
+ if guard != nil {
+ summary.EventsRetained = guard.Retained()
+ summary.EventsRotatedOut = guard.Written() - summary.EventsRetained
+ if summary.EventsRotatedOut > 0 {
+ errs = append(errs, fmt.Errorf("%d of the %d events this sweep wrote were rotated out of the runtime log by another writer before it finished",
+ summary.EventsRotatedOut, guard.Written()))
+ }
+ }
if len(errs) > 0 {
return summary, errors.Join(errs...)
}
return summary, nil
}
-func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, summary *Summary) (bool, error) {
+// countChanged is how many of refs have records the cursor has not reached, which is what a
+// sweep that stopped before them leaves for the next one.
+func countChanged(refs []SessionRef, state *State) int {
+ n := 0
+ for _, ref := range refs {
+ c := state.Files[ref.Path]
+ if c == nil || ref.SizeBytes != c.SizeBytes || ref.ModTimeUnixMS != c.ModTimeUnixMS {
+ n++
+ }
+ }
+ return n
+}
+
+func collectSession(store *Store, ref SessionRef, state *State, opts CollectOptions, guard *writer.RetentionGuard, summary *Summary) (bool, error) {
cursor := state.cursor(ref.Path)
if ref.SizeBytes < cursor.SizeBytes {
cursor.LastLine = 0
@@ -172,7 +226,7 @@ func collectSession(store *Store, ref SessionRef, state *State, opts CollectOpti
return false, nil
}
for i, item := range mapped {
- if err := emit(item.Event, opts); err != nil {
+ if err := emit(item.Event, opts, guard); err != nil {
advanceCursorPartial(cursor, mapped, i)
return true, err
}
@@ -213,7 +267,7 @@ func advanceCursorPartial(cursor *Cursor, mapped []MappedEvent, failedIdx int) {
cursor.LastLine = lastCompleteLine
}
-func emit(event schema.Event, opts CollectOptions) error {
+func emit(event schema.Event, opts CollectOptions, guard *writer.RetentionGuard) error {
if opts.Print {
out := opts.Out
if out == nil {
@@ -224,6 +278,6 @@ func emit(event schema.Event, opts CollectOptions) error {
if !opts.Write {
return nil
}
- _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode})
+ _, err := writer.AppendEvent(event, writer.Options{Path: opts.LogPath, UserMode: opts.UserMode, RotateSize: opts.RotateBytes, Guard: guard})
return err
}
diff --git a/cli/beacon/internal/claudesession/retention_test.go b/cli/beacon/internal/claudesession/retention_test.go
new file mode 100644
index 00000000..f6580578
--- /dev/null
+++ b/cli/beacon/internal/claudesession/retention_test.go
@@ -0,0 +1,182 @@
+package claudesession
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+// backfillFixture writes sessions Claude sessions of one prompt each, far more output than a
+// rotation window of a few kilobytes holds, so a sweep over them has to confront the window.
+func backfillFixture(t *testing.T, sessions int) (projects, statePath, logPath string) {
+ t.Helper()
+ dir := t.TempDir()
+ projects = filepath.Join(dir, "projects")
+ for i := 0; i < sessions; i++ {
+ id := fmt.Sprintf("sess-%03d", i)
+ writeFile(t, filepath.Join(projects, "-tmp-repo", id+".jsonl"), userLine(id, "u-"+id, "prompt "+id)+"\n")
+ }
+ return projects, filepath.Join(dir, "state", "claude.json"), filepath.Join(dir, "logs", "runtime.jsonl")
+}
+
+// retainedEvents reads every file the rotation contract keeps for logPath.
+func retainedEvents(t *testing.T, logPath string) []schema.Event {
+ t.Helper()
+ var out []schema.Event
+ for _, p := range writer.RetainedLogPaths(logPath) {
+ out = append(out, readLog(t, p)...)
+ }
+ return out
+}
+
+// shipAway moves the retained log files aside, standing in for a forwarder that has shipped them,
+// and returns what they held.
+func shipAway(t *testing.T, logPath string, batch int) []schema.Event {
+ t.Helper()
+ events := retainedEvents(t, logPath)
+ for _, p := range writer.RetainedLogPaths(logPath) {
+ if err := os.Rename(p, p+".shipped"+strconv.Itoa(batch)); err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ }
+ return events
+}
+
+const smallWindow = 4096
+
+// #619: a backfill larger than the rotation window used to rotate its own output away and report
+// errors: 0. The sweep now stops before the rotation that would discard what it wrote, says so,
+// and every event it reports as emitted is still on disk.
+func TestCollectOnceStopsAtTheRotationWindowInsteadOfDiscardingItsOwnOutput(t *testing.T) {
+ projects, statePath, logPath := backfillFixture(t, 60)
+ opts := CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true, RotateBytes: smallWindow}
+
+ summary, err := CollectOnce(opts)
+ if !errors.Is(err, writer.ErrRetentionWindowFull) {
+ t.Fatalf("CollectOnce err = %v, want ErrRetentionWindowFull", err)
+ }
+ if !summary.RetentionLimited {
+ t.Error("summary does not report that the window stopped the sweep")
+ }
+ if summary.SessionsPending == 0 || summary.SessionsPending >= summary.Sessions {
+ t.Errorf("SessionsPending = %d of %d, want some but not all", summary.SessionsPending, summary.Sessions)
+ }
+ if summary.Errors != 0 {
+ t.Errorf("Errors = %d, want 0: stopping at the window is not a failed session", summary.Errors)
+ }
+ onDisk := len(retainedEvents(t, logPath))
+ if summary.EventsEmitted == 0 || summary.EventsRetained != summary.EventsEmitted || onDisk != summary.EventsEmitted {
+ t.Fatalf("emitted=%d retained=%d on disk=%d, want all equal and non-zero",
+ summary.EventsEmitted, summary.EventsRetained, onDisk)
+ }
+ if summary.EventsRotatedOut != 0 {
+ t.Errorf("EventsRotatedOut = %d, want 0", summary.EventsRotatedOut)
+ }
+}
+
+// The cursor must not run ahead of what was written: sessions the sweep stopped before stay
+// pending, so repeated sweeps (with the log shipped in between) collect every prompt exactly once.
+func TestCollectOnceLeavesPendingSessionsForTheNextSweep(t *testing.T) {
+ const sessions = 60
+ projects, statePath, logPath := backfillFixture(t, sessions)
+ opts := CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true, RotateBytes: smallWindow}
+
+ seen := map[string]int{}
+ limited := 0
+ for batch := 0; batch < 20; batch++ {
+ summary, err := CollectOnce(opts)
+ if err != nil && !errors.Is(err, writer.ErrRetentionWindowFull) {
+ t.Fatalf("sweep %d: %v", batch, err)
+ }
+ for _, ev := range shipAway(t, logPath, batch) {
+ if ev.Event.Action == "prompt.submitted" && ev.Session != nil {
+ seen[ev.Session.ID]++
+ }
+ }
+ if !summary.RetentionLimited {
+ break
+ }
+ limited++
+ }
+ if limited == 0 {
+ t.Fatal("fixture never filled the window; the test proves nothing")
+ }
+ if len(seen) != sessions {
+ t.Errorf("collected prompts from %d sessions, want %d", len(seen), sessions)
+ }
+ for id, n := range seen {
+ if n != 1 {
+ t.Errorf("session %s prompt collected %d times, want 1", id, n)
+ }
+ }
+}
+
+// A window large enough for the backfill is the supported way to do it in one run.
+func TestCollectOnceWithALargeEnoughWindowCollectsEverythingInOneSweep(t *testing.T) {
+ projects, statePath, logPath := backfillFixture(t, 60)
+ opts := CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true, RotateBytes: 1 << 20}
+
+ summary, err := CollectOnce(opts)
+ if err != nil {
+ t.Fatalf("CollectOnce: %v", err)
+ }
+ if summary.RetentionLimited || summary.SessionsPending != 0 {
+ t.Errorf("summary = %+v, want no retention limit", summary)
+ }
+ if summary.SessionsChanged != 60 {
+ t.Errorf("SessionsChanged = %d, want 60", summary.SessionsChanged)
+ }
+ if onDisk := len(retainedEvents(t, logPath)); summary.EventsRetained != summary.EventsEmitted || onDisk != summary.EventsEmitted {
+ t.Errorf("emitted=%d retained=%d on disk=%d, want all equal", summary.EventsEmitted, summary.EventsRetained, onDisk)
+ }
+}
+
+// --print writes nothing, so it has nothing to retain and no window to fill.
+func TestCollectOncePrintIsNotRetentionLimited(t *testing.T) {
+ projects, _, _ := backfillFixture(t, 60)
+ summary, err := CollectOnce(CollectOptions{ProjectsDir: projects, Print: true, RotateBytes: smallWindow})
+ if err != nil {
+ t.Fatalf("CollectOnce --print: %v", err)
+ }
+ if summary.RetentionLimited || summary.EventsRetained != 0 || summary.SessionsChanged != 60 {
+ t.Errorf("summary = %+v, want every session printed and nothing retained", summary)
+ }
+}
+
+// Pending means records left to read. Sessions later in the sweep that were already collected have
+// none, so a stop in one growing session must not report the whole history as pending.
+func TestCollectOncePendingCountsOnlySessionsWithRecordsLeft(t *testing.T) {
+ projects, statePath, logPath := backfillFixture(t, 60)
+ full := CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true, RotateBytes: 1 << 20}
+ if _, err := CollectOnce(full); err != nil {
+ t.Fatalf("initial sweep: %v", err)
+ }
+
+ // Grow one session far past the small window and make it the oldest, so the sweep reaches it
+ // first and stops inside it with 59 already-collected sessions after it.
+ grown := filepath.Join(projects, "-tmp-repo", "sess-000.jsonl")
+ body := userLine("sess-000", "u-sess-000", "prompt sess-000") + "\n"
+ for i := 0; i < 200; i++ {
+ body += userLine("sess-000", fmt.Sprintf("u-more-%d", i), fmt.Sprintf("more %d", i)) + "\n"
+ }
+ writeFile(t, grown, body)
+ old := time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC)
+ if err := os.Chtimes(grown, old, old); err != nil {
+ t.Fatal(err)
+ }
+
+ summary, err := CollectOnce(CollectOptions{ProjectsDir: projects, StatePath: statePath, LogPath: logPath, Write: true, UserMode: true, RotateBytes: smallWindow})
+ if !errors.Is(err, writer.ErrRetentionWindowFull) {
+ t.Fatalf("err = %v, want ErrRetentionWindowFull", err)
+ }
+ if summary.SessionsPending != 1 {
+ t.Errorf("SessionsPending = %d, want 1 (only the grown session has records left)", summary.SessionsPending)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/retention.go b/cli/beacon/internal/endpoint/writer/retention.go
new file mode 100644
index 00000000..8b81cfa9
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/retention.go
@@ -0,0 +1,169 @@
+package writer
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "errors"
+ "fmt"
+ "os"
+)
+
+// ErrRetentionWindowFull is returned by a guarded append whose rotation would discard the file
+// holding the guard's first event. Nothing is written or rotated when it is returned.
+var ErrRetentionWindowFull = errors.New("the runtime log's rotation window is full of this run's own output")
+
+// RetentionGuard keeps one run of appends -- a session backfill sweep, say -- from rotating its
+// own output out of the runtime log, and reports how much of that output the log still holds.
+//
+// The log keeps the live file plus a fixed number of archives, and every rotation deletes the
+// oldest archive. A run that writes more than that window used to rotate its own first events away
+// before it finished, so a backfill of 595,640 events kept 27,550 and still reported success
+// (#619). With a guard, the append whose rotation would delete the file holding the run's first
+// event fails with ErrRetentionWindowFull instead, and the caller can stop where it is and leave
+// the rest for the next run.
+//
+// The guard counts the distinct files its appends landed in. That sees rotations by other writers
+// too (the hooks and the collector share the log), but only after the fact: another process can
+// still rotate the window over during the run, which is what Retained reports.
+//
+// The zero value is ready to use. A guard is not safe for concurrent use; give each run its own.
+type RetentionGuard struct {
+ path string
+ archives int
+ segments []retentionSegment
+}
+
+// retentionSegment is a run of consecutive guarded appends that landed in one file, identified by
+// the file and by the first of those lines: where it starts and a digest of its bytes. The file
+// identity alone is not enough, because filesystems recycle the inode of a deleted archive for the
+// next file created, and a recycled inode would make a rotated-out segment look retained.
+//
+// file is nil when the file could not be identified; its events are then assumed retained rather
+// than reported lost on no evidence.
+type retentionSegment struct {
+ file os.FileInfo
+ offset int64
+ length int
+ digest [sha256.Size]byte
+ end int64
+ events int
+}
+
+// Written is the number of events the guard's appends wrote. Appends the writer suppressed as
+// duplicates wrote nothing and are not counted.
+func (g *RetentionGuard) Written() int {
+ if g == nil {
+ return 0
+ }
+ n := 0
+ for _, s := range g.segments {
+ n += s.events
+ }
+ return n
+}
+
+// Retained is the number of the guard's written events still in a file the rotation contract
+// keeps: the live log or one of its archives. Written minus Retained is what was rotated out.
+func (g *RetentionGuard) Retained() int {
+ if g == nil || len(g.segments) == 0 {
+ return 0
+ }
+ var kept []os.FileInfo
+ var keptPaths []string
+ for _, p := range retainedPaths(g.path, g.archives) {
+ if info, err := os.Stat(p); err == nil {
+ kept = append(kept, info)
+ keptPaths = append(keptPaths, p)
+ }
+ }
+ n := 0
+ for _, s := range g.segments {
+ if s.file == nil {
+ n += s.events
+ continue
+ }
+ for i, info := range kept {
+ if os.SameFile(s.file, info) && s.firstLineAt(keptPaths[i]) {
+ n += s.events
+ break
+ }
+ }
+ }
+ return n
+}
+
+// firstLineAt reports whether path still holds the segment's first line where it was written.
+func (s retentionSegment) firstLineAt(path string) bool {
+ f, err := os.Open(path)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+ buf := make([]byte, s.length)
+ if _, err := f.ReadAt(buf, s.offset); err != nil {
+ return false
+ }
+ digest := sha256.Sum256(buf)
+ return bytes.Equal(digest[:], s.digest[:])
+}
+
+// rotationWouldDiscardOwnOutput reports whether a rotation now would delete the file holding the
+// guard's first event. The guard's files are, oldest first, at .N ... .1 and the live path, and a
+// rotation deletes .archives, so once the guard has written into archives+1 files the oldest of
+// them is at .archives. Before the guard's first write there is nothing of its own to lose.
+func (g *RetentionGuard) rotationWouldDiscardOwnOutput(archives int) bool {
+ if archives < 1 {
+ archives = DefaultRotateArchives
+ }
+ return len(g.segments) >= archives+1
+}
+
+// record notes one written line. info is the file it was appended to, stat'd after the write under
+// the log's lock, so its size is where the line ends.
+func (g *RetentionGuard) record(path string, archives int, line []byte, info os.FileInfo, statErr error) {
+ if archives < 1 {
+ archives = DefaultRotateArchives
+ }
+ g.path = path
+ g.archives = archives
+ last := len(g.segments) - 1
+ if statErr != nil {
+ // The write happened, so it counts; attribute it to the file the previous append used,
+ // which is where it almost certainly went.
+ if last >= 0 {
+ g.segments[last].events++
+ return
+ }
+ g.segments = append(g.segments, retentionSegment{events: 1})
+ return
+ }
+ end := info.Size()
+ // Same file as the previous append, and grown past where that append ended: a file that was
+ // replaced by one with a recycled inode starts over from empty.
+ if last >= 0 && g.segments[last].file != nil && os.SameFile(g.segments[last].file, info) && end > g.segments[last].end {
+ g.segments[last].events++
+ g.segments[last].end = end
+ return
+ }
+ g.segments = append(g.segments, retentionSegment{
+ file: info,
+ offset: end - int64(len(line)),
+ length: len(line),
+ digest: sha256.Sum256(line),
+ end: end,
+ events: 1,
+ })
+}
+
+// retainedPaths is RetainedLogPaths for an explicit archive count.
+func retainedPaths(path string, archives int) []string {
+ if path == "" {
+ return nil
+ }
+ paths := make([]string, 0, archives+1)
+ paths = append(paths, path)
+ for i := 1; i <= archives; i++ {
+ paths = append(paths, path+fmt.Sprintf(".%d", i))
+ }
+ return paths
+}
diff --git a/cli/beacon/internal/endpoint/writer/retention_test.go b/cli/beacon/internal/endpoint/writer/retention_test.go
new file mode 100644
index 00000000..ac8d0897
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/retention_test.go
@@ -0,0 +1,174 @@
+package writer
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+)
+
+func retentionEvent(i int) schema.Event {
+ return schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "retention event " + strconv.Itoa(i),
+ })
+}
+
+// retainedText is everything the rotation contract keeps for path, for asserting which events
+// survived.
+func retainedText(t *testing.T, path string, archives int) string {
+ t.Helper()
+ var b strings.Builder
+ for i := 0; i <= archives; i++ {
+ p := path
+ if i > 0 {
+ p = path + "." + strconv.Itoa(i)
+ }
+ data, err := os.ReadFile(p)
+ if err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+ b.Write(data)
+ }
+ return b.String()
+}
+
+// A guarded writer stops at the one append whose rotation would discard the file holding the
+// guard's first event. Every file here holds one event (RotateSize 1), so with two archives the
+// guard can place three events and the fourth is refused.
+func TestRetentionGuardRefusesTheRotationThatWouldDiscardItsOwnOutput(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ guard := &RetentionGuard{}
+ opts := Options{Path: path, RotateSize: 1, RotateArchives: 2, Guard: guard}
+
+ for i := 0; i < 3; i++ {
+ if _, err := AppendEvent(retentionEvent(i), opts); err != nil {
+ t.Fatalf("AppendEvent %d: %v", i, err)
+ }
+ }
+ before := retainedText(t, path, 2)
+
+ _, err := AppendEvent(retentionEvent(3), opts)
+ if !errors.Is(err, ErrRetentionWindowFull) {
+ t.Fatalf("fourth AppendEvent err = %v, want ErrRetentionWindowFull", err)
+ }
+ after := retainedText(t, path, 2)
+ if after != before {
+ t.Fatalf("the refused append changed the log:\nbefore:\n%s\nafter:\n%s", before, after)
+ }
+ for i := 0; i < 3; i++ {
+ if !strings.Contains(after, "retention event "+strconv.Itoa(i)+`"`) {
+ t.Errorf("event %d was rotated out of the window:\n%s", i, after)
+ }
+ }
+ if strings.Contains(after, "retention event 3") {
+ t.Errorf("the refused event was written anyway")
+ }
+ if got := guard.Written(); got != 3 {
+ t.Errorf("Written() = %d, want 3", got)
+ }
+ if got := guard.Retained(); got != 3 {
+ t.Errorf("Retained() = %d, want 3", got)
+ }
+}
+
+// Rotating data that was already in the log before the guard wrote anything is ordinary rotation,
+// not the guard's output being lost, so it is allowed and does not use up the window.
+func TestRetentionGuardAllowsRotatingPreexistingDataBeforeItsFirstWrite(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(path, []byte("pre-existing line\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ guard := &RetentionGuard{}
+ opts := Options{Path: path, RotateSize: 1, RotateArchives: 1, Guard: guard}
+
+ for i := 0; i < 2; i++ {
+ if _, err := AppendEvent(retentionEvent(i), opts); err != nil {
+ t.Fatalf("AppendEvent %d: %v", i, err)
+ }
+ }
+ if _, err := AppendEvent(retentionEvent(2), opts); !errors.Is(err, ErrRetentionWindowFull) {
+ t.Fatalf("third AppendEvent err = %v, want ErrRetentionWindowFull", err)
+ }
+ text := retainedText(t, path, 1)
+ if !strings.Contains(text, "retention event 0") || !strings.Contains(text, "retention event 1") {
+ t.Fatalf("guarded events missing from the window:\n%s", text)
+ }
+ if got := guard.Retained(); got != 2 {
+ t.Errorf("Retained() = %d, want 2", got)
+ }
+}
+
+// The guard cannot stop another process from rotating the log, but it must notice when that
+// discarded what it wrote, so a caller never reports lost events as retained.
+func TestRetentionGuardCountsEventsAnotherWriterRotatedOut(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ guard := &RetentionGuard{}
+ for i := 0; i < 2; i++ {
+ if _, err := AppendEvent(retentionEvent(i), Options{Path: path, RotateArchives: 2, Guard: guard}); err != nil {
+ t.Fatalf("guarded AppendEvent %d: %v", i, err)
+ }
+ }
+ other := Options{Path: path, RotateSize: 1, RotateArchives: 2}
+
+ if _, err := AppendEvent(retentionEvent(100), other); err != nil {
+ t.Fatal(err)
+ }
+ if got := guard.Retained(); got != 2 {
+ t.Fatalf("after one foreign rotation Retained() = %d, want 2 (the events are in .1)", got)
+ }
+ for i := 101; i < 104; i++ {
+ if _, err := AppendEvent(retentionEvent(i), other); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if strings.Contains(retainedText(t, path, 2), "retention event 0") {
+ t.Fatal("fixture did not rotate the guarded events out")
+ }
+ if got := guard.Retained(); got != 0 {
+ t.Errorf("after the window rolled over Retained() = %d, want 0", got)
+ }
+ if got := guard.Written(); got != 2 {
+ t.Errorf("Written() = %d, want 2", got)
+ }
+}
+
+// An append the writer suppresses as a duplicate writes nothing, so it is neither written nor
+// retained -- otherwise a caller would count it as lost.
+func TestRetentionGuardDoesNotCountSuppressedDuplicates(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "mcp.tool_invoked",
+ Harness: schema.HarnessInfo{Name: "cursor"},
+ Message: "Tool execution observed",
+ })
+ event.Timestamp = "2026-06-18T21:11:24Z"
+ event.Session = &schema.SessionInfo{ID: "s1"}
+ event.MCP = &schema.MCPInfo{Server: "clickhouse", Tool: "execute_sql"}
+ duplicate := event
+ duplicate.Harness.Name = "claude"
+ duplicate.Timestamp = "2026-06-18T21:11:25Z"
+
+ guard := &RetentionGuard{}
+ for _, ev := range []schema.Event{event, duplicate} {
+ if _, err := AppendEvent(ev, Options{Path: path, Guard: guard}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if w, r := guard.Written(), guard.Retained(); w != 1 || r != 1 {
+ t.Fatalf("Written()=%d Retained()=%d, want 1 and 1", w, r)
+ }
+}
+
+// A guard that never wrote has nothing to report and nothing to look at.
+func TestRetentionGuardWithNoWritesRetainsNothing(t *testing.T) {
+ guard := &RetentionGuard{}
+ if w, r := guard.Written(), guard.Retained(); w != 0 || r != 0 {
+ t.Fatalf("Written()=%d Retained()=%d, want 0 and 0", w, r)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index f688e8a0..55503015 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -30,6 +30,9 @@ type Options struct {
MaxBytes int
RotateSize int64
RotateArchives int
+ // Guard, when set, keeps this append from rotating out anything the guard's earlier appends
+ // wrote, and records where this one landed. See RetentionGuard.
+ Guard *RetentionGuard
}
// SystemLogPath is the system-mode runtime log, resolved per platform.
@@ -98,7 +101,7 @@ func AppendEvent(event schema.Event, opts Options) (string, error) {
data = stamped
}
}
- if err := appendJSONL(opts.Path, append(data, '\n'), opts.RotateSize, opts.RotateArchives); err != nil {
+ if err := appendJSONL(opts.Path, append(data, '\n'), opts.RotateSize, opts.RotateArchives, opts.Guard); err != nil {
return "", err
}
return opts.Path, nil
@@ -180,7 +183,7 @@ func SanitizeEvent(event schema.Event, maxBytes int) schema.Event {
return asymptoteobserve.SanitizeEvent(event, maxBytes)
}
-func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int) error {
+func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int, guard *RetentionGuard) error {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
@@ -202,6 +205,17 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int
if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
return nil
}
+ if guard != nil {
+ // Decided under the lock, so no other Beacon writer can rotate between the check and the
+ // rotation it permits.
+ rotate, err := needsRotation(path, rotateBytes, int64(len(line)))
+ if err != nil {
+ return err
+ }
+ if rotate && guard.rotationWouldDiscardOwnOutput(rotateArchives) {
+ return ErrRetentionWindowFull
+ }
+ }
if err := rotateIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil {
return err
}
@@ -210,8 +224,14 @@ func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int
return err
}
defer f.Close()
- _, err = f.Write(line)
- return err
+ if _, err := f.Write(line); err != nil {
+ return err
+ }
+ if guard != nil {
+ info, statErr := f.Stat()
+ guard.record(path, rotateArchives, line, info, statErr)
+ }
+ return nil
}
func openRuntimeFile(path string, flag int) (*os.File, error) {
@@ -239,15 +259,7 @@ func openRuntimeFile(path string, flag int) (*os.File, error) {
// rather than guessing how many archives exist. The hook adapter and the beaconjson exporter rotate
// with the same count, so the list covers whichever process wrote the log.
func RetainedLogPaths(path string) []string {
- if path == "" {
- return nil
- }
- paths := make([]string, 0, DefaultRotateArchives+1)
- paths = append(paths, path)
- for i := 1; i <= DefaultRotateArchives; i++ {
- paths = append(paths, path+fmt.Sprintf(".%d", i))
- }
- return paths
+ return retainedPaths(path, DefaultRotateArchives)
}
func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int64) error {
@@ -257,16 +269,10 @@ func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int
if archives < 1 {
archives = DefaultRotateArchives
}
- info, err := os.Stat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
+ rotate, err := needsRotation(path, maxSize, nextWriteBytes)
+ if err != nil || !rotate {
return err
}
- if info.Size() == 0 || info.Size()+nextWriteBytes <= maxSize {
- return nil
- }
if err := removeOverflowArchives(path, archives); err != nil {
return err
}
@@ -281,6 +287,23 @@ func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int
return os.Rename(path, rotated)
}
+// needsRotation reports whether appending nextWriteBytes to path would take it past maxSize, which
+// is when rotateIfNeeded rotates. An empty or missing file never rotates, so one oversized line
+// still lands somewhere.
+func needsRotation(path string, maxSize int64, nextWriteBytes int64) (bool, error) {
+ if maxSize <= 0 {
+ return false, nil
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
+ }
+ return info.Size() > 0 && info.Size()+nextWriteBytes > maxSize, nil
+}
+
func removeOverflowArchives(path string, archives int) error {
dir := filepath.Dir(path)
base := filepath.Base(path)
diff --git a/docs/guides/local-testing/logs.mdx b/docs/guides/local-testing/logs.mdx
index e8529314..22a8d232 100644
--- a/docs/guides/local-testing/logs.mdx
+++ b/docs/guides/local-testing/logs.mdx
@@ -74,6 +74,8 @@ runtime.jsonl.4
runtime.jsonl.5
```
+Session-file sync commands write through the same rotation. `beacon endpoint claude sync` stops before a rotation would discard its own output and leaves the rest pending; see [large backfills](/runtimes/claude-code#large-backfills-and-log-rotation).
+
External shippers should continue tailing the active `runtime.jsonl` path and use their normal file-rotation handling to checkpoint offsets. The local dashboard can inspect the active log and numbered archives when you need to review recent rotated events.
## 4. Test a custom log path
diff --git a/docs/runtimes/claude-code.mdx b/docs/runtimes/claude-code.mdx
index beaab109..42f7e6ce 100644
--- a/docs/runtimes/claude-code.mdx
+++ b/docs/runtimes/claude-code.mdx
@@ -124,6 +124,25 @@ Detailed tool inputs can contain sensitive command arguments, paths, URLs, searc
Run `beacon endpoint claude sync --watch`, or schedule one-shot sweeps, if you want the poll path to stay current. The live OTLP and hook paths remain the real-time integrations; the poll path is for backfill and catch-up.
+### Large backfills and log rotation
+
+The runtime log keeps the live file plus five archives, 10 MiB each, and every rotation deletes the oldest archive. A first sync over a long Claude Code history can produce far more than that window. A sweep never rotates out its own output. When writing the next event would delete the file that holds the sweep's first event, the sweep stops. It leaves the cursors of the remaining sessions (including the one it stopped inside) where they were and exits non-zero:
+
+```text
+claude sync: 3496 sessions, 168 changed, 33689 events (33689 retained), 0 errors
+ stopped before log rotation would discard this sweep's own events; 3329 session(s) left pending for the next sweep.
+```
+
+With `--json`, the summary carries `events_retained` (events this sweep wrote that are still in the log or its archives when it finishes), `events_rotated_out` (events another writer's rotations discarded during the sweep, which also makes the sweep exit non-zero), `retention_limited`, and `sessions_pending`.
+
+The next sweep continues where this one stopped. The guard covers one sweep at a time, so the next sweep's rotations can discard the previous sweep's output. That includes `--watch`, which sweeps again on every interval. If you need every event, ship or copy the log files between sweeps. To backfill in one sweep, raise the file size for this sync only:
+
+```bash
+beacon endpoint claude sync --rotate-bytes 1073741824
+```
+
+`--rotate-bytes` cannot be smaller than the default 10 MiB. The archive count stays at five, because the hooks and the collector prune any archive past five on their next rotation. After the sync, those writers keep rotating at 10 MiB, so the large file becomes an ordinary archive and stays readable until five more rotations have happened. Hooks and the collector also rotate at 10 MiB while the sync runs, so live agent activity during a large backfill can stop the sweep early. The sweep then stops at the window, and none of its events are lost. Run large backfills while agents are idle.
+
## Deployment notes
For MDM deployments, use the signed and notarized macOS `.pkg` so endpoint events land in `/var/log/beacon-agent/runtime.jsonl`. The package installs the endpoint agent under `/opt/beacon`, creates system endpoint configuration, and loads the local collector LaunchDaemon.