anda_engine 0.12.31

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! Persistent note tool for agent-scoped self-memory.
//!
//! This module provides:
//! - a durable note store backed by [`StoreFeatures`],
//! - tool input/output types for reading and mutating notes,
//! - and the public tool entrypoint ([`NoteTool`]).
//!
//! Notes are scoped to the current agent path. Since tools run under the
//! calling agent's context tree, one agent's notes are not visible to another.

use anda_core::{
    BoxError, FunctionDefinition, Path, PutMode, Resource, StoreFeatures, Tool, ToolOutput,
};
use ciborium::from_reader;
use ic_auth_types::deterministic_cbor_into_vec;
use object_store::Error as ObjectStoreError;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::HashSet;

use crate::{
    context::{AgentCtx, BaseCtx},
    hook::{DynToolHook, ToolHook},
};

const NOTE_ACTION_READ: &str = "read";
const NOTE_ACTION_ADD: &str = "add";
const NOTE_ACTION_REPLACE: &str = "replace";
const NOTE_ACTION_REMOVE: &str = "remove";
const NOTE_STORE_PATH: &str = "notes";
const NOTE_CHAR_LIMIT: usize = 16384;
const NOTE_MATCH_PREVIEW_LIMIT: usize = 120;
const NOTE_EMPTY_CONTENT: &str = "content cannot be empty";
const NOTE_EMPTY_OLD_TEXT: &str = "old_text cannot be empty";
const NOTE_ENTRY_DELIMITER: &str = "\n---\n";

static VALID_ACTIONS: &[&str] = &[
    NOTE_ACTION_READ,
    NOTE_ACTION_ADD,
    NOTE_ACTION_REPLACE,
    NOTE_ACTION_REMOVE,
];

/// Arguments accepted by the note tool.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct NoteArgs {
    /// Action to perform. Omit or use `read` to retrieve current notes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
    /// Note content for `add` and `replace`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    /// Unique substring used to identify a note for `replace` and `remove`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old_text: Option<String>,
}

/// Output returned by the note tool.
#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct NoteOutput {
    pub success: bool,
    pub notes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub usage: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matches: Option<Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)]
struct NoteStore {
    notes: Vec<String>,
}

impl NoteStore {
    fn usage(&self, char_limit: usize) -> String {
        let current = self.char_count();
        let pct = ((current * 100) / char_limit).min(100);
        format!("{pct}% - {current}/{char_limit} chars")
    }

    fn char_count(&self) -> usize {
        joined_len(&self.notes)
    }

    fn success_output(&self, message: Option<String>, char_limit: Option<usize>) -> NoteOutput {
        NoteOutput {
            success: true,
            notes: self.notes.clone(),
            usage: char_limit.map(|limit| self.usage(limit)),
            message,
            error: None,
            matches: None,
        }
    }

    fn failure_output(
        &self,
        error: String,
        matches: Option<Vec<String>>,
        char_limit: Option<usize>,
    ) -> NoteOutput {
        NoteOutput {
            success: false,
            notes: self.notes.clone(),
            usage: char_limit.map(|limit| self.usage(limit)),
            message: None,
            error: Some(error),
            matches,
        }
    }

    fn add(&mut self, content: String, char_limit: usize) -> NoteOutput {
        let content = content.trim();
        if content.is_empty() {
            return self.failure_output(NOTE_EMPTY_CONTENT.to_string(), None, Some(char_limit));
        }

        if self.notes.iter().any(|entry| entry == content) {
            return self.success_output(
                Some("Entry already exists (no duplicate added).".into()),
                Some(char_limit),
            );
        }

        let mut next = self.notes.clone();
        next.push(content.to_string());
        if let Err(error) = validate_note_size(&next) {
            return self.failure_output(error, None, Some(char_limit));
        }

        self.notes = next;
        self.success_output(Some("Entry added.".into()), Some(char_limit))
    }

