a3s-code-core 9.0.0

A3S Code Core - Embeddable AI agent library with tool execution
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
use a3s_code_core::config::{CodeConfig, ModelConfig, ModelModalities, ProviderConfig};
use a3s_code_core::llm::{ContentBlock, LlmClient, LlmResponse, Message, StreamEvent, TokenUsage};
use a3s_code_core::store::{MemorySessionStore, SessionStore};
use a3s_code_core::{
    Agent, AgentProtocolChangeSetRequestV1, AgentProtocolChangeSetV1, AgentProtocolCommandV1,
    AgentProtocolEventPageRequestV1, AgentProtocolHarness, AgentProtocolHarnessError,
    AgentProtocolRunIdentityV1, AgentProtocolRunRecoverV1, AgentProtocolRunStartV1,
    AgentProtocolRunStateV1, ModelInputSnapshotV1, ModelUsageSnapshotV1, PlanningMode,
    RunCapabilitySnapshotV1, SessionOptions, ToolRequestOriginV1, ToolRequestSnapshotV1,
    AGENT_PROTOCOL_V1,
};
use base64::Engine as _;
use std::collections::HashMap;
use std::process::Command;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

#[derive(Clone)]
struct StaticStreamingClient;

#[derive(Clone)]
struct ScriptedStreamingClient {
    responses: Arc<std::sync::Mutex<Vec<LlmResponse>>>,
}

impl ScriptedStreamingClient {
    fn new(mut responses: Vec<LlmResponse>) -> Self {
        responses.reverse();
        Self {
            responses: Arc::new(std::sync::Mutex::new(responses)),
        }
    }

    fn next(&self) -> anyhow::Result<LlmResponse> {
        self.responses
            .lock()
            .unwrap()
            .pop()
            .ok_or_else(|| anyhow::anyhow!("scripted Harness client exhausted"))
    }
}

#[async_trait::async_trait]
impl LlmClient for StaticStreamingClient {
    async fn complete(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        _tools: &[a3s_code_core::llm::ToolDefinition],
    ) -> anyhow::Result<LlmResponse> {
        Ok(response())
    }

    async fn complete_streaming(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        _tools: &[a3s_code_core::llm::ToolDefinition],
        _cancel_token: CancellationToken,
    ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
        let (sender, receiver) = mpsc::channel(4);
        tokio::spawn(async move {
            let _ = sender.send(StreamEvent::TextDelta("done".into())).await;
            let _ = sender.send(StreamEvent::Done(response())).await;
        });
        Ok(receiver)
    }
}

#[async_trait::async_trait]
impl LlmClient for ScriptedStreamingClient {
    async fn complete(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        _tools: &[a3s_code_core::llm::ToolDefinition],
    ) -> anyhow::Result<LlmResponse> {
        self.next()
    }

    async fn complete_streaming(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        _tools: &[a3s_code_core::llm::ToolDefinition],
        _cancel_token: CancellationToken,
    ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
        let response = self.next()?;
        let (sender, receiver) = mpsc::channel(4);
        tokio::spawn(async move {
            let text = response.text();
            if !text.is_empty() {
                let _ = sender.send(StreamEvent::TextDelta(text)).await;
            }
            let _ = sender.send(StreamEvent::Done(response)).await;
        });
        Ok(receiver)
    }
}

fn response() -> LlmResponse {
    LlmResponse {
        message: Message {
            role: "assistant".into(),
            content: vec![ContentBlock::Text {
                text: "done".into(),
            }],
            reasoning_content: None,
            transcript_text: None,
            transcript_visibility: Default::default(),
        },
        usage: TokenUsage {
            prompt_tokens: 1,
            completion_tokens: 1,
            total_tokens: 2,
            cache_read_tokens: None,
            cache_write_tokens: None,
        },
        stop_reason: Some("end_turn".into()),
        token_logprobs: Vec::new(),
        meta: None,
    }
}

