a3s 0.9.1

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
use super::*;

#[test]
fn parses_deepresearch_cli_options() {
    let opts = parse_deepresearch_args(&["--local".into(), "rust".into(), "async".into()])
        .expect("local deepresearch args");
    assert_eq!(opts.query, "rust async");
    assert_eq!(opts.runtime_mode, DeepResearchRuntimeMode::Local);

    let opts =
        parse_deepresearch_args(&["--os".into(), "market".into()]).expect("os deepresearch args");
    assert_eq!(opts.query, "market");
    assert_eq!(opts.runtime_mode, DeepResearchRuntimeMode::Os);

    let opts = parse_deepresearch_args(&["compare".into(), "runtimes".into()])
        .expect("auto deepresearch args");
    assert_eq!(opts.query, "compare runtimes");
    assert_eq!(opts.runtime_mode, DeepResearchRuntimeMode::Auto);
}

#[tokio::test]
async fn deepresearch_cli_os_mode_is_temporarily_disabled() {
    let err = execute_deepresearch_in(
        &["--os".into(), "market".into()],
        Path::new("."),
        CodeConfig::default(),
        PathBuf::from(".a3s/memory"),
    )
    .await
    .expect_err("--os should be disabled before touching OS Runtime");
    let message = err.to_string();
    assert!(message.contains("temporarily disabled"), "{message}");
    assert!(message.contains("Function-as-a-Service"), "{message}");
}

#[test]
fn deepresearch_cli_policy_only_allows_report_artifact_writes() {
    use a3s_code_core::permissions::PermissionDecision;

    let policy = deepresearch_cli_permission_policy();

    assert_eq!(
        policy.check(
            "write",
            &serde_json::json!({
                "file_path": ".a3s/research/local-test/report.md",
                "content": "# Report"
            })
        ),
        PermissionDecision::Allow
    );
    assert_eq!(
        policy.check(
            "Write",
            &serde_json::json!({
                "file_path": ".a3s/research/local-test/index.html",
                "content": "<!doctype html><html><body></body></html>"
            })
        ),
        PermissionDecision::Allow
    );
    assert_eq!(
        policy.check("web_search", &serde_json::json!({"query": "a3s"})),
        PermissionDecision::Allow
    );
    assert_eq!(
        policy.check("bash", &serde_json::json!({"command": "ls -la"})),
        PermissionDecision::Deny
    );
    assert_eq!(
        policy.check(
            "write",
            &serde_json::json!({"file_path": "README.md", "content": "oops"})
        ),
        PermissionDecision::Deny
    );
    assert_eq!(
        policy.check(
            "write",
            &serde_json::json!({
                "file_path": "/tmp/workspace/.a3s/research/local-test/index.html",
                "content": "ambiguous absolute path"
            })
        ),
        PermissionDecision::Deny
    );
    assert_eq!(
        policy.check(
            "write",
            &serde_json::json!({
                "file_path": ".a3s/research/local-test/../../README.md",
                "content": "path traversal"
            })
        ),
        PermissionDecision::Deny
    );
    assert_eq!(
        policy.check(
            "edit",
            &serde_json::json!({
                "file_path": ".a3s/research/local-test/..\\..\\README.md",
                "old_string": "before",
                "new_string": "after"
            })
        ),
        PermissionDecision::Deny
    );
    assert_eq!(
        policy.check("bash", &serde_json::json!({"command": "rm -rf target"})),
        PermissionDecision::Deny
    );
}