    fn replace(&mut self, old_text: String, content: String, char_limit: usize) -> NoteOutput {
        let old_text = old_text.trim();
        if old_text.is_empty() {
            return self.failure_output(NOTE_EMPTY_OLD_TEXT.to_string(), None, Some(char_limit));
        }

        let content = content.trim();
        if content.is_empty() {
            return self.failure_output(NOTE_EMPTY_CONTENT.to_string(), None, Some(char_limit));
        }

        let matches = self.find_matches(old_text);
        let Some(index) = resolve_single_match(&matches) else {
            if matches.is_empty() {
                return self.failure_output(
                    format!("No entry matched {:?}.", old_text),
                    None,
                    Some(char_limit),
                );
            }

            return self.failure_output(
                format!("Multiple entries matched {:?}. Be more specific.", old_text),
                Some(preview_matches(&matches)),
                Some(char_limit),
            );
        };

        let mut next = self.notes.clone();
        next[index] = content.to_string();
        if let Err(error) = validate_note_size(&next) {
            return self.failure_output(error, None, Some(char_limit));
        }

        self.notes = next;
        self.success_output(Some("Entry replaced.".into()), Some(char_limit))
    }

    fn remove(&mut self, old_text: String, char_limit: usize) -> NoteOutput {
        let old_text = old_text.trim();
        if old_text.is_empty() {
            return self.failure_output(NOTE_EMPTY_OLD_TEXT.to_string(), None, Some(char_limit));
        }

        let matches = self.find_matches(old_text);
        let Some(index) = resolve_single_match(&matches) else {
            if matches.is_empty() {
                return self.failure_output(
                    format!("No entry matched {:?}.", old_text),
                    None,
                    Some(char_limit),
                );
            }

            return self.failure_output(
                format!("Multiple entries matched {:?}. Be more specific.", old_text),
                Some(preview_matches(&matches)),
                Some(char_limit),
            );
        };

        self.notes.remove(index);
        self.success_output(Some("Entry removed.".into()), Some(char_limit))
    }

    fn find_matches(&self, needle: &str) -> Vec<(usize, String)> {
        self.notes
            .iter()
            .enumerate()
            .filter(|(_, entry)| entry.contains(needle))
            .map(|(index, entry)| (index, entry.clone()))
            .collect()
    }
}

pub type NoteToolHook = DynToolHook<NoteArgs, NoteOutput>;

/// Tool implementation that exposes a persistent agent-scoped note store.
#[derive(Clone)]
pub struct NoteTool {
    char_limit: usize,
    description: String,
}

impl Default for NoteTool {
    fn default() -> Self {
        Self::new()
    }
}

impl NoteTool {
    /// Tool name used for registration and function definition.
    pub const NAME: &'static str = "note";

    /// Creates a note tool with the default behavioral guidance.
    pub fn new() -> Self {
        Self {
            char_limit: NOTE_CHAR_LIMIT,
            description: concat!(
                "Manage persistent notes for the current agent only. ",
                "These notes are stored durably and are isolated by agent, ",
                "so other agents cannot read them. ",
                "Call with no parameters or action=read to read the current notes.\n\n",
                "Writing:\n",
                "- action=add with content: append a new note\n",
                "- action=replace with old_text and content: replace one matching note\n",
                "- action=remove with old_text: remove one matching note\n\n",
                "Use short unique substrings for old_text. ",
                "Exact duplicate notes are ignored. ",
                "The store is bounded to prevent unbounded growth.\n\n",
                "Always returns the full current note list and usage."
            )
            .to_string(),
        }
    }

    pub fn with_char_limit(mut self, char_limit: usize) -> Self {
        self.char_limit = char_limit;
        self
    }

    pub fn with_description(mut self, description: String) -> Self {
        self.description = description;
        self
    }

    fn store_path(agent: &str) -> Path {
        Path::from(format!("{NOTE_STORE_PATH}:{agent}"))
    }

    async fn load_store(ctx: &BaseCtx) -> Result<NoteStore, BoxError> {
        match ctx.store_get(&Self::store_path(&ctx.agent)).await {
            Ok((data, _)) => Ok(from_reader(&data[..])?),
            Err(err) if is_missing_store_object(err.as_ref()) => Ok(NoteStore::default()),
            Err(err) => Err(err),
        }
    }

