tftio-kb 2.5.3

Personal knowledge base — typed AST with org-mode as projection, SQLite-backed
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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
//! `kb prompt` — MiniJinja template runner over the local kb corpus.
//!
//! kb assembles; the user executes. This module:
//!
//! - Resolves template names against the user override directory
//!   (`$XDG_CONFIG_HOME/kb/prompts/<name>.j2`, `$HOME/.config` fallback)
//!   and the built-in templates embedded under `crates/kb/templates/`.
//! - Exposes a documented query surface to MiniJinja contexts —
//!   `recent`, `orphans`, `hubs`, `tag_frequency` as eagerly-computed
//!   values plus `by_tag`, `search`, `all_nodes`, `get`,
//!   `link_distance`, `links` as callable functions.
//! - Renders templates in MiniJinja's sandboxed
//!   [`UndefinedBehavior::Strict`] mode and returns the rendered string.
//!
//! Per-node values carry a summary projection (`node.body`) defined as
//! title + the first paragraph's plain text, capped at
//! [`SUMMARY_BODY_CHAR_BUDGET`] characters. The full body remains
//! available via `node.body_full` for templates that explicitly opt in.

use std::collections::{BTreeMap, HashSet, VecDeque};
use std::path::PathBuf;

use minijinja::value::Value;
use minijinja::{Environment, Error as JinjaError, ErrorKind, UndefinedBehavior};
use rusqlite::Connection;
use serde::Serialize;
use thiserror::Error;

use crate::ast::{Block, Document, Inline};
use crate::sexp::SexpError;
use crate::storage;

/// Failure modes of template resolution and rendering.
#[derive(Debug, Error)]
pub enum PromptError {
    /// No template with the requested name exists (neither a user
    /// override nor a built-in).
    #[error("no template named {0}")]
    TemplateNotFound(String),

    /// A user-override template file could not be read.
    #[error("failed to read user template {path}: {source}")]
    ReadTemplate {
        /// Path of the template file that failed to read.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },

    /// A database query backing the template context failed.
    #[error("query layer failed: {0}")]
    Sql(#[from] rusqlite::Error),

    /// A stored AST blob failed to decode while building the context.
    #[error("corrupt stored document: {0}")]
    Decode(#[from] SexpError),

    /// MiniJinja failed to parse, load, or render the template.
    #[error("template error: {0}")]
    Render(#[from] JinjaError),
}

/// Character budget for the summary projection (`node.body`). A
/// conservative window so contexts stay short by default. Templates
/// that want more reach for `node.body_full`.
pub const SUMMARY_BODY_CHAR_BUDGET: usize = 500;

/// Default cap on the number of "recent" nodes eagerly bound into the
/// template context.
pub const DEFAULT_RECENT_LIMIT: usize = 50;

/// Default cap on the number of hubs eagerly bound into the context.
pub const DEFAULT_HUBS_LIMIT: usize = 20;

/// Built-in templates embedded at compile time.
///
/// Each entry is `(name, body)` where `name` is the bare template name
/// (no extension). The user-override layer in
/// [`resolve_template_source`] takes precedence over this list.
const BUILTIN_TEMPLATES: &[(&str, &str)] = &[(
    "cold-start-audit",
    include_str!("../templates/cold-start-audit.j2"),
)];

/// File extension used for templates on disk.
const TEMPLATE_EXT: &str = "j2";

// ── Public entry points ────────────────────────────────────────────────

/// A summary record describing one available template — built-in or
/// user-supplied. Used by `kb prompt list`.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct TemplateSummary {
    /// Bare template name (no extension).
    pub name: String,
    /// `"builtin"` when the template ships embedded with the crate;
    /// `"user"` when resolved from the override directory.
    pub source: String,
    /// Absolute path on disk when `source = "user"`; `None` for
    /// built-ins.
    pub path: Option<PathBuf>,
}

/// List every template available to `kb prompt`, merging built-ins with
/// user-override files. User overrides win on name collision and
/// `source` then reports `"user"`.
#[must_use]
pub fn list_templates() -> Vec<TemplateSummary> {
    list_templates_in(user_template_dir().as_deref())
}

/// `list_templates`, parameterized over the override directory. Passing
/// `None` means "no user overrides considered" — only built-ins are
/// returned. Tests use this directly with a tempdir to avoid mutating
/// process-global env.
#[must_use]
fn list_templates_in(override_dir: Option<&std::path::Path>) -> Vec<TemplateSummary> {
    let mut by_name: BTreeMap<String, TemplateSummary> = BTreeMap::new();
    for (name, _) in BUILTIN_TEMPLATES {
        by_name.insert(
            (*name).to_string(),
            TemplateSummary {
                name: (*name).to_string(),
                source: "builtin".to_string(),
                path: None,
            },
        );
    }
    if let Some(dir) = override_dir {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|s| s.to_str()) != Some(TEMPLATE_EXT) {
                    continue;
                }
                let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
                    continue;
                };
                by_name.insert(
                    stem.to_string(),
                    TemplateSummary {
                        name: stem.to_string(),
                        source: "user".to_string(),
                        path: Some(path),
                    },
                );
            }
        }
    }
    by_name.into_values().collect()
}