#[tokio::test]
async fn deepresearch_cli_synthesis_denies_non_report_writes_before_fallback() {
    let workspace = std::env::temp_dir().join(format!(
        "a3s-deepresearch-cli-denied-write-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&workspace).unwrap();
    let cfg = workspace.join("config.acl");
    test_config(&cfg);
    let agent = Agent::new(cfg.to_string_lossy().to_string()).await.unwrap();
    let llm = Arc::new(ScriptedLlmClient::new(vec![
        tool_call_response(
            "toolu_write_readme",
            "write",
            serde_json::json!({
                "file_path": "README.md",
                "content": "DeepResearch should not write ordinary workspace files.",
            }),
        ),
        text_response(
            "Synthesis recovered after a denied workspace write but did not write report files.",
        ),
        text_response("Repair also did not write report files."),
    ]));
    let report_tool_gate = DeepResearchReportToolGate::default();
    let permission_policy = deepresearch_cli_permission_policy();
    let opts = SessionOptions::new()
        .with_llm_client(llm)
        .with_permission_policy(permission_policy.clone())
        .with_permission_checker(Arc::new(DeepResearchPermissionChecker {
            base: permission_policy,
            report_tool_gate: report_tool_gate.clone(),
        }))
        .with_planning_mode(a3s_code_core::PlanningMode::Disabled)
        .with_max_tool_rounds(4);
    let session = agent
        .session_async(workspace.to_string_lossy().to_string(), Some(opts))
        .await
        .unwrap();
    let synthesis = synthesize_deepresearch_report(
        &session,
        &workspace,
        "denied write fallback",
        false,
        r#"{"mode":"local_parallel_task","research":"evidence after denied write"}"#,
        0,
        None,
        &report_tool_gate,
    )
    .await
    .expect("host fallback should materialize after denied non-report write");
    let DeepResearchReportSynthesis {
        text: final_text,
        artifacts,
        status,
    } = synthesis;

    assert_eq!(status, DeepResearchReportStatus::FallbackDraft);
    assert!(
        !workspace.join("README.md").exists(),
        "DeepResearch CLI policy must block non-report writes"
    );
    assert!(
        final_text.contains("DeepResearch fallback draft written at"),
        "{final_text}"
    );
    assert!(!final_text.contains("A3S_RESEARCH_VIEW"), "{final_text}");
    assert_eq!(
        artifacts.markdown,
        workspace
            .join(".a3s/research/denied-write-fallback/report.md")
            .canonicalize()
            .unwrap()
    );
    assert_eq!(
        artifacts.html,
        workspace
            .join(".a3s/research/denied-write-fallback/index.html")
            .canonicalize()
            .unwrap()
    );

    let _ = std::fs::remove_dir_all(&workspace);
}

#[tokio::test]
async fn deepresearch_cli_repair_pass_writes_required_markdown_and_html_artifacts() {
    let workspace = std::env::temp_dir().join(format!(
        "a3s-deepresearch-cli-artifacts-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&workspace).unwrap();
    let cfg = workspace.join("config.acl");
    test_config(&cfg);
    let agent = Agent::new(cfg.to_string_lossy().to_string()).await.unwrap();
    let llm = Arc::new(ScriptedLlmClient::new(vec![
        text_response("Initial synthesis without a report marker."),
        tool_call_response(
            "toolu_write_markdown",
            "write",
            serde_json::json!({
                "file_path": ".a3s/research/local-test/report.md",
                "content": "# Local Test\n\n## Findings\n\nThis source-backed markdown report summarizes the gathered DeepResearch evidence, explains the main finding, and records caveats for review.\n\n## Sources\n\n- https://example.com/research\n\n## Confidence\n\nConfidence is medium because this deterministic test evidence is compact but traceable.\n",
            }),
        ),
        tool_call_response(
            "toolu_write_html",
            "write",
            serde_json::json!({
                "file_path": ".a3s/research/local-test/index.html",
                "content": "<!doctype html><html><body><h1>Local Test</h1><section><h2>Findings</h2><p>This source-backed report summarizes gathered DeepResearch evidence, caveats, and the main finding for review.</p></section><section><h2>Sources</h2><p>Evidence source: https://example.com/research. Confidence is medium.</p></section></body></html>",
            }),
        ),
        text_response(
            "Step 2 complete: Markdown report written.\nTargeted verification could not be performed because file-read tooling is currently blocked.\nA3S_RESEARCH_VIEW: .a3s/research/local-test/index.html",
        ),
    ]));
    let report_tool_gate = DeepResearchReportToolGate::default();
    let permission_policy = deepresearch_cli_permission_policy();
    let opts = SessionOptions::new()
        .with_llm_client(llm)
        .with_permission_policy(permission_policy.clone())
        .with_permission_checker(Arc::new(DeepResearchPermissionChecker {
            base: permission_policy,
            report_tool_gate: report_tool_gate.clone(),
        }))
        .with_planning_mode(a3s_code_core::PlanningMode::Disabled)
        .with_max_tool_rounds(6);
    let session = agent
        .session_async(workspace.to_string_lossy().to_string(), Some(opts))
        .await
        .unwrap();

    let synthesis = synthesize_deepresearch_report(
        &session,
        &workspace,
        "local test",
        false,
        r#"{"mode":"local_parallel_task","research":"evidence"}"#,
        0,
        None,
        &report_tool_gate,
    )
    .await
    .unwrap_or_else(|error| {
        let markdown = workspace.join(".a3s/research/local-test/report.md");
        let html = workspace.join(".a3s/research/local-test/index.html");
        panic!(
            "{error}; markdown_exists={}; html_exists={}",
            markdown.exists(),
            html.exists()
        )
    });
    let DeepResearchReportSynthesis {
        text: final_text,
        artifacts,
        status,
    } = synthesis;

    assert_eq!(status, DeepResearchReportStatus::Completed);
    assert!(
        final_text.contains("A3S_RESEARCH_VIEW: .a3s/research/local-test/index.html"),
        "{final_text}"
    );
    assert!(
        final_text.contains("# Local Test"),
        "dirty repair text should be rebuilt from validated report.md: {final_text}"
    );
    assert!(
        !final_text.contains("Step 2 complete")
            && !final_text.contains("Targeted verification could not be performed"),
        "internal repair narration must not survive final synthesis text: {final_text}"
    );
    assert_eq!(
        artifacts.markdown,
        workspace
            .join(".a3s/research/local-test/report.md")
            .canonicalize()
            .unwrap()
    );
    assert_eq!(
        artifacts.html,
        workspace
            .join(".a3s/research/local-test/index.html")
            .canonicalize()
            .unwrap()
    );
    assert!(std::fs::metadata(&artifacts.markdown).unwrap().len() > 0);
    assert!(std::fs::metadata(&artifacts.html).unwrap().len() > 0);
    let _ = std::fs::remove_dir_all(&workspace);
}

#[tokio::test]
async fn deepresearch_cli_materializes_fallback_artifacts_when_model_never_writes_report() {
    let workspace = std::env::temp_dir().join(format!(
        "a3s-deepresearch-cli-fallback-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&workspace).unwrap();
    let cfg = workspace.join("config.acl");
    test_config(&cfg);
    let agent = Agent::new(cfg.to_string_lossy().to_string()).await.unwrap();
    let llm = Arc::new(ScriptedLlmClient::new(vec![
        text_response("Initial synthesis without report files."),
        text_response("Repair also forgot to write the report files."),
    ]));
    let opts = SessionOptions::new()
        .with_llm_client(llm)
        .with_planning_mode(a3s_code_core::PlanningMode::Disabled);
    let session = agent
        .session_async(workspace.to_string_lossy().to_string(), Some(opts))
        .await
        .unwrap();
    let report_tool_gate = DeepResearchReportToolGate::default();

    let synthesis = synthesize_deepresearch_report(
        &session,
        &workspace,
        "fallback only",
        false,
        r#"{"mode":"local_parallel_task","research":"fallback evidence"}"#,
        0,
        None,
        &report_tool_gate,
    )
    .await
    .expect("host fallback should materialize draft artifacts");
    let DeepResearchReportSynthesis {
        text: final_text,
        artifacts,
        status,
    } = synthesis;

    assert_eq!(status, DeepResearchReportStatus::FallbackDraft);
    assert!(
        final_text.contains("DeepResearch fallback draft written at"),
        "{final_text}"
    );
    assert!(!final_text.contains("A3S_RESEARCH_VIEW"), "{final_text}");
    assert_eq!(
        artifacts.markdown,
        workspace
            .join(".a3s/research/fallback-only/report.md")
            .canonicalize()
            .unwrap()
    );
    assert_eq!(
        artifacts.html,
        workspace
            .join(".a3s/research/fallback-only/index.html")
            .canonicalize()
            .unwrap()
    );
    let markdown = std::fs::read_to_string(&artifacts.markdown).unwrap();
    assert!(markdown.contains("Repair also forgot"));
    assert!(markdown.contains("fallback evidence"));
    assert!(markdown.contains("DeepResearch Fallback Draft"));
    assert!(!markdown.contains("A3S_RESEARCH_VIEW"));
    let html = std::fs::read_to_string(&artifacts.html).unwrap();
    assert!(html.contains("DeepResearch Fallback Draft"));
    assert!(html.contains("fallback evidence"));
    assert!(!html.contains("A3S_RESEARCH_VIEW"));

    let _ = std::fs::remove_dir_all(&workspace);
}

#[tokio::test]
async fn deepresearch_cli_failed_collection_without_sources_falls_back_without_model_recovery() {
    let workspace = std::env::temp_dir().join(format!(
        "a3s-deepresearch-cli-no-evidence-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&workspace).unwrap();
    let cfg = workspace.join("config.acl");
    test_config(&cfg);
    let agent = Agent::new(cfg.to_string_lossy().to_string()).await.unwrap();
    let llm = Arc::new(ScriptedLlmClient::new(vec![text_response(
        "Incorrect recovery should not be used.\nA3S_RESEARCH_VIEW: .a3s/research/no-evidence/index.html",
    )]));
    let opts = SessionOptions::new()
        .with_llm_client(llm)
        .with_planning_mode(a3s_code_core::PlanningMode::Disabled);
    let session = agent
        .session_async(workspace.to_string_lossy().to_string(), Some(opts))
        .await
        .unwrap();
    let report_tool_gate = DeepResearchReportToolGate::default();

    let synthesis = synthesize_deepresearch_report(
        &session,
        &workspace,
        "no evidence",
        false,
        "dynamic_workflow timed out before evidence was available",
        1,
        None,
        &report_tool_gate,
    )
    .await
    .expect("host fallback should materialize draft artifacts");

    assert_eq!(synthesis.status, DeepResearchReportStatus::FallbackDraft);
    assert!(
        synthesis
            .text
            .contains("DeepResearch fallback draft written at"),
        "{}",
        synthesis.text
    );
    assert!(!synthesis.text.contains("A3S_RESEARCH_VIEW"));
    let markdown = std::fs::read_to_string(&synthesis.artifacts.markdown).unwrap();
    assert!(markdown.contains("DeepResearch Fallback Draft"));
    assert!(markdown.contains("evidence collection failed"));
    assert!(!markdown.contains("Incorrect recovery should not be used"));

    let _ = std::fs::remove_dir_all(&workspace);
}

#[tokio::test]
async fn deepresearch_cli_dirty_synthesis_is_repaired_or_falls_back_cleanly() {
    let workspace = std::env::temp_dir().join(format!(
        "a3s-deepresearch-cli-dirty-fallback-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&workspace).unwrap();
    let cfg = workspace.join("config.acl");
    test_config(&cfg);
    let agent = Agent::new(cfg.to_string_lossy().to_string()).await.unwrap();
    let llm = Arc::new(ScriptedLlmClient::new(vec![
        text_response(
            "● Searched web fifa results\n⎿ [tool output truncated: showing first bytes]\nerror: Max tool rounds (30) exceeded",
        ),
        text_response(
            "DynamicWorkflowRuntime evidence package:\n```json\n{\"summary\":\"raw\",\"sources\":[],\"confidence\":\"low\"}\n```",
        ),
    ]));
    let opts = SessionOptions::new().with_planning_mode(a3s_code_core::PlanningMode::Disabled);
    let session = agent
        .session_async(
            workspace.to_string_lossy().to_string(),
            Some(opts.with_llm_client(llm)),
        )
        .await
        .unwrap();
    let report_tool_gate = DeepResearchReportToolGate::default();

    let synthesis = synthesize_deepresearch_report(
        &session,
        &workspace,
        "dirty fallback",
        false,
        r#"{"mode":"local_parallel_task","research":{"metadata":{"success_count":1,"task_count":1},"output":"● Searched web\n⎿ [tool output truncated]"}}"#,
        0,
        None,
        &report_tool_gate,
    )
    .await
    .expect("host fallback should materialize when synthesis remains dirty");
    let DeepResearchReportSynthesis {
        text: final_text,
        artifacts,
        status,
    } = synthesis;

    assert_eq!(status, DeepResearchReportStatus::FallbackDraft);
    assert!(
        final_text.contains("DeepResearch fallback draft written at"),
        "{final_text}"
    );
    assert!(!final_text.contains("A3S_RESEARCH_VIEW"), "{final_text}");
    assert!(
        !deep_research_output_has_internal_leak(&final_text),
        "{final_text}"
    );
    let markdown = std::fs::read_to_string(&artifacts.markdown).unwrap();
    let html = std::fs::read_to_string(&artifacts.html).unwrap();
    assert!(
        !deep_research_output_has_internal_leak(&markdown),
        "{markdown}"
    );
    assert!(!deep_research_output_has_internal_leak(&html), "{html}");

    let _ = std::fs::remove_dir_all(&workspace);
}