fn tool_response(name: &str, input: serde_json::Value) -> LlmResponse {
    LlmResponse {
        message: Message {
            role: "assistant".into(),
            content: vec![ContentBlock::ToolUse {
                id: "tool-write-1".into(),
                name: name.into(),
                input,
            }],
            reasoning_content: None,
            transcript_text: None,
            transcript_visibility: Default::default(),
        },
        usage: TokenUsage {
            prompt_tokens: 1,
            completion_tokens: 1,
            total_tokens: 2,
            cache_read_tokens: None,
            cache_write_tokens: None,
        },
        stop_reason: Some("tool_use".into()),
        token_logprobs: Vec::new(),
        meta: None,
    }
}

fn git(workspace: &std::path::Path, args: &[&str]) {
    let output = Command::new("git")
        .args(args)
        .current_dir(workspace)
        .output()
        .expect("run Git fixture command");
    assert!(
        output.status.success(),
        "Git fixture command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn initialize_git_workspace(workspace: &std::path::Path) {
    git(workspace, &["init"]);
    git(workspace, &["config", "user.name", "A3S Test"]);
    git(workspace, &["config", "user.email", "test@a3s.invalid"]);
    std::fs::write(workspace.join("seed.txt"), "seed\n").expect("write seed file");
    git(workspace, &["add", "seed.txt"]);
    git(workspace, &["commit", "-m", "seed"]);
}

fn offline_config() -> CodeConfig {
    CodeConfig {
        default_model: Some("fixture/static".into()),
        providers: vec![ProviderConfig {
            name: "fixture".into(),
            api_key: Some("offline".into()),
            base_url: None,
            headers: HashMap::new(),
            session_id_header: None,
            models: vec![ModelConfig {
                id: "static".into(),
                name: "Static".into(),
                family: "fixture".into(),
                api_key: None,
                base_url: None,
                headers: HashMap::new(),
                session_id_header: None,
                attachment: false,
                reasoning: false,
                tool_call: true,
                temperature: true,
                release_date: None,
                modalities: ModelModalities::default(),
                cost: Default::default(),
                limit: Default::default(),
            }],
        }],
        ..Default::default()
    }
}

fn manifest() -> a3s_code_core::release::AgentReleaseManifest {
    a3s_code_core::release::AgentReleaseManifest::parse(include_str!(
        "../../fixtures/agent-release-contract/.a3s/asset.acl"
    ))
    .unwrap()
}

fn start(release_identity: &str, session_id: &str, run_id: &str) -> AgentProtocolCommandV1 {
    AgentProtocolCommandV1::Start {
        request: AgentProtocolRunStartV1 {
            schema: AgentProtocolRunStartV1::SCHEMA.into(),
            request_id: format!("{run_id}:start"),
            identity: AgentProtocolRunIdentityV1 {
                schema: AgentProtocolRunIdentityV1::SCHEMA.into(),
                protocol: AGENT_PROTOCOL_V1.into(),
                agent_release_identity: release_identity.into(),
                session_id: session_id.into(),
                run_id: run_id.into(),
            },
            prompt: format!("execute {run_id}"),
        },
    }
}

async fn wait_for_terminal(
    harness: &AgentProtocolHarness,
    command: &AgentProtocolCommandV1,
) -> a3s_code_core::AgentProtocolEventPageV1 {
    tokio::time::timeout(std::time::Duration::from_secs(2), async {
        loop {
            let page = harness
                .event_page(&AgentProtocolEventPageRequestV1 {
                    schema: AgentProtocolEventPageRequestV1::SCHEMA.into(),
                    identity: command.identity().clone(),
                    after_event_sequence: None,
                    limit: 64,
                })
                .await
                .unwrap();
            if page.state.is_terminal() {
                break page;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("detached Harness run must terminate")
}

fn assert_unverified_mutation(page: &a3s_code_core::AgentProtocolEventPageV1) {
    assert_eq!(page.state, AgentProtocolRunStateV1::Failed);
    let message = page
        .events
        .iter()
        .find(|record| record.event.event_type == "error")
        .and_then(|record| record.event.payload["message"].as_str())
        .unwrap_or("");
    assert!(
        message.contains("completion gate:") && message.contains("no bound Passed verification"),
        "{message}"
    );
}

async fn wait_for_change_set(
    harness: &AgentProtocolHarness,
    command: &AgentProtocolCommandV1,
) -> AgentProtocolChangeSetV1 {
    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        loop {
            match harness
                .change_set(&AgentProtocolChangeSetRequestV1 {
                    schema: AgentProtocolChangeSetRequestV1::SCHEMA.into(),
                    identity: command.identity().clone(),
                })
                .await
            {
                Ok(change_set) => break change_set,
                Err(AgentProtocolHarnessError::Host(
                    a3s_code_core::AgentProtocolHostError::ChangeSetPending,
                )) => tokio::task::yield_now().await,
                Err(error) => panic!("unexpected change-set error: {error}"),
            }
        }
    })
    .await
    .expect("change set must be captured after terminal state")
}

#[tokio::test]
async fn harness_multiplexes_sessions_through_code_owned_hosts() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let identity = manifest.artifact().digest().to_string();
    let agent = Arc::new(Agent::from_config(offline_config()).await.unwrap());
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::clone(&agent),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)));
    let first = start(&identity, "conversation-one", "execution-one");
    let second = start(&identity, "conversation-two", "execution-two");

    harness.execute(&first).await.unwrap();
    harness.execute(&second).await.unwrap();
    assert_eq!(
        wait_for_terminal(&harness, &first)
            .await
            .identity
            .session_id,
        "conversation-one"
    );
    assert_eq!(
        wait_for_terminal(&harness, &second)
            .await
            .identity
            .session_id,
        "conversation-two"
    );
    assert_eq!(harness.session_count().await, 2);
    assert_eq!(agent.list_sessions().await.len(), 2);

    harness.close().await;
    assert!(agent.is_closed());
}

