kimun-notes 0.23.2

A terminal-based notes application
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
//! Orchestration: turn observed changes and the vault's authoritative state into
//! server pushes/deletes. [`RagSync`] wires the observer; `drain` flushes the
//! dirty-set (the fast path); `reconcile` is the correctness backbone.
//! All server I/O goes through [`RagTransport`], so this logic is
//! tested with a fake against a real vault.

use std::collections::HashMap;
use std::sync::Arc;

use kimun_core::{IndexObserver, NoteVault, error::VaultError, nfs::VaultPath};

use crate::server_client::dto::{WireDoc, WireSection};
use crate::server_client::{
    DirtyOp, DirtySet, RagClient, RagError, RagObserver, RagTransport, hash_string, reconcile_diff,
};

/// What a reachable server can do, derived from `/health`: search
/// needs an embedder, question-answering needs an embedder AND an LLM.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerCapability {
    /// No embedder configured — nothing works server-side; the client must not
    /// push or reconcile (every call would 503).
    Unconfigured,
    /// Embedder, no LLM: search and sync work, question-answering does not.
    SemanticOnly,
    /// Embedder and LLM: everything works.
    Full,
}

impl ServerCapability {
    /// Derives the capability from a health probe's fields.
    pub fn from_health(health: &crate::server_client::dto::Health) -> Self {
        match (health.embedder.is_some(), health.llm_provider.is_some()) {
            (false, _) => ServerCapability::Unconfigured,
            (true, false) => ServerCapability::SemanticOnly,
            (true, true) => ServerCapability::Full,
        }
    }

    /// Whether question-answering is usable.
    pub fn llm_available(self) -> bool {
        matches!(self, ServerCapability::Full)
    }
}

/// One `/health` round-trip's worth of facts: what the server can do, and
/// whether it gates its API behind a bearer token. `/health` itself is
/// un-gated, so a client with a missing/wrong token still probes fine —
/// `auth_required` lets it report "unauthorized" up front instead of
/// discovering a 401 on the first sync call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServerProbe {
    pub capability: ServerCapability,
    pub auth_required: bool,
}

/// Bundles a vault, its dirty-set, and the server client, and drives sync. The
/// caller (the TUI) owns the schedule: [`probe`](RagSync::probe) to gate
/// features, and call [`tick`](RagSync::tick) periodically to keep the server in
/// step.
pub struct RagSync {
    vault: Arc<NoteVault>,
    dirty: Arc<DirtySet>,
    /// The exact observer this sync registered, kept so `Drop` can deregister
    /// *only* ours (by identity) and never a newer one that replaced it.
    observer: Arc<dyn IndexObserver>,
    client: RagClient,
}

impl RagSync {
    /// Registers the observer on `vault` and returns a handle over it. Construct
    /// **one** `RagSync` per vault: the observer is zero-or-one, so a second
    /// `RagSync` for the same vault replaces the first's observer and strands its
    /// dirty-set (its `tick` still self-heals via reconcile, but its drain fast
    /// path goes silent).
    pub fn new(vault: Arc<NoteVault>, client: RagClient) -> Self {
        let dirty = Arc::new(DirtySet::default());
        let observer: Arc<dyn IndexObserver> = Arc::new(RagObserver::new(dirty.clone()));
        vault.set_index_observer(observer.clone());
        Self {
            vault,
            dirty,
            observer,
            client,
        }
    }

    /// Probe reachability, capability, and auth in one `/health` request:
    /// `None` = offline; otherwise a [`ServerProbe`] carrying the server's
    /// [`ServerCapability`] — `Unconfigured` (no embedder: don't sync),
    /// `SemanticOnly` (search, no Q&A), or `Full` — and whether the API
    /// requires a bearer token.
    pub async fn probe(&self) -> Option<ServerProbe> {
        self.client.health().await.ok().map(|h| ServerProbe {
            capability: ServerCapability::from_health(&h),
            auth_required: h.auth_required,
        })
    }

    /// Whether the local index is filled and safe to sync from. `false` while
    /// a healed/rebuilding index is still empty — syncing then would read "no
    /// notes" and tear the server collection down (see [`reconcile`]).
    pub fn index_ready(&self) -> bool {
        self.vault.index_ready()
    }

    /// One sync pass: flush pending changes, then reconcile to repair drift.
    /// Returns `false` when either half was skipped because the local index
    /// is not ready yet — call again once it is.
    pub async fn tick(&self) -> Result<bool, RagError> {
        let drained = drain(&self.vault, &self.dirty, &self.client).await?;
        let reconciled = reconcile(&self.vault, &self.client).await?;
        Ok(drained && reconciled)
    }