    async fn save_store(ctx: &BaseCtx, store: &NoteStore) -> Result<(), BoxError> {
        let data = deterministic_cbor_into_vec(store)?;
        ctx.store_put(
            &Self::store_path(&ctx.agent),
            PutMode::Overwrite,
            data.into(),
        )
        .await?;
        Ok(())
    }
}

/// Public entrypoint for loading notes outside of the tool call interface, e.g. in agent.
pub async fn load_notes(ctx: &AgentCtx) -> Option<NoteOutput> {
    let base_ctx = ctx.child_base(NoteTool::NAME).ok()?;
    NoteTool::load_store(&base_ctx)
        .await
        .ok()
        .map(|store| store.success_output(None, None))
}

impl Tool<BaseCtx> for NoteTool {
    type Args = NoteArgs;
    type Output = NoteOutput;

    fn name(&self) -> String {
        Self::NAME.to_string()
    }

    fn description(&self) -> String {
        self.description.clone()
    }

    fn definition(&self) -> FunctionDefinition {
        FunctionDefinition {
            name: self.name(),
            description: self.description(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "action": {
                        "type": ["string", "null"],
                        "enum": [
                            NOTE_ACTION_READ,
                            NOTE_ACTION_ADD,
                            NOTE_ACTION_REPLACE,
                            NOTE_ACTION_REMOVE,
                            null
                        ],
                        "description": "Action to perform. Use null or read to return the current notes.",
                        "default": NOTE_ACTION_READ
                    },
                    "content": {
                        "type": ["string", "null"],
                        "description": "Note content for add and replace."
                    },
                    "old_text": {
                        "type": ["string", "null"],
                        "description": "Unique substring identifying the note to replace or remove."
                    }
                },
                "required": ["action", "content", "old_text"],
                "additionalProperties": false
            }),
            strict: Some(true),
        }
    }

    async fn call(
        &self,
        ctx: BaseCtx,
        args: Self::Args,
        _resources: Vec<Resource>,
    ) -> Result<ToolOutput<Self::Output>, BoxError> {
        let hook = ctx.get_state::<NoteToolHook>();
        let args = if let Some(hook) = &hook {
            hook.before_tool_call(&ctx, args).await?
        } else {
            args
        };

        let mut store = Self::load_store(&ctx).await?;
        let action = args
            .action
            .as_deref()
            .map(|value| value.trim().to_ascii_lowercase())
            .unwrap_or_else(|| NOTE_ACTION_READ.to_string());

        let output = match action.as_str() {
            NOTE_ACTION_READ => store.success_output(None, Some(self.char_limit)),
            NOTE_ACTION_ADD => match args.content {
                Some(content) => {
                    let output = store.add(content, self.char_limit);
                    if output.success {
                        Self::save_store(&ctx, &store).await?;
                    }
                    output
                }
                None => store.failure_output(
                    "content is required for add".into(),
                    None,
                    Some(self.char_limit),
                ),
            },
            NOTE_ACTION_REPLACE => match (args.old_text, args.content) {
                (Some(old_text), Some(content)) => {
                    let output = store.replace(old_text, content, self.char_limit);
                    if output.success {
                        Self::save_store(&ctx, &store).await?;
                    }
                    output
                }
                (None, _) => store.failure_output(
                    "old_text is required for replace".into(),
                    None,
                    Some(self.char_limit),
                ),
                (_, None) => store.failure_output(
                    "content is required for replace".into(),
                    None,
                    Some(self.char_limit),
                ),
            },
            NOTE_ACTION_REMOVE => match args.old_text {
                Some(old_text) => {
                    let output = store.remove(old_text, self.char_limit);
                    if output.success {
                        Self::save_store(&ctx, &store).await?;
                    }
                    output
                }
                None => store.failure_output(
                    "old_text is required for remove".into(),
                    None,
                    Some(self.char_limit),
                ),
            },
            _ => store.failure_output(
                format!(
                    "Unknown action {:?}. Use one of: {}.",
                    action,
                    VALID_ACTIONS.join(", ")
                ),
                None,
                Some(self.char_limit),
            ),
        };

        let output = ToolOutput::new(output);
        if let Some(hook) = &hook {
            return hook.after_tool_call(&ctx, output).await;
        }

        Ok(output)
    }
}

