-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_claude_hooks_runtime.py
More file actions
1798 lines (1585 loc) · 65.7 KB
/
Copy pathtest_claude_hooks_runtime.py
File metadata and controls
1798 lines (1585 loc) · 65.7 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
"""RED: Claude work-loop hook runtime behavior (issue #249)."""
from __future__ import annotations
import json
import shlex
import subprocess
import sys
from datetime import timedelta
from pathlib import Path
import pytest
from brigade import cli, localio
from brigade.claude_hooks import runtime
from brigade.install import install_selection
from brigade.selection import Selection
def _wired_claude(tmp_path: Path) -> Path:
target = tmp_path / "repo"
selection = Selection(depth="repo", harnesses=["claude"], owner="claude", includes=[])
assert install_selection(target, selection) == 0
return target
def _git_wired_claude(tmp_path: Path) -> Path:
target = _wired_claude(tmp_path)
subprocess.run(["git", "init"], cwd=target, check=True, capture_output=True, text=True)
subprocess.run(
["git", "config", "user.email", "test@example.com"],
cwd=target,
check=True,
capture_output=True,
text=True,
)
subprocess.run(
["git", "config", "user.name", "Test User"],
cwd=target,
check=True,
capture_output=True,
text=True,
)
return target
def _payload(target: Path, event: str, *, session_id: str = "session-1", **extra):
return {
"session_id": session_id,
"cwd": str(target),
"hook_event_name": event,
**extra,
}
def test_session_start_injects_brief_once_per_repo(tmp_path: Path, monkeypatch):
target = _wired_claude(tmp_path)
calls: list[Path] = []
def fake_brief(repo: Path) -> str:
calls.append(repo)
return "work brief: test\nnext: fix issue"
monkeypatch.setattr(runtime, "_run_brief", fake_brief)
first = runtime.handle_payload("SessionStart", _payload(target, "SessionStart"))
second = runtime.handle_payload("SessionStart", _payload(target, "SessionStart"))
assert first["hookSpecificOutput"]["hookEventName"] == "SessionStart"
assert "work brief: test" in first["hookSpecificOutput"]["additionalContext"]
assert second is None
assert calls == [target.resolve()]
def test_all_events_are_inert_for_unwired_repo(tmp_path: Path, monkeypatch):
monkeypatch.setattr(runtime, "_run_brief", lambda target: (_ for _ in ()).throw(AssertionError(target)))
assert runtime.handle_payload("SessionStart", _payload(tmp_path, "SessionStart")) is None
assert (
runtime.handle_payload(
"PreToolUse",
_payload(tmp_path, "PreToolUse", tool_name="Bash", tool_input={"command": "pytest"}),
)
is None
)
assert runtime.handle_payload("Stop", _payload(tmp_path, "Stop", stop_hook_active=False)) is None
def test_pretooluse_denies_raw_verification_with_exact_replacement(tmp_path: Path):
target = _wired_claude(tmp_path)
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": "python -m pytest -q"}),
)
specific = result["hookSpecificOutput"]
assert specific["hookEventName"] == "PreToolUse"
assert specific["permissionDecision"] == "deny"
reason = specific["permissionDecisionReason"]
assert "brigade work verify run" in reason
assert f"--target {target.resolve()}" in reason
assert "--capture brigade-work" in reason
assert "python -m pytest -q" in reason
def test_pretooluse_avoids_recursion_and_false_positive_noise(tmp_path: Path):
target = _wired_claude(tmp_path)
for command in (
'brigade work verify run --target . --command "pytest" --capture brigade-work',
"echo pytest",
"echo '$(pytest -q)'",
'echo "(pytest -q)"',
"sh -c 'echo pytest'",
"bash -o errexit -c 'echo pytest'",
"bash script.sh -c pytest",
"if true; then echo pytest; fi",
"{ echo pytest; }",
"python -V -m pytest",
"python -c \"print('pytest')\"",
"ruff format src/",
"rg test src",
"cat tests/test_cli.py",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
assert result is None, command
def test_pretooluse_denies_compound_containing_verifier(tmp_path: Path):
target = _wired_claude(tmp_path)
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": "cd src && pytest -q"}),
)
assert result["hookSpecificOutput"]["permissionDecision"] == "deny"
def test_pretooluse_denies_verifier_smuggled_with_routed_verify(tmp_path: Path):
target = _wired_claude(tmp_path)
routed = 'brigade work verify run --target . --command "pytest" --capture brigade-work'
for command in (
f"pytest -q && {routed}",
f"{routed} && pytest -q",
f"cd src && pytest -q; {routed}",
"pytest brigade work verify",
f"{routed}\npytest -q",
f"pytest -q\n{routed}",
"echo ok\npytest -q",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
assert result["hookSpecificOutput"]["permissionDecision"] == "deny", command
def test_pretooluse_denies_confident_verifier_wrappers(tmp_path: Path):
target = _wired_claude(tmp_path)
for command in (
"uv run pytest -q",
"uv run -- pytest -q",
"uv run --no-sync pytest -q",
"uv run --python 3.12 pytest -q",
"uv run --with rich pytest -q",
"uv --directory src run pytest -q",
"poetry run pytest -q",
"poetry run -- pytest -q",
"poetry run -C src pytest -q",
"poetry -C src run pytest -q",
"npx jest",
"npm run test:unit",
"npm run -- test",
"npm run -s test",
"npm run --silent test",
"pnpm --filter app run test",
"yarn run -- test",
"bun run -- test",
"make -p test",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
assert result["hookSpecificOutput"]["permissionDecision"] == "deny", command
def test_pretooluse_denies_standard_shell_and_npx_wrappers(tmp_path: Path):
target = _wired_claude(tmp_path)
for command in (
"env CI=1 pytest -q",
"env -i CI=1 pytest -q",
"env -v pytest -q",
"env -iv pytest -q",
"env -Csrc pytest -q",
"env -uFOO pytest -q",
"env --argv0=verify pytest -q",
"env -S 'pytest -q'",
"env --split-string='pytest -q'",
"command pytest -q",
"command -p pytest -q",
"npx --yes jest",
"npx --prefer-offline jest",
"npx -y jest",
"npx --prefix /tmp jest",
"npx --node-options=--test jest",
"npx --future-option /tmp jest",
"python -u -m pytest -q",
"python -B -m unittest",
"python -d -m pytest -q",
"python -X dev -m pytest -q",
"python -W ignore -m pytest -q",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
assert result["hookSpecificOutput"]["permissionDecision"] == "deny", command
def test_pretooluse_withholds_exact_guidance_for_unknown_npx_options(tmp_path: Path):
target = _wired_claude(tmp_path)
result = runtime.handle_payload(
"PreToolUse",
_payload(
target,
"PreToolUse",
tool_name="Bash",
tool_input={"command": "npx --future-option /tmp jest"},
),
)
reason = result["hookSpecificOutput"]["permissionDecisionReason"]
assert "Use:" not in reason
def test_pretooluse_withholds_exact_guidance_for_unknown_runner_options(tmp_path: Path):
target = _wired_claude(tmp_path)
result = runtime.handle_payload(
"PreToolUse",
_payload(
target,
"PreToolUse",
tool_name="Bash",
tool_input={"command": "uv --future-option value run pytest -q"},
),
)
reason = result["hookSpecificOutput"]["permissionDecisionReason"]
assert "Use:" not in reason
def test_pretooluse_compound_guidance_routes_only_the_verifier_segment(tmp_path: Path):
target = _wired_claude(tmp_path)
for command, expected in (
("pytest -q; echo done", "pytest -q"),
("pytest -q\ntrue", "pytest -q"),
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
reason = result["hookSpecificOutput"]["permissionDecisionReason"]
replacement = shlex.split(reason.split("Use: ", 1)[1])
routed_command = replacement[replacement.index("--command") + 1]
assert routed_command == expected, command
def test_pretooluse_denies_nested_verifiers_without_unsafe_guidance(tmp_path: Path):
target = _wired_claude(tmp_path)
for command in (
"(pytest -q)",
'echo "$(pytest -q)"',
"pytest -q > result.txt",
"printf setup | pytest -q",
"cd -P src && pytest -q",
"cd src && cd nested && pytest -q",
"cd src; pytest -q",
"cd src\npytest -q",
"cd src && true && pytest -q",
"sh -c 'pytest -q'",
"bash -lc 'pytest -q'",
"pytest -q 2>&1",
"pytest -q &> result.txt",
"printf setup |& pytest -q",
'echo "$(echo "$(pytest -q)")"',
"if true; then pytest -q; fi",
"{ pytest -q; }",
"bash -o errexit -c 'pytest -q'",
"bash -O extglob -c 'pytest -q'",
"sh -o errexit -c 'pytest -q'",
"cd src && pytest -q",
"pushd src && pytest -q",
"builtin cd src && pytest -q",
"command cd src && pytest -q",
"source setup.sh && pytest -q",
"echo setup && pytest -q",
"cd - && pytest -q",
"cd ~ && pytest -q",
'cd "$SOURCE_ROOT" && pytest -q',
'PYTHONPATH="$PWD/src" python -m pytest -q',
"pytest -q tests/test_*.py",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
reason = result["hookSpecificOutput"]["permissionDecisionReason"]
assert result["hookSpecificOutput"]["permissionDecision"] == "deny", command
assert "Use:" not in reason, command
assert "Split shell grouping" in reason, command
def test_pretooluse_guidance_preserves_safe_verifier_context(tmp_path: Path):
target = _wired_claude(tmp_path)
for command, expected in (
("CI=1 pytest -q", "CI=1 pytest -q"),
("env -C src pytest -q", "env -C src pytest -q"),
("command pytest -q", "pytest -q"),
("command -p pytest -q", "pytest -q"),
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
reason = result["hookSpecificOutput"]["permissionDecisionReason"]
replacement = shlex.split(reason.split("Use: ", 1)[1])
routed_command = replacement[replacement.index("--command") + 1]
assert routed_command == expected, command
def test_pretooluse_denies_make_with_global_options(tmp_path: Path):
target = _wired_claude(tmp_path)
for command in (
"make -C src test",
"make --directory=src test",
"make -j4 test",
"make -j 4 check",
"make -s verify",
):
result = runtime.handle_payload(
"PreToolUse",
_payload(target, "PreToolUse", tool_name="Bash", tool_input={"command": command}),
)
assert result["hookSpecificOutput"]["permissionDecision"] == "deny", command
def test_posttooluse_records_python_c_write_via_repo_snapshot(tmp_path: Path):
target = _wired_claude(tmp_path)
session_id = "python-c-write"
out_file = target / "snapshot.py"
command = f"{sys.executable} -c \"from pathlib import Path; Path({str(out_file)!r}).write_text('x')\""
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is False
assert "pending_bash_fingerprint" in runtime.read_session_state(target, session_id)
out_file.write_text("x")
succeeded = {**pretool, "hook_event_name": "PostToolUse"}
assert runtime.handle_payload("PostToolUse", succeeded) is None
state = runtime.read_session_state(target, session_id)
assert state["write_observed"] is True
assert "pending_bash_fingerprint" not in state
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
def test_posttooluse_ignores_concurrent_session_write_during_read_only_bash(tmp_path: Path):
target = _wired_claude(tmp_path)
reader_session = "read-only-bash"
writer_session = "concurrent-writer"
pretool = _payload(
target,
"PreToolUse",
session_id=reader_session,
tool_name="Bash",
tool_input={"command": f"{sys.executable} -c \"print('noop')\""},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
pending_reader_state = runtime.read_session_state(target, reader_session)
assert "pending_bash_fingerprint" in pending_reader_state
assert "pending_bash_started_at" in pending_reader_state
changed = target / "concurrent.py"
changed.write_text("changed\n")
assert (
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=writer_session,
tool_name="Write",
tool_input={"file_path": str(changed)},
),
)
is None
)
assert runtime.read_session_state(target, writer_session)["write_observed"] is True
assert runtime.handle_payload("PostToolUse", {**pretool, "hook_event_name": "PostToolUse"}) is None
reader_state = runtime.read_session_state(target, reader_session)
assert reader_state["write_observed"] is False
assert "pending_bash_fingerprint" not in reader_state
assert "pending_bash_started_at" not in reader_state
assert (
runtime.handle_payload("Stop", _payload(target, "Stop", session_id=reader_session, stop_hook_active=False))
is None
)
def test_posttooluse_snapshot_fails_closed_when_state_cannot_be_inspected(tmp_path: Path, monkeypatch):
target = _wired_claude(tmp_path)
session_id = "snapshot-unavailable"
monkeypatch.setattr(runtime, "repo_worktree_fingerprint", lambda repo: None)
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": f"{sys.executable} -c \"print('noop')\""},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, session_id).get("pending_bash_fingerprint") == "unavailable"
succeeded = {**pretool, "hook_event_name": "PostToolUse"}
assert runtime.handle_payload("PostToolUse", succeeded) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is True
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
def test_posttooluse_fails_closed_when_post_command_snapshot_is_unavailable(tmp_path: Path, monkeypatch):
target = _wired_claude(tmp_path)
session_id = "post-snapshot-unavailable"
fingerprint_calls = 0
def sequenced_fingerprint(repo: Path) -> str | None:
nonlocal fingerprint_calls
fingerprint_calls += 1
return "baseline" if fingerprint_calls < 4 else None
monkeypatch.setattr(runtime, "repo_worktree_fingerprint", sequenced_fingerprint)
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": f"{sys.executable} -c \"print('noop')\""},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, session_id)["pending_bash_fingerprint"] == "baseline"
assert runtime.handle_payload("PostToolUse", {**pretool, "hook_event_name": "PostToolUse"}) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is True
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
@pytest.mark.parametrize("command", ["gh --version", "jq --version", "rg --version"])
def test_posttooluse_unlisted_read_only_command_does_not_observe_write(tmp_path: Path, command: str):
target = _git_wired_claude(tmp_path)
session_id = f"read-only-{command.split()[0]}"
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.handle_payload("PostToolUse", {**pretool, "hook_event_name": "PostToolUse"}) is None
state = runtime.read_session_state(target, session_id)
assert state["write_observed"] is False
assert "pending_bash_fingerprint" not in state
assert (
runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False)) is None
)
def test_final_bash_handoff_write_does_not_require_verification_again(tmp_path: Path, monkeypatch):
target = _wired_claude(tmp_path)
session_id = "bash-handoff-last"
monkeypatch.setattr(runtime, "_run_brief", lambda repo: "brief")
runtime.handle_payload("SessionStart", _payload(target, "SessionStart", session_id=session_id))
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
),
)
state = runtime.read_session_state(target, session_id)
run_dir = target / ".brigade" / "work" / "verify-runs" / "run-1"
run_dir.mkdir(parents=True)
(run_dir / "receipt.json").write_text(
json.dumps(
{
"run_id": "run-1",
"status": "completed",
"started_at": state["last_verification_write_at"],
"harness_session": {
"harness": "claude",
"fingerprint": state["session_fingerprint"],
},
}
)
+ "\n"
)
handoff = target / ".claude" / "memory-handoffs" / "handoff.md"
handoff.write_text("durable finding\n")
command = "printf '%s\\n' finding >> .claude/memory-handoffs/handoff.md"
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
),
)
updated = runtime.read_session_state(target, session_id)
assert updated["last_write_at"] >= updated["last_verification_write_at"]
assert updated["last_verification_write_at"] == state["last_verification_write_at"]
assert (
runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False)) is None
)
@pytest.mark.parametrize(
"command",
[
"sed -i 's/old/new/' src/app.py && printf done >> .claude/memory-handoffs/note.md",
"sed -i 's/old/new/' src/app.py > .claude/memory-handoffs/note.md",
"ruff format src/app.py > .claude/memory-handoffs/note.md",
"python fix.py > .claude/memory-handoffs/note.md",
"git commit -am fix > .claude/memory-handoffs/note.md",
"mv src/app.py .claude/memory-handoffs/app.md",
"truncate -s 0 src/app.py .claude/memory-handoffs/note.md",
"cp -t src .claude/memory-handoffs/note.md",
"cp --target-directory src .claude/memory-handoffs/note.md",
"install --target-directory=src .claude/memory-handoffs/note.md",
"install -d src .claude/memory-handoffs/note",
"install --directory src .claude/memory-handoffs/note",
"mv -tsrc .claude/memory-handoffs/note.md",
"mv --target-directory=src .claude/memory-handoffs/note.md",
"install -dm755 src .claude/memory-handoffs/note",
],
)
def test_mixed_bash_code_and_handoff_write_requires_new_verification(tmp_path: Path, monkeypatch, command: str):
target = _wired_claude(tmp_path)
session_id = "mixed-bash-handoff"
monkeypatch.setattr(runtime, "_run_brief", lambda repo: "brief")
runtime.handle_payload("SessionStart", _payload(target, "SessionStart", session_id=session_id))
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
),
)
state = runtime.read_session_state(target, session_id)
run_dir = target / ".brigade" / "work" / "verify-runs" / "run-1"
run_dir.mkdir(parents=True)
(run_dir / "receipt.json").write_text(
json.dumps(
{
"run_id": "run-1",
"status": "completed",
"started_at": state["last_verification_write_at"],
"harness_session": {
"harness": "claude",
"fingerprint": state["session_fingerprint"],
},
}
)
+ "\n"
)
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
),
)
updated = runtime.read_session_state(target, session_id)
assert updated["last_verification_write_at"] > state["last_verification_write_at"]
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
def test_stop_ignores_postcapture_brigade_run_artifact_writes(tmp_path: Path, monkeypatch):
"""Issue #483: detached brigade run artifacts under .brigade/runs/ must not re-arm closeout."""
target = _wired_claude(tmp_path)
session_id = "brigade-runs-artifact"
monkeypatch.setattr(runtime, "_run_brief", lambda repo: "brief")
runtime.handle_payload("SessionStart", _payload(target, "SessionStart", session_id=session_id))
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
),
)
state = runtime.read_session_state(target, session_id)
run_dir = target / ".brigade" / "work" / "verify-runs" / "run-1"
run_dir.mkdir(parents=True)
(run_dir / "receipt.json").write_text(
json.dumps(
{
"run_id": "run-1",
"status": "completed",
"started_at": state["last_verification_write_at"],
"harness_session": {
"harness": "claude",
"fingerprint": state["session_fingerprint"],
},
}
)
+ "\n"
)
artifact = target / ".brigade" / "runs" / "detached-1" / "run.json"
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": f"mkdir -p {artifact.parent} && touch {artifact}"},
),
)
updated = runtime.read_session_state(target, session_id)
assert updated["last_verification_write_at"] == state["last_verification_write_at"]
result = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert "decision" not in result
def test_stop_still_blocks_after_source_edit_post_capture(tmp_path: Path, monkeypatch):
"""Issue #483: real source edits after capture must still trip the closeout gate."""
target = _wired_claude(tmp_path)
session_id = "source-edit-post-capture"
monkeypatch.setattr(runtime, "_run_brief", lambda repo: "brief")
runtime.handle_payload("SessionStart", _payload(target, "SessionStart", session_id=session_id))
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
),
)
state = runtime.read_session_state(target, session_id)
run_dir = target / ".brigade" / "work" / "verify-runs" / "run-1"
run_dir.mkdir(parents=True)
(run_dir / "receipt.json").write_text(
json.dumps(
{
"run_id": "run-1",
"status": "completed",
"started_at": state["last_verification_write_at"],
"harness_session": {
"harness": "claude",
"fingerprint": state["session_fingerprint"],
},
}
)
+ "\n"
)
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "src.py"), "content": "changed\n"},
),
)
updated = runtime.read_session_state(target, session_id)
assert updated["last_verification_write_at"] > state["last_verification_write_at"]
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
def test_posttooluse_brigade_run_does_not_record_write(tmp_path: Path, monkeypatch):
"""Issue #483: brigade run bash must not bump verification write timestamps."""
target = _wired_claude(tmp_path)
session_id = "brigade-run-bash"
monkeypatch.setattr(runtime, "_run_brief", lambda repo: "brief")
runtime.handle_payload("SessionStart", _payload(target, "SessionStart", session_id=session_id))
runtime.handle_payload(
"PostToolUse",
_payload(
target,
"PostToolUse",
session_id=session_id,
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
),
)
state = runtime.read_session_state(target, session_id)
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": "brigade run --detach -- echo noop"},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert "pending_bash_fingerprint" in runtime.read_session_state(target, session_id)
runtime.handle_payload("PostToolUse", {**pretool, "hook_event_name": "PostToolUse"})
updated = runtime.read_session_state(target, session_id)
assert updated["last_verification_write_at"] == state["last_verification_write_at"]
assert "pending_bash_fingerprint" not in updated
def test_repo_worktree_fingerprint_detects_dirty_tracked_same_size_rewrite(tmp_path: Path):
target = _git_wired_claude(tmp_path)
tracked = target / "tracked.txt"
tracked.write_text("version-a\n")
subprocess.run(["git", "add", "tracked.txt"], cwd=target, check=True, capture_output=True, text=True)
subprocess.run(["git", "commit", "-m", "init"], cwd=target, check=True, capture_output=True, text=True)
tracked.write_text("version-b\n")
assert len("version-a\n") == len("version-b\n")
status_before = subprocess.check_output(
["git", "-C", str(target), "status", "--porcelain", "-u", "--no-renames"],
text=True,
)
baseline = runtime.repo_worktree_fingerprint(target)
tracked.write_text("version-c\n")
assert len("version-b\n") == len("version-c\n")
status_after = subprocess.check_output(
["git", "-C", str(target), "status", "--porcelain", "-u", "--no-renames"],
text=True,
)
assert status_before == status_after
updated = runtime.repo_worktree_fingerprint(target)
assert baseline is not None
assert updated is not None
assert baseline != updated
def test_repo_worktree_fingerprint_detects_untracked_same_size_rewrite(tmp_path: Path):
target = _git_wired_claude(tmp_path)
untracked = target / "new.txt"
untracked.write_text("aaaa")
status_before = subprocess.check_output(
["git", "-C", str(target), "status", "--porcelain", "-u", "--no-renames"],
text=True,
)
baseline = runtime.repo_worktree_fingerprint(target)
untracked.write_text("bbbb")
status_after = subprocess.check_output(
["git", "-C", str(target), "status", "--porcelain", "-u", "--no-renames"],
text=True,
)
assert status_before == status_after
updated = runtime.repo_worktree_fingerprint(target)
assert baseline is not None
assert updated is not None
assert baseline != updated
def test_repo_worktree_fingerprint_detects_untracked_tail_byte_change(tmp_path: Path):
target = _git_wired_claude(tmp_path)
untracked = target / "large.bin"
content_a = b"a" * 65536 + b"x"
content_b = b"a" * 65536 + b"y"
assert len(content_a) == 65537 == len(content_b)
untracked.write_bytes(content_a)
baseline = runtime.repo_worktree_fingerprint(target)
untracked.write_bytes(content_b)
updated = runtime.repo_worktree_fingerprint(target)
assert baseline is not None
assert updated is not None
assert baseline != updated
def test_repo_worktree_fingerprint_hashes_large_untracked_without_read_bytes(tmp_path: Path, monkeypatch):
target = _git_wired_claude(tmp_path)
large = target / "model.cache"
with large.open("wb") as handle:
handle.seek(100 * 1024 * 1024 - 1)
handle.write(b"\0")
hash_calls: list[str] = []
real_run = runtime._run_snapshot_git
def tracked_run(repo: Path, *git_args: str):
if git_args[:1] == ("hash-object",):
hash_calls.append(git_args[-1])
return real_run(repo, *git_args)
def forbid_read_bytes(self: Path, *args, **kwargs):
raise AssertionError("repo_worktree_fingerprint must not read whole file bytes in-process")
monkeypatch.setattr(runtime, "_run_snapshot_git", tracked_run)
monkeypatch.setattr(Path, "read_bytes", forbid_read_bytes)
fingerprint = runtime.repo_worktree_fingerprint(target)
assert fingerprint is not None
assert "model.cache" in hash_calls
def test_wired_target_from_payload_ignores_incidental_repo_paths(tmp_path: Path):
cwd_repo = _configured_git_repo(tmp_path / "cwdrepo")
incidental = _configured_git_repo(tmp_path / "incidental")
command = f"rg pattern {incidental}/tracked.txt"
resolved = runtime.wired_target_from_payload(
_payload(
cwd_repo,
"PreToolUse",
tool_name="Bash",
tool_input={"command": command},
)
)
assert resolved == cwd_repo.resolve()
def test_wired_target_from_payload_without_cwd_uses_named_repo_not_process_dir(tmp_path: Path):
named = _configured_git_repo(tmp_path / "named")
# Payload omits cwd; the command explicitly names a wired repo.
payload = {
"session_id": "no-cwd",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": f"rg pattern {named}/tracked.txt"},
}
resolved = runtime.wired_target_from_payload(payload)
assert resolved == named.resolve()
def test_wired_target_from_payload_without_cwd_and_no_named_repo_returns_none(tmp_path: Path):
# Payload omits cwd and the command mentions no wired repo path.
payload = {
"session_id": "no-cwd",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": "echo hello"},
}
resolved = runtime.wired_target_from_payload(payload)
assert resolved is None
def test_repo_worktree_fingerprint_returns_none_when_hash_object_fails_for_untracked(tmp_path: Path, monkeypatch):
target = _git_wired_claude(tmp_path)
(target / "new.txt").write_text("content")
real_run = runtime._run_snapshot_git
def fake_run(repo: Path, *git_args: str):
if git_args[:1] == ("hash-object",):
return None
return real_run(repo, *git_args)
monkeypatch.setattr(runtime, "_run_snapshot_git", fake_run)
assert runtime.repo_worktree_fingerprint(target) is None
def test_posttooluse_fails_closed_when_untracked_state_check_fails(tmp_path: Path, monkeypatch):
target = _git_wired_claude(tmp_path)
session_id = "hash-object-fail"
out_file = target / "new.txt"
out_file.write_text("before")
real_run = runtime._run_snapshot_git
def fake_run(repo: Path, *git_args: str):
if git_args[:1] == ("hash-object",):
return None
return real_run(repo, *git_args)
monkeypatch.setattr(runtime, "_run_snapshot_git", fake_run)
command = f"{sys.executable} -c \"from pathlib import Path; Path({str(out_file)!r}).write_text('after')\""
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
state = runtime.read_session_state(target, session_id)
assert state["write_observed"] is False
assert state["pending_bash_fingerprint"] == "unavailable"
out_file.write_text("after")
succeeded = {**pretool, "hook_event_name": "PostToolUse"}
assert runtime.handle_payload("PostToolUse", succeeded) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is True
blocked = runtime.handle_payload("Stop", _payload(target, "Stop", session_id=session_id, stop_hook_active=False))
assert blocked["decision"] == "block"
def test_posttooluse_records_bash_write_on_dirty_tracked_same_size_rewrite(tmp_path: Path):
target = _git_wired_claude(tmp_path)
session_id = "dirty-tracked-rewrite"
tracked = target / "tracked.txt"
tracked.write_text("version-a\n")
subprocess.run(["git", "add", "tracked.txt"], cwd=target, check=True, capture_output=True, text=True)
subprocess.run(["git", "commit", "-m", "init"], cwd=target, check=True, capture_output=True, text=True)
tracked.write_text("version-b\n")
command = f"{sys.executable} -c \"from pathlib import Path; Path({str(tracked)!r}).write_text('version-c\\\\n')\""
pretool = _payload(
target,
"PreToolUse",
session_id=session_id,
tool_name="Bash",
tool_input={"command": command},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is False
tracked.write_text("version-c\n")
succeeded = {**pretool, "hook_event_name": "PostToolUse"}
assert runtime.handle_payload("PostToolUse", succeeded) is None
assert runtime.read_session_state(target, session_id)["write_observed"] is True
def test_posttooluse_records_only_successful_writes(tmp_path: Path):
target = _wired_claude(tmp_path)
pretool = _payload(
target,
"PreToolUse",
session_id="write",
tool_name="Write",
tool_input={"file_path": str(target / "file.py")},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, "write")["write_observed"] is False
assert runtime.handle_payload("Stop", _payload(target, "Stop", session_id="write")) is None
posttool = {**pretool, "hook_event_name": "PostToolUse"}
assert runtime.handle_payload("PostToolUse", posttool) is None
assert runtime.read_session_state(target, "write")["write_observed"] is True
def test_cli_accepts_managed_posttooluse_event(monkeypatch):
calls: list[tuple[str, str]] = []
def fake_hook_run(*, event: str, package: str) -> int:
calls.append((event, package))
return 0
monkeypatch.setattr(runtime, "hook_run", fake_hook_run)
assert cli.main(["work", "hook-run", "--event", "PostToolUse", "--package", "brigade-claude-work-loop@1.0.0"]) == 0
assert calls == [("PostToolUse", "brigade-claude-work-loop@1.0.0")]
def test_posttooluse_records_only_successful_confident_bash_writes(tmp_path: Path):
target = _wired_claude(tmp_path)
command = "sed -i 's/old/new/' file.py"
pretool = _payload(
target,
"PreToolUse",
session_id="bash-write",
tool_name="Bash",
tool_input={"command": command},
)
assert runtime.handle_payload("PreToolUse", pretool) is None
assert runtime.read_session_state(target, "bash-write")["write_observed"] is False
failed = {**pretool, "hook_event_name": "PostToolUseFailure"}
assert runtime.handle_payload("PostToolUseFailure", failed) is None
assert runtime.read_session_state(target, "bash-write")["write_observed"] is False
succeeded = {**pretool, "hook_event_name": "PostToolUse"}