/// Resolved template source: the raw text plus where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTemplate {
    pub name: String,
    pub source: String,
    pub path: Option<PathBuf>,
    pub body: String,
}

/// Resolve a template by name: user override wins, then built-in.
///
/// # Errors
///
/// Returns [`PromptError::TemplateNotFound`] if no template with that
/// name exists, or [`PromptError::ReadTemplate`] if a matching user
/// override file cannot be read.
pub fn resolve_template_source(name: &str) -> Result<ResolvedTemplate, PromptError> {
    resolve_template_source_in(name, user_template_dir().as_deref())
}

/// `resolve_template_source`, parameterized over the override directory.
/// Passing `None` means "no user overrides considered" — only built-ins
/// are searched. Tests use this directly with a tempdir to avoid
/// mutating process-global env.
fn resolve_template_source_in(
    name: &str,
    override_dir: Option<&std::path::Path>,
) -> Result<ResolvedTemplate, PromptError> {
    if let Some(dir) = override_dir {
        let path = dir.join(format!("{name}.{TEMPLATE_EXT}"));
        if path.is_file() {
            let body =
                std::fs::read_to_string(&path).map_err(|source| PromptError::ReadTemplate {
                    path: path.clone(),
                    source,
                })?;
            return Ok(ResolvedTemplate {
                name: name.to_string(),
                source: "user".to_string(),
                path: Some(path),
                body,
            });
        }
    }
    for (n, body) in BUILTIN_TEMPLATES {
        if *n == name {
            return Ok(ResolvedTemplate {
                name: name.to_string(),
                source: "builtin".to_string(),
                path: None,
                body: (*body).to_string(),
            });
        }
    }
    Err(PromptError::TemplateNotFound(name.to_string()))
}

/// Render the named template against the live kb corpus.
///
/// # Errors
///
/// Returns [`PromptError`] when the template cannot be resolved, a stored
/// document fails to decode, the SQL query layer fails, or MiniJinja
/// reports a parse/load/render error.
pub fn render_prompt(conn: &Connection, name: &str) -> Result<String, PromptError> {
    let resolved = resolve_template_source(name)?;
    let context = build_context(conn)?;
    let mut env = build_env();
    env.add_template_owned(resolved.name.clone(), resolved.body.clone())?;
    let tmpl = env.get_template(&resolved.name)?;
    Ok(tmpl.render(context)?)
}

// ── User override directory ────────────────────────────────────────────

/// `$XDG_CONFIG_HOME/kb/prompts` (with `$HOME/.config/kb/prompts`
/// fallback). Returns `None` if neither variable is set.
#[must_use]
#[allow(
    clippy::disallowed_methods,
    reason = "XDG_CONFIG_HOME/HOME locate the optional user template override dir; sanctioned bootstrap locators (REPO_INVARIANTS.md #5b)"
)]
pub fn user_template_dir() -> Option<PathBuf> {
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
        if !xdg.is_empty() {
            return Some(PathBuf::from(xdg).join("kb").join("prompts"));
        }
    }
    if let Ok(home) = std::env::var("HOME") {
        if !home.is_empty() {
            return Some(
                PathBuf::from(home)
                    .join(".config")
                    .join("kb")
                    .join("prompts"),
            );
        }
    }
    dirs::config_dir().map(|d| d.join("kb").join("prompts"))
}

// ── MiniJinja environment ──────────────────────────────────────────────