#[tokio::test]
async fn harness_replay_binds_redacted_capability_and_model_input_evidence() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let identity = manifest.artifact().digest().to_string();
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(
        SessionOptions::new()
            .with_planning_mode(PlanningMode::Disabled)
            .with_llm_client(Arc::new(StaticStreamingClient)),
    );
    let mut command = start(&identity, "evidence-conversation", "evidence-execution");
    let AgentProtocolCommandV1::Start { request } = &mut command else {
        unreachable!()
    };
    request.prompt = "top-secret Harness prompt".to_string();

    let receipt = harness.execute(&command).await.unwrap();
    assert!(!receipt.replayed);
    let first_page = wait_for_terminal(&harness, &command).await;
    let capability = first_page
        .events
        .iter()
        .find(|record| record.event.event_type == "run_capability_bound")
        .expect("Harness run must retain a capability snapshot");
    let capability: RunCapabilitySnapshotV1 =
        serde_json::from_value(capability.event.payload["snapshot"].clone()).unwrap();
    capability.validate().unwrap();
    let input = first_page
        .events
        .iter()
        .find(|record| record.event.event_type == "model_input_bound")
        .expect("Harness run must retain a model-input snapshot");
    let input: ModelInputSnapshotV1 =
        serde_json::from_value(input.event.payload["snapshot"].clone()).unwrap();
    input.validate_against(&capability).unwrap();
    assert_eq!(input.call_sequence, 1);
    let usage_record = first_page
        .events
        .iter()
        .find(|record| record.event.event_type == "model_usage_bound")
        .expect("Harness run must retain a model-usage snapshot");
    let usage: ModelUsageSnapshotV1 =
        serde_json::from_value(usage_record.event.payload["snapshot"].clone()).unwrap();
    usage.validate_against(&input).unwrap();
    assert_eq!(usage.reported_total_tokens, 2);
    let input_position = first_page
        .events
        .iter()
        .position(|record| record.event.event_type == "model_input_bound")
        .unwrap();
    let usage_position = first_page
        .events
        .iter()
        .position(|record| record.event.event_type == "model_usage_bound")
        .unwrap();
    let terminal_position = first_page
        .events
        .iter()
        .position(|record| record.event.event_type == "agent_end")
        .unwrap();
    assert!(input_position < usage_position && usage_position < terminal_position);
    let evidence_json =
        serde_json::to_string(&(capability.clone(), input.clone(), usage.clone())).unwrap();
    assert!(!evidence_json.contains("top-secret Harness prompt"));

    let replay = harness.execute(&command).await.unwrap();
    assert!(replay.replayed);
    let replay_page = wait_for_terminal(&harness, &command).await;
    let replay_capability: RunCapabilitySnapshotV1 = serde_json::from_value(
        replay_page
            .events
            .iter()
            .find(|record| record.event.event_type == "run_capability_bound")
            .unwrap()
            .event
            .payload["snapshot"]
            .clone(),
    )
    .unwrap();
    let replay_input: ModelInputSnapshotV1 = serde_json::from_value(
        replay_page
            .events
            .iter()
            .find(|record| record.event.event_type == "model_input_bound")
            .unwrap()
            .event
            .payload["snapshot"]
            .clone(),
    )
    .unwrap();
    let replay_usage: ModelUsageSnapshotV1 = serde_json::from_value(
        replay_page
            .events
            .iter()
            .find(|record| record.event.event_type == "model_usage_bound")
            .unwrap()
            .event
            .payload["snapshot"]
            .clone(),
    )
    .unwrap();
    assert_eq!(replay_capability, capability);
    assert_eq!(replay_input, input);
    assert_eq!(replay_usage, usage);

    harness.close().await;
}

