a3s 0.10.5

a3s — A3S coding agent CLI; `a3s code` launches the interactive TUI
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
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use a3s_code_core::llm::{
    structured::NativeStructuredSupport, LlmClient, LlmResponse, Message, StreamEvent, TokenUsage,
    ToolDefinition,
};
use a3s_code_core::tools::{Tool, ToolContext, ToolOutput};
use a3s_code_core::{Agent, SessionOptions};
use tokio_util::sync::CancellationToken;

use super::*;

const FETCHED_SENTENCE: &str =
    "The official Nimbus record states that version 2 receives fixes through September 2027.";

fn generated_schema_tool(tools: &[ToolDefinition]) -> anyhow::Result<&ToolDefinition> {
    anyhow::ensure!(
        tools.len() == 1,
        "fixture expected one forced structured-output tool"
    );
    Ok(&tools[0])
}

fn first_schema_enum_string<'a>(schema: &'a Value, pointer: &str) -> anyhow::Result<&'a str> {
    schema
        .pointer(pointer)
        .and_then(Value::as_array)
        .and_then(|values| values.first())
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("fixture schema omitted enum at {pointer}"))
}

fn schema_boolean_choice(schema: &Value, pointer: &str) -> bool {
    schema
        .pointer(pointer)
        .and_then(Value::as_array)
        .is_none_or(|values| values.iter().any(|value| value == &Value::Bool(true)))
}

fn evidence_selection_from_schema(schema: &Value) -> anyhow::Result<Value> {
    let chunk_id = first_schema_enum_string(schema, "/properties/chunk_ids/items/enum")?;
    let coverage = schema
        .pointer("/properties/source_coverage/items/oneOf/0/properties")
        .ok_or_else(|| anyhow::anyhow!("fixture schema omitted source coverage properties"))?;
    let relevance = schema
        .pointer("/properties/source_relevance/items/oneOf/0/properties")
        .ok_or_else(|| anyhow::anyhow!("fixture schema omitted source relevance properties"))?;
    let source_id = first_schema_enum_string(coverage, "/source_id/enum")?;
    let obligation_id = first_schema_enum_string(coverage, "/obligation_id/enum")?;
    let criterion_indexes = coverage
        .pointer("/completion_criterion_indexes/items/enum")
        .and_then(Value::as_array)
        .cloned()
        .ok_or_else(|| anyhow::anyhow!("fixture schema omitted criterion indexes"))?;
    anyhow::ensure!(
        first_schema_enum_string(relevance, "/source_id/enum")? == source_id
            && first_schema_enum_string(relevance, "/obligation_id/enum")? == obligation_id,
        "fixture schema carried inconsistent coverage and relevance identities"
    );

    Ok(serde_json::json!({
        "chunk_ids": [chunk_id],
        "source_coverage": [{
            "source_id": source_id,
            "obligation_id": obligation_id,
            "completion_criterion_indexes": criterion_indexes,
            "roles": {
                "supporting": true,
                "primary": schema_boolean_choice(coverage, "/roles/properties/primary/enum"),
                "independent": schema_boolean_choice(
                    coverage,
                    "/roles/properties/independent/enum"
                )
            }
        }],
        "source_relevance": [{
            "source_id": source_id,
            "obligation_id": obligation_id
        }]
    }))
}

struct EvidenceFirstSearch {
    return_source: bool,
}

#[async_trait::async_trait]
impl Tool for EvidenceFirstSearch {
    fn name(&self) -> &str {
        "evidence_first_fixture_search"
    }

    fn description(&self) -> &str {
        "Returns the evidence-first runtime fixture search catalog."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(&self, _args: &Value, _ctx: &ToolContext) -> anyhow::Result<ToolOutput> {
        let results = if self.return_source {
            serde_json::json!([{
                "title": "Official Nimbus support record",
                "url": "https://docs.rs/nimbus/latest/nimbus/support",
                "engines": ["fixture"]
            }])
        } else {
            serde_json::json!([])
        };
        Ok(ToolOutput::success(results.to_string()))
    }
}

struct EvidenceFirstFetch;

#[async_trait::async_trait]
impl Tool for EvidenceFirstFetch {
    fn name(&self) -> &str {
        "evidence_first_fixture_fetch"
    }