fn build_env() -> Environment<'static> {
    let mut env = Environment::new();
    env.set_undefined_behavior(UndefinedBehavior::Strict);
    env
}

// ── Context construction ───────────────────────────────────────────────

/// The eagerly-bound corpus snapshot exposed as the template context.
///
/// Function bindings (`by_tag`, `search`, `all_nodes`, `get`,
/// `link_distance`, `links`) are attached as callables so a template
/// can pull additional node sets at render time without paying for them
/// when unused.
fn build_context(conn: &Connection) -> Result<Value, PromptError> {
    let recent_rows = storage::list_recent(conn, DEFAULT_RECENT_LIMIT)?;
    let orphan_rows = storage::list_orphans(conn)?;
    let hub_rows = storage::list_hubs(conn, DEFAULT_HUBS_LIMIT)?;
    let tag_freq = tag_frequency(conn)?;

    let recent: Vec<Value> = recent_rows
        .iter()
        .map(node_value_from_row)
        .collect::<Result<_, _>>()?;
    let orphans: Vec<Value> = orphan_rows
        .iter()
        .map(node_value_from_row)
        .collect::<Result<_, _>>()?;
    let hubs: Vec<Value> = hub_rows
        .iter()
        .map(|h| {
            Value::from_serialize(serde_json::json!({
                "id": h.id,
                "title": h.title,
                "in_degree": h.in_degree,
            }))
        })
        .collect();
    let tag_frequency_val: Vec<Value> = tag_freq
        .iter()
        .map(|(tag, count)| {
            Value::from_serialize(serde_json::json!({
                "tag": tag,
                "count": count,
            }))
        })
        .collect();

    let db_path = db_path_of(conn);
    let by_tag = make_by_tag(db_path.clone());
    let search_fn = make_search(db_path.clone());
    let all_fn = make_all_nodes(db_path.clone());
    let get_fn = make_get(db_path.clone());
    let links_fn = make_links(db_path.clone());
    let link_distance_fn = make_link_distance(db_path);

    let mut ctx: BTreeMap<&'static str, Value> = BTreeMap::new();
    ctx.insert("recent", Value::from(recent));
    ctx.insert("orphans", Value::from(orphans));
    ctx.insert("hubs", Value::from(hubs));
    ctx.insert("tag_frequency", Value::from(tag_frequency_val));
    ctx.insert("by_tag", by_tag);
    ctx.insert("search", search_fn);
    ctx.insert("all_nodes", all_fn);
    ctx.insert("get", get_fn);
    ctx.insert("links", links_fn);
    ctx.insert("link_distance", link_distance_fn);

    Ok(Value::from_serialize(&ctx))
}

/// Best-effort recovery of the underlying SQLite path so the template
/// callbacks can reopen their own connections. MiniJinja callables run
/// in `'static` closures, which precludes borrowing the original
/// connection.
fn db_path_of(conn: &Connection) -> String {
    conn.path().map_or_else(String::new, |p| p.to_string())
}

// ── Node projection ────────────────────────────────────────────────────

/// Project one [`storage::NodeRow`] into the MiniJinja value shape:
/// `{id, title, tags, body, body_full, created_at, updated_at}`.
///
/// `row.ast_blob` is external DB state, so a corrupt blob is a runtime
/// failure rather than a provable invariant — it is surfaced as
/// [`PromptError::Decode`] instead of panicking.
fn node_value_from_row(row: &storage::NodeRow) -> Result<Value, PromptError> {
    let doc = crate::sexp::decode_document(&row.ast_blob)?;
    let body_full = first_paragraph_or_all(&doc, usize::MAX);
    let body = summary_body(row.title.as_str(), &doc);
    let tags = collect_tag_names(&doc);
    Ok(Value::from_serialize(serde_json::json!({
        "id": row.id,
        "title": row.title,
        "tags": tags,
        "body": body,
        "body_full": body_full,
        "created_at": row.created_at,
        "updated_at": row.updated_at,
    })))
}

fn collect_tag_names(doc: &Document) -> Vec<String> {
    storage::extract_tags(doc)
        .into_iter()
        .map(|t| t.0)
        .collect()
}

