car-memgine 0.15.1

Memgine — graph-based memory engine for Common Agent Runtime
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
//! Deterministic constraint pre-computation.
//!
//! Evaluates constraints against known facts before the LLM sees them.
//! When a constraint can be resolved deterministically (e.g., numeric
//! comparison), it's annotated with pass/fail so the LLM doesn't have
//! to do the math.
//!
//! Inspired by StateBench's Honcho-inspired constraint checker.

use std::fmt;

/// Result of pre-evaluating a constraint.
#[derive(Debug, Clone)]
pub struct ConstraintCheckResult {
    /// The constraint being checked.
    pub constraint_key: String,
    pub constraint_text: String,
    /// pass / fail / unknown
    pub status: ConstraintStatus,
    /// Human-readable explanation.
    pub reason: String,
    /// Fact keys used in evaluation.
    pub relevant_facts: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConstraintStatus {
    /// Constraint is satisfied.
    Pass,
    /// Constraint is violated.
    Fail,
    /// Cannot evaluate deterministically.
    Unknown,
}

impl fmt::Display for ConstraintStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConstraintStatus::Pass => write!(f, "PASS"),
            ConstraintStatus::Fail => write!(f, "FAIL"),
            ConstraintStatus::Unknown => write!(f, "UNKNOWN"),
        }
    }
}

/// A fact's key-value for constraint evaluation.
#[derive(Debug, Clone)]
pub struct FactValue {
    pub key: String,
    pub value: String,
}

/// Check all constraints against all known facts.
pub fn check_constraints(
    constraints: &[FactValue],
    facts: &[FactValue],
) -> Vec<ConstraintCheckResult> {
    constraints.iter().map(|c| check_one(c, facts)).collect()
}

/// Check a single constraint against all facts.
fn check_one(constraint: &FactValue, facts: &[FactValue]) -> ConstraintCheckResult {
    let c_text = &constraint.value;
    let c_lower = c_text.to_lowercase();

    // Budget/cost constraints: "budget is $X" or "cannot exceed $X"
    if is_budget_constraint(&c_lower) {
        if let Some(limit) = extract_dollar_amount(c_text) {
            // Look for a matching spending/cost fact
            for fact in facts {
                let f_lower = fact.value.to_lowercase();
                if f_lower.contains("cost")
                    || f_lower.contains("spend")
                    || f_lower.contains("price")
                    || f_lower.contains("total")
                    || f_lower.contains("budget")
                {
                    if let Some(amount) = extract_dollar_amount(&fact.value) {
                        let status = if amount <= limit {
                            ConstraintStatus::Pass
                        } else {
                            ConstraintStatus::Fail
                        };
                        return ConstraintCheckResult {
                            constraint_key: constraint.key.clone(),
                            constraint_text: c_text.clone(),
                            status,
                            reason: format!(
                                "${:.0} {} ${:.0} limit",
                                amount,
                                if amount <= limit { "within" } else { "exceeds" },
                                limit,
                            ),
                            relevant_facts: vec![fact.key.clone()],
                        };
                    }
                }
            }
        }
    }

    // Capacity constraints: "maximum N people/units"
    if is_capacity_constraint(&c_lower) {
        if let Some(limit) = extract_count(&c_lower) {
            for fact in facts {
                let f_lower = fact.value.to_lowercase();
                if let Some(count) = extract_count(&f_lower) {
                    if fact.key.to_lowercase().contains(
                        &constraint
                            .key
                            .to_lowercase()
                            .replace("_limit", "")
                            .replace("_cap", "")
                            .replace("_max", ""),
                    ) || f_lower.contains("team")
                        || f_lower.contains("staff")
                        || f_lower.contains("assigned")
                        || f_lower.contains("current")
                    {
                        let status = if count <= limit {
                            ConstraintStatus::Pass
                        } else {
                            ConstraintStatus::Fail
                        };
                        return ConstraintCheckResult {
                            constraint_key: constraint.key.clone(),
                            constraint_text: c_text.clone(),
                            status,
                            reason: format!(
                                "{} {} {} limit",
                                count,
                                if count <= limit { "within" } else { "exceeds" },
                                limit,
                            ),
                            relevant_facts: vec![fact.key.clone()],
                        };
                    }
                }
            }
        }
    }

    // Approval constraints: "requires approval from X"
    if is_approval_constraint(&c_lower) {
        for fact in facts {
            let f_lower = fact.value.to_lowercase();
            if f_lower.contains("approved")
                || f_lower.contains("signed off")
                || f_lower.contains("authorized")
            {
                return ConstraintCheckResult {
                    constraint_key: constraint.key.clone(),
                    constraint_text: c_text.clone(),
                    status: ConstraintStatus::Pass,
                    reason: "approval found".into(),
                    relevant_facts: vec![fact.key.clone()],
                };
            }
        }
        // No approval found — still unknown (approval might come later)
    }

    // Can't evaluate deterministically
    ConstraintCheckResult {
        constraint_key: constraint.key.clone(),
        constraint_text: c_text.clone(),
        status: ConstraintStatus::Unknown,
        reason: "cannot evaluate deterministically".into(),
        relevant_facts: vec![],
    }
}

