-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_receipts_cmd.py
More file actions
1884 lines (1636 loc) · 63 KB
/
Copy pathtest_receipts_cmd.py
File metadata and controls
1884 lines (1636 loc) · 63 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 json
import subprocess
import sys
from pathlib import Path
import pytest
from brigade import cli, localio, outcome, outcome_cmd, receipt_signing, receipts_cmd, runbook_cmd, work_cmd
from tests.work_cmd_test_helpers import _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,
)
return subprocess.check_output(["git", "-C", str(path), "rev-parse", "HEAD"], text=True).strip()
def _write_digestless_work_receipt(target):
run_dir = target / ".brigade" / "work" / "verify-runs" / "legacy"
run_dir.mkdir(parents=True)
receipt = {
"run_id": "legacy",
"target": str(target),
"status": "completed",
"commands": [],
}
localio.write_json(run_dir / "receipt.json", receipt)
def _write_runbook(path):
path.write_text(
json.dumps(
{
"id": "smoke",
"description": "tiny runbook",
"allowed_commands": ["printf"],
"steps": [{"id": "hello", "run": "printf hello"}],
}
)
)
return path
def _append_outcome(target, evidence_ref):
outcome_cmd.append_records(
target,
[
outcome.OutcomeRecord(
"taste",
"skill",
evidence_ref,
"verify",
1,
evidence_ref,
f"2026-07-08T00:00:0{evidence_ref[-1]}+00:00",
)
],
)
def _receipt_digest(payload):
return localio.canonical_json_digest(payload, exclude_keys={"digests"})
def _write_verify_export_receipt(
target,
run_id,
*,
started_at,
digest=True,
digest_signature=None,
code_graph_delta=None,
git=None,
):
run_dir = target / ".brigade" / "work" / "verify-runs" / run_id
run_dir.mkdir(parents=True)
stdout = run_dir / "command-1-stdout.log"
stderr = run_dir / "command-1-stderr.log"
stdout.write_text("ok\n")
stderr.write_text("")
receipt = {
"run_id": run_id,
"target": str(target),
"status": "completed",
"started_at": started_at,
"completed_at": started_at.replace("00Z", "05Z"),
"commands": [
{
"command": "python3 -c \"print('ok')\"",
"status": "completed",
"exit_code": 0,
"stdout_log_path": str(stdout),
"stderr_log_path": str(stderr),
}
],
}
if code_graph_delta is not None:
sidecar = run_dir / "graph-delta.json"
sidecar.write_text(json.dumps(code_graph_delta, sort_keys=True) + "\n")
receipt["code_graph_delta"] = code_graph_delta
if git is not None:
receipt["git"] = git
if digest:
logs = {
"command-1-stderr.log": localio.file_sha256(stderr),
"command-1-stdout.log": localio.file_sha256(stdout),
}
if code_graph_delta is not None:
logs["graph-delta.json"] = localio.file_sha256(run_dir / "graph-delta.json")
receipt["digests"] = {
"algorithm": "sha256",
"logs": dict(sorted(logs.items())),
"receipt_sha256": _receipt_digest(receipt),
}
if digest_signature is not None:
receipt["digests"]["signature"] = digest_signature["signature"]
receipt["digests"]["key_id"] = digest_signature["key_id"]
localio.write_json(run_dir / "receipt.json", receipt)
return run_dir / "receipt.json"
def _write_run_export_receipt(target, run_id, *, started_at, digest=False, code_graph_delta=None):
run_dir = target / ".brigade" / "runs" / run_id
run_dir.mkdir(parents=True)
payload = {
"task": "export receipts",
"cwd": str(target),
"orchestrator": "planner",
"dry_run": False,
"read_only": False,
"status": "ok",
"started_at": started_at,
"finished_at": started_at.replace("00Z", "07Z"),
"artifacts": str(run_dir),
}
if code_graph_delta is not None:
payload["code_graph_delta"] = code_graph_delta
if digest:
payload["digests"] = {
"algorithm": "sha256",
"receipt_sha256": _receipt_digest(payload),
}
localio.write_json(run_dir / "run.json", payload)
return run_dir / "run.json"
def _jsonl(text):
return [json.loads(line) for line in text.splitlines() if line.strip()]
def _write_repo_catalog(target, entries):
config = target / ".brigade" / "repos.toml"
config.parent.mkdir(parents=True, exist_ok=True)
sections = []
for repo_id, label, path, enabled in entries:
sections.append(
"\n".join(
[
"[[repo]]",
f"id = {json.dumps(repo_id)}",
f"label = {json.dumps(label)}",
f"path = {json.dumps(str(path))}",
f"enabled = {str(enabled).lower()}",
]
)
)
config.write_text("\n\n".join(sections) + "\n")
return config
def _write_fake_miseledger(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
export_path = pathlib.Path(sys.argv[3])
pathlib.Path({str(marker)!r}).write_text(json.dumps({{
"argv": sys.argv[1:],
"export_path": str(export_path),
"input": export_path.read_text(),
}}))
print(json.dumps({{"inserted_items": 1, "already_known": 0}}))
sys.exit({exit_code})
"""
)
path.chmod(0o755)
return path
def test_receipts_export_miseledger_emits_required_verify_fields_and_artifacts(tmp_path, capsys):
receipt_path = _write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-abc123",
started_at="2026-07-08T12:00:00Z",
digest=True,
code_graph_delta={"status": "ok", "summary": "edge_churn=2", "changed_symbol_count": 2},
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path)]) == 0
rows = _jsonl(capsys.readouterr().out)
assert len(rows) == 1
row = rows[0]
assert row["schema"] == "miseledger.adapter.v1"
assert row["source"]["kind"] == "brigade"
assert row["collection"]["external_id"] == "brigade:work:verify-runs"
assert row["collection"]["kind"] == "brigade_work_verify_runs"
assert row["item"]["external_id"] == "brigade:work-verify:20260708-120000-work-verify-abc123"
assert row["item"]["kind"] == "brigade_work_verify_receipt"
assert row["actor"] == {"external_id": "brigade:system", "type": "system", "name": "Brigade"}
assert "edge_churn=2" in row["item"]["text"]
assert row["item"]["metadata"]["code_graph_delta_summary"] == "edge_churn=2"
assert row["item"]["metadata"]["code_graph_delta"]["changed_symbol_count"] == 2
assert row["raw"]["path"] == ".brigade/work/verify-runs/20260708-120000-work-verify-abc123/receipt.json"
assert row["raw"]["hash"] == "sha256:" + json.loads(receipt_path.read_text())["digests"]["receipt_sha256"]
assert row["raw"]["ordinal"] == 1
assert all(
set(artifact) <= {"external_id", "kind", "path", "url", "mime_type", "text", "hash", "metadata"}
for artifact in row["artifacts"]
)
artifact_paths = {artifact["path"] for artifact in row["artifacts"]}
assert ".brigade/work/verify-runs/20260708-120000-work-verify-abc123/receipt.json" in artifact_paths
assert ".brigade/work/verify-runs/20260708-120000-work-verify-abc123/command-1-stdout.log" in artifact_paths
assert ".brigade/work/verify-runs/20260708-120000-work-verify-abc123/graph-delta.json" in artifact_paths
assert row["artifacts"][0]["hash"].startswith("sha256:")
assert row["links"] == []
assert row["relations"] == []
def test_receipts_export_miseledger_composes_graph_delta_code_references(tmp_path, capsys):
head = "a" * 40
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-code-reference",
started_at="2026-07-08T12:00:00Z",
code_graph_delta={
"status": "ok",
"changed_nodes": [
{
"kind": "function",
"qualified_name": "brigade.receipts_cmd._metadata_with_delta",
"file_path": "src/brigade/receipts_cmd.py",
"start_line": 787,
"end_line": 789,
}
],
},
git={"head": head, "branch": "code-reference", "dirty_files": 0},
)
_init_git_repo(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "https://github.com/escoffier-labs/brigade.git"],
cwd=tmp_path,
check=True,
stdout=subprocess.DEVNULL,
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path)]) == 0
row = _jsonl(capsys.readouterr().out)[0]
assert row["item"]["metadata"]["code_references"] == [
{
"change_kind": "changed",
"file_path": "src/brigade/receipts_cmd.py",
"qualified_name": "brigade.receipts_cmd._metadata_with_delta",
"repository": "escoffier-labs/brigade",
"revision": {"commit": head},
"schema": "brigade.code-reference.v1",
"source_span": {"start_line": 787, "line_count": 3},
"symbol_kind": "function",
}
]
assert row["item"]["metadata"]["code_references_total"] == 1
assert row["item"]["metadata"]["code_references_truncated"] is False
assert row["item"]["metadata"]["code_graph_delta"]["changed_nodes"][0]["start_line"] == 787
def test_receipts_export_miseledger_keeps_compaction_candidate_accounting_and_skips_malformed_nodes(tmp_path, capsys):
head = "a" * 40
valid_nodes = [
{
"change_kind": "added",
"kind": "function",
"qualified_name": f"pkg.symbol_{number:02d}",
"file_path": "pkg/mod.py",
"start_line": number,
"end_line": number,
}
for number in range(1, 21)
]
_write_verify_export_receipt(
tmp_path,
"20260708-120001-work-verify-code-reference-accounting",
started_at="2026-07-08T12:00:01Z",
code_graph_delta={
"status": "ok",
"code_reference_nodes": list(reversed(valid_nodes))
+ [{"kind": "function", "qualified_name": "empty_path", "file_path": "", "start_line": 1, "end_line": 1}],
"code_reference_nodes_total": 28,
"code_reference_nodes_truncated": True,
},
git={"head": head, "branch": "code-reference", "dirty_files": 0},
)
_init_git_repo(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "https://github.com/escoffier-labs/brigade.git"],
cwd=tmp_path,
check=True,
stdout=subprocess.DEVNULL,
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path)]) == 0
row = _jsonl(capsys.readouterr().out)[0]
metadata = row["item"]["metadata"]
assert len(metadata["code_references"]) == 20
assert metadata["code_references_total"] == 20
assert metadata["code_references_truncated"] is False
assert [reference["qualified_name"] for reference in metadata["code_references"]] == sorted(
reference["qualified_name"] for reference in metadata["code_references"]
)
@pytest.mark.parametrize(
("retained_count", "declared_total", "declared_truncated", "malformed", "expected_total", "expected_truncated"),
[
(19, 19, False, False, 19, False),
(19, 20, False, False, 19, False),
(19, 20, True, False, 19, False),
(20, 20, True, False, 20, False),
(20, 21, False, False, 20, False),
(20, 28, True, False, 28, True),
(20, 28, True, True, 20, False),
],
)
def test_receipts_export_recomputes_inconsistent_compact_code_reference_metadata(
tmp_path,
monkeypatch,
retained_count,
declared_total,
declared_truncated,
malformed,
expected_total,
expected_truncated,
):
nodes = [
{
"change_kind": "added",
"kind": "function",
"qualified_name": f"pkg.symbol_{number:02d}",
"file_path": "pkg/mod.py",
"start_line": number,
"end_line": number,
}
for number in range(1, retained_count + 1)
]
if malformed:
nodes.append({"change_kind": "added", "kind": "function", "qualified_name": "", "file_path": "pkg/mod.py"})
monkeypatch.setattr(receipts_cmd, "_code_reference_repository", lambda target: "escoffier-labs/brigade")
references, total, truncated = receipts_cmd._code_references_from_delta(
{
"git": {"head": "a" * 40},
"code_graph_delta": {
"code_reference_nodes": nodes,
"code_reference_nodes_total": declared_total,
"code_reference_nodes_truncated": declared_truncated,
},
},
tmp_path,
)
assert len(references) == retained_count
assert total == expected_total
assert truncated is expected_truncated
def test_receipts_export_miseledger_exports_run_and_digestless_verify_receipts(tmp_path, capsys):
_init_git_repo_with_head(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "https://github.com/example-org/example-repo.git"],
cwd=tmp_path,
check=True,
)
verify_path = _write_verify_export_receipt(
tmp_path,
"20260708-110000-work-verify-def456",
started_at="2026-07-08T11:00:00Z",
digest=False,
)
run_path = _write_run_export_receipt(
tmp_path,
"20260708-130000-aabbccdd",
started_at="2026-07-08T13:00:00Z",
digest=True,
code_graph_delta={"status": "ok", "summary": "changed_symbols=1"},
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert [row["item"]["kind"] for row in rows] == [
"brigade_run_receipt",
"brigade_work_verify_receipt",
]
assert rows[0]["collection"]["external_id"] == "brigade:runs"
assert rows[0]["item"]["external_id"] == "brigade:run:20260708-130000-aabbccdd"
assert rows[0]["item"]["metadata"]["project"] == "example-repo"
assert rows[0]["item"]["metadata"]["workspace_dir"] == str(tmp_path.resolve())
assert rows[0]["raw"]["hash"] == "sha256:" + json.loads(run_path.read_text())["digests"]["receipt_sha256"]
assert rows[0]["item"]["metadata"]["code_graph_delta_summary"] == "changed_symbols=1"
assert rows[1]["item"]["metadata"]["project"] == "example-repo"
assert rows[1]["item"]["metadata"]["workspace_dir"] == str(tmp_path.resolve())
assert rows[1]["raw"]["hash"] == "sha256:" + localio.file_sha256(verify_path)
assert rows[1]["item"]["metadata"]["digest_source"] == "file_sha256"
def test_receipts_export_miseledger_includes_digest_signature_when_present(tmp_path, capsys):
signature = {"signature": "a" * 64, "key_id": "deadbeef"}
_write_verify_export_receipt(
tmp_path,
"20260708-110000-work-verify-signed",
started_at="2026-07-08T11:00:00Z",
digest_signature=signature,
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert rows[0]["item"]["metadata"]["digest_signature"] == signature
def test_receipts_export_miseledger_omits_digest_signature_when_absent(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-110000-work-verify-unsigned",
started_at="2026-07-08T11:00:00Z",
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert "digest_signature" not in rows[0]["item"]["metadata"]
def test_receipts_export_miseledger_is_byte_identical_and_limit_uses_newest_first(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-090000-work-verify-old",
started_at="2026-07-08T09:00:00Z",
)
_write_run_export_receipt(tmp_path, "20260708-140000-new", started_at="2026-07-08T14:00:00Z")
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--limit", "1"]) == 0
first = capsys.readouterr().out
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--limit", "1"]) == 0
second = capsys.readouterr().out
assert first == second
rows = _jsonl(first)
assert [row["item"]["external_id"] for row in rows] == ["brigade:run:20260708-140000-new"]
def test_receipts_export_miseledger_new_only_exports_once_and_records_cursor(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-090000-work-verify-old",
started_at="2026-07-08T09:00:00Z",
)
_write_run_export_receipt(tmp_path, "20260708-140000-new", started_at="2026-07-08T14:00:00Z")
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
first_rows = _jsonl(capsys.readouterr().out)
assert len(first_rows) == 2
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
cursor = json.loads(cursor_path.read_text())
assert cursor["raw_hashes"] == sorted(row["raw"]["hash"] for row in first_rows)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
second = capsys.readouterr()
assert second.out == ""
assert second.err == ""
assert json.loads(cursor_path.read_text()) == cursor
def test_receipts_export_miseledger_without_new_only_ignores_cursor(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-090000-work-verify-old",
started_at="2026-07-08T09:00:00Z",
)
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
cursor_path.parent.mkdir(parents=True, exist_ok=True)
cursor_path.write_text("{not json\n")
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert len(rows) == 1
assert cursor_path.read_text() == "{not json\n"
def test_receipts_export_miseledger_new_only_cursor_records_only_written_lines(tmp_path, monkeypatch, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-first",
started_at="2026-07-08T12:00:00Z",
)
_write_run_export_receipt(tmp_path, "20260708-130000-second", started_at="2026-07-08T13:00:00Z")
out_path = tmp_path / "export.jsonl"
writes = []
class PartialWrite:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return False
def write(self, line):
writes.append(line)
if len(writes) == 2:
raise OSError("disk full")
return len(line)
original_open = Path.open
def partial_open(self, *args, **kwargs):
mode = args[0] if args else kwargs.get("mode", "r")
if self == out_path and "w" in mode:
return PartialWrite()
return original_open(self, *args, **kwargs)
monkeypatch.setattr(Path, "open", partial_open)
assert receipts_cmd.export_miseledger(target=tmp_path, out=out_path, new_only=True) == 1
captured = capsys.readouterr()
assert "could not write output" in captured.err
assert len(writes) == 2
first_hash = json.loads(writes[0])["raw"]["hash"]
cursor = json.loads((tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json").read_text())
assert cursor["raw_hashes"] == [first_hash]
def test_receipts_export_miseledger_import_runs_fake_binary_and_prints_summary(tmp_path, monkeypatch, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-import",
started_at="2026-07-08T12:00:00Z",
)
fake = tmp_path / "miseledger"
fake.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"]
(export_path.parent / "import-argv.json").write_text(json.dumps({{"argv": sys.argv[1:], "input": export_path.read_text()}}))
print(json.dumps({{"inserted_items": 1, "already_known": 0}}))
"""
)
fake.chmod(0o755)
monkeypatch.setenv("PATH", str(tmp_path))
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--import"]) == 0
captured = capsys.readouterr()
assert captured.out == "miseledger import: inserted_items=1 already_known=0\n"
assert captured.err == ""
marker = json.loads((tmp_path / ".brigade" / "work" / "import-argv.json").read_text())
assert marker["argv"][0:2] == ["import", "adapter"]
assert marker["argv"][3:] == ["--source", "brigade", "--json"]
assert len(_jsonl(marker["input"])) == 1
def test_receipts_export_miseledger_import_missing_binary_errors_and_exits_nonzero(tmp_path, monkeypatch, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-missing-import",
started_at="2026-07-08T12:00:00Z",
)
out_path = tmp_path / "export.jsonl"
empty_path = tmp_path / "empty-path"
empty_path.mkdir()
monkeypatch.setenv("PATH", str(empty_path))
assert receipts_cmd.export_miseledger(target=tmp_path, out=out_path, import_miseledger=True) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert "warning: miseledger binary not found on PATH; export kept at" in captured.err
assert len(_jsonl(out_path.read_text())) == 1
def test_receipts_export_miseledger_empty_is_healthy_without_json(tmp_path, capsys):
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
captured = capsys.readouterr()
assert captured.out == ""
assert captured.err == ""
def test_receipts_export_miseledger_import_skips_binary_on_zero_item_export(tmp_path, monkeypatch, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-nothing-new",
started_at="2026-07-08T12:00:00Z",
)
fake = tmp_path / "miseledger"
fake.write_text(
f"""#!{sys.executable}
import pathlib
import sys
pathlib.Path(sys.argv[3]).parent.joinpath("import-argv.json").write_text("invoked")
"""
)
fake.chmod(0o755)
monkeypatch.setenv("PATH", str(tmp_path))
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
assert len(_jsonl(capsys.readouterr().out)) == 1
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only", "--import"]) == 0
captured = capsys.readouterr()
assert captured.out == "nothing new; import skipped\n"
assert captured.err == ""
work_dir = tmp_path / ".brigade" / "work"
assert not (work_dir / "import-argv.json").exists()
assert list(work_dir.glob("miseledger-export-*.jsonl")) == []
def test_receipts_export_miseledger_import_all_malformed_exits_nonzero(tmp_path, monkeypatch, capsys):
bad_dir = tmp_path / ".brigade" / "work" / "verify-runs" / "bad"
bad_dir.mkdir(parents=True)
(bad_dir / "receipt.json").write_text("{not json\n")
marker = tmp_path / "import.json"
_write_fake_miseledger(tmp_path / "bin" / "miseledger", marker)
monkeypatch.setenv("PATH", str(tmp_path / "bin"))
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--import"]) == 1
captured = capsys.readouterr()
assert captured.out == ""
assert "warning: skipped malformed receipt" in captured.err
assert not marker.exists()
def test_receipts_export_miseledger_new_only_import_mixed_skip_and_malformed_exits_nonzero(
tmp_path, monkeypatch, capsys
):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-seen",
started_at="2026-07-08T12:00:00Z",
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
capsys.readouterr()
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
cursor = cursor_path.read_text()
bad_dir = tmp_path / ".brigade" / "work" / "verify-runs" / "bad"
bad_dir.mkdir(parents=True)
(bad_dir / "receipt.json").write_text("{not json\n")
marker = tmp_path / "import.json"
_write_fake_miseledger(tmp_path / "bin" / "miseledger", marker)
monkeypatch.setenv("PATH", str(tmp_path / "bin"))
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--new-only",
"--import",
]
)
== 1
)
captured = capsys.readouterr()
assert captured.out == ""
assert "warning: skipped malformed receipt" in captured.err
assert cursor_path.read_text() == cursor
assert not marker.exists()
def test_receipts_export_miseledger_copies_git_metadata_and_github_commit_link(tmp_path, capsys):
head = _init_git_repo_with_head(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "https://github.com/example-org/example-repo.git"],
cwd=tmp_path,
check=True,
)
git = {"head": head, "branch": "main", "dirty_files": 2}
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-git",
started_at="2026-07-08T12:00:00Z",
git=git,
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert rows[0]["item"]["metadata"]["git"] == git
assert rows[0]["links"] == [
{
"external_id": "brigade:work-verify:20260708-120000-work-verify-git:git-commit",
"kind": "url",
"url": f"https://github.com/example-org/example-repo/commit/{head}",
}
]
def test_receipts_export_miseledger_supports_ssh_github_commit_link(tmp_path, capsys):
head = _init_git_repo_with_head(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "git@github.com:example-org/example-repo.git"],
cwd=tmp_path,
check=True,
)
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-ssh-git",
started_at="2026-07-08T12:00:00Z",
git={"head": head, "branch": "main", "dirty_files": 0},
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert rows[0]["links"][0]["url"] == f"https://github.com/example-org/example-repo/commit/{head}"
def test_receipts_export_miseledger_keeps_git_metadata_without_non_github_link(tmp_path, capsys):
head = _init_git_repo_with_head(tmp_path)
subprocess.run(
["git", "remote", "add", "origin", "https://example.invalid/example-org/example-repo.git"],
cwd=tmp_path,
check=True,
)
git = {"head": head, "branch": "main", "dirty_files": 0}
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-no-link",
started_at="2026-07-08T12:00:00Z",
git=git,
)
assert receipts_cmd.export_miseledger(target=tmp_path) == 0
rows = _jsonl(capsys.readouterr().out)
assert rows[0]["item"]["metadata"]["git"] == git
assert rows[0]["links"] == []
def test_receipts_export_miseledger_malformed_receipt_is_failed_after_partial_export(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-150000-work-verify-good",
started_at="2026-07-08T15:00:00Z",
)
bad_dir = tmp_path / ".brigade" / "work" / "verify-runs" / "20260708-160000-work-verify-bad"
bad_dir.mkdir(parents=True)
(bad_dir / "receipt.json").write_text("{not json\n")
out_path = tmp_path / "export.jsonl"
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--out",
str(out_path),
"--json",
]
)
== 1
)
captured = capsys.readouterr()
payload = json.loads(captured.out)
rows = _jsonl(out_path.read_text())
assert len(rows) == 1
assert payload["status"] == "failed"
assert payload["candidate_count"] == 2
assert payload["exported_count"] == 1
assert payload["error_count"] == 1
assert "warning: skipped malformed receipt" in captured.err
assert "20260708-160000-work-verify-bad" in captured.err
def test_receipts_export_miseledger_malformed_receipt_fails_non_json_after_partial_export(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-150000-work-verify-good",
started_at="2026-07-08T15:00:00Z",
)
bad_dir = tmp_path / ".brigade" / "work" / "verify-runs" / "20260708-160000-work-verify-bad"
bad_dir.mkdir(parents=True)
(bad_dir / "receipt.json").write_text("{not json\n")
assert receipts_cmd.export_miseledger(target=tmp_path) == 1
captured = capsys.readouterr()
rows = _jsonl(captured.out)
assert len(rows) == 1
assert rows[0]["schema"] == "miseledger.adapter.v1"
assert "warning: skipped malformed receipt" in captured.err
def test_receipts_export_miseledger_json_empty_is_typed_and_healthy(tmp_path, capsys):
out_path = tmp_path / "empty.jsonl"
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--out",
str(out_path),
"--json",
]
)
== 0
)
captured = capsys.readouterr()
assert json.loads(captured.out) == {
"candidate_count": 0,
"error_count": 0,
"exported_count": 0,
"schema": "brigade.miseledger_export_result.v1",
"skipped_count": 0,
"status": "empty",
"target_label": "repository",
}
assert captured.err == ""
def test_receipts_export_miseledger_json_empty_write_failure_emits_failed_result(tmp_path, monkeypatch, capsys):
out_path = tmp_path / "empty.jsonl"
original_open = Path.open
def failed_open(self, *args, **kwargs):
if self == out_path:
raise OSError("disk full")
return original_open(self, *args, **kwargs)
monkeypatch.setattr(Path, "open", failed_open)
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--out",
str(out_path),
"--json",
]
)
== 1
)
captured = capsys.readouterr()
payload = json.loads(captured.out)
assert payload == {
"candidate_count": 0,
"error_count": 1,
"exported_count": 0,
"schema": "brigade.miseledger_export_result.v1",
"skipped_count": 0,
"status": "failed",
"target_label": "repository",
}
assert captured.out.count("\n") == 1
assert "could not write output" in captured.err
assert "disk full" in captured.err
def test_receipts_export_miseledger_json_nothing_new_is_idempotent(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-once",
started_at="2026-07-08T12:00:00Z",
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
capsys.readouterr()
cursor_path = tmp_path / ".brigade" / "work" / "miseledger-export-cursor.json"
cursor = cursor_path.read_text()
out_path = tmp_path / "nothing-new.jsonl"
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--new-only",
"--out",
str(out_path),
"--json",
]
)
== 0
)
captured = capsys.readouterr()
payload = json.loads(captured.out)
assert payload["status"] == "nothing-new"
assert payload["candidate_count"] == 1
assert payload["exported_count"] == 0
assert payload["skipped_count"] == 1
assert payload["error_count"] == 0
assert out_path.read_text() == ""
assert cursor_path.read_text() == cursor
def test_receipts_export_miseledger_json_zero_row_import_emits_only_result_json(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-once",
started_at="2026-07-08T12:00:00Z",
)
assert cli.main(["receipts", "export", "miseledger", "--target", str(tmp_path), "--new-only"]) == 0
capsys.readouterr()
out_path = tmp_path / "nothing-new.jsonl"
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),
"--new-only",
"--out",
str(out_path),
"--json",
"--import",
]
)
== 0
)
captured = capsys.readouterr()
payload = json.loads(captured.out)
assert payload["status"] == "nothing-new"
assert captured.out.count("\n") == 1
assert captured.err == ""
def test_receipts_export_miseledger_json_reports_exported_counts(tmp_path, capsys):
_write_verify_export_receipt(
tmp_path,
"20260708-120000-work-verify-exported",
started_at="2026-07-08T12:00:00Z",
)
out_path = tmp_path / "exported.jsonl"
assert (
cli.main(
[
"receipts",
"export",
"miseledger",
"--target",
str(tmp_path),