a3s-code-core 6.3.0

A3S Code Core - Embeddable AI agent library with tool execution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
use super::*;

fn snapshot(state: &ExecutionLoopState) -> MemoryExtractionSnapshot {
    MemoryExtractionSnapshot::from_state(state)
}

#[test]
fn parses_fenced_extraction_json() {
    let items = parse_extracted_memories(
            r#"```json
{"items":[{"memory_type":"semantic","content":"A3S memory should store durable project facts.","importance":0.8,"tags":["A3S","Memory"],"source":"project_fact"}]}
```"#,
        )
        .unwrap();

    assert_eq!(items.len(), 1);
    assert_eq!(items[0].memory_type, "semantic");
}

#[test]
fn parser_keeps_valid_items_when_sibling_is_malformed() {
    let items = parse_extracted_memories(
            r#"{"items":[
                {"memory_type":"semantic","content":"A3S asks the LLM to judge every completed non-empty turn for durable memory.","importance":0.8,"tags":["memory"],"source":"project_fact"},
                {"memory_type":"semantic","content":42,"importance":"high"},
                {"memory_type":"procedural","content":"Run memory extraction tests after changing extraction parsing behavior.","importance":0.7,"tags":["tests"],"source":"workflow"}
            ]}"#,
        )
        .unwrap();

    assert_eq!(items.len(), 2);
    assert!(items[0].content.contains("completed non-empty turn"));
    assert!(items[1].content.contains("extraction parsing"));
}

#[test]
fn missing_extracted_content_is_skipped_during_item_conversion() {
    let extracted = ExtractedMemory {
        memory_type: "semantic".to_string(),
        content: String::new(),
        importance: Some(0.8),
        confidence: Some(0.9),
        tags: vec!["memory".to_string()],
        source: Some("project_fact".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This project fact affects future memory behavior.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    assert!(extracted
        .into_memory_item("remember memory behavior", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extracted_memory_becomes_tagged_item() {
    let extracted = ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Run focused memory tests after changing FileMemoryStore.".to_string(),
        importance: Some(0.9),
        confidence: Some(0.95),
        tags: vec!["Memory!".to_string(), "Tests".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This repeatable verification prevents storage regressions.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    let (item, supersedes, conflicts_with) = extracted
        .into_memory_item("optimize memory", "sess-1", &HashSet::new())
        .unwrap();
    assert!(supersedes.is_empty());
    assert!(conflicts_with.is_empty());
    assert_eq!(item.memory_type, MemoryType::Procedural);
    assert!(item.tags.contains(&"llm".to_string()));
    assert!(item.tags.contains(&"memory".to_string()));
    assert_eq!(item.metadata.get("source").unwrap(), "workflow");
    assert_eq!(item.metadata.get("confidence").unwrap(), "0.95");
    assert_eq!(item.metadata.get("scope").unwrap(), "workspace");
    assert_eq!(
        item.metadata.get("workspace").map(String::as_str),
        Some("optimize memory")
    );
    assert!(item.metadata.get("reason").unwrap().contains("regressions"));
    assert!(!item.metadata.contains_key("prompt"));
}

#[test]
fn extracted_memory_skips_sensitive_content() {
    let extracted = ExtractedMemory {
        memory_type: "semantic".to_string(),
        content: "The production API key is sk-1234567890abcdef1234567890abcdef.".to_string(),
        importance: Some(0.9),
        confidence: Some(0.95),
        tags: vec!["secret".to_string()],
        source: Some("project_fact".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("Future provider setup would otherwise use this value.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    assert!(extracted
        .into_memory_item("remember the key", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extracted_memory_does_not_persist_the_turn_prompt() {
    let extracted = ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Use environment variables when configuring provider credentials.".to_string(),
        importance: Some(0.8),
        confidence: Some(0.9),
        tags: vec!["config".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some(
            "This reusable rule prevents credentials from entering configuration.".to_string(),
        ),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    let (item, _, _) = extracted
        .into_memory_item("/workspace", "sess-1", &HashSet::new())
        .unwrap();

    assert!(!item.metadata.contains_key("prompt"));
}

#[test]
fn extraction_prompt_redacts_sensitive_turn_fields() {
    let prompt = build_extraction_prompt(
        "provider api_key = sk-1234567890abcdef1234567890abcdef",
        "Use token: ghp_1234567890abcdef1234567890abcdef",
        "assistant: password = supersecret123",
        "None",
        3,
    );

    assert!(prompt.contains(SENSITIVE_REDACTION));
    assert!(!prompt.contains("sk-1234567890abcdef"));
    assert!(!prompt.contains("ghp_1234567890abcdef"));
    assert!(!prompt.contains("supersecret123"));
}

#[test]
fn extraction_prompt_requires_plain_user_facing_learning_text() {
    let prompt = build_extraction_prompt("p", "r", "t", "None", 3);

    assert!(prompt.contains("plain user-facing language"));
    assert!(prompt.contains("at most 64 characters"));
    assert!(prompt.contains("agent or subagent orchestration"));
    assert!(prompt.contains("A task-specific direction is not a stable preference or skill"));
}

#[test]
fn extraction_rejects_missing_or_unknown_source() {
    let missing = ExtractedMemory {
        memory_type: "semantic".to_string(),
        content: "A3S memory uses LLM value judgment after completed turns.".to_string(),
        importance: Some(0.8),
        confidence: Some(0.9),
        tags: vec![],
        source: None,
        scope: Some("workspace".to_string()),
        reason: Some("This behavior controls future memory persistence.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };
    let extracted = ExtractedMemory {
        memory_type: "semantic".to_string(),
        content: "A3S memory lets the LLM judge value after completed turns.".to_string(),
        importance: Some(0.8),
        confidence: Some(0.9),
        tags: vec![],
        source: Some("api_key = sk-1234567890abcdef1234567890abcdef".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This behavior controls future memory persistence.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    assert!(missing
        .into_memory_item("memory design", "sess-1", &HashSet::new())
        .is_none());
    assert!(extracted
        .into_memory_item("memory design", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extraction_rejects_episodic_turn_history() {
    let extracted = ExtractedMemory {
        memory_type: "episodic".to_string(),
        content: "In this turn, the user asked the assistant to run the memory tests.".to_string(),
        importance: Some(0.9),
        confidence: Some(0.95),
        tags: vec!["history".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This only describes what happened in the current turn.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    assert!(extracted
        .into_memory_item("run memory tests", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extraction_rejects_low_importance_items() {
    let extracted = ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Run focused memory tests after changing memory persistence behavior.".to_string(),
        importance: Some(0.2),
        confidence: Some(0.95),
        tags: vec!["memory".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This repeatable check can prevent persistence regressions.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    assert!(extracted
        .into_memory_item("memory design", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extraction_requires_confident_scoped_and_justified_llm_judgement() {
    let candidate = || ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Run focused memory tests after changing memory persistence behavior.".to_string(),
        importance: Some(0.85),
        confidence: Some(0.95),
        tags: vec!["memory".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This repeatable check prevents future persistence regressions.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution: None,
    };

    let mut low_confidence = candidate();
    low_confidence.confidence = Some(0.4);
    assert!(low_confidence
        .into_memory_item("/workspace", "sess-1", &HashSet::new())
        .is_none());

    let mut missing_scope = candidate();
    missing_scope.scope = None;
    assert!(missing_scope
        .into_memory_item("/workspace", "sess-1", &HashSet::new())
        .is_none());

    let mut missing_reason = candidate();
    missing_reason.reason = None;
    assert!(missing_reason
        .into_memory_item("/workspace", "sess-1", &HashSet::new())
        .is_none());
}

#[test]
fn extracted_memory_records_allowed_supersedes() {
    let allowed_id = uuid::Uuid::new_v4().to_string();
    let ignored_id = uuid::Uuid::new_v4().to_string();
    let allowed = HashSet::from([allowed_id.clone()]);
    let extracted = ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Run focused memory and file-store tests after changing memory persistence."
            .to_string(),
        importance: Some(0.9),
        confidence: Some(0.95),
        tags: vec!["memory".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This verification workflow prevents persistence regressions.".to_string()),
        supersedes: vec![allowed_id.clone(), ignored_id],
        conflicts_with: vec![],
        evolution: None,
    };

    let (item, supersedes, conflicts_with) = extracted
        .into_memory_item("memory design", "sess-1", &allowed)
        .unwrap();

    assert_eq!(supersedes, vec![allowed_id.clone()]);
    assert!(conflicts_with.is_empty());
    assert!(item.tags.contains(&"consolidated".to_string()));
    assert_eq!(item.metadata.get("supersedes").unwrap(), &allowed_id);
}

#[test]
fn extracted_memory_records_allowed_conflicts() {
    let conflict_id = uuid::Uuid::new_v4().to_string();
    let ignored_id = uuid::Uuid::new_v4().to_string();
    let allowed = HashSet::from([conflict_id.clone()]);
    let extracted = ExtractedMemory {
        memory_type: "semantic".to_string(),
        content: "This project currently prefers workspace-local memory stores.".to_string(),
        importance: Some(0.75),
        confidence: Some(0.9),
        tags: vec!["memory".to_string()],
        source: Some("decision".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some("This decision determines where future sessions persist memory.".to_string()),
        supersedes: vec![],
        conflicts_with: vec![conflict_id.clone(), ignored_id],
        evolution: None,
    };

    let (item, supersedes, conflicts_with) = extracted
        .into_memory_item("memory design", "sess-1", &allowed)
        .unwrap();

    assert!(supersedes.is_empty());
    assert_eq!(conflicts_with, vec![conflict_id.clone()]);
    assert!(item.tags.contains(&"conflict".to_string()));
    assert_eq!(item.metadata.get("conflicts_with").unwrap(), &conflict_id);
}

#[test]
fn extracted_evolution_signal_populates_validated_metadata() {
    let extracted = reusable_skill_memory(Some(ExtractedEvolution {
        kind: "skill".to_string(),
        pattern_key: " Skill / Focused Verification ".to_string(),
        title: "Focused verification".to_string(),
        summary: "Run the smallest relevant checks before broad validation.".to_string(),
        instructions: vec![
            "Identify the smallest relevant test target.".to_string(),
            "Run focused checks before the full workspace suite.".to_string(),
        ],
    }));

    let (item, _, _) = extracted
        .into_memory_item("/workspace", "session-one", &HashSet::new())
        .unwrap();

    assert!(item.tags.contains(&"evolution".to_string()));
    assert!(item.tags.contains(&"evolution-skill".to_string()));
    assert_eq!(
        item.metadata.get("evolution_kind").map(String::as_str),
        Some("skill")
    );
    assert_eq!(
        item.metadata.get("evolution_pattern").map(String::as_str),
        Some("skill.focused.verification")
    );
    let instructions: Vec<String> =
        serde_json::from_str(item.metadata.get("evolution_instructions").unwrap()).unwrap();
    assert_eq!(instructions.len(), 2);
    assert!(instructions[0].contains("smallest relevant test target"));
}

#[test]
fn invalid_or_sensitive_evolution_description_is_not_persisted() {
    let cases = [
        ExtractedEvolution {
            kind: "preference".to_string(),
            pattern_key: "preference.output.concise".to_string(),
            title: "Concise output".to_string(),
            summary: "Keep future responses compact and evidence-backed.".to_string(),
            instructions: vec!["Lead with the result before details.".to_string()],
        },
        ExtractedEvolution {
            kind: "skill".to_string(),
            pattern_key: "single".to_string(),
            title: "Invalid pattern".to_string(),
            summary: "This pattern lacks the required semantic segments.".to_string(),
            instructions: vec!["Run the relevant validation target.".to_string()],
        },
        ExtractedEvolution {
            kind: "skill".to_string(),
            pattern_key: "skill.provider.setup".to_string(),
            title: "Provider setup".to_string(),
            summary: "Configure the provider using the reusable local workflow.".to_string(),
            instructions: vec!["Set api_key=supersecret123 before running the command.".to_string()],
        },
    ];

    for signal in cases {
        let extracted = reusable_skill_memory(Some(signal));
        let (item, _, _) = extracted
            .into_memory_item("/workspace", "session-one", &HashSet::new())
            .unwrap();
        assert!(!item.tags.contains(&"evolution".to_string()));
        assert!(!item.metadata.contains_key("evolution_kind"));
        assert!(!item.metadata.contains_key("evolution_instructions"));
    }
}

#[test]
fn overlong_evolution_copy_is_not_persisted() {
    let cases = [
        ExtractedEvolution {
            kind: "skill".to_string(),
            pattern_key: "skill.focused.verification".to_string(),
            title:
                "A very long internal orchestration title that cannot fit in the product interface"
                    .to_string(),
            summary: "Run the smallest relevant checks before broad validation.".to_string(),
            instructions: vec!["Run the smallest relevant test target first.".to_string()],
        },
        ExtractedEvolution {
            kind: "skill".to_string(),
            pattern_key: "skill.focused.verification".to_string(),
            title: "Focused verification".to_string(),
            summary: "x".repeat(MAX_EVOLUTION_SUMMARY_CHARS + 1),
            instructions: vec!["Run the smallest relevant test target first.".to_string()],
        },
        ExtractedEvolution {
            kind: "skill".to_string(),
            pattern_key: "skill.focused.verification".to_string(),
            title: "Focused verification".to_string(),
            summary: "Run the smallest relevant checks before broad validation.".to_string(),
            instructions: vec!["x".repeat(MAX_EVOLUTION_INSTRUCTION_CHARS + 1)],
        },
    ];

    for signal in cases {
        let extracted = reusable_skill_memory(Some(signal));
        let (item, _, _) = extracted
            .into_memory_item("/workspace", "session-one", &HashSet::new())
            .unwrap();
        assert!(!item.tags.contains(&"evolution".to_string()));
    }
}

fn reusable_skill_memory(evolution: Option<ExtractedEvolution>) -> ExtractedMemory {
    ExtractedMemory {
        memory_type: "procedural".to_string(),
        content: "Run focused checks after changing memory persistence behavior.".to_string(),
        importance: Some(0.9),
        confidence: Some(0.95),
        tags: vec!["memory".to_string(), "tests".to_string()],
        source: Some("workflow".to_string()),
        scope: Some("workspace".to_string()),
        reason: Some(
            "This repeatable workflow prevents future persistence regressions.".to_string(),
        ),
        supersedes: vec![],
        conflicts_with: vec![],
        evolution,
    }
}

#[test]
fn related_memories_are_formatted_as_json_lines() {
    let item = MemoryItem::new("Run focused memory store tests after FileMemoryStore changes.")
        .with_type(MemoryType::Procedural)
        .with_importance(0.84)
        .with_tag("Memory!")
        .with_metadata("source", "workflow");

    let formatted = format_related_memories_for_extraction(vec![item.clone()]);

    assert!(formatted.prompt.contains(&format!(r#""id":"{}""#, item.id)));
    assert!(formatted.prompt.contains(r#""type":"procedural""#));
    assert!(formatted.prompt.contains(r#""source":"workflow""#));
    assert!(formatted.prompt.contains(r#""tags":["memory"]"#));
    assert!(formatted.prompt.contains("FileMemoryStore changes"));
    assert!(formatted.allowed_supersedes.contains(&item.id));
}

#[test]
fn related_memories_include_existing_relation_metadata() {
    let item =
        MemoryItem::new("Use the consolidated memory workflow for project-specific preferences.")
            .with_type(MemoryType::Semantic)
            .with_metadata("supersedes", "old-preference, bad id with spaces")
            .with_metadata("conflicts_with", "legacy-default,<script>");

    let formatted = format_related_memories_for_extraction(vec![item]);

    assert!(formatted
        .prompt
        .contains(r#""supersedes":["old-preference"]"#));
    assert!(formatted
        .prompt
        .contains(r#""conflicts_with":["legacy-default"]"#));
    assert!(!formatted.prompt.contains("bad id with spaces"));
    assert!(!formatted.prompt.contains("<script>"));
}

#[test]
fn related_memories_skip_sensitive_items() {
    let secret = MemoryItem::new("The provider token is sk-1234567890abcdef1234567890abcdef.")
        .with_type(MemoryType::Semantic);
    let safe = MemoryItem::new("Prefer environment variables for provider credentials.")
        .with_type(MemoryType::Procedural);

    let formatted = format_related_memories_for_extraction(vec![secret, safe]);

    assert!(!formatted.prompt.contains("sk-1234567890abcdef"));
    assert!(formatted.prompt.contains("environment variables"));
    assert_eq!(formatted.allowed_supersedes.len(), 1);
}

#[tokio::test]
async fn related_memories_are_loaded_for_extraction_prompt() {
    let memory = Arc::new(AgentMemory::new(Arc::new(a3s_memory::InMemoryStore::new())));
    memory
        .remember(
            MemoryItem::new(
                "Run focused memory store tests after changing FileMemoryStore behavior.",
            )
            .with_type(MemoryType::Procedural)
            .with_tag("memory"),
        )
        .await
        .unwrap();

    let related = related_memories_for_extraction(
        &memory,
        "remember FileMemoryStore testing workflow",
        "Use focused memory tests.",
    )
    .await;
    let prompt = build_extraction_prompt("p", "r", "t", &related.prompt, 2);

    assert!(prompt.contains("Related existing memories"));
    assert!(prompt.contains("FileMemoryStore behavior"));
    assert!(prompt.contains("avoid duplicates"));
    assert_eq!(related.allowed_supersedes.len(), 1);
}

#[test]
fn duplicate_memory_detection_only_handles_exact_normalized_content() {
    assert!(memory_contents_are_duplicates(
        "Run focused memory store tests after changing FileMemoryStore behavior.",
        "  run focused memory store tests after changing FileMemoryStore behavior.  "
    ));
    assert!(!memory_contents_are_duplicates(
        "Run focused memory store regression tests after changing FileMemoryStore behavior.",
        "Run focused memory store tests after changing FileMemoryStore behavior."
    ));
    assert!(!memory_contents_are_duplicates(
        "Run focused memory store tests after changing FileMemoryStore behavior.",
        "Prefer HCL configuration files for repository-level product settings."
    ));
}

#[test]
fn extraction_evaluation_requires_a_completed_turn() {
    let state = ExecutionLoopState::new(&[]);
    assert!(!should_attempt_llm_memory_extraction(
        &snapshot(&state),
        "",
        "hello"
    ));
    assert!(!should_attempt_llm_memory_extraction(
        &snapshot(&state),
        "hello",
        ""
    ));
}

#[test]
fn every_completed_turn_is_sent_to_the_llm_value_judge() {
    let state = ExecutionLoopState::new(&[]);
    assert!(should_attempt_llm_memory_extraction(
        &snapshot(&state),
        "hi",
        "hello"
    ));
    assert!(should_attempt_llm_memory_extraction(
        &snapshot(&state),
        "请继续",
        "好的"
    ));
}