/// Format constraint check results as a context section.
pub fn format_checklist(results: &[ConstraintCheckResult]) -> String {
    if results.is_empty() {
        return String::new();
    }

    let mut lines = vec!["## Constraint Pre-Check".to_string()];
    for r in results {
        let icon = match r.status {
            ConstraintStatus::Pass => "",
            ConstraintStatus::Fail => "",
            ConstraintStatus::Unknown => "",
        };
        lines.push(format!(
            "{} {} [{}]: {}",
            icon, r.status, r.constraint_key, r.reason
        ));
    }
    lines.join("\n")
}

// --- Extractors ---

fn extract_dollar_amount(text: &str) -> Option<f64> {
    // Try $XM, $XK, then plain $X
    let re_m = regex_lite_find(text, r"\$\s*([\d,]+(?:\.\d+)?)\s*[Mm]");
    if let Some(s) = re_m {
        return parse_number(&s).map(|n| n * 1_000_000.0);
    }

    let re_k = regex_lite_find(text, r"\$\s*([\d,]+(?:\.\d+)?)\s*[Kk]");
    if let Some(s) = re_k {
        return parse_number(&s).map(|n| n * 1000.0);
    }

    // Plain dollar amount
    let chars: Vec<char> = text.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c == '$' {
            let start = i + 1;
            // Skip whitespace after $
            let start = chars[start..]
                .iter()
                .position(|c| !c.is_whitespace())
                .map(|p| start + p)
                .unwrap_or(start);
            let end = chars[start..]
                .iter()
                .position(|c| !c.is_ascii_digit() && *c != ',' && *c != '.')
                .map(|p| start + p)
                .unwrap_or(chars.len());
            let num_str: String = chars[start..end].iter().collect();
            return parse_number(&num_str);
        }
    }
    None
}

fn extract_count(text: &str) -> Option<u64> {
    // Look for "N people/engineers/staff/units/items"
    let words: Vec<&str> = text.split_whitespace().collect();
    let count_contexts = [
        "people",
        "engineers",
        "staff",
        "team",
        "members",
        "seats",
        "units",
        "items",
        "projects",
        "employees",
    ];

    for (i, word) in words.iter().enumerate() {
        if let Ok(n) = word.parse::<u64>() {
            // Check if next word is a count context
            if i + 1 < words.len()
                && count_contexts
                    .iter()
                    .any(|ctx| words[i + 1].starts_with(ctx))
            {
                return Some(n);
            }
        }
    }
    // Fallback: just find a number
    for word in &words {
        if let Ok(n) = word.parse::<u64>() {
            return Some(n);
        }
    }
    None
}

fn is_budget_constraint(text: &str) -> bool {
    [
        "budget",
        "limit",
        "cap",
        "maximum",
        "cannot exceed",
        "spending",
        "allocation",
        "ceiling",
    ]
    .iter()
    .any(|kw| text.contains(kw))
}

fn is_capacity_constraint(text: &str) -> bool {
    [
        "capacity",
        "maximum",
        "headcount",
        "limit",
        "no more than",
        "at most",
    ]
    .iter()
    .any(|kw| text.contains(kw))
}