    fn description(&self) -> &str {
        "Returns one deterministic fetched source."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({"type": "object"})
    }

    async fn execute(&self, args: &Value, _ctx: &ToolContext) -> anyhow::Result<ToolOutput> {
        anyhow::ensure!(
            args.get("url").and_then(Value::as_str)
                == Some("https://docs.rs/nimbus/latest/nimbus/support"),
            "unexpected evidence-first fixture URL"
        );
        Ok(
            ToolOutput::success(FETCHED_SENTENCE).with_metadata(serde_json::json!({
                "source_anchors": ["https://docs.rs/nimbus/latest/nimbus/support"],
                "document_kind": "html",
                "content_type": "text/html",
                "range": {
                    "offset": 0,
                    "returned_chars": FETCHED_SENTENCE.chars().count(),
                    "next_offset": null,
                    "eof": true
                }
            })),
        )
    }
}

#[derive(Clone, Copy)]
enum ProposalBehavior {
    Slow,
    Invalid,
    FailOnceThenValid,
    Qualified,
}

struct EvidenceFirstProposal {
    behavior: ProposalBehavior,
    report_path: PathBuf,
    calls: Arc<AtomicUsize>,
    saw_staged_report: Arc<AtomicBool>,
}

impl EvidenceFirstProposal {
    async fn proposal(&self, tools: &[ToolDefinition]) -> anyhow::Result<Value> {
        let tool = generated_schema_tool(tools)?;
        match tool.name.as_str() {
            "emit_deep_research_semantic_outline" => Ok(serde_json::json!({
                "report_title": "Nimbus support research",
                "research_scope": "focused",
                "freshness_required": false,
                "workspace_evidence_required": false,
                "tracks": [{
                    "id": "support.boundary",
                    "title": "Support boundary",
                    "focus": "Establish the supported Nimbus release and maintenance boundary.",
                    "material": true,
                    "completion_criteria": [
                        "A traceable source identifies the release and support boundary."
                    ],
                    "evidence_requirements": {
                        "primary_source_required": true,
                        "independent_corroboration_required": false
                    }
                }],
                "supplemental_queries": []
            })),
            "emit_deep_research_web_source_selection" => Ok(serde_json::json!({
                "candidate_ids": [
                    first_schema_enum_string(
                        &tool.parameters,
                        "/properties/candidate_ids/items/enum"
                    )?
                ]
            })),
            "emit_deep_research_evidence_selection"
            | "emit_deep_research_evidence_shard_selection"
            | "emit_deep_research_evidence_source_reduction" => {
                evidence_selection_from_schema(&tool.parameters)
            }
            "emit_deep_research_typed_claim_graph" => {
                self.calls.fetch_add(1, Ordering::SeqCst);
                let staged = std::fs::read_to_string(&self.report_path)?;
                anyhow::ensure!(
                    staged.contains(FETCHED_SENTENCE),
                    "the model proposal started before the source-backed report was staged"
                );
                self.saw_staged_report.store(true, Ordering::SeqCst);

                match self.behavior {
                    ProposalBehavior::Slow => std::future::pending::<anyhow::Result<Value>>().await,
                    ProposalBehavior::Invalid => Ok(serde_json::json!({
                        "report_language": "en",
                        "labels": {
                            "answer": "Direct Answer",
                            "findings": "Findings",
                            "recommendations": "Evidence-Based Recommendations",
                            "limitations": "Limitations",
                            "evidence_boundary": "This report publishes no conclusion beyond the fetched evidence.",
                            "sources": "Sources",
                            "contradiction": "Contradiction",
                            "inference": "Inference",
                            "basis": "Basis",
                            "derivation": "Derivation"
                        },
                        "claims": [{
                            "id": "fabricated-answer",
                            "dimension_id": "support.boundary",
                            "placement": "direct_answer",
                            "kind": "fact",
                            "text": "A fabricated source claims support through 2099.",
                            "evidence_refs": [{
                                "source_id": "source-99",
                                "chunk_ids": ["source-99:chunk:1"]
                            }],
                            "basis_claim_ids": [],
                            "derivation": null
                        }],
                        "relations": [],
                        "gaps": []
                    })),
                    ProposalBehavior::FailOnceThenValid
                        if self.calls.load(Ordering::SeqCst) == 1 =>
                    {
                        anyhow::bail!("simulated transient streaming failure")
                    }
                    ProposalBehavior::FailOnceThenValid => Ok(serde_json::json!({
                        "report_language": "en",
                        "labels": {
                            "answer": "Direct Answer",
                            "findings": "Findings",
                            "recommendations": "Evidence-Based Recommendations",
                            "limitations": "Limitations",
                            "evidence_boundary": "This report publishes no conclusion beyond the fetched evidence.",
                            "sources": "Sources",
                            "contradiction": "Contradiction",
                            "inference": "Inference",
                            "basis": "Basis",
                            "derivation": "Derivation"
                        },
                        "claims": [{
                            "id": "nimbus-answer",
                            "dimension_id": "support.boundary",
                            "placement": "direct_answer",
                            "kind": "fact",
                            "text": "Nimbus version 2 receives fixes through September 2027.",
                            "evidence_refs": [{
                                "source_id": "source-1",
                                "chunk_ids": ["source-1:chunk:1"]
                            }],
                            "basis_claim_ids": [],
                            "derivation": null
                        }, {
                            "id": "nimbus-boundary",
                            "dimension_id": "support.boundary",
                            "placement": "finding",
                            "kind": "fact",
                            "text": "The official Nimbus record identifies version 2 and September 2027 as the support boundary.",
                            "evidence_refs": [{
                                "source_id": "source-1",
                                "chunk_ids": ["source-1:chunk:1"]
                            }],
                            "basis_claim_ids": [],
                            "derivation": null
                        }],
                        "relations": [],
                        "gaps": []
                    })),
                    ProposalBehavior::Qualified => Ok(serde_json::json!({
                        "report_language": "en",
                        "labels": {
                            "answer": "Direct Answer",
                            "findings": "Findings",
                            "recommendations": "Evidence-Based Recommendations",
                            "limitations": "Limitations",
                            "evidence_boundary": "This report publishes no conclusion beyond the fetched evidence.",
                            "sources": "Sources",
                            "contradiction": "Contradiction",
                            "inference": "Inference",
                            "basis": "Basis",
                            "derivation": "Derivation"
                        },
                        "claims": [{
                            "id": "nimbus-qualified-answer",
                            "dimension_id": "support.boundary",
                            "placement": "direct_answer",
                            "kind": "fact",
                            "text": "Nimbus version 2 receives fixes through September 2027.",
                            "evidence_refs": [{
                                "source_id": "source-1",
                                "chunk_ids": ["source-1:chunk:1"]
                            }],
                            "basis_claim_ids": [],
                            "derivation": null
                        }],
                        "relations": [],
                        "gaps": [{
                            "id": "nimbus-unresolved-boundary",
                            "dimension_id": "support.boundary",
                            "text": "The reviewed record does not establish support conditions beyond the stated maintenance date."
                        }]
                    })),
                }
            }
            unexpected => {
                anyhow::bail!("unexpected evidence-first structured schema tool `{unexpected}`")
            }
        }
    }

