sara-tasks 1.7.0

Sara — folder-aware task manager
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use anyhow::Result;
use rusqlite::Connection;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};

use crate::infrastructure::{db, memory_graph::MemoryGraph};

/// Default minimum synapse weight for two memories to be considered clustered.
/// Above a single weak shared tag (`W_SHARED_TAG` = 0.3) so broad tag crowding
/// does not explode into noise; a shared file (0.6), shared task (0.8), an
/// explicit link, or several summed anchors clears it.
pub const DEFAULT_MIN_WEIGHT: f64 = 0.5;

/// Default largest cluster `reflect` will propose. A connected component above
/// this is single-linkage chaining (A~B~C~…), not one lesson, so it is split at
/// its weakest synapses until every piece fits. 0 disables splitting.
pub const DEFAULT_MAX_CLUSTER: usize = 8;

/// A proposed consolidation: a cluster of related, not-yet-consolidated memories
/// and the canonical+derived_from restructuring that would tidy them.
#[derive(Debug)]
struct Cluster {
    /// Member labels (e.g. `m209`), suggested canonical first.
    members: Vec<String>,
    /// Label of the member proposed to become the canonical (strongest member).
    suggested_canonical: String,
    /// Tags shared by every member (may be empty).
    shared_tags: Vec<String>,
    /// Ranking score: size dominates, strength breaks ties.
    score: f64,
}

/// Union-find over memory indices for transitive clustering.
struct UnionFind {
    parent: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        UnionFind {
            parent: (0..n).collect(),
        }
    }
    fn find(&mut self, x: usize) -> usize {
        let mut r = x;
        while self.parent[r] != r {
            r = self.parent[r];
        }
        // Path compression.
        let mut cur = x;
        while self.parent[cur] != r {
            let next = self.parent[cur];
            self.parent[cur] = r;
            cur = next;
        }
        r
    }
    fn union(&mut self, a: usize, b: usize) {
        let (ra, rb) = (self.find(a), self.find(b));
        if ra != rb {
            self.parent[ra] = rb;
        }
    }
}