#[tokio::test]
async fn harness_replay_binds_tool_requests_without_argument_plaintext() {
    let workspace = tempfile::tempdir().unwrap();
    initialize_git_workspace(workspace.path());
    let manifest = manifest();
    let release_identity = manifest.artifact().digest().to_string();
    let arguments = serde_json::json!({
        "file_path": "remote.txt",
        "content": "private Tool request content\n"
    });
    let client =
        ScriptedStreamingClient::new(vec![tool_response("write", arguments.clone()), response()]);
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(
        SessionOptions::new()
            .with_planning_mode(PlanningMode::Disabled)
            .with_confirmation_manager(Arc::new(a3s_code_core::hitl::AutoApproveConfirmation))
            .with_llm_client(Arc::new(client)),
    );
    let command = start(
        &release_identity,
        "tool-evidence-conversation",
        "tool-evidence-execution",
    );

    harness.execute(&command).await.unwrap();
    let page = wait_for_terminal(&harness, &command).await;
    assert_unverified_mutation(&page);
    let request_record = page
        .events
        .iter()
        .find(|record| record.event.event_type == "tool_request_bound")
        .expect("Harness run must retain Tool-request evidence");
    let tool_id = request_record.event.payload["tool_id"].as_str().unwrap();
    let tool_name = request_record.event.payload["tool_name"].as_str().unwrap();
    let snapshot: ToolRequestSnapshotV1 =
        serde_json::from_value(request_record.event.payload["snapshot"].clone()).unwrap();
    snapshot
        .validate_against(tool_id, tool_name, &arguments, ToolRequestOriginV1::Agent)
        .unwrap();
    assert_eq!(tool_id, "tool-write-1");
    assert_eq!(tool_name, "write");
    assert!(!serde_json::to_string(&snapshot)
        .unwrap()
        .contains("private Tool request content"));
    let request_position = page
        .events
        .iter()
        .position(|record| record.event.event_type == "tool_request_bound")
        .unwrap();
    let execution_position = page
        .events
        .iter()
        .position(|record| record.event.event_type == "tool_execution_start")
        .unwrap();
    assert!(request_position < execution_position);

    let replay = harness.execute(&command).await.unwrap();
    assert!(replay.replayed);
    let replay_page = wait_for_terminal(&harness, &command).await;
    let replay_snapshot: ToolRequestSnapshotV1 = serde_json::from_value(
        replay_page
            .events
            .iter()
            .find(|record| record.event.event_type == "tool_request_bound")
            .unwrap()
            .event
            .payload["snapshot"]
            .clone(),
    )
    .unwrap();
    assert_eq!(replay_snapshot, snapshot);

    harness.close().await;
}

