Skip to content

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

Merge origin/main into claude/issue-885-hook-state-unused

Clauded89e4f539b07
diff --cc cli/beacon-hooks/cmd/stop.go
index 26b62a4a,de6ee11a..83c379d8
--- a/cli/beacon-hooks/cmd/stop.go
+++ b/cli/beacon-hooks/cmd/stop.go
@@@ -72,7 -73,23 +73,12 @@@ func runStop(cmd *cobra.Command, args [
}
config.RotateLogIfNeededForPlatform(platformFlag)
+ st := state.NewSessionState(sessionID, platformFlag)
+ // Factory Droid's Stop payload carries no reply; its transcript does.
+ if platformFlag == "factory" {
+ emitFactoryTranscriptReply(logger, input, sessionID, transcriptPath, st)
+ }
- // The public Beacon build is local-only. Clear any pending remote evaluations
- // left over from older hook versions instead of polling a hosted service.
- pendingEvals := st.GetPendingEvaluations()
- if len(pendingEvals) > 0 {
- if err := st.ClearEvaluations(); err != nil {
- logger.Warn("Failed to clear stale remote evaluations in local-only build", "count", len(pendingEvals), "error", err.Error())
- } else {
- logger.Warn("Cleared stale remote evaluations in local-only build", "count", len(pendingEvals))
- }
- }
-
elapsed := time.Since(start)
logger.Info("stop completed", "duration_ms", elapsed.Milliseconds())
emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields(sessionID, input))
diff --cc cli/beacon-hooks/internal/state/state.go
index 30820251,5cc48385..fc12dd14
--- a/cli/beacon-hooks/internal/state/state.go
+++ b/cli/beacon-hooks/internal/state/state.go
@@@ -69,14 -69,34 +69,25 @@@ func writeStateFile(path string, data [
}
const (
- staleEvaluationTTLHours = 2
+ staleSessionTTLHours = 2
+ // replyMarkerTTL is how long a session's last recorded reply is remembered. A Stop that
+ // re-fires over an unchanged transcript after that writes the reply again, which costs one
+ // duplicate event rather than an unbounded state file.
+ replyMarkerTTL = 14 * 24 * time.Hour
)
-// Evaluation represents a pending evaluation
-type Evaluation struct {
- EvaluationID string `json:"evaluation_id"`
- FilePath string `json:"file_path"`
- CreatedAt string `json:"created_at"`
-}
-
-// SessionData represents data for a single session
+// SessionData represents data for a single session. Older state files also carry evaluations,
+// reprompt_count and model keys; they are ignored on load and dropped on the next save.
type SessionData struct {
- PromptEmitted bool `json:"prompt_emitted,omitempty"`
- CreatedAt string `json:"created_at,omitempty"`
- Evaluations []Evaluation `json:"evaluations"`
- RepromptCount int `json:"reprompt_count"`
- Model string `json:"model,omitempty"`
- PromptEmitted bool `json:"prompt_emitted,omitempty"`
++ PromptEmitted bool `json:"prompt_emitted,omitempty"`
+ // LastReplyID names the last assistant reply a hook recorded for this session, so a reply read
+ // from a transcript that has not moved since the previous turn is not recorded twice.
+ LastReplyID string `json:"last_reply_id,omitempty"`
+ // LastReplyAt is when LastReplyID was recorded. Stale-session cleanup keeps a session whose
- // reply marker is younger than replyMarkerTTL, so the dedupe outlives the two-hour evaluation
- // window that every other session field is cleaned up on.
++ // reply marker is younger than replyMarkerTTL, so the dedupe outlives the two-hour window
++ // that every other session is cleaned up on.
+ LastReplyAt string `json:"last_reply_at,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
}
// SessionState manages session state
@@@ -176,7 -207,98 +187,26 @@@ func (s *SessionState) MarkPromptEmitte
return true, nil
}
+ // MarkReplyRecorded records id as the session's last recorded assistant reply. It reports false,
+ // and changes nothing, when id is already the last one recorded, so a caller writes a reply at
+ // most once even when two Stop hooks of one session race.
+ func (s *SessionState) MarkReplyRecorded(id string) (bool, error) {
+ defer lockState(s.platform)()
+
+ state := s.loadStateFile()
+ s.ensureSession(state)
+ if state[s.sessionID].LastReplyID == id {
+ return false, nil
+ }
+ state[s.sessionID].LastReplyID = id
+ state[s.sessionID].LastReplyAt = time.Now().UTC().Format(time.RFC3339)
+ if err := s.saveStateFile(state); err != nil {
+ return false, err
+ }
+ return true, nil
+ }
+
-// AddEvaluation adds a new pending evaluation
-func (s *SessionState) AddEvaluation(evaluationID, filePath string) error {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- s.ensureSession(state)
-
- state[s.sessionID].Evaluations = append(state[s.sessionID].Evaluations, Evaluation{
- EvaluationID: evaluationID,
- FilePath: filePath,
- CreatedAt: time.Now().UTC().Format(time.RFC3339),
- })
-
- return s.saveStateFile(state)
-}
-
-// GetPendingEvaluations returns pending evaluations for this session
-func (s *SessionState) GetPendingEvaluations() []Evaluation {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- if sessionData, ok := state[s.sessionID]; ok {
- return sessionData.Evaluations
- }
- return []Evaluation{}
-}
-
-// ClearEvaluations removes all evaluations for this session
-func (s *SessionState) ClearEvaluations() error {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- s.ensureSession(state)
- state[s.sessionID].Evaluations = []Evaluation{}
- return s.saveStateFile(state)
-}
-
-// GetRepromptCount returns the current re-prompt count
-func (s *SessionState) GetRepromptCount() int {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- if sessionData, ok := state[s.sessionID]; ok {
- return sessionData.RepromptCount
- }
- return 0
-}
-
-// IncrementRepromptCount increments and returns the re-prompt count
-func (s *SessionState) IncrementRepromptCount() (int, error) {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- s.ensureSession(state)
- state[s.sessionID].RepromptCount++
- newCount := state[s.sessionID].RepromptCount
- if err := s.saveStateFile(state); err != nil {
- return 0, err
- }
- return newCount, nil
-}
-
-// ResetRepromptCount resets the re-prompt count to 0
-func (s *SessionState) ResetRepromptCount() error {
- defer lockState(s.platform)()
-
- state := s.loadStateFile()
- s.ensureSession(state)
- state[s.sessionID].RepromptCount = 0
- return s.saveStateFile(state)
-}
-
-// CleanupStaleForPlatform removes stale evaluations for the given platform
+// CleanupStaleForPlatform removes stale sessions for the given platform
func CleanupStaleForPlatform(platform string) int {
defer lockState(platform)()
@@@ -200,9 -323,23 +230,12 @@@
sessionsToRemove := []string{}
for sessionID, sessionData := range state {
- var freshEvals []Evaluation
- for _, eval := range sessionData.Evaluations {
- createdAt, err := time.Parse(time.RFC3339, eval.CreatedAt)
- if err != nil || createdAt.After(cutoff) {
- freshEvals = append(freshEvals, eval)
- } else {
- removedCount++
- }
++ if sessionData.hasRecentReplyMarker() {
++ continue
+ }
- sessionData.Evaluations = freshEvals
-
- // Mark empty sessions for removal only if they are stale
- if len(freshEvals) == 0 && sessionData.RepromptCount == 0 && !sessionData.hasRecentReplyMarker() {
- createdAt, err := time.Parse(time.RFC3339, sessionData.CreatedAt)
- if err != nil || createdAt.Before(cutoff) {
- sessionsToRemove = append(sessionsToRemove, sessionID)
- }
+ createdAt, err := time.Parse(time.RFC3339, sessionData.CreatedAt)
+ if err != nil || createdAt.Before(cutoff) {
+ sessionsToRemove = append(sessionsToRemove, sessionID)
}
}
@@@ -220,5 -357,14 +253,14 @@@
}
}
- return removedCount
+ return len(sessionsToRemove)
}
+
+ // hasRecentReplyMarker reports whether the session recorded a reply within replyMarkerTTL.
+ func (d *SessionData) hasRecentReplyMarker() bool {
+ if d.LastReplyID == "" {
+ return false
+ }
+ at, err := time.Parse(time.RFC3339, d.LastReplyAt)
+ return err == nil && time.Since(at) < replyMarkerTTL
+ }
diff --cc cli/beacon-hooks/internal/state/state_test.go
index d7f7036d,35f89407..7a5101ee
--- a/cli/beacon-hooks/internal/state/state_test.go
+++ b/cli/beacon-hooks/internal/state/state_test.go
@@@ -157,3 -157,63 +157,63 @@@ func TestStateIsSafeAcrossProcesses(t *
}
}
}
+
+ func TestMarkReplyRecordedOncePerReplyAndSession(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ a := NewSessionState("session-a", "cursor")
+ for i, want := range []bool{true, false} {
+ fresh, err := a.MarkReplyRecorded("msg-1")
+ if err != nil || fresh != want {
+ t.Fatalf("mark %d = %v, %v; want %v", i+1, fresh, err, want)
+ }
+ }
+ // A later reply is new, and a reply id is per session.
+ if fresh, _ := NewSessionState("session-a", "cursor").MarkReplyRecorded("msg-2"); !fresh {
+ t.Fatal("a new reply id was treated as already recorded")
+ }
+ if fresh, _ := NewSessionState("session-b", "cursor").MarkReplyRecorded("msg-2"); !fresh {
+ t.Fatal("another session's reply id suppressed this session's")
+ }
+ // The marker sits beside the other session data without disturbing it.
- if err := a.SetModel("m"); err != nil {
++ if err := a.SetPromptEmitted(); err != nil {
+ t.Fatal(err)
+ }
+ if fresh, _ := a.MarkReplyRecorded("msg-2"); fresh {
- t.Fatal("setting the model reset the recorded reply")
++ t.Fatal("setting prompt_emitted reset the recorded reply")
+ }
+ }
+
+ // Stale-session cleanup runs on every SessionStart and SessionEnd of the platform and removes
-// sessions older than two hours with no evaluations, which is every Factory session. A session's
++// sessions older than two hours, which is every Factory session. A session's
+ // reply marker has to survive it, or a Stop over an unchanged transcript records the reply again.
+ func TestCleanupKeepsARecentReplyMarker(t *testing.T) {
+ _, cleanup := setupTestStateDir(t)
+ defer cleanup()
+
+ old := time.Now().Add(-3 * time.Hour).UTC().Format(time.RFC3339)
+ expired := time.Now().Add(-replyMarkerTTL - time.Hour).UTC().Format(time.RFC3339)
+ st := NewSessionState("seed", "cursor")
+ state := map[string]*SessionData{
+ "recent-reply": {CreatedAt: old, LastReplyID: "m1", LastReplyAt: time.Now().UTC().Format(time.RFC3339)},
+ "expired-reply": {CreatedAt: old, LastReplyID: "m2", LastReplyAt: expired},
+ "no-reply": {CreatedAt: old},
+ }
+ if err := st.saveStateFile(state); err != nil {
+ t.Fatal(err)
+ }
+
+ CleanupStaleForPlatform("cursor")
+
+ after := st.loadStateFile()
+ if after["recent-reply"] == nil {
+ t.Fatal("cleanup removed a session with a recent reply marker")
+ }
+ if after["expired-reply"] != nil || after["no-reply"] != nil {
+ t.Fatalf("cleanup kept stale sessions: %v", after)
+ }
+ if fresh, _ := NewSessionState("recent-reply", "cursor").MarkReplyRecorded("m1"); fresh {
+ t.Fatal("the reply was treated as new after cleanup")
+ }
+ }