aidaemon 0.11.3

A personal AI agent that runs as a background daemon, accessible via Telegram, Slack, or Discord, with tool use, MCP integration, and persistent memory
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::agent::{tool_is_side_effecting, LearningContext};
use crate::tools::fs_utils;
use crate::traits::{ToolCallSemantics, ToolCapabilities, ToolTargetHint, ToolTargetHintKind};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EvidenceKind {
    FileRead,
    CommandOutput,
    GitState,
    ProcessState,
    ApiResponse,
    VerificationResult,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EvidenceTrust {
    Direct,
    Inferred,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EvidenceRecord {
    pub kind: EvidenceKind,
    pub source: String,
    pub observed_at: DateTime<Utc>,
    pub trust: EvidenceTrust,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub targets: Vec<ToolTargetHint>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct EvidenceState {
    pub target: Option<ToolTargetHint>,
    #[serde(default)]
    pub records: Vec<EvidenceRecord>,
    #[serde(default)]
    pub contradictions: Vec<String>,
    #[serde(default)]
    pub post_change_verification_done: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EvidenceGateViolation {
    pub kind: EvidenceKind,
    pub reason: String,
    pub coaching: String,
    pub target: Option<String>,
}

impl EvidenceState {
    pub fn record_direct(
        &mut self,
        kind: EvidenceKind,
        source: impl Into<String>,
        targets: Vec<ToolTargetHint>,
    ) {
        if self.target.is_none() {
            self.target = targets.first().cloned();
        }
        self.records.push(EvidenceRecord {
            kind,
            source: source.into(),
            observed_at: Utc::now(),
            trust: EvidenceTrust::Direct,
            targets,
        });
    }

    fn has_direct_targeted_evidence(&self, kind: EvidenceKind, expected: &ToolTargetHint) -> bool {
        self.records.iter().any(|record| {
            record.kind == kind
                && record.trust == EvidenceTrust::Direct
                && record
                    .targets
                    .iter()
                    .any(|target| target_matches_expected(target, expected))
        })
    }

    pub fn invalidate_file_read_path(&mut self, path: &str) {
        let expected = normalized_path_key(path);
        self.records.retain(|record| {
            if record.kind != EvidenceKind::FileRead {
                return true;
            }
            !record.targets.iter().any(|target| {
                target.kind == ToolTargetHintKind::Path
                    && normalized_path_key(&target.value) == expected
            })
        });
        if self.target.as_ref().is_some_and(|target| {
            target.kind == ToolTargetHintKind::Path
                && normalized_path_key(&target.value) == expected
        }) {
            self.target = None;
        }
    }

    pub fn clear_file_read_evidence(&mut self) {
        self.records
            .retain(|record| record.kind != EvidenceKind::FileRead);
        if self
            .target
            .as_ref()
            .is_some_and(|target| target.kind == ToolTargetHintKind::Path)
        {
            self.target = None;
        }
    }
}

fn normalized_path_key(path: &str) -> String {
    let normalized = fs_utils::validate_path(path)
        .ok()
        .and_then(|path| std::fs::canonicalize(&path).ok().or(Some(path)));
    normalized
        .map(|path| path.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string())
}

pub fn has_completed_side_effecting_tool_call(
    learning_ctx: &LearningContext,
    available_capabilities: &HashMap<String, ToolCapabilities>,
) -> bool {
    learning_ctx.tool_calls.iter().any(|tool_call| {
        tool_call
            .split('(')
            .next()
            .is_some_and(|name| tool_is_side_effecting(name, available_capabilities))
    })
}

pub fn assess_pre_execution_evidence_gate(
    tool_name: &str,
    raw_arguments: &str,
    evidence_state: &EvidenceState,
) -> Option<EvidenceGateViolation> {
    match tool_name {
        "edit_file" => {
            let target = path_target_hint(raw_arguments)?;
            if evidence_state.has_direct_targeted_evidence(EvidenceKind::FileRead, &target) {
                None
            } else {
                Some(EvidenceGateViolation {
                    kind: EvidenceKind::FileRead,
                    reason: "edit_file requires direct file-read evidence for the target path"
                        .to_string(),
                    coaching: format!(
                        "Before editing {}, use `read_file` on that exact path, then retry `edit_file`.",
                        target.value
                    ),
                    target: Some(target.value),
                })
            }
        }
        "write_file" => {
            let target = path_target_hint(raw_arguments)?;
            let path_exists = fs_utils::validate_path(&target.value)
                .map(|path| path.exists())
                .unwrap_or(false);
            if !path_exists
                || evidence_state.has_direct_targeted_evidence(EvidenceKind::FileRead, &target)
            {
                None
            } else {
                Some(EvidenceGateViolation {
                    kind: EvidenceKind::FileRead,
                    reason:
                        "overwriting an existing file requires direct file-read evidence first"
                            .to_string(),
                    coaching: format!(
                        "Before overwriting {}, use `read_file` on that path, then retry `write_file`.",
                        target.value
                    ),
                    target: Some(target.value),
                })
            }
        }
        "git_commit" => {
            let target = git_scope_target_hint(raw_arguments);
            if evidence_state.has_direct_targeted_evidence(EvidenceKind::GitState, &target) {
                None
            } else {
                Some(EvidenceGateViolation {
                    kind: EvidenceKind::GitState,
                    reason: "git_commit requires a fresh git state inspection first".to_string(),
                    coaching: format!(
                        "Inspect the repository state with `git_info` for {}, then retry `git_commit`.",
                        target.value
                    ),
                    target: Some(target.value),
                })
            }
        }
        _ => None,
    }
}

pub fn record_successful_tool_evidence(
    evidence_state: &mut EvidenceState,
    tool_name: &str,
    raw_arguments: &str,
    semantics: &ToolCallSemantics,
) {
    match tool_name {
        "read_file" if !semantics.target_hints.is_empty() => {
            evidence_state.record_direct(
                EvidenceKind::FileRead,
                tool_name,
                semantics.target_hints.clone(),
            );
        }
        "git_info" => {
            evidence_state.record_direct(
                EvidenceKind::GitState,
                tool_name,
                git_scope_targets(raw_arguments, semantics),
            );
        }
        "service_status" => {
            let targets = semantics.target_hints.clone();
            if !targets.is_empty() {
                evidence_state.record_direct(EvidenceKind::ProcessState, tool_name, targets);
            }
        }
        _ => {}
    }
}

fn extract_string_arg(raw_arguments: &str, keys: &[&str]) -> Option<String> {
    let parsed = serde_json::from_str::<serde_json::Value>(raw_arguments).ok()?;
    let map = parsed.as_object()?;
    for key in keys {
        if let Some(value) = map.get(*key).and_then(|value| value.as_str()) {
            let trimmed = value.trim();
            if !trimmed.is_empty() {
                return Some(trimmed.to_string());
            }
        }
    }
    None
}

fn path_target_hint(raw_arguments: &str) -> Option<ToolTargetHint> {
    extract_string_arg(raw_arguments, &["path", "file_path", "file", "filename"])
        .and_then(|path| ToolTargetHint::new(ToolTargetHintKind::Path, path))
}

fn git_scope_target_hint(raw_arguments: &str) -> ToolTargetHint {
    ToolTargetHint::new(
        ToolTargetHintKind::ProjectScope,
        extract_string_arg(raw_arguments, &["path", "repo_path", "repo_dir"])
            .unwrap_or_else(|| ".".to_string()),
    )
    .unwrap_or(ToolTargetHint {
        kind: ToolTargetHintKind::ProjectScope,
        value: ".".to_string(),
    })
}

fn git_scope_targets(raw_arguments: &str, semantics: &ToolCallSemantics) -> Vec<ToolTargetHint> {
    if semantics.target_hints.is_empty() {
        vec![git_scope_target_hint(raw_arguments)]
    } else {
        semantics.target_hints.clone()
    }
}

fn normalize_target_value(value: &str) -> String {
    let normalized = fs_utils::validate_path(value)
        .map(|path| path.to_string_lossy().to_string())
        .unwrap_or_else(|_| value.to_string());
    normalized
        .trim()
        .trim_end_matches(['/', '\\'])
        .to_ascii_lowercase()
}

fn target_matches_expected(observed: &ToolTargetHint, expected: &ToolTargetHint) -> bool {
    let compatible_kind = matches!(
        (observed.kind, expected.kind),
        (ToolTargetHintKind::Path, ToolTargetHintKind::Path)
            | (
                ToolTargetHintKind::ProjectScope,
                ToolTargetHintKind::ProjectScope
            )
            | (ToolTargetHintKind::Path, ToolTargetHintKind::ProjectScope)
            | (ToolTargetHintKind::ProjectScope, ToolTargetHintKind::Path)
    );
    if !compatible_kind {
        return false;
    }

    let observed = normalize_target_value(&observed.value);
    let expected = normalize_target_value(&expected.value);
    !observed.is_empty()
        && !expected.is_empty()
        && (observed == expected
            || observed.starts_with(&format!("{expected}/"))
            || expected.starts_with(&format!("{observed}/")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::{ToolCallSemantics, ToolTargetHintKind};

    #[test]
    fn edit_requires_prior_file_read() {
        let evidence = EvidenceState::default();
        let violation = assess_pre_execution_evidence_gate(
            "edit_file",
            r#"{"path":"/tmp/example.txt"}"#,
            &evidence,
        )
        .expect("edit_file should require prior read");
        assert_eq!(violation.kind, EvidenceKind::FileRead);
    }

    #[test]
    fn file_read_evidence_satisfies_edit_gate() {
        let mut evidence = EvidenceState::default();
        evidence.record_direct(
            EvidenceKind::FileRead,
            "read_file",
            vec![
                ToolTargetHint::new(ToolTargetHintKind::Path, "/tmp/example.txt")
                    .expect("path hint"),
            ],
        );
        let violation = assess_pre_execution_evidence_gate(
            "edit_file",
            r#"{"path":"/tmp/example.txt"}"#,
            &evidence,
        );
        assert!(violation.is_none());
    }

    #[test]
    fn git_commit_requires_git_state() {
        let evidence = EvidenceState::default();
        let violation =
            assess_pre_execution_evidence_gate("git_commit", r#"{"path":"."}"#, &evidence)
                .expect("git commit should require git state");
        assert_eq!(violation.kind, EvidenceKind::GitState);
    }

    #[test]
    fn git_info_registers_git_state() {
        let mut evidence = EvidenceState::default();
        record_successful_tool_evidence(
            &mut evidence,
            "git_info",
            r#"{"path":"."}"#,
            &ToolCallSemantics::observation(),
        );
        assert_eq!(evidence.records.len(), 1);
        assert_eq!(evidence.records[0].kind, EvidenceKind::GitState);
    }

    #[test]
    fn git_info_evidence_satisfies_git_commit_gate() {
        let mut evidence = EvidenceState::default();
        record_successful_tool_evidence(
            &mut evidence,
            "git_info",
            r#"{"path":"/tmp/example-repo"}"#,
            &ToolCallSemantics::observation(),
        );
        let violation = assess_pre_execution_evidence_gate(
            "git_commit",
            r#"{"path":"/tmp/example-repo","message":"checkpoint"}"#,
            &evidence,
        );
        assert!(violation.is_none());
    }

    #[test]
    fn invalidating_file_read_evidence_removes_only_matching_path() {
        let mut evidence = EvidenceState::default();
        for path in ["/tmp/a.md", "/tmp/b.md"] {
            evidence.record_direct(
                EvidenceKind::FileRead,
                "read_file",
                vec![ToolTargetHint::new(ToolTargetHintKind::Path, path).unwrap()],
            );
        }

        evidence.invalidate_file_read_path("/tmp/a.md");

        assert!(!evidence.has_direct_targeted_evidence(
            EvidenceKind::FileRead,
            &ToolTargetHint::new(ToolTargetHintKind::Path, "/tmp/a.md").unwrap()
        ));
        assert!(evidence.has_direct_targeted_evidence(
            EvidenceKind::FileRead,
            &ToolTargetHint::new(ToolTargetHintKind::Path, "/tmp/b.md").unwrap()
        ));
    }

    #[test]
    fn clearing_file_read_evidence_preserves_other_evidence_kinds() {
        let mut evidence = EvidenceState::default();
        evidence.record_direct(
            EvidenceKind::FileRead,
            "read_file",
            vec![ToolTargetHint::new(ToolTargetHintKind::Path, "/tmp/a.md").unwrap()],
        );
        evidence.record_direct(EvidenceKind::CommandOutput, "terminal", Vec::new());

        evidence.clear_file_read_evidence();

        assert_eq!(evidence.records.len(), 1);
        assert_eq!(evidence.records[0].kind, EvidenceKind::CommandOutput);
    }
}