a3s 0.9.3

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
//! Closed-evidence structured generation for the final DeepResearch report.

use serde::{Deserialize, Serialize};

const REPORT_MIN_CHARS: usize = 120;
const REPORT_MAX_CHARS: usize = 60_000;

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportNarrativeMode {
    Pyramid,
    Narrative,
    Instructional,
    #[default]
    Briefing,
}

impl ReportNarrativeMode {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Pyramid => "mode-pyramid",
            Self::Narrative => "mode-narrative",
            Self::Instructional => "mode-instructional",
            Self::Briefing => "mode-briefing",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum ReportArchetype {
    #[default]
    Editorial,
    Analytical,
    Chronicle,
    Executive,
    FieldNotes,
}

impl ReportArchetype {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Editorial => "archetype-editorial",
            Self::Analytical => "archetype-analytical",
            Self::Chronicle => "archetype-chronicle",
            Self::Executive => "archetype-executive",
            Self::FieldNotes => "archetype-field-notes",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportPalette {
    #[default]
    Ocean,
    Graphite,
    Forest,
    Amber,
    Plum,
}

impl ReportPalette {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Ocean => "palette-ocean",
            Self::Graphite => "palette-graphite",
            Self::Forest => "palette-forest",
            Self::Amber => "palette-amber",
            Self::Plum => "palette-plum",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportDensity {
    Compact,
    #[default]
    Balanced,
    Spacious,
}

impl ReportDensity {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Compact => "density-compact",
            Self::Balanced => "density-balanced",
            Self::Spacious => "density-spacious",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportHero {
    Statement,
    #[default]
    Split,
    Metrics,
}

impl ReportHero {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Statement => "hero-statement",
            Self::Split => "hero-split",
            Self::Metrics => "hero-metrics",
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportVisualStance {
    Safe,
    #[default]
    Shifted,
    Bold,
}

impl ReportVisualStance {
    pub(crate) fn class_name(self) -> &'static str {
        match self {
            Self::Safe => "stance-safe",
            Self::Shifted => "stance-shifted",
            Self::Bold => "stance-bold",
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReportPresentation {
    pub(crate) narrative_mode: ReportNarrativeMode,
    pub(crate) archetype: ReportArchetype,
    pub(crate) palette: ReportPalette,
    pub(crate) density: ReportDensity,
    pub(crate) hero: ReportHero,
    pub(crate) visual_stance: ReportVisualStance,
    pub(crate) rationale: String,
}

impl ReportPresentation {
    pub(crate) fn body_classes(&self) -> String {
        [
            self.narrative_mode.class_name(),
            self.archetype.class_name(),
            self.palette.class_name(),
            self.density.class_name(),
            self.hero.class_name(),
            self.visual_stance.class_name(),
        ]
        .join(" ")
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum ReportTrackStatus {
    Answered,
    Bounded,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReportTrackCoverage {
    pub(crate) track: String,
    pub(crate) status: ReportTrackStatus,
    pub(crate) finding: String,
    pub(crate) interpretation: String,
    pub(crate) implication: String,
    pub(crate) uncertainty: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ReportEditorialPlan {
    pub(crate) thesis: String,
    pub(crate) track_coverage: Vec<ReportTrackCoverage>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GeneratedDeepResearchReport {
    pub(crate) markdown: String,
    pub(crate) editorial: ReportEditorialPlan,
    pub(crate) presentation: ReportPresentation,
}

pub(super) fn deep_research_report_generation_args(
    prompt: &str,
    timeout_ms: u64,
) -> serde_json::Value {
    serde_json::json!({
        "schema": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "markdown": {
                    "type": "string",
                    "minLength": REPORT_MIN_CHARS,
                    "maxLength": REPORT_MAX_CHARS,
                    "description": "The complete source-backed human-facing report in Markdown."
                },
                "editorial": {
                    "type": "object",
                    "additionalProperties": false,
                    "properties": {
                        "thesis": {
                            "type": "string",
                            "minLength": 12,
                            "maxLength": 1200,
                            "description": "One reader-facing sentence that directly answers the query and can lead the report hero."
                        },
                        "track_coverage": {
                            "type": "array",
                            "minItems": 1,
                            "maxItems": 6,
                            "description": "One entry for every planned research track. Reuse the full track name when practical; otherwise use a concise, unambiguous semantic label. This is a private quality map, not report prose.",
                            "items": {
                                "type": "object",
                                "additionalProperties": false,
                                "properties": {
                                    "track": { "type": "string", "minLength": 2, "maxLength": 180 },
                                    "status": { "type": "string", "enum": ["answered", "bounded"] },
                                    "finding": { "type": "string", "minLength": 8, "maxLength": 600 },
                                    "interpretation": { "type": "string", "minLength": 8, "maxLength": 600 },
                                    "implication": { "type": "string", "maxLength": 600 },
                                    "uncertainty": { "type": "string", "maxLength": 600 }
                                },
                                "required": ["track", "status", "finding", "interpretation", "implication", "uncertainty"]
                            }
                        }
                    },
                    "required": ["thesis", "track_coverage"]
                },
                "presentation": {
                    "type": "object",
                    "additionalProperties": false,
                    "description": "A content-semantic art-direction lock. Choose deliberately from the report's argument, audience, evidence shape, and reading occasion; never from topic keywords or a task-specific template.",
                    "properties": {
                        "narrative_mode": {
                            "type": "string",
                            "enum": ["pyramid", "narrative", "instructional", "briefing"],
                            "description": "How the report argues: conclusion-first, event arc, progressive explanation, or balanced scan."
                        },
                        "archetype": {
                            "type": "string",
                            "enum": ["editorial", "analytical", "chronicle", "executive", "field-notes"],
                            "description": "The visual composition family. Analytical emphasizes comparisons; chronicle emphasizes ordered change; executive is restrained and decision-first; field-notes suits observation and investigation; editorial suits long-form synthesis."
                        },
                        "palette": {
                            "type": "string",
                            "enum": ["ocean", "graphite", "forest", "amber", "plum"],
                            "description": "A curated accessible color system selected for tone and audience, independent from the subject's literal colors."
                        },
                        "density": {
                            "type": "string",
                            "enum": ["compact", "balanced", "spacious"],
                            "description": "Information density appropriate to evidence volume and reading occasion."
                        },
                        "hero": {
                            "type": "string",
                            "enum": ["statement", "split", "metrics"],
                            "description": "Cover composition: thesis-led statement, balanced split, or evidence-profile-led metrics."
                        },
                        "visual_stance": {
                            "type": "string",
                            "enum": ["safe", "shifted", "bold"],
                            "description": "Safe for formal/high-risk contexts, shifted for one controlled distinctive motif, bold only when audience and evidence support it."
                        },
                        "rationale": {
                            "type": "string",
                            "minLength": 12,
                            "maxLength": 500,
                            "description": "A concise private explanation tying the choices to content structure and audience. It is never rendered."
                        }
                    },
                    "required": ["narrative_mode", "archetype", "palette", "density", "hero", "visual_stance", "rationale"]
                }
            },
            "required": ["markdown", "editorial", "presentation"]
        },
        "schema_name": "deep_research_report",
        "schema_description": "A complete evidence-grounded DeepResearch report plus a semantic coverage map and content-driven report-master presentation lock",
        "prompt": prompt,
        "system": "You are a closed-evidence research writer and report art director. Return only the requested object. Spend the completion budget on a genuinely useful Markdown report; keep each private coverage field to one or two precise sentences. Audit every planned track through finding, interpretation, implication, and uncertainty. Choose presentation from the argument, audience, evidence shape, and reading occasion; do not reuse a default style or infer design from topic keywords. Do not invoke or discuss tools, delegation, files, workflows, or the writing process.",
        "mode": "tool",
        "max_repair_attempts": 1,
        "timeout_ms": timeout_ms.clamp(1_000, 600_000)
    })
}

pub(super) fn deep_research_report_from_generation(
    output: &str,
    exit_code: i32,
) -> Result<GeneratedDeepResearchReport, String> {
    if exit_code != 0 {
        return Err(output
            .lines()
            .next()
            .unwrap_or("structured report generation failed")
            .to_string());
    }
    let envelope = serde_json::from_str::<serde_json::Value>(output)
        .map_err(|error| format!("structured report response was not valid JSON: {error}"))?;
    let object = envelope
        .get("object")
        .cloned()
        .ok_or_else(|| "structured report response did not contain an object".to_string())?;
    let mut report = serde_json::from_value::<GeneratedDeepResearchReport>(object)
        .map_err(|error| format!("structured report object violated its contract: {error}"))?;
    report.markdown = report.markdown.trim().to_string();
    report.editorial.thesis = report.editorial.thesis.trim().to_string();
    report.presentation.rationale = report.presentation.rationale.trim().to_string();
    if report.markdown.chars().count() < REPORT_MIN_CHARS {
        return Err("structured report response did not contain substantive Markdown".to_string());
    }
    if report.editorial.thesis.chars().count() < 12 {
        return Err("structured report response did not contain a substantive thesis".to_string());
    }
    if report.editorial.track_coverage.is_empty() {
        return Err(
            "structured report response did not audit any planned research track".to_string(),
        );
    }
    Ok(report)
}

#[cfg(test)]
pub(super) fn deep_research_report_markdown_from_generation(
    output: &str,
    exit_code: i32,
) -> Result<String, String> {
    deep_research_report_from_generation(output, exit_code).map(|report| report.markdown)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn valid_object(markdown: String) -> serde_json::Value {
        serde_json::json!({
            "markdown": markdown,
            "editorial": {
                "thesis": "The evidence supports a bounded, source-backed conclusion.",
                "track_coverage": [{
                    "track": "Current status",
                    "status": "answered",
                    "finding": "The current status is documented by the cited source.",
                    "interpretation": "The documented status materially answers the request.",
                    "implication": "Readers can act on the stated current status.",
                    "uncertainty": "The evidence remains bounded to the retrieval date."
                }]
            },
            "presentation": {
                "narrative_mode": "pyramid",
                "archetype": "analytical",
                "palette": "graphite",
                "density": "compact",
                "hero": "metrics",
                "visual_stance": "safe",
                "rationale": "A decision-first analytical treatment fits the compact evidence set."
            }
        })
    }

    #[test]
    fn report_generation_forces_one_closed_structured_output() {
        let args = deep_research_report_generation_args("Write the report", 160_000);

        assert_eq!(args["mode"], "tool");
        assert_eq!(args["timeout_ms"], 160_000);
        assert_eq!(args["max_repair_attempts"], 1);
        assert_eq!(args["schema"]["additionalProperties"], false);
        assert_eq!(
            args["schema"]["properties"]["markdown"]["maxLength"],
            REPORT_MAX_CHARS
        );
        assert_eq!(
            args["schema"]["properties"]["presentation"]["properties"]["archetype"]["enum"],
            serde_json::json!([
                "editorial",
                "analytical",
                "chronicle",
                "executive",
                "field-notes"
            ])
        );
        assert!(args["system"]
            .as_str()
            .is_some_and(|system| system.contains("do not reuse a default style")));
    }

    #[test]
    fn report_generation_extracts_validated_content_and_art_direction() {
        let markdown = format!(
            "# Report\n\n## Findings\n\n{}\n\n## Sources\n\n- https://example.com/source\n\n## Limitations\n\nBounded evidence.",
            "Substantive source-backed analysis. ".repeat(5)
        );
        let output = serde_json::json!({
            "object": valid_object(markdown.clone()),
            "mode_used": "tool"
        })
        .to_string();

        let report = deep_research_report_from_generation(&output, 0).unwrap();
        assert_eq!(report.markdown, markdown);
        assert_eq!(report.presentation.archetype, ReportArchetype::Analytical);
        assert_eq!(report.presentation.hero, ReportHero::Metrics);
        assert_eq!(
            deep_research_report_markdown_from_generation(&output, 0).unwrap(),
            markdown
        );
        assert!(deep_research_report_from_generation(&output, 1).is_err());
        assert!(deep_research_report_from_generation("{}", 0).is_err());
    }

    #[test]
    fn report_generation_rejects_unapproved_presentation_values() {
        let markdown = "Substantive source-backed analysis. ".repeat(8);
        let mut object = valid_object(markdown);
        object["presentation"]["archetype"] = serde_json::json!("world-cup-special");
        let output = serde_json::json!({ "object": object }).to_string();

        let error = deep_research_report_from_generation(&output, 0).unwrap_err();
        assert!(error.contains("violated its contract"), "{error}");
    }
}