/// Summary projection: title + first paragraph's plain text, capped at
/// [`SUMMARY_BODY_CHAR_BUDGET`] characters. Heuristic chosen for
/// context-window discipline — see crate-level docs.
pub fn summary_body(title: &str, doc: &Document) -> String {
    let first_para = first_paragraph_text(&doc.blocks).unwrap_or_default();
    let mut out = String::new();
    if !title.trim().is_empty() {
        out.push_str(title);
    }
    if !first_para.trim().is_empty() {
        if !out.is_empty() {
            out.push_str("\n\n");
        }
        out.push_str(&first_para);
    }
    truncate_chars(&out, SUMMARY_BODY_CHAR_BUDGET)
}

fn first_paragraph_or_all(doc: &Document, cap: usize) -> String {
    let text = storage::extract_body_text(doc);
    if cap == usize::MAX {
        text
    } else {
        truncate_chars(&text, cap)
    }
}

fn first_paragraph_text(blocks: &[Block]) -> Option<String> {
    for block in blocks {
        match block {
            Block::Paragraph { inlines } => {
                let text = inline_plain(inlines);
                if !text.trim().is_empty() {
                    return Some(text);
                }
            }
            Block::Heading { children, .. } | Block::QuoteBlock { children } => {
                if let Some(t) = first_paragraph_text(children) {
                    return Some(t);
                }
            }
            _ => {}
        }
    }
    None
}

fn inline_plain(inlines: &[Inline]) -> String {
    let mut out = String::new();
    for inl in inlines {
        match inl {
            Inline::Plain(s) | Inline::InlineCode(s) | Inline::Verbatim(s) => out.push_str(s),
            Inline::Bold(xs) | Inline::Italic(xs) | Inline::Strikethrough(xs) => {
                out.push_str(&inline_plain(xs));
            }
            Inline::LineBreak => out.push('\n'),
            Inline::Link {
                target,
                description,
            } => {
                if let Some(desc) = description {
                    out.push_str(desc);
                } else {
                    out.push_str(target);
                }
            }
        }
    }
    out
}

fn truncate_chars(s: &str, cap: usize) -> String {
    if s.chars().count() <= cap {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(cap).collect();
        format!("{truncated}")
    }
}

// ── Tag frequency ──────────────────────────────────────────────────────

/// Corpus-level tag frequency table: `(tag, count)` pairs sorted by
/// count desc then tag asc.
///
/// # Errors
///
/// Returns `rusqlite::Error` on database failure.
pub fn tag_frequency(conn: &Connection) -> Result<Vec<(String, i64)>, rusqlite::Error> {
    let mut stmt = conn.prepare(
        "SELECT tag, COUNT(*) AS c FROM node_tags GROUP BY tag ORDER BY c DESC, tag ASC",
    )?;
    let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
    rows.collect()
}

// ── Callable bindings ──────────────────────────────────────────────────

/// Open a fresh connection inside a callable closure. MiniJinja
/// callables are `Send + Sync + 'static` so they cannot borrow the
/// original connection; we trade the open cost for clean lifetimes.
fn open_conn(path: &str) -> Result<Connection, JinjaError> {
    storage::open_db(path).map_err(|e| {
        JinjaError::new(
            ErrorKind::InvalidOperation,
            format!("kb: failed to open db {path}: {e}"),
        )
    })
}

/// Project a node row inside a callable closure, lifting a decode
/// failure into a MiniJinja error so it surfaces at render time.
fn node_value_in_callable(row: &storage::NodeRow) -> Result<Value, JinjaError> {
    node_value_from_row(row)
        .map_err(|e| JinjaError::new(ErrorKind::InvalidOperation, e.to_string()))
}

/// Project a slice of node rows inside a callable closure.
fn node_values_in_callable(rows: &[storage::NodeRow]) -> Result<Vec<Value>, JinjaError> {
    rows.iter().map(node_value_in_callable).collect()
}

fn make_by_tag(path: String) -> Value {
    Value::from_function(move |tag: &str| -> Result<Value, JinjaError> {
        let conn = open_conn(&path)?;
        let rows = storage::list_by_tag(&conn, tag).map_err(|e| {
            JinjaError::new(ErrorKind::InvalidOperation, format!("by_tag failed: {e}"))
        })?;
        Ok(Value::from(node_values_in_callable(&rows)?))
    })
}

