fix(hooks): short-circuit immediately when disabled · Entire

fix(hooks): short-circuit immediately when disabled

9efa8aa→main·

suhaanthayyil·3d ago·2 files·+142 added/-3 removed

Agent hook execution (entire hooks ) gated on IsEnabled(), which failed OPEN on any settings read error: err == nil && !enabled only short-circuited when the read succeeded. A corrupted or otherwise unreadable .entire/settings.json (or a repo that was never entire enabled, since loadFromFile defaults Enabled to true) made every hook invocation fall through to full lifecycle dispatch instead of exiting fast — for Stop hooks this includes a multi-second wait on the transcript-flush sentinel.

Git hooks already gated on settings.IsSetUpAndEnabled, which fails closed (false) on any load error, so they were unaffected. Switch the agent hook path to the same fail-closed gate for consistency: any settings read error is now treated as disabled.

Fixes #524

Changes

2

18 unmodified lines

19
20
21
22
23
24
25
82 unmodified lines

108
109
110
110
111
112
111
112
113
114
115
116
117
118
119
120
121
122
123
124

18 unmodified lines

"github.com/entireio/cli/cmd/entire/cli/gitrepo"
    "github.com/entireio/cli/cmd/entire/cli/logging"
    "github.com/entireio/cli/cmd/entire/cli/paths"
    "github.com/entireio/cli/cmd/entire/cli/settings"
    "github.com/entireio/cli/cmd/entire/cli/strategy"
    "github.com/entireio/cli/cmd/entire/cli/telemetry"
    "github.com/entireio/cli/cmd/entire/cli/versioncheck"
82 unmodified lines

return nil
    }

// Skip if Entire is not enabled
    enabled, err := IsEnabled(cmd.Context())
    if err == nil && !enabled {
    // Skip if Entire is not set up and enabled. This must fail closed: any
    // settings read error (missing file, corrupted JSON, transient I/O
    // failure) is treated as disabled so a hook never silently falls through
    // to full lifecycle work just because settings couldn't be read. Using
    // IsEnabled here previously failed OPEN on error (`err == nil && !enabled`
    // only short-circuits when the read succeeded), which meant a corrupted
    // or unreadable settings file made every hook invocation pay the full
    // dispatch cost instead of exiting fast (#524).
    // settings.IsSetUpAndEnabled is the same fail-closed gate the git hooks
    // use (see PersistentPreRunE in hooks_git_cmd.go).
    if !settings.IsSetUpAndEnabled(cmd.Context()) {
        return nil
    }

Mcmd/entire/cli/hook_registry.go+12/-3

230 unmodified lines

231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366

230 unmodified lines

require.True(t, os.IsNotExist(statErr), "session-start must not claim the session when checkpoint policy is unreadable")
}

// TestExecuteAgentHookShortCircuitsWhenDisabled is a regression test for #524:
// a hook must not perform any dispatch/strategy work when Entire is
// disabled. Asserted via the same "session was never claimed" signal the
// checkpoint-policy tests above use, rather than a timing assertion.
func TestExecuteAgentHookShortCircuitsWhenDisabled(t *testing.T) {
    setupStopTestRepo(t)
    repoRoot := mustGetwd(t)

entireDir := filepath.Join(repoRoot, ".entire")
    require.NoError(t, os.MkdirAll(entireDir, 0o750))
    require.NoError(t, os.WriteFile(filepath.Join(entireDir, "settings.json"), []byte(`{"enabled":false}`), 0o600))

sessionID := "disabled-session-start"
    payload, err := json.Marshal(map[string]string{
        "session_id":      sessionID,
        "transcript_path": filepath.Join(repoRoot, "transcript.jsonl"),
    })
    require.NoError(t, err)

cmd := &cobra.Command{}
    cmd.SetIn(bytes.NewReader(payload))
    cmd.SetErr(&bytes.Buffer{})
    cmd.SetContext(context.Background())

require.NoError(t, executeAgentHook(cmd, agent.AgentNameClaudeCode, claudecode.HookNameSessionStart, false))

hintPath := filepath.Join(repoRoot, ".git", session.SessionStateDirName, sessionID+".agent")
    _, statErr := os.Stat(hintPath)
    require.True(t, os.IsNotExist(statErr), "disabled hook must not dispatch or claim the session")
}

