-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrouter_test.go
More file actions
616 lines (570 loc) · 20.9 KB
/
Copy pathrouter_test.go
File metadata and controls
616 lines (570 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package agenthooks
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
)
func neutralStage(calls *[]string, name string) func(context.Context, *ToolPreEvent) (ToolPreDecision, error) {
return func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
*calls = append(*calls, name)
return NoDecision(), nil
}
}
func denyStage(calls *[]string, name, reason string) func(context.Context, *ToolPreEvent) (ToolPreDecision, error) {
return func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
*calls = append(*calls, name)
return Deny(reason), nil
}
}
func TestStackedRegistrationOrderFirstConclusiveWins(t *testing.T) {
r := quietRunner()
var calls []string
r.OnToolPre(neutralStage(&calls, "h1"), neutralStage(&calls, "h2"))
r.OnToolPre(denyStage(&calls, "h3", "third wins"))
r.OnToolPre(neutralStage(&calls, "h4")) // after the winner: must not run
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if got := strings.Join(calls, ","); got != "h1,h2,h3" {
t.Errorf("run order = %s, want h1,h2,h3 (h4 short-circuited)", got)
}
if d.Kind() != DecisionDeny || d.Reason() != "third wins" {
t.Errorf("got kind=%v reason=%q", d.Kind(), d.Reason())
}
}
func TestStackedNeutralEnrichmentPreserved(t *testing.T) {
// A lone handler returning an enriched neutral must behave exactly as it
// did before registration stacked: context/system message survive.
single := quietRunner()
single.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return NoDecision().WithContext("hint").WithSystemMessage("note"), nil
})
d, err := single.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if d.Kind() != DecisionNoDecision || d.SystemMessage() != "note" {
t.Errorf("neutral enrichment lost: kind=%v sys=%q", d.Kind(), d.SystemMessage())
}
if got := d.Context(); len(got) != 1 || got[0] != "hint" {
t.Errorf("Context() = %v, want [hint]", got)
}
// Multiple all-neutral stages merge their contexts in order.
multi := quietRunner()
multi.OnToolPre(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return NoDecision().WithContext("a"), nil
},
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return NoDecision().WithContext("b"), nil
},
)
d, err = multi.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if got := d.Context(); d.Kind() != DecisionNoDecision || len(got) != 2 || got[0] != "a" || got[1] != "b" {
t.Errorf("merged neutral = kind %v, ctx %v; want no-decision, [a b]", d.Kind(), got)
}
}
func TestEdgePathRunsStackedHandlers(t *testing.T) {
// The pipeline slots in where single-handler dispatch was: the wire
// output for a stacked neutral->deny is identical to a lone deny.
r := quietRunner()
var calls []string
r.OnToolPre(neutralStage(&calls, "n"), denyStage(&calls, "d", "blocked"))
out, code := runWith(t, r, claudeArgs(), fixture(t, "claude/pre_tool_use.json"))
want := `{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"blocked"}}`
if out != want || code != 0 {
t.Errorf("got %q (exit %d), want %q (exit 0)", out, code, want)
}
if got := strings.Join(calls, ","); got != "n,d" {
t.Errorf("run order = %s, want n,d", got)
}
}
func TestAnyShortCircuits(t *testing.T) {
var calls []string
h := Any(
neutralStage(&calls, "n"),
denyStage(&calls, "d", "stop"),
neutralStage(&calls, "never"),
)
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Any: %v", err)
}
if got := strings.Join(calls, ","); got != "n,d" {
t.Errorf("run order = %s, want n,d", got)
}
if d.Kind() != DecisionDeny || d.Reason() != "stop" {
t.Errorf("got kind=%v reason=%q", d.Kind(), d.Reason())
}
}
func TestAnyErrorAborts(t *testing.T) {
sentinel := errors.New("boom")
var calls []string
h := Any(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "err")
return NoDecision(), sentinel
},
denyStage(&calls, "never", "x"),
)
_, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if !errors.Is(err, sentinel) {
t.Errorf("want sentinel error, got %v", err)
}
if got := strings.Join(calls, ","); got != "err" {
t.Errorf("error must abort immediately, ran %s", got)
}
}
func TestAllMostRestrictiveWinsContextAppends(t *testing.T) {
var calls []string
h := All(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "allow")
return Allow().WithContext("allow-ctx"), nil
},
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "deny")
return Deny("deny wins").WithContext("deny-ctx").WithSystemMessage("sys"), nil
},
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "ask")
return AskUser("please").WithContext("ask-ctx"), nil
},
)
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("All: %v", err)
}
if got := strings.Join(calls, ","); got != "allow,deny,ask" {
t.Errorf("All must run every handler in order, ran %s", got)
}
if d.Kind() != DecisionDeny || d.Reason() != "deny wins" || d.SystemMessage() != "sys" {
t.Errorf("winner fields not wholesale: kind=%v reason=%q sys=%q", d.Kind(), d.Reason(), d.SystemMessage())
}
want := []string{"allow-ctx", "deny-ctx", "ask-ctx"}
got := d.Context()
if len(got) != len(want) {
t.Fatalf("Context() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("Context() = %v, want %v", got, want)
}
}
}
func TestAllTiePrefersEarliest(t *testing.T) {
h := All(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) { return Deny("first"), nil },
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) { return Deny("second"), nil },
)
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("All: %v", err)
}
if d.Reason() != "first" {
t.Errorf("tie must go to the earliest, got %q", d.Reason())
}
}
func TestAllStopAgentSticky(t *testing.T) {
h := All(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) { return Deny("gate"), nil },
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return NoDecision().StopAgent("halt everything"), nil
},
)
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("All: %v", err)
}
core := d.decCore()
if d.Kind() != DecisionDeny || !core.stopAgent || core.stopReason != "halt everything" {
t.Errorf("StopAgent must stick through the merge: kind=%v stop=%v reason=%q", d.Kind(), core.stopAgent, core.stopReason)
}
}
func TestAllErrorsJoinAndAbort(t *testing.T) {
e1, e2 := errors.New("first failure"), errors.New("second failure")
var calls []string
h := All(
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "f1")
return NoDecision(), e1
},
denyStage(&calls, "ok", "x"),
func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
calls = append(calls, "f2")
return NoDecision(), e2
},
)
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if !errors.Is(err, e1) || !errors.Is(err, e2) {
t.Errorf("joined error must carry both failures, got %v", err)
}
if got := strings.Join(calls, ","); got != "f1,ok,f2" {
t.Errorf("All must run every handler even after an error, ran %s", got)
}
if coreOf(d).kind != DecisionNoDecision {
t.Errorf("aborted combinator must return the neutral decision, got %v", d.Kind())
}
}
func TestAllContinueBeatsFinish(t *testing.T) {
ev := &StopEvent{Event: Event{Provider: ProviderClaudeCode, NativeName: "Stop", Kind: KindStop}}
h := All(
func(ctx context.Context, e *StopEvent) (StopDecision, error) { return Finish(), nil },
func(ctx context.Context, e *StopEvent) (StopDecision, error) { return ContinueWith("more work"), nil },
)
d, err := h(context.Background(), ev)
if err != nil {
t.Fatalf("All: %v", err)
}
if d.Kind() != DecisionContinue || d.Instruction() != "more work" {
t.Errorf("continue must outrank finish: kind=%v instruction=%q", d.Kind(), d.Instruction())
}
}
func TestWhenGuardsByMatcher(t *testing.T) {
shell := testToolPreEvent(ProviderClaudeCode, "Bash")
read := testToolPreEvent(ProviderClaudeCode, "Read")
mcp := testToolPreEvent(ProviderClaudeCode, "mcp__srv__lookup")
cases := []struct {
name string
m Matcher
hit *ToolPreEvent
miss *ToolPreEvent
}{
{"canonical", MatchCanonical(ToolShell), shell, read},
{"names", MatchTools("bash"), shell, read}, // case-insensitive
{"mcp", MatchMCP("srv/*"), mcp, shell},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var calls []string
h := When(tc.m, denyStage(&calls, "h", "gated"))
d, err := h(context.Background(), tc.hit)
if err != nil || d.Kind() != DecisionDeny {
t.Errorf("matching tool must dispatch: %v, %v", d.Kind(), err)
}
d, err = h(context.Background(), tc.miss)
if err != nil || d.Kind() != DecisionNoDecision {
t.Errorf("non-matching tool must be neutral: %v, %v", d.Kind(), err)
}
if len(calls) != 1 {
t.Errorf("handler ran %d times, want 1", len(calls))
}
})
}
}
func TestWhenNonToolEventIsNeutral(t *testing.T) {
called := false
h := When(MatchTools("Bash"), func(ctx context.Context, e *PromptEvent) (PromptDecision, error) {
called = true
return BlockPrompt("x"), nil
})
pe := &PromptEvent{Event: Event{Provider: ProviderClaudeCode, Kind: KindPromptSubmitted}, Prompt: "hi"}
d, err := h(context.Background(), pe)
if err != nil || d.Kind() != DecisionNoDecision || called {
t.Errorf("events without a tool call never match: kind=%v called=%v err=%v", d.Kind(), called, err)
}
}
type matchEverything struct{}
func (matchEverything) Matches(ToolCall) bool { return true }
func TestWhenAcceptsCustomMatcher(t *testing.T) {
var calls []string
h := When(matchEverything{}, denyStage(&calls, "h", "gated"))
d, err := h(context.Background(), testToolPreEvent(ProviderClaudeCode, "AnythingAtAll"))
if err != nil || d.Kind() != DecisionDeny || len(calls) != 1 {
t.Errorf("custom matcher must plug in: kind=%v calls=%v err=%v", d.Kind(), calls, err)
}
}
func TestUseMiddlewareOrder(t *testing.T) {
r := quietRunner()
var order []string
mw := func(name string) Interceptor {
return func(ctx context.Context, typed any, next Next) (Decision, error) {
order = append(order, name+"-before")
d, err := next(ctx, typed)
order = append(order, name+"-after")
return d, err
}
}
r.Use(mw("outer"))
r.Use(mw("inner"))
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
order = append(order, "handler")
return Deny("no"), nil
})
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil || d.Kind() != DecisionDeny {
t.Fatalf("got %v, %v", d, err)
}
want := "outer-before,inner-before,handler,inner-after,outer-after"
if got := strings.Join(order, ","); got != want {
t.Errorf("middleware order = %s, want %s", got, want)
}
}
func TestUseShortCircuitSkipsHandlers(t *testing.T) {
r := quietRunner()
handlerRan := false
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) {
return Deny("gated by middleware"), nil // never calls next
})
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
handlerRan = true
return NoDecision(), nil
})
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil || d.Kind() != DecisionDeny || handlerRan {
t.Errorf("middleware short-circuit: kind=%v handlerRan=%v err=%v", d.Kind(), handlerRan, err)
}
// Same middleware gates the edge path: the wire carries its deny.
out, code := runWith(t, r, claudeArgs(), fixture(t, "claude/pre_tool_use.json"))
if code != 0 || !strings.Contains(out, `"permissionDecision":"deny"`) {
t.Errorf("middleware must gate the edge path too: %q (exit %d)", out, code)
}
}
func TestUseTransformsProjection(t *testing.T) {
r := quietRunner()
var seen string
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) {
if tp, ok := typed.(*ToolPreEvent); ok {
tp.Tool.Input = json.RawMessage(`{"command":"echo safe"}`)
}
return next(ctx, typed)
})
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
seen = string(e.Tool.Input)
return NoDecision(), nil
})
ev := testToolPreEvent(ProviderClaudeCode, "Bash")
rawBefore := string(ev.Raw)
if _, err := r.Decide(context.Background(), ev); err != nil {
t.Fatalf("Decide: %v", err)
}
if seen != `{"command":"echo safe"}` {
t.Errorf("handler must see the transformed projection, saw %s", seen)
}
if string(ev.Raw) != rawBefore {
t.Error("Raw must stay verbatim through middleware transforms")
}
}
func TestUsePostProcessesDecision(t *testing.T) {
r := quietRunner()
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) {
d, err := next(ctx, typed)
if err == nil && d.Kind() == DecisionDeny {
return AskUser("softened: " + d.Reason()), nil
}
return d, err
})
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return Deny("hard"), nil
})
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if d.Kind() != DecisionAsk || d.Reason() != "softened: hard" {
t.Errorf("post-processing lost: kind=%v reason=%q", d.Kind(), d.Reason())
}
}
func walkToolPreStage(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return NoDecision(), nil
}
func walkStopStage(ctx context.Context, e *StopEvent) (StopDecision, error) {
return Finish(), nil
}
func walkMCPInventoryStage(context.Context, *MCPInventoryEvent) error { return nil }
func TestWalkOrderNamesAndPositions(t *testing.T) {
r := quietRunner()
r.OnAny(func(ctx context.Context, e *Event) error { return nil })
r.OnOther("Setup", func(ctx context.Context, e *Event) error { return nil })
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) { return next(ctx, typed) })
r.OnMCPInventory(walkMCPInventoryStage)
r.OnToolPre(walkToolPreStage, walkToolPreStage)
r.OnStop(walkStopStage)
var infos []StageInfo
if err := r.Walk(func(si StageInfo) error {
infos = append(infos, si)
return nil
}); err != nil {
t.Fatalf("Walk: %v", err)
}
if len(infos) != 7 {
t.Fatalf("visited %d stages, want 7: %+v", len(infos), infos)
}
check := func(i int, kind EventKind, typ StageType, pos int) {
t.Helper()
if infos[i].Kind != kind || infos[i].Type != typ || infos[i].Pos != pos {
t.Errorf("stage %d = %+v, want kind=%q type=%s pos=%d", i, infos[i], kind, typ, pos)
}
}
check(0, "", StageObserver, 0) // OnAny
check(1, KindOther, StageObserver, 0) // OnOther
check(2, "", StageMiddleware, 0) // Use
check(3, KindMCPInventory, StageHandler, 0)
check(4, KindToolPre, StageHandler, 0)
check(5, KindToolPre, StageHandler, 1)
check(6, KindStop, StageHandler, 0)
// OnOther stages all report KindOther, so Native carries the native event
// name they were registered for; every other stage leaves it empty.
if infos[1].Native != "Setup" {
t.Errorf("OnOther stage Native = %q, want %q", infos[1].Native, "Setup")
}
if infos[0].Native != "" || infos[4].Native != "" {
t.Errorf("non-OnOther stages must have empty Native: %q, %q", infos[0].Native, infos[4].Native)
}
// Names are the reflected function names: named funcs report as
// themselves, anonymous funcs as their closure names.
if !strings.Contains(infos[3].Name, "walkMCPInventoryStage") {
t.Errorf("reflected name for a named func: %q", infos[3].Name)
}
if !strings.Contains(infos[4].Name, "walkToolPreStage") {
t.Errorf("reflected name for a named func: %q", infos[4].Name)
}
if !strings.Contains(infos[5].Name, "walkToolPreStage") {
t.Errorf("reflected name for a named func: %q", infos[5].Name)
}
if !strings.Contains(infos[6].Name, "walkStopStage") {
t.Errorf("reflected name for a named func: %q", infos[6].Name)
}
}
func TestWalkStopsOnError(t *testing.T) {
r := quietRunner()
r.OnToolPre(walkToolPreStage, walkToolPreStage, walkToolPreStage)
sentinel := errors.New("stop walking")
visits := 0
err := r.Walk(func(si StageInfo) error {
visits++
if visits == 2 {
return sentinel
}
return nil
})
if !errors.Is(err, sentinel) || visits != 2 {
t.Errorf("Walk must stop at the first error: err=%v visits=%d", err, visits)
}
}
func TestCombinatorsCompose(t *testing.T) {
// Closure property: combinators nest and register like leaves.
var calls []string
r := quietRunner()
r.OnToolPre(
Any(
When(MatchCanonical(ToolFileRead), denyStage(&calls, "reads", "no reads")),
All(
neutralStage(&calls, "audit"),
When(MatchCanonical(ToolShell), denyStage(&calls, "shells", "no shells")),
),
),
)
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if got := strings.Join(calls, ","); got != "audit,shells" {
t.Errorf("composition ran %s, want audit,shells", got)
}
if d.Kind() != DecisionDeny || d.Reason() != "no shells" {
t.Errorf("got kind=%v reason=%q", d.Kind(), d.Reason())
}
}
// A blocking OnAny observer that ignores ctx must not defeat Decide's context
// deadline: observers run inside the same guard as the typed pipeline.
func TestDecideHonorsDeadlineAgainstBlockingObserver(t *testing.T) {
r := quietRunner()
r.OnAny(func(ctx context.Context, e *Event) error {
time.Sleep(2 * time.Second) // ignores ctx on purpose
return nil
})
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
_, err := r.Decide(ctx, testToolPreEvent(ProviderClaudeCode, "Bash"))
if elapsed := time.Since(start); elapsed > time.Second {
t.Errorf("deadline not enforced against observer: took %v", elapsed)
}
if err == nil {
t.Fatal("Decide must return the deadline error, got nil")
}
}
// A typed-nil event pointer must be rejected as an invalid event, not
// dereferenced into a panic by eventOf.
func TestDecideRejectsTypedNilEvent(t *testing.T) {
r := quietRunner()
var ev *ToolPreEvent // typed nil
d, err := r.Decide(context.Background(), ev)
if err == nil {
t.Fatal("Decide must reject a typed-nil event with an error")
}
if d != nil {
t.Errorf("rejected event must yield a nil decision, got %v", d)
}
}
// A misbehaving interceptor that returns a nil Decision must be normalized to
// the neutral zero decision so callers can inspect it without panicking.
func TestDecideNormalizesNilDecisionFromMiddleware(t *testing.T) {
r := quietRunner()
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) {
return nil, nil // never calls next; returns a nil decision
})
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
if d == nil {
t.Fatal("nil decision must be normalized to a non-nil neutral decision")
}
if d.Kind() != DecisionNoDecision {
t.Errorf("normalized decision kind = %v, want no-decision", d.Kind())
}
}
// next is at-most-once: a second call returns an error rather than silently
// re-running the downstream pipeline.
func TestInterceptorNextAtMostOnce(t *testing.T) {
r := quietRunner()
handlerCalls := 0
var secondErr error
r.Use(func(ctx context.Context, typed any, next Next) (Decision, error) {
d, err := next(ctx, typed)
_, secondErr = next(ctx, typed)
return d, err
})
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
handlerCalls++
return NoDecision(), nil
})
if _, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash")); err != nil {
t.Fatalf("Decide: %v", err)
}
if secondErr == nil {
t.Error("second next call must return an error")
}
if handlerCalls != 1 {
t.Errorf("downstream handler ran %d times, want 1", handlerCalls)
}
}
// StopsAgent exposes the StopAgent modifier and its reason on the Decision
// view returned by Decide.
func TestStopsAgentAccessor(t *testing.T) {
r := quietRunner()
r.OnToolPre(func(ctx context.Context, e *ToolPreEvent) (ToolPreDecision, error) {
return Deny("blocked").StopAgent("halt now"), nil
})
d, err := r.Decide(context.Background(), testToolPreEvent(ProviderClaudeCode, "Bash"))
if err != nil {
t.Fatalf("Decide: %v", err)
}
reason, ok := d.StopsAgent()
if !ok || reason != "halt now" {
t.Errorf("StopsAgent() = %q, %v; want \"halt now\", true", reason, ok)
}
// A decision without the modifier reports ok=false and an empty reason.
if reason, ok := NoDecision().StopsAgent(); ok || reason != "" {
t.Errorf("neutral StopsAgent() = %q, %v; want \"\", false", reason, ok)
}
}