#[tokio::test]
async fn harness_isolates_sessions_and_exports_one_digest_bound_run_patch() {
    let workspace = tempfile::tempdir().unwrap();
    initialize_git_workspace(workspace.path());
    let manifest = manifest();
    let release_identity = manifest.artifact().digest().to_string();
    let client = ScriptedStreamingClient::new(vec![
        tool_response(
            "write",
            serde_json::json!({
                "file_path": "remote.txt",
                "content": "remote change\n"
            }),
        ),
        response(),
    ]);
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(
        SessionOptions::new()
            .with_planning_mode(PlanningMode::Disabled)
            .with_confirmation_manager(Arc::new(a3s_code_core::hitl::AutoApproveConfirmation))
            .with_llm_client(Arc::new(client)),
    );
    let command = start(
        &release_identity,
        "changes-conversation",
        "changes-execution",
    );

    harness.execute(&command).await.unwrap();
    assert_unverified_mutation(&wait_for_terminal(&harness, &command).await);
    let change_set = wait_for_change_set(&harness, &command).await;
    change_set.validate().unwrap();
    let patch = base64::engine::general_purpose::STANDARD
        .decode(&change_set.patch_base64)
        .unwrap();
    let patch = String::from_utf8(patch).unwrap();
    assert!(
        patch.contains("diff --git a/remote.txt b/remote.txt"),
        "{patch}"
    );
    assert!(patch.contains("+remote change"), "{patch}");
    assert_eq!(change_set.patch_bytes as usize, patch.len());
    assert!(!workspace.path().join("remote.txt").exists());

    harness.close().await;
    git(workspace.path(), &["status", "--porcelain"]);
}