// TestExecuteAgentHookShortCircuitsWhenSettingsMissing is a regression test
// for #524: a repo that was never `entire enable`d (no .entire/settings.json)
// must short-circuit rather than falling through to full lifecycle dispatch.
func TestExecuteAgentHookShortCircuitsWhenSettingsMissing(t *testing.T) {
    setupStopTestRepo(t)
    repoRoot := mustGetwd(t)
    // Deliberately do NOT create .entire/settings.json.

sessionID := "missing-settings-session-start"
    payload, err := json.Marshal(map[string]string{
        "session_id":      sessionID,
        "transcript_path": filepath.Join(repoRoot, "transcript.jsonl"),
    })
    require.NoError(t, err)

cmd := &cobra.Command{}
    cmd.SetIn(bytes.NewReader(payload))
    cmd.SetErr(&bytes.Buffer{})
    cmd.SetContext(context.Background())

require.NoError(t, executeAgentHook(cmd, agent.AgentNameClaudeCode, claudecode.HookNameSessionStart, false))

hintPath := filepath.Join(repoRoot, ".git", session.SessionStateDirName, sessionID+".agent")
    _, statErr := os.Stat(hintPath)
    require.True(t, os.IsNotExist(statErr), "hook must not dispatch when Entire was never enabled in this repo")
}

// TestExecuteAgentHookShortCircuitsWhenSettingsCorrupted is a regression test
// for #524. Before this fix, IsEnabled() failed OPEN on a settings.Load()
// error (the caller's `err == nil && !enabled` check only short-circuited
// when the read succeeded), so a corrupted settings file made every hook
// invocation pay the full dispatch cost — including, for Stop hooks, a
// multi-second wait on the transcript-flush sentinel (see
// ClaudeCodeAgent.ParseHookEvent) — instead of exiting fast. The gate must
// fail closed on any settings read error.
func TestExecuteAgentHookShortCircuitsWhenSettingsCorrupted(t *testing.T) {
    setupStopTestRepo(t)
    repoRoot := mustGetwd(t)

entireDir := filepath.Join(repoRoot, ".entire")
    require.NoError(t, os.MkdirAll(entireDir, 0o750))
    require.NoError(t, os.WriteFile(filepath.Join(entireDir, "settings.json"), []byte(`{ enabled: false, not valid json`), 0o600))

sessionID := "corrupted-settings-session-start"
    payload, err := json.Marshal(map[string]string{
        "session_id":      sessionID,
        "transcript_path": filepath.Join(repoRoot, "transcript.jsonl"),
    })
    require.NoError(t, err)

cmd := &cobra.Command{}
    cmd.SetIn(bytes.NewReader(payload))
    cmd.SetErr(&bytes.Buffer{})
    cmd.SetContext(context.Background())

require.NoError(t, executeAgentHook(cmd, agent.AgentNameClaudeCode, claudecode.HookNameSessionStart, false))

hintPath := filepath.Join(repoRoot, ".git", session.SessionStateDirName, sessionID+".agent")
    _, statErr := os.Stat(hintPath)
    require.True(t, os.IsNotExist(statErr), "hook must fail closed (not dispatch) when settings are unreadable")
}

// TestExecuteAgentHookStopReturnsFastWhenSettingsCorrupted directly
// regression-tests the reported symptom: `entire hooks claude-code stop`
// against a corrupted settings file must return in well under the
// multi-second transcript-flush-sentinel timeout it used to hit, not just
// skip dispatch. The bound is intentionally generous (this repo has no
// other timing-based tests to match precedent against) — it only needs to
distinguish "short-circuited" from "waited on the sentinel timeout".
func TestExecuteAgentHookStopReturnsFastWhenSettingsCorrupted(t *testing.T) {
    setupStopTestRepo(t)
    repoRoot := mustGetwd(t)

transcriptPath := filepath.Join(repoRoot, "transcript.jsonl")
    require.NoError(t, os.WriteFile(transcriptPath, []byte(`{"type":"user","message":{"content":"hi"}}`+"\n"), 0o600))

payload, err := json.Marshal(map[string]string{
        "session_id":      "corrupted-settings-stop",
        "transcript_path": transcriptPath,
    })
    require.NoError(t, err)

cmd := &cobra.Command{}
    cmd.SetIn(bytes.NewReader(payload))
    cmd.SetErr(&bytes.Buffer{})
    cmd.SetContext(context.Background())

start := time.Now()
    require.NoError(t, executeAgentHook(cmd, agent.AgentNameClaudeCode, claudecode.HookNameStop, false))
    elapsed := time.Since(start)

require.Lessf(t, elapsed, 1*time.Second,
        "stop hook took %s against a corrupted settings file; want a fast short-circuit, not the transcript-flush-sentinel timeout path", elapsed)
}

func TestAgentHookPolicyFailsWhenRepoCannotOpen(t *testing.T) {
    _, err := agentHookPolicy(context.Background(), filepath.Join(t.TempDir(), "missing"))