pointbreak 0.5.0

Durable terminal code review for changes humans and coding agents collaborate on together
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
mod support;

use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use pointbreak::model::ObjectId;
use pointbreak::session::{
    ArtifactKind, ArtifactRef, ImportArtifactOptions, export_artifact, import_artifact,
    read_object_artifact, referenced_artifacts,
};
use serde_json::Value;
use support::git_repo::GitRepo;
use support::shore;

/// Shared-store review fixture: the seed worktree captures one review unit,
/// which writes through to the shared common-dir store (`.git/shore`) by default.
/// The reader is a sibling worktree of the same clone, so its reads resolve the
/// same shared store with no `store link` step.
struct LinkedFixture {
    main: GitRepo,
    _worktree_parent: tempfile::TempDir,
    seed: PathBuf,
    reader: PathBuf,
    seed_revision_id: String,
    seed_snapshot_id: String,
    seed_object_artifact_content_hash: String,
}

impl LinkedFixture {
    fn new() -> Self {
        let main = GitRepo::new();
        main.write("README.md", "base\n");
        main.commit_all("base");

        let worktree_parent = tempfile::tempdir().expect("create worktree parent");
        let seed = worktree_parent.path().join("seed");
        add_worktree(main.path(), &seed, "seed");
        let reader = worktree_parent.path().join("reader");
        add_worktree(main.path(), &reader, "reader");

        let mut fixture = Self {
            main,
            _worktree_parent: worktree_parent,
            seed,
            reader,
            seed_revision_id: String::new(),
            seed_snapshot_id: String::new(),
            seed_object_artifact_content_hash: String::new(),
        };
        fs::write(fixture.seed.join("README.md"), "changed in seed\n").unwrap();
        let capture = fixture.capture(&fixture.seed);
        fixture.seed_revision_id = capture["revision"]["id"]
            .as_str()
            .expect("capture has review unit id")
            .to_owned();
        fixture.seed_snapshot_id = capture["revision"]["objectId"]
            .as_str()
            .expect("capture has snapshot id")
            .to_owned();
        fixture.seed_object_artifact_content_hash =
            capture["revision"]["objectArtifactContentHash"]
                .as_str()
                .expect("capture has object artifact content hash")
                .to_owned();
        fixture
    }

    fn capture(&self, worktree: &Path) -> Value {
        run_shore_json(&["capture", "--repo", worktree.to_str().unwrap()])
    }

    fn observation_add(&self, worktree: &Path, revision_id: &str, body: &str) -> Value {
        run_shore_json(&[
            "observation",
            "add",
            "--repo",
            worktree.to_str().unwrap(),
            "--revision",
            revision_id,
            "--track",
            "agent:test-fixture",
            "--title",
            "linked body artifact",
            "--body",
            body,
        ])
    }

    fn linked_store_dir(&self) -> PathBuf {
        self.main.path().join(".git/shore")
    }

    fn history_json(&self, worktree: &Path, include_body: bool) -> Value {
        let mut args = vec!["history", "--repo", worktree.to_str().unwrap()];
        if include_body {
            args.push("--include-body");
        }
        run_shore_json(&args)
    }

    fn unit_show_json(&self, worktree: &Path, revision_id: &str) -> Value {
        run_shore_json(&[
            "revision",
            "show",
            revision_id,
            "--repo",
            worktree.to_str().unwrap(),
            "--include-body",
        ])
    }

    /// Record one of each reviewer-facing fact on the seed's review unit.
    /// Returns the opened input request's id.
    fn seed_full_facts(&self, body: &str) -> String {
        self.observation_add(&self.seed, &self.seed_revision_id, body);
        let seed = self.seed.to_str().unwrap();
        let opened = run_shore_json(&[
            "input-request",
            "open",
            "--repo",
            seed,
            "--track",
            "agent:test-fixture",
            "--title",
            "Need approval",
            "--reason",
            "manual-decision-required",
            "--body",
            "approve this path?",
        ]);
        run_shore_json(&[
            "assessment",
            "add",
            "--repo",
            seed,
            "--track",
            "human:kevin",
            "--assessment",
            "accepted",
            "--summary",
            "ship it",
        ]);
        run_shore_json(&[
            "validation",
            "add",
            "--repo",
            seed,
            "--track",
            "agent:test-fixture",
            "--check-name",
            "cargo test",
            "--status",
            "passed",
        ]);
        opened["inputRequestId"]
            .as_str()
            .expect("input request open returns id")
            .to_owned()
    }

    fn respond_input_request(&self, worktree: &Path, input_request_id: &str) -> Value {
        run_shore_json(&[
            "input-request",
            "respond",
            input_request_id,
            "--repo",
            worktree.to_str().unwrap(),
            "--outcome",
            "approved",
            "--reason",
            "approved locally",
        ])
    }

