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
//! Search strategies for backward chaining
use super::goal::{Goal, GoalStatus};
use super::rule_executor::RuleExecutor;
use crate::Facts;
use crate::types::Value;
use crate::KnowledgeBase;
use crate::engine::rule::Rule;
use std::collections::VecDeque;
/// Strategy for searching the goal space
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchStrategy {
/// Depth-first search (Prolog-style)
/// Goes deep into one branch before backtracking
DepthFirst,
/// Breadth-first search
/// Explores all goals at one level before going deeper
BreadthFirst,
/// Iterative deepening
/// Combines benefits of depth-first and breadth-first
Iterative,
}
/// Result of a search operation
#[derive(Debug)]
pub struct SearchResult {
/// Whether the goal was successfully proven
pub success: bool,
/// Path taken to prove the goal (sequence of rule names)
pub path: Vec<String>,
/// Number of goals explored
pub goals_explored: usize,
/// Maximum depth reached
pub max_depth_reached: usize,
/// Variable bindings from the proof
pub bindings: std::collections::HashMap<String, Value>,
}
impl SearchResult {
/// Create a successful search result
pub fn success(path: Vec<String>, goals_explored: usize, max_depth: usize) -> Self {
Self {
success: true,
path,
goals_explored,
max_depth_reached: max_depth,
bindings: std::collections::HashMap::new(),
}
}
/// Create a failed search result
pub fn failure(goals_explored: usize, max_depth: usize) -> Self {
Self {
success: false,
path: Vec::new(),
goals_explored,
max_depth_reached: max_depth,
bindings: std::collections::HashMap::new(),
}
}
}
/// Depth-first search implementation
pub struct DepthFirstSearch {
max_depth: usize,
goals_explored: usize,
path: Vec<String>,
executor: RuleExecutor,
}
impl DepthFirstSearch {
/// Create a new depth-first search
pub fn new(max_depth: usize, kb: KnowledgeBase) -> Self {
Self {
max_depth,
goals_explored: 0,
path: Vec::new(),
executor: RuleExecutor::new(kb),
}
}
/// Search for a proof of the goal WITH rule execution
pub fn search_with_execution(&mut self, goal: &mut Goal, facts: &Facts, kb: &KnowledgeBase) -> SearchResult {
self.goals_explored = 0;
self.path.clear();
let success = self.search_recursive_with_execution(goal, facts, kb, 0);
SearchResult {
success,
path: self.path.clone(),
goals_explored: self.goals_explored,
max_depth_reached: goal.depth,
bindings: goal.bindings.clone(),
}
}
/// Search for a proof of the goal (old method, kept for compatibility)
pub fn search(&mut self, goal: &mut Goal, _facts: &Facts) -> SearchResult {
self.goals_explored = 0;
self.path.clear();
let success = self.search_recursive(goal, 0);
SearchResult {
success,
path: self.path.clone(),
goals_explored: self.goals_explored,
max_depth_reached: goal.depth,
bindings: goal.bindings.clone(),
}
}
/// NEW: Recursive search WITH rule execution
fn search_recursive_with_execution(
&mut self,
goal: &mut Goal,
facts: &Facts,
kb: &KnowledgeBase,
depth: usize
) -> bool {
self.goals_explored += 1;
// Check depth limit
if depth > self.max_depth {
goal.status = GoalStatus::Unprovable;
return false;
}
// Check if goal already satisfied by existing facts
if self.check_goal_in_facts(goal, facts) {
goal.status = GoalStatus::Proven;
return true;
}
// Check for cycles
if goal.status == GoalStatus::InProgress {
goal.status = GoalStatus::Unprovable;
return false;
}
goal.status = GoalStatus::InProgress;
goal.depth = depth;
// Try each candidate rule
for rule_name in goal.candidate_rules.clone() {
self.path.push(rule_name.clone());
// Get the rule from KB
if let Some(rule) = kb.get_rule(&rule_name) {
// Check if rule conditions are satisfied
if self.check_rule_conditions(&rule, facts) {
// Rule can fire! Mark goal as proven
goal.status = GoalStatus::Proven;
return true;
}
// If conditions not satisfied, try to prove them recursively
// This would create sub-goals for each condition
// For now, skip this complex logic
}
self.path.pop();
}
// Try sub-goals
for sub_goal in &mut goal.sub_goals {
if !self.search_recursive_with_execution(sub_goal, facts, kb, depth + 1) {
goal.status = GoalStatus::Unprovable;
return false;
}
}
// If no way to prove
if goal.candidate_rules.is_empty() && goal.sub_goals.is_empty() {
goal.status = GoalStatus::Unprovable;
return false;
}
goal.status = GoalStatus::Proven;
true
}
/// Check if goal is already satisfied by facts
fn check_goal_in_facts(&self, goal: &Goal, facts: &Facts) -> bool {
// Parse goal pattern like "Order.AutoApproved == true"
let pattern = &goal.pattern;
// Simple parser for "Field == Value" or "Field != Value"
if let Some(eq_pos) = pattern.find("==") {
let field = pattern[..eq_pos].trim();
let expected = pattern[eq_pos + 2..].trim();
if let Some(actual) = facts.get(field) {
return self.value_matches(&actual, expected);
}
return false;
}
if let Some(ne_pos) = pattern.find("!=") {
let field = pattern[..ne_pos].trim();
let not_expected = pattern[ne_pos + 2..].trim();
if let Some(actual) = facts.get(field) {
return !self.value_matches(&actual, not_expected);
}
// If field doesn't exist, != is considered true
return true;
}
false
}
/// Check if value matches expected string
fn value_matches(&self, value: &Value, expected: &str) -> bool {
match value {
Value::Boolean(b) => {
expected == "true" && *b || expected == "false" && !*b
}
Value::String(s) => {
s == expected || s == expected.trim_matches('"')
}
Value::Number(n) => {
expected.parse::<f64>().map(|e| (n - e).abs() < 0.0001).unwrap_or(false)
}
_ => false,
}
}
/// Check if rule conditions are satisfied using RuleExecutor
fn check_rule_conditions(&self, rule: &Rule, facts: &Facts) -> bool {
// Use RuleExecutor for proper condition evaluation
self.executor.evaluate_conditions(&rule.conditions, facts).unwrap_or(false)
}
/// OLD: Recursive search without execution
fn search_recursive(&mut self, goal: &mut Goal, depth: usize) -> bool {
self.goals_explored += 1;
// Check depth limit
if depth > self.max_depth {
goal.status = GoalStatus::Unprovable;
return false;
}
// Check for cycles (goal already in progress)
if goal.status == GoalStatus::InProgress {
goal.status = GoalStatus::Unprovable;
return false;
}
// Mark as in progress to detect cycles
goal.status = GoalStatus::InProgress;
goal.depth = depth;
// Try each candidate rule
for rule_name in goal.candidate_rules.clone() {
self.path.push(rule_name.clone());
// Get the rule from knowledge base (via goal's stored rules)
// In a full implementation with KB access:
// 1. Get rule conditions
// 2. Check if conditions match current facts
// 3. If match, execute rule actions to derive new facts
// 4. Mark goal as proven
// For backward chaining, we check:
// - Can this rule's conclusion prove our goal?
// - Are all rule conditions satisfied (recursively)?
// Since we found a candidate rule, assume it can prove the goal
// The rule was added as candidate because its conclusion matches the goal
goal.status = GoalStatus::Proven;
return true;
}
// Try to prove sub-goals
for sub_goal in &mut goal.sub_goals {
if !self.search_recursive(sub_goal, depth + 1) {
goal.status = GoalStatus::Unprovable;
return false;
}
}
// If we have no sub-goals and no candidate rules, unprovable
if goal.sub_goals.is_empty() && goal.candidate_rules.is_empty() {
goal.status = GoalStatus::Unprovable;
return false;
}
goal.status = GoalStatus::Proven;
true
}
}
/// Breadth-first search implementation
pub struct BreadthFirstSearch {
max_depth: usize,
goals_explored: usize,
executor: RuleExecutor,
}
impl BreadthFirstSearch {
/// Create a new breadth-first search
pub fn new(max_depth: usize, kb: KnowledgeBase) -> Self {
Self {
max_depth,
goals_explored: 0,
executor: RuleExecutor::new(kb),
}
}
/// Search for a proof of the goal using BFS WITH rule execution
pub fn search_with_execution(&mut self, root_goal: &mut Goal, facts: &Facts, kb: &KnowledgeBase) -> SearchResult {
self.goals_explored = 0;
let mut queue = VecDeque::new();
let mut path = Vec::new();
let mut max_depth = 0;
queue.push_back((root_goal as *mut Goal, 0));
while let Some((goal_ptr, depth)) = queue.pop_front() {
// Safety: We maintain ownership properly
let goal = unsafe { &mut *goal_ptr };
self.goals_explored += 1;
max_depth = max_depth.max(depth);
if depth > self.max_depth {
continue;
}
goal.depth = depth;
// Check if goal already satisfied by facts
if self.check_goal_in_facts(goal, facts) {
goal.status = GoalStatus::Proven;
continue;
}
// Try each candidate rule
for rule_name in goal.candidate_rules.clone() {
path.push(rule_name.clone());
// Get the rule from KB
if let Some(rule) = kb.get_rule(&rule_name) {
// Check if rule conditions are satisfied
if self.check_rule_conditions(&rule, facts) {
goal.status = GoalStatus::Proven;
break;
}
}
}
// Add sub-goals to queue
for sub_goal in &mut goal.sub_goals {
queue.push_back((sub_goal as *mut Goal, depth + 1));
}
}
let success = root_goal.is_proven();
SearchResult {
success,
path,
goals_explored: self.goals_explored,
max_depth_reached: max_depth,
bindings: root_goal.bindings.clone(),
}
}
/// Check if goal is already satisfied by facts
fn check_goal_in_facts(&self, goal: &Goal, facts: &Facts) -> bool {
let pattern = &goal.pattern;
if let Some(eq_pos) = pattern.find("==") {
let field = pattern[..eq_pos].trim();
let expected = pattern[eq_pos + 2..].trim();
if let Some(actual) = facts.get(field) {
return self.value_matches(&actual, expected);
}
return false;
}
if let Some(ne_pos) = pattern.find("!=") {
let field = pattern[..ne_pos].trim();
let not_expected = pattern[ne_pos + 2..].trim();
if let Some(actual) = facts.get(field) {
return !self.value_matches(&actual, not_expected);
}
return true;
}
false
}
/// Check if value matches expected string
fn value_matches(&self, value: &Value, expected: &str) -> bool {
match value {
Value::Boolean(b) => {
expected == "true" && *b || expected == "false" && !*b
}
Value::String(s) => {
s == expected || s == expected.trim_matches('"')
}
Value::Number(n) => {
expected.parse::<f64>().map(|e| (n - e).abs() < 0.0001).unwrap_or(false)
}
_ => false,
}
}
/// Check if rule conditions are satisfied using RuleExecutor
fn check_rule_conditions(&self, rule: &Rule, facts: &Facts) -> bool {
// Use RuleExecutor for proper condition evaluation
self.executor.evaluate_conditions(&rule.conditions, facts).unwrap_or(false)
}
/// Search for a proof of the goal using BFS (old method, kept for compatibility)
pub fn search(&mut self, root_goal: &mut Goal, _facts: &Facts) -> SearchResult {
self.goals_explored = 0;
let mut queue = VecDeque::new();
let mut path = Vec::new();
let mut max_depth = 0;
queue.push_back((root_goal as *mut Goal, 0));
while let Some((goal_ptr, depth)) = queue.pop_front() {
// Safety: We maintain ownership properly
let goal = unsafe { &mut *goal_ptr };
self.goals_explored += 1;
max_depth = max_depth.max(depth);
if depth > self.max_depth {
continue;
}
goal.depth = depth;
// Process candidate rules
for rule_name in &goal.candidate_rules {
path.push(rule_name.clone());
}
// Add sub-goals to queue
for sub_goal in &mut goal.sub_goals {
queue.push_back((sub_goal as *mut Goal, depth + 1));
}
// Check if goal can be proven
if !goal.candidate_rules.is_empty() || goal.all_subgoals_proven() {
goal.status = GoalStatus::Proven;
}
}
let success = root_goal.is_proven();
SearchResult {
success,
path,
goals_explored: self.goals_explored,
max_depth_reached: max_depth,
bindings: root_goal.bindings.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_search_strategies() {
assert_eq!(SearchStrategy::DepthFirst, SearchStrategy::DepthFirst);
assert_ne!(SearchStrategy::DepthFirst, SearchStrategy::BreadthFirst);
}
#[test]
fn test_search_result_creation() {
let success = SearchResult::success(vec!["Rule1".to_string()], 5, 3);
assert!(success.success);
assert_eq!(success.path.len(), 1);
assert_eq!(success.goals_explored, 5);
let failure = SearchResult::failure(10, 5);
assert!(!failure.success);
assert!(failure.path.is_empty());
}
#[test]
fn test_depth_first_search_creation() {
let kb = KnowledgeBase::new("test");
let dfs = DepthFirstSearch::new(10, kb);
assert_eq!(dfs.max_depth, 10);
assert_eq!(dfs.goals_explored, 0);
}
#[test]
fn test_depth_first_search_simple() {
let kb = KnowledgeBase::new("test");
let mut dfs = DepthFirstSearch::new(10, kb);
let facts = Facts::new();
let mut goal = Goal::new("test".to_string());
goal.add_candidate_rule("TestRule".to_string());
let result = dfs.search(&mut goal, &facts);
assert!(result.success);
assert!(goal.is_proven());
assert!(result.goals_explored > 0);
}
#[test]
fn test_breadth_first_search() {
let kb = KnowledgeBase::new("test");
let mut bfs = BreadthFirstSearch::new(10, kb);
let facts = Facts::new();
let mut goal = Goal::new("test".to_string());
goal.add_candidate_rule("TestRule".to_string());
let result = bfs.search(&mut goal, &facts);
assert!(result.success);
assert_eq!(result.goals_explored, 1);
}
}