artifactize 0.19.0

The AI-native collaboration layer for one-of-a-kind teammates and their agents: split a project into Artifacts with their own evals, and reuse every review while it still holds.
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
#[path = "support/run.rs"]
mod owned_run;

use std::{
    fs,
    path::{Path, PathBuf},
    process::Command,
    time::Duration,
};

use artifactize_core::{
    human,
    project::{self, VerifyOptions, selection::Selection},
    store::{self, OwnedReceipts, RunView},
};
use serde_json::{Value, json};
use support::os::{cat_program, false_program, true_program};
use tokio_util::sync::CancellationToken;

#[path = "../../artifactize-core/tests/support/mod.rs"]
mod support;
use support::runs::RecordOutput;

struct Fixture {
    _root: owned_run::Root,
    repo: PathBuf,
    state: PathBuf,
}

impl Fixture {
    fn new(fingerprint: bool) -> Self {
        let root = owned_run::Root::from(support::os::tempdir());
        let repo = root.path().join("repo");
        fs::create_dir(&repo).unwrap();
        write_human(&repo, fingerprint);
        let state = root.path().join("state");
        root.track(&state, &repo);
        Self {
            repo,
            state,
            _root: root,
        }
    }

    async fn verify(&self, options: VerifyOptions) -> RunView {
        tokio::time::timeout(
            Duration::from_secs(10),
            support::runs::record(
                &self.repo,
                Some(&self.state),
                &Selection::All,
                &options,
                CancellationToken::new(),
            ),
        )
        .await
        .expect("verify must exit while Humans wait")
        .unwrap()
    }

    async fn receipts(&self) -> OwnedReceipts {
        OwnedReceipts::open(&self.state, &self.repo).await.unwrap()
    }