    /// Flush pending changes only — the cheap fast path (touches only dirty
    /// notes). Run this often; run [`tick`](Self::tick)/[`reconcile`](Self::reconcile)
    /// occasionally as the safety net. Returns `false` when skipped because
    /// the local index is not ready.
    pub async fn drain(&self) -> Result<bool, RagError> {
        drain(&self.vault, &self.dirty, &self.client).await
    }

    /// Full hash-diff reconciliation only — an index-wide read + a full-collection
    /// hash fetch. The periodic backbone; not needed on every tick. Returns
    /// `false` when skipped because the local index is not ready.
    pub async fn reconcile(&self) -> Result<bool, RagError> {
        reconcile(&self.vault, &self.client).await
    }

    /// The underlying client, for queries (search / ask).
    pub fn client(&self) -> &RagClient {
        &self.client
    }
}

impl Drop for RagSync {
    fn drop(&mut self) {
        // Deregister *our* observer so a superseded/aborted sync doesn't leave
        // the vault feeding a dirty-set nobody drains — but only if it's still
        // ours, so we never wipe a newer sync that has replaced it.
        self.vault.clear_index_observer_if(&self.observer);
    }
}

/// Builds the wire document for a note: its canonical path, content hash, and
/// heading sections pulled from the index. Returns `None` when the note has no
/// indexable sections — an empty note is not RAG content, so it is never pushed
/// (this keeps both backends from perpetually re-pushing chunkless notes, since
/// only one of them records a hash for them server-side).
pub async fn build_doc(
    vault: &NoteVault,
    path: &VaultPath,
    hash: u64,
) -> Result<Option<WireDoc>, VaultError> {
    let chunks = vault.get_note_chunks(path).await?;
    let sections: Vec<WireSection> = chunks
        .into_values()
        .flatten()
        .map(|c| WireSection {
            title: c.get_breadcrumb().to_string(),
            text: c.get_text().to_string(),
        })
        .collect();
    if sections.is_empty() {
        return Ok(None);
    }
    Ok(Some(WireDoc {
        path: path.to_string(),
        hash: hash_string(hash),
        sections,
    }))
}

/// Flushes the dirty-set to the server. Failed operations are re-queued so the
/// next drain (or a reconcile) retries them.
///
/// Returns `false` (doing nothing) when the local index is not ready: an
/// unready (healed/rebuilding) index reads as empty, so build_doc would find
/// no chunks and turn queued upserts into server-side deletes. The dirty-set
/// stays queued until the index is filled; callers should retry then.
pub async fn drain<T: RagTransport>(
    vault: &NoteVault,
    dirty: &DirtySet,
    transport: &T,
) -> Result<bool, RagError> {
    if !vault.index_ready() {
        return Ok(false);
    }
    let ops = dirty.drain();
    if ops.is_empty() {
        return Ok(true);
    }

    let mut upserts: Vec<(VaultPath, u64)> = Vec::new();
    let mut deletes: Vec<String> = Vec::new();
    for (path, op) in ops {
        match op {
            DirtyOp::Upsert(hash) => upserts.push((path, hash)),
            DirtyOp::Delete => deletes.push(path.to_string()),
        }
    }

    // Build the docs for upserts; a note that can't be read right now is
    // re-queued rather than dropped.
    let mut docs = Vec::new();
    let mut built: Vec<(VaultPath, u64)> = Vec::new();
    for (path, hash) in upserts {
        match build_doc(vault, &path, hash).await {
            Ok(Some(doc)) => {
                docs.push(doc);
                built.push((path, hash));
            }
            // An emptied note has no chunks to index — delete it server-side so
            // its old chunks don't linger (and so /hashes stops reporting it).
            Ok(None) => deletes.push(path.to_string()),
            Err(_) => dirty.requeue([(path, DirtyOp::Upsert(hash))]),
        }
    }

    let mut first_err: Option<RagError> = None;
    if !docs.is_empty()
        && let Err(e) = transport.push_docs(docs).await
    {
        dirty.requeue(built.into_iter().map(|(p, h)| (p, DirtyOp::Upsert(h))));
        first_err = Some(e);
    }
    if !deletes.is_empty() {
        let paths_for_requeue: Vec<VaultPath> = deletes.iter().map(VaultPath::new).collect();
        if let Err(e) = transport.delete_paths(deletes).await {
            dirty.requeue(paths_for_requeue.into_iter().map(|p| (p, DirtyOp::Delete)));
            first_err = first_err.or(Some(e));
        }
    }

    match first_err {
        Some(e) => Err(e),
        None => Ok(true),
    }
}