    fn response(value: Value) -> LlmResponse {
        LlmResponse {
            message: Message::assistant(&value.to_string()),
            usage: TokenUsage::default(),
            stop_reason: Some("stop".to_string()),
            token_logprobs: Vec::new(),
            meta: None,
        }
    }
}

#[async_trait::async_trait]
impl LlmClient for EvidenceFirstProposal {
    fn native_structured_support(&self) -> NativeStructuredSupport {
        NativeStructuredSupport::ForcedTool
    }

    async fn complete(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        tools: &[ToolDefinition],
    ) -> anyhow::Result<LlmResponse> {
        self.proposal(tools).await.map(Self::response)
    }

    async fn complete_streaming(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        tools: &[ToolDefinition],
        _cancel_token: CancellationToken,
    ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
        let response = Self::response(self.proposal(tools).await?);
        let text = response.message.text();
        let (tx, rx) = mpsc::channel(4);
        tokio::spawn(async move {
            tx.send(StreamEvent::TextDelta(text)).await.ok();
            tx.send(StreamEvent::Done(response)).await.ok();
        });
        Ok(rx)
    }
}

struct UnexpectedProposal {
    calls: Arc<AtomicUsize>,
}

#[async_trait::async_trait]
impl LlmClient for UnexpectedProposal {
    fn native_structured_support(&self) -> NativeStructuredSupport {
        NativeStructuredSupport::ForcedTool
    }

