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
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial
//! Built-in rules for common validation scenarios
//!
//! These rules cover common patterns like:
//! - Integrity constraints (no self-references, valid types)
//! - Authority rules (ownership, permissions)
//! - Temporal rules (ordering, expiration)
//! - Semantic rules (transitivity, symmetry)
use aingle_graph::{NodeId, Value};
use crate::rule::{Pattern, Rule, RuleSet, TriplePattern};
/// A collection of pre-defined rule sets for common logical validation and inference scenarios.
///
/// These rule sets can be used directly or customized to fit specific application needs.
pub struct BuiltinRules;
/// Helper function to convert a `NodeId` to a string representation for binding purposes.
fn node_to_str(node: &NodeId) -> String {
match node {
NodeId::Named(s) => s.clone(),
NodeId::Hash(h) => format!("hash:{:x?}", &h[..8]),
NodeId::Blank(id) => format!("_:b{}", id),
}
}
/// A minimal `hex` encoding module used internally by built-in rules for string representation.
#[allow(dead_code)]
mod hex {
/// Encodes a byte slice into a hexadecimal string.
pub fn encode(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
}
impl BuiltinRules {
/// Retrieves a `RuleSet` containing all available built-in rules across all categories.
pub fn all() -> RuleSet {
let mut ruleset = RuleSet::new("builtin_all");
ruleset.description =
"All built-in rules combined for comprehensive validation and inference.".to_string();
for rule in Self::integrity_rules().rules {
ruleset.add(rule);
}
for rule in Self::authority_rules().rules {
ruleset.add(rule);
}
for rule in Self::temporal_rules().rules {
ruleset.add(rule);
}
for rule in Self::semantic_rules().rules {
ruleset.add(rule);
}
ruleset
}
/// Retrieves a `RuleSet` focused on core data integrity constraints.
pub fn integrity_rules() -> RuleSet {
let mut ruleset = RuleSet::new("integrity");
ruleset.description =
"Core integrity constraints for data consistency and validity.".to_string();
// Rule: Prevents nodes from having relationships with themselves (e.g., "A knows A").
ruleset.add(
Rule::integrity("no_self_reference")
.name("No Self References")
.description("Prevents nodes from having relationships with themselves.")
.when(|t| match &t.object {
Value::Node(node) => node_to_str(node) == node_to_str(&t.subject),
_ => false,
})
.reject("Self-references are not allowed.")
.priority(100)
.build(),
);
// Rule: Ensures predicates are not empty strings.
ruleset.add(
Rule::integrity("no_empty_predicate")
.name("No Empty Predicates")
.description("Predicates must have a non-empty name.")
.when(|t| t.predicate.as_str().is_empty())
.reject("Predicate cannot be empty.")
.priority(100)
.build(),
);
// Rule: Ensures subjects are not empty strings (for named nodes).
ruleset.add(
Rule::integrity("no_empty_subject")
.name("No Empty Subjects")
.description("Subjects must have a non-empty identifier.")
.when(|t| match &t.subject {
NodeId::Named(s) => s.is_empty(),
_ => false,
})
.reject("Subject cannot be empty.")
.priority(100)
.build(),
);
// Rule: Validates that node IDs do not contain invalid whitespace characters.
ruleset.add(
Rule::integrity("valid_node_format")
.name("Valid Node Format")
.description(
"Node IDs should follow naming conventions and not contain invalid whitespace.",
)
.when(|t| match &t.subject {
NodeId::Named(s) => s.contains(' ') || s.contains('\t') || s.contains('\n'),
_ => false,
})
.reject("Node ID contains invalid whitespace characters.")
.priority(90)
.build(),
);
// Rule: Prevents contradicting type declarations (e.g., something cannot be both "animal" and "not-animal").
ruleset.add(
Rule::integrity("type_consistency")
.name("Type Consistency")
.description("Prevents contradicting type declarations.")
.when_predicate("type")
.accept() // This rule would likely require more complex graph interaction to fully validate contradictions.
.priority(80)
.build(),
);
ruleset
}
/// Retrieves a `RuleSet` for managing authority and permission checks.
pub fn authority_rules() -> RuleSet {
let mut ruleset = RuleSet::new("authority");
ruleset.description =
"Rules for validating authority, permissions, and access control.".to_string();
// Rule: States that the owner of a resource implicitly has all permissions on that resource.
ruleset.add(
Rule::authority("owner_permissions")
.name("Owner Has All Permissions")
.description("The owner of a resource has all permissions on it.")
.when_predicate("owns")
.accept()
.priority(100)
.build(),
);
// Rule: A placeholder for checking if a permission grant is valid. Requires further context for full validation.
ruleset.add(
Rule::authority("grant_check")
.name("Grant Permission Check")
.description("Checks if a permission grant is valid (e.g., only owners can grant permissions).")
.when_predicate("grants_permission")
.accept() // Would need graph context to fully validate who is granting.
.priority(90)
.build(),
);
// Rule: Identifies entities with an "admin" role, implying elevated permissions.
ruleset.add(
Rule::authority("admin_role")
.name("Admin Role")
.description("Admins have elevated permissions.")
.when(|t| {
if t.predicate.as_str() != "has_role" {
return false;
}
match &t.object {
Value::String(s) => s == "admin",
Value::Node(node) => node_to_str(node) == "admin",
_ => false,
}
})
.accept()
.priority(85)
.build(),
);
// Rule: Facilitates permission delegation chains.
ruleset.add(
Rule::authority("delegation")
.name("Delegation")
.description("Allows for the delegation of permissions from one entity to another.")
.when_predicate("delegates_to")
.accept()
.priority(80)
.build(),
);
ruleset
}
/// Retrieves a `RuleSet` for validating temporal constraints.
pub fn temporal_rules() -> RuleSet {
let mut ruleset = RuleSet::new("temporal");
ruleset.description =
"Rules for validating time-based constraints and ordering.".to_string();
// Rule: Ensures consistency for "before" and "after" relationships.
ruleset.add(
Rule::temporal("before_after")
.name("Before/After Consistency")
.description("If A is 'before' B, then B must implicitly be 'after' A.")
.when_predicate("before")
.accept() // This rule would typically infer the inverse relation if not explicitly present.
.priority(100)
.build(),
);
// Rule: Validates that timestamps maintain a logical order (e.g., creation before modification).
ruleset.add(
Rule::temporal("timestamp_order")
.name("Timestamp Ordering")
.description("Ensures created timestamps precede modified timestamps.")
.when_predicate("created_at")
.accept()
.priority(90)
.build(),
);
// Rule: Identifies expired items based on an "expires_at" predicate.
ruleset.add(
Rule::temporal("expiration")
.name("Expiration Check")
.description("Identifies items that have passed their expiration date.")
.when_predicate("expires_at")
.accept() // Would need current time for full validation against `expires_at`.
.priority(80)
.build(),
);
// Rule: Verifies that sequence numbers are monotonically increasing.
ruleset.add(
Rule::temporal("sequence")
.name("Sequence Ordering")
.description("Ensures sequence numbers are monotonically increasing.")
.when_predicate("has_sequence")
.accept()
.priority(85)
.build(),
);
ruleset
}
/// Retrieves a `RuleSet` for semantic inference.
pub fn semantic_rules() -> RuleSet {
let mut ruleset = RuleSet::new("semantic");
ruleset.description =
"Rules for inferring new facts based on semantic relationships.".to_string();
// Rule: Infers indirect knowledge from transitive "knows" relationships.
ruleset.add(
Rule::inference("transitive_knows")
.name("Transitive Knows")
.description("If A knows B, and B knows C, then A indirectly knows C.")
.when_predicate("knows")
.when_exists(TriplePattern::new(
Pattern::Variable("s".to_string()),
"knows",
Pattern::Variable("intermediate".to_string()),
))
.infer(TriplePattern::new(
Pattern::Variable("s".to_string()),
"indirectly_knows",
Pattern::Variable("o".to_string()),
))
.priority(50)
.build(),
);
// Rule: Infers the symmetric nature of "married_to" relationships.
ruleset.add(
Rule::inference("symmetric_married")
.name("Symmetric Marriage")
.description("If A is married to B, then B is also married to A.")
.when_predicate("married_to")
.infer(TriplePattern::new(
Pattern::Variable("o".to_string()),
"married_to",
Pattern::Variable("s".to_string()),
))
.priority(50)
.build(),
);
// Rule: Infers an entity's type from its subclass hierarchy.
ruleset.add(
Rule::inference("subclass_type")
.name("Subclass Type Inference")
.description(
"If A is of type B, and B is a subclass of C, then A is also of type C.",
)
.when_predicate("type")
.when_exists(TriplePattern::new(
Pattern::Variable("type".to_string()),
"subclass_of",
Pattern::Variable("supertype".to_string()),
))
.infer(TriplePattern::new(
Pattern::Variable("s".to_string()),
"type",
Pattern::Variable("supertype".to_string()),
))
.priority(60)
.build(),
);
// Rule: Infers inverse relationships, such as "child_of" from "parent_of".
ruleset.add(
Rule::inference("inverse_parent_child")
.name("Inverse Parent/Child")
.description("If A is a parent of B, then B is a child of A.")
.when_predicate("parent_of")
.infer(TriplePattern::new(
Pattern::Variable("o".to_string()),
"child_of",
Pattern::Variable("s".to_string()),
))
.priority(50)
.build(),
);
// Rule: Infers sibling relationships from shared parentage.
ruleset.add(
Rule::inference("sibling_inference")
.name("Sibling Inference")
.description("If A is a parent of B, and A is also a parent of C, then B and C are siblings.")
.when_predicate("parent_of")
.when_exists(TriplePattern::new(
Pattern::Variable("parent".to_string()),
"parent_of",
Pattern::Variable("sibling".to_string()),
))
.infer(TriplePattern::new(
Pattern::Variable("o".to_string()),
"sibling_of",
Pattern::Variable("sibling".to_string()),
))
.priority(40)
.build(),
);
ruleset
}
/// Retrieves a `RuleSet` containing AIngle-specific validation rules.
pub fn aingle_rules() -> RuleSet {
let mut ruleset = RuleSet::new("aingle");
ruleset.description =
"AIngle-specific validation rules for core data structures and operations.".to_string();
// Rule: Validates the author signature of entries.
ruleset.add(
Rule::authority("entry_author")
.name("Entry Author Validation")
.description("Entries must have a valid author signature.")
.when_predicate("aingle:author")
.accept()
.priority(100)
.build(),
);
// Rule: Ensures action sequence numbers are monotonically increasing.
ruleset.add(
Rule::temporal("action_sequence")
.name("Action Sequence")
.description("Action sequence numbers must increase for valid ordering.")
.when_predicate("aingle:seq")
.accept()
.priority(100)
.build(),
);
// Rule: Verifies that actions correctly reference valid previous actions in their chain.
ruleset.add(
Rule::integrity("prev_action_chain")
.name("Previous Action Chain")
.description("Actions must reference valid previous actions in their history.")
.when_predicate("aingle:prevAction")
.accept()
.priority(100)
.build(),
);
// Rule: Validates the integrity of entry hashes.
ruleset.add(
Rule::integrity("entry_hash")
.name("Entry Hash Validation")
.description("Entry hashes must be valid and correctly computed.")
.when_predicate("aingle:entryHash")
.accept()
.priority(100)
.build(),
);
// Rule: Validates the public keys of agents.
ruleset.add(
Rule::authority("valid_agent")
.name("Valid Agent")
.description("Agents must have valid public keys for identification.")
.when_predicate("aingle:agent")
.accept()
.priority(95)
.build(),
);
ruleset
}
/// Retrieves a minimal `RuleSet` containing only the most essential built-in rules.
pub fn minimal() -> RuleSet {
let mut ruleset = RuleSet::new("minimal");
ruleset.description =
"A minimal set of essential built-in rules for basic integrity.".to_string();
// Rule: Prevents self-referential relationships, crucial for basic graph integrity.
ruleset.add(
Rule::integrity("no_self_reference")
.name("No Self References")
.when(|t| match &t.object {
Value::Node(node) => node_to_str(node) == node_to_str(&t.subject),
_ => false,
})
.reject("Self-references not allowed.")
.priority(100)
.build(),
);
// Rule: Ensures that predicates are never empty strings.
ruleset.add(
Rule::integrity("no_empty_predicate")
.name("No Empty Predicates")
.when(|t| t.predicate.as_str().is_empty())
.reject("Empty predicate.")
.priority(100)
.build(),
);
ruleset
}
}
#[cfg(test)]
mod tests {
use super::*;
use aingle_graph::{Predicate, Triple};
#[test]
fn test_integrity_rules() {
let rules = BuiltinRules::integrity_rules();
assert!(!rules.is_empty());
assert!(rules.get("no_self_reference").is_some());
assert!(rules.get("no_empty_predicate").is_some());
}
#[test]
fn test_authority_rules() {
let rules = BuiltinRules::authority_rules();
assert!(!rules.is_empty());
assert!(rules.get("owner_permissions").is_some());
}
#[test]
fn test_temporal_rules() {
let rules = BuiltinRules::temporal_rules();
assert!(!rules.is_empty());
assert!(rules.get("before_after").is_some());
}
#[test]
fn test_semantic_rules() {
let rules = BuiltinRules::semantic_rules();
assert!(!rules.is_empty());
assert!(rules.get("transitive_knows").is_some());
assert!(rules.get("symmetric_married").is_some());
}
#[test]
fn test_aingle_rules() {
let rules = BuiltinRules::aingle_rules();
assert!(!rules.is_empty());
assert!(rules.get("entry_author").is_some());
assert!(rules.get("action_sequence").is_some());
}
#[test]
fn test_all_rules() {
let rules = BuiltinRules::all();
// Should have rules from all categories
assert!(rules.len() > 10);
}
#[test]
fn test_minimal_rules() {
let rules = BuiltinRules::minimal();
assert_eq!(rules.len(), 2);
}
#[test]
fn test_self_reference_rule() {
let rules = BuiltinRules::integrity_rules();
let rule = rules.get("no_self_reference").unwrap();
// Should reject self-reference
let self_ref = Triple::new(
NodeId::named("alice"),
Predicate::named("knows"),
Value::Node(NodeId::named("alice")),
);
let mut bindings = crate::rule::Bindings::new();
assert!(rule.matches(&self_ref, &mut bindings));
// Should accept non-self-reference
let other_ref = Triple::new(
NodeId::named("alice"),
Predicate::named("knows"),
Value::Node(NodeId::named("bob")),
);
bindings.clear();
assert!(!rule.matches(&other_ref, &mut bindings));
}
#[test]
fn test_empty_predicate_rule() {
let rules = BuiltinRules::integrity_rules();
let rule = rules.get("no_empty_predicate").unwrap();
// Should reject empty predicate
let empty_pred = Triple::new(
NodeId::named("alice"),
Predicate::named(""),
Value::literal("test"),
);
let mut bindings = crate::rule::Bindings::new();
assert!(rule.matches(&empty_pred, &mut bindings));
// Should accept non-empty predicate
let valid = Triple::new(
NodeId::named("alice"),
Predicate::named("knows"),
Value::literal("test"),
);
bindings.clear();
assert!(!rule.matches(&valid, &mut bindings));
}
}