Skip to content

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

fix(hooks): serialize the session state file across hook processes (#877)

Rudy Mizrahi Celeklib3f2cc4b4129
diff --git a/cli/beacon-hooks/cmd/pre_tool.go b/cli/beacon-hooks/cmd/pre_tool.go
index 4240ba88..9fd95011 100644
--- a/cli/beacon-hooks/cmd/pre_tool.go
+++ b/cli/beacon-hooks/cmd/pre_tool.go
@@ -288,6 +288,15 @@ func emitAntigravityPromptFromTranscript(logger *logging.Logger, input map[strin
if prompt == "" {
return
}
+ // Claim the prompt before recording it. Parallel tool calls run parallel PreToolUse hooks, and
+ // a check followed by a later set let each of them see "not emitted" and record the prompt.
+ // A claim that could not be saved still records it: a duplicate beats a lost prompt.
+ claimed, err := st.MarkPromptEmittedIfNeeded()
+ if err != nil {
+ logger.Warn("Failed to persist prompt state", "error", err.Error())
+ } else if !claimed {
+ return
+ }
fields := sessionFields(sessionID, input)
fields["prompt"] = map[string]interface{}{"text": prompt}
fields["gen_ai"] = mergeNested(fields["gen_ai"], map[string]interface{}{
@@ -298,9 +307,6 @@ func emitAntigravityPromptFromTranscript(logger *logging.Logger, input map[strin
if link, ok := handoffLinkEvent(fields, prompt); ok {
emitHookEvent(logger, link.action, link.category, link.severity, link.message, input, link.fields)
}
- if err := st.SetPromptEmitted(); err != nil {
- logger.Warn("Failed to persist prompt state", "error", err.Error())
- }
}
func antigravityPromptFromTranscript(input map[string]interface{}, sessionID string) string {
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.go
index 94dbd290..5fb6a2e1 100644
--- a/cli/beacon-hooks/cmd/pre_tool_test.go
+++ b/cli/beacon-hooks/cmd/pre_tool_test.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"testing"
"github.com/spf13/cobra"
@@ -731,6 +732,41 @@ func TestRunPreToolSynthesizesAntigravityPromptFromTranscript(t *testing.T) {
}
}
+// Parallel tool calls run parallel PreToolUse hooks. Each may fall back to the transcript, and the
+// prompt it finds must be recorded once, not once per hook that saw it unclaimed.
+func TestAntigravityTranscriptPromptIsRecordedOnceByParallelHooks(t *testing.T) {
+ setupHookConfigDirs(t)
+ platformFlag = "antigravity"
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ t.Setenv("BEACON_CONTENT_RETENTION", "full")
+ transcriptPath := filepath.Join(t.TempDir(), "transcript.jsonl")
+ if err := os.WriteFile(transcriptPath, []byte(`{"source":"USER_EXPLICIT","type":"USER_INPUT","content":"<USER_REQUEST>\nrefactor the parser\n</USER_REQUEST>"}`+"\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+
+ var wg sync.WaitGroup
+ for i := 0; i < 8; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ input := map[string]interface{}{"conversationId": "ag-parallel", "transcriptPath": transcriptPath}
+ emitAntigravityPromptFromTranscript(newHookLogger("pre-tool", "antigravity", "ag-parallel"), input, "ag-parallel")
+ }()
+ }
+ wg.Wait()
+
+ prompts := 0
+ for _, event := range endpointEvents(t, logPath) {
+ if event["event"].(map[string]interface{})["action"] == "prompt.submitted" {
+ prompts++
+ }
+ }
+ if prompts != 1 {
+ t.Fatalf("prompt.submitted recorded %d times by parallel hooks, want once", prompts)
+ }
+}
+
func TestRunPreToolRetriesAntigravityPromptUntilTranscriptExists(t *testing.T) {
setupHookConfigDirs(t)
platformFlag = "antigravity"
diff --git a/cli/beacon-hooks/internal/state/state.go b/cli/beacon-hooks/internal/state/state.go
index 9278c934..b44bd84f 100644
--- a/cli/beacon-hooks/internal/state/state.go
+++ b/cli/beacon-hooks/internal/state/state.go
@@ -8,10 +8,66 @@ import (
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
var stateMutex sync.Mutex
+// lockState serializes access to the platform's state file. Hooks run as separate processes, one per
+// event, so the in-process mutex is not enough: without the file lock two concurrent hooks read the same
+// state and the later write drops the earlier one's change. The lock is advisory, taken on a sibling
+// file so that replacing state.json never invalidates it. If the lock file cannot be opened the caller
+// proceeds without cross-process exclusion, as before, rather than failing a hook.
+func lockState(platform string) (unlock func()) {
+ stateMutex.Lock()
+ if err := config.EnsureStateDir(platform); err != nil {
+ return stateMutex.Unlock
+ }
+ file, err := os.OpenFile(filepath.Join(config.GetStateDir(platform), "state.json.lock"), os.O_CREATE|os.O_RDWR, 0o644)
+ if err != nil {
+ return stateMutex.Unlock
+ }
+ held, err := filelock.Exclusive(file)
+ if err != nil {
+ _ = file.Close()
+ return stateMutex.Unlock
+ }
+ return func() {
+ _ = held.Release()
+ _ = file.Close()
+ stateMutex.Unlock()
+ }
+}
+
+// writeStateFile replaces path through a uniquely named temporary file, so concurrent writers never
+// share one and a reader never sees a partial file.
+func writeStateFile(path string, data []byte) error {
+ tmp, err := os.CreateTemp(filepath.Dir(path), "state.json.*.tmp")
+ if err != nil {
+ return err
+ }
+ tmpPath := tmp.Name()
+ if _, err := tmp.Write(data); err != nil {
+ _ = tmp.Close()
+ _ = os.Remove(tmpPath)
+ return err
+ }
+ if err := tmp.Chmod(0o644); err != nil {
+ _ = tmp.Close()
+ _ = os.Remove(tmpPath)
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ _ = os.Remove(tmpPath)
+ return err
+ }
+ if err := os.Rename(tmpPath, path); err != nil {
+ _ = os.Remove(tmpPath)
+ return err
+ }
+ return nil
+}
+
const (
staleEvaluationTTLHours = 2
)
@@ -72,13 +128,7 @@ func (s *SessionState) saveStateFile(state map[string]*SessionData) error {
return err
}
- // Write to temp file first, then rename (atomic)
- tmpPath := s.stateFilePath + ".tmp"
- if err := os.WriteFile(tmpPath, data, 0644); err != nil {
- return err
- }
-
- return os.Rename(tmpPath, s.stateFilePath)
+ return writeStateFile(s.stateFilePath, data)
}
func (s *SessionState) ensureSession(state map[string]*SessionData) {
@@ -93,8 +143,7 @@ func (s *SessionState) ensureSession(state map[string]*SessionData) {
// SetModel stores the AI model name for this session
func (s *SessionState) SetModel(model string) error {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -104,8 +153,7 @@ func (s *SessionState) SetModel(model string) error {
// GetModel returns the AI model name for this session
func (s *SessionState) GetModel() string {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
if sessionData, ok := state[s.sessionID]; ok {
@@ -115,8 +163,7 @@ func (s *SessionState) GetModel() string {
}
func (s *SessionState) HasPromptEmitted() bool {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
if sessionData, ok := state[s.sessionID]; ok {
@@ -126,8 +173,7 @@ func (s *SessionState) HasPromptEmitted() bool {
}
func (s *SessionState) SetPromptEmitted() error {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -136,8 +182,7 @@ func (s *SessionState) SetPromptEmitted() error {
}
func (s *SessionState) MarkPromptEmittedIfNeeded() (bool, error) {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -153,8 +198,7 @@ func (s *SessionState) MarkPromptEmittedIfNeeded() (bool, error) {
// AddEvaluation adds a new pending evaluation
func (s *SessionState) AddEvaluation(evaluationID, filePath string) error {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -170,8 +214,7 @@ func (s *SessionState) AddEvaluation(evaluationID, filePath string) error {
// GetPendingEvaluations returns pending evaluations for this session
func (s *SessionState) GetPendingEvaluations() []Evaluation {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
if sessionData, ok := state[s.sessionID]; ok {
@@ -182,8 +225,7 @@ func (s *SessionState) GetPendingEvaluations() []Evaluation {
// ClearEvaluations removes all evaluations for this session
func (s *SessionState) ClearEvaluations() error {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -193,8 +235,7 @@ func (s *SessionState) ClearEvaluations() error {
// GetRepromptCount returns the current re-prompt count
func (s *SessionState) GetRepromptCount() int {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
if sessionData, ok := state[s.sessionID]; ok {
@@ -205,8 +246,7 @@ func (s *SessionState) GetRepromptCount() int {
// IncrementRepromptCount increments and returns the re-prompt count
func (s *SessionState) IncrementRepromptCount() (int, error) {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -220,8 +260,7 @@ func (s *SessionState) IncrementRepromptCount() (int, error) {
// ResetRepromptCount resets the re-prompt count to 0
func (s *SessionState) ResetRepromptCount() error {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(s.platform)()
state := s.loadStateFile()
s.ensureSession(state)
@@ -231,8 +270,7 @@ func (s *SessionState) ResetRepromptCount() error {
// CleanupStaleForPlatform removes stale evaluations for the given platform
func CleanupStaleForPlatform(platform string) int {
- stateMutex.Lock()
- defer stateMutex.Unlock()
+ defer lockState(platform)()
stateFilePath := filepath.Join(config.GetStateDir(platform), "state.json")
@@ -285,10 +323,7 @@ func CleanupStaleForPlatform(platform string) int {
config.EnsureStateDir(platform)
jsonData, err := json.MarshalIndent(state, "", " ")
if err == nil {
- tmpPath := stateFilePath + ".tmp"
- if err := os.WriteFile(tmpPath, jsonData, 0644); err == nil {
- os.Rename(tmpPath, stateFilePath)
- }
+ _ = writeStateFile(stateFilePath, jsonData)
}
}
diff --git a/cli/beacon-hooks/internal/state/state_test.go b/cli/beacon-hooks/internal/state/state_test.go
index 8f70f06d..c099e7fe 100644
--- a/cli/beacon-hooks/internal/state/state_test.go
+++ b/cli/beacon-hooks/internal/state/state_test.go
@@ -1,7 +1,9 @@
package state
import (
+ "bytes"
"os"
+ "os/exec"
"path/filepath"
"testing"
@@ -100,3 +102,57 @@ func TestSessionStateSurfacesSaveFailure(t *testing.T) {
t.Fatal("SetModel returned nil, want save failure")
}
}
+
+// TestHelperProcessIncrement is not a test: it is the body of the child processes started by
+// TestStateIsSafeAcrossProcesses, which stand in for concurrent hook invocations.
+func TestHelperProcessIncrement(t *testing.T) {
+ dir := os.Getenv("BEACON_STATE_HELPER_DIR")
+ if dir == "" {
+ t.Skip("helper process only")
+ }
+ config.CursorDir = dir
+ st := NewSessionState("shared-session", "cursor")
+ for i := 0; i < 40; i++ {
+ if _, err := st.IncrementRepromptCount(); err != nil {
+ t.Fatalf("IncrementRepromptCount: %v", err)
+ }
+ }
+}
+
+// Hooks run as separate processes, so the state file needs cross-process exclusion: the
+// in-process mutex cannot stop two hook invocations from losing each other's update.
+func TestStateIsSafeAcrossProcesses(t *testing.T) {
+ dir, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ const procs, perProc = 4, 40
+ var cmds []*exec.Cmd
+ var outputs []*bytes.Buffer
+ for i := 0; i < procs; i++ {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcessIncrement$")
+ cmd.Env = append(os.Environ(), "BEACON_STATE_HELPER_DIR="+dir)
+ out := &bytes.Buffer{}
+ cmd.Stdout, cmd.Stderr = out, out
+ outputs = append(outputs, out)
+ if err := cmd.Start(); err != nil {
+ t.Fatalf("start helper: %v", err)
+ }
+ cmds = append(cmds, cmd)
+ }
+ for i, cmd := range cmds {
+ if err := cmd.Wait(); err != nil {
+ t.Fatalf("helper failed: %v\n%s", err, outputs[i])
+ }
+ }
+
+ if got, want := NewSessionState("shared-session", "cursor").GetRepromptCount(), procs*perProc; got != want {
+ t.Fatalf("reprompt count = %d, want %d: concurrent processes lost updates", got, want)
+ }
+ if leftovers, _ := filepath.Glob(filepath.Join(dir, "state.json.*")); len(leftovers) > 0 {
+ for _, f := range leftovers {
+ if filepath.Base(f) != "state.json.lock" {
+ t.Fatalf("temporary state file left behind: %s", f)
+ }
+ }
+ }
+}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index ea5224a6..b135e33e 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -11,6 +11,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
## October 2026
+- **Concurrent hooks no longer clobber the per-session state file** · The hook adapter keeps a small `state.json` (session model, prompt-emitted flag, reprompt counts) that every hook process reads and rewrites. Two hooks running at once shared one temporary file, so one could fail with `rename ...: no such file or directory` and a surviving write could drop the other's change. Access is now serialized with a file lock and each write uses its own temporary file.
- **Codex install, hooks and inventory follow `CODEX_HOME`** · `beacon endpoint install`, `beacon endpoint hooks install --harness codex`, `beacon endpoint discover` and inventory now read and write `$CODEX_HOME/config.toml` and `$CODEX_HOME/hooks.json` when `CODEX_HOME` is set, as Codex does. They previously always used `~/.codex`, so with `CODEX_HOME` set, Codex never saw the OTLP exporter or the SessionStart hook and live capture silently recorded nothing. A per-user install or repair also writes the resolved `CODEX_HOME` into the scheduled inventory job, which launchd and systemd start without your shell's environment. A `CODEX_HOME` that is not an existing directory is now an install error rather than a silent write to `~/.codex`. Project-level `.codex` files are unchanged.
- **Oversized session events no longer stall a sync** · An event still over the 64 KB limit after its raw payload was dropped, such as a tool call with many large edit hunks, made session sync fail at that line on every sweep, so nothing later in that session was recorded. The writer now drops the event's retained content and marks it truncated, as the hook and collector writers already did, keeping the tool name, call ID and file path.
- **Cursor sync keeps prompts in compacted conversations** · In a Cursor conversation with a context summary, `beacon endpoint cursor sync` and the session backfill skipped the first new record on every sync that found new activity, often the next prompt, and recorded the compaction again each time. New records are now kept and each compaction is recorded once. A compaction already recorded by an older release is recorded one more time after upgrading.