/// Reconciles the server with the vault: diff hash sets, then push/delete only
/// the differences. Self-healing — repairs anything the drain path missed.
///
/// Returns `false` (doing nothing) when the local index is not ready: a
/// healed/rebuilding index reads as an empty vault, and diffing against that
/// snapshot would put every server doc in `to_delete` — wiping the collection.
/// Callers should retry once the index is filled.
pub async fn reconcile<T: RagTransport>(
    vault: &NoteVault,
    transport: &T,
) -> Result<bool, RagError> {
    if !vault.index_ready() {
        return Ok(false);
    }
    let notes = vault
        .get_all_notes()
        .await
        .map_err(|e| RagError::Protocol(format!("read vault notes: {e}")))?;

    let local_hashes: HashMap<String, u64> = notes
        .into_iter()
        .map(|(entry, content)| (entry.path.to_string(), content.hash))
        .collect();
    let local_str: HashMap<String, String> = local_hashes
        .iter()
        .map(|(p, h)| (p.clone(), hash_string(*h)))
        .collect();

    let server = transport.server_hashes().await?;
    let plan = reconcile_diff(&local_str, &server);

    let mut docs = Vec::new();
    let mut to_delete = plan.to_delete;
    for path_str in &plan.to_push {
        let hash = local_hashes[path_str];
        match build_doc(vault, &VaultPath::new(path_str), hash)
            .await
            .map_err(|e| RagError::Protocol(format!("build doc {path_str}: {e}")))?
        {
            Some(doc) => docs.push(doc),
            // Empty note: it carries no chunks. If the server still has it (it
            // was emptied), delete it; if not, it's already converged (nothing
            // to push). Either way it never becomes a stale server entry.
            None => {
                if server.contains_key(path_str) {
                    to_delete.push(path_str.clone());
                }
            }
        }
    }
    if !docs.is_empty() {
        transport.push_docs(docs).await?;
    }
    if !to_delete.is_empty() {
        transport.delete_paths(to_delete).await?;
    }
    Ok(true)
}

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

    #[test]
    fn capability_from_health_fields() {
        use crate::server_client::dto::Health;
        let h = |embedder: Option<&str>, llm: Option<&str>| Health {
            status: "ok".into(),
            reranker: false,
            embedder: embedder.map(str::to_string),
            llm_provider: llm.map(str::to_string),
            auth_required: false,
        };
        assert_eq!(
            ServerCapability::from_health(&h(None, None)),
            ServerCapability::Unconfigured
        );
        assert_eq!(
            // An LLM without an embedder still can't answer — retrieval is dead.
            ServerCapability::from_health(&h(None, Some("gemini"))),
            ServerCapability::Unconfigured
        );
        assert_eq!(
            ServerCapability::from_health(&h(Some("fastembed"), None)),
            ServerCapability::SemanticOnly
        );
        assert_eq!(
            ServerCapability::from_health(&h(Some("fastembed"), Some("gemini"))),
            ServerCapability::Full
        );
    }
    use kimun_core::VaultConfig;
    use std::sync::Mutex;
    use tempfile::TempDir;

    #[derive(Default)]
    struct FakeTransport {
        pushed: Mutex<Vec<WireDoc>>,
        deleted: Mutex<Vec<String>>,
        server: Mutex<HashMap<String, String>>,
        fail_push: Mutex<bool>,
    }

    #[async_trait]
    impl RagTransport for FakeTransport {
        async fn push_docs(&self, docs: Vec<WireDoc>) -> Result<(), RagError> {
            if *self.fail_push.lock().unwrap() {
                return Err(RagError::Protocol("boom".into()));
            }
            self.pushed.lock().unwrap().extend(docs);
            Ok(())
        }
        async fn delete_paths(&self, paths: Vec<String>) -> Result<(), RagError> {
            self.deleted.lock().unwrap().extend(paths);
            Ok(())
        }
        async fn server_hashes(&self) -> Result<HashMap<String, String>, RagError> {
            Ok(self.server.lock().unwrap().clone())
        }
    }

    /// Test-only observer wiring feeding a bare dirty-set, for exercising the
    /// free `drain`/`reconcile` fns directly. Production always goes through
    /// [`RagSync::new`], which additionally keeps the observer handle so its
    /// `Drop` can deregister by identity.
    fn register(vault: &NoteVault) -> Arc<DirtySet> {
        let dirty = Arc::new(DirtySet::default());
        vault.set_index_observer(Arc::new(RagObserver::new(dirty.clone())));
        dirty
    }

    /// A vault root as a `SystemPath`. Built from `kimun_core` rather than the
    /// crate's own test helper: this module must not name anything outside
    /// itself, so it stays extractable as a crate (adr/0042).
    fn sys(path: impl AsRef<std::path::Path>) -> kimun_core::SystemPath {
        kimun_core::SystemPath::try_absolute(path).expect("test path must be absolute")
    }

    async fn vault(dir: &std::path::Path) -> NoteVault {
        let vault = NoteVault::new(VaultConfig::new(sys(dir))).await.unwrap();
        // Fill the freshly-healed index so index_ready() holds — the state the
        // drain/reconcile gates require (mirrors the app's validate_and_init).
        vault.validate_and_init().await.unwrap();
        vault
    }

    #[tokio::test]
    async fn drain_pushes_created_note_and_deletes_removed() {
        let dir = TempDir::new().unwrap();
        let vault = vault(dir.path()).await;
        let dirty = register(&vault);
        let transport = FakeTransport::default();

        vault
            .create_note(&VaultPath::new("a.md"), "# Title\n\nbody")
            .await
            .unwrap();
        drain(&vault, &dirty, &transport).await.unwrap();

        // Block-scoped: clippy's await_holding_lock tracks lexical scope, so an
        // explicit drop() before the awaits below wouldn't silence it.
        {
            let pushed = transport.pushed.lock().unwrap();
            assert_eq!(pushed.len(), 1);
            assert_eq!(pushed[0].path, "/a.md"); // canonical
            assert!(!pushed[0].sections.is_empty());
            assert!(dirty.is_empty());
        }

        vault.delete_note(&VaultPath::new("a.md")).await.unwrap();
        drain(&vault, &dirty, &transport).await.unwrap();
        assert_eq!(
            *transport.deleted.lock().unwrap(),
            vec!["/a.md".to_string()]
        );
    }

    #[tokio::test]
    async fn failed_push_requeues() {
        let dir = TempDir::new().unwrap();
        let vault = vault(dir.path()).await;
        let dirty = register(&vault);
        let transport = FakeTransport::default();
        *transport.fail_push.lock().unwrap() = true;

        vault
            .create_note(&VaultPath::new("a.md"), "body")
            .await
            .unwrap();
        assert!(drain(&vault, &dirty, &transport).await.is_err());
        // The op survived for a later retry.
        assert_eq!(dirty.len(), 1);
    }

    #[tokio::test]
    async fn reconcile_pushes_missing_and_deletes_stale() {
        let dir = TempDir::new().unwrap();
        let vault = vault(dir.path()).await;
        let _dirty = register(&vault);
        let transport = FakeTransport::default();

        vault
            .create_note(&VaultPath::new("keep.md"), "kept")
            .await
            .unwrap();
        // Server already has a stale note the vault no longer contains.
        transport
            .server
            .lock()
            .unwrap()
            .insert("/gone.md".to_string(), "oldhash".to_string());

        assert!(reconcile(&vault, &transport).await.unwrap());

        let pushed = transport.pushed.lock().unwrap();
        assert!(pushed.iter().any(|d| d.path == "/keep.md"));
        assert_eq!(
            *transport.deleted.lock().unwrap(),
            vec!["/gone.md".to_string()]
        );
    }

    #[tokio::test]
    async fn reconcile_skipped_while_index_not_ready() {
        let dir = TempDir::new().unwrap();
        // No validate_and_init: the fresh index is healed-but-empty, exactly
        // the state where a reconcile would read "no local notes" and delete
        // the whole server collection.
        let vault = NoteVault::new(VaultConfig::new(sys(dir.path())))
            .await
            .unwrap();
        assert!(!vault.index_ready());
        let transport = FakeTransport::default();
        transport
            .server
            .lock()
            .unwrap()
            .insert("/precious.md".to_string(), "hash".to_string());

        assert!(!reconcile(&vault, &transport).await.unwrap());
        assert!(transport.deleted.lock().unwrap().is_empty());
        assert!(transport.pushed.lock().unwrap().is_empty());

        // Drain likewise holds queued ops instead of misreading the empty
        // index (an upsert would otherwise become a server-side delete),
        // and reports the skip so callers don't claim the vault is synced.
        let dirty = register(&vault);
        dirty.record(&kimun_core::NoteChange::Upsert {
            path: VaultPath::new("precious.md"),
            hash: 1,
        });
        assert!(!drain(&vault, &dirty, &transport).await.unwrap());
        assert_eq!(dirty.len(), 1);
        assert!(transport.deleted.lock().unwrap().is_empty());
    }
}