recall-graph 0.2.0

Knowledge graph with semantic search for AI memory systems
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
use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Serialize};

/// Node types in the knowledge graph.
/// Mutable types can be merged/updated. Immutable types are historical facts.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EntityType {
    Person,
    Project,
    Tool,
    Service,
    Preference,
    Decision,
    Event,
    Concept,
    Case,
    Pattern,
    Thread,
    Thought,
    Question,
    Observation,
    Policy,
}

impl EntityType {
    pub fn is_mutable(&self) -> bool {
        !matches!(
            self,
            Self::Decision | Self::Event | Self::Case | Self::Observation
        )
    }
}

impl fmt::Display for EntityType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = serde_json::to_value(self)
            .ok()
            .and_then(|v| v.as_str().map(String::from))
            .unwrap_or_else(|| format!("{:?}", self));
        write!(f, "{}", s)
    }
}

impl std::str::FromStr for EntityType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_value(serde_json::Value::String(s.to_string()))
            .map_err(|_| format!("unknown entity type: {}", s))
    }
}

/// Input for creating a new entity.
#[derive(Debug, Clone)]
pub struct NewEntity {
    pub name: String,
    pub entity_type: EntityType,
    pub abstract_text: String,
    pub overview: Option<String>,
    pub content: Option<String>,
    pub attributes: Option<serde_json::Value>,
    pub source: Option<String>,
}

/// A stored entity with all fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entity {
    pub id: serde_json::Value,
    pub name: String,
    pub entity_type: EntityType,
    #[serde(rename = "abstract")]
    pub abstract_text: String,
    pub overview: String,
    pub content: Option<String>,
    pub attributes: Option<serde_json::Value>,
    #[serde(default)]
    pub embedding: Option<Vec<f32>>,
    #[serde(default = "default_true")]
    pub mutable: bool,
    #[serde(default)]
    pub access_count: i64,
    pub created_at: serde_json::Value,
    pub updated_at: serde_json::Value,
    pub source: Option<String>,
}

impl Entity {
    /// Get the record ID as a string (e.g. "entity:abc123").
    pub fn id_string(&self) -> String {
        match &self.id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }

