fur-cli 2.1.1

Turn your AI chats into a durable, local-first diary. Save messages, attach notes, organize conversations, and stop losing context every time the model forgets you exist.
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
//! Conversation lineage, derived from `.fur/threads/`.
//!
//! # Assertions, not records
//!
//! `parents` and `children` are independent claims. A holds "B is my child"
//! and B holds "A is my parent"; either can exist without the other, because
//! one of them may have been imported from a registry without the other. The
//! traversal graph is therefore the *union* of every claim in the project, and
//! an edge asserted from one side only is a real edge.
//!
//! The raw claims are kept alongside the union, because the union deliberately
//! erases which side made the claim — and that is exactly what asymmetry
//! detection needs.
//!
//! # Cycles are data, not errors
//!
//! Nothing here rejects a cycle. `fur link` refuses to create one locally, but
//! two people can independently publish A→B and B→A and the cycle only exists
//! once both land in one archive. Every walk carries a visited set — which it
//! needs for diamonds regardless — so a node reached twice is emitted once and
//! flagged, never expanded again.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs;
use std::path::Path;

use serde_json::Value;

/// One row of a rendered lineage tree.
pub struct TreeEntry {
    pub id: String,
    /// Nesting level; 0 is a root.
    pub depth: usize,
    /// Already shown higher up — the second arm of a diamond. Not expanded.
    pub repeat: bool,
    /// Has parents, none of which are in this project. Sits at the margin
    /// because there is nothing local to nest it under.
    pub orphan_parent: bool,
}

pub struct Lineage {
    titles: BTreeMap<String, String>,
    parents: BTreeMap<String, BTreeSet<String>>,
    children: BTreeMap<String, BTreeSet<String>>,
    claimed_parents: BTreeMap<String, BTreeSet<String>>,
    claimed_children: BTreeMap<String, BTreeSet<String>>,
}

// `title`, `asymmetric` and `dangling` are the reporting surface: `fur doctor`
// and the visual export read them, the conversation table does not.
#[allow(dead_code)]
impl Lineage {
    /// Build from `.fur/threads/`, reading the directory rather than the index
    /// so a stale `index.json` cannot hide a conversation.
    pub fn load(fur_dir: &Path) -> Result<Lineage, String> {
        let threads = fur_dir.join("threads");
        let entries = fs::read_dir(&threads)
            .map_err(|e| format!("cannot read {}: {}", threads.display(), e))?;

        let mut lineage = Lineage {
            titles: BTreeMap::new(),
            parents: BTreeMap::new(),
            children: BTreeMap::new(),
            claimed_parents: BTreeMap::new(),
            claimed_children: BTreeMap::new(),
        };

        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }

            let Some(content) = crate::security::io::read_text_file(&path) else {
                continue;
            };
            let Ok(convo) = serde_json::from_str::<Value>(&content) else {
                continue;
            };
            let Some(id) = convo["id"].as_str() else {
                continue;
            };

            lineage.titles.insert(
                id.to_string(),
                convo["title"].as_str().unwrap_or("Untitled").to_string(),
            );