    fn cli_verify(&self) -> Value {
        let output = Command::new(support::os::cli())
            .arg("--repo")
            .arg(&self.repo)
            .arg("--state-dir")
            .arg(&self.state)
            .args(["verify", "--all", "--json"])
            .record_output()
            .unwrap();
        // Submission returns at once; the request stays open for the person.
        assert_eq!(
            output.status.code(),
            Some(0),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        serde_json::from_slice(&output.stdout).unwrap()
    }
}

fn write_human(path: &Path, fingerprint: bool) {
    fs::create_dir_all(path).unwrap();
    support::declaration::write(path.join("fingerprint"), "human-v1\n").unwrap();
    let mut declaration = json!({
        "name":"review",
        "views":{
            "human_tools":{
                "inspect":{
                    "description":"Inspect",
                    "kind":"output",
                    "command":cat_program(),
                    "args":["fingerprint"],
                },
                "fail":{"description":"Fail","kind":"output","command":false_program(),"args":[]},
            },
            "agent_tools":{"read":{"builtin":"read"}},
        },
        "evals":[
            {
                "id":"check",
                "title":"Human check",
                "profile":{"kind":"human"},
                "payload":{"instruction":"Review."},
                "pass_schema":{
                    "type":"object",
                    "properties":{"approved":{"const":true}},
                    "required":["approved"],
                    "additionalProperties":false,
                },
                "fail_schema":{
                    "type":"object",
                    "properties":{"reason":{"type":"string","minLength":1}},
                    "required":["reason"],
                    "additionalProperties":false,
                },
            },
        ],
    });
    if fingerprint {
        declaration["fingerprint"] =
            json!({"script":{"command":cat_program(),"args":["fingerprint"]}});
    } else {
        declaration["fingerprint"] = json!(false);
    }
    support::declaration::write(path.join("index.artf"), declaration.to_string()).unwrap();
}

/// Options that record Human requests and return at once instead of waiting for them.
fn returning() -> VerifyOptions {
    VerifyOptions {
        ..Default::default()
    }
}

fn green() -> Value {
    json!({"verdict":"GREEN","approved":true})
}

/// A request ID parsed once, where a test names one.
fn rid(id: &str) -> artifactize_core::types::RequestId {
    id.parse().unwrap()
}

#[tokio::test]
async fn waiting_survives_verifier_exit_and_zero_budget_with_idempotent_claims() {
    let fixture = Fixture::new(true);
    let run = fixture.cli_verify();
    let id = run["requests"][0]["id"].as_str().unwrap();
    assert_eq!(run["status"], "WAITING_HUMAN");
    assert_eq!(run["requests"][0]["status"], "DEFERRED");
    assert_eq!(run["executionsStarted"], 0);
    let receipts = fixture.receipts().await;
    let alice_id = "alice".parse().unwrap();
    let bob_id = "bob".parse().unwrap();
    let request = rid(id);
    let (alice, bob) = tokio::join!(
        human::claim(&receipts, &request, &alice_id),
        human::claim(&receipts, &request, &bob_id)
    );
    assert_ne!(alice.is_ok(), bob.is_ok());
    let claim = alice.or(bob).unwrap();
    assert_eq!(
        human::claim(&receipts, &rid(id), &claim.reviewer)
            .await
            .unwrap()
            .claimed_at,
        claim.claimed_at
    );
    let follower = fixture
        .verify(VerifyOptions {
            max_executions: Some(0),
            ..returning()
        })
        .await;
    assert_eq!(follower.requests[0].status().as_str(), "DEFERRED");
    assert_eq!(
        follower.requests[0].execution_id.as_deref(),
        run["requests"][0]["executionId"].as_str()
    );
    let default = Fixture::new(false)
        .verify(VerifyOptions {
            max_executions: Some(0),
            ..returning()
        })
        .await;
    assert_eq!(default.requests[0].status().as_str(), "DEFERRED");
    assert_eq!(default.run.executions_started, 0);
}

#[tokio::test]
async fn claimant_only_tools_and_correctable_schema_errors_then_exactly_once_submit() {
    let fixture = Fixture::new(false);
    let run = fixture.verify(returning()).await;
    let id = &run.requests[0].id;
    let receipts = fixture.receipts().await;
    assert!(
        human::submit(
            &receipts,
            &rid(id),
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    human::claim(&receipts, &rid(id), &"alice".parse().unwrap())
        .await
        .unwrap();
    assert!(
        human::run_human_tool(
            &receipts,
            id,
            &"bob".parse().unwrap(),
            &"inspect_review".parse().unwrap(),
            CancellationToken::new(),
            artifactize_core::review::log::Run::unwatched()
        )
        .await
        .is_err()
    );
    assert!(
        human::submit(
            &receipts,
            &rid(id),
            &"bob".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    assert!(
        human::run_human_tool(
            &receipts,
            id,
            &"alice".parse().unwrap(),
            &"read_review".parse().unwrap(),
            CancellationToken::new(),
            artifactize_core::review::log::Run::unwatched()
        )
        .await
        .is_err()
    );
    let result = human::run_human_tool(
        &receipts,
        id,
        &"alice".parse().unwrap(),
        &"inspect_review".parse().unwrap(),
        CancellationToken::new(),
        artifactize_core::review::log::Run::unwatched(),
    )
    .await
    .unwrap();
    assert!(!result.is_error());
    let result = human::run_human_tool(
        &receipts,
        id,
        &"alice".parse().unwrap(),
        &"fail_review".parse().unwrap(),
        CancellationToken::new(),
        artifactize_core::review::log::Run::unwatched(),
    )
    .await
    .unwrap();
    assert!(result.is_error());
    for result in [
        json!({"verdict":"GREEN"}),
        json!({"verdict":"RED","reason":3}),
        json!({"verdict":"BLUE"}),
        json!({"verdict":"GREEN","approved":true,"extra":1}),
        json!({"verdict":"RED","reason":"x".repeat(256_000)}),
    ] {
        assert!(
            human::submit(
                &receipts,
                &rid(id),
                &"alice".parse().unwrap(),
                &result,
                CancellationToken::new()
            )
            .await
            .is_err()
        );
        assert_eq!(
            store::read_run(&fixture.state, &run.run.id)
                .await
                .unwrap()
                .requests[0]
                .status()
                .as_str(),
            "DEFERRED"
        );
    }
    let result = human::submit(
        &receipts,
        &rid(id),
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(result.status().as_str(), "GREEN");
    assert!(
        human::submit(
            &receipts,
            &rid(id),
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    assert!(
        human::claim(&receipts, &rid(id), &"alice".parse().unwrap())
            .await
            .is_err()
    );
    assert!(
        human::run_human_tool(
            &receipts,
            id,
            &"alice".parse().unwrap(),
            &"inspect_review".parse().unwrap(),
            CancellationToken::new(),
            artifactize_core::review::log::Run::unwatched()
        )
        .await
        .is_err()
    );
    let saved = store::read_request(&fixture.state, id).await.unwrap();
    assert_eq!(saved.request.status().as_str(), "GREEN");
    assert!(
        saved.claim.is_none(),
        "submission releases the public claim"
    );
    assert!(
        artifactize_core::cache::list(&fixture.state, true)
            .await
            .unwrap()
            .is_empty(),
        "fingerprint=false must not publish reusable evidence"
    );
}

#[tokio::test]
async fn fingerprint_change_before_submit_or_tool_settles_error_without_publishing() {
    for tool in [false, true] {
        let fixture = Fixture::new(true);
        let run = fixture.verify(returning()).await;
        let id = &run.requests[0].id;
        let receipts = fixture.receipts().await;
        human::claim(&receipts, &rid(id), &"alice".parse().unwrap())
            .await
            .unwrap();
        fs::write(fixture.repo.join("fingerprint"), "human-v2\n").unwrap();
        let error = if tool {
            human::run_human_tool(
                &receipts,
                id,
                &"alice".parse().unwrap(),
                &"inspect_review".parse().unwrap(),
                CancellationToken::new(),
                artifactize_core::review::log::Run::unwatched(),
            )
            .await
            .unwrap_err()
        } else {
            human::submit(
                &receipts,
                &rid(id),
                &"alice".parse().unwrap(),
                &green(),
                CancellationToken::new(),
            )
            .await
            .unwrap_err()
        };
        assert!(
            error.contains("Fingerprint changed during review"),
            "{error}"
        );
        let saved = store::read_run(&fixture.state, &run.run.id).await.unwrap();
        assert_eq!(saved.requests[0].status().as_str(), "ERROR");
        assert_eq!(
            saved.requests[0].error_code().as_deref(),
            Some("INPUT_CHANGED")
        );
        assert!(saved.requests[0].result().is_none());
        assert!(
            store::read_keyed_executions(&fixture.state, &[run.requests[0].key.clone().unwrap()],)
                .await
                .unwrap()
                .is_empty(),
            "the failed Human owner must not remain available for joining"
        );
        assert!(
            artifactize_core::cache::show(
                &fixture.state,
                run.requests[0].key.as_deref().unwrap(),
                false,
            )
            .await
            .unwrap()
            .is_empty()
        );
    }
}

#[tokio::test]
async fn scoped_declaration_changes_and_new_children_refuse_reconnection() {
    let fixture = Fixture::new(false);
    let run = fixture.verify(returning()).await;
    let id = &run.requests[0].id;
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &rid(id), &"alice".parse().unwrap())
        .await
        .unwrap();
    fs::create_dir(fixture.repo.join("child")).unwrap();
    support::declaration::write(
        fixture.repo.join("child/index.artf"),
        r#"{"name":"child","basis":true}"#,
    )
    .unwrap();
    assert!(
        human::run_human_tool(
            &receipts,
            id,
            &"alice".parse().unwrap(),
            &"inspect_review".parse().unwrap(),
            CancellationToken::new(),
            artifactize_core::review::log::Run::unwatched()
        )
        .await
        .unwrap_err()
        .contains("declarations changed")
    );
    assert!(
        human::submit(
            &receipts,
            &rid(id),
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    fs::remove_file(fixture.repo.join("child/index.artf")).unwrap();
    human::submit(
        &receipts,
        &rid(id),
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
}

#[tokio::test]
async fn a_submitted_signoff_settles_its_provisional_dependents_in_the_owned_run() {
    let fixture = Fixture::new(false);
    write_human(&fixture.repo.join("child"), true);
    support::declaration::write(
        fixture.repo.join("index.artf"),
        json!({
            "name":"parent",
            "evals":[
                {
                    "id":"test",
                    "title":"Dependent",
                    "profile":{"kind":"runtime","command":true_program(),"args":[]},
                    "payload":{"instruction":"Check {review}."},
                },
            ],
        })
        .to_string(),
    )
    .unwrap();
    let run = fixture.verify(returning()).await;
    assert_eq!(run.run.status().as_str(), "WAITING_HUMAN");
    let waiting = run
        .requests
        .iter()
        .find(|r| r.status() == artifactize_core::types::RequestStatus::Deferred)
        .unwrap();
    assert_eq!(
        run.requests
            .iter()
            .find(|r| r.target == "parent")
            .unwrap()
            .status()
            .as_str(),
        "PROVISIONAL",
        "a pending sign-off holds up nothing that relies on it"
    );
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &waiting.id, &"alice".parse().unwrap())
        .await
        .unwrap();
    human::submit(
        &receipts,
        &waiting.id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let observed = owned_run::terminal(&fixture.state, &run.run.id).await;
    assert_eq!(
        observed.run.status(),
        artifactize_core::types::RunStatus::Green
    );
    assert_eq!(
        store::read_run(&fixture.state, &run.run.id)
            .await
            .unwrap()
            .run
            .executions_started,
        1
    );
    let complete = fixture.verify(returning()).await;
    assert_eq!(complete.run.status().as_str(), "GREEN");
    assert_eq!(complete.run.executions_started, 0);
    assert!(
        complete
            .requests
            .iter()
            .all(|r| r.status() == artifactize_core::types::RequestStatus::Green)
    );
}

#[tokio::test]
async fn an_open_run_reads_running_again_once_its_last_signoff_is_submitted() {
    let fixture = Fixture::new(true);
    let release = fixture._root.path().join("release");
    // The sign-off holds up nothing: the root's machine eval runs on PROVISIONAL meanwhile.
    write_human(&fixture.repo.join("child"), true);
    support::declaration::write(
        fixture.repo.join("index.artf"),
        json!({
            "name":"work",
            "evals":[
                {
                    "id":"wait",
                    "title":"Machine work",
                    "profile":{
                        "kind":"runtime",
                        "command":support::os::waiting_program(fixture._root.path()),
                        "args":[support::os::path_text(&release)],
                    },
                    "payload":{"instruction":"Wait."},
                },
            ],
        })
        .to_string(),
    )
    .unwrap();
    // Started without a barrier: the machine eval runs until the test releases it.
    let context = artifactize_core::runs::Context::new(
        &fixture.repo,
        Some(&fixture.state),
        &support::os::cli(),
    )
    .unwrap();
    let id = artifactize_core::runs::start(&context, &Selection::All, &returning(), None)
        .await
        .unwrap()
        .run;
    let mut changes = artifactize_core::changes::Subscription::new(&fixture.state).await;
    let status = |view: &RunView, target: &str| {
        view.requests
            .iter()
            .find(|request| request.target == target)
            .unwrap()
            .status()
    };
    let waiting = tokio::time::timeout(support::os::patience(Duration::from_secs(30)), async {
        loop {
            let view = store::read_run(&fixture.state, id.as_str()).await.unwrap();
            if status(&view, "review").is_human_wait()
                && status(&view, "work") == artifactize_core::types::RequestStatus::Running
            {
                return view;
            }
            changes.next_state().await;
        }
    })
    .await
    .expect("the sign-off waits while the machine eval runs");
    let shown = |view: &RunView| view.run.status().as_str();
    assert_eq!(shown(&waiting), "WAITING_HUMAN");
    // It follows from the open sign-off; the saved Run stays RUNNING.
    let saved: (String, String) = rusqlite::Connection::open_with_flags(
        fixture.state.join(store::DATABASE),
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
    )
    .unwrap()
    .query_row(
        "SELECT status,json_extract(data,'$.status') FROM runs WHERE id=?",
        [id.as_str()],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )
    .unwrap();
    assert_eq!(saved, ("RUNNING".into(), "RUNNING".into()));

    let receipts = fixture.receipts().await;
    let signoff = &waiting
        .requests
        .iter()
        .find(|request| request.target == "review")
        .unwrap()
        .id;
    let alice = "alice".parse().unwrap();
    human::claim(&receipts, signoff, &alice).await.unwrap();
    human::submit(
        &receipts,
        signoff,
        &alice,
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    // Every reader shows the open Run RUNNING again while its machine eval still runs.
    let running = store::read_run(&fixture.state, id.as_str()).await.unwrap();
    assert_eq!(status(&running, "work").as_str(), "RUNNING");
    assert_eq!(shown(&running), "RUNNING");
    let listed = store::read_runs(&fixture.state, Some(&fixture.repo), 10, 0)
        .await
        .unwrap();
    assert_eq!(listed[0].status.as_str(), "RUNNING");
    let catalog = store::read_catalog(&fixture.state).await.unwrap();
    assert_eq!(catalog[0].status.as_str(), "RUNNING");

    fs::write(&release, "").unwrap();
    let ended = owned_run::terminal(&fixture.state, &id).await;
    assert_eq!(shown(&ended), "GREEN");
}

#[tokio::test]
async fn cross_repo_waiters_share_claim_tools_and_one_published_result() {
    let fixture = Fixture::new(true);
    let original = fixture.cli_verify();
    let mut other = Fixture::new(true);
    // The follower owns its Run in the shared state before its own repository drops.
    other.state = fixture.state.clone();
    other._root.track(&other.state, &other.repo);
    let run = support::runs::record(
        &other.repo,
        Some(&fixture.state),
        &Selection::All,
        &returning(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(run.requests[0].status().as_str(), "DEFERRED");
    let receipts = fixture.receipts().await;
    let follower = &run.requests[0].id;
    let owner = original["requests"][0]["id"].as_str().unwrap();
    assert_eq!(
        human::claim(&receipts, &rid(follower), &"alice".parse().unwrap())
            .await
            .unwrap()
            .request_id
            .as_str(),
        owner
    );
    assert!(
        human::claim(&receipts, &rid(owner), &"bob".parse().unwrap())
            .await
            .is_err()
    );
    fs::write(other.repo.join("fingerprint"), "different-repo-input\n").unwrap();
    let result = human::run_human_tool(
        &receipts,
        follower,
        &"alice".parse().unwrap(),
        &"inspect_review".parse().unwrap(),
        CancellationToken::new(),
        artifactize_core::review::log::Run::unwatched(),
    )
    .await
    .unwrap();
    assert_eq!(
        serde_json::to_value(result).unwrap()["content"][0]["text"],
        "human-v1\n"
    );
    human::submit(
        &receipts,
        &rid(follower),
        &"alice".parse().unwrap(),
        &json!({"verdict":"RED","reason":"Needs work"}),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert!(
        human::submit(
            &receipts,
            &rid(owner),
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    // The owned worker, not the observer, must save the follower's completed Run.
    let settled = owned_run::terminal(&fixture.state, &run.run.id).await;
    assert_eq!(settled.run.status().as_str(), "RED");
    assert_eq!(settled.requests[0].status().as_str(), "RED");
    assert_eq!(
        store::read_run(&fixture.state, &run.run.id)
            .await
            .unwrap()
            .requests[0]
            .status()
            .as_str(),
        "RED"
    );
    fs::write(other.repo.join("fingerprint"), "human-v1\n").unwrap();
    let completed = support::runs::record(
        &other.repo,
        Some(&fixture.state),
        &Selection::All,
        &returning(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(completed.run.status().as_str(), "RED");
    assert_eq!(
        completed.requests[0]
            .result()
            .as_ref()
            .unwrap()
            .owner_fields()["reason"],
        "Needs work"
    );
    assert_eq!(
        completed.requests[0].execution_id.as_deref(),
        original["requests"][0]["executionId"].as_str()
    );
    let history = artifactize_core::cache::list(&fixture.state, true)
        .await
        .unwrap();
    assert_eq!(history.len(), 1, "the joined review publishes one result");
    assert_eq!(
        history[0].execution_id,
        completed.requests[0].execution_id.clone().unwrap()
    );
}

#[tokio::test]
async fn only_the_claimant_unclaims_a_waiting_request_including_through_followers() {
    let fixture = Fixture::new(true);
    let original = fixture.cli_verify();
    let owner = original["requests"][0]["id"].as_str().unwrap();
    let mut other = Fixture::new(true);
    // The follower owns its Run in the shared state before its own repository drops.
    other.state = fixture.state.clone();
    other._root.track(&other.state, &other.repo);
    let run = support::runs::record(
        &other.repo,
        Some(&fixture.state),
        &Selection::All,
        &returning(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let follower = &run.requests[0].id;
    let receipts = fixture.receipts().await;
    assert!(
        human::unclaim(&receipts, &rid(owner), &"alice".parse().unwrap())
            .await
            .unwrap_err()
            .contains("claimant")
    );
    let claim = human::claim(&receipts, &rid(owner), &"alice".parse().unwrap())
        .await
        .unwrap();
    assert!(
        "".parse::<artifactize_core::types::ReviewerId>().is_err(),
        "an empty reviewer must be rejected at the input edge"
    );
    for id in [owner, follower.as_str()] {
        assert!(
            human::unclaim(&receipts, &rid(id), &"bob".parse().unwrap())
                .await
                .is_err()
        );
    }
    // A follower forwards the release to its original request, like a claim.
    let released = human::unclaim(&receipts, &rid(follower), &"alice".parse().unwrap())
        .await
        .unwrap();
    assert_eq!(
        (released.request_id.as_str(), released.claimed_at),
        (owner, claim.claimed_at)
    );
    assert!(
        human::unclaim(&receipts, &rid(owner), &"alice".parse().unwrap())
            .await
            .is_err()
    );
    assert!(
        human::submit(
            &receipts,
            &rid(owner),
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    assert_eq!(
        human::claim(&receipts, &rid(follower), &"bob".parse().unwrap())
            .await
            .unwrap()
            .request_id
            .as_str(),
        owner
    );
    assert_eq!(
        store::read_request(&fixture.state, owner)
            .await
            .unwrap()
            .claim
            .unwrap()
            .reviewer,
        "bob"
    );
    human::submit(
        &receipts,
        &rid(owner),
        &"bob".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    for id in [owner, follower.as_str()] {
        assert!(
            human::unclaim(&receipts, &rid(id), &"bob".parse().unwrap())
                .await
                .unwrap_err()
                .contains("not waiting")
        );
    }
}

#[tokio::test]
async fn concurrent_submissions_commit_only_once() {
    let fixture = Fixture::new(true);
    let run = fixture.verify(returning()).await;
    let id = &run.requests[0].id;
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &rid(id), &"alice".parse().unwrap())
        .await
        .unwrap();
    let result = green();
    let reviewer = "alice".parse().unwrap();
    let request = rid(id);
    let (first, second) = tokio::join!(
        human::submit(
            &receipts,
            &request,
            &reviewer,
            &result,
            CancellationToken::new()
        ),
        human::submit(
            &receipts,
            &request,
            &reviewer,
            &result,
            CancellationToken::new()
        ),
    );
    assert_ne!(first.is_ok(), second.is_ok());
}

#[tokio::test]
async fn forced_human_checks_fingerprint_without_replacing_cache() {
    let fixture = Fixture::new(true);
    let run = fixture.verify(returning()).await;
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &run.requests[0].id, &"alice".parse().unwrap())
        .await
        .unwrap();
    human::submit(
        &receipts,
        &run.requests[0].id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let forced = fixture
        .verify(VerifyOptions {
            force: true,
            ..returning()
        })
        .await;
    assert_eq!(forced.requests[0].status().as_str(), "DEFERRED");
    human::claim(&receipts, &forced.requests[0].id, &"alice".parse().unwrap())
        .await
        .unwrap();
    fs::write(fixture.repo.join("fingerprint"), "changed\n").unwrap();
    assert!(
        human::submit(
            &receipts,
            &forced.requests[0].id,
            &"alice".parse().unwrap(),
            &green(),
            CancellationToken::new()
        )
        .await
        .is_err()
    );
    let cached = artifactize_core::cache::show(
        &fixture.state,
        run.requests[0].key.as_deref().unwrap(),
        false,
    )
    .await
    .unwrap()
    .pop()
    .unwrap();
    assert_eq!(cached.provenance.request_id, run.requests[0].id);
    assert_eq!(cached.status().as_str(), "GREEN");
}

#[tokio::test]
async fn omitted_fingerprint_reuses_human_signoff_and_rechecks_changed_inputs() {
    let fixture = Fixture::new(false);
    let path = fixture.repo.join("index.artf");
    let mut declaration: Value = support::declaration::read(fs::read(&path).unwrap()).unwrap();
    declaration.as_object_mut().unwrap().remove("fingerprint");
    support::declaration::write(&path, declaration.to_string()).unwrap();
    let run = fixture.verify(returning()).await;
    assert!(
        run.requests[0]
            .fingerprint
            .as_ref()
            .unwrap()
            .starts_with("artifactsum:")
    );
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &run.requests[0].id, &"alice".parse().unwrap())
        .await
        .unwrap();
    human::submit(
        &receipts,
        &run.requests[0].id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let next = fixture.verify(returning()).await;
    assert_eq!(next.requests[0].status().as_str(), "GREEN");
    assert_eq!(next.requests[0].execution_id, run.requests[0].execution_id);
    fs::write(fixture.repo.join("fingerprint"), "human-v2\n").unwrap();
    let changed = fixture.verify(returning()).await;
    assert_eq!(changed.requests[0].status().as_str(), "DEFERRED");
    assert_ne!(changed.requests[0].key, run.requests[0].key);
    human::claim(
        &receipts,
        &changed.requests[0].id,
        &"alice".parse().unwrap(),
    )
    .await
    .unwrap();
    fs::write(fixture.repo.join("fingerprint"), "human-v3\n").unwrap();
    let error = human::submit(
        &receipts,
        &changed.requests[0].id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap_err();
    assert!(
        error.contains("Fingerprint changed during review"),
        "{error}"
    );
}

#[tokio::test]
async fn fingerprint_false_results_are_not_reused_by_a_new_verify() {
    let fixture = Fixture::new(false);
    let run = fixture.verify(returning()).await;
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &run.requests[0].id, &"alice".parse().unwrap())
        .await
        .unwrap();
    human::submit(
        &receipts,
        &run.requests[0].id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let next = fixture.verify(returning()).await;
    assert_eq!(next.requests[0].status().as_str(), "DEFERRED");
    assert_ne!(next.requests[0].execution_id, run.requests[0].execution_id);
}

#[tokio::test]
async fn human_forwarding_settlement_and_status_are_scoped_to_the_definition() {
    let fixture = Fixture::new(true);
    let path = fixture.repo.join("index.artf");
    let mut declaration: Value = support::declaration::read(fs::read(&path).unwrap()).unwrap();
    let mut same = declaration["evals"][0].clone();
    same["id"] = json!("same");
    same["title"] = json!("Same criteria");
    let mut different = same.clone();
    different["id"] = json!("zz-different");
    different["pass_schema"]["properties"]["approved"]["const"] = json!(false);
    declaration["evals"]
        .as_array_mut()
        .unwrap()
        .extend([same, different]);
    support::declaration::write(path, declaration.to_string()).unwrap();
    let run = fixture.verify(returning()).await;
    assert_eq!(run.requests[0].execution_id, run.requests[1].execution_id);
    assert_eq!(run.requests[0].eval_def_hash, run.requests[1].eval_def_hash);
    assert_ne!(run.requests[0].execution_id, run.requests[2].execution_id);
    assert_ne!(run.requests[0].eval_def_hash, run.requests[2].eval_def_hash);
    let receipts = fixture.receipts().await;
    let claim = human::claim(&receipts, &run.requests[1].id, &"alice".parse().unwrap())
        .await
        .unwrap();
    assert_eq!(claim.request_id, run.requests[0].id);
    human::submit(
        &receipts,
        &run.requests[1].id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let saved = store::read_run(&fixture.state, &run.run.id).await.unwrap();
    assert_eq!(saved.requests[0].status().as_str(), "GREEN");
    assert_eq!(saved.requests[1].status().as_str(), "GREEN");
    assert_eq!(saved.requests[2].status().as_str(), "DEFERRED");
    let status = project::status(
        &fixture.repo,
        Some(&fixture.state),
        &Selection::All,
        &returning(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(status.counts.reuse, 2);
    assert_eq!(status.counts.wait, 1);
    assert_eq!(status.evals[2].state, project::EvalCondition::Deferred);
    assert_eq!(
        human::claim(&receipts, &run.requests[2].id, &"bob".parse().unwrap())
            .await
            .unwrap()
            .request_id
            .as_str(),
        run.requests[2].id.as_str()
    );
    human::submit(
        &receipts,
        &run.requests[2].id,
        &"bob".parse().unwrap(),
        &json!({"verdict":"RED","reason":"Different review"}),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    let reused = fixture.verify(returning()).await;
    assert_eq!(reused.requests[0].status().as_str(), "GREEN");
    assert_eq!(reused.requests[1].status().as_str(), "GREEN");
    assert_eq!(reused.requests[2].status().as_str(), "RED");
    for (new, original) in reused.requests.iter().zip(&run.requests) {
        assert_eq!(new.execution_id, original.execution_id);
        assert_eq!(
            new.provenance.as_ref().unwrap().eval_def_hash,
            original.eval_def_hash
        );
    }
    assert_eq!(
        artifactize_core::cache::list(&fixture.state, true)
            .await
            .unwrap()
            .len(),
        2,
        "the two distinct definitions publish independent review evidence"
    );
    let status = project::status(
        &fixture.repo,
        Some(&fixture.state),
        &Selection::All,
        &returning(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(status.counts.reuse, 3);
    assert_eq!(status.evals[2].state, project::EvalCondition::Red);
}

#[tokio::test]
async fn a_variant_human_signoff_reconnects_and_its_record_names_the_variant() {
    let fixture = Fixture::new(true);
    let path = fixture.repo.join("index.artf");
    let mut declaration: Value = support::declaration::read(fs::read(&path).unwrap()).unwrap();
    declaration["evals"][0]["profile_variants"] = json!({"lead":{"kind":"human"}});
    support::declaration::write(&path, declaration.to_string()).unwrap();
    let run = fixture
        .verify(VerifyOptions {
            profile: Some(project::selection::ProfileSelection::Named(
                "lead".parse().unwrap(),
            )),
            ..returning()
        })
        .await;
    let request = &run.requests[0];
    assert_eq!(request.status().as_str(), "DEFERRED");
    assert_eq!(request.options.variant.as_deref(), Some("lead"));
    let receipts = fixture.receipts().await;
    human::claim(&receipts, &request.id, &"alice".parse().unwrap())
        .await
        .unwrap();
    let settled = human::submit(
        &receipts,
        &request.id,
        &"alice".parse().unwrap(),
        &green(),
        CancellationToken::new(),
    )
    .await
    .unwrap();
    assert_eq!(settled.status().as_str(), "GREEN");
    // The declared profile reuses the sign-off the variant produced.
    let reused = fixture.verify(returning()).await;
    assert_eq!(reused.requests[0].status().as_str(), "GREEN");
    assert_eq!(reused.requests[0].execution_id, request.execution_id);
    assert_eq!(reused.requests[0].options.variant.as_deref(), Some("lead"));
    assert_eq!(reused.requests[0].reviewer.as_deref(), Some("alice"));
}