    /// Force-remove the seed worktree; its review record survives in the shared
    /// common-dir store, which is not part of the removed worktree.
    fn remove_seed(&self) {
        run_git_os(
            self.main.path(),
            [
                OsString::from("worktree"),
                OsString::from("remove"),
                OsString::from("--force"),
                self.seed.as_os_str().to_owned(),
            ],
        );
        assert!(!self.seed.exists());
    }

    fn unit_list_json(&self, worktree: &Path) -> Value {
        run_shore_json(&["revision", "list", "--repo", worktree.to_str().unwrap()])
    }
}

/// One fully populated seed unit (every fact kind + response) written through to
/// the shared common-dir store, with the seed worktree force-removed. The shared
/// arrangement for the deleted-source-worktree matrix.
fn populated_fixture_with_deleted_seed(body: &str) -> (LinkedFixture, String) {
    let fixture = LinkedFixture::new();
    let input_request_id = fixture.seed_full_facts(body);
    fixture.respond_input_request(&fixture.seed, &input_request_id);
    fixture.remove_seed();
    (fixture, input_request_id)
}

fn assert_no_deleted_path_in_diagnostics(fixture: &LinkedFixture, json: &Value) {
    let diagnostics = json["diagnostics"].to_string();
    assert!(
        !diagnostics.contains(fixture.seed.to_str().unwrap()),
        "diagnostics mention the deleted worktree path: {diagnostics}"
    );
}