fn is_approval_constraint(text: &str) -> bool {
    [
        "approval required",
        "needs approval",
        "must be approved",
        "requires sign-off",
        "authorization required",
    ]
    .iter()
    .any(|kw| text.contains(kw))
}

fn parse_number(s: &str) -> Option<f64> {
    s.replace(',', "").parse::<f64>().ok()
}

/// Simple regex-like pattern matching for dollar amounts.
/// Returns the numeric part (without $ and suffix).
fn regex_lite_find(text: &str, _pattern: &str) -> Option<String> {
    // We don't want to add a regex dependency, so we do targeted parsing.
    // The caller tells us the pattern type via the pattern string.
    if _pattern.contains("[Mm]") {
        // Looking for $X.XM
        if let Some(dollar_pos) = text.find('$') {
            let after = &text[dollar_pos + 1..];
            let after = after.trim_start();
            let end = after
                .find(|c: char| !c.is_ascii_digit() && c != ',' && c != '.')
                .unwrap_or(after.len());
            let num = &after[..end];
            let suffix = after[end..].trim_start();
            if suffix.starts_with('M') || suffix.starts_with('m') {
                return Some(num.to_string());
            }
        }
    } else if _pattern.contains("[Kk]") {
        if let Some(dollar_pos) = text.find('$') {
            let after = &text[dollar_pos + 1..];
            let after = after.trim_start();
            let end = after
                .find(|c: char| !c.is_ascii_digit() && c != ',' && c != '.')
                .unwrap_or(after.len());
            let num = &after[..end];
            let suffix = after[end..].trim_start();
            if suffix.starts_with('K') || suffix.starts_with('k') {
                return Some(num.to_string());
            }
        }
    }
    None
}

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

    #[test]
    fn extract_plain_dollar() {
        assert_eq!(extract_dollar_amount("budget is $150,000"), Some(150_000.0));
        assert_eq!(extract_dollar_amount("costs $2,500"), Some(2500.0));
    }

    #[test]
    fn extract_dollar_k() {
        assert_eq!(extract_dollar_amount("budget: $200K"), Some(200_000.0));
    }

    #[test]
    fn extract_dollar_m() {
        assert_eq!(extract_dollar_amount("total $1.5M"), Some(1_500_000.0));
    }

    #[test]
    fn budget_constraint_pass() {
        let constraints = vec![FactValue {
            key: "project_budget".into(),
            value: "Budget limit: $200,000".into(),
        }];
        let facts = vec![FactValue {
            key: "current_spending".into(),
            value: "Total cost so far: $150,000".into(),
        }];
        let results = check_constraints(&constraints, &facts);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].status, ConstraintStatus::Pass);
    }

    #[test]
    fn budget_constraint_fail() {
        let constraints = vec![FactValue {
            key: "project_budget".into(),
            value: "Budget limit: $100,000".into(),
        }];
        let facts = vec![FactValue {
            key: "current_spending".into(),
            value: "Total cost: $150,000".into(),
        }];
        let results = check_constraints(&constraints, &facts);
        assert_eq!(results[0].status, ConstraintStatus::Fail);
    }

    #[test]
    fn unknown_when_no_matching_facts() {
        let constraints = vec![FactValue {
            key: "approval".into(),
            value: "Requires VP approval".into(),
        }];
        let results = check_constraints(&constraints, &[]);
        assert_eq!(results[0].status, ConstraintStatus::Unknown);
    }

    #[test]
    fn format_checklist_output() {
        let results = vec![
            ConstraintCheckResult {
                constraint_key: "budget".into(),
                constraint_text: "Budget $200K".into(),
                status: ConstraintStatus::Pass,
                reason: "$150000 within $200000 limit".into(),
                relevant_facts: vec!["spending".into()],
            },
            ConstraintCheckResult {
                constraint_key: "approval".into(),
                constraint_text: "Needs VP sign-off".into(),
                status: ConstraintStatus::Unknown,
                reason: "cannot evaluate deterministically".into(),
                relevant_facts: vec![],
            },
        ];
        let output = format_checklist(&results);
        assert!(output.contains("PASS"));
        assert!(output.contains("UNKNOWN"));
        assert!(output.contains("Constraint Pre-Check"));
    }
}