-
Notifications
You must be signed in to change notification settings - Fork 444
Expand file tree
/
Copy pathpolicy-evaluator.test.ts
More file actions
1323 lines (1178 loc) · 58.1 KB
/
Copy pathpolicy-evaluator.test.ts
File metadata and controls
1323 lines (1178 loc) · 58.1 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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @vitest-environment node
import { describe, it, expect, beforeEach } from "vitest";
import { evaluatePolicies } from "../../src/hooks/policy-evaluator";
import { registerPolicy, clearPolicies } from "../../src/hooks/policy-registry";
describe("hooks/policy-evaluator", () => {
beforeEach(() => {
clearPolicies();
});
it("returns allow (exit 0, no stdout) when no policies match", async () => {
const result = await evaluatePolicies("PreToolUse", { tool_name: "Read" });
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe("");
expect(result.policyName).toBeNull();
expect(result.reason).toBeNull();
});
it("returns allow when all policies allow", async () => {
registerPolicy("allow1", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
registerPolicy("allow2", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe("");
expect(result.policyName).toBeNull();
expect(result.reason).toBeNull();
});
it("deny short-circuits — first deny wins for PreToolUse", async () => {
registerPolicy("blocker", "desc", () => ({ decision: "deny", reason: "blocked" }), {
events: ["PreToolUse"],
});
registerPolicy("allow", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash", tool_input: { command: "ls" } });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.permissionDecision).toBe("deny");
expect(parsed.hookSpecificOutput.permissionDecisionReason).toBe(
"Blocked Bash by failproofai because: blocked, as per the policy configured by the user",
);
expect(parsed.hookSpecificOutput.hookEventName).toBe("PreToolUse");
expect(result.policyName).toBe("exospherehost/blocker");
expect(result.reason).toBe("blocked");
});
it("formats PostToolUse deny with additionalContext", async () => {
registerPolicy("jwt-scrub", "desc", () => ({
decision: "deny",
reason: "JWT found",
message: "[REDACTED]",
}), { events: ["PostToolUse"] });
const result = await evaluatePolicies("PostToolUse", { tool_name: "Read" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.hookEventName).toBe("PostToolUse");
expect(parsed.hookSpecificOutput.additionalContext).toBe(
"Blocked Read by failproofai because: JWT found, as per the policy configured by the user",
);
expect(result.policyName).toBe("exospherehost/jwt-scrub");
expect(result.reason).toBe("JWT found");
});
it("other event types use exit 2 for deny", async () => {
registerPolicy("blocker", "desc", () => ({ decision: "deny", reason: "nope" }), {
events: ["SessionStart"],
});
const result = await evaluatePolicies("SessionStart", {});
expect(result.exitCode).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toBe("nope");
expect(result.reason).toBe("nope");
});
it("passes toolName and toolInput from payload to policy context", async () => {
let capturedCtx: unknown = null;
registerPolicy("spy", "desc", (ctx) => {
capturedCtx = ctx;
return { decision: "allow" };
}, { events: ["PreToolUse"] });
await evaluatePolicies("PreToolUse", {
tool_name: "Bash",
tool_input: { command: "ls" },
});
const ctx = capturedCtx as { toolName: string; toolInput: { command: string } };
expect(ctx.toolName).toBe("Bash");
expect(ctx.toolInput.command).toBe("ls");
});
it("supports async policy functions", async () => {
registerPolicy("async-deny", "desc", async () => {
return { decision: "deny", reason: "async block" };
}, { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.permissionDecision).toBe("deny");
});
it("instruct produces additionalContext in stdout with exit code 0", async () => {
registerPolicy("advisor", "desc", () => ({
decision: "instruct",
reason: "You should try something else",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Read" });
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.additionalContext).toContain("You should try something else");
expect(result.policyName).toBe("exospherehost/advisor");
expect(result.policyNames).toEqual(["exospherehost/advisor"]);
expect(result.reason).toBe("You should try something else");
});
it("deny takes precedence over instruct", async () => {
registerPolicy("advisor", "desc", () => ({
decision: "instruct",
reason: "just a warning",
}), { events: ["PreToolUse"] });
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "hard block",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.decision).toBe("deny");
expect(result.policyName).toBe("exospherehost/blocker");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.permissionDecision).toBe("deny");
});
it("EvaluationResult.decision is 'allow' when all allow", async () => {
registerPolicy("ok", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Read" });
expect(result.decision).toBe("allow");
expect(result.stdout).toBe("");
});
it("skips a policy that throws and continues to allow", async () => {
registerPolicy("thrower", "desc", () => { throw new Error("unexpected failure"); }, { events: ["PreToolUse"] });
registerPolicy("ok", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
});
it("skips an async policy that rejects and continues to allow", async () => {
registerPolicy("async-thrower", "desc", async () => { throw new Error("async failure"); }, { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
});
it("Stop + instruct returns exitCode 2 with reason in stderr", async () => {
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "Unsatisfied intents remain",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.exitCode).toBe(2);
expect(result.decision).toBe("instruct");
expect(result.stdout).toBe("");
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("Unsatisfied intents remain");
expect(result.policyName).toBe("exospherehost/verify");
});
it("SubagentStop + instruct also returns exitCode 2 (Claude path mirrors Stop)", async () => {
// The instruct-path Stop branch was widened to include SubagentStop, so
// custom subagent-instruct policies now go through the MANDATORY ACTION
// wrapper instead of falling through to the generic hookSpecificOutput
// additionalContext shape (which Claude does not honor for SubagentStop).
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "subagent left work undone",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {});
expect(result.exitCode).toBe(2);
expect(result.decision).toBe("instruct");
expect(result.stdout).toBe("");
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("subagent left work undone");
});
it("Copilot Stop + instruct emits {decision:'block', reason} JSON on stdout (NOT exit 2)", async () => {
// CodeRabbit catch on PR #299: the Copilot block-payload branch existed in
// the deny path but the instruct path's `eventType === "Stop"` arm had no
// Copilot branch, so instruct verdicts on Copilot Stop fell through to
// exit-2 — which Copilot logs as `[WARNING] Hook warning: ...` but does
// NOT honor for retry. Mirror the deny branch so instruct enforces too.
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "needs verification",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "copilot" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("needs verification");
});
it("Copilot SubagentStop + instruct also emits {decision:'block', reason} JSON", async () => {
// Combined coverage of both fixes: instruct-path SubagentStop on Copilot
// must produce the JSON-block shape (was double-fallthrough before — the
// branch only matched Stop AND only the deny path had a Copilot arm).
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "subagent verification pending",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "copilot" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("subagent verification pending");
});
it("Cursor SubagentStop + instruct emits {followup_message} JSON (parity with Stop branch)", async () => {
// The Cursor Stop instruct branch was widened to also match SubagentStop
// so custom policies subscribing to SubagentStop on Cursor get the same
// force-retry semantics. Mirrors the Copilot widening above.
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "subagent verification pending",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "cursor" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.followup_message).toMatch(/^Instruction from failproofai:/);
expect(parsed.followup_message).toContain("subagent verification pending");
});
it("OpenCode Stop + instruct emits {hookSpecificOutput.additionalContext} JSON on stdout (NOT exit 2)", async () => {
// Mirrors the Copilot/Cursor instruct-on-Stop fixes: without a per-CLI
// branch, opencode instruct verdicts fall through to exit-2 + stderr,
// which the OpenCode shim throws from inside session.idle — a no-op
// because the agent has already gone idle. The shim's only working
// force-retry channel is hookSpecificOutput.additionalContext routed
// through client.session.prompt.
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "needs verification",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "opencode" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as { hookSpecificOutput?: { additionalContext?: string } };
expect(parsed.hookSpecificOutput?.additionalContext).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.hookSpecificOutput?.additionalContext).toContain("needs verification");
});
it("OpenCode SubagentStop + instruct also emits {hookSpecificOutput.additionalContext} JSON", async () => {
// Forward-compat parity with the SubagentStop deny test — see comment
// there for why we widen even though OpenCode doesn't yet expose
// subagent boundaries to plugins.
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "subagent verification pending",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "opencode" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as { hookSpecificOutput?: { additionalContext?: string } };
expect(parsed.hookSpecificOutput?.additionalContext).toContain("subagent verification pending");
});
it("Gemini Stop + instruct emits {decision:'block', reason} JSON on stdout (force-retry via AfterAgent)", async () => {
// Confirms the existing cli==="gemini" Stop arm in the instruct path
// emits the documented force-retry shape. Pairs with the deny-path
// test in the "Stop event deny format" describe block.
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "needs verification",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "gemini" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
expect(result.decision).toBe("instruct");
const parsed = JSON.parse(result.stdout) as { decision?: string; reason?: string };
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("needs verification");
});
it("accumulates multiple instruct messages", async () => {
registerPolicy("first", "desc", () => ({
decision: "instruct",
reason: "first warning",
}), { events: ["PreToolUse"] });
registerPolicy("second", "desc", () => ({
decision: "instruct",
reason: "second warning",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Read" });
expect(result.decision).toBe("instruct");
expect(result.policyName).toBe("exospherehost/first");
expect(result.policyNames).toEqual(["exospherehost/first", "exospherehost/second"]);
expect(result.reason).toBe("first warning\nsecond warning");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.additionalContext).toContain("first warning");
expect(parsed.hookSpecificOutput.additionalContext).toContain("second warning");
});
describe("allow with message", () => {
it("returns additionalContext when allow has a reason", async () => {
registerPolicy("info", "desc", () => ({
decision: "allow",
reason: "All checks passed",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Read" });
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
expect(result.reason).toBe("All checks passed");
expect(result.policyName).toBe("exospherehost/info");
expect(result.policyNames).toEqual(["exospherehost/info"]);
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.additionalContext).toBe("Note from failproofai: All checks passed");
expect(result.stderr).toContain("[failproofai] exospherehost/info: All checks passed");
});
it("combines multiple allow messages with newline", async () => {
registerPolicy("info1", "desc", () => ({
decision: "allow",
reason: "Commit check passed",
}), { events: ["Stop"] });
registerPolicy("info2", "desc", () => ({
decision: "allow",
reason: "Push check passed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
expect(result.policyName).toBe("exospherehost/info1");
expect(result.policyNames).toEqual(["exospherehost/info1", "exospherehost/info2"]);
const parsed = JSON.parse(result.stdout);
expect(parsed.reason).toBe("Commit check passed\nPush check passed");
expect(result.stderr).toContain("[failproofai] exospherehost/info1: Commit check passed");
expect(result.stderr).toContain("[failproofai] exospherehost/info2: Push check passed");
});
it("returns empty stdout when allow has no reason (backward-compatible)", async () => {
registerPolicy("ok", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe("");
expect(result.stderr).toBe("");
expect(result.reason).toBeNull();
expect(result.policyName).toBeNull();
expect(result.policyNames).toBeUndefined();
});
it("deny still takes precedence over allow with message", async () => {
registerPolicy("info", "desc", () => ({
decision: "allow",
reason: "looks good",
}), { events: ["PreToolUse"] });
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.decision).toBe("deny");
expect(result.policyName).toBe("exospherehost/blocker");
});
it("instruct takes precedence over allow with message", async () => {
registerPolicy("info", "desc", () => ({
decision: "allow",
reason: "looks good",
}), { events: ["PreToolUse"] });
registerPolicy("advisor", "desc", () => ({
decision: "instruct",
reason: "be careful",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" });
expect(result.decision).toBe("instruct");
expect(result.policyName).toBe("exospherehost/advisor");
});
});
describe("params injection", () => {
it("injects schema defaults into ctx.params when no policyParams in config", async () => {
let capturedParams: unknown = null;
// Use BUILTIN_POLICIES to get a real policy with a params schema
const { BUILTIN_POLICIES } = await import("../../src/hooks/builtin-policies");
const orig = BUILTIN_POLICIES.find((p) => p.name === "block-sudo")!;
// Wrap the original fn to capture params
registerPolicy("block-sudo", orig.description, async (ctx) => {
capturedParams = ctx.params;
return { decision: "allow" };
}, orig.match);
await evaluatePolicies("PreToolUse", { tool_name: "Bash", tool_input: { command: "ls" } }, undefined, { enabledPolicies: ["block-sudo"] });
expect(capturedParams).toBeDefined();
expect((capturedParams as Record<string, unknown>).allowPatterns).toEqual([]);
});
it("overrides schema defaults with policyParams from config", async () => {
let capturedParams: unknown = null;
const { BUILTIN_POLICIES } = await import("../../src/hooks/builtin-policies");
const orig = BUILTIN_POLICIES.find((p) => p.name === "block-sudo")!;
registerPolicy("block-sudo", orig.description, async (ctx) => {
capturedParams = ctx.params;
return { decision: "allow" };
}, orig.match);
const config = {
enabledPolicies: ["block-sudo"],
policyParams: { "block-sudo": { allowPatterns: ["sudo systemctl status"] } },
};
await evaluatePolicies("PreToolUse", { tool_name: "Bash", tool_input: { command: "ls" } }, undefined, config);
expect((capturedParams as Record<string, unknown>).allowPatterns).toEqual(["sudo systemctl status"]);
});
it("unknown policyParams key does not crash evaluator", async () => {
registerPolicy("allow-all", "desc", () => ({ decision: "allow" }), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["allow-all"],
policyParams: { "nonexistent-policy": { someParam: 42 } },
};
await expect(
evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, config),
).resolves.not.toThrow();
});
it("flat policyParams key only matches default-namespace policies (not custom/myorg)", async () => {
// A custom hook registered with a third-party namespace must NOT pick up
// params keyed by the bare short name — that key belongs to the
// exospherehost/<short> builtin slot, not myorg/<short>.
let capturedHint: unknown = null;
registerPolicy("myorg/foo", "desc", () => ({
decision: "deny",
reason: "denied by myorg/foo",
}), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["myorg/foo"],
policyParams: { foo: { hint: "should NOT leak across namespaces" } },
};
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, config);
expect(result.decision).toBe("deny");
// Reason must not include the hint from the unrelated default-namespace key
expect(result.reason).toBe("denied by myorg/foo");
capturedHint = result.reason?.includes("should NOT leak");
expect(capturedHint).toBe(false);
});
it("custom hooks registered with custom/ prefix receive empty params", async () => {
let capturedParams: unknown = undefined;
registerPolicy("custom/my-hook", "custom", async (ctx) => {
capturedParams = ctx.params;
return { decision: "allow" };
}, { events: ["PreToolUse"] }, -1);
await evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, { enabledPolicies: [] });
// Custom hooks get empty params object
expect(capturedParams).toEqual({});
});
});
describe("Stop event deny format", () => {
it("Stop deny uses exit code 2 with reason in stderr", async () => {
registerPolicy("stop-blocker", "desc", () => ({
decision: "deny",
reason: "changes not committed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.exitCode).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("changes not committed");
expect(result.decision).toBe("deny");
expect(result.reason).toBe("changes not committed");
});
it("Copilot Stop deny emits {decision:'block', reason} JSON on stdout (NOT exit 2)", async () => {
// Copilot CLI 1.0.41 logs exit-2 from agentStop as `[WARNING] Hook
// warning: ...` but does NOT retry the agent. The documented retry
// shape is `{decision: "block", reason}` JSON on stdout (exit 0) — the
// reason becomes the next-turn prompt. The cli==="copilot" branch in
// policy-evaluator.ts emits this shape; this test pins it.
registerPolicy("stop-blocker", "desc", () => ({
decision: "deny",
reason: "changes not committed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "copilot" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("changes not committed");
expect(result.decision).toBe("deny");
});
it("Copilot SubagentStop deny also emits {decision:'block', reason} JSON (subagent retry)", async () => {
// CodeRabbit catch on PR #299: the cli==="copilot" branch initially only
// matched eventType==="Stop", so SubagentStop denies fell through to
// exit-2 — which Copilot ignores for stop-style events, leaving subagent
// policies as observation-only. Custom policies matching SubagentStop
// need the same JSON-block shape as Stop. (Builtin require-*-before-stop
// policies still match Stop only by design — they are session-completion
// gates, not subagent-return gates.)
registerPolicy("subagent-blocker", "desc", () => ({
decision: "deny",
reason: "subagent left work undone",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "copilot" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("subagent left work undone");
expect(result.decision).toBe("deny");
});
it("Claude SubagentStop deny still uses exit-2+stderr (regression: non-copilot path unchanged)", async () => {
// The Stop branch was widened to include SubagentStop; verify the
// non-copilot path still emits exit-2 with the MANDATORY ACTION wrapper
// (was previously falling through to the bare-reason "other events"
// fallback at the function tail — pre-existing minor inconsistency that
// the widening also fixed for SubagentStop on Claude).
registerPolicy("subagent-blocker", "desc", () => ({
decision: "deny",
reason: "subagent left work undone",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {});
expect(result.exitCode).toBe(2);
expect(result.stdout).toBe("");
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("subagent left work undone");
expect(result.decision).toBe("deny");
});
it("Cursor Stop deny emits {followup_message} JSON on stdout (NOT exit 2)", async () => {
// Cursor's `stop` hook ignores `{permission: "deny"}` — that shape is
// only honored on tool events. The only force-retry channel for Stop
// is `{followup_message}` on stdout (exit 0); Cursor auto-submits the
// text as the next user message (capped at `loop_limit`, default 5).
// Without the cli==="cursor" Stop arm in policy-evaluator.ts, the 5
// require-*-before-stop builtins were observation-only on Cursor —
// the deny was logged but the agent stopped cleanly.
// Ref: https://cursor.com/docs/hooks
registerPolicy("stop-blocker", "desc", () => ({
decision: "deny",
reason: "changes not committed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "cursor" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.followup_message).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.followup_message).toContain("changes not committed");
// The flat {permission:"deny", user_message, agent_message} shape MUST
// NOT be emitted on Stop — Cursor would ignore it and the agent would
// stop cleanly. This is the load-bearing assertion.
expect(parsed.permission).toBeUndefined();
expect(parsed.user_message).toBeUndefined();
expect(parsed.agent_message).toBeUndefined();
expect(result.decision).toBe("deny");
});
it("Cursor SubagentStop deny also emits {followup_message} JSON (subagent retry)", async () => {
// The cli==="cursor" Stop arm was widened to also match SubagentStop
// so custom policies subscribing to SubagentStop on Cursor enforce
// (the 5 require-*-before-stop builtins still match Stop only by
// design — they are session-completion gates, not subagent-return
// gates). Mirrors the Copilot SubagentStop widening from #299.
registerPolicy("subagent-blocker", "desc", () => ({
decision: "deny",
reason: "subagent left work undone",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "cursor" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.followup_message).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.followup_message).toContain("subagent left work undone");
expect(result.decision).toBe("deny");
});
it("Cursor PreToolUse deny still uses {permission:'deny'} flat shape (regression: tool-event path unchanged)", async () => {
// The Stop/SubagentStop arm is added INSIDE the cli==="cursor" branch
// so the flat-shape return below it is unchanged for tool events.
// Verify PreToolUse still emits the flat deny shape — Cursor's tool
// hooks DO honor it.
registerPolicy("tool-blocker", "desc", () => ({
decision: "deny",
reason: "blocked tool",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies(
"PreToolUse",
{ tool_name: "Bash", tool_input: { command: "ls" } },
{ cli: "cursor" },
);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout) as Record<string, unknown>;
expect(parsed.permission).toBe("deny");
expect(parsed.user_message).toMatch(/Blocked Bash by failproofai/);
expect(parsed.agent_message).toMatch(/Blocked Bash by failproofai/);
// No followup_message on tool events — that's a Stop-only shape.
expect(parsed.followup_message).toBeUndefined();
});
it("Stop deny short-circuits subsequent policies", async () => {
const secondPolicyCalled = { value: false };
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked first",
}), { events: ["Stop"] });
registerPolicy("second", "desc", () => {
secondPolicyCalled.value = true;
return { decision: "allow" };
}, { events: ["Stop"] });
await evaluatePolicies("Stop", {});
expect(secondPolicyCalled.value).toBe(false);
});
it("OpenCode Stop deny emits {hookSpecificOutput.additionalContext} JSON on stdout (NOT exit 2)", async () => {
// OpenCode's `session.idle` event is notification-only — by the time
// the plugin handler fires, the agent has already gone idle and a
// thrown error from the handler does not force-retry. The shim's only
// working force-retry channel is `client.session.prompt(...)`, which
// it routes through `hookSpecificOutput.additionalContext`. Without
// this branch, the 5 require-*-before-stop builtins were
// observation-only on OpenCode — the deny was logged in the dashboard
// but the agent stopped silently.
registerPolicy("stop-blocker", "desc", () => ({
decision: "deny",
reason: "changes not committed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "opencode" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as { hookSpecificOutput?: { additionalContext?: string; permissionDecision?: string } };
expect(parsed.hookSpecificOutput?.additionalContext).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.hookSpecificOutput?.additionalContext).toContain("changes not committed");
// Load-bearing: must NOT emit exit-2 (the shim would `throw` from
// session.idle, which OpenCode logs but ignores) or
// permissionDecision: "deny" (the shim would also throw on that path).
expect(parsed.hookSpecificOutput?.permissionDecision).toBeUndefined();
expect(result.decision).toBe("deny");
});
it("OpenCode SubagentStop deny also emits {hookSpecificOutput.additionalContext} JSON (forward-compat)", async () => {
// OpenCode does not yet expose subagent boundaries to plugins, but
// custom policies subscribing to SubagentStop should still get the
// force-retry shape if OpenCode adds the bus event later. Mirrors the
// Cursor + Copilot SubagentStop widening.
registerPolicy("subagent-blocker", "desc", () => ({
decision: "deny",
reason: "subagent left work undone",
}), { events: ["SubagentStop"] });
const result = await evaluatePolicies("SubagentStop", {}, { cli: "opencode" });
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout) as { hookSpecificOutput?: { additionalContext?: string } };
expect(parsed.hookSpecificOutput?.additionalContext).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.hookSpecificOutput?.additionalContext).toContain("subagent left work undone");
expect(result.decision).toBe("deny");
});
it("OpenCode PreToolUse deny still uses Claude permissionDecision shape (regression: tool-event path unchanged)", async () => {
// The Stop arm is added INSIDE the cli==="opencode" branch so the
// generic Claude shape below it is unchanged for tool events. The
// shim's applyDecision throws on permissionDecision: "deny" — that's
// the working path for tool events.
registerPolicy("tool-blocker", "desc", () => ({
decision: "deny",
reason: "blocked tool",
}), { events: ["PreToolUse"] });
const result = await evaluatePolicies(
"PreToolUse",
{ tool_name: "Bash", tool_input: { command: "ls" } },
{ cli: "opencode" },
);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout) as { hookSpecificOutput?: { permissionDecision?: string; additionalContext?: string } };
expect(parsed.hookSpecificOutput?.permissionDecision).toBe("deny");
// No additionalContext on tool events — that's a Stop-only shape.
expect(parsed.hookSpecificOutput?.additionalContext).toBeUndefined();
});
it("Gemini Stop deny emits {decision:'block', reason} JSON on stdout (force-retry via AfterAgent)", async () => {
// Per Gemini's hooks docs (https://geminicli.com/docs/hooks/), the
// AfterAgent hook (canonical "Stop") force-retries when the hook
// returns `{decision: "block", reason}` on stdout. Exit-2 is per-
// action only ("turn continues") and would NOT trigger the retry.
registerPolicy("stop-blocker", "desc", () => ({
decision: "deny",
reason: "tests not run",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {}, { cli: "gemini" });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout) as { decision?: string; reason?: string };
expect(parsed.decision).toBe("block");
expect(parsed.reason).toContain("MANDATORY ACTION REQUIRED");
expect(parsed.reason).toContain("tests not run");
expect(result.decision).toBe("deny");
});
});
describe("workflow policy chain integration", () => {
it("first deny short-circuits — later workflow policies do not run", async () => {
const policyCalls: string[] = [];
registerPolicy("require-commit", "desc", () => {
policyCalls.push("commit");
return { decision: "deny", reason: "uncommitted changes" };
}, { events: ["Stop"] });
registerPolicy("require-push", "desc", () => {
policyCalls.push("push");
return { decision: "deny", reason: "unpushed commits" };
}, { events: ["Stop"] });
registerPolicy("require-pr", "desc", () => {
policyCalls.push("pr");
return { decision: "deny", reason: "no PR" };
}, { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.decision).toBe("deny");
expect(result.policyName).toBe("exospherehost/require-commit");
expect(policyCalls).toEqual(["commit"]);
});
it("all workflow policies allow with messages — messages accumulate", async () => {
registerPolicy("wf-commit", "desc", () => ({
decision: "allow",
reason: "All changes committed",
}), { events: ["Stop"] });
registerPolicy("wf-push", "desc", () => ({
decision: "allow",
reason: "All commits pushed",
}), { events: ["Stop"] });
registerPolicy("wf-pr", "desc", () => ({
decision: "allow",
reason: "PR #42 exists",
}), { events: ["Stop"] });
registerPolicy("wf-ci", "desc", () => ({
decision: "allow",
reason: "All CI checks passed",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
expect(result.policyNames).toEqual(["exospherehost/wf-commit", "exospherehost/wf-push", "exospherehost/wf-pr", "exospherehost/wf-ci"]);
const parsed = JSON.parse(result.stdout);
expect(parsed.reason).toContain("All changes committed");
expect(parsed.reason).toContain("All commits pushed");
expect(parsed.reason).toContain("PR #42 exists");
expect(parsed.reason).toContain("All CI checks passed");
});
it("allow messages from early policies are discarded when a later policy denies", async () => {
registerPolicy("wf-commit", "desc", () => ({
decision: "allow",
reason: "All changes committed",
}), { events: ["Stop"] });
registerPolicy("wf-push", "desc", () => ({
decision: "deny",
reason: "unpushed commits",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.decision).toBe("deny");
expect(result.policyName).toBe("exospherehost/wf-push");
expect(result.reason).toBe("unpushed commits");
});
it("instruct on Stop takes precedence over allow messages", async () => {
registerPolicy("wf-commit", "desc", () => ({
decision: "allow",
reason: "All committed",
}), { events: ["Stop"] });
registerPolicy("wf-instruct", "desc", () => ({
decision: "instruct",
reason: "Please verify tests",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.decision).toBe("instruct");
expect(result.exitCode).toBe(2);
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("Please verify tests");
});
it("mixed allow (no message) and allow (with message) — only messages returned", async () => {
registerPolicy("silent", "desc", () => ({
decision: "allow",
}), { events: ["Stop"] });
registerPolicy("informative", "desc", () => ({
decision: "allow",
reason: "CI is green",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.exitCode).toBe(0);
expect(result.decision).toBe("allow");
expect(result.policyName).toBe("exospherehost/informative");
expect(result.policyNames).toEqual(["exospherehost/informative"]);
const parsed = JSON.parse(result.stdout);
expect(parsed.reason).toBe("CI is green");
});
it("policy that throws is skipped — subsequent policies still run", async () => {
registerPolicy("thrower", "desc", () => {
throw new Error("unexpected crash");
}, { events: ["Stop"] });
registerPolicy("checker", "desc", () => ({
decision: "deny",
reason: "uncommitted",
}), { events: ["Stop"] });
const result = await evaluatePolicies("Stop", {});
expect(result.decision).toBe("deny");
expect(result.policyName).toBe("exospherehost/checker");
});
});
describe("hint appending", () => {
it("appends hint to deny reason for PreToolUse", async () => {
registerPolicy("block-force-push", "desc", () => ({
decision: "deny",
reason: "Force-pushing is blocked",
}), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["block-force-push"],
policyParams: { "block-force-push": { hint: "Try creating a fresh branch instead." } },
};
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash", tool_input: { command: "git push --force" } }, undefined, config);
expect(result.decision).toBe("deny");
expect(result.reason).toBe("Force-pushing is blocked. Try creating a fresh branch instead.");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.permissionDecisionReason).toContain("Try creating a fresh branch instead.");
});
it("appends hint to deny reason for PostToolUse", async () => {
registerPolicy("scrubber", "desc", () => ({
decision: "deny",
reason: "Secret detected",
}), { events: ["PostToolUse"] });
const config = {
enabledPolicies: ["scrubber"],
policyParams: { scrubber: { hint: "Remove the secret before retrying." } },
};
const result = await evaluatePolicies("PostToolUse", { tool_name: "Bash" }, undefined, config);
expect(result.decision).toBe("deny");
expect(result.reason).toBe("Secret detected. Remove the secret before retrying.");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.additionalContext).toContain("Remove the secret before retrying.");
});
it("appends hint to deny reason for other event types (exit 2)", async () => {
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "nope",
}), { events: ["SessionStart"] });
const config = {
enabledPolicies: ["blocker"],
policyParams: { blocker: { hint: "Ask admin for access." } },
};
const result = await evaluatePolicies("SessionStart", {}, undefined, config);
expect(result.exitCode).toBe(2);
expect(result.reason).toBe("nope. Ask admin for access.");
expect(result.stderr).toBe("nope. Ask admin for access.");
});
it("appends hint to instruct reason", async () => {
registerPolicy("advisor", "desc", () => ({
decision: "instruct",
reason: "Large file detected",
}), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["advisor"],
policyParams: { advisor: { hint: "Consider splitting into smaller files." } },
};
const result = await evaluatePolicies("PreToolUse", { tool_name: "Write" }, undefined, config);
expect(result.decision).toBe("instruct");
expect(result.reason).toBe("Large file detected. Consider splitting into smaller files.");
const parsed = JSON.parse(result.stdout);
expect(parsed.hookSpecificOutput.additionalContext).toContain("Consider splitting into smaller files.");
});
it("appends hint to instruct reason on Stop event", async () => {
registerPolicy("verify", "desc", () => ({
decision: "instruct",
reason: "Unsatisfied intents",
}), { events: ["Stop"] });
const config = {
enabledPolicies: ["verify"],
policyParams: { verify: { hint: "Run the test suite first." } },
};
const result = await evaluatePolicies("Stop", {}, undefined, config);
expect(result.exitCode).toBe(2);
expect(result.decision).toBe("instruct");
expect(result.reason).toBe("Unsatisfied intents. Run the test suite first.");
expect(result.stderr).toContain("MANDATORY ACTION REQUIRED");
expect(result.stderr).toContain("Unsatisfied intents. Run the test suite first.");
});
it("does not alter reason when no hint is configured", async () => {
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked",
}), { events: ["PreToolUse"] });
const config = { enabledPolicies: ["blocker"] };
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, config);
expect(result.reason).toBe("blocked");
});
it("does not alter reason when policyParams has no hint key", async () => {
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked",
}), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["blocker"],
policyParams: { blocker: { someOtherParam: "value" } },
};
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, config);
expect(result.reason).toBe("blocked");
});
it("ignores hint when it is not a string (number)", async () => {
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked",
}), { events: ["PreToolUse"] });
const config = {
enabledPolicies: ["blocker"],
policyParams: { blocker: { hint: 123 } },
};
const result = await evaluatePolicies("PreToolUse", { tool_name: "Bash" }, undefined, config);
expect(result.reason).toBe("blocked");
});
it("ignores hint when it is an empty string", async () => {
registerPolicy("blocker", "desc", () => ({
decision: "deny",
reason: "blocked",