-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_claude_code_hook.py
More file actions
2631 lines (2241 loc) · 94.6 KB
/
Copy pathtest_claude_code_hook.py
File metadata and controls
2631 lines (2241 loc) · 94.6 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
"""Tests for the Ardur Claude Code hook adapter."""
from __future__ import annotations
import ast
import base64
import hashlib
import json
from pathlib import Path
from typing import Any
import pytest
from cryptography.hazmat.primitives.asymmetric import ec
from vibap.claude_code_hook import (
ChainState,
append_receipt,
load_active_passport,
MissionLoadError,
previous_receipt_hash,
_summarize_child_receipts_unverified,
)
from vibap.passport import (
MissionPassport,
generate_keypair,
issue_passport,
)
_FAKE_DAEMON_ACCEPT_TIMEOUT_S = 10.0
_TEST_DAEMON_TIMEOUT_MS = "1000"
def _issue_test_passport(tmp_path: Path) -> tuple[str, ec.EllipticCurvePrivateKey]:
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="test mission",
allowed_tools=["Read"],
forbidden_tools=["Bash"],
resource_scope=["/tmp/*"],
max_tool_calls=10,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
return token, private_key
def _deny_reason(output: dict) -> str:
hook_output = output["hookSpecificOutput"]
assert hook_output["hookEventName"] == "PreToolUse"
assert hook_output["permissionDecision"] == "deny"
return hook_output["permissionDecisionReason"]
def _issue_wildcard_test_passport(
tmp_path: Path,
*,
extra_claims: dict[str, Any] | None = None,
) -> str:
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="test Claude Code trace path containment",
allowed_tools=["*"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=20,
max_duration_s=600,
)
return issue_passport(mission, private_key, ttl_s=3600, extra_claims=extra_claims)
def _exercise_receipt_lock_and_subagent_sinks(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
token: str,
) -> Path:
chain_dir = tmp_path / "chain"
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(chain_dir))
from vibap.claude_code_hook import handle_post_tool_use, handle_pre_tool_use, handle_subagent_start
pre_output = handle_pre_tool_use(
{
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Read",
"tool_use_id": "toolu_read_1",
"tool_input": {"file_path": str(tmp_path / "README.md")},
},
keys_dir=tmp_path,
)
assert pre_output["continue"] is True
post_output = handle_post_tool_use(
{
"session_id": "sess-1",
"hook_event_name": "PostToolUse",
"tool_name": "Read",
"tool_use_id": "toolu_read_1",
"tool_input": {"file_path": str(tmp_path / "README.md")},
"tool_response": {"content": "hello"},
},
keys_dir=tmp_path,
)
assert post_output == {"continue": True}
start_output = handle_subagent_start(
{
"session_id": "sess-1",
"hook_event_name": "SubagentStart",
"agent_id": "agent-child-1",
"agent_type": "Explore",
},
keys_dir=tmp_path,
)
assert start_output["hookSpecificOutput"]["hookEventName"] == "SubagentStart"
return chain_dir
def _assert_chain_artifacts_are_single_nested_trace(chain_dir: Path) -> Path:
receipts = list(chain_dir.rglob("receipts.jsonl"))
locks = list(chain_dir.rglob(".lock"))
registries = list(chain_dir.rglob("subagents.jsonl"))
assert len(receipts) == 1
assert len(locks) == 1
assert len(registries) == 1
trace_dir = receipts[0].parent
assert trace_dir.resolve().parent == chain_dir.resolve()
assert locks[0].parent == trace_dir
assert registries[0].parent == trace_dir
assert (chain_dir / "receipts.jsonl").exists() is False
assert (chain_dir / ".lock").exists() is False
assert (chain_dir / "subagents.jsonl").exists() is False
assert len(receipts[0].read_text(encoding="utf-8").splitlines()) == 3
assert len(registries[0].read_text(encoding="utf-8").splitlines()) == 1
return trace_dir
def test_loads_passport_from_env_var_path(tmp_path, monkeypatch):
token, _ = _issue_test_passport(tmp_path)
passport_file = tmp_path / "active.jwt"
passport_file.write_text(token, encoding="utf-8")
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", str(passport_file))
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
claims = load_active_passport(keys_dir=tmp_path)
assert claims["sub"] == "alice"
assert claims["mission"] == "test mission"
def test_loads_passport_from_literal_jwt_in_env_var(tmp_path, monkeypatch):
token, _ = _issue_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
claims = load_active_passport(keys_dir=tmp_path)
assert claims["sub"] == "alice"
def test_returns_error_when_no_passport_anywhere(tmp_path, monkeypatch):
# Pre-generate the keypair so the missing-keys path is not the failure
# mode being tested; the failure being tested here is "no passport".
generate_keypair(keys_dir=tmp_path)
monkeypatch.delenv("ARDUR_MISSION_PASSPORT", raising=False)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
with pytest.raises(MissionLoadError) as exc_info:
load_active_passport(keys_dir=tmp_path)
assert "no active mission passport" in str(exc_info.value).lower()
def test_returns_error_on_signature_mismatch(tmp_path, monkeypatch):
token, _ = _issue_test_passport(tmp_path)
# Pre-generate a DIFFERENT keypair under other_keys so load_public_key
# returns a non-matching public key. (VIBAP_HOME is not load-bearing
# here because the passport is delivered as a literal JWT via the env
# var; only keys_dir affects which public key verify_passport sees.)
other_keys = tmp_path / "other"
other_keys.mkdir()
generate_keypair(keys_dir=other_keys)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(other_keys))
with pytest.raises(MissionLoadError) as exc_info:
load_active_passport(keys_dir=other_keys)
assert "signature" in str(exc_info.value).lower() or "verify" in str(exc_info.value).lower()
def test_empty_vibap_home_falls_back_to_default_home(tmp_path, monkeypatch):
# VIBAP_HOME="" must NOT be interpreted as "use cwd"; the loader should
# treat it the same as unset and fall through to DEFAULT_HOME.
generate_keypair(keys_dir=tmp_path)
monkeypatch.delenv("ARDUR_MISSION_PASSPORT", raising=False)
monkeypatch.setenv("VIBAP_HOME", "") # explicit empty string
with pytest.raises(MissionLoadError) as exc_info:
load_active_passport(keys_dir=tmp_path)
# The error here is "no passport" (the loader didn't crash on empty
# string and didn't find a passport in CWD/.vibap).
assert "no active mission passport" in str(exc_info.value).lower()
def test_jwt_heuristic_does_not_misclassify_path_starting_with_ey(tmp_path, monkeypatch):
# A path-like value starting with "ey" but not "eyJ" must be treated
# as a path, not a literal JWT. Without keys we expect either a
# missing-keys MissionLoadError or a no-passport MissionLoadError —
# never an "all candidate passports failed verification" error
# (which would mean the loader tried to decode the path as a JWT).
generate_keypair(keys_dir=tmp_path)
fake_path = tmp_path / "eya_relative_file.json"
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", str(fake_path))
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
with pytest.raises(MissionLoadError) as exc_info:
load_active_passport(keys_dir=tmp_path)
msg = str(exc_info.value).lower()
assert "no active mission passport" in msg
assert "failed verification" not in msg
def test_empty_chain_returns_none(tmp_path):
state = ChainState(chain_dir=tmp_path, trace_id="trace-1")
assert previous_receipt_hash(state) is None
def test_single_entry_returns_its_hash(tmp_path):
state = ChainState(chain_dir=tmp_path, trace_id="trace-1")
fake_jwt = "fake.signed.jwt"
append_receipt(state, fake_jwt)
expected = "sha-256:" + hashlib.sha256(fake_jwt.encode("utf-8")).hexdigest()
assert previous_receipt_hash(state) == expected
def test_multi_entry_returns_last_hash(tmp_path):
state = ChainState(chain_dir=tmp_path, trace_id="trace-1")
append_receipt(state, "first.jwt.x")
append_receipt(state, "second.jwt.y")
append_receipt(state, "third.jwt.z")
expected = "sha-256:" + hashlib.sha256("third.jwt.z".encode("utf-8")).hexdigest()
assert previous_receipt_hash(state) == expected
def test_chain_per_trace_does_not_collide(tmp_path):
state_a = ChainState(chain_dir=tmp_path, trace_id="trace-a")
state_b = ChainState(chain_dir=tmp_path, trace_id="trace-b")
append_receipt(state_a, "a-only.jwt")
append_receipt(state_b, "b-only.jwt")
assert previous_receipt_hash(state_a) == "sha-256:" + hashlib.sha256("a-only.jwt".encode()).hexdigest()
assert previous_receipt_hash(state_b) == "sha-256:" + hashlib.sha256("b-only.jwt".encode()).hexdigest()
def test_child_receipt_summary_streams_chain_file(tmp_path, monkeypatch):
state = ChainState(chain_dir=tmp_path, trace_id="trace-stream")
state.trace_dir.mkdir(parents=True)
def unsigned_jwt(claims: dict[str, Any]) -> str:
def encode(segment: dict[str, Any]) -> str:
encoded = base64.urlsafe_b64encode(
json.dumps(segment, sort_keys=True, separators=(",", ":")).encode("utf-8")
)
return encoded.rstrip(b"=").decode("ascii")
return f"{encode({'alg': 'none', 'typ': 'JWT'})}.{encode(claims)}."
matching = unsigned_jwt(
{
"tool": "Read",
"verdict": "compliant",
"measurements": {
"claude_code": {
"claude_agent_id": "agent-child-1",
"transcript_path": "/tmp/child-transcript.jsonl",
}
},
}
)
ignored_lifecycle = unsigned_jwt(
{
"tool": "SubagentStop",
"measurements": {"claude_code": {"claude_agent_id": "agent-child-1"}},
}
)
state.file.write_text(f"{matching}\n{ignored_lifecycle}\n", encoding="utf-8")
original_read_text = Path.read_text
def fail_read_text(self, *args, **kwargs):
if self == state.file:
raise AssertionError("child receipt summary must stream the chain file")
return original_read_text(self, *args, **kwargs)
monkeypatch.setattr(Path, "read_text", fail_read_text)
summary = _summarize_child_receipts_unverified(
state=state,
agent_id="agent-child-1",
agent_transcript_path="/tmp/child-transcript.jsonl",
)
assert summary == {"receipt_count": 1, "tools": {"Read": 1}, "violations": 0}
@pytest.mark.parametrize(
"bad_trace_id",
[".", "..", "bad/trace", r"bad\trace", "/tmp/absolute-out", "bad trace"],
)
def test_unsafe_env_trace_ids_do_not_escape_or_collapse_chain_paths_across_hook_sinks(
tmp_path,
monkeypatch,
bad_trace_id: str,
):
token = _issue_wildcard_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_TRACE_ID", bad_trace_id)
chain_dir = _exercise_receipt_lock_and_subagent_sinks(tmp_path, monkeypatch, token)
assert not (tmp_path / "receipts.jsonl").exists()
assert not (tmp_path / ".lock").exists()
assert not (tmp_path / "subagents.jsonl").exists()
trace_dir = _assert_chain_artifacts_are_single_nested_trace(chain_dir)
assert trace_dir.name != bad_trace_id
assert "/" not in trace_dir.name
assert "\\" not in trace_dir.name
def test_unsafe_passport_jti_fallback_material_is_contained_and_single_segment(tmp_path, monkeypatch):
cases = {
"dotdot": "../passport-out",
"slash": "bad/trace",
"backslash": r"bad\trace",
"absolute": str(tmp_path / "absolute-out"),
"space": "bad trace",
}
for name, bad_jti in cases.items():
case_dir = tmp_path / name
case_dir.mkdir()
token = _issue_wildcard_test_passport(case_dir, extra_claims={"jti": bad_jti})
monkeypatch.delenv("ARDUR_TRACE_ID", raising=False)
chain_dir = _exercise_receipt_lock_and_subagent_sinks(case_dir, monkeypatch, token)
assert not (case_dir / "receipts.jsonl").exists()
assert not (case_dir / ".lock").exists()
assert not (case_dir / "subagents.jsonl").exists()
trace_dir = _assert_chain_artifacts_are_single_nested_trace(chain_dir)
assert trace_dir.name.startswith("trace-")
assert "/" not in trace_dir.name
assert "\\" not in trace_dir.name
assert trace_dir.name not in {".", "..", "bad", "trace", "passport-out", "absolute-out"}
def test_safe_dot_containing_env_trace_id_is_preserved_as_single_segment(tmp_path, monkeypatch):
token = _issue_wildcard_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_TRACE_ID", "trace.v1-alpha_2")
chain_dir = _exercise_receipt_lock_and_subagent_sinks(tmp_path, monkeypatch, token)
trace_dir = _assert_chain_artifacts_are_single_nested_trace(chain_dir)
assert trace_dir.name == "trace.v1-alpha_2"
def test_resolve_chain_state_rejects_path_material_before_artifact_creation(tmp_path, monkeypatch):
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
from vibap.claude_code_hook import resolve_chain_state
unsafe_trace_ids = [
".",
"..",
"bad/trace",
r"bad\trace",
str(tmp_path / "absolute-out"),
"bad trace",
]
for trace_id in unsafe_trace_ids:
with pytest.raises(ValueError):
resolve_chain_state(trace_id=trace_id)
assert not (tmp_path / "receipts.jsonl").exists()
assert not (tmp_path / ".lock").exists()
assert not (tmp_path / "subagents.jsonl").exists()
assert not (tmp_path / "chain").exists()
def test_allow_path_returns_continue_true_and_chains_receipt(tmp_path, monkeypatch):
token, _ = _issue_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
from vibap.claude_code_hook import handle_pre_tool_use
hook_input = {
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Read",
"tool_input": {"file_path": "/tmp/x.txt"},
}
output = handle_pre_tool_use(hook_input, keys_dir=tmp_path)
assert output["continue"] is True
assert "receipt" in output["systemMessage"].lower()
# Receipt was appended to the chain.
receipts = list((tmp_path / "chain").rglob("receipts.jsonl"))
assert len(receipts) == 1
lines = receipts[0].read_text(encoding="utf-8").splitlines()
assert len(lines) == 1
# First receipt in a fresh chain must have parent_receipt_hash=None
# (signals "root receipt"). Inspect the JWT claims without verifying
# the signature — the test isn't asserting receipt validity here, just
# the chain semantics.
import jwt as pyjwt
claims = pyjwt.decode(lines[0].strip(), options={"verify_signature": False})
assert claims.get("parent_receipt_hash") is None
# C1: content-class telemetry fields are backfilled into the signed
# receipt payload. content_class and content_provenance survive from the
# mapper; instruction_bearing is the bool from the mapper.
assert claims.get("content_class") == "user_input"
assert claims.get("content_provenance") == {"source": "claude_code_tool_input"}
assert claims.get("instruction_bearing") is False
# C2: step_id carries the ":pre" phase suffix to disambiguate from
# the Post receipt for the same call.
assert claims.get("step_id", "").endswith(":pre")
# C3: the signed receipt preserves the actual backend decision reason,
# rather than falling back to a synthetic hook-level summary.
assert claims.get("policy_decisions") == [
{"backend": "native", "decision": "Allow", "reason": "within scope"}
]
def test_wildcard_allowed_tools_permits_agent_dispatch_and_reports_it(tmp_path, monkeypatch):
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="observe subagent launch",
allowed_tools=["*"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=10,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
from vibap.claude_code_hook import handle_pre_tool_use
from vibap.claude_code_report import build_claude_code_report
output = handle_pre_tool_use(
{
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Agent",
"tool_input": {
"agent_type": "general-purpose",
"description": "Read README title",
"prompt": "Use Read to inspect README.md",
},
},
keys_dir=tmp_path,
)
assert output["continue"] is True
report = build_claude_code_report(
home=tmp_path,
chain_dir=tmp_path / "chain",
keys_dir=tmp_path,
verify_expiry=False,
)
assert report["totals"]["dispatch_count"] == 1
assert report["next_steps"] == []
assert report["totals"]["dispatch_launch_count"] == 1
assert report["totals"]["dispatch_observation_count"] == 0
assert report["totals"]["dispatch_receipt_count"] == 1
assert report["totals"]["tools"] == {"Agent": 1}
assert report["totals"]["side_effect_classes"] == {"subagent_launch": 1}
def test_empty_claude_code_report_includes_local_next_steps(tmp_path):
from vibap.claude_code_report import build_claude_code_report
report = build_claude_code_report(
home=tmp_path,
chain_dir=tmp_path / "missing-chain",
keys_dir=tmp_path / "keys",
verify_expiry=False,
)
assert report["chain_count"] == 0
assert report["receipt_count"] == 0
assert report["home"] == "<CLAUDE_CODE_HOME>"
assert report["chain_dir"] == "<ARDUR_CLAUDE_CODE_CHAIN>"
assert report["keys_dir"] == "<ARDUR_KEYS>"
report_text = json.dumps(report, sort_keys=True)
assert str(tmp_path) not in report_text
assert "<ABSOLUTE_PATH:" not in report_text
steps = report["next_steps"]
assert [step["action"] for step in steps] == [
"configure_claude_code_protection",
"run_claude_code_with_plugin",
"rerun_receipt_report",
]
rendered_steps = repr(steps)
assert "ardur protect claude-code" in rendered_steps
assert "claude --plugin-dir" in rendered_steps
assert "ardur claude-code-report" in rendered_steps
assert "<your-project>" in rendered_steps
assert "<ardur-home>" in rendered_steps
assert "<claude-code-plugin>" in rendered_steps
assert str(tmp_path) not in rendered_steps
def test_empty_claude_code_report_human_output_prints_next_steps(tmp_path, capsys):
import argparse
from vibap.cli import cmd_claude_code_report
exit_code = cmd_claude_code_report(
argparse.Namespace(
home=tmp_path,
chain_dir=tmp_path / "missing-chain",
keys_dir=tmp_path / "keys",
verify_expiry=False,
json=False,
)
)
assert exit_code == 0
output = capsys.readouterr().out
assert "Ardur Claude Code receipt report: 0 receipts across 0 chains" in output
assert "Next steps:" in output
assert "ardur protect claude-code" in output
assert "claude --plugin-dir" in output
assert "ardur claude-code-report" in output
next_steps_output = output.split("Next steps:", 1)[1]
assert str(tmp_path) not in output
assert "<ABSOLUTE_PATH:" not in output
assert str(tmp_path) not in next_steps_output
def test_subagent_lifecycle_receipts_and_report_derived_tool_attribution(tmp_path, monkeypatch):
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="observe child lifecycle",
allowed_tools=["*"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=20,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
child_transcript = tmp_path / "subagents" / "agent-child-1.jsonl"
child_transcript.parent.mkdir()
child_transcript.write_text('{"tool_use_id":"toolu_read_1"}\n', encoding="utf-8")
parent_transcript = tmp_path / "parent.jsonl"
parent_transcript.write_text("{}\n", encoding="utf-8")
from vibap.claude_code_hook import (
handle_pre_tool_use,
handle_post_tool_use,
handle_subagent_start,
handle_subagent_stop,
)
from vibap.claude_code_report import build_claude_code_report
start_output = handle_subagent_start(
{
"session_id": "sess-1",
"transcript_path": str(parent_transcript),
"cwd": str(tmp_path),
"hook_event_name": "SubagentStart",
"agent_id": "agent-child-1",
"agent_type": "Explore",
},
keys_dir=tmp_path,
)
assert start_output["hookSpecificOutput"]["hookEventName"] == "SubagentStart"
assert "child:" in start_output["hookSpecificOutput"]["additionalContext"]
handle_pre_tool_use(
{
"session_id": "sess-1",
"transcript_path": str(child_transcript),
"cwd": str(tmp_path),
"hook_event_name": "PreToolUse",
"tool_name": "Read",
"tool_use_id": "toolu_read_1",
"tool_input": {"file_path": str(tmp_path / "README.md")},
},
keys_dir=tmp_path,
)
handle_post_tool_use(
{
"session_id": "sess-1",
"transcript_path": str(child_transcript),
"cwd": str(tmp_path),
"hook_event_name": "PostToolUse",
"tool_name": "Read",
"tool_use_id": "toolu_read_1",
"tool_input": {"file_path": str(tmp_path / "README.md")},
"tool_response": {"content": "hello"},
},
keys_dir=tmp_path,
)
stop_output = handle_subagent_stop(
{
"session_id": "sess-1",
"transcript_path": str(parent_transcript),
"cwd": str(tmp_path),
"hook_event_name": "SubagentStop",
"agent_id": "agent-child-1",
"agent_type": "Explore",
"agent_transcript_path": str(child_transcript),
"last_assistant_message": "done",
},
keys_dir=tmp_path,
)
assert stop_output == {"continue": True}
receipts = list((tmp_path / "chain").rglob("receipts.jsonl"))
assert len(receipts) == 1
lines = [line.strip() for line in receipts[0].read_text(encoding="utf-8").splitlines() if line.strip()]
assert len(lines) == 4
import jwt as pyjwt
claims = [pyjwt.decode(line, options={"verify_signature": False}) for line in lines]
assert [claim["tool"] for claim in claims] == ["SubagentStart", "Read", "Read", "SubagentStop"]
start_meta = claims[0]["measurements"]["claude_code"]
assert start_meta["claude_agent_id"] == "agent-child-1"
assert start_meta["actor_kind"] == "subagent"
assert start_meta["attribution"]["mode"] == "exact"
read_meta = claims[1]["measurements"]["claude_code"]
assert read_meta["tool_use_id"] == "toolu_read_1"
assert read_meta["actor_kind"] == "unattributed"
stop_meta = claims[-1]["measurements"]["claude_code"]
assert stop_meta["final_response_hash"]["alg"] == "sha-256"
assert stop_meta["child_receipt_summary"]["receipt_count"] == 2
registry = list((tmp_path / "chain").rglob("subagents.jsonl"))
assert len(registry) == 1
assert len(registry[0].read_text(encoding="utf-8").splitlines()) == 2
report = build_claude_code_report(
home=tmp_path,
chain_dir=tmp_path / "chain",
keys_dir=tmp_path,
verify_expiry=False,
)
assert report["chain_verification"]["ok"] is True
assert report["totals"]["subagents_started"] == 1
assert report["totals"]["subagents_stopped"] == 1
assert report["coverage"]["per_child_attribution"] == "derived"
assert report["totals"]["unattributed_tool_receipt_count"] == 0
subagent = report["chains"][0]["subagents"][0]
assert subagent["claude_agent_id"] == "agent-child-1"
assert subagent["tool_receipt_count"] == 2
assert subagent["tools"] == {"Read": 2}
assert subagent["attribution_modes"] == {"derived": 2}
def test_report_keeps_unmatched_child_tools_trace_only(tmp_path, monkeypatch):
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="do not guess child attribution",
allowed_tools=["*"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=20,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
child_transcript = tmp_path / "subagents" / "agent-child-2.jsonl"
child_transcript.parent.mkdir()
child_transcript.write_text('{"tool_use_id":"different_tool"}\n', encoding="utf-8")
parent_transcript = tmp_path / "parent.jsonl"
parent_transcript.write_text("{}\n", encoding="utf-8")
from vibap.claude_code_hook import handle_pre_tool_use, handle_subagent_start, handle_subagent_stop
from vibap.claude_code_report import build_claude_code_report
handle_subagent_start(
{
"session_id": "sess-1",
"transcript_path": str(parent_transcript),
"cwd": str(tmp_path),
"hook_event_name": "SubagentStart",
"agent_id": "agent-child-2",
"agent_type": "Explore",
},
keys_dir=tmp_path,
)
handle_pre_tool_use(
{
"session_id": "sess-1",
"transcript_path": str(parent_transcript),
"cwd": str(tmp_path),
"hook_event_name": "PreToolUse",
"tool_name": "Read",
"tool_use_id": "toolu_unmatched",
"tool_input": {"file_path": str(tmp_path / "README.md")},
},
keys_dir=tmp_path,
)
handle_subagent_stop(
{
"session_id": "sess-1",
"transcript_path": str(parent_transcript),
"cwd": str(tmp_path),
"hook_event_name": "SubagentStop",
"agent_id": "agent-child-2",
"agent_type": "Explore",
"agent_transcript_path": str(child_transcript),
},
keys_dir=tmp_path,
)
report = build_claude_code_report(
home=tmp_path,
chain_dir=tmp_path / "chain",
keys_dir=tmp_path,
verify_expiry=False,
)
assert report["coverage"]["per_child_attribution"] == "trace_only"
assert report["totals"]["unattributed_tool_receipt_count"] == 1
assert report["chains"][0]["unattributed_tool_receipts"][0]["tool_use_id"] == "toolu_unmatched"
def test_long_scoped_bash_command_is_not_denied_by_truncated_target(tmp_path, monkeypatch):
private_key, _public_key = generate_keypair(keys_dir=tmp_path)
scope = tmp_path / "scope"
nested = scope / "a" / "b" / "c" / "d"
nested.mkdir(parents=True)
mission = MissionPassport(
agent_id="alice",
mission="allow long scoped bash",
allowed_tools=["Bash"],
forbidden_tools=[],
resource_scope=[str(scope), f"{scope}/*"],
max_tool_calls=10,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
from vibap.claude_code_hook import handle_pre_tool_use
command = f"ls -la {nested} {nested} {nested} {nested}"
assert len(command) > 128
output = handle_pre_tool_use(
{
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": command},
},
keys_dir=tmp_path,
)
assert output["continue"] is True
def test_parallel_pre_tool_use_processes_serialize_receipt_chain(tmp_path):
import os
import subprocess
import sys
private_key, public_key = generate_keypair(keys_dir=tmp_path)
mission = MissionPassport(
agent_id="alice",
mission="parallel subagent launch",
allowed_tools=["Agent"],
forbidden_tools=[],
resource_scope=[],
max_tool_calls=20,
max_duration_s=600,
)
token = issue_passport(mission, private_key, ttl_s=3600)
repo_root = Path(__file__).resolve().parents[2]
env = {
**os.environ,
"ARDUR_MISSION_PASSPORT": token,
"VIBAP_HOME": str(tmp_path),
"ARDUR_CC_HOOK_DIR": str(tmp_path / "chain"),
"PYTHONPATH": str(repo_root / "python"),
}
processes = []
for index in range(5):
hook_input = json.dumps(
{
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Agent",
"tool_input": {
"agent_type": "general-purpose",
"description": f"parallel agent {index}",
"prompt": "Use a tool and write a short report.",
},
}
)
processes.append(
subprocess.Popen(
[
sys.executable,
"-m",
"vibap.claude_code_hook",
"pre",
"--keys-dir",
str(tmp_path),
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=env,
)
)
processes[-1].stdin.write(hook_input)
processes[-1].stdin.close()
for process in processes:
stdout = process.stdout.read()
stderr = process.stderr.read()
assert process.wait(timeout=10) == 0, stderr
assert json.loads(stdout)["continue"] is True
receipts = list((tmp_path / "chain").rglob("receipts.jsonl"))
assert len(receipts) == 1
lines = [line.strip() for line in receipts[0].read_text(encoding="utf-8").splitlines() if line.strip()]
assert len(lines) == 5
from vibap.receipt import verify_chain
verify_chain(lines, public_key, verify_expiry=False)
def test_deny_path_returns_continue_false_with_stop_reason(tmp_path, monkeypatch):
# Reuse the canonical test helper; it already sets forbidden_tools=["Bash"].
token, _ = _issue_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
from vibap.claude_code_hook import handle_pre_tool_use
output = handle_pre_tool_use(
{
"session_id": "sess-1",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {"command": "rm -rf /"},
},
keys_dir=tmp_path,
)
assert "ardur:" in _deny_reason(output).lower()
receipts = list((tmp_path / "chain").rglob("receipts.jsonl"))
assert len(receipts) == 1
lines = receipts[0].read_text(encoding="utf-8").splitlines()
assert len(lines) == 1
# Audit trail: the appended receipt MUST carry a non-compliant verdict.
# Inspect without verifying signature — we only care about chain semantics.
import jwt as pyjwt
claims = pyjwt.decode(lines[0].strip(), options={"verify_signature": False})
assert claims.get("verdict") == "violation"
assert claims.get("policy_decisions") == [
{
"backend": "native",
"decision": "Deny",
"reason": "tool 'Bash' is in forbidden_tools",
}
]
def test_post_tool_use_chains_to_pre_and_records_result_hash(tmp_path, monkeypatch):
token, _ = _issue_test_passport(tmp_path)
monkeypatch.setenv("ARDUR_MISSION_PASSPORT", token)
monkeypatch.setenv("VIBAP_HOME", str(tmp_path))
monkeypatch.setenv("ARDUR_CC_HOOK_DIR", str(tmp_path / "chain"))
# First, run PreToolUse to seed the chain.
from vibap.claude_code_hook import handle_pre_tool_use, handle_post_tool_use
handle_pre_tool_use(
{
"tool_name": "Read",
"tool_input": {"file_path": "/tmp/x.txt"},
},
keys_dir=tmp_path,
)
# Then PostToolUse for the same call.
output = handle_post_tool_use(
{
"tool_name": "Read",
"tool_input": {"file_path": "/tmp/x.txt"},
"tool_response": {"content": "file body", "exit_code": 0},
},
keys_dir=tmp_path,
)
assert output == {"continue": True}
receipts = list((tmp_path / "chain").rglob("receipts.jsonl"))
assert len(receipts) == 1
lines = receipts[0].read_text(encoding="utf-8").splitlines()
assert len(lines) == 2 # pre + post
# Chain integrity: the post receipt must reference the pre receipt's
# JWT hash as its parent. This is the core invariant the receipt chain
# is built around — without it, an auditor cannot verify ordering.
# parent_receipt_hash is stored as bare 64-char hex (no "sha-256:" prefix)
# so that verify_chain can compare it directly against its own computed hash.
import hashlib as _hashlib
import jwt as pyjwt
pre_jwt = lines[0].strip()
post_jwt = lines[1].strip()
expected_parent = _hashlib.sha256(pre_jwt.encode("utf-8")).hexdigest()
pre_claims = pyjwt.decode(pre_jwt, options={"verify_signature": False})
post_claims = pyjwt.decode(post_jwt, options={"verify_signature": False})
assert post_claims.get("parent_receipt_hash") == expected_parent
assert post_claims.get("verdict") == "compliant"
# Result hash present and well-formed.
rh = post_claims.get("result_hash")
assert isinstance(rh, dict)
assert rh.get("alg") == "sha-256"
assert isinstance(rh.get("value"), str) and len(rh["value"]) == 64
# C2: Pre and Post receipts MUST have distinct step_ids — the deterministic
# base derivation hashes the same inputs, so without the phase suffix
# they would collide on calls that fall in the same wall-clock second.
assert pre_claims.get("step_id", "").endswith(":pre")
assert post_claims.get("step_id", "").endswith(":post")
assert pre_claims["step_id"] != post_claims["step_id"]
# C1: content-class telemetry fields appear on the post receipt too.
assert post_claims.get("content_class") == "user_input"
assert post_claims.get("content_provenance") == {"source": "claude_code_tool_input"}
assert post_claims.get("instruction_bearing") is False
def test_main_pre_reads_stdin_writes_stdout(tmp_path, monkeypatch):
import os
import subprocess
import sys
token, _ = _issue_test_passport(tmp_path)
env = {**os.environ}
env["ARDUR_MISSION_PASSPORT"] = token
env["VIBAP_HOME"] = str(tmp_path)
env["ARDUR_CC_HOOK_DIR"] = str(tmp_path / "chain")
hook_input = json.dumps({
"tool_name": "Read",
"tool_input": {"file_path": "/tmp/x.txt"},
})
repo_root = Path(__file__).resolve().parents[2]
result = subprocess.run(
[sys.executable, "-m", "vibap.claude_code_hook", "pre",
"--keys-dir", str(tmp_path)],
input=hook_input,
capture_output=True,
text=True,
env={**env, "PYTHONPATH": str(repo_root / "python")},
)
assert result.returncode == 0, f"stderr: {result.stderr}"
output = json.loads(result.stdout)
assert output["continue"] is True
@pytest.mark.parametrize(
("stdin_payload", "condition", "expected_detail"),
[
(
"{not-json",
"claude_code_hook_input_malformed",
"parsing failed at line 1, column 2",
),
(
"[1, 2, 3]",
"claude_code_hook_input_not_object",