a3s 0.10.0

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
pub(super) async fn resolve_questions_once(
    session: &AgentSession,
    progress_tx: &mpsc::Sender<AgentEvent>,
    execution: &mut InquiryExecution,
    state: &mut InquiryState,
    events: &mut Vec<InquiryEvent>,
    limits: &InquiryLimits,
    checkpoint: Option<&InquiryCheckpointWriter>,
) -> Result<(), String> {
    let resolution_timeout_ms = match checkpoint {
        Some(checkpoint) => {
            let Some(timeout_ms) = checkpoint.question_review_stage_timeout_ms(
                DEEP_RESEARCH_QUESTION_REVIEW_STAGE_TIMEOUT_MS,
            ) else {
                terminalize_budget_exhaustion(
                    Some(checkpoint),
                    state,
                    events,
                    limits,
                    "the shared inquiry deadline left no closed-evidence review budget after reserving finalization",
                )
                .await?;
                return Ok(());
            };
            timeout_ms
        }
        None => DEEP_RESEARCH_QUESTION_REVIEW_STAGE_TIMEOUT_MS,
    };
    let queued = state
        .questions
        .iter()
        .filter(|question| question.status == QuestionStatus::Queued)
        .cloned()
        .collect::<Vec<_>>();
    resolve_queued_questions(
        session,
        progress_tx,
        &execution.result,
        &queued,
        state,
        events,
        limits,
        checkpoint,
        resolution_timeout_ms,
    )
    .await?;
    bound_questions(
        state,
        events,
        limits,
        "the single closed-evidence review retained no support for this question",
    )?;
    exhaust_if_material_evidence_floor_missing(state, events, limits)?;
    checkpoint_inquiry(checkpoint, events, state).await
}

pub(super) async fn assess_completed_research_contract(
    state: &mut InquiryState,
    events: &mut Vec<InquiryEvent>,
    limits: &InquiryLimits,
    checkpoint: Option<&InquiryCheckpointWriter>,
) -> Result<ResearchContractOutcome, String> {
    if state.phase != a3s::research::InquiryPhase::Outlining {
        return Err(format!(
            "research contract assessment requires Outlining; current phase is {:?}",
            state.phase
        ));
    }
    let assessment =
        derive_research_contract_assessment(state).map_err(|error| error.to_string())?;
    let event =
        research_contract_assessment_event(state, assessment).map_err(|error| error.to_string())?;
    apply_event_and_checkpoint(checkpoint, state, events, event, limits).await?;
    research_contract_outcome(state)
        .ok_or_else(|| "host contract reduction produced no terminal outcome".to_string())
}

fn exhaust_if_material_evidence_floor_missing(
    state: &mut InquiryState,
    events: &mut Vec<InquiryEvent>,
    limits: &InquiryLimits,
) -> Result<(), String> {
    if state.phase == a3s::research::InquiryPhase::Exhausted {
        return Ok(());
    }
    if material_evidence_floor(state) {
        return Ok(());
    }
    let uncovered_material = state
        .obligations
        .iter()
        .filter(|obligation| obligation.material)
        .filter(|obligation| {
            !state.questions.iter().any(|question| {
                question.material
                    && question.status == QuestionStatus::Answered
                    && !question.evidence_ids.is_empty()
                    && question.obligation_ids.contains(&obligation.id)
            })
        })
        .count()
        .max(1);
    apply_event(
        state,
        events,
        InquiryEvent::BudgetExhausted {
            reason: format!(
                "{uncovered_material} material research obligation(s) had no traceable answered evidence path after the retrieval pass"
            ),
        },
        limits,
    )
}