            for parent in string_list(&convo, "parents") {
                lineage
                    .claimed_parents
                    .entry(id.to_string())
                    .or_default()
                    .insert(parent.clone());
                lineage.add_edge(&parent, id);
            }
            for child in string_list(&convo, "children") {
                lineage
                    .claimed_children
                    .entry(id.to_string())
                    .or_default()
                    .insert(child.clone());
                lineage.add_edge(id, &child);
            }
        }

        Ok(lineage)
    }

    /// Record one edge in both directions, so a claim from either end is
    /// visible from both.
    fn add_edge(&mut self, parent: &str, child: &str) {
        self.children
            .entry(parent.to_string())
            .or_default()
            .insert(child.to_string());
        self.parents
            .entry(child.to_string())
            .or_default()
            .insert(parent.to_string());
    }

    pub fn is_empty(&self) -> bool {
        self.parents.is_empty() && self.children.is_empty()
    }

    pub fn is_local(&self, id: &str) -> bool {
        self.titles.contains_key(id)
    }

    pub fn title(&self, id: &str) -> Option<&str> {
        self.titles.get(id).map(|s| s.as_str())
    }

    /// Would linking `parent` → `child` close a loop? True when `child` can
    /// already reach `parent` by following children.
    pub fn would_cycle(&self, parent: &str, child: &str) -> bool {
        let mut seen: HashSet<&str> = HashSet::new();
        let mut stack = vec![child];

        while let Some(id) = stack.pop() {
            if id == parent {
                return true;
            }
            if !seen.insert(id) {
                continue;
            }
            if let Some(kids) = self.children.get(id) {
                stack.extend(kids.iter().map(|s| s.as_str()));
            }
        }

        false
    }

    /// Every local conversation reachable upward from `start`, in dependency
    /// order: a conversation always appears after everything it draws on.
    ///
    /// `start` is last. Absent conversations are skipped — there is nothing
    /// local to print for them — but `absent_ancestors` reports them so the
    /// document can say what it could not include.
    pub fn ancestry(&self, start: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut state: HashMap<String, u8> = HashMap::new();
        self.visit_up(start, &mut state, &mut out);
        out
    }

    /// Post-order DFS. `state` marks 1 = in progress, 2 = emitted; the
    /// in-progress mark is what makes an imported cycle terminate instead of
    /// recursing forever.
    fn visit_up(&self, id: &str, state: &mut HashMap<String, u8>, out: &mut Vec<String>) {
        match state.get(id) {
            Some(_) => return,
            None => state.insert(id.to_string(), 1),
        };

        if let Some(parents) = self.parents.get(id) {
            for parent in parents {
                if self.is_local(parent) {
                    self.visit_up(parent, state, out);
                }
            }
        }

        state.insert(id.to_string(), 2);

        if self.is_local(id) {
            out.push(id.to_string());
        }
    }

    /// Every local conversation reachable downward from `start`, in dependency
    /// order: a conversation always appears after everything it draws on.
    ///
    /// The reachable set is collected first, then ordered by walking *upward*
    /// within it — the same rule that orders ancestors. Ordering by descent
    /// would emit a diamond's tip before one of its arms.
    pub fn descendants(&self, start: &str) -> Vec<String> {
        let mut reachable: HashSet<String> = HashSet::new();
        let mut stack = vec![start.to_string()];

        while let Some(id) = stack.pop() {
            if !reachable.insert(id.clone()) {
                continue;
            }
            if let Some(kids) = self.children.get(&id) {
                stack.extend(kids.iter().cloned());
            }
        }

        let mut out = Vec::new();
        let mut state: HashMap<String, u8> = HashMap::new();

        // Seed `start` as emitted so it leads, and so parents outside the
        // reachable set are never pulled in by the upward walk.
        state.insert(start.to_string(), 2);
        if self.is_local(start) {
            out.push(start.to_string());
        }

        let mut members: Vec<&String> = reachable.iter().filter(|id| *id != start).collect();
        members.sort();

        for id in members {
            self.visit_up_within(id, &reachable, &mut state, &mut out);
        }

        out
    }

    /// Post-order DFS restricted to `allowed`, so ordering a subgraph cannot
    /// drag in conversations from outside it.
    fn visit_up_within(
        &self,
        id: &str,
        allowed: &HashSet<String>,
        state: &mut HashMap<String, u8>,
        out: &mut Vec<String>,
    ) {
        match state.get(id) {
            Some(_) => return,
            None => state.insert(id.to_string(), 1),
        };

        if let Some(parents) = self.parents.get(id) {
            for parent in parents {
                if allowed.contains(parent) && self.is_local(parent) {
                    self.visit_up_within(parent, allowed, state, out);
                }
            }
        }

        state.insert(id.to_string(), 2);

        if self.is_local(id) {
            out.push(id.to_string());
        }
    }

    /// Ancestors of `start` that this project does not hold, so a provenance
    /// document can name what it was unable to include.
    pub fn absent_ancestors(&self, start: &str) -> Vec<String> {
        let local = self.ancestry(start);
        let mut out = BTreeSet::new();

        for id in local.iter().map(|s| s.as_str()).chain(std::iter::once(start)) {
            if let Some(parents) = self.parents.get(id) {
                for parent in parents {
                    if !self.is_local(parent) {
                        out.insert(parent.clone());
                    }
                }
            }
        }

        out.into_iter().collect()
    }

    /// Direct local parents of `id`, for the lineage map at the head of a
    /// provenance document.
    pub fn parents_of(&self, id: &str) -> Vec<String> {
        self.parents
            .get(id)
            .map(|set| set.iter().filter(|p| self.is_local(p)).cloned().collect())
            .unwrap_or_default()
    }

    /// Every local conversation, sorted.
    pub fn ids(&self) -> Vec<String> {
        self.titles.keys().cloned().collect()
    }

    /// Parents of `id`, including ones this project does not hold.
    pub fn all_parents(&self, id: &str) -> Vec<String> {
        self.parents
            .get(id)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Children of `id`, including ones this project does not hold.
    pub fn all_children(&self, id: &str) -> Vec<String> {
        self.children
            .get(id)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Edges between two local conversations asserted from one side only.
    ///
    /// Compares the raw claims, never the union — in the union a one-sided
    /// claim has already been mirrored for traversal, so checking it there
    /// could never report anything. Edges whose far end is absent are skipped:
    /// there is no local file that could hold the mirror.
    pub fn asymmetric(&self) -> Vec<(String, String)> {
        let mut out = BTreeSet::new();

        for (parent, kids) in &self.claimed_children {
            for child in kids {
                if !self.is_local(parent) || !self.is_local(child) {
                    continue;
                }
                let mirrored = self
                    .claimed_parents
                    .get(child)
                    .map(|set| set.contains(parent))
                    .unwrap_or(false);
                if !mirrored {
                    out.insert((parent.clone(), child.clone()));
                }
            }
        }

        for (child, parents) in &self.claimed_parents {
            for parent in parents {
                if !self.is_local(parent) || !self.is_local(child) {
                    continue;
                }
                let mirrored = self
                    .claimed_children
                    .get(parent)
                    .map(|set| set.contains(child))
                    .unwrap_or(false);
                if !mirrored {
                    out.insert((parent.clone(), child.clone()));
                }
            }
        }

        out.into_iter().collect()
    }

    /// Conversation ids that nothing local holds as a parent.
    pub fn dangling(&self) -> Vec<String> {
        self.parents
            .keys()
            .chain(self.children.keys())
            .chain(self.parents.values().flatten())
            .chain(self.children.values().flatten())
            .filter(|id| !self.is_local(id))
            .cloned()
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect()
    }

    /// Flatten the project into display order: roots first, children nested
    /// beneath them, siblings in the order given by `order`.
    ///
    /// `order` is the caller's preferred sequence (newest first, typically);
    /// it decides which root comes first and how siblings sort, while the
    /// lineage decides the nesting. Conversations no root reaches — every
    /// member of a cycle — are appended at the margin so nothing disappears.
    pub fn forest(&self, order: &[String]) -> Vec<TreeEntry> {
        let mut out = Vec::new();
        let mut visited: HashSet<String> = HashSet::new();

        for id in order {
            if !self.is_local(id) || self.has_local_parent(id) {
                continue;
            }
            self.descend(id, 0, order, &mut visited, &mut out);
        }

        for id in order {
            if self.is_local(id) && !visited.contains(id) {
                self.descend(id, 0, order, &mut visited, &mut out);
            }
        }

        out
    }

    fn descend(
        &self,
        id: &str,
        depth: usize,
        order: &[String],
        visited: &mut HashSet<String>,
        out: &mut Vec<TreeEntry>,
    ) {
        let repeat = !visited.insert(id.to_string());

        out.push(TreeEntry {
            id: id.to_string(),
            depth,
            repeat,
            orphan_parent: depth == 0 && self.has_only_absent_parents(id),
        });

        if repeat {
            return;
        }

        for child in self.ordered_local_children(id, order) {
            self.descend(&child, depth + 1, order, visited, out);
        }
    }

    fn has_local_parent(&self, id: &str) -> bool {
        self.parents
            .get(id)
            .map(|set| set.iter().any(|p| self.is_local(p)))
            .unwrap_or(false)
    }

    fn has_only_absent_parents(&self, id: &str) -> bool {
        match self.parents.get(id) {
            Some(set) if !set.is_empty() => set.iter().all(|p| !self.is_local(p)),
            _ => false,
        }
    }

    fn ordered_local_children(&self, id: &str, order: &[String]) -> Vec<String> {
        let Some(kids) = self.children.get(id) else {
            return Vec::new();
        };

        let mut out: Vec<String> = kids.iter().filter(|k| self.is_local(k)).cloned().collect();

        out.sort_by_key(|k| order.iter().position(|o| o == k).unwrap_or(usize::MAX));
        out
    }
}

fn string_list(value: &Value, key: &str) -> Vec<String> {
    value[key]
        .as_array()
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect()
        })
        .unwrap_or_default()
}