#[tokio::test]
async fn harness_resumes_the_code_store_before_replaying_a_start_after_restart() {
    let workspace = tempfile::tempdir().unwrap();
    initialize_git_workspace(workspace.path());
    let store = Arc::new(MemorySessionStore::new());
    let release = manifest();
    let release_identity = release.artifact().digest().to_string();
    let command = start(
        &release_identity,
        "durable-conversation",
        "durable-execution",
    );
    let first_client = ScriptedStreamingClient::new(vec![
        tool_response(
            "write",
            serde_json::json!({
                "file_path": "remote.txt",
                "content": "survives restart\n"
            }),
        ),
        response(),
    ]);

    let first_agent = Arc::new(Agent::from_config(offline_config()).await.unwrap());
    let first = AgentProtocolHarness::new(
        release.clone(),
        first_agent,
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(
        SessionOptions::new()
            .with_session_store(store.clone() as Arc<dyn SessionStore>)
            .with_planning_mode(PlanningMode::Disabled)
            .with_confirmation_manager(Arc::new(a3s_code_core::hitl::AutoApproveConfirmation))
            .with_llm_client(Arc::new(first_client)),
    );
    let receipt = first.execute(&command).await.unwrap();
    assert!(!receipt.replayed);
    assert_unverified_mutation(&wait_for_terminal(&first, &command).await);
    wait_for_change_set(&first, &command).await;
    tokio::time::timeout(std::time::Duration::from_secs(2), async {
        loop {
            if store
                .load_snapshot("durable-conversation")
                .await
                .unwrap()
                .is_some_and(|snapshot| {
                    snapshot.run_records.iter().any(|record| {
                        record.snapshot.id == "durable-execution"
                            && record.snapshot.status == a3s_code_core::RunStatus::Failed
                            && record.snapshot.workspace_change_set.is_some()
                    })
                })
            {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("terminal run must be persisted before restart");
    first.close().await;
    git(workspace.path(), &["gc", "--prune=now"]);

    let second_agent = Arc::new(Agent::from_config(offline_config()).await.unwrap());
    let second_client = ScriptedStreamingClient::new(vec![
        tool_response(
            "write",
            serde_json::json!({
                "file_path": "follow-up.txt",
                "content": "second run\n"
            }),
        ),
        response(),
    ]);
    let second = AgentProtocolHarness::new(
        release,
        second_agent,
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(
        SessionOptions::new()
            .with_session_store(store as Arc<dyn SessionStore>)
            .with_planning_mode(PlanningMode::Disabled)
            .with_confirmation_manager(Arc::new(a3s_code_core::hitl::AutoApproveConfirmation))
            .with_llm_client(Arc::new(second_client)),
    );
    let replay = second.execute(&command).await.unwrap();
    assert!(replay.replayed);
    assert_eq!(replay.state, AgentProtocolRunStateV1::Failed);
    assert_eq!(second.session_count().await, 1);

    let follow_up = start(
        &release_identity,
        "durable-conversation",
        "durable-execution-follow-up",
    );
    second.execute(&follow_up).await.unwrap();
    assert_unverified_mutation(&wait_for_terminal(&second, &follow_up).await);
    let change_set = wait_for_change_set(&second, &follow_up).await;
    let patch = base64::engine::general_purpose::STANDARD
        .decode(change_set.patch_base64)
        .unwrap();
    let patch = String::from_utf8(patch).unwrap();
    assert!(patch.contains("diff --git a/follow-up.txt b/follow-up.txt"));
    assert!(!patch.contains("remote.txt"));
    assert!(!workspace.path().join("remote.txt").exists());
    assert!(!workspace.path().join("follow-up.txt").exists());
    second.close().await;
}

#[tokio::test]
async fn harness_does_not_create_a_session_for_an_unknown_observation() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let command = start(
        manifest.artifact().digest(),
        "missing-conversation",
        "missing-execution",
    );
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap();
    let error = harness
        .event_page(&AgentProtocolEventPageRequestV1 {
            schema: AgentProtocolEventPageRequestV1::SCHEMA.into(),
            identity: command.identity().clone(),
            after_event_sequence: None,
            limit: 1,
        })
        .await
        .expect_err("an unknown observation must not allocate a session");

    assert!(matches!(error, AgentProtocolHarnessError::SessionNotFound));
    assert_eq!(harness.session_count().await, 0);
    harness.close().await;
}

#[tokio::test]
async fn harness_does_not_create_a_session_for_missing_recovery() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let release_identity = manifest.artifact().digest().to_string();
    let identity = AgentProtocolRunIdentityV1 {
        schema: AgentProtocolRunIdentityV1::SCHEMA.into(),
        protocol: AGENT_PROTOCOL_V1.into(),
        agent_release_identity: release_identity,
        session_id: "missing-recovery-session".into(),
        run_id: "recovered-run".into(),
    };
    let command = AgentProtocolCommandV1::Recover {
        request: AgentProtocolRunRecoverV1 {
            schema: AgentProtocolRunRecoverV1::SCHEMA.into(),
            request_id: "missing-recovery:request".into(),
            identity,
            checkpoint_run_id: "checkpoint-run".into(),
        },
    };
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap();

    let error = harness
        .execute(&command)
        .await
        .expect_err("missing recovery must fail before creating a Session");
    assert!(matches!(error, AgentProtocolHarnessError::SessionNotFound));
    assert_eq!(harness.session_count().await, 0);
    harness.close().await;
}

#[tokio::test]
async fn harness_fails_closed_at_its_retained_session_limit() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let release_identity = manifest.artifact().digest().to_string();
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)))
    .with_max_sessions(1)
    .unwrap();
    harness
        .execute(&start(
            &release_identity,
            "first-conversation",
            "first-execution",
        ))
        .await
        .unwrap();

    let error = harness
        .execute(&start(
            &release_identity,
            "second-conversation",
            "second-execution",
        ))
        .await
        .expect_err("a second retained conversation must exceed the exact limit");
    assert!(matches!(error, AgentProtocolHarnessError::SessionCapacity));
    assert_eq!(harness.session_count().await, 1);
    harness.close().await;
}

