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
feat(sessionsync): add a locked read-modify-write for shared state files
Saurav Singh04ef1d496977
diff --git a/cli/beacon/internal/sessionfs/collectors_test.go b/cli/beacon/internal/sessionfs/collectors_test.goindex a517affd..f6213475 100644--- a/cli/beacon/internal/sessionfs/collectors_test.go+++ b/cli/beacon/internal/sessionfs/collectors_test.go@@ -32,6 +32,8 @@ var directReads = map[string]bool{var allowedDirectReads = map[string]bool{// The collector's own cursor file, under Beacon's base directory rather than the user's store."sessionsync.Load.os.ReadFile": true,+ // The lock beside a cursor file several sweeps share, also under Beacon's base directory.+ "sessionsync.Update.os.OpenFile": true,// The driver open itself, after SQLitePath has turned the path into a confined snapshot."sessionsync.OpenSQLite.sql.Open": true,// Existence checks on project paths named inside a transcript, to infer the workspace. Theydiff --git a/cli/beacon/internal/sessionsync/sessionsync.go b/cli/beacon/internal/sessionsync/sessionsync.goindex e9171824..4bab66bc 100644--- a/cli/beacon/internal/sessionsync/sessionsync.go+++ b/cli/beacon/internal/sessionsync/sessionsync.go@@ -18,6 +18,7 @@ import ("github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"_ "modernc.org/sqlite")@@ -98,6 +99,48 @@ func (f StateFile[S]) Save(path string, s *S) error {return os.Rename(tmp, path)}+// Update loads the file at path, lets mutate change it, and saves it when mutate reports a change,+// all under an exclusive lock on path+".lock". A file several sweeps share, such as one every home+// of a runtime writes to, needs it: a plain Load and Save from two sweeps at once keeps only the+// change of whichever saves last. An empty path runs mutate on a new state and saves nothing.+func (f StateFile[S]) Update(path string, mutate func(*S) bool) (err error) {+ if f.empty(path) {+ mutate(f.New())+ return nil+ }+ mode := f.DirMode+ if mode == 0 {+ mode = 0o755+ }+ if err := os.MkdirAll(filepath.Dir(path), mode); err != nil {+ return err+ }+ lockFile, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0o600)+ if err != nil {+ return err+ }+ // The lock file is never written, so closing it loses nothing; its error is reported only+ // when nothing else went wrong.+ defer func() {+ if cerr := lockFile.Close(); cerr != nil && err == nil {+ err = cerr+ }+ }()+ lock, err := filelock.Exclusive(lockFile)+ if err != nil {+ return err+ }+ defer lock.Release()+ s, err := f.Load(path)+ if err != nil {+ return err+ }+ if !mutate(s) {+ return nil+ }+ return f.Save(path, s)+}+// Sink is where a sweep's events go: one JSON object per line to Out for --print, or appended to// the runtime log with Log.type Sink struct {diff --git a/cli/beacon/internal/sessionsync/sessionsync_test.go b/cli/beacon/internal/sessionsync/sessionsync_test.goindex c678d4eb..8eb434fb 100644--- a/cli/beacon/internal/sessionsync/sessionsync_test.go+++ b/cli/beacon/internal/sessionsync/sessionsync_test.go@@ -7,6 +7,7 @@ import ("os""path/filepath""strings"+ "sync""testing""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"@@ -88,6 +89,76 @@ func TestStateFileEmptyPath(t *testing.T) {}}+func TestStateFileUpdate(t *testing.T) {+ path := filepath.Join(t.TempDir(), "state", "test.json")+ if err := testFile.Update(path, func(s *testState) bool { return false }); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("an update that changed nothing saved the file: %v", err)+ }+ n := int64(3)+ if err := testFile.Update(path, func(s *testState) bool { s.Files["a"] = &n; return true }); err != nil {+ t.Fatal(err)+ }+ var seen *int64+ if err := testFile.Update(path, func(s *testState) bool { seen = s.Files["a"]; return false }); err != nil {+ t.Fatal(err)+ }+ if seen == nil || *seen != 3 {+ t.Fatalf("second update saw %v, want the first update's change", seen)+ }++ if err := os.WriteFile(path, []byte(`{`), 0o600); err != nil {+ t.Fatal(err)+ }+ called := false+ if err := testFile.Update(path, func(s *testState) bool { called = true; return true }); err == nil || called {+ t.Fatalf("update of a corrupt file returned %v and ran mutate = %v, want an error before mutate", err, called)+ }+ if err := testFile.Update("", func(s *testState) bool { called = true; return true }); err != nil || !called {+ t.Fatalf("update of an empty path returned %v and ran mutate = %v, want mutate run and nothing saved", err, called)+ }+}++// Every update reads what the one before it saved, so concurrent sweeps that share a file never+// lose each other's change.+func TestStateFileUpdateSerializesWriters(t *testing.T) {+ path := filepath.Join(t.TempDir(), "test.json")+ const writers = 16+ var wg sync.WaitGroup+ errs := make(chan error, writers)+ for i := 0; i < writers; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ errs <- testFile.Update(path, func(s *testState) bool {+ count := s.Files["count"]+ if count == nil {+ count = new(int64)+ s.Files["count"] = count+ }+ *count+++ return true+ })+ }()+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }+ state, err := testFile.Load(path)+ if err != nil {+ t.Fatal(err)+ }+ if got := state.Files["count"]; got == nil || *got != writers {+ t.Fatalf("count = %v, want %d", got, writers)+ }+}+func TestOpenSQLiteIsReadOnly(t *testing.T) {path := filepath.Join(t.TempDir(), "store.db")rw, err := sql.Open("sqlite", path)