/// Core shared by CLI and MCP. Clusters related memories via the MemoryGraph and
/// proposes canonical+derived_from consolidations for clusters not yet tidied.
///
/// A cluster is a connected component (over synapses of weight >= `min_weight`)
/// of two or more memories. A component is **excluded** when it is already
/// consolidated: there exists a memory `P` such that every member either *is* `P`
/// or has an outgoing `derived_from` edge to `P` (i.e. a canonical and its
/// children, or siblings under a shared parent).
///
/// A component larger than `max_cluster` (0 = unlimited) that is not already
/// consolidated is split by [`split_component`] before being proposed.
pub fn reflect_value(conn: &Connection, min_weight: f64, max_cluster: usize) -> Result<Value> {
    let graph = MemoryGraph::build(conn)?;
    if graph.is_empty() {
        return Ok(json!({ "clusters": [], "count": 0 }));
    }

    // uuid -> node index.
    let index: HashMap<String, usize> = graph
        .nodes
        .iter()
        .enumerate()
        .map(|(i, n)| (n.uuid.to_string(), i))
        .collect();

    // Cluster via union-find over strong-enough edges.
    let mut uf = UnionFind::new(graph.nodes.len());
    let mut eligible: Vec<(usize, usize, f64)> = Vec::new();
    for (a, b, w) in graph.edges() {
        if w < min_weight {
            continue;
        }
        if let (Some(&ia), Some(&ib)) = (index.get(&a.to_string()), index.get(&b.to_string())) {
            uf.union(ia, ib);
            eligible.push((ia, ib, w));
        }
    }

    // Group node indices by component root.
    let mut components: HashMap<usize, Vec<usize>> = HashMap::new();
    for i in 0..graph.nodes.len() {
        let root = uf.find(i);
        components.entry(root).or_default().push(i);
    }

    // Per-memory outgoing `derived_from` parents (uuids), for the exclusion rule.
    let derived_parents: HashMap<String, HashSet<String>> = graph
        .nodes
        .iter()
        .map(|n| {
            let parents: HashSet<String> = db::get_memory_links_from(conn, &n.uuid.to_string())
                .unwrap_or_default()
                .into_iter()
                .filter(|l| l.relation == "derived_from")
                .map(|l| l.to_uuid)
                .collect();
            (n.uuid.to_string(), parents)
        })
        .collect();

    // Per-memory normalised tag set, for shared-tag intersection.
    let mut tags_by_uuid: HashMap<String, Vec<String>> = HashMap::new();
    for m in db::list_memories(conn)? {
        let tags: Vec<String> = m.tags.iter().map(|t| t.to_lowercase()).collect();
        tags_by_uuid.insert(m.uuid.to_string(), tags);
    }

    let uuids_of = |members: &[usize]| -> Vec<String> {
        members
            .iter()
            .map(|&i| graph.nodes[i].uuid.to_string())
            .collect()
    };

    // Split oversized components, but only ones not already tidied: a canonical
    // with many children is one consolidated family, not a chain to break up.
    let mut pieces: Vec<Vec<usize>> = Vec::new();
    for members in components.into_values() {
        if members.len() < 2 {
            continue;
        }
        if max_cluster > 0
            && members.len() > max_cluster
            && !is_already_consolidated(&uuids_of(&members), &derived_parents)
        {
            pieces.extend(split_component(members, &eligible, max_cluster));
        } else {
            pieces.push(members);
        }
    }

    let mut clusters: Vec<Cluster> = Vec::new();
    for member_idx in &pieces {
        if member_idx.len() < 2 {
            continue;
        }
        let uuids = uuids_of(member_idx);

        if is_already_consolidated(&uuids, &derived_parents) {
            continue;
        }

        // Strongest member becomes the suggested canonical.
        let mut sorted: Vec<usize> = member_idx.clone();
        sorted.sort_by(|&a, &b| {
            graph.nodes[b]
                .strength
                .partial_cmp(&graph.nodes[a].strength)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(graph.nodes[a].label.cmp(&graph.nodes[b].label))
        });
        let suggested_canonical = graph.nodes[sorted[0]].label.clone();
        let members: Vec<String> = sorted
            .iter()
            .map(|&i| graph.nodes[i].label.clone())
            .collect();

        let shared_tags = shared_tags(&uuids, &tags_by_uuid);

        let strength_sum: f64 = member_idx.iter().map(|&i| graph.nodes[i].strength).sum();
        let score = member_idx.len() as f64 * 100.0 + strength_sum;

        clusters.push(Cluster {
            members,
            suggested_canonical,
            shared_tags,
            score,
        });
    }

    // Rank: biggest, strongest clusters first; stable by canonical label.
    clusters.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(a.suggested_canonical.cmp(&b.suggested_canonical))
    });

    let items: Vec<Value> = clusters
        .iter()
        .map(|c| {
            let proposed_links: Vec<Value> = c
                .members
                .iter()
                .filter(|m| **m != c.suggested_canonical)
                .map(|m| {
                    json!({
                        "from": m,
                        "relation": "derived_from",
                        "to": c.suggested_canonical,
                    })
                })
                .collect();
            json!({
                "members": c.members,
                "suggested_canonical": c.suggested_canonical,
                "shared_tags": c.shared_tags,
                "proposed_links": proposed_links,
                "score": c.score,
            })
        })
        .collect();

    Ok(json!({
        "clusters": items,
        "count": items.len(),
    }))
}

/// Break a chained component into pieces of at most `max` members by repeatedly
/// dropping its weakest synapse level and re-taking connected components
/// (divisive single linkage). Tightly-bound cores survive; the weak bridges that
/// chained them together are what get cut. Members left without any surviving
/// edge come back as singletons, which callers ignore.
fn split_component(
    members: Vec<usize>,
    edges: &[(usize, usize, f64)],
    max: usize,
) -> Vec<Vec<usize>> {
    if members.len() <= max {
        return vec![members];
    }
    let local: HashMap<usize, usize> = members.iter().enumerate().map(|(k, &i)| (i, k)).collect();
    let inside: Vec<(usize, usize, f64)> = edges
        .iter()
        .copied()
        .filter(|(a, b, _)| local.contains_key(a) && local.contains_key(b))
        .collect();
    let Some(weakest) = inside.iter().map(|e| e.2).min_by(f64::total_cmp) else {
        return members.into_iter().map(|m| vec![m]).collect();
    };
    let kept: Vec<(usize, usize, f64)> = inside.into_iter().filter(|e| e.2 > weakest).collect();

    let mut uf = UnionFind::new(members.len());
    for (a, b, _) in &kept {
        uf.union(local[a], local[b]);
    }
    let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
    for (k, &m) in members.iter().enumerate() {
        groups.entry(uf.find(k)).or_default().push(m);
    }
    let mut out = Vec::new();
    for group in groups.into_values() {
        out.extend(split_component(group, &kept, max));
    }
    out
}