#[test]
fn harness_is_send_and_sync() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<AgentProtocolHarness>();
}

#[tokio::test]
async fn harness_rejects_empty_workspace_before_session_admission() {
    let error = AgentProtocolHarness::new(
        manifest(),
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        "   ",
    )
    .expect_err("an empty workspace must fail closed");
    assert!(matches!(error, AgentProtocolHarnessError::Workspace(_)));
}

#[tokio::test]
async fn harness_exposes_release_metadata_and_debug_fields() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let digest = manifest.artifact().digest().to_string();
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_max_sessions(8)
    .unwrap();
    assert_eq!(harness.agent_release_identity(), digest);
    assert_eq!(harness.max_sessions(), 8);
    assert!(!harness.is_closed());
    assert_eq!(harness.manifest().protocol(), AGENT_PROTOCOL_V1);
    let debug = format!("{harness:?}");
    assert!(debug.contains("AgentProtocolHarness"));
    assert!(debug.contains("workspace"));
    harness.close().await;
    assert!(harness.is_closed());
    // Second close is a no-op.
    harness.close().await;
}

#[tokio::test]
async fn harness_rejects_zero_session_capacity() {
    let workspace = tempfile::tempdir().unwrap();
    let error = AgentProtocolHarness::new(
        manifest(),
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_max_sessions(0)
    .expect_err("zero capacity must fail closed");
    assert!(matches!(error, AgentProtocolHarnessError::SessionCapacity));
}

#[tokio::test]
async fn competing_session_admission_reuses_the_same_host_entry() {
    let workspace = tempfile::tempdir().unwrap();
    let harness = Arc::new(
        AgentProtocolHarness::new(
            manifest(),
            Arc::new(Agent::from_config(offline_config()).await.unwrap()),
            workspace.path().display().to_string(),
        )
        .unwrap()
        .with_session_options(
            SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)),
        ),
    );
    let first = start(
        harness.agent_release_identity(),
        "concurrent-admit-session",
        "concurrent-admit-run-a",
    );
    let second = start(
        harness.agent_release_identity(),
        "concurrent-admit-session",
        "concurrent-admit-run-b",
    );
    let left = {
        let harness = Arc::clone(&harness);
        tokio::spawn(async move { harness.execute(&first).await })
    };
    let right = {
        let harness = Arc::clone(&harness);
        tokio::spawn(async move { harness.execute(&second).await })
    };
    let (left, right) = tokio::join!(left, right);
    let left = left.expect("left join");
    let right = right.expect("right join");
    match (left, right) {
        (Ok(_), Ok(_)) => {}
        (
            Ok(_),
            Err(AgentProtocolHarnessError::Code(a3s_code_core::CodeError::SessionBusy { .. })),
        )
        | (
            Err(AgentProtocolHarnessError::Code(a3s_code_core::CodeError::SessionBusy { .. })),
            Ok(_),
        )
        | (
            Ok(_),
            Err(AgentProtocolHarnessError::Host(a3s_code_core::AgentProtocolHostError::Code(
                a3s_code_core::CodeError::SessionBusy { .. },
            ))),
        )
        | (
            Err(AgentProtocolHarnessError::Host(a3s_code_core::AgentProtocolHostError::Code(
                a3s_code_core::CodeError::SessionBusy { .. },
            ))),
            Ok(_),
        ) => {}
        other => panic!("unexpected concurrent admit outcome: {other:?}"),
    }
    assert_eq!(harness.session_count().await, 1);
    harness.close().await;
}

#[tokio::test]
async fn harness_rejects_release_mismatch_and_closed_admission() {
    let workspace = tempfile::tempdir().unwrap();
    let manifest = manifest();
    let harness = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)));

    let foreign = start(
        &format!("sha256:{}", "b".repeat(64)),
        "foreign-session",
        "foreign-run",
    );
    let mismatch = harness
        .execute(&foreign)
        .await
        .expect_err("foreign release must fail");
    assert!(matches!(
        mismatch,
        AgentProtocolHarnessError::Host(a3s_code_core::AgentProtocolHostError::ReleaseMismatch)
    ));

    harness.close().await;
    let closed = harness
        .execute(&start(
            harness.agent_release_identity(),
            "after-close",
            "after-close-run",
        ))
        .await
        .expect_err("closed harness must reject admission");
    assert!(matches!(closed, AgentProtocolHarnessError::Closed));
}