#[allow(clippy::too_many_arguments)]
async fn resolve_queued_questions(
    session: &AgentSession,
    progress_tx: &mpsc::Sender<AgentEvent>,
    result: &ToolCallResult,
    queued: &[Question],
    state: &mut InquiryState,
    events: &mut Vec<InquiryEvent>,
    limits: &InquiryLimits,
    checkpoint: Option<&InquiryCheckpointWriter>,
    resolution_timeout_ms: u64,
) -> Result<(), String> {
    if queued.is_empty() {
        return Err("DeepResearch retrieval pass has no scheduled questions".to_string());
    }
    let canonical =
        deep_research_canonical_workflow_output(&result.output, result.metadata.as_ref());
    let evidence = accepted_evidence_ledger(&canonical, result.metadata.as_ref());
    let evidence_catalog = prepare_evidence_catalog(state, &evidence)?;
    if evidence_catalog.addressable.is_empty() {
        bound_question_batch(
            state,
            events,
            limits,
            queued,
            "no accepted evidence was retained for this question",
        )?;
        checkpoint_inquiry(checkpoint, events, state).await?;
        return Ok(());
    }
    let query = canonical_query(&canonical);
    // The request participates in the stable Flow identity. Keep its active
    // generation fuse constant across process recovery; the review collector
    // separately enforces the remaining whole-stage wall-clock budget,
    // including admission queue time.
    let generation_timeout_ms = QUESTION_RESOLUTION_ATTEMPT_TIMEOUT_MS;
    let question_groups = question_review_groups(queued);
    let question_group_count = question_groups.len();
    let review_units = question_groups
        .into_iter()
        .enumerate()
        .map(|(ordinal, questions)| {
            let linked_obligations = state
                .obligations
                .iter()
                .filter(|obligation| {
                    questions.iter().any(|question| {
                        question.obligation_ids.contains(&obligation.id)
                    })
                })
                .cloned()
                .collect::<Vec<_>>();
            let group_evidence = question_group_evidence(&evidence_catalog.addressable, &questions);
            let prepared_packet = prepare_question_evidence_packet(
                &group_evidence,
                MAX_QUESTION_EVIDENCE_ITEMS,
                MAX_QUESTION_EVIDENCE_PACKET_CHARS,
            );
            let (allowed_evidence_ids, generation_args) = match prepared_packet {
                Ok(prepared_packet) => {
                    let generation_args = question_resolution_generation_params(
                        query.as_deref().unwrap_or("DeepResearch inquiry"),
                        &questions,
                        &linked_obligations,
                        &state.stop_conditions,
                        &prepared_packet.allowed_evidence_ids,
                        &prepared_packet.payload,
                        generation_timeout_ms,
                    )
                    .map_err(|error| error.to_string())
                    .and_then(|args| {
                        serde_json::to_value(args).map_err(|error| {
                            format!("encode question resolution request: {error}")
                        })
                    });
                    (prepared_packet.allowed_evidence_ids, generation_args)
                }
                Err(error) => (
                    BTreeSet::new(),
                    Err(format!(
                        "closed-evidence question packet could not be prepared: {error}"
                    )),
                ),
            };
            QuestionReviewUnit {
                ordinal,
                questions,
                stage_label: question_review_stage_label(ordinal, question_group_count),
                generation_args,
                allowed_evidence_ids,
            }
        })
        .collect::<Vec<_>>();
    let review_stream = stream::iter(review_units.into_iter().map(|unit| async move {
        execute_question_review_unit(
            session,
            progress_tx,
            checkpoint,
            unit,
            QUESTION_RESOLUTION_WORKFLOW_TIMEOUT_MS,
        )
        .await
    }))
    .buffer_unordered(MAX_CONCURRENT_QUESTION_REVIEWS);
    let (mut review_results, review_timed_out) =
        collect_inquiry_stage_results(review_stream, resolution_timeout_ms).await;
    review_results.sort_by_key(|result| result.ordinal);

    apply_pending_evidence(state, events, limits, evidence_catalog.pending)?;
    for result in review_results {
        let group_events = match result.events {
            Ok(group_events) => group_events,
            Err(error) => {
                tracing::warn!(
                    question_ids = %result.questions.iter()
                        .map(|question| question.id.as_str())
                        .collect::<Vec<_>>()
                        .join(","),
                    stage = %result.stage_label,
                    %error,
                    "DeepResearch closed-evidence obligation review unit did not produce valid resolutions"
                );
                result
                    .questions
                    .into_iter()
                    .map(|question| InquiryEvent::QuestionBounded {
                        question_id: question.id,
                        reason: "closed-evidence assessment did not establish a valid, traceable answer for this question".to_string(),
                    })
                    .collect()
            }
        };
        for event in group_events {
            apply_event(state, events, event, limits)?;
        }
    }
    if review_timed_out {
        bound_questions(
            state,
            events,
            limits,
            "the bounded closed-evidence review stage reached its deadline before this question completed",
        )?;
    }
    checkpoint_inquiry(checkpoint, events, state).await?;
    Ok(())
}

struct QuestionReviewUnit {
    ordinal: usize,
    questions: Vec<Question>,
    stage_label: String,
    generation_args: Result<Value, String>,
    allowed_evidence_ids: BTreeSet<String>,
}

struct QuestionReviewResult {
    ordinal: usize,
    questions: Vec<Question>,
    stage_label: String,
    events: Result<Vec<InquiryEvent>, String>,
}