fn make_search(path: String) -> Value {
    Value::from_function(move |query: &str| -> Result<Value, JinjaError> {
        let conn = open_conn(&path)?;
        let ids = storage::search_fts(&conn, query).map_err(|e| {
            JinjaError::new(ErrorKind::InvalidOperation, format!("search failed: {e}"))
        })?;
        let mut out = Vec::with_capacity(ids.len());
        for id in &ids {
            if let Some(row) = storage::get_node_row(&conn, id).map_err(|e| {
                JinjaError::new(ErrorKind::InvalidOperation, format!("search fetch: {e}"))
            })? {
                out.push(node_value_in_callable(&row)?);
            }
        }
        Ok(Value::from(out))
    })
}

fn make_all_nodes(path: String) -> Value {
    Value::from_function(move || -> Result<Value, JinjaError> {
        let conn = open_conn(&path)?;
        // Cap at a generous bound — full enumeration on a personal kb
        // is fine, but unbounded queries on shared kbs should not
        // accidentally OOM the renderer.
        let pairs = storage::list_all_nodes(&conn, 10_000, 0).map_err(|e| {
            JinjaError::new(
                ErrorKind::InvalidOperation,
                format!("all_nodes failed: {e}"),
            )
        })?;
        let mut out = Vec::with_capacity(pairs.len());
        for (id, _title) in &pairs {
            if let Some(row) = storage::get_node_row(&conn, &id.0).map_err(|e| {
                JinjaError::new(ErrorKind::InvalidOperation, format!("all_nodes fetch: {e}"))
            })? {
                out.push(node_value_in_callable(&row)?);
            }
        }
        Ok(Value::from(out))
    })
}

fn make_get(path: String) -> Value {
    Value::from_function(move |id: &str| -> Result<Value, JinjaError> {
        let conn = open_conn(&path)?;
        match storage::get_node_row(&conn, id)
            .map_err(|e| JinjaError::new(ErrorKind::InvalidOperation, format!("get failed: {e}")))?
        {
            Some(row) => node_value_in_callable(&row),
            None => Ok(Value::from(())),
        }
    })
}

fn make_links(path: String) -> Value {
    Value::from_function(move |id: &str| -> Result<Value, JinjaError> {
        let conn = open_conn(&path)?;
        let nb = storage::get_links(&conn, id).map_err(|e| {
            JinjaError::new(ErrorKind::InvalidOperation, format!("links failed: {e}"))
        })?;
        let to_row = |r: &storage::LinkRow| {
            serde_json::json!({
                "source_id": r.source_id,
                "link_type": r.link_type,
                "target_id": r.target_id,
                "target_slug": r.target_slug,
            })
        };
        Ok(Value::from_serialize(serde_json::json!({
            "outgoing": nb.outgoing.iter().map(to_row).collect::<Vec<_>>(),
            "incoming": nb.incoming.iter().map(to_row).collect::<Vec<_>>(),
        })))
    })
}

fn make_link_distance(path: String) -> Value {
    Value::from_function(
        move |id: &str, max_depth: i64| -> Result<Value, JinjaError> {
            let conn = open_conn(&path)?;
            let max = usize::try_from(max_depth.max(0)).unwrap_or(0);
            let ids = bfs_link_distance(&conn, id, max).map_err(|e| {
                JinjaError::new(
                    ErrorKind::InvalidOperation,
                    format!("link_distance failed: {e}"),
                )
            })?;
            let mut out = Vec::with_capacity(ids.len());
            for nid in &ids {
                if let Some(row) = storage::get_node_row(&conn, nid).map_err(|e| {
                    JinjaError::new(
                        ErrorKind::InvalidOperation,
                        format!("link_distance fetch: {e}"),
                    )
                })? {
                    out.push(node_value_in_callable(&row)?);
                }
            }
            Ok(Value::from(out))
        },
    )
}

/// Breadth-first walk of the unified link graph from `start` outward up
/// to `max_depth` hops, returning every reachable node id including
/// `start`.
fn bfs_link_distance(
    conn: &Connection,
    start: &str,
    max_depth: usize,
) -> Result<Vec<String>, rusqlite::Error> {
    let mut visited: HashSet<String> = HashSet::new();
    let mut queue: VecDeque<(String, usize)> = VecDeque::new();
    let mut order: Vec<String> = Vec::new();
    queue.push_back((start.to_string(), 0));
    visited.insert(start.to_string());
    while let Some((node, depth)) = queue.pop_front() {
        order.push(node.clone());
        if depth >= max_depth {
            continue;
        }
        let nb = storage::get_links(conn, &node)?;
        for row in nb.outgoing.iter().chain(nb.incoming.iter()) {
            let candidates = [row.target_id.as_ref(), Some(&row.source_id)];
            for c in candidates.into_iter().flatten() {
                if c == &node {
                    continue;
                }
                if visited.insert(c.clone()) {
                    queue.push_back((c.clone(), depth + 1));
                }
            }
        }
    }
    Ok(order)
}