#[test]
fn deleted_worktree_unit_list_lists_unit() {
    let (fixture, _) = populated_fixture_with_deleted_seed("m1");

    let json = fixture.unit_list_json(&fixture.reader);

    assert_eq!(json["revisionCount"], 1);
    assert_eq!(
        json["entries"][0]["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_unit_show_renders_composite_with_snapshot() {
    let body = "m".repeat(5000);
    let (fixture, _) = populated_fixture_with_deleted_seed(&body);

    let json = fixture.unit_show_json(&fixture.reader, &fixture.seed_revision_id);

    assert_eq!(json["summary"]["observationCount"], 1);
    assert_eq!(json["summary"]["inputRequestCount"], 1);
    assert_eq!(json["summary"]["assessmentCount"], 1);
    assert_eq!(json["summary"]["validationCheckCount"], 1);
    assert!(json["summary"]["snapshotRowCount"].as_u64().unwrap() > 0);
    assert_eq!(json["observations"][0]["body"], Value::String(body));
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_history_renders_timeline_with_bodies() {
    let body = "n".repeat(5000);
    let (fixture, _) = populated_fixture_with_deleted_seed(&body);

    let json = fixture.history_json(&fixture.reader, true);

    assert!(json["eventCount"].as_u64().unwrap() > 0);
    assert!(
        json.to_string().contains(&body),
        "hydrated observation body loads from the linked store"
    );
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_observation_list_renders_with_hydrated_body() {
    let body = "p".repeat(5000);
    let (fixture, _) = populated_fixture_with_deleted_seed(&body);

    let json = run_shore_json(&[
        "observation",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--include-body",
    ]);

    assert_eq!(json["observations"].as_array().unwrap().len(), 1);
    assert_eq!(json["observations"][0]["body"], Value::String(body));
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_input_request_list_renders_with_response() {
    let (fixture, input_request_id) = populated_fixture_with_deleted_seed("m5");

    let json = run_shore_json(&[
        "input-request",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--status",
        "all",
    ]);

    assert_eq!(json["inputRequests"].as_array().unwrap().len(), 1);
    assert_eq!(
        json["inputRequests"][0]["id"],
        Value::String(input_request_id)
    );
    assert_eq!(
        json["inputRequests"][0]["responses"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_assessment_show_renders() {
    let (fixture, _) = populated_fixture_with_deleted_seed("m6");

    let json = run_shore_json(&[
        "assessment",
        "show",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
    ]);

    assert_eq!(json["assessments"].as_array().unwrap().len(), 1);
    assert_eq!(json["assessments"][0]["assessment"], "accepted");
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn deleted_worktree_validation_list_renders() {
    let (fixture, _) = populated_fixture_with_deleted_seed("m7");

    let json = run_shore_json(&[
        "validation",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
    ]);

    assert_eq!(json["validationChecks"].as_array().unwrap().len(), 1);
    assert_no_deleted_path_in_diagnostics(&fixture, &json);
}

#[test]
fn linked_reads_agree_on_event_set_hash_across_surfaces() {
    let fixture = LinkedFixture::new();
    fixture.seed_full_facts("short body");

    let reader_units = fixture.unit_list_json(&fixture.reader);
    let reader_history = fixture.history_json(&fixture.reader, false);
    let seed_units = fixture.unit_list_json(&fixture.seed);
    let seed_history = fixture.history_json(&fixture.seed, false);

    // Issue #140's regression signal, inverted into the standing guard: every
    // read surface in every linked checkout reports one eventSetHash.
    let hash = event_set_hash(&reader_units);
    assert!(hash.starts_with("sha256:"));
    assert_eq!(event_set_hash(&reader_history), hash);
    assert_eq!(event_set_hash(&seed_units), hash);
    assert_eq!(event_set_hash(&seed_history), hash);
    assert_eq!(reader_units["eventCount"], reader_history["eventCount"]);
    assert_eq!(reader_units["eventCount"], seed_units["eventCount"]);
}

#[test]
fn reader_capture_is_immediately_visible_via_write_through() {
    let fixture = LinkedFixture::new();

    let units = fixture.unit_list_json(&fixture.reader);
    assert_eq!(units["revisionCount"], 1);
    let before_hash = event_set_hash(&units).to_owned();

    // The reader captures in its own worktree: write-through lands it in the
    // shared common-dir store, so it is visible immediately with no `store link`.
    fs::write(fixture.reader.join("README.md"), "changed in reader\n").unwrap();
    let local_capture = fixture.capture(&fixture.reader);
    let local_unit_id = local_capture["revision"]["id"].as_str().unwrap().to_owned();

    let units = fixture.unit_list_json(&fixture.reader);
    let history = fixture.history_json(&fixture.reader, false);
    assert_eq!(units["revisionCount"], 2);
    assert!(units["entries"].to_string().contains(&local_unit_id));
    let advanced_hash = event_set_hash(&units);
    assert_ne!(advanced_hash, before_hash);
    assert_eq!(event_set_hash(&history), advanced_hash);
}

#[test]
fn reader_capture_file_target_observation_resolves_artifact() {
    let fixture = LinkedFixture::new();

    // The reader captures in its own worktree: the unit and its object artifact
    // write through to the shared common-dir store.
    fs::write(fixture.reader.join("README.md"), "changed in reader\n").unwrap();
    let capture = fixture.capture(&fixture.reader);
    let local_unit_id = capture["revision"]["id"]
        .as_str()
        .expect("local capture has review unit id")
        .to_owned();

    // A file-targeted observation against that captured unit resolves its bound
    // object artifact from the shared store and records the file target.
    let json = run_shore_json(&[
        "observation",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &local_unit_id,
        "--track",
        "agent:test-fixture",
        "--title",
        "file targeted on local capture",
        "--file",
        "README.md",
    ]);

    assert_eq!(json["target"]["kind"], "file");
    assert_eq!(json["target"]["filePath"], "README.md");
    assert_eq!(json["target"]["revisionId"], Value::String(local_unit_id));
}

#[test]
fn linked_reader_attaches_observation_to_linked_only_unit() {
    let fixture = LinkedFixture::new();

    // The reader attaches an observation to the seed's linked-only unit. Before
    // the migration this is RED: record_observation validates against the
    // reader's empty worktree-local store and fails with "unknown review unit".
    let result = fixture.observation_add(
        &fixture.reader,
        &fixture.seed_revision_id,
        "cross-worktree note",
    );

    assert_eq!(result["eventsCreated"], 1);
    assert!(
        result["observationId"].as_str().is_some(),
        "result carries an observation id: {result}"
    );
}

#[test]
fn linked_reader_opens_input_request_against_linked_only_unit() {
    let fixture = LinkedFixture::new();

    // RED today: open_input_request validates against the reader's empty local
    // store and fails with "unknown review unit".
    let result = run_shore_json(&[
        "input-request",
        "open",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "agent:test-fixture",
        "--title",
        "cross-worktree question",
        "--reason",
        "manual-decision-required",
        "--body",
        "approve?",
    ]);

    assert_eq!(result["eventsCreated"], 1);
    assert!(result["inputRequestId"].as_str().is_some());
}

#[test]
fn linked_reader_opens_input_request_with_observation_ref_target() {
    let fixture = LinkedFixture::new();

    // The seed records an observation on its unit and links it; the observation
    // now lives only in the linked store.
    let observation = fixture.observation_add(
        &fixture.seed,
        &fixture.seed_revision_id,
        "observation to reference",
    );
    let observation_id = observation["observationId"]
        .as_str()
        .expect("seed observation has an id")
        .to_owned();

    // RED today: resolve_input_request_target cannot see the linked-only
    // observation from the reader's local store.
    let result = run_shore_json(&[
        "input-request",
        "open",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--observation",
        &observation_id,
        "--track",
        "agent:test-fixture",
        "--title",
        "question about that observation",
        "--reason",
        "manual-decision-required",
        "--body",
        "is this right?",
    ]);

    assert_eq!(result["eventsCreated"], 1);
    assert_eq!(result["target"]["kind"], "observation");
    assert_eq!(
        result["target"]["observationId"],
        Value::String(observation_id)
    );
}

#[test]
fn linked_reader_responds_to_linked_only_input_request() {
    let fixture = LinkedFixture::new();
    let request_id = fixture.seed_full_facts("seed body");
    // The opened request lives in the seed's local store until link; copy it to
    // the linked store so the reader can see it.

    // RED today: respond_input_request reads the reader's empty local store and
    // fails with "unknown input request".
    let result = fixture.respond_input_request(&fixture.reader, &request_id);

    assert_eq!(result["eventsCreated"], 1);
    assert_eq!(result["outcome"], "approved");
}

#[test]
fn linked_reader_respond_copies_request_event_target_fields() {
    let fixture = LinkedFixture::new();
    let request_id = fixture.seed_full_facts("seed body");

    fixture.respond_input_request(&fixture.reader, &request_id);

    // The response lands in the clone-local store (write-through). Its EventTarget
    // must be copied verbatim from the union-read request, not fabricated.
    let events = read_store_events(&fixture.linked_store_dir());
    let response = events
        .iter()
        .find(|event| {
            event.event_type == pointbreak::session::event::EventType::InputRequestResponded
        })
        .expect("the response event is in the linked store");
    // The response addresses the same review-domain revision the request did. The
    // signed envelope now carries only an opaque `subjectId`, so the revision rides
    // the payload's `revisionId` (reconstructable without re-reading the request) —
    // copied verbatim from the union-read request, on the same track.
    let response_payload: pointbreak::session::event::InputRequestRespondedPayload =
        serde_json::from_value(response.payload.clone()).unwrap();
    assert_eq!(
        response_payload.revision_id.as_ref().map(|id| id.as_str()),
        Some(fixture.seed_revision_id.as_str())
    );
    assert_eq!(
        response.target.track_id.as_ref().map(|id| id.as_str()),
        Some("agent:test-fixture")
    );
}

#[test]
fn linked_reader_records_assessment_on_linked_only_unit() {
    let fixture = LinkedFixture::new();

    // RED today: record_assessment validates against the reader's empty local
    // store and fails with "unknown review unit".
    let result = run_shore_json(&[
        "assessment",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "human:kevin",
        "--assessment",
        "accepted",
        "--summary",
        "ship it",
    ]);

    assert_eq!(result["eventsCreated"], 1);
    assert!(result["assessmentId"].as_str().is_some());
}

#[test]
fn linked_reader_assessment_relates_linked_only_observation() {
    let fixture = LinkedFixture::new();
    let observation = fixture.observation_add(
        &fixture.seed,
        &fixture.seed_revision_id,
        "observation to relate",
    );
    let observation_id = observation["observationId"]
        .as_str()
        .expect("seed observation id")
        .to_owned();

    // RED today: relationship validation reads the reader's local store and
    // fails with "unknown observation".
    let result = run_shore_json(&[
        "assessment",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "human:kevin",
        "--assessment",
        "accepted",
        "--summary",
        "looks good",
        "--related-observation",
        &observation_id,
    ]);

    assert_eq!(result["eventsCreated"], 1);
}

#[test]
fn linked_reader_assessment_replaces_linked_only_assessment() {
    let fixture = LinkedFixture::new();
    let seed_assessment = run_shore_json(&[
        "assessment",
        "add",
        "--repo",
        fixture.seed.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "human:kevin",
        "--assessment",
        "accepted",
        "--summary",
        "first pass",
    ]);
    let assessment_id = seed_assessment["assessmentId"]
        .as_str()
        .expect("seed assessment id")
        .to_owned();

    // RED today: --replaces validation reads the reader's local store and fails
    // with "unknown assessment".
    let result = run_shore_json(&[
        "assessment",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "human:kevin",
        "--assessment",
        "needs-changes",
        "--summary",
        "second pass",
        "--replaces",
        &assessment_id,
    ]);

    assert_eq!(result["eventsCreated"], 1);
}

#[test]
fn linked_reader_records_validation_on_linked_only_unit() {
    let fixture = LinkedFixture::new();

    // RED today: record_validation_check validates against the reader's empty
    // local store and fails with "unknown review unit".
    let result = run_shore_json(&[
        "validation",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--track",
        "agent:test-fixture",
        "--check-name",
        "cargo test",
        "--status",
        "passed",
    ]);

    assert_eq!(result["eventsCreated"], 1);
}

#[test]
fn linked_fact_writes_land_in_linked_store_not_worktree_local() {
    let fixture = LinkedFixture::new();
    // Seed an input request so the reader has one to respond to, and link so the
    // baseline captures everything the seed has published.
    let request_id = fixture.seed_full_facts("seed body");
    let linked_before = event_file_names(&fixture.linked_store_dir());

    // One of each migrated fact on the reader against the seed's linked-only unit.
    let reader = fixture.reader.to_str().unwrap();
    let unit = fixture.seed_revision_id.as_str();
    fixture.observation_add(&fixture.reader, unit, "cross-worktree note");
    run_shore_json(&[
        "input-request",
        "open",
        "--repo",
        reader,
        "--revision",
        unit,
        "--track",
        "agent:test-fixture",
        "--title",
        "q",
        "--reason",
        "manual-decision-required",
        "--body",
        "?",
    ]);
    run_shore_json(&[
        "assessment",
        "add",
        "--repo",
        reader,
        "--revision",
        unit,
        "--track",
        "human:kevin",
        "--assessment",
        "accepted",
        "--summary",
        "ok",
    ]);
    run_shore_json(&[
        "validation",
        "add",
        "--repo",
        reader,
        "--revision",
        unit,
        "--track",
        "agent:test-fixture",
        "--check-name",
        "cargo test",
        "--status",
        "passed",
    ]);
    fixture.respond_input_request(&fixture.reader, &request_id);

    // Every write-through fact landed in the clone-local store, not worktree-local.
    let linked_after = event_file_names(&fixture.linked_store_dir());
    assert!(
        linked_after.len() > linked_before.len(),
        "linked store gained the write-through fact events: before={} after={}",
        linked_before.len(),
        linked_after.len()
    );
    assert!(
        event_file_names(&fixture.reader.join(".shore/data")).is_empty(),
        "reader worktree-local store received no fact events in linked mode"
    );
}

#[test]
fn linked_fact_write_state_json_is_orphan_free() {
    let fixture = LinkedFixture::new();
    fixture.observation_add(
        &fixture.reader,
        &fixture.seed_revision_id,
        "cross-worktree note",
    );

    // The fact's state.json is rebuilt in the clone-local store (write-through).
    // The StateReducer does not cross-check facts against captures, so there is
    // no orphan diagnostic even though the capture and fact may interleave.
    let bytes = fs::read(fixture.linked_store_dir().join("state.json"))
        .expect("read clone-local state.json");
    let state: Value = serde_json::from_slice(&bytes).expect("state.json is json");
    assert!(state["observationCount"].as_u64().unwrap() >= 1);
    assert!(
        !state_diagnostic_codes(&state)
            .iter()
            .any(|code| code.contains("orphan")),
        "diagnostics: {}",
        state["diagnostics"]
    );
}

#[test]
fn linked_fact_write_does_not_copy_object_artifacts_to_linked_store() {
    let fixture = LinkedFixture::new();
    // Reader captures locally: its object artifact lands in the reader's .shore/data.
    fs::write(fixture.reader.join("README.md"), "changed in reader\n").unwrap();
    let capture = fixture.capture(&fixture.reader);
    let local_unit = capture["revision"]["id"].as_str().unwrap().to_owned();

    let snapshots_before = object_artifact_names(&fixture.linked_store_dir());
    // File-targeted observation against the locally captured unit (the artifact
    // worktree-local fallback path). The write must not push the snapshot
    // artifact to the linked store — only `store link` copies artifacts.
    run_shore_json(&[
        "observation",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &local_unit,
        "--track",
        "agent:test-fixture",
        "--title",
        "t",
        "--file",
        "README.md",
    ]);
    let snapshots_after = object_artifact_names(&fixture.linked_store_dir());

    assert_eq!(
        snapshots_before, snapshots_after,
        "no object artifacts copied to the linked store by a write"
    );
}

fn event_file_names(store_dir: &Path) -> Vec<String> {
    json_file_names(&store_dir.join("events"))
}

/// Deserialize every event file directly out of an explicit store directory.
/// `read_events(worktree)` resolves the worktree-local `.shore/data` store; in
/// linked mode write-through lands events in the clone-local store, so reading
/// those events back means reading the clone-local store directory itself.
fn read_store_events(store_dir: &Path) -> Vec<pointbreak::session::event::ShoreEvent> {
    let events_dir = store_dir.join("events");
    let mut entries: Vec<PathBuf> = match fs::read_dir(&events_dir) {
        Ok(read_dir) => read_dir
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path())
            .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
            .collect(),
        Err(_) => Vec::new(),
    };
    entries.sort();
    entries
        .iter()
        .map(|path| {
            let bytes = fs::read(path).expect("read event file");
            serde_json::from_slice(&bytes).expect("event file is a ShoreEvent")
        })
        .collect()
}

fn object_artifact_names(store_dir: &Path) -> Vec<String> {
    json_file_names(&store_dir.join("artifacts/objects"))
}

fn json_file_names(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = match fs::read_dir(dir) {
        Ok(entries) => entries
            .filter_map(|entry| entry.ok())
            .filter_map(|entry| entry.file_name().into_string().ok())
            .filter(|name| name.ends_with(".json"))
            .collect(),
        Err(_) => Vec::new(),
    };
    names.sort();
    names
}

fn state_diagnostic_codes(state: &Value) -> Vec<String> {
    state["diagnostics"]
        .as_array()
        .map(|diagnostics| {
            diagnostics
                .iter()
                .filter_map(|diagnostic| diagnostic["code"].as_str().map(str::to_owned))
                .collect()
        })
        .unwrap_or_default()
}

#[test]
fn cross_worktree_fact_is_immediately_visible_via_write_through() {
    let fixture = LinkedFixture::new();
    let added = fixture.observation_add(&fixture.reader, &fixture.seed_revision_id, "cross note");
    let observation_id = added["observationId"].as_str().unwrap().to_owned();

    // Write-through: the seed (a separate checkout reading the shared common-dir
    // store) sees the reader's observation immediately, with no `store link`.
    let seen = observation_list_json(&fixture.seed, &fixture.seed_revision_id);
    assert!(contains_observation(&seen, &observation_id));
}

#[test]
fn file_targeted_cross_worktree_fact_is_immediately_readable() {
    let fixture = LinkedFixture::new();
    // The reader captures a unit in its worktree and records a file-targeted
    // observation with a body against it; both write through to the shared store.
    fs::write(fixture.reader.join("README.md"), "changed in reader\n").unwrap();
    let capture = fixture.capture(&fixture.reader);
    let local_unit = capture["revision"]["id"].as_str().unwrap().to_owned();
    let body = "z".repeat(5000);
    run_shore_json(&[
        "observation",
        "add",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &local_unit,
        "--track",
        "agent:test-fixture",
        "--title",
        "file note",
        "--file",
        "README.md",
        "--body",
        &body,
    ]);

    // A sibling checkout reads the fact's body directly from the shared store,
    // with no `store link` step.
    let listed = run_shore_json(&[
        "observation",
        "list",
        "--repo",
        fixture.seed.to_str().unwrap(),
        "--revision",
        &local_unit,
        "--include-body",
    ]);
    assert_eq!(listed["observations"][0]["body"], Value::String(body));
}

fn observation_list_json(worktree: &Path, revision_id: &str) -> Value {
    run_shore_json(&[
        "observation",
        "list",
        "--repo",
        worktree.to_str().unwrap(),
        "--revision",
        revision_id,
    ])
}

fn contains_observation(list: &Value, observation_id: &str) -> bool {
    list["observations"].as_array().is_some_and(|observations| {
        observations
            .iter()
            .any(|observation| observation["id"] == Value::String(observation_id.to_owned()))
    })
}

fn event_set_hash(json: &Value) -> &str {
    json["eventSetHash"].as_str().expect("eventSetHash present")
}

fn run_shore_json(args: &[&str]) -> Value {
    let output = shore(args.iter().copied());
    assert!(
        output.status.success(),
        "shore {args:?} failed\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("shore stdout is json")
}

fn add_worktree(repo: &Path, path: &Path, branch: &str) {
    run_git_os(
        repo,
        [
            OsString::from("worktree"),
            OsString::from("add"),
            OsString::from("-b"),
            OsString::from(branch),
            path.as_os_str().to_owned(),
        ],
    );
}

fn run_git_os<I>(cwd: &Path, args: I)
where
    I: IntoIterator<Item = OsString>,
{
    let output = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .unwrap_or_else(|error| panic!("run git in {}: {error}", cwd.display()));
    assert!(
        output.status.success(),
        "git failed in {}\nstdout:\n{}\nstderr:\n{}",
        cwd.display(),
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn linked_unit_list_without_local_events_has_no_divergence_diagnostic() {
    let fixture = LinkedFixture::new();

    let json = fixture.unit_list_json(&fixture.reader);

    assert_eq!(json["revisionCount"], 1);
    assert_eq!(json["eventCount"], 2);
    assert_eq!(
        json["entries"][0]["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert!(
        json["eventSetHash"]
            .as_str()
            .unwrap()
            .starts_with("sha256:")
    );
}

#[test]
fn linked_history_reads_full_timeline_from_linked_store() {
    let fixture = LinkedFixture::new();
    let body = "h".repeat(5000);
    fixture.observation_add(&fixture.seed, &fixture.seed_revision_id, &body);

    let json = fixture.history_json(&fixture.reader, true);

    assert_eq!(json["eventCount"], 3);
    let event_types: Vec<&str> = json["entries"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|entry| entry["eventType"].as_str())
        .collect();
    assert!(
        event_types.contains(&"work_object_proposed"),
        "{event_types:?}"
    );
    assert!(
        event_types.contains(&"review_observation_recorded"),
        "{event_types:?}"
    );
    assert!(
        json.to_string().contains(&body),
        "hydrated observation body loads from the linked store"
    );
}

#[test]
fn linked_unit_show_resolves_linked_only_unit() {
    let fixture = LinkedFixture::new();
    let body = "o".repeat(5000);
    fixture.seed_full_facts(&body);

    let json = fixture.unit_show_json(&fixture.reader, &fixture.seed_revision_id);

    assert_eq!(
        json["revision"]["id"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_eq!(json["summary"]["observationCount"], 1);
    assert_eq!(json["summary"]["inputRequestCount"], 1);
    assert_eq!(json["summary"]["assessmentCount"], 1);
    assert_eq!(json["summary"]["validationCheckCount"], 1);
    assert_eq!(
        json["observations"][0]["body"],
        Value::String(body),
        "observation body hydrates from the linked store"
    );
}

#[test]
fn linked_unit_show_loads_bound_snapshot_from_linked_store() {
    let fixture = LinkedFixture::new();

    let json = fixture.unit_show_json(&fixture.reader, &fixture.seed_revision_id);

    assert_eq!(
        json["revision"]["objectArtifactContentHash"],
        Value::String(fixture.seed_object_artifact_content_hash.clone())
    );
    assert!(
        json["summary"]["snapshotRowCount"].as_u64().unwrap() > 0,
        "bound snapshot rows project from the linked artifact"
    );
}

#[test]
fn linked_observation_list_resolves_linked_unit() {
    let fixture = LinkedFixture::new();
    let body = "b".repeat(5000);
    fixture.seed_full_facts(&body);

    let json = run_shore_json(&[
        "observation",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
        "--include-body",
    ]);

    assert_eq!(
        json["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_eq!(json["observations"].as_array().unwrap().len(), 1);
    assert_eq!(json["observations"][0]["body"], Value::String(body));
}

#[test]
fn linked_input_request_list_resolves_linked_unit() {
    let fixture = LinkedFixture::new();
    fixture.seed_full_facts("short body");

    let json = run_shore_json(&[
        "input-request",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
    ]);

    assert_eq!(
        json["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_eq!(json["inputRequests"].as_array().unwrap().len(), 1);
    assert_eq!(json["inputRequests"][0]["title"], "Need approval");
}

#[test]
fn linked_input_request_fetch_resolves_linked_request() {
    let fixture = LinkedFixture::new();
    let input_request_id = fixture.seed_full_facts("short body");

    let json = run_shore_json(&[
        "input-request",
        "show",
        &input_request_id,
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--include-body",
    ]);

    assert_eq!(json["inputRequest"]["id"], Value::String(input_request_id));
    assert_eq!(json["inputRequest"]["title"], "Need approval");
}

#[test]
fn linked_assessment_show_resolves_linked_unit() {
    let fixture = LinkedFixture::new();
    fixture.seed_full_facts("short body");

    let json = run_shore_json(&[
        "assessment",
        "show",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
    ]);

    assert_eq!(
        json["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_eq!(json["assessments"].as_array().unwrap().len(), 1);
    assert_eq!(json["assessments"][0]["assessment"], "accepted");
}

#[test]
fn linked_validation_list_resolves_linked_unit() {
    let fixture = LinkedFixture::new();
    fixture.seed_full_facts("short body");

    let json = run_shore_json(&[
        "validation",
        "list",
        "--repo",
        fixture.reader.to_str().unwrap(),
        "--revision",
        &fixture.seed_revision_id,
    ]);

    assert_eq!(
        json["revisionId"],
        Value::String(fixture.seed_revision_id.clone())
    );
    assert_eq!(json["validationChecks"].as_array().unwrap().len(), 1);
    assert_eq!(json["validationChecks"][0]["checkName"], "cargo test");
}

#[test]
fn object_artifact_reads_from_linked_store() {
    let fixture = LinkedFixture::new();
    let snapshot_id = ObjectId::new(fixture.seed_snapshot_id.clone());

    let artifact = read_object_artifact(&fixture.reader, &snapshot_id)
        .expect("object artifact reads from the linked store");

    // The object-scoped v2 artifact carries no revision_id; resolving its
    // snapshot id through the linked store is what proves the read.
    assert_eq!(artifact.snapshot.object_id, snapshot_id);
}

#[test]
fn export_artifact_body_reads_from_linked_store() {
    let fixture = LinkedFixture::new();
    let body = "x".repeat(5000);
    fixture.observation_add(&fixture.seed, &fixture.seed_revision_id, &body);

    let body_ref = seed_body_artifact_ref(&fixture);
    let bytes = export_artifact(&fixture.reader, &body_ref)
        .expect("body artifact exports from the linked store");

    assert!(!bytes.is_empty());
}

#[test]
fn import_artifact_writes_through_to_linked_store() {
    let fixture = LinkedFixture::new();
    let body = "y".repeat(5000);
    fixture.observation_add(&fixture.seed, &fixture.seed_revision_id, &body);

    let body_ref = seed_body_artifact_ref(&fixture);
    let artifact_relative_path = format!(
        "artifacts/notes/{}.json",
        body_ref
            .content_hash()
            .strip_prefix("sha256:")
            .expect("body content hash is sha256-prefixed")
    );
    let bytes = fs::read(fixture.linked_store_dir().join(&artifact_relative_path)).unwrap();

    import_artifact(ImportArtifactOptions::new(&fixture.reader, body_ref, bytes))
        .expect("import into the linked reader succeeds");

    // Write-through (INV-1): import lands the artifact bytes in the clone-local
    // store (the same store reads resolve), never the reader's worktree-local
    // `.shore/data`.
    assert!(
        fixture
            .linked_store_dir()
            .join(&artifact_relative_path)
            .is_file()
    );
    assert!(
        !fixture
            .reader
            .join(".shore/data")
            .join(&artifact_relative_path)
            .exists()
    );
}

fn seed_body_artifact_ref(fixture: &LinkedFixture) -> ArtifactRef {
    // The seed's observation write-throughs to the clone-local store, so the body
    // artifact ref is derived from the clone-local events, not worktree-local.
    let events = read_store_events(&fixture.linked_store_dir());
    referenced_artifacts(&events)
        .expect("derive artifact refs from seed events")
        .into_iter()
        .find(|artifact| artifact.kind() == ArtifactKind::Body)
        .expect("seed events reference a body artifact")
}

#[test]
fn worktree_local_unit_list_is_unchanged() {
    let repo = GitRepo::new();
    repo.write("src/lib.rs", "pub fn value() -> u32 { 1 }\n");
    repo.commit_all("base");
    repo.write("src/lib.rs", "pub fn value() -> u32 { 2 }\n");
    run_shore_json(&["capture", "--repo", repo.path().to_str().unwrap()]);

    let json = run_shore_json(&["revision", "list", "--repo", repo.path().to_str().unwrap()]);

    assert_eq!(json["schema"], "shore.review-revision-list");
    assert_eq!(json["version"], 1);
    assert_eq!(json["eventCount"], 2);
    assert_eq!(json["revisionCount"], 1);
}

#[test]
fn main_worktree_of_a_clone_round_trips_a_capture_in_place() {
    // The headline acceptance test: in the MAIN worktree of a clone, a capture
    // round-trips in place — `unit list` / `unit show` / `history` resolve it with
    // NO dedicated worktree, NO `store link`, and NO `--revision`. The shared
    // common-dir store is the default for every worktree.
    let main = GitRepo::new();
    main.write("README.md", "base\n");
    main.commit_all("base");

    // A tracked change on a branch, captured in the main worktree.
    main.git(["checkout", "-b", "feature"]);
    main.write("README.md", "changed on a branch in the main worktree\n");
    let capture = run_shore_json(&["capture", "--repo", main.path().to_str().unwrap()]);
    let unit_id = capture["revision"]["id"].as_str().unwrap().to_owned();

    // With NO --revision, the same worktree's reads resolve the capture in
    // place (write-through landed it in the same `.git/shore` store reads use).
    let list = run_shore_json(&["revision", "list", "--repo", main.path().to_str().unwrap()]);
    assert_eq!(list["revisionCount"], 1);
    assert_eq!(
        list["entries"][0]["revisionId"],
        Value::String(unit_id.clone())
    );

    let show = run_shore_json(&["revision", "show", "--repo", main.path().to_str().unwrap()]);
    assert_eq!(show["revision"]["id"], Value::String(unit_id.clone()));

    let history = run_shore_json(&["history", "--repo", main.path().to_str().unwrap()]);
    assert!(
        history["entries"]
            .as_array()
            .unwrap()
            .iter()
            .any(|entry| entry.to_string().contains(&unit_id)),
        "history includes the captured unit: {}",
        history["entries"]
    );
    // The capture landed in the shared common-dir store, not stranded worktree-local.
    let status = run_shore_json(&["store", "status", "--repo", main.path().to_str().unwrap()]);
    assert_eq!(status["mode"], "local");
    assert_eq!(status["inventory"]["eventCount"], 2);
}

#[test]
fn fresh_single_worktree_has_clean_own_only_reads() {
    // A plain single-worktree clone: a capture writes through to the shared
    // common-dir store and the same worktree's reads resolve it in place.
    let repo = GitRepo::new();
    repo.write("README.md", "base\n");
    repo.commit_all("base");
    repo.write("README.md", "changed locally\n");
    let capture = run_shore_json(&["capture", "--repo", repo.path().to_str().unwrap()]);
    let unit_id = capture["revision"]["id"].as_str().unwrap().to_owned();

    let list = run_shore_json(&["revision", "list", "--repo", repo.path().to_str().unwrap()]);
    assert_eq!(list["revisionCount"], 1);
    assert_eq!(
        list["entries"][0]["revisionId"],
        Value::String(unit_id.clone())
    );

    let status = run_shore_json(&["store", "status", "--repo", repo.path().to_str().unwrap()]);
    assert_eq!(status["mode"], "local");
    // The capture landed in the shared common-dir store, not the worktree-local one.
    assert!(
        support::common_dir_store(repo.path())
            .join("events")
            .is_dir()
    );
}