    async fn complete(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        tools: &[ToolDefinition],
    ) -> anyhow::Result<LlmResponse> {
        let tool = generated_schema_tool(tools)?;
        if tool.name == "emit_deep_research_semantic_outline" {
            return Ok(EvidenceFirstProposal::response(serde_json::json!({
                "report_title": "Nimbus evidence check",
                "research_scope": "focused",
                "freshness_required": false,
                "workspace_evidence_required": false,
                "tracks": [{
                    "id": "request.primary",
                    "title": "Requested evidence",
                    "focus": "Establish the requested answer.",
                    "material": true,
                    "completion_criteria": ["The answer is supported or explicitly bounded."],
                    "evidence_requirements": {
                        "primary_source_required": false,
                        "independent_corroboration_required": false
                    }
                }],
                "supplemental_queries": []
            })));
        }
        self.calls.fetch_add(1, Ordering::SeqCst);
        anyhow::bail!("no-evidence publication must not invoke report generation")
    }

    async fn complete_streaming(
        &self,
        _messages: &[Message],
        _system: Option<&str>,
        tools: &[ToolDefinition],
        _cancel_token: CancellationToken,
    ) -> anyhow::Result<mpsc::Receiver<StreamEvent>> {
        let tool = generated_schema_tool(tools)?;
        if tool.name == "emit_deep_research_semantic_outline" {
            let response = EvidenceFirstProposal::response(serde_json::json!({
                "report_title": "Nimbus evidence check",
                "research_scope": "focused",
                "freshness_required": false,
                "workspace_evidence_required": false,
                "tracks": [{
                    "id": "request.primary",
                    "title": "Requested evidence",
                    "focus": "Establish the requested answer.",
                    "material": true,
                    "completion_criteria": ["The answer is supported or explicitly bounded."],
                    "evidence_requirements": {
                        "primary_source_required": false,
                        "independent_corroboration_required": false
                    }
                }],
                "supplemental_queries": []
            }));
            let text = response.message.text();
            let (tx, rx) = mpsc::channel(4);
            tokio::spawn(async move {
                tx.send(StreamEvent::TextDelta(text)).await.ok();
                tx.send(StreamEvent::Done(response)).await.ok();
            });
            return Ok(rx);
        }
        self.calls.fetch_add(1, Ordering::SeqCst);
        anyhow::bail!("no-evidence publication must not invoke report generation")
    }
}

#[tokio::test]
async fn proposal_timeout_preserves_the_already_staged_source_report() {
    let workspace = tempfile::tempdir().expect("create timeout workspace");
    let query = "Which Nimbus release is supported?";
    let calls = Arc::new(AtomicUsize::new(0));
    let saw_staged_report = Arc::new(AtomicBool::new(false));
    let report_path = report_markdown_path(workspace.path(), query);
    let (_agent, session) = fixture_session(
        workspace.path(),
        true,
        Arc::new(EvidenceFirstProposal {
            behavior: ProposalBehavior::Slow,
            report_path,
            calls: Arc::clone(&calls),
            saw_staged_report: Arc::clone(&saw_staged_report),
        }),
    )
    .await;
    let args = evidence_first_args(query, "evidence-first-proposal-timeout");
    record_workflow_started(
        workspace.path(),
        "evidence-first-proposal-timeout",
        deep_research_evidence_first_research_spec(&args),
    )
    .await
    .expect("pre-create the TUI-owned journal with the shared spec");

    let result = tokio::time::timeout(
        Duration::from_secs(6),
        execute_fixture_runtime(session, args, 1_200),
    )
    .await
    .expect("two bounded proposal attempts must cancel an indefinitely pending model call")
    .expect("timeout must fall back instead of failing the run");
    assert!(
        (1..=2).contains(&calls.load(Ordering::SeqCst)),
        "{}",
        result.output
    );
    assert!(saw_staged_report.load(Ordering::SeqCst));
    assert_source_backed_result(workspace.path(), query, &result);
}

#[tokio::test]
async fn transient_report_stream_failure_retries_and_publishes_a_real_report() {
    let workspace = tempfile::tempdir().expect("create retry workspace");
    let query = "Which Nimbus release is supported?";
    let run_id = "evidence-first-proposal-retry";
    let calls = Arc::new(AtomicUsize::new(0));
    let saw_staged_report = Arc::new(AtomicBool::new(false));
    let report_path = report_markdown_path(workspace.path(), query);
    let (_agent, session) = fixture_session(
        workspace.path(),
        true,
        Arc::new(EvidenceFirstProposal {
            behavior: ProposalBehavior::FailOnceThenValid,
            report_path,
            calls: Arc::clone(&calls),
            saw_staged_report: Arc::clone(&saw_staged_report),
        }),
    )
    .await;
    let args = evidence_first_args(query, run_id);

    let result = execute_fixture_runtime(session, args, 5_000)
        .await
        .expect("transient report generation failure must be retried");

    assert_eq!(calls.load(Ordering::SeqCst), 2, "{}", result.output);
    assert!(saw_staged_report.load(Ordering::SeqCst));
    let output: Value = serde_json::from_str(&result.output).expect("decode retry output");
    assert_eq!(output["publication"]["status"], "synthesized");
    assert_eq!(output["research"]["status"], "success");
    assert_eq!(output["publication"]["quality"]["direct_answer_count"], 1);
    assert_eq!(output["publication"]["quality"]["finding_count"], 1);
    assert_eq!(output["publication"]["quality"]["accepted_claim_count"], 2);
    let markdown = std::fs::read_to_string(report_markdown_path(workspace.path(), query))
        .expect("read synthesized retry report");
    assert!(markdown.contains("## Direct Answer"), "{markdown}");
    assert!(markdown.contains("## Findings"), "{markdown}");
    assert!(
        !markdown.contains("Preserved Source Evidence"),
        "{markdown}"
    );
    let recovered =
        super::super::deep_research_artifacts::recover_deep_research_publication_receipt(
            workspace.path(),
            query,
            run_id,
        )
        .expect("read the run-scoped publication receipt")
        .expect("recover the completed publication before terminal settlement");
    assert_eq!(
        recovered.publication,
        super::super::deep_research_artifacts::DeepResearchEvidenceFirstPublication::Synthesized
    );
    assert_eq!(recovered.quality.accepted_claim_count, 2);
    assert_eq!(recovered.quality.cited_source_count, 1);
}

#[tokio::test]
async fn qualified_claim_graph_survives_publication_and_receipt_recovery() {
    let workspace = tempfile::tempdir().expect("create qualified workspace");
    let query = "Which Nimbus release is supported?";
    let run_id = "evidence-first-qualified-report";
    let calls = Arc::new(AtomicUsize::new(0));
    let saw_staged_report = Arc::new(AtomicBool::new(false));
    let report_path = report_markdown_path(workspace.path(), query);
    let (_agent, session) = fixture_session(
        workspace.path(),
        true,
        Arc::new(EvidenceFirstProposal {
            behavior: ProposalBehavior::Qualified,
            report_path,
            calls: Arc::clone(&calls),
            saw_staged_report: Arc::clone(&saw_staged_report),
        }),
    )
    .await;
    let result = execute_fixture_runtime(session, evidence_first_args(query, run_id), 5_000)
        .await
        .expect("qualified report execution");

    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert!(saw_staged_report.load(Ordering::SeqCst));
    let output: Value = serde_json::from_str(&result.output).expect("decode qualified output");
    assert_eq!(output["publication"]["status"], "qualified");
    assert_eq!(output["research"]["status"], "partial_success");
    assert_eq!(output["publication"]["quality"]["accepted_claim_count"], 1);
    assert_eq!(output["publication"]["quality"]["accepted_gap_count"], 1);
    let recovered =
        super::super::deep_research_artifacts::recover_deep_research_publication_receipt(
            workspace.path(),
            query,
            run_id,
        )
        .expect("read qualified publication receipt")
        .expect("recover qualified publication");
    assert_eq!(
        recovered.publication,
        super::super::deep_research_artifacts::DeepResearchEvidenceFirstPublication::Qualified
    );
    assert_eq!(recovered.quality.accepted_gap_count, 1);
}

#[tokio::test]
async fn invalid_proposal_preserves_valid_fetched_evidence() {
    let workspace = tempfile::tempdir().expect("create invalid-proposal workspace");
    let query = "Which Nimbus release is supported?";
    let calls = Arc::new(AtomicUsize::new(0));
    let saw_staged_report = Arc::new(AtomicBool::new(false));
    let report_path = report_markdown_path(workspace.path(), query);
    let (_agent, session) = fixture_session(
        workspace.path(),
        true,
        Arc::new(EvidenceFirstProposal {
            behavior: ProposalBehavior::Invalid,
            report_path,
            calls: Arc::clone(&calls),
            saw_staged_report: Arc::clone(&saw_staged_report),
        }),
    )
    .await;
    let args = evidence_first_args(query, "evidence-first-invalid-proposal");

    let result = execute_fixture_runtime(session, args, 2_000)
        .await
        .expect("invalid proposal must fall back instead of failing the run");
    assert_eq!(
        calls.load(Ordering::SeqCst),
        2,
        "the per-run schema rejects the unknown alias and the durable port uses only its one bounded retry: {}",
        result.output
    );
    assert!(saw_staged_report.load(Ordering::SeqCst));
    assert_source_backed_result(workspace.path(), query, &result);
    let markdown = std::fs::read_to_string(report_markdown_path(workspace.path(), query))
        .expect("read retained source-backed Markdown");
    assert!(!markdown.contains("2099"));
    assert!(!markdown.contains("source-99"));
}

#[tokio::test]
async fn empty_acquisition_publishes_honest_artifacts_without_a_model_call() {
    let workspace = tempfile::tempdir().expect("create no-evidence runtime workspace");
    let query = "核查 Nimbus 当前支持策略";
    let calls = Arc::new(AtomicUsize::new(0));
    let (_agent, session) = fixture_session(
        workspace.path(),
        false,
        Arc::new(UnexpectedProposal {
            calls: Arc::clone(&calls),
        }),
    )
    .await;
    let args = evidence_first_args(query, "evidence-first-no-evidence");

    let result = execute_fixture_runtime(session, args, 1_000)
        .await
        .expect("empty acquisition must publish an honest terminal artifact");
    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert!(
        result.metadata.is_none(),
        "the Host result must not expose child workflow metadata"
    );
    let output: Value = serde_json::from_str(&result.output).expect("decode runtime output");
    assert_eq!(output["publication"]["status"], "no_evidence");
    assert_eq!(output["research"]["status"], "failed");
    let published =
        super::super::deep_research_artifacts::deep_research_evidence_first_published_report(
            workspace.path(),
            query,
            &result.output,
        )
        .expect("validate no-evidence publication")
        .expect("rediscover no-evidence artifacts");
    assert_eq!(
        published.publication,
        super::super::deep_research_artifacts::DeepResearchEvidenceFirstPublication::NoEvidence
    );
}

async fn fixture_session(
    workspace: &Path,
    return_source: bool,
    proposal: Arc<dyn LlmClient>,
) -> (Agent, AgentSession) {
    let config = workspace.join("config.acl");
    std::fs::write(
        &config,
        "default_model = \"openai/x\"\n\
         providers \"openai\" {\n  apiKey = \"x\"\n  baseUrl = \"http://127.0.0.1:1\"\n  \
         models \"x\" { name = \"x\" }\n}\n",
    )
    .expect("write evidence-first fixture config");
    let agent = Agent::new(config.to_string_lossy().to_string())
        .await
        .expect("create evidence-first fixture agent");
    let options = SessionOptions::new()
        .with_session_id(format!(
            "evidence-first-fixture-{}-{}",
            std::process::id(),
            rand::random::<u64>()
        ))
        .with_llm_client(proposal)
        .with_auto_save(false)
        .with_tool_timeout(5_000);
    let session = agent
        .session_async(workspace.to_string_lossy().to_string(), Some(options))
        .await
        .expect("create evidence-first fixture session");
    session
        .register_dynamic_workflow_runtime()
        .expect("register dynamic workflow runtime");
    session
        .register_dynamic_tool(Arc::new(EvidenceFirstSearch { return_source }))
        .expect("register fixture search");
    session
        .register_dynamic_tool(Arc::new(EvidenceFirstFetch))
        .expect("register fixture fetch");
    (agent, session)
}

pub(super) async fn product_adapter_fixture_session(workspace: &Path) -> (Agent, AgentSession) {
    fixture_session(
        workspace,
        false,
        Arc::new(EvidenceFirstProposal {
            behavior: ProposalBehavior::Invalid,
            report_path: report_markdown_path(workspace, "unused product adapter fixture"),
            calls: Arc::new(AtomicUsize::new(0)),
            saw_staged_report: Arc::new(AtomicBool::new(false)),
        }),
    )
    .await
}

fn evidence_first_args(query: &str, run_id: &str) -> Value {
    let mut args = super::super::deep_research_workflow_args_with_scope(
        query,
        super::super::DeepResearchEvidenceScope::WebAndWorkspace,
    );
    let source = args["source"]
        .as_str()
        .expect("DeepResearch workflow source")
        .replace(
            "ctx.tool(\"web_search\"",
            "ctx.tool(\"evidence_first_fixture_search\"",
        )
        .replace(
            "tool: \"web_search\"",
            "tool: \"evidence_first_fixture_search\"",
        )
        .replace(
            "ctx.tool(\"web_fetch\"",
            "ctx.tool(\"evidence_first_fixture_fetch\"",
        )
        .replace(
            "tool: \"web_fetch\"",
            "tool: \"evidence_first_fixture_fetch\"",
        );
    args["source"] = Value::String(source);
    args["run_id"] = Value::String(run_id.to_string());
    args
}

async fn execute_fixture_runtime(
    session: AgentSession,
    args: Value,
    proposal_stage_timeout_ms: u64,
) -> Result<ToolCallResult, String> {
    let (progress_tx, mut progress_rx) = mpsc::channel(PROGRESS_CHANNEL_CAPACITY);
    let progress_drain = tokio::spawn(async move { while progress_rx.recv().await.is_some() {} });
    let result = run_evidence_first_research_with_limits(
        Arc::new(session),
        args,
        progress_tx,
        EvidenceFirstRuntimeLimits {
            bootstrap_stage_timeout_ms: 5_000,
            planned_retrieval_stage_timeout_ms: 5_000,
            report_proposal_attempt_timeout_ms: proposal_stage_timeout_ms
                .saturating_sub(200)
                .max(1_000),
            report_proposal_stage_timeout_ms: proposal_stage_timeout_ms,
        },
    )
    .await;
    progress_drain.await.expect("drain progress events");
    result
}

fn assert_source_backed_result(workspace: &Path, query: &str, result: &ToolCallResult) {
    assert!(
        result.metadata.is_none(),
        "the Host result must not expose child workflow metadata"
    );
    let output: Value = serde_json::from_str(&result.output).expect("decode runtime output");
    assert_eq!(output["publication"]["status"], "source_backed");
    assert_eq!(output["research"]["status"], "degraded");
    assert!(output["research"]["warnings"]["report_error"].is_string());
    let published =
        super::super::deep_research_artifacts::deep_research_evidence_first_published_report(
            workspace,
            query,
            &result.output,
        )
        .expect("validate source-backed publication")
        .expect("rediscover source-backed artifacts");
    assert_eq!(
        published.publication,
        super::super::deep_research_artifacts::DeepResearchEvidenceFirstPublication::SourceBacked
    );
    let markdown =
        std::fs::read_to_string(published.artifacts.markdown).expect("read source-backed Markdown");
    assert!(markdown.contains(FETCHED_SENTENCE));
}

fn report_markdown_path(workspace: &Path, query: &str) -> PathBuf {
    workspace
        .join(".a3s/research")
        .join(super::super::deep_research_artifacts::deep_research_report_slug(query))
        .join("report.md")
}