// ── Tests ──────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser;
    use minijinja::value::ValueKind;

    fn setup_db() -> Connection {
        let conn = storage::open_db(":memory:").expect("open db");
        storage::init_db(&conn).expect("init db");
        conn
    }

    fn insert(conn: &Connection, id: &str, body: &str) {
        let doc = parser::parse_document(body).expect("parse");
        storage::insert_node(conn, id, &doc).expect("insert");
    }

    /// Anchors criterion 09fa365d: the cold-start-audit template ships
    /// embedded with the crate.
    #[test]
    fn cold_start_audit_template_ships() {
        let resolved =
            resolve_template_source("cold-start-audit").expect("cold-start-audit template missing");
        assert_eq!(resolved.source, "builtin");
        assert!(resolved.path.is_none());
        assert!(
            resolved.body.contains("Cold-Start Audit"),
            "template body should contain its title heading: {}",
            resolved.body
        );
        let summary = list_templates();
        assert!(
            summary.iter().any(|t| t.name == "cold-start-audit"),
            "list_templates must include cold-start-audit: {summary:?}"
        );
    }

    /// Anchors criterion ed2ea536: rendering produces text that
    /// references the corpus.
    #[test]
    fn prompt_renders_to_stdout() {
        let conn = setup_db();
        insert(
            &conn,
            "n1",
            "#+title: Hello World\n* heading\n\nA short paragraph here.\n",
        );
        insert(&conn, "n2", "* Another\n\nMore text.\n");
        let out = render_prompt(&conn, "cold-start-audit").expect("render");
        assert!(out.contains("Cold-Start Audit"), "expected heading: {out}");
        assert!(out.contains("Hello World"), "expected n1 title: {out}");
    }

    /// Anchors criterion da830e76: node.body defaults to the summary
    /// projection, capped at SUMMARY_BODY_CHAR_BUDGET, and node.body_full
    /// returns the full text.
    #[test]
    fn summary_projection_default() {
        let long_para: String = "x".repeat(SUMMARY_BODY_CHAR_BUDGET * 3);
        let body = format!("#+title: Big\n\n{long_para}\n");
        let doc = parser::parse_document(&body).expect("parse");
        let summary = summary_body("Big", &doc);
        assert!(
            summary.chars().count() <= SUMMARY_BODY_CHAR_BUDGET + 1,
            "summary should be capped to ~{SUMMARY_BODY_CHAR_BUDGET} chars, got {}",
            summary.chars().count()
        );
        assert!(summary.starts_with("Big"));

        // Render a tiny template that exercises both body and body_full.
        let conn = setup_db();
        storage::insert_node(&conn, "n1", &doc).expect("insert");
        let path = db_path_of(&conn);
        let ctx = build_context(&conn).expect("ctx");
        let mut env = build_env();
        env.add_template(
            "t",
            "{{ recent[0].body }}|{{ recent[0].body_full | length }}",
        )
        .expect("compile");
        let rendered = env.get_template("t").unwrap().render(ctx).expect("render");
        let parts: Vec<&str> = rendered.split('|').collect();
        assert_eq!(parts.len(), 2, "two fields rendered: {rendered}");
        assert!(
            parts[0].chars().count() <= SUMMARY_BODY_CHAR_BUDGET + 1,
            "body summary length: {}",
            parts[0].chars().count()
        );
        let full_len: usize = parts[1].parse().expect("body_full length parses");
        assert!(
            full_len > SUMMARY_BODY_CHAR_BUDGET,
            "body_full must exceed summary cap: {full_len}"
        );
        let _ = path;
    }

    /// Anchors criterion 9820d90d: the documented query surface
    /// (`recent`, `orphans`, `hubs`, `tag_frequency`, `by_tag`,
    /// `search`, `all_nodes`, `get`, `links`, `link_distance`) is
    /// callable from templates and returns sensible shapes.
    #[test]
    fn template_query_surface() {
        // Callables reopen the database by path, so we need a real
        // file rather than an `:memory:` connection.
        let tmp = tempfile::tempdir().expect("tempdir");
        let db_path = tmp.path().join("kb.db");
        let conn = storage::open_db(&db_path.to_string_lossy()).expect("open db");
        storage::init_db(&conn).expect("init db");
        insert(
            &conn,
            "n1",
            "#+title: Alpha\n#+filetags: :rust:\n* h\n\nAlpha body.\n",
        );
        insert(
            &conn,
            "n2",
            "#+title: Beta\n#+filetags: :rust:\n* h\n\nBeta body links to [[id:n1]].\n",
        );
        // Make sure links are populated against the unified table.
        let _ = storage::relink_all(&conn).expect("relink");

        let mut env = build_env();
        let ctx = build_context(&conn).expect("ctx");
        let template = r#"
recent={{ recent | length }}
orphans={{ orphans | length }}
hubs={{ hubs | length }}
tags={{ tag_frequency | length }}
bytag={{ by_tag("rust") | length }}
search={{ search("Alpha") | length }}
all={{ all_nodes() | length }}
get={{ get("n1").title }}
links_out={{ links("n2").outgoing | length }}
distance={{ link_distance("n1", 2) | length }}
"#;
        env.add_template("t", template).expect("compile");
        let out = env.get_template("t").unwrap().render(ctx).expect("render");
        assert!(out.contains("recent=2"), "{out}");
        assert!(out.contains("tags=1"), "{out}");
        assert!(out.contains("bytag=2"), "{out}");
        assert!(out.contains("search=1"), "{out}");
        assert!(out.contains("all=2"), "{out}");
        assert!(out.contains("get=Alpha"), "{out}");
        assert!(
            out.contains("distance=2") || out.contains("distance=1"),
            "{out}"
        );
    }

    /// Anchors criterion bb10df24: user override directory wins over
    /// built-in templates.
    #[test]
    fn user_override_resolution() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let prompts_dir = tmp.path().join("kb").join("prompts");
        std::fs::create_dir_all(&prompts_dir).expect("mkdir");
        let user_path = prompts_dir.join("cold-start-audit.j2");
        std::fs::write(&user_path, "USER OVERRIDE BODY").expect("write");

        let resolved =
            resolve_template_source_in("cold-start-audit", Some(&prompts_dir)).expect("resolve");
        assert_eq!(resolved.source, "user", "user override should win");
        assert_eq!(resolved.body, "USER OVERRIDE BODY");
        assert_eq!(resolved.path.as_deref(), Some(user_path.as_path()));

        let summaries = list_templates_in(Some(&prompts_dir));
        let cs = summaries
            .iter()
            .find(|t| t.name == "cold-start-audit")
            .expect("present");
        assert_eq!(cs.source, "user");

        // And a brand-new user template appears alongside built-ins.
        std::fs::write(prompts_dir.join("custom.j2"), "x").expect("write");
        let summaries2 = list_templates_in(Some(&prompts_dir));
        assert!(
            summaries2
                .iter()
                .any(|t| t.name == "custom" && t.source == "user")
        );

        // With `None`, only built-ins are visible — verifies the
        // parameter is load-bearing, not a no-op.
        let builtins_only = list_templates_in(None);
        assert!(
            builtins_only.iter().all(|t| t.source == "builtin"),
            "no override dir → no user-source rows"
        );
    }

    /// MiniJinja `Value` keeps its shape across the boundary — guard
    /// the public projection contract.
    #[test]
    fn node_value_has_expected_keys() {
        let conn = setup_db();
        insert(&conn, "n1", "#+title: T\n* h\n\nbody.\n");
        let row = storage::get_node_row(&conn, "n1").unwrap().unwrap();
        let v = node_value_from_row(&row).expect("project row");
        assert_eq!(v.kind(), ValueKind::Map);
        for key in [
            "id",
            "title",
            "tags",
            "body",
            "body_full",
            "created_at",
            "updated_at",
        ] {
            assert!(
                v.get_attr(key).is_ok(),
                "missing key {key} in node value: {v:?}"
            );
        }
    }
}