fn validate_note_size(notes: &[String]) -> Result<(), String> {
    let current = joined_len(notes);
    if current > NOTE_CHAR_LIMIT {
        return Err(format!(
            "Notes use {current}/{NOTE_CHAR_LIMIT} chars. Shorten the new content or remove older notes first."
        ));
    }

    Ok(())
}

fn joined_len(notes: &[String]) -> usize {
    if notes.is_empty() {
        0
    } else {
        notes.join(NOTE_ENTRY_DELIMITER).chars().count()
    }
}

fn resolve_single_match(matches: &[(usize, String)]) -> Option<usize> {
    if matches.is_empty() {
        return None;
    }

    if matches.len() == 1 {
        return Some(matches[0].0);
    }

    let unique: HashSet<&str> = matches.iter().map(|(_, entry)| entry.as_str()).collect();
    if unique.len() == 1 {
        return Some(matches[0].0);
    }

    None
}

fn preview_matches(matches: &[(usize, String)]) -> Vec<String> {
    matches
        .iter()
        .map(|(_, entry)| {
            if entry.chars().count() > NOTE_MATCH_PREVIEW_LIMIT {
                format!(
                    "{}...",
                    entry
                        .chars()
                        .take(NOTE_MATCH_PREVIEW_LIMIT)
                        .collect::<String>()
                )
            } else {
                entry.clone()
            }
        })
        .collect()
}