/// A component is already consolidated when some memory `P` is a common parent:
/// every member either *is* `P` or has a `derived_from` edge to `P`.
fn is_already_consolidated(
    uuids: &[String],
    derived_parents: &HashMap<String, HashSet<String>>,
) -> bool {
    // Candidate parents: any member, plus any parent any member points at.
    let mut candidates: HashSet<String> = uuids.iter().cloned().collect();
    for u in uuids {
        if let Some(parents) = derived_parents.get(u) {
            candidates.extend(parents.iter().cloned());
        }
    }
    candidates.iter().any(|p| {
        uuids.iter().all(|u| {
            u == p
                || derived_parents
                    .get(u)
                    .is_some_and(|parents| parents.contains(p))
        })
    })
}

/// Tags present on every member of the cluster.
fn shared_tags(uuids: &[String], tags_by_uuid: &HashMap<String, Vec<String>>) -> Vec<String> {
    let mut iter = uuids.iter();
    let first = match iter.next().and_then(|u| tags_by_uuid.get(u)) {
        Some(t) => t.clone(),
        None => return vec![],
    };
    let mut shared: Vec<String> = first;
    for u in iter {
        let set: HashSet<&String> = tags_by_uuid
            .get(u)
            .map(|t| t.iter().collect())
            .unwrap_or_default();
        shared.retain(|t| set.contains(t));
    }
    shared.sort();
    shared.dedup();
    shared
}

/// Materialise the consolidation the proposer suggests: for every cluster,
/// create the proposed `derived_from` edges (each non-canonical member ->
/// suggested canonical) via `db::insert_memory_link`. Idempotent — the DB dedups
/// `(from,to,relation)` and an already-consolidated cluster is not proposed
/// again. A link that would trip the `derived_from` cycle guard is skipped and
/// reported rather than aborting the whole pass.
///
/// Returns `{ applied, links[], skipped[], clusters }`.
pub fn apply_value(conn: &Connection, min_weight: f64, max_cluster: usize) -> Result<Value> {
    let proposal = reflect_value(conn, min_weight, max_cluster)?;
    let clusters = proposal["clusters"].as_array().cloned().unwrap_or_default();

    let mut applied: Vec<Value> = Vec::new();
    let mut skipped: Vec<Value> = Vec::new();

    for c in &clusters {
        let canonical = c["suggested_canonical"].as_str().unwrap_or_default();
        for link in c["proposed_links"].as_array().into_iter().flatten() {
            let from = link["from"].as_str().unwrap_or_default();
            let (from_uuid, to_uuid) = match (
                db::get_item_by_handle(conn, from),
                db::get_item_by_handle(conn, canonical),
            ) {
                (Ok(f), Ok(t)) => (f.uuid.to_string(), t.uuid.to_string()),
                _ => {
                    skipped.push(json!({
                        "from": from,
                        "to": canonical,
                        "relation": "derived_from",
                        "reason": "could not resolve memory label",
                    }));
                    continue;
                }
            };
            match db::insert_memory_link(conn, &from_uuid, &to_uuid, "derived_from", 1.0) {
                Ok(()) => applied.push(json!({
                    "from": from,
                    "relation": "derived_from",
                    "to": canonical,
                })),
                Err(e) => skipped.push(json!({
                    "from": from,
                    "to": canonical,
                    "relation": "derived_from",
                    "reason": e.to_string(),
                })),
            }
        }
    }

    Ok(json!({
        "applied": applied.len(),
        "links": applied,
        "skipped": skipped,
        "clusters": clusters.len(),
    }))
}

