eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
use std::collections::{BTreeMap, BTreeSet};

use fnx_algorithms::{articulation_points, number_connected_components, onion_layers};
use fnx_classes::Graph;
use serde::{Deserialize, Serialize};

use crate::graph::{GraphResult, algorithms};
use crate::util::radix_ulid_sort::sort_by_ulid_payload_or_lexical;

pub const DEFAULT_ONION_DECAY_MAX: f64 = 3.0;
pub const DEFAULT_ARTICULATION_PROTECTION: f64 = 0.5;

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StructuralDecayPolicy {
    pub onion_decay_max: f64,
    pub articulation_protection: f64,
}

impl StructuralDecayPolicy {
    #[must_use]
    pub fn from_optional_config(
        onion_decay_max: Option<f64>,
        articulation_protection: Option<f64>,
    ) -> Self {
        Self {
            onion_decay_max: onion_decay_max.unwrap_or(DEFAULT_ONION_DECAY_MAX),
            articulation_protection: articulation_protection
                .unwrap_or(DEFAULT_ARTICULATION_PROTECTION),
        }
    }
}

impl Default for StructuralDecayPolicy {
    fn default() -> Self {
        Self {
            onion_decay_max: DEFAULT_ONION_DECAY_MAX,
            articulation_protection: DEFAULT_ARTICULATION_PROTECTION,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ArticulationPointReport {
    pub memory_ids: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OnionLayerReport {
    pub layers_by_memory: BTreeMap<String, usize>,
    pub max_layer: usize,
}

#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StructuralDecayMultiplier {
    pub memory_id: String,
    pub onion_layer: Option<usize>,
    pub max_layer: usize,
    pub is_articulation_point: bool,
    pub structural_multiplier: f64,
    pub rationale: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StructuralDecayConnectivityReport {
    pub component_count: usize,
    pub is_connected: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub struct StructuralDecayIndex {
    onion: OnionLayerReport,
    articulation_points: BTreeSet<String>,
    policy: StructuralDecayPolicy,
}

impl StructuralDecayIndex {
    #[must_use]
    pub fn adjustment(&self, memory_id: &str) -> StructuralDecayMultiplier {
        let onion_layer = self.onion.layers_by_memory.get(memory_id).copied();
        let is_articulation_point = self.articulation_points.contains(memory_id);

        let Some(layer) = onion_layer else {
            return StructuralDecayMultiplier {
                memory_id: memory_id.to_owned(),
                onion_layer,
                max_layer: self.onion.max_layer,
                is_articulation_point,
                structural_multiplier: 1.0,
                rationale: "structural_decay_baseline".to_owned(),
            };
        };

        if self.onion.max_layer < 2 {
            return StructuralDecayMultiplier {
                memory_id: memory_id.to_owned(),
                onion_layer: Some(layer),
                max_layer: self.onion.max_layer,
                is_articulation_point,
                structural_multiplier: 1.0,
                rationale: "structural_decay_baseline".to_owned(),
            };
        }

        let onion_normalized =
            (self.onion.max_layer.saturating_sub(layer)) as f64 / self.onion.max_layer as f64;
        let onion_multiplier =
            1.0 + (self.policy.onion_decay_max - 1.0).max(0.0) * onion_normalized;
        let articulation_multiplier = if is_articulation_point {
            if self.policy.articulation_protection.is_nan() {
                DEFAULT_ARTICULATION_PROTECTION
            } else {
                self.policy.articulation_protection.clamp(0.0, 1.0)
            }
        } else {
            1.0
        };
        let structural_multiplier = onion_multiplier * articulation_multiplier;

        StructuralDecayMultiplier {
            memory_id: memory_id.to_owned(),
            onion_layer: Some(layer),
            max_layer: self.onion.max_layer,
            is_articulation_point,
            structural_multiplier,
            rationale: structural_decay_rationale(layer, is_articulation_point),
        }
    }
}

#[must_use]
pub fn compute_structural_decay_index(graph: &Graph) -> StructuralDecayIndex {
    compute_structural_decay_index_with_policy(graph, StructuralDecayPolicy::default())
}

#[must_use]
pub fn compute_structural_decay_index_with_policy(
    graph: &Graph,
    policy: StructuralDecayPolicy,
) -> StructuralDecayIndex {
    StructuralDecayIndex {
        onion: compute_onion_layers(graph),
        articulation_points: compute_articulation_points(graph)
            .memory_ids
            .into_iter()
            .collect(),
        policy,
    }
}

#[must_use]
pub fn compute_articulation_points(graph: &Graph) -> ArticulationPointReport {
    match try_compute_articulation_points(graph) {
        Ok(report) => report,
        Err(error) => {
            tracing::warn!(
                target: "ee::graph",
                algorithm = "articulation_points",
                error = %error,
                "structural decay articulation-point wrapper failed; returning empty report"
            );
            ArticulationPointReport { memory_ids: vec![] }
        }
    }
}

pub fn try_compute_articulation_points(graph: &Graph) -> GraphResult<ArticulationPointReport> {
    let cx = algorithms::current_or_testing_cx();
    let graph = graph.clone();
    algorithms::run_with_budget(
        &cx,
        "articulation_points",
        algorithms::DEFAULT_BACKGROUND_BUDGET,
        move || compute_articulation_points_unbudgeted(&graph),
    )
}

fn compute_articulation_points_unbudgeted(graph: &Graph) -> ArticulationPointReport {
    let mut memory_ids = articulation_points(graph).nodes;
    sort_by_ulid_payload_or_lexical(&mut memory_ids, String::as_str);
    ArticulationPointReport { memory_ids }
}

#[must_use]
pub fn compute_onion_layers(graph: &Graph) -> OnionLayerReport {
    match try_compute_onion_layers(graph) {
        Ok(report) => report,
        Err(error) => {
            tracing::warn!(
                target: "ee::graph",
                algorithm = "onion_layers",
                error = %error,
                "structural decay onion-layer wrapper failed; returning empty report"
            );
            OnionLayerReport {
                layers_by_memory: BTreeMap::new(),
                max_layer: 0,
            }
        }
    }
}

pub fn try_compute_onion_layers(graph: &Graph) -> GraphResult<OnionLayerReport> {
    let cx = algorithms::current_or_testing_cx();
    let graph = graph.clone();
    algorithms::run_with_budget(
        &cx,
        "onion_layers",
        algorithms::DEFAULT_BACKGROUND_BUDGET,
        move || compute_onion_layers_unbudgeted(&graph),
    )
}

fn compute_onion_layers_unbudgeted(graph: &Graph) -> OnionLayerReport {
    let layers_by_memory = onion_layers(graph)
        .layers
        .into_iter()
        .map(|layer| (layer.node, layer.layer))
        .collect::<BTreeMap<_, _>>();
    let max_layer = layers_by_memory.values().copied().max().unwrap_or(0);

    OnionLayerReport {
        layers_by_memory,
        max_layer,
    }
}

#[must_use]
pub fn compute_structural_decay_connectivity(graph: &Graph) -> StructuralDecayConnectivityReport {
    match try_compute_structural_decay_connectivity(graph) {
        Ok(report) => report,
        Err(error) => {
            tracing::warn!(
                target: "ee::graph",
                algorithm = "number_connected_components",
                error = %error,
                "structural decay connectivity wrapper failed; returning connected baseline"
            );
            StructuralDecayConnectivityReport {
                component_count: 0,
                is_connected: true,
            }
        }
    }
}

pub fn try_compute_structural_decay_connectivity(
    graph: &Graph,
) -> GraphResult<StructuralDecayConnectivityReport> {
    let cx = algorithms::current_or_testing_cx();
    let graph = graph.clone();
    algorithms::run_with_budget(
        &cx,
        "number_connected_components",
        algorithms::DEFAULT_BACKGROUND_BUDGET,
        move || compute_structural_decay_connectivity_unbudgeted(&graph),
    )
}

fn compute_structural_decay_connectivity_unbudgeted(
    graph: &Graph,
) -> StructuralDecayConnectivityReport {
    let component_count = number_connected_components(graph).count;
    StructuralDecayConnectivityReport {
        component_count,
        is_connected: component_count <= 1,
    }
}

#[must_use]
pub fn compute_structural_decay_multiplier(graph: &Graph, memory_id: &str) -> f64 {
    compute_structural_decay_adjustment(graph, memory_id).structural_multiplier
}

#[must_use]
pub fn compute_structural_decay_adjustment(
    graph: &Graph,
    memory_id: &str,
) -> StructuralDecayMultiplier {
    compute_structural_decay_adjustment_with_policy(
        graph,
        memory_id,
        StructuralDecayPolicy::default(),
    )
}

#[must_use]
pub fn compute_structural_decay_adjustment_with_policy(
    graph: &Graph,
    memory_id: &str,
    policy: StructuralDecayPolicy,
) -> StructuralDecayMultiplier {
    compute_structural_decay_index_with_policy(graph, policy).adjustment(memory_id)
}

fn structural_decay_rationale(layer: usize, is_articulation_point: bool) -> String {
    if is_articulation_point {
        format!("articulation_point_in_layer_{layer}")
    } else {
        format!("onion_layer_{layer}")
    }
}

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

    const PUBLIC_ID_EARLY: &str = "note_01J0000000000000000000000A";
    const PUBLIC_ID_LATE: &str = "mem_01J0000000000000000000000C";

    #[test]
    fn articulation_points_are_sorted() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("b", "d")]);

        let report = compute_articulation_points(&graph);

        assert_eq!(report.memory_ids, vec!["b"]);
    }

    #[test]
    fn articulation_points_cover_disconnected_components() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("x", "y"), ("y", "z")]);

        let report = compute_articulation_points(&graph);

        assert_eq!(report.memory_ids, vec!["b", "y"]);
    }

    #[test]
    fn articulation_points_use_radix_public_id_payload_order() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([
            ("left_c", PUBLIC_ID_LATE),
            (PUBLIC_ID_LATE, "right_c"),
            ("left_a", PUBLIC_ID_EARLY),
            (PUBLIC_ID_EARLY, "right_a"),
        ]);

        let report = compute_articulation_points(&graph);

        assert_eq!(report.memory_ids, vec![PUBLIC_ID_EARLY, PUBLIC_ID_LATE]);
    }

    #[test]
    fn structural_decay_connectivity_reports_disconnected_graphs() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("x", "y")]);

        let report = compute_structural_decay_connectivity(&graph);

        assert_eq!(report.component_count, 2);
        assert!(!report.is_connected);
    }

    #[test]
    fn onion_layers_keep_core_above_leaf_shells() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([
            ("core_a", "core_b"),
            ("core_b", "core_c"),
            ("core_a", "core_c"),
            ("core_a", "leaf_a"),
            ("core_b", "leaf_b"),
        ]);

        let report = compute_onion_layers(&graph);

        assert_eq!(report.layers_by_memory.len(), 5);
        let leaf_layers = ["leaf_a", "leaf_b"]
            .iter()
            .map(|memory_id| report.layers_by_memory[*memory_id])
            .collect::<Vec<_>>();
        let core_layers = ["core_a", "core_b", "core_c"]
            .iter()
            .map(|memory_id| report.layers_by_memory[*memory_id])
            .collect::<Vec<_>>();
        let leaf_max = leaf_layers.iter().copied().fold(usize::MIN, usize::max);
        let core_min = core_layers.iter().copied().fold(usize::MAX, usize::min);
        assert!(
            core_min >= leaf_max,
            "core layer {core_min} should not be outside leaf layer {leaf_max}"
        );
        let observed_max_layer = report
            .layers_by_memory
            .values()
            .copied()
            .fold(usize::MIN, usize::max);
        assert_eq!(report.max_layer, observed_max_layer);
    }

    #[test]
    fn structural_decay_uses_baseline_for_single_shell_graphs() {
        let graph = Graph::complete_graph(CompatibilityMode::Strict, 4);

        let adjustment = compute_structural_decay_adjustment(&graph, "0");

        assert_eq!(adjustment.structural_multiplier, 1.0);
        assert_eq!(adjustment.rationale, "structural_decay_baseline");
    }

    #[test]
    fn structural_decay_uses_baseline_for_missing_memory() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c")]);

        let adjustment = compute_structural_decay_adjustment(&graph, "missing");

        assert_eq!(adjustment.memory_id, "missing");
        assert_eq!(adjustment.onion_layer, None);
        assert_eq!(adjustment.structural_multiplier, 1.0);
        assert!(!adjustment.is_articulation_point);
        assert_eq!(adjustment.rationale, "structural_decay_baseline");
    }

    #[test]
    fn structural_decay_protects_articulation_points() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("c", "d"), ("c", "e")]);

        let adjustment = compute_structural_decay_adjustment(&graph, "c");

        assert!(adjustment.is_articulation_point);
        assert!(adjustment.structural_multiplier < 1.0);
        assert_eq!(adjustment.rationale, "articulation_point_in_layer_2");
    }

    #[test]
    fn structural_decay_policy_uses_graph_config_overrides() {
        let policy = StructuralDecayPolicy::from_optional_config(Some(2.0), Some(0.25));
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("c", "d"), ("c", "e")]);

        let adjustment = compute_structural_decay_adjustment_with_policy(&graph, "c", policy);

        assert_eq!(policy.onion_decay_max, 2.0);
        assert_eq!(policy.articulation_protection, 0.25);
        assert!(adjustment.is_articulation_point);
        assert!(adjustment.structural_multiplier <= 0.5);
    }

    #[test]
    fn structural_decay_index_matches_direct_adjustments() {
        let policy = StructuralDecayPolicy::from_optional_config(Some(2.5), Some(0.4));
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([
            ("a", "b"),
            ("b", "c"),
            ("c", "d"),
            ("c", "e"),
            ("e", "f"),
        ]);
        let index = compute_structural_decay_index_with_policy(&graph, policy);

        for memory_id in ["a", "b", "c", "e", "missing"] {
            assert_eq!(
                index.adjustment(memory_id),
                compute_structural_decay_adjustment_with_policy(&graph, memory_id, policy)
            );
        }
    }

    // bd-1n0np.20.3 — bridge-exemption unit coverage over the existing
    // articulation-point structural-decay machinery (no reimplementation).

    #[test]
    fn bridge_exemption_detects_sole_articulation_bridge() {
        // A failure node bridged to its solution solely through one memory: that
        // memory is the cut vertex (the load-bearing bridge to protect).
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("failure", "bridge"), ("bridge", "solution")]);

        let report = compute_articulation_points(&graph);

        assert_eq!(report.memory_ids, vec!["bridge".to_string()]);
    }

    #[test]
    fn bridge_exemption_protects_only_genuine_sole_bridges_not_leaves() {
        // c is the sole bridge for d/e; d is a leaf. Exemption (protection
        // multiplier < 1.0) must apply ONLY to the articulation point.
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("c", "d"), ("c", "e")]);
        let index = compute_structural_decay_index(&graph);

        let bridge = index.adjustment("c");
        assert!(
            bridge.is_articulation_point,
            "c is a sole-bridge articulation"
        );
        assert!(
            bridge.structural_multiplier < 1.0,
            "the sole bridge is protected from decay"
        );

        let leaf = index.adjustment("d");
        assert!(
            !leaf.is_articulation_point,
            "a leaf is not a bridge and earns no exemption"
        );
    }

    #[test]
    fn bridge_exemption_skipped_in_dense_clique_no_cut_vertex() {
        // A clique has no cut vertices: nothing is a sole bridge, so nothing is
        // exempted (honest miss in dense graphs, not over-protection).
        let graph = Graph::complete_graph(CompatibilityMode::Strict, 4);

        let report = compute_articulation_points(&graph);
        assert!(
            report.memory_ids.is_empty(),
            "a clique has no articulation points"
        );

        let index = compute_structural_decay_index(&graph);
        let adjustment = index.adjustment("0");
        assert!(!adjustment.is_articulation_point);
        assert_eq!(adjustment.structural_multiplier, 1.0);
    }

    #[test]
    fn bridge_exemption_adjustment_is_deterministic() {
        let mut graph = Graph::new(CompatibilityMode::Strict);
        let _ = graph.extend_edges_unrecorded([("a", "b"), ("b", "c"), ("c", "d"), ("c", "e")]);

        let first = compute_structural_decay_index(&graph);
        let second = compute_structural_decay_index(&graph);

        assert_eq!(first.adjustment("c"), second.adjustment("c"));
        assert_eq!(first.adjustment("d"), second.adjustment("d"));
    }
}