fn is_missing_store_object(err: &(dyn std::error::Error + 'static)) -> bool {
    err.downcast_ref::<ObjectStoreError>()
        .is_some_and(|err| matches!(err, ObjectStoreError::NotFound { .. }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{context::AgentCtx, engine::EngineBuilder};
    use async_trait::async_trait;
    use std::sync::Arc;

    fn agent_ctx(name: &str) -> AgentCtx {
        EngineBuilder::new()
            .mock_ctx()
            .child(name, name)
            .expect("create child agent ctx")
    }

    fn note_ctx(name: &str) -> BaseCtx {
        agent_ctx(name)
            .child_base(NoteTool::NAME)
            .expect("create note tool ctx")
    }

    struct MutatingHook;

    #[async_trait]
    impl ToolHook<NoteArgs, NoteOutput> for MutatingHook {
        async fn before_tool_call(
            &self,
            _ctx: &BaseCtx,
            mut args: NoteArgs,
        ) -> Result<NoteArgs, BoxError> {
            args.action = Some(NOTE_ACTION_ADD.to_string());
            args.content = Some("hook inserted note".to_string());
            Ok(args)
        }

        async fn after_tool_call(
            &self,
            _ctx: &BaseCtx,
            mut output: ToolOutput<NoteOutput>,
        ) -> Result<ToolOutput<NoteOutput>, BoxError> {
            output.output.message = Some("hook observed output".to_string());
            Ok(output)
        }
    }

    #[test]
    fn store_add_replace_remove_match_memory_style() {
        let mut store = NoteStore::default();

        let added = store.add("remember the release checklist".into(), NOTE_CHAR_LIMIT);
        assert!(added.success);
        assert_eq!(
            store.notes,
            vec!["remember the release checklist".to_string()]
        );

        let duplicate = store.add("remember the release checklist".into(), NOTE_CHAR_LIMIT);
        assert!(duplicate.success);
        assert_eq!(store.notes.len(), 1);

        let replaced = store.replace(
            "release".into(),
            "remember the launch checklist".into(),
            NOTE_CHAR_LIMIT,
        );
        assert!(replaced.success);
        assert_eq!(
            store.notes,
            vec!["remember the launch checklist".to_string()]
        );

        let removed = store.remove("launch".into(), NOTE_CHAR_LIMIT);
        assert!(removed.success);
        assert!(store.notes.is_empty());
    }

    #[test]
    fn store_reports_ambiguous_matches() {
        let mut store = NoteStore {
            notes: vec![
                "remember alpha release".to_string(),
                "remember alpha rollout".to_string(),
            ],
        };

        let output = store.replace("alpha".into(), "new note".into(), NOTE_CHAR_LIMIT);
        assert!(!output.success);
        assert_eq!(store.notes.len(), 2);
        assert_eq!(output.matches.unwrap().len(), 2);
    }

    #[test]
    fn store_reports_empty_missing_limit_and_preview_errors() {
        let mut store = NoteStore::default();
        assert_eq!(store.usage(10), "0% - 0/10 chars");
        assert_eq!(
            store.add("   ".into(), NOTE_CHAR_LIMIT).error.as_deref(),
            Some(NOTE_EMPTY_CONTENT)
        );

        store.notes = vec![
            "alpha exact".to_string(),
            "alpha exact".to_string(),
            format!("alpha {}", "x".repeat(NOTE_MATCH_PREVIEW_LIMIT + 20)),
        ];
        let duplicate_match = store.replace("exact".into(), "changed".into(), NOTE_CHAR_LIMIT);
        assert!(duplicate_match.success);
        assert_eq!(store.notes[0], "changed");

        assert_eq!(
            store
                .replace(" ".into(), "new".into(), NOTE_CHAR_LIMIT)
                .error
                .as_deref(),
            Some(NOTE_EMPTY_OLD_TEXT)
        );
        assert_eq!(
            store
                .replace("alpha".into(), " ".into(), NOTE_CHAR_LIMIT)
                .error
                .as_deref(),
            Some(NOTE_EMPTY_CONTENT)
        );
        assert!(
            store
                .replace("missing".into(), "new".into(), NOTE_CHAR_LIMIT)
                .error
                .unwrap()
                .contains("No entry matched")
        );

        let ambiguous = store.remove("alpha".into(), NOTE_CHAR_LIMIT);
        assert!(!ambiguous.success);
        let previews = ambiguous.matches.unwrap();
        assert_eq!(previews.len(), 2);
        assert!(previews[1].ends_with("..."));

        assert_eq!(
            store.remove(" ".into(), NOTE_CHAR_LIMIT).error.as_deref(),
            Some(NOTE_EMPTY_OLD_TEXT)
        );
        assert!(
            store
                .remove("missing".into(), NOTE_CHAR_LIMIT)
                .error
                .unwrap()
                .contains("No entry matched")
        );

        let oversized = "x".repeat(NOTE_CHAR_LIMIT + 1);
        assert!(
            validate_note_size(&[oversized])
                .unwrap_err()
                .contains("Shorten")
        );
    }

    #[tokio::test]
    async fn tool_reads_empty_store_before_first_write() {
        let tool = NoteTool::new();
        let output = tool
            .call(note_ctx("writer"), NoteArgs::default(), Vec::new())
            .await
            .unwrap();

        assert!(output.output.success);
        assert!(output.output.notes.is_empty());
    }

    #[tokio::test]
    async fn tool_persists_notes_across_calls_for_same_agent() {
        let tool = NoteTool::new();
        let ctx = note_ctx("writer");

        let first = tool
            .call(
                ctx.clone(),
                NoteArgs {
                    action: Some(NOTE_ACTION_ADD.to_string()),
                    content: Some("remember to tag releases".to_string()),
                    old_text: None,
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert!(first.output.success);
        assert_eq!(
            first.output.notes,
            vec!["remember to tag releases".to_string()]
        );

        let second = tool
            .call(ctx.clone(), NoteArgs::default(), Vec::new())
            .await
            .unwrap();
        assert_eq!(second.output.notes, first.output.notes);

        let third = tool
            .call(
                ctx,
                NoteArgs {
                    action: Some(NOTE_ACTION_REPLACE.to_string()),
                    content: Some("remember to tag stable releases".to_string()),
                    old_text: Some("tag releases".to_string()),
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert!(third.output.success);
        assert_eq!(
            third.output.notes,
            vec!["remember to tag stable releases".to_string()]
        );
    }

    #[tokio::test]
    async fn tool_storage_is_isolated_between_agents() {
        let tool = NoteTool::new();

        let writer = tool
            .call(
                note_ctx("writer"),
                NoteArgs {
                    action: Some(NOTE_ACTION_ADD.to_string()),
                    content: Some("writer only note".to_string()),
                    old_text: None,
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert!(writer.output.success);
        assert_eq!(writer.output.notes, vec!["writer only note".to_string()]);

        let reviewer = tool
            .call(note_ctx("reviewer"), NoteArgs::default(), Vec::new())
            .await
            .unwrap();
        assert!(reviewer.output.success);
        assert!(reviewer.output.notes.is_empty());
    }

    #[tokio::test]
    async fn tool_reports_validation_errors_and_unknown_actions_without_persisting() {
        let tool = NoteTool::default()
            .with_char_limit(32)
            .with_description("custom note description".to_string());
        assert_eq!(tool.description(), "custom note description");
        let ctx = note_ctx("validation");

        let missing_content = tool
            .call(
                ctx.clone(),
                NoteArgs {
                    action: Some(NOTE_ACTION_ADD.to_string()),
                    content: None,
                    old_text: None,
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert_eq!(
            missing_content.output.error.as_deref(),
            Some("content is required for add")
        );
        assert_eq!(
            missing_content.output.usage.as_deref(),
            Some("0% - 0/32 chars")
        );

        for (action, expected) in [
            (NOTE_ACTION_REPLACE, "old_text is required for replace"),
            (NOTE_ACTION_REMOVE, "old_text is required for remove"),
        ] {
            let output = tool
                .call(
                    ctx.clone(),
                    NoteArgs {
                        action: Some(action.to_string()),
                        content: None,
                        old_text: None,
                    },
                    Vec::new(),
                )
                .await
                .unwrap();
            assert_eq!(output.output.error.as_deref(), Some(expected));
        }

        let missing_replace_content = tool
            .call(
                ctx.clone(),
                NoteArgs {
                    action: Some(NOTE_ACTION_REPLACE.to_string()),
                    content: None,
                    old_text: Some("entry".to_string()),
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert_eq!(
            missing_replace_content.output.error.as_deref(),
            Some("content is required for replace")
        );

        let unknown = tool
            .call(
                ctx.clone(),
                NoteArgs {
                    action: Some("archive".to_string()),
                    content: None,
                    old_text: None,
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert!(
            unknown
                .output
                .error
                .as_deref()
                .is_some_and(|error| error.contains("Unknown action"))
        );

        let read = tool
            .call(ctx, NoteArgs::default(), Vec::new())
            .await
            .unwrap();
        assert!(read.output.notes.is_empty());
    }

    #[tokio::test]
    async fn tool_hooks_and_load_notes_use_agent_scoped_store() {
        let engine_ctx = EngineBuilder::new().mock_ctx();
        let agent = engine_ctx
            .child("hooked", "hooked")
            .expect("create child agent ctx");
        let ctx = agent.child_base(NoteTool::NAME).unwrap();
        ctx.set_state(NoteToolHook::new(Arc::new(MutatingHook)));

        let tool = NoteTool::new();
        let output = tool
            .call(
                ctx,
                NoteArgs {
                    action: Some(NOTE_ACTION_READ.to_string()),
                    content: None,
                    old_text: None,
                },
                Vec::new(),
            )
            .await
            .unwrap();
        assert_eq!(output.output.notes, vec!["hook inserted note".to_string()]);
        assert_eq!(
            output.output.message.as_deref(),
            Some("hook observed output")
        );

        let loaded = load_notes(&agent).await.unwrap();
        assert!(loaded.success);
        assert_eq!(loaded.notes, vec!["hook inserted note".to_string()]);
        assert!(loaded.usage.is_none());
    }

    #[test]
    fn definition_schema_avoids_anyof() {
        let definition = NoteTool::new().definition();

        assert!(
            definition.parameters["properties"]["action"]
                .get("anyOf")
                .is_none()
        );
        assert_eq!(
            definition.parameters["properties"]["action"]["type"],
            json!(["string", "null"])
        );
        assert_eq!(
            definition.parameters["properties"]["action"]["enum"],
            json!([
                NOTE_ACTION_READ,
                NOTE_ACTION_ADD,
                NOTE_ACTION_REPLACE,
                NOTE_ACTION_REMOVE,
                null
            ])
        );
        assert_eq!(
            definition.parameters["required"],
            json!(["action", "content", "old_text"])
        );
    }
}