#[tokio::test]
async fn harness_rejects_protocol_mismatch_on_construction() {
    let workspace = tempfile::tempdir().unwrap();
    let source = include_str!("../../fixtures/agent-release-contract/.a3s/asset.acl")
        .replace(AGENT_PROTOCOL_V1, "a3s.code.agent.v2");
    let manifest = a3s_code_core::release::AgentReleaseManifest::parse(&source).unwrap();
    let error = AgentProtocolHarness::new(
        manifest,
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .expect_err("v1 harness must reject another protocol");
    assert!(
        matches!(
            error,
            AgentProtocolHarnessError::Host(
                a3s_code_core::AgentProtocolHostError::ReleaseProtocolMismatch
            ) | AgentProtocolHarnessError::Release(_)
        ),
        "unexpected construction error: {error:?} code={}",
        error.code()
    );
}

#[tokio::test]
async fn harness_isolated_worktree_drop_warns_when_git_removal_fails() {
    let workspace = tempfile::tempdir().unwrap();
    let status = Command::new("git")
        .args(["init"])
        .current_dir(workspace.path())
        .status()
        .unwrap();
    assert!(status.success());
    std::fs::write(workspace.path().join("README.md"), "hi\n").unwrap();
    let _ = Command::new("git")
        .args(["add", "README.md"])
        .current_dir(workspace.path())
        .status();
    let _ = Command::new("git")
        .args([
            "-c",
            "user.email=t@t",
            "-c",
            "user.name=t",
            "commit",
            "-m",
            "i",
        ])
        .current_dir(workspace.path())
        .status();

    let harness = AgentProtocolHarness::new(
        manifest(),
        Arc::new(Agent::from_config(offline_config()).await.unwrap()),
        workspace.path().display().to_string(),
    )
    .unwrap()
    .with_session_options(SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)));
    harness
        .execute(&start(
            harness.agent_release_identity(),
            "isolated-drop-session",
            "isolated-drop-run",
        ))
        .await
        .unwrap();
    // Corrupt the source git dir so Drop's remove_isolated_worktree fails and
    // takes the warn path instead of succeeding silently.
    let _ = std::fs::remove_dir_all(workspace.path().join(".git"));
    harness.close().await;
}

#[tokio::test]
async fn host_for_rejects_when_closed_after_admission_lock() {
    let workspace = tempfile::tempdir().unwrap();
    let harness = Arc::new(
        AgentProtocolHarness::new(
            manifest(),
            Arc::new(Agent::from_config(offline_config()).await.unwrap()),
            workspace.path().display().to_string(),
        )
        .unwrap()
        .with_session_options(
            SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient)),
        ),
    );
    let release = harness.agent_release_identity().to_string();
    // First admission holds the mutex long enough for a second caller to pass
    // the pre-lock closed check and then observe Closed after acquiring it.
    let keeper = {
        let harness = Arc::clone(&harness);
        let release = release.clone();
        tokio::spawn(async move {
            harness
                .execute(&start(&release, "keeper-session", "keeper-run"))
                .await
        })
    };
    tokio::task::yield_now().await;
    let raced = {
        let harness = Arc::clone(&harness);
        let release = release.clone();
        tokio::spawn(async move {
            harness
                .execute(&start(&release, "race-session", "race-run"))
                .await
        })
    };
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    harness.close().await;
    let _ = keeper.await.expect("join keeper");
    let result = raced.await.expect("join raced");
    assert!(
        matches!(result, Err(AgentProtocolHarnessError::Closed) | Ok(_)),
        "unexpected race outcome: {result:?}"
    );
}