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
refactor(hooks): remove unused hook state methods (#885)
Claude0bc075ecd62f
diff --git a/cli/beacon-hooks/cmd/pre_tool_test.go b/cli/beacon-hooks/cmd/pre_tool_test.goindex 5fb6a2e1..a7b527c6 100644--- a/cli/beacon-hooks/cmd/pre_tool_test.go+++ b/cli/beacon-hooks/cmd/pre_tool_test.go@@ -14,7 +14,6 @@ import ("github.com/spf13/cobra"hookconfig "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"- "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state")func TestRunPreToolAllowsAndEmitsTelemetry(t *testing.T) {@@ -950,19 +949,23 @@ func TestRunPromptSubmitIgnoresLegacyRetentionEnv(t *testing.T) {}}-func TestRunSessionStartStoresModel(t *testing.T) {+// The state entry is what lets the stale sweep remove the session log when session-end never runs.+func TestRunSessionStartRecordsSession(t *testing.T) {setupHookConfigDirs(t)platformFlag = "cursor"- out := runHookWithInput(t, runSessionStart, map[string]interface{}{- "conversation_id": "conv-model",- "model": "gpt-5.5",- })- if len(out) != 0 {- t.Fatalf("session-start response = %#v, want empty response", out)+ runHookWithInput(t, runSessionStart, map[string]interface{}{"conversation_id": "conv-start"})++ data, err := os.ReadFile(filepath.Join(hookconfig.GetStateDir("cursor"), "state.json"))+ if err != nil {+ t.Fatalf("read state: %v", err)+ }+ var sessions map[string]json.RawMessage+ if err := json.Unmarshal(data, &sessions); err != nil {+ t.Fatalf("parse state: %v", err)}- if got := state.NewSessionState("conv-model", "cursor").GetModel(); got != "gpt-5.5" {- t.Fatalf("stored model = %q, want gpt-5.5", got)+ if _, ok := sessions["conv-start"]; !ok {+ t.Fatalf("state = %s, want conv-start recorded", data)}}diff --git a/cli/beacon-hooks/cmd/session_start.go b/cli/beacon-hooks/cmd/session_start.goindex d0fbbbb4..ff256ea1 100644--- a/cli/beacon-hooks/cmd/session_start.go+++ b/cli/beacon-hooks/cmd/session_start.go@@ -58,17 +58,12 @@ func runSessionStart(cmd *cobra.Command, args []string) {cleaned := state.CleanupStaleForPlatform(platformFlag)if cleaned > 0 {- logger.Info(fmt.Sprintf("Cleaned up %d stale evaluations", cleaned))+ logger.Info(fmt.Sprintf("Cleaned up %d stale sessions", cleaned))}- // Persist model name so post-tool can include it in evaluations- if model, ok := input["model"].(string); ok && model != "" {- st := state.NewSessionState(sessionID, platformFlag)- if err := st.SetModel(model); err != nil {- logger.Warn("Failed to persist session model", "model", model, "error", err.Error())- } else {- logger.Debug("Stored session model", "model", model)- }+ // Recording the session lets a later sweep remove its log if session-end never runs+ if err := state.NewSessionState(sessionID, platformFlag).Register(); err != nil {+ logger.Warn("Failed to record session state", "error", err.Error())}logger.Info("Session initialized", "session_id", sessionID, "platform", platformFlag)diff --git a/cli/beacon-hooks/cmd/stop.go b/cli/beacon-hooks/cmd/stop.goindex b319ebc3..26b62a4a 100644--- a/cli/beacon-hooks/cmd/stop.go+++ b/cli/beacon-hooks/cmd/stop.go@@ -11,7 +11,6 @@ import ("github.com/spf13/cobra""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config"- "github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/state")var stopCmd = &cobra.Command{@@ -73,18 +72,6 @@ func runStop(cmd *cobra.Command, args []string) {}config.RotateLogIfNeededForPlatform(platformFlag)- st := state.NewSessionState(sessionID, platformFlag)-- // 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())diff --git a/cli/beacon-hooks/internal/state/state.go b/cli/beacon-hooks/internal/state/state.goindex b44bd84f..30820251 100644--- a/cli/beacon-hooks/internal/state/state.go+++ b/cli/beacon-hooks/internal/state/state.go@@ -69,23 +69,14 @@ func writeStateFile(path string, data []byte) error {}const (- staleEvaluationTTLHours = 2+ staleSessionTTLHours = 2)-// 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 {- Evaluations []Evaluation `json:"evaluations"`- RepromptCount int `json:"reprompt_count"`- Model string `json:"model,omitempty"`- PromptEmitted bool `json:"prompt_emitted,omitempty"`- CreatedAt string `json:"created_at,omitempty"`+ PromptEmitted bool `json:"prompt_emitted,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`}// SessionState manages session state@@ -134,34 +125,23 @@ func (s *SessionState) saveStateFile(state map[string]*SessionData) error {func (s *SessionState) ensureSession(state map[string]*SessionData) {if state[s.sessionID] == nil {state[s.sessionID] = &SessionData{- Evaluations: []Evaluation{},- RepromptCount: 0,- CreatedAt: time.Now().UTC().Format(time.RFC3339),+ CreatedAt: time.Now().UTC().Format(time.RFC3339),}}}-// SetModel stores the AI model name for this session-func (s *SessionState) SetModel(model string) error {+// Register records the session so CleanupStaleForPlatform can remove its log if session-end never runs+func (s *SessionState) Register() error {defer lockState(s.platform)()state := s.loadStateFile()+ if state[s.sessionID] != nil {+ return nil+ }s.ensureSession(state)- state[s.sessionID].Model = modelreturn s.saveStateFile(state)}-// GetModel returns the AI model name for this session-func (s *SessionState) GetModel() string {- defer lockState(s.platform)()-- state := s.loadStateFile()- if sessionData, ok := state[s.sessionID]; ok {- return sessionData.Model- }- return ""-}-func (s *SessionState) HasPromptEmitted() bool {defer lockState(s.platform)()@@ -196,79 +176,7 @@ func (s *SessionState) MarkPromptEmittedIfNeeded() (bool, error) {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 platformfunc CleanupStaleForPlatform(platform string) int {defer lockState(platform)()@@ -288,28 +196,13 @@ func CleanupStaleForPlatform(platform string) int {return 0}- cutoff := time.Now().Add(-time.Duration(staleEvaluationTTLHours) * time.Hour)- removedCount := 0+ cutoff := time.Now().Add(-time.Duration(staleSessionTTLHours) * time.Hour)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++- }- }- sessionData.Evaluations = freshEvals-- // Mark empty sessions for removal only if they are stale- if len(freshEvals) == 0 && sessionData.RepromptCount == 0 {- 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)}}@@ -319,7 +212,7 @@ func CleanupStaleForPlatform(platform string) int {os.Remove(config.GetSessionLogFile(platform, sessionID))}- if removedCount > 0 || len(sessionsToRemove) > 0 {+ if len(sessionsToRemove) > 0 {config.EnsureStateDir(platform)jsonData, err := json.MarshalIndent(state, "", " ")if err == nil {@@ -327,5 +220,5 @@ func CleanupStaleForPlatform(platform string) int {}}- return removedCount+ return len(sessionsToRemove)}diff --git a/cli/beacon-hooks/internal/state/state_test.go b/cli/beacon-hooks/internal/state/state_test.goindex c099e7fe..d7f7036d 100644--- a/cli/beacon-hooks/internal/state/state_test.go+++ b/cli/beacon-hooks/internal/state/state_test.go@@ -2,10 +2,12 @@ package stateimport ("bytes"+ "fmt""os""os/exec""path/filepath""testing"+ "time""github.com/asymptote-labs/agent-beacon/cli/beacon-hooks/internal/config")@@ -23,51 +25,46 @@ func setupTestStateDir(t *testing.T) (tmpDir string, cleanup func()) {}}-func TestSessionModelPersistsToDisk(t *testing.T) {- _, cleanup := setupTestStateDir(t)- defer cleanup()-- st1 := NewSessionState("test-session", "cursor")- st1.SetModel("gpt-5.5")-- st2 := NewSessionState("test-session", "cursor")- if got := st2.GetModel(); got != "gpt-5.5" {- t.Errorf("model = %q, want %q", got, "gpt-5.5")- }-}-func TestSessionStateIsolatedBySession(t *testing.T) {_, cleanup := setupTestStateDir(t)defer cleanup()- st1 := NewSessionState("session-a", "cursor")- st2 := NewSessionState("session-b", "cursor")-- st1.SetModel("model-a")- st2.SetModel("model-b")+ if err := NewSessionState("session-a", "cursor").SetPromptEmitted(); err != nil {+ t.Fatalf("SetPromptEmitted: %v", err)+ }- if got := st1.GetModel(); got != "model-a" {- t.Errorf("session-a model = %q, want model-a", got)+ if !NewSessionState("session-a", "cursor").HasPromptEmitted() {+ t.Error("session-a prompt_emitted = false, want true")}- if got := st2.GetModel(); got != "model-b" {- t.Errorf("session-b model = %q, want model-b", got)+ if NewSessionState("session-b", "cursor").HasPromptEmitted() {+ t.Error("session-b prompt_emitted = true, want false")}}-func TestEvaluationsPersistToDisk(t *testing.T) {- _, cleanup := setupTestStateDir(t)+// State files written by older hooks carry evaluations, reprompt_count and model keys. They must+// still load, and the sweep must remove their stale sessions.+func TestLegacyStateFileLoads(t *testing.T) {+ tmpDir, cleanup := setupTestStateDir(t)defer cleanup()- st1 := NewSessionState("test-session", "cursor")- st1.AddEvaluation("eval-1", "/path/to/file.go")+ fresh := time.Now().UTC().Format(time.RFC3339)+ stale := time.Now().Add(-3 * time.Hour).UTC().Format(time.RFC3339)+ legacy := `{+ "fresh": {"evaluations": [{"evaluation_id": "e1", "file_path": "/a.go", "created_at": "` + fresh + `"}], "reprompt_count": 2, "model": "gpt-5.5", "prompt_emitted": true, "created_at": "` + fresh + `"},+ "stale": {"evaluations": [], "reprompt_count": 3, "model": "gpt-5.5", "created_at": "` + stale + `"}+}`+ if err := os.WriteFile(filepath.Join(tmpDir, "state.json"), []byte(legacy), 0o644); err != nil {+ t.Fatalf("write legacy state: %v", err)+ }- st2 := NewSessionState("test-session", "cursor")- evals := st2.GetPendingEvaluations()- if len(evals) != 1 || evals[0].EvaluationID != "eval-1" {- t.Fatalf("evaluations = %#v, want eval-1", evals)+ if !NewSessionState("fresh", "cursor").HasPromptEmitted() {+ t.Fatal("legacy session prompt_emitted = false, want true")}- if evals[0].FilePath != "/path/to/file.go" {- t.Errorf("file path = %q, want /path/to/file.go", evals[0].FilePath)+ if got := CleanupStaleForPlatform("cursor"); got != 1 {+ t.Fatalf("CleanupStaleForPlatform = %d, want 1 stale session removed", got)+ }+ if !NewSessionState("fresh", "cursor").HasPromptEmitted() {+ t.Fatal("fresh legacy session lost by the sweep")}}@@ -76,7 +73,7 @@ func TestSessionStateFileLocation(t *testing.T) {defer cleanup()st := NewSessionState("test-session", "cursor")- st.SetModel("gpt-5.5")+ st.SetPromptEmitted()// Verify state.json was created in the expected locationstateFile := filepath.Join(tmpDir, "state.json")@@ -98,23 +95,23 @@ func TestSessionStateSurfacesSaveFailure(t *testing.T) {})st := NewSessionState("test-session", "cursor")- if err := st.SetModel("gpt-5.5"); err == nil {- t.Fatal("SetModel returned nil, want save failure")+ if err := st.SetPromptEmitted(); err == nil {+ t.Fatal("SetPromptEmitted returned nil, want save failure")}}-// TestHelperProcessIncrement is not a test: it is the body of the child processes started by+// TestHelperProcessRecord 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) {+func TestHelperProcessRecord(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")+ proc := os.Getenv("BEACON_STATE_HELPER_PROC")for i := 0; i < 40; i++ {- if _, err := st.IncrementRepromptCount(); err != nil {- t.Fatalf("IncrementRepromptCount: %v", err)+ if err := NewSessionState(fmt.Sprintf("session-%s-%d", proc, i), "cursor").SetPromptEmitted(); err != nil {+ t.Fatalf("SetPromptEmitted: %v", err)}}}@@ -129,8 +126,8 @@ func TestStateIsSafeAcrossProcesses(t *testing.T) {var cmds []*exec.Cmdvar outputs []*bytes.Bufferfor i := 0; i < procs; i++ {- cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcessIncrement$")- cmd.Env = append(os.Environ(), "BEACON_STATE_HELPER_DIR="+dir)+ cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcessRecord$")+ cmd.Env = append(os.Environ(), "BEACON_STATE_HELPER_DIR="+dir, fmt.Sprintf("BEACON_STATE_HELPER_PROC=%d", i))out := &bytes.Buffer{}cmd.Stdout, cmd.Stderr = out, outoutputs = append(outputs, out)@@ -145,8 +142,12 @@ func TestStateIsSafeAcrossProcesses(t *testing.T) {}}- 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)+ for i := 0; i < procs; i++ {+ for j := 0; j < perProc; j++ {+ if !NewSessionState(fmt.Sprintf("session-%d-%d", i, j), "cursor").HasPromptEmitted() {+ t.Fatalf("session-%d-%d missing: concurrent processes lost updates", i, j)+ }+ }}if leftovers, _ := filepath.Glob(filepath.Join(dir, "state.json.*")); len(leftovers) > 0 {for _, f := range leftovers {