-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_work_cmd_verification.py
More file actions
2703 lines (2238 loc) · 104 KB
/
Copy pathtest_work_cmd_verification.py
File metadata and controls
2703 lines (2238 loc) · 104 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
import hashlib
import json
import os
import shlex
import sqlite3
import subprocess
import sys
from pathlib import Path
import pytest
from brigade import cli
from brigade import graphtrail_delta
from brigade import localio
from brigade import receipts_cmd
from brigade import work_cmd
from tests.work_cmd_test_helpers import (
_write_json,
_init_git_repo,
)
def _init_git_repo_with_head(path):
_init_git_repo(path)
(path / ".gitignore").write_text(".brigade/\n")
subprocess.run(["git", "add", ".gitignore"], cwd=path, check=True, stdout=subprocess.DEVNULL)
subprocess.run(
["git", "-c", "user.name=Test User", "-c", "user.email=test@example.invalid", "commit", "-m", "init"],
cwd=path,
check=True,
stdout=subprocess.DEVNULL,
)
def test_verify_run_marks_parser_rejected_command_as_rejected_not_failed(tmp_path, capsys):
# A command Brigade's own parser refuses (shell metacharacters here) never runs;
# it is invalid input, not a verified regression, so the receipt status must be
# 'rejected' (neutral for outcome capture), never 'failed' (-1).
_init_git_repo(tmp_path)
rc = work_cmd.verify_run(target=tmp_path, commands=["echo hi && echo bye"], json_output=True)
payload = json.loads(capsys.readouterr().out)
assert rc != 0
assert payload["status"] == "rejected"
assert payload["commands"][0]["status"] == "rejected"
from brigade import outcome_cmd
assert outcome_cmd.capture(target=tmp_path, artifact_id="brigade-work", json_output=True) == 0
record = json.loads(capsys.readouterr().out)["record"]
assert record["signal_value"] == 0
def test_verify_run_capture_records_outcome_in_one_step(tmp_path, capsys):
_init_git_repo(tmp_path)
from brigade import outcome_cmd
rc = work_cmd.verify_run(
target=tmp_path, commands=["python3 -c \"print('ok')\""], capture="skill-x", capture_kind="skill"
)
assert rc == 0
captured = capsys.readouterr()
assert "miseledger indexing:" in captured.out
records = outcome_cmd.load_records(tmp_path)
assert len(records) == 1
assert records[0].artifact_id == "skill-x" and records[0].signal_value == 1
def _write_fake_miseledger_for_verify(path, marker, *, exit_code=0):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
f"""#!{sys.executable}
import json
import pathlib
import sys
assert sys.argv[1:3] == ["import", "adapter"]
export_path = pathlib.Path(sys.argv[3])
assert sys.argv[4:] == ["--source", "brigade", "--json"]
marker = pathlib.Path({str(marker)!r})
marker.write_text(export_path.read_text())
print(json.dumps({{"inserted_items": 1, "already_known": 0}}))
sys.exit({exit_code})
"""
)
path.chmod(0o755)
def test_verify_run_capture_auto_indexes_miseledger_receipts(tmp_path, monkeypatch, capsys):
_init_git_repo(tmp_path)
marker = tmp_path / "imported.jsonl"
_write_fake_miseledger_for_verify(tmp_path / "bin" / "miseledger", marker)
monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")
rc = work_cmd.verify_run(
target=tmp_path,
commands=["python3 -c \"print('ok')\""],
capture="skill-x",
capture_kind="skill",
)
captured = capsys.readouterr()
assert rc == 0
assert "miseledger indexing: indexed" in captured.out
assert marker.is_file()
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
assert cursor_path.is_file()
def test_verify_run_capture_json_includes_miseledger_indexing_status(tmp_path, monkeypatch, capsys):
_init_git_repo(tmp_path)
marker = tmp_path / "imported.jsonl"
_write_fake_miseledger_for_verify(tmp_path / "bin" / "miseledger", marker)
monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")
rc = work_cmd.verify_run(
target=tmp_path,
commands=["python3 -c \"print('ok')\""],
capture="skill-x",
json_output=True,
)
captured = capsys.readouterr()
assert rc == 0
payload = json.loads(captured.out)
indexing = payload["miseledger_indexing"]
assert indexing["schema"] == "brigade.miseledger_index_result.v1"
assert indexing["status"] == "indexed"
assert indexing["exported_count"] >= 1
assert captured.err == ""
def test_verify_run_capture_miseledger_failure_is_fail_open(tmp_path, monkeypatch, capsys):
_init_git_repo(tmp_path)
empty_path = tmp_path / "empty-path"
empty_path.mkdir()
monkeypatch.setenv("PATH", f"{empty_path}{os.pathsep}{os.environ['PATH']}")
rc = work_cmd.verify_run(
target=tmp_path,
commands=["python3 -c \"print('ok')\""],
capture="skill-x",
)
captured = capsys.readouterr()
assert rc == 0
assert "miseledger indexing: import failed" in captured.out
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
assert not cursor_path.exists()
def test_verify_run_capture_json_miseledger_failure_preserves_exit_code(tmp_path, monkeypatch, capsys):
_init_git_repo(tmp_path)
empty_path = tmp_path / "empty-path"
empty_path.mkdir()
monkeypatch.setenv("PATH", f"{empty_path}{os.pathsep}{os.environ['PATH']}")
rc = work_cmd.verify_run(
target=tmp_path,
commands=['python3 -c "raise SystemExit(3)"'],
capture="skill-x",
json_output=True,
)
captured = capsys.readouterr()
assert rc == 3
payload = json.loads(captured.out)
assert payload["miseledger_indexing"]["status"] == "failed"
assert captured.err == ""
def test_verify_run_stamps_valid_claude_session_fingerprint(tmp_path, capsys, monkeypatch):
from brigade.claude_hooks.runtime import _session_fingerprint
_init_git_repo(tmp_path)
fingerprint = _session_fingerprint("session-from-runtime")
monkeypatch.setenv("BRIGADE_CLAUDE_SESSION", fingerprint)
assert work_cmd.verify_run(target=tmp_path, commands=["python3 -c \"print('ok')\""], json_output=True) == 0
receipt = json.loads(capsys.readouterr().out)
assert receipt["harness_session"] == {"harness": "claude", "fingerprint": fingerprint}
def test_prune_verify_runs_keeps_newest(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
for name in ("20260101-000001-a", "20260101-000002-b", "20260101-000003-c"):
(root / name).mkdir()
removed = verification._prune_verify_runs(tmp_path, keep=2)
assert removed == 1
assert sorted(p.name for p in root.iterdir()) == ["20260101-000002-b", "20260101-000003-c"]
def _write_verify_run_dir(root, name, *, schema_version=2, sign=False, tamper=False):
"""Build a run dir whose receipt carries a self-consistent digests block."""
run_dir = root / name
run_dir.mkdir(parents=True)
log_path = run_dir / "command-1-stdout.log"
log_path.write_text(f"stdout for {name}\n")
receipt = {
"schema_version": schema_version,
"run_id": name,
"target": str(root),
"status": "completed",
"started_at": "2026-01-01T00:00:00+00:00",
"completed_at": "2026-01-01T00:00:01+00:00",
"path": str(run_dir),
"commands": [],
}
digests = {
"algorithm": "sha256",
"logs": {"command-1-stdout.log": localio.file_sha256(log_path)},
"receipt_sha256": localio.canonical_json_digest(receipt, exclude_keys={"digests"}),
}
if sign:
digests["signature"] = f"sig-{name}"
digests["key_id"] = "test-key"
if tamper:
digests["receipt_sha256"] = "0" * 64
receipt["digests"] = digests
(run_dir / "receipt.json").write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")
return run_dir, receipt
def _read_archive_index(archive_root):
return localio.read_jsonl_dicts(archive_root / "index.jsonl")
def test_prune_verify_runs_archives_evidence_before_delete(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
names = ["20260101-000001-a", "20260101-000002-b", "20260101-000003-c", "20260101-000004-d"]
source_bytes = {}
receipts = {}
for name in names:
_, receipt = _write_verify_run_dir(root, name, sign=True)
receipts[name] = receipt
source_bytes[name] = (root / name / "receipt.json").read_bytes()
archive_root = tmp_path / "verify-archive"
removed = verification._prune_verify_runs(tmp_path, keep=2, archive_root=archive_root)
assert removed == 2
assert sorted(p.name for p in root.iterdir()) == ["20260101-000003-c", "20260101-000004-d"]
# Evidence for the pruned runs survives in the archive, byte-identical.
for name in ("20260101-000001-a", "20260101-000002-b"):
archived = archive_root / name
assert (archived / "receipt.json").read_bytes() == source_bytes[name]
assert (archived / "command-1-stdout.log").is_file()
# The append-only index records one line per archived run, oldest first,
# carrying the receipt's integrity metadata and schema version.
entries = _read_archive_index(archive_root)
assert [entry["run_id"] for entry in entries] == ["20260101-000001-a", "20260101-000002-b"]
for entry in entries:
receipt = receipts[entry["run_id"]]
assert entry["schema"] == "brigade.verify_archive_index.v1"
assert entry["schema_version"] == 1
assert entry["already_archived"] is False
assert entry["receipt_schema_version"] == 2
assert entry["receipt_sha256"] == receipt["digests"]["receipt_sha256"]
assert entry["signature"] == receipt["digests"]["signature"]
assert entry["key_id"] == "test-key"
assert entry["receipt_file_sha256"] == hashlib.sha256(source_bytes[entry["run_id"]]).hexdigest()
assert entry["status"] == "completed"
# Archived receipts still verify against their own integrity metadata.
for name in ("20260101-000001-a", "20260101-000002-b"):
payload = json.loads((archive_root / name / "receipt.json").read_text())
assert localio.canonical_json_digest(payload, exclude_keys={"digests"}) == payload["digests"]["receipt_sha256"]
def test_prune_verify_runs_archive_failure_keeps_run_dir(tmp_path, monkeypatch):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
names = ["20260101-000001-a", "20260101-000002-b", "20260101-000003-c"]
for name in names:
_write_verify_run_dir(root, name)
def _failing_archive(run_dir, archive_root):
raise OSError("archive destination unavailable")
monkeypatch.setattr(verification, "_archive_verify_run", _failing_archive)
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=tmp_path / "verify-archive")
assert removed == 0
assert sorted(p.name for p in root.iterdir()) == names
def test_prune_verify_runs_invalid_archive_config_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
_write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
_write_verify_retention_config(tmp_path, verify_archive_dir="")
removed = verification._prune_verify_runs(tmp_path, keep=1)
assert removed == 0
assert (root / "20260101-000001-a" / "receipt.json").is_file()
@pytest.mark.parametrize("archive_location", ["equal", "ancestor", "descendant", "symlink-alias"])
def test_prune_verify_runs_rejects_archive_overlap(tmp_path, archive_location):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
_write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
if archive_location == "equal":
archive_root = root
elif archive_location == "ancestor":
archive_root = root.parent
elif archive_location == "descendant":
archive_root = root / "archive"
else:
archive_root = tmp_path / "archive-alias"
archive_root.symlink_to(root, target_is_directory=True)
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 0
assert (root / "20260101-000001-a" / "receipt.json").is_file()
def test_prune_verify_runs_tampered_receipt_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
_write_verify_run_dir(root, "20260101-000001-a", tamper=True)
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
# The tampered receipt fails the post-copy integrity re-check, so its run
# dir is kept locally and no archive copy is left behind.
assert removed == 0
assert sorted(p.name for p in root.iterdir()) == ["20260101-000001-a", "20260101-000002-b"]
assert not (archive_root / "20260101-000001-a").exists()
assert _read_archive_index(archive_root) == []
def test_prune_verify_runs_archive_conflict_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
_write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
conflicting = archive_root / "20260101-000001-a"
conflicting.mkdir(parents=True)
(conflicting / "receipt.json").write_text('{"run_id": "different-evidence"}\n')
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 0
assert (root / "20260101-000001-a").is_dir()
def test_prune_verify_runs_partial_existing_archive_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
run_dir, _ = _write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
archived = archive_root / run_dir.name
archived.mkdir(parents=True)
(archived / "receipt.json").write_bytes((run_dir / "receipt.json").read_bytes())
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 0
assert run_dir.is_dir()
assert not (archived / "command-1-stdout.log").exists()
def test_prune_verify_runs_symlink_existing_archive_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
run_dir, _ = _write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
archive_root.mkdir()
(archive_root / run_dir.name).symlink_to(run_dir, target_is_directory=True)
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 0
assert run_dir.is_dir()
assert (run_dir / "receipt.json").is_file()
def test_prune_verify_runs_rearchive_identical_evidence_is_safe(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
run_dir, receipt = _write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
import shutil as _shutil
_shutil.copytree(run_dir, archive_root / "20260101-000001-a")
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 1
assert not (root / "20260101-000001-a").exists()
entries = _read_archive_index(archive_root)
assert len(entries) == 1
assert entries[0]["already_archived"] is True
assert entries[0]["receipt_sha256"] == receipt["digests"]["receipt_sha256"]
def test_prune_verify_runs_source_symlink_keeps_run_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
run_dir, _ = _write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
outside = tmp_path / "private.log"
outside.write_text("private evidence\n")
(run_dir / "linked.log").symlink_to(outside)
archive_root = tmp_path / "verify-archive"
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 0
assert run_dir.is_dir()
assert not (archive_root / run_dir.name).exists()
@pytest.mark.skipif(os.name != "posix", reason="requires POSIX FIFO support")
def test_prune_verify_runs_source_special_file_keeps_run_dir(tmp_path, monkeypatch):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
run_dir, _ = _write_verify_run_dir(root, "20260101-000001-a")
_write_verify_run_dir(root, "20260101-000002-b")
os.mkfifo(run_dir / "stream")
copy_attempted = False
def _unexpected_copytree(*args, **kwargs):
nonlocal copy_attempted
copy_attempted = True
raise OSError("copytree must not receive special files")
monkeypatch.setattr(verification.shutil, "copytree", _unexpected_copytree)
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=tmp_path / "verify-archive")
assert removed == 0
assert copy_attempted is False
assert run_dir.is_dir()
def test_prune_verify_runs_without_receipt_archives_with_null_metadata(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
legacy = root / "20260101-000001-a"
legacy.mkdir()
(legacy / "command-1-stdout.log").write_text("partial run\n")
_write_verify_run_dir(root, "20260101-000002-b")
archive_root = tmp_path / "verify-archive"
removed = verification._prune_verify_runs(tmp_path, keep=1, archive_root=archive_root)
assert removed == 1
assert (archive_root / "20260101-000001-a" / "command-1-stdout.log").is_file()
entries = _read_archive_index(archive_root)
assert len(entries) == 1
entry = entries[0]
assert entry["run_id"] == "20260101-000001-a"
assert entry["receipt_file_sha256"] is None
assert entry["receipt_sha256"] is None
assert entry["receipt_schema_version"] is None
assert entry["signature"] is None
assert entry["status"] is None
def _write_verify_retention_config(tmp_path, **overrides):
payload = {
"version": 1,
"depth": "repo",
"harnesses": ["claude"],
"owner": "claude",
"includes": [],
}
payload.update(overrides)
path = tmp_path / ".brigade" / "config.json"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload) + "\n")
def test_prune_verify_runs_respects_configured_keep_and_archive_dir(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
names = ["20260101-000001-a", "20260101-000002-b", "20260101-000003-c"]
for name in names:
_write_verify_run_dir(root, name)
_write_verify_retention_config(tmp_path, verify_runs_keep=1, verify_archive_dir="evidence/verify-archive")
removed = verification._prune_verify_runs(tmp_path)
assert removed == 2
assert sorted(p.name for p in root.iterdir()) == ["20260101-000003-c"]
archive_root = tmp_path / "evidence" / "verify-archive"
assert (archive_root / "20260101-000001-a" / "receipt.json").is_file()
assert (archive_root / "20260101-000002-b" / "receipt.json").is_file()
assert len(_read_archive_index(archive_root)) == 2
def test_prune_verify_runs_defaults_archive_next_to_runs_root(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
for name in ("20260101-000001-a", "20260101-000002-b"):
_write_verify_run_dir(root, name)
removed = verification._prune_verify_runs(tmp_path, keep=1)
assert removed == 1
default_archive = tmp_path / ".brigade" / "work" / "verify-archive"
assert (default_archive / "20260101-000001-a" / "receipt.json").is_file()
assert len(_read_archive_index(default_archive)) == 1
def test_prune_verify_runs_archive_disabled_matches_legacy_delete(tmp_path):
from brigade.work_cmd import helpers, verification
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
names = ["20260101-000001-a", "20260101-000002-b", "20260101-000003-c"]
for name in names:
_write_verify_run_dir(root, name)
_write_verify_retention_config(tmp_path, verify_runs_keep=1, verify_archive_enabled=False)
removed = verification._prune_verify_runs(tmp_path)
assert removed == 2
assert sorted(p.name for p in root.iterdir()) == ["20260101-000003-c"]
assert not (tmp_path / ".brigade" / "work" / "verify-archive").exists()
def test_verify_run_finalization_archives_pruned_runs(tmp_path):
from brigade.work_cmd import helpers
_init_git_repo(tmp_path)
root = helpers._verify_runs_root(tmp_path)
root.mkdir(parents=True)
# Seed the runs root at the retention cap so the new run triggers pruning.
for index in range(50):
_write_verify_run_dir(root, f"20260101-0000{index:02d}-seed")
assert work_cmd.verify_run(target=tmp_path, commands=["python3 -c \"print('ok')\""]) == 0
run_dirs = sorted(p.name for p in root.iterdir())
assert len(run_dirs) == 50
assert "20260101-000000-seed" not in run_dirs
default_archive = tmp_path / ".brigade" / "work" / "verify-archive"
assert (default_archive / "20260101-000000-seed" / "receipt.json").is_file()
entries = _read_archive_index(default_archive)
assert [entry["run_id"] for entry in entries] == ["20260101-000000-seed"]
assert entries[0]["receipt_schema_version"] == 2
def test_outcome_health_flags_dormant_then_half_fed(tmp_path):
from brigade import outcome_cmd
dormant = outcome_cmd.health(tmp_path)
assert dormant["record_count"] == 0 and dormant["verify_run_count"] == 0
assert dormant["top_issue"]["name"] == "outcome_loop_dormant"
_init_git_repo(tmp_path)
assert work_cmd.verify_run(target=tmp_path, commands=["python3 -c \"print('ok')\""]) == 0
half_fed = outcome_cmd.health(tmp_path)
assert half_fed["verify_run_count"] >= 1 and half_fed["eligible_receipt_count"] == 0
assert half_fed["top_issue"]["name"] == "outcome_loop_half_fed"
assert "subject_binding" in half_fed["top_issue"]["detail"]
def test_work_acceptance_rollup_covers_completion_review_and_closeout(tmp_path, capsys):
_init_git_repo(tmp_path)
ledger = {
"version": 1,
"tasks": [
{
"id": "pending-ready",
"text": "Pending with acceptance",
"status": "pending",
"acceptance": ["Ready acceptance."],
},
{
"id": "pending-missing",
"text": "Pending missing acceptance",
"status": "pending",
},
{
"id": "done-ready",
"text": "Done with completion",
"status": "done",
"acceptance": ["Done acceptance."],
"completed_acceptance": ["Done acceptance."],
"completion": {"session_path": ".brigade/work/session-one"},
},
{
"id": "done-missing-completion",
"text": "Done missing completion",
"status": "done",
"acceptance": ["Done acceptance."],
"completed_acceptance": ["Done acceptance."],
},
{
"id": "done-missing-completed-acceptance",
"text": "Done missing completed acceptance",
"status": "done",
"acceptance": ["Done acceptance."],
"completion": {"session_path": ".brigade/work/session-two"},
},
],
}
work_cmd._write_task_ledger(tmp_path, ledger)
imports = []
for finding_id, status, task_id, dismiss_reason in (
("pending-finding", "pending", None, None),
("dismissed-finding", "dismissed", None, "not actionable"),
("completed-finding", "promoted", "done-ready", None),
):
item = work_cmd._make_import(
f"Review finding {finding_id}",
kind="task",
source="code-review",
metadata={
"reviewer_id": "codex-review",
"review_run_id": "run-one",
"review_finding_id": finding_id,
"source_item_key": f"code-review:codex-review:{finding_id}",
"source_fingerprint": f"fp-{finding_id}",
},
)
item["status"] = status
if task_id:
item["task_id"] = task_id
if dismiss_reason:
item["dismiss_reason"] = dismiss_reason
imports.append(item)
work_cmd._write_imports(tmp_path, imports)
(tmp_path / ".brigade" / "work" / "closeouts" / "blocked-closeout").mkdir(parents=True)
_write_json(
tmp_path / ".brigade" / "work" / "closeouts" / "blocked-closeout" / "closeout.json",
{
"closeout_id": "blocked-closeout",
"ready": False,
"status": "blocked",
"created_at": "2026-05-29T12:00:00+00:00",
"acceptance_criteria": ["Closeout acceptance."],
"blockers": ["review run is not closed out"],
},
)
assert work_cmd.acceptance(target=tmp_path, json_output=True) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["pending_with_acceptance"] == ["pending-ready"]
assert payload["pending_missing_acceptance"] == ["pending-missing"]
assert payload["done_with_completion"] == ["done-ready", "done-missing-completed-acceptance"]
assert payload["done_missing_completion"] == ["done-missing-completion"]
assert payload["done_missing_completed_acceptance"] == ["done-missing-completed-acceptance"]
assert payload["review_findings"]["outcomes"] == {
"completed": 1,
"dismissed": 1,
"pending": 1,
}
assert payload["latest_work_closeout"]["closeout_id"] == "blocked-closeout"
issue_names = {issue["name"] for issue in payload["issues"]}
assert "acceptance_pending_missing" in issue_names
assert "acceptance_done_missing_completion" in issue_names
assert "acceptance_done_missing_completed_acceptance" in issue_names
assert "acceptance_review_findings_unresolved" in issue_names
assert "acceptance_work_closeout_blocked" in issue_names
assert work_cmd.acceptance(target=tmp_path) == 0
out = capsys.readouterr().out
assert "done_missing_completed_acceptance: 1" in out
assert "review_findings_unresolved: 1" in out
assert "work_closeout: blocked-closeout" in out
def test_work_verify_plan_run_list_show(tmp_path, capsys):
_init_git_repo(tmp_path)
assert work_cmd.verify_plan(target=tmp_path, commands=["python3 -c \"print('ok')\""], json_output=True) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["commands"] == ["python3 -c \"print('ok')\""]
assert payload["blockers"] == []
assert (
work_cmd.verify_run(target=tmp_path, commands=["python3 -c \"print('ok')\""], timeout=30, json_output=True) == 0
)
receipt = json.loads(capsys.readouterr().out)
assert receipt["status"] == "completed"
assert receipt["commands"][0]["stdout_summary"] == "ok"
assert Path(receipt["commands"][0]["stdout_log_path"]).is_file()
assert Path(receipt["path"], "receipt.json").is_file()
assert Path(receipt["path"], "summary.md").is_file()
assert work_cmd.verify_runs(target=tmp_path, json_output=True) == 0
runs = json.loads(capsys.readouterr().out)
assert runs["runs"][0]["run_id"] == receipt["run_id"]
assert work_cmd.verify_show(target=tmp_path, run_id="latest") == 0
out = capsys.readouterr().out
assert f"work verify run: {receipt['run_id']}" in out
assert "python3 -c" in out
def _init_verify_target_with_head(target):
target.mkdir(parents=True, exist_ok=True)
_init_git_repo_with_head(target)
@pytest.mark.skipif(os.name != "posix", reason="requires POSIX shell env-prefix invocation")
def test_verify_reused_receipt_stamps_harness_session_from_outer_env_prefix(tmp_target, monkeypatch):
"""Regression #541: cache-hit receipts must stamp outer BRIGADE_CLAUDE_SESSION."""
from brigade.claude_hooks.runtime import _session_fingerprint
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
graphtrail_bin = str(tmp_target / "missing-graphtrail")
monkeypatch.setenv("GRAPHTRAIL_BIN", graphtrail_bin)
fingerprint_a = _session_fingerprint("session-a-outer-prefix")
fingerprint_b = _session_fingerprint("session-b-outer-prefix")
verify_command = "true"
target = str(tmp_target)
brigade_cli = (
f"{shlex.quote(sys.executable)} -m brigade work verify run "
f"--target {shlex.quote(target)} --command {shlex.quote(verify_command)}"
)
subprocess_env = {**os.environ, "GRAPHTRAIL_BIN": graphtrail_bin}
case_a = subprocess.run(
["/bin/sh", "-c", f"BRIGADE_CLAUDE_SESSION={fingerprint_a} {brigade_cli}"],
cwd=tmp_target,
env=subprocess_env,
check=False,
capture_output=True,
text=True,
)
assert case_a.returncode == 0, case_a.stderr
case_b = subprocess.run(
[
"/bin/sh",
"-c",
f"BRIGADE_CLAUDE_SESSION={fingerprint_b} PY=/fake/path {brigade_cli}",
],
cwd=tmp_target,
env=subprocess_env,
check=False,
capture_output=True,
text=True,
)
assert case_b.returncode == 0, case_b.stderr
receipts = verification._verify_receipts(tmp_target)
assert len(receipts) == 2
reused = receipts[0]
fresh = receipts[1]
assert reused["reused_from"] == fresh["run_id"]
assert fresh["harness_session"] == {"harness": "claude", "fingerprint": fingerprint_a}
assert reused["harness_session"] == {"harness": "claude", "fingerprint": fingerprint_b}
assert reused["planned_commands"] == [verify_command]
def test_verify_reused_receipt_records_env_assignments_inside_command(tmp_target, monkeypatch):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
command = f'FOO=bar BAZ=qux {sys.executable} -c "print(1)"'
assert verification.verify_run(target=tmp_target, commands=[command], timeout=60) == 0
assert verification.verify_run(target=tmp_target, commands=[command], timeout=60) == 0
receipts = verification._verify_receipts(tmp_target)
assert len(receipts) == 2
reused = receipts[0]
fresh = receipts[1]
assert reused["reused_from"] == fresh["run_id"]
assert reused["commands"][0]["env"] == ["BAZ", "FOO"]
assert reused["planned_commands"] == [command]
def test_verify_reuses_identical_tree(tmp_target, monkeypatch):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
rc1 = verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
assert rc1 == 0
rc2 = verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
assert rc2 == 0
receipts = verification._verify_receipts(tmp_target)
assert len(receipts) == 2
newest = receipts[0]
assert newest["status"] == "completed"
assert newest["reused_from"] == receipts[1]["run_id"]
# the reused receipt carries forward the prior run's command records
assert newest["commands"] == receipts[1]["commands"]
def test_verify_no_reuse_flag_forces_run(tmp_target, monkeypatch):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
verification.verify_run(target=tmp_target, commands=["true"], timeout=60, reuse=False)
receipts = verification._verify_receipts(tmp_target)
assert "reused_from" not in receipts[0]
def test_verify_dirty_tree_not_reused(tmp_target, monkeypatch):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
(tmp_target / "newfile.txt").write_text("x\n")
verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
receipts = verification._verify_receipts(tmp_target)
assert "reused_from" not in receipts[0]
def test_verify_failed_receipt_not_reused(tmp_target, monkeypatch):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc != 0
receipts = verification._verify_receipts(tmp_target)
assert "reused_from" not in receipts[0]
def test_verify_warns_before_retrying_uncaptured_failed_command(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
failed = verification._verify_receipts(tmp_target)[0]
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc != 0
err = capsys.readouterr().err
assert f"warning: brigade outcome capture brigade-work --run-id {failed['run_id']}" in err
def test_verify_blocks_before_retrying_uncaptured_failed_command(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
_write_brigade_config(tmp_target, capture_before_retry="block")
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
failed = verification._verify_receipts(tmp_target)[0]
before = _count_verify_run_dirs(tmp_target)
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc == 1
assert _count_verify_run_dirs(tmp_target) == before
err = capsys.readouterr().err
assert f"error: brigade outcome capture brigade-work --run-id {failed['run_id']}" in err
def test_verify_off_allows_silent_retry_of_uncaptured_failed_command(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
_write_brigade_config(tmp_target, capture_before_retry="off")
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc != 0
err = capsys.readouterr().err
assert "brigade outcome capture" not in err
def test_verify_captured_failed_command_retries_silently(tmp_target, monkeypatch, capsys):
from brigade import outcome_cmd
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
failed = verification._verify_receipts(tmp_target)[0]
assert outcome_cmd.capture(target=tmp_target, artifact_id="brigade-work", run_id=failed["run_id"]) == 0
capsys.readouterr()
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc != 0
err = capsys.readouterr().err
assert "brigade outcome capture" not in err
def test_verify_first_run_and_passed_retry_stay_silent(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
rc = verification.verify_run(target=tmp_target, commands=["true"], timeout=60)
assert rc == 0
err = capsys.readouterr().err
assert "brigade outcome capture" not in err
rc = verification.verify_run(target=tmp_target, commands=["true"], timeout=60, reuse=False)
assert rc == 0
err = capsys.readouterr().err
assert "brigade outcome capture" not in err
def test_verify_pass_after_failure_makes_next_retry_silent(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
(tmp_target / "check.py").write_text(
"from pathlib import Path\n"
"marker = Path('passed-once')\n"
"if not marker.exists():\n"
" marker.write_text('ready')\n"
" raise SystemExit(1)\n"
)
command = "python3 check.py"
assert verification.verify_run(target=tmp_target, commands=[command], timeout=60) != 0
assert verification.verify_run(target=tmp_target, commands=[command], timeout=60) == 0
capsys.readouterr()
assert verification.verify_run(target=tmp_target, commands=[command], timeout=60, reuse=False) == 0
assert "brigade outcome capture" not in capsys.readouterr().err
def test_verify_capture_before_retry_matches_exact_command_identity(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))
verification.verify_run(target=tmp_target, commands=["VAR=1 false"], timeout=60)
failed = verification._verify_receipts(tmp_target)[0]
rc = verification.verify_run(target=tmp_target, commands=["false"], timeout=60)
assert rc != 0
err = capsys.readouterr().err
assert "brigade outcome capture" not in err
rc = verification.verify_run(target=tmp_target, commands=["VAR=1 false"], timeout=60)
assert rc != 0
err = capsys.readouterr().err
assert f"warning: brigade outcome capture brigade-work --run-id {failed['run_id']}" in err
def test_verify_command_identity_normalizes_whitespace(tmp_target, monkeypatch, capsys):
from brigade.work_cmd import verification
_init_verify_target_with_head(tmp_target)
monkeypatch.setenv("GRAPHTRAIL_BIN", str(tmp_target / "missing-graphtrail"))