    /// Get the updated_at timestamp as a string.
    pub fn updated_at_string(&self) -> String {
        match &self.updated_at {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

fn default_true() -> bool {
    true
}

/// Fields that can be updated on an entity.
#[derive(Debug, Clone, Default, Serialize)]
pub struct EntityUpdate {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub abstract_text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub overview: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes: Option<serde_json::Value>,
}

/// Input for creating a new relationship.
#[derive(Debug, Clone)]
pub struct NewRelationship {
    pub from_entity: String,
    pub to_entity: String,
    pub rel_type: String,
    pub description: Option<String>,
    pub confidence: Option<f32>,
    pub source: Option<String>,
}

/// A stored relationship.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relationship {
    pub id: serde_json::Value,
    #[serde(rename = "in")]
    pub from_id: serde_json::Value,
    #[serde(rename = "out")]
    pub to_id: serde_json::Value,
    pub rel_type: String,
    pub description: Option<String>,
    pub valid_from: serde_json::Value,
    pub valid_until: Option<serde_json::Value>,
    pub confidence: f64,
    pub source: Option<String>,
}

impl Relationship {
    /// Get the record ID as a string.
    pub fn id_string(&self) -> String {
        match &self.id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

/// Direction for relationship queries.
#[derive(Debug, Clone, Copy)]
pub enum Direction {
    Outgoing,
    Incoming,
    Both,
}

// ── Tiered entity projections ────────────────────────────────────────

/// L0 — Minimal entity for traversal. No embedding, no content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntitySummary {
    pub id: serde_json::Value,
    pub name: String,
    pub entity_type: EntityType,
    #[serde(rename = "abstract")]
    pub abstract_text: String,
}

impl EntitySummary {
    pub fn id_string(&self) -> String {
        match &self.id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

/// L1 — Search result detail. Everything except content and embedding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityDetail {
    pub id: serde_json::Value,
    pub name: String,
    pub entity_type: EntityType,
    #[serde(rename = "abstract")]
    pub abstract_text: String,
    pub overview: String,
    pub attributes: Option<serde_json::Value>,
    #[serde(default)]
    pub access_count: i64,
    pub updated_at: serde_json::Value,
    pub source: Option<String>,
}

impl EntityDetail {
    pub fn id_string(&self) -> String {
        match &self.id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }

    pub fn updated_at_string(&self) -> String {
        match &self.updated_at {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

// ── Search types ────────────────────────────────────────────────────

/// Options for entity search.
#[derive(Debug, Clone, Default)]
pub struct SearchOptions {
    pub limit: usize,
    pub entity_type: Option<String>,
    pub keyword: Option<String>,
}

/// How an entity was found.
#[derive(Debug, Clone)]
pub enum MatchSource {
    /// Found via semantic similarity.
    Semantic,
    /// Found via graph expansion from a parent entity.
    Graph { parent: String, rel_type: String },
    /// Found via keyword filter match.
    Keyword,
}

/// A scored entity in search results.
#[derive(Debug, Clone)]
pub struct ScoredEntity {
    pub entity: EntityDetail,
    pub score: f64,
    pub source: MatchSource,
}

/// An episode search result.
#[derive(Debug, Clone)]
pub struct EpisodeSearchResult {
    pub episode: Episode,
    pub score: f64,
    pub distance: f64,
}

/// Options for hybrid query (semantic + graph expansion + episodes).
#[derive(Debug, Clone)]
pub struct QueryOptions {
    pub limit: usize,
    pub entity_type: Option<String>,
    pub keyword: Option<String>,
    pub graph_depth: u32,
    pub include_episodes: bool,
}

impl Default for QueryOptions {
    fn default() -> Self {
        Self {
            limit: 10,
            entity_type: None,
            keyword: None,
            graph_depth: 1,
            include_episodes: false,
        }
    }
}

/// Result of a hybrid query.
#[derive(Debug, Clone)]
pub struct QueryResult {
    pub entities: Vec<ScoredEntity>,
    pub episodes: Vec<EpisodeSearchResult>,
}

/// A search result with scoring (legacy — wraps full Entity).
#[derive(Debug, Clone)]
pub struct SearchResult {
    pub entity: Entity,
    pub score: f64,
    pub distance: f64,
}

/// A node in a traversal tree.
#[derive(Debug, Clone)]
pub struct TraversalNode {
    pub entity: EntitySummary,
    pub edges: Vec<TraversalEdge>,
}

/// An edge in a traversal tree.
#[derive(Debug, Clone)]
pub struct TraversalEdge {
    pub rel_type: String,
    pub direction: String,
    pub target: TraversalNode,
    pub valid_from: serde_json::Value,
    pub valid_until: Option<serde_json::Value>,
}

/// A row from a relationship query (shared by traverse and query).
#[derive(Debug, Clone, serde::Deserialize)]
pub struct EdgeRow {
    pub rel_type: String,
    pub valid_from: serde_json::Value,
    pub valid_until: Option<serde_json::Value>,
    pub target_id: serde_json::Value,
}

impl EdgeRow {
    pub fn target_id_string(&self) -> String {
        match &self.target_id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

/// Graph-level statistics.
#[derive(Debug, Clone)]
pub struct GraphStats {
    pub entity_count: u64,
    pub relationship_count: u64,
    pub episode_count: u64,
    pub entity_type_counts: HashMap<String, u64>,
}

// ── Ingestion types (Phase 2) ────────────────────────────────────────

/// Input for creating a new episode.
#[derive(Debug, Clone)]
pub struct NewEpisode {
    pub session_id: String,
    pub abstract_text: String,
    pub overview: Option<String>,
    pub content: Option<String>,
    pub log_number: Option<u32>,
}

/// A stored episode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Episode {
    pub id: serde_json::Value,
    pub session_id: String,
    pub timestamp: serde_json::Value,
    #[serde(rename = "abstract")]
    pub abstract_text: String,
    pub overview: Option<String>,
    pub content: Option<String>,
    #[serde(default)]
    pub embedding: Option<Vec<f32>>,
    pub log_number: Option<i64>,
}

impl Episode {
    pub fn id_string(&self) -> String {
        match &self.id {
            serde_json::Value::String(s) => s.clone(),
            other => other.to_string(),
        }
    }
}

/// A candidate entity extracted by the LLM from a conversation chunk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedEntity {
    pub name: String,
    #[serde(rename = "type")]
    pub entity_type: EntityType,
    #[serde(rename = "abstract")]
    pub abstract_text: String,
    pub overview: Option<String>,
    pub content: Option<String>,
    pub attributes: Option<serde_json::Value>,
}

/// A candidate relationship extracted by the LLM.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedRelationship {
    pub source: String,
    pub target: String,
    pub rel_type: String,
    pub description: Option<String>,
}

/// An extracted case (problem-solution pair).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedCase {
    pub problem: String,
    pub solution: String,
    pub context: Option<String>,
}

/// An extracted pattern (reusable process).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedPattern {
    pub name: String,
    pub process: String,
    pub conditions: Option<String>,
}

/// An extracted preference (one per facet).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtractedPreference {
    pub facet: String,
    pub value: String,
    pub context: Option<String>,
}

/// Full extraction result from a single conversation chunk.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExtractionResult {
    #[serde(default)]
    pub entities: Vec<ExtractedEntity>,
    #[serde(default)]
    pub relationships: Vec<ExtractedRelationship>,
    #[serde(default)]
    pub cases: Vec<ExtractedCase>,
    #[serde(default)]
    pub patterns: Vec<ExtractedPattern>,
    #[serde(default)]
    pub preferences: Vec<ExtractedPreference>,
}

/// LLM deduplication decision for a candidate entity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DedupDecision {
    Skip,
    Create,
    Merge { target: String },
}

// ── Pipeline types ───────────────────────────────────────────────────

/// Canonical relationship types for the praxis pipeline.
pub mod pipeline_rels {
    pub const EVOLVED_FROM: &str = "EVOLVED_FROM";
    pub const CRYSTALLIZED_FROM: &str = "CRYSTALLIZED_FROM";
    pub const INFORMED_BY: &str = "INFORMED_BY";
    pub const EXPLORES: &str = "EXPLORES";
    pub const GRADUATED_TO: &str = "GRADUATED_TO";
    pub const ARCHIVED_FROM: &str = "ARCHIVED_FROM";
    pub const CONNECTED_TO: &str = "CONNECTED_TO";
}

/// Contents of all 5 pipeline markdown files.
#[derive(Debug, Clone, Default)]
pub struct PipelineDocuments {
    pub learning: String,
    pub thoughts: String,
    pub curiosity: String,
    pub reflections: String,
    pub praxis: String,
}

/// Report from a pipeline sync operation.
#[derive(Debug, Clone, Default)]
pub struct PipelineSyncReport {
    pub entities_created: u32,
    pub entities_updated: u32,
    pub entities_archived: u32,
    pub relationships_created: u32,
    pub relationships_skipped: u32,
    pub errors: Vec<String>,
}

/// Pipeline health stats from the graph.
#[derive(Debug, Clone, Default)]
pub struct PipelineGraphStats {
    pub by_stage: HashMap<String, HashMap<String, u64>>,
    pub stale_thoughts: Vec<EntityDetail>,
    pub stale_questions: Vec<EntityDetail>,
    pub total_entities: u64,
    pub last_movement: Option<String>,
}

/// A parsed pipeline entry from a markdown document.
#[derive(Debug, Clone)]
pub struct PipelineEntry {
    /// Title from ### heading (cleaned of dates and markers).
    pub title: String,
    /// Full content under the heading.
    pub body: String,
    /// Status: "active", "graduated", "dissolved", "explored", "retired".
    pub status: String,
    /// Stage: "learning", "thoughts", "curiosity", "reflections", "praxis".
    pub stage: String,
    /// Mapped entity type.
    pub entity_type: EntityType,
    /// Date from heading or metadata field.
    pub date: Option<String>,
    /// **Source:** field value.
    pub source_ref: Option<String>,
    /// **Destination:** field value.
    pub destination: Option<String>,
    /// Parsed "Connected to:" references.
    pub connected_to: Vec<String>,
    /// Sub-type for special sections: "theme", "pattern", "phronesis".
    pub sub_type: Option<String>,
}

/// Result of a full ingestion run.
#[derive(Debug, Clone, Default)]
pub struct IngestionReport {
    pub episodes_created: u32,
    pub entities_created: u32,
    pub entities_merged: u32,
    pub entities_skipped: u32,
    pub relationships_created: u32,
    pub relationships_skipped: u32,
    pub errors: Vec<String>,
}