async fn execute_question_review_unit(
    session: &AgentSession,
    progress_tx: &mpsc::Sender<AgentEvent>,
    checkpoint: Option<&InquiryCheckpointWriter>,
    unit: QuestionReviewUnit,
    resolution_timeout_ms: u64,
) -> QuestionReviewResult {
    let QuestionReviewUnit {
        ordinal,
        questions,
        stage_label,
        generation_args,
        allowed_evidence_ids,
    } = unit;
    let events = match generation_args {
        Ok(generation_args) => call_generation_with_progress(
            session,
            generation_args,
            progress_tx,
            checkpoint,
            &stage_label,
            resolution_timeout_ms,
            QUESTION_RESOLUTION_MAX_ATTEMPTS,
        )
        .await
        .and_then(|generated| generated_object::<Value>(&generated))
        .map(|value| {
            isolated_wire_question_resolution_events(
                value,
                &questions,
                &allowed_evidence_ids,
            )
        }),
        Err(error) => Err(error),
    };
    QuestionReviewResult {
        ordinal,
        questions,
        stage_label,
        events,
    }
}

/// Decode each expected answer independently after validating the shared wire
/// envelope. A malformed sibling must not erase a valid answer from the same
/// obligation review; the malformed entry alone fails closed to `bounded`.
pub(super) fn isolated_wire_question_resolution_events(
    value: Value,
    questions: &[Question],
    allowed_evidence_ids: &BTreeSet<String>,
) -> Vec<InquiryEvent> {
    let Some(root) = value.as_object() else {
        return bounded_review_events(questions);
    };
    if root.len() != 1 {
        return bounded_review_events(questions);
    }
    let Some(entries) = root.get("resolutions").and_then(Value::as_object) else {
        return bounded_review_events(questions);
    };
    let expected_ids = questions
        .iter()
        .map(|question| question.id.as_str())
        .collect::<BTreeSet<_>>();
    if entries
        .keys()
        .any(|question_id| !expected_ids.contains(question_id.as_str()))
    {
        return bounded_review_events(questions);
    }

    questions
        .iter()
        .map(|question| {
            let Some(entry) = entries.get(&question.id) else {
                return bounded_review_event(question);
            };
            let mut singleton_entries = Map::new();
            singleton_entries.insert(question.id.clone(), entry.clone());
            let mut singleton = Map::new();
            singleton.insert(
                "resolutions".to_string(),
                Value::Object(singleton_entries),
            );
            let resolution = decode_question_resolution(
                Value::Object(singleton),
                allowed_evidence_ids,
            );
            let Ok(resolution) = resolution else {
                return bounded_review_event(question);
            };
            isolated_question_resolution_events(
                &resolution,
                std::slice::from_ref(question),
                allowed_evidence_ids,
            )
            .into_iter()
            .next()
            .unwrap_or_else(|| bounded_review_event(question))
        })
        .collect()
}

fn bounded_review_events(questions: &[Question]) -> Vec<InquiryEvent> {
    questions.iter().map(bounded_review_event).collect()
}

fn bounded_review_event(question: &Question) -> InquiryEvent {
    InquiryEvent::QuestionBounded {
        question_id: question.id.clone(),
        reason: "closed-evidence assessment did not establish a valid, traceable answer for this question".to_string(),
    }
}

pub(super) fn isolated_question_resolution_events(
    output: &QuestionResolutionOutput,
    questions: &[Question],
    allowed_evidence_ids: &BTreeSet<String>,
) -> Vec<InquiryEvent> {
    questions
        .iter()
        .map(|question| {
            let matches = output
                .resolutions
                .iter()
                .filter(|resolution| match resolution {
                    QuestionResolution::Answered { question_id, .. }
                    | QuestionResolution::Partial { question_id, .. }
                    | QuestionResolution::Bounded { question_id, .. } => {
                        question_id == &question.id
                    }
                })
                .cloned()
                .collect::<Vec<_>>();
            if matches.len() == 1 {
                let single = QuestionResolutionOutput {
                    resolutions: matches,
                };
                if let Ok(mut events) = question_resolution_events(
                    &single,
                    std::slice::from_ref(question),
                    allowed_evidence_ids,
                ) {
                    if events.len() == 1 {
                        return events.remove(0);
                    }
                }
            }
            bounded_review_event(question)
        })
        .collect()
}

/// Questions linked to the same obligation contract share one closed-evidence
/// generation. This preserves exact question identities while avoiding
/// repeatedly sending the same evidence packet through a single-flight model.
pub(super) fn question_review_groups(queued: &[Question]) -> Vec<Vec<Question>> {
    let mut groups: Vec<Vec<Question>> = Vec::new();
    for question in queued {
        if let Some(group) = groups.iter_mut().find(|group| {
            group.first().is_some_and(|first| {
                first.obligation_ids == question.obligation_ids
            })
        }) {
            group.push(question.clone());
        } else {
            groups.push(vec![question.clone()]);
        }
    }
    groups
}

fn question_review_stage_label(ordinal: usize, question_count: usize) -> String {
    if question_count == 1 {
        "question-review".to_string()
    } else {
        format!("question-review-{}", ordinal + 1)
    }
}