/// `sara reflect [--apply]` — propose (default) or materialise canonical+derived
/// consolidations for clusters of related, not-yet-tidied memories.
pub fn run(
    conn: &Connection,
    min_weight: f64,
    max_cluster: usize,
    json_output: bool,
    apply: bool,
) -> Result<()> {
    if apply {
        let v = apply_value(conn, min_weight, max_cluster)?;
        if json_output {
            println!("{}", serde_json::to_string_pretty(&v)?);
            return Ok(());
        }
        let applied = v["applied"].as_u64().unwrap_or(0);
        let skipped = v["skipped"].as_array().map(|a| a.len()).unwrap_or(0);
        if applied == 0 && skipped == 0 {
            println!(
                "Nothing to consolidate — no un-linked related clusters above the weight threshold."
            );
            return Ok(());
        }
        println!(
            "Consolidated {applied} link(s) across {} cluster(s):",
            v["clusters"].as_u64().unwrap_or(0)
        );
        for link in v["links"].as_array().into_iter().flatten() {
            println!(
                "  {} derived_from {}",
                link["from"].as_str().unwrap_or("?"),
                link["to"].as_str().unwrap_or("?"),
            );
        }
        if skipped > 0 {
            println!("\nSkipped {skipped} link(s):");
            for s in v["skipped"].as_array().into_iter().flatten() {
                println!(
                    "  {} -> {} : {}",
                    s["from"].as_str().unwrap_or("?"),
                    s["to"].as_str().unwrap_or("?"),
                    s["reason"].as_str().unwrap_or(""),
                );
            }
        }
        return Ok(());
    }

    let v = reflect_value(conn, min_weight, max_cluster)?;
    let count = v["count"].as_u64().unwrap_or(0);

    if json_output {
        println!("{}", serde_json::to_string_pretty(&v)?);
        return Ok(());
    }

    if count == 0 {
        println!(
            "Nothing to consolidate — no un-linked related clusters above the weight threshold."
        );
        return Ok(());
    }

    println!("{count} consolidation candidate(s) — related memories with no shared canonical:");
    println!();
    if let Some(clusters) = v["clusters"].as_array() {
        for c in clusters {
            let canonical = c["suggested_canonical"].as_str().unwrap_or("?");
            let members: Vec<&str> = c["members"]
                .as_array()
                .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                .unwrap_or_default();
            let tags: Vec<&str> = c["shared_tags"]
                .as_array()
                .map(|a| a.iter().filter_map(|x| x.as_str()).collect())
                .unwrap_or_default();

            let tag_str = if tags.is_empty() {
                String::new()
            } else {
                format!("  [shared tags: {}]", tags.join(", "))
            };
            println!(
                "  {} members, canonical -> {canonical}{tag_str}",
                members.len()
            );
            println!("    cluster: {}", members.join(", "));
            for link in c["proposed_links"].as_array().into_iter().flatten() {
                let from = link["from"].as_str().unwrap_or("?");
                println!("    sara link-memory {from} derived_from {canonical}");
            }
            println!();
        }
    }
    println!("Review each cluster, then run the printed `sara link-memory` lines to consolidate.");
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::infrastructure::{db, model::Item};
    use uuid::Uuid;

    /// Insert a tagged memory (no anchors — edges are added explicitly per test).
    fn insert_memory(conn: &rusqlite::Connection, body: &str, tag: &str) -> Uuid {
        let mut item = Item::new_memory(body.to_string(), body.to_string(), None);
        item.tags = vec![tag.to_string()];
        item.path = Some(String::new());
        db::insert_item(conn, &mut item).unwrap();
        item.uuid
    }

    fn link(conn: &rusqlite::Connection, from: &Uuid, to: &Uuid, relation: &str) {
        db::insert_memory_link(conn, &from.to_string(), &to.to_string(), relation, 1.0).unwrap();
    }

    fn weighted_link(conn: &rusqlite::Connection, from: &Uuid, to: &Uuid, weight: f64) {
        db::insert_memory_link(
            conn,
            &from.to_string(),
            &to.to_string(),
            "similar_to",
            weight,
        )
        .unwrap();
    }

    fn cluster_sizes(v: &serde_json::Value) -> Vec<usize> {
        let mut sizes: Vec<usize> = v["clusters"]
            .as_array()
            .unwrap()
            .iter()
            .map(|c| c["members"].as_array().unwrap().len())
            .collect();
        sizes.sort_unstable_by(|a, b| b.cmp(a));
        sizes
    }

    #[test]
    fn chained_mega_component_is_split_at_its_weakest_links() {
        // Single linkage chains a long run of moderately-related memories into
        // one blob. Two tight triangles joined by a weak chain must come back as
        // the two triangles, not as one 12-member cluster.
        let conn = db::open_in_memory_for_test();
        let m: Vec<Uuid> = (0..12)
            .map(|i| insert_memory(&conn, &format!("memory {i}"), &format!("t{i}")))
            .collect();
        for w in m[2..10].windows(2) {
            weighted_link(&conn, &w[0], &w[1], 1.0); // chain edge: 0.7
        }
        for tri in [&m[0..3], &m[9..12]] {
            weighted_link(&conn, &tri[0], &tri[1], 2.0); // tight edge: capped 1.0
            weighted_link(&conn, &tri[1], &tri[2], 2.0);
            weighted_link(&conn, &tri[0], &tri[2], 2.0);
        }

        let unsplit = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, 0).unwrap();
        assert_eq!(cluster_sizes(&unsplit), vec![12], "0 disables splitting");

        let v = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, 4).unwrap();
        assert_eq!(cluster_sizes(&v), vec![3, 3]);
    }

    #[test]
    fn component_within_max_size_is_not_split() {
        let conn = db::open_in_memory_for_test();
        let m: Vec<Uuid> = (0..4)
            .map(|i| insert_memory(&conn, &format!("memory {i}"), &format!("t{i}")))
            .collect();
        weighted_link(&conn, &m[0], &m[1], 2.0);
        weighted_link(&conn, &m[1], &m[2], 1.0);
        weighted_link(&conn, &m[2], &m[3], 1.0);
        let v = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, 4).unwrap();
        assert_eq!(cluster_sizes(&v), vec![4]);
    }

    #[test]
    fn fresh_related_cluster_is_proposed_with_a_canonical() {
        let conn = db::open_in_memory_for_test();
        // Three memories flagged related (similar_to, 0.7 each) but with no
        // canonical yet — the exact shape a consolidation should propose.
        let a = insert_memory(
            &conn,
            "dependabot bump broke restore in repo a",
            "dependabot",
        );
        let b = insert_memory(
            &conn,
            "dependabot bump broke restore in repo b",
            "dependabot",
        );
        let c = insert_memory(
            &conn,
            "dependabot bump broke restore in repo c",
            "dependabot",
        );
        link(&conn, &a, &b, "similar_to");
        link(&conn, &b, &c, "similar_to");

        let v = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
            .unwrap();
        assert_eq!(v["count"].as_u64().unwrap(), 1, "one cluster expected");
        let cluster = &v["clusters"][0];
        assert_eq!(cluster["members"].as_array().unwrap().len(), 3);
        assert!(!cluster["suggested_canonical"].as_str().unwrap().is_empty());
        // Two derived_from links proposed (canonical + 2 children).
        assert_eq!(cluster["proposed_links"].as_array().unwrap().len(), 2);
        // The shared tag is surfaced.
        assert!(
            cluster["shared_tags"]
                .as_array()
                .unwrap()
                .iter()
                .any(|t| t == "dependabot")
        );
    }

    #[test]
    fn already_consolidated_cluster_is_excluded() {
        let conn = db::open_in_memory_for_test();
        let canonical = insert_memory(&conn, "canonical pattern", "dependabot");
        let child_a = insert_memory(&conn, "applied in repo a", "dependabot");
        let child_b = insert_memory(&conn, "applied in repo b", "dependabot");

        // Both children point at the canonical — the cluster is already tidy.
        // (derived_from carries weight 0.8, so they still form one component.)
        link(&conn, &child_a, &canonical, "derived_from");
        link(&conn, &child_b, &canonical, "derived_from");

        let v = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
            .unwrap();
        assert_eq!(
            v["count"].as_u64().unwrap(),
            0,
            "a canonical + its derived children must not be re-proposed"
        );
    }

    #[test]
    fn unrelated_memories_are_not_clustered() {
        let conn = db::open_in_memory_for_test();
        insert_memory(&conn, "memory about auth", "auth");
        insert_memory(&conn, "memory about billing", "billing");

        let v = super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
            .unwrap();
        assert_eq!(
            v["count"].as_u64().unwrap(),
            0,
            "no shared anchors -> no cluster"
        );
    }

    /// Count `derived_from` edges emanating from the given memories.
    fn derived_from_count(conn: &rusqlite::Connection, uuids: &[&Uuid]) -> usize {
        uuids
            .iter()
            .map(|u| {
                db::get_memory_links_from(conn, &u.to_string())
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|l| l.relation == "derived_from")
                    .count()
            })
            .sum()
    }

    #[test]
    fn reflect_apply_creates_derived_links() {
        let conn = db::open_in_memory_for_test();
        let a = insert_memory(&conn, "dependabot bump repo a", "dependabot");
        let b = insert_memory(&conn, "dependabot bump repo b", "dependabot");
        let c = insert_memory(&conn, "dependabot bump repo c", "dependabot");
        link(&conn, &a, &b, "similar_to");
        link(&conn, &b, &c, "similar_to");

        let v = super::apply_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
            .unwrap();
        assert_eq!(
            v["applied"].as_u64().unwrap(),
            2,
            "two children linked to the canonical"
        );
        assert!(
            v["skipped"].as_array().unwrap().is_empty(),
            "nothing skipped"
        );

        // Exactly two derived_from edges now exist across the cluster.
        assert_eq!(derived_from_count(&conn, &[&a, &b, &c]), 2);
    }

    #[test]
    fn reflect_apply_is_idempotent_and_excludes_after() {
        let conn = db::open_in_memory_for_test();
        let a = insert_memory(&conn, "dependabot bump repo a", "dependabot");
        let b = insert_memory(&conn, "dependabot bump repo b", "dependabot");
        let c = insert_memory(&conn, "dependabot bump repo c", "dependabot");
        link(&conn, &a, &b, "similar_to");
        link(&conn, &b, &c, "similar_to");

        let first =
            super::apply_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
                .unwrap();
        assert_eq!(first["applied"].as_u64().unwrap(), 2);

        // Second run: the cluster is now consolidated -> nothing to propose/apply.
        let second =
            super::apply_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
                .unwrap();
        assert_eq!(second["applied"].as_u64().unwrap(), 0, "no re-application");
        assert!(second["skipped"].as_array().unwrap().is_empty());

        // No duplicate edges, and the proposer no longer sees the cluster.
        assert_eq!(
            derived_from_count(&conn, &[&a, &b, &c]),
            2,
            "no duplicate links"
        );
        let proposal =
            super::reflect_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
                .unwrap();
        assert_eq!(
            proposal["count"].as_u64().unwrap(),
            0,
            "consolidated cluster excluded"
        );
    }

    #[test]
    fn reflect_apply_skips_cycle_violations() {
        let conn = db::open_in_memory_for_test();
        // Insertion order fixes labels m1<m2<m3; equal strength -> canonical = a.
        let a = insert_memory(&conn, "dependabot bump repo a", "dependabot");
        let b = insert_memory(&conn, "dependabot bump repo b", "dependabot");
        let c = insert_memory(&conn, "dependabot bump repo c", "dependabot");
        link(&conn, &a, &b, "similar_to");
        link(&conn, &b, &c, "similar_to");
        // Pre-existing a -> b derived_from: proposing b -> a would form a cycle.
        link(&conn, &a, &b, "derived_from");
        // `b` now carries an incoming derived_from edge, which gives it a small
        // canonical-derived strength bonus (task e7ff611e) that would otherwise
        // flip the tie-break and make `b` the suggested canonical instead of
        // `a`. Pin `a`'s strength above that bonus via a completed source task
        // so the tie-break (and the scenario this test targets) is unaffected.
        let mut task = crate::infrastructure::model::Task::new(
            "completed task".to_string(),
            "Sara".to_string(),
        );
        task.status = crate::infrastructure::model::Status::Completed;
        db::insert_task(&conn, &mut task).unwrap();
        db::set_item_task_links(&conn, &a, &[(task.uuid, "explicit")]).unwrap();

        let v = super::apply_value(&conn, super::DEFAULT_MIN_WEIGHT, super::DEFAULT_MAX_CLUSTER)
            .unwrap();
        // c -> a applies; b -> a is skipped for the cycle it would create.
        assert_eq!(
            v["applied"].as_u64().unwrap(),
            1,
            "only the safe link applies"
        );
        let skipped = v["skipped"].as_array().unwrap();
        assert_eq!(
            skipped.len(),
            1,
            "the cycle-forming link is skipped, not fatal"
        );
        assert!(
            skipped[0]["reason"]
                .as_str()
                .unwrap()
                .to_lowercase()
                .contains("cycle"),
            "skip reason names the cycle: {:?}",
            skipped[0]["reason"]
        );

        // c -> a exists; b -> a does not.
        let c_links = db::get_memory_links_from(&conn, &c.to_string()).unwrap();
        assert!(
            c_links
                .iter()
                .any(|l| l.relation == "derived_from" && l.to_uuid == a.to_string())
        );
        let b_links = db::get_memory_links_from(&conn, &b.to_string()).unwrap();
        assert!(
            !b_links
                .iter()
                .any(|l| l.relation == "derived_from" && l.to_uuid == a.to_string())
        );
    }
}