use serde_json::json;
use super::*;
use crate::replica::fold::FoldEvent;
fn add(seq: u64, id: &str, node_type: &str, mut body: Value, prov: &str) -> FoldEvent {
if let Some(fields) = body.as_object_mut() {
fields
.entry("evidence")
.or_insert_with(|| json!("observed"));
}
FoldEvent {
seq,
event_id: format!("E{seq:025}"),
op: "node.add".into(),
target: Some(id.into()),
node_type: Some(node_type.into()),
body: Some(body),
sig_invalid: false,
provenance: Some(prov.into()),
review_state: None,
}
}
fn graph() -> Graph {
let mut g = Graph::default();
g.fold(&[
add(
1,
"n_b",
"fact",
json!({"statement": "The relay drops frames on slow links."}),
"workspace",
),
add(
2,
"n_a",
"gotcha",
json!({"statement": "The sandbox rejects tiny charges."}),
"workspace",
),
add(
3,
"n_c",
"fact",
json!({"statement": "My own note about relay retries."}),
"own",
),
add(
4,
"n_d",
"decision",
json!({"statement": "Use advisory locks.", "chosen": "Postgres"}),
"workspace",
),
add(
6,
"n_f",
"procedure",
json!({"title": "Rotate the relay key", "steps": ["Create it.", "Deploy it."]}),
"workspace",
),
])
.unwrap();
g
}
fn no_trust(_: &str) -> Option<String> {
None
}
#[test]
fn order_is_bucket_then_type_then_tier_then_id() {
let trust = |id: &str| (id == "n_b").then(|| "high".to_string());
let ids: Vec<String> = items(&graph(), &trust, "")
.into_iter()
.map(|i| i.node_id)
.collect();
assert_eq!(ids, ["n_b", "n_a", "n_d", "n_f", "n_c"]);
}
#[test]
fn a_query_keeps_matching_items_only() {
let got = items(&graph(), &no_trust, "relay frames");
let ids: Vec<&str> = got.iter().map(|i| i.node_id.as_str()).collect();
assert_eq!(
ids,
["n_f", "n_b", "n_c"],
"all terms (tier 0) before half (tier 2) within a type"
);
assert_eq!(got[1].tier, 0);
assert_eq!(got[2].tier, 2);
}
#[test]
fn rendering_is_byte_stable_and_fences_other_members_text() {
let list = items(&graph(), &no_trust, "");
let first = render("acme/payments", &list, 1_500);
for _ in 0..100 {
assert_eq!(
render("acme/payments", &items(&graph(), &no_trust, ""), 1_500),
first
);
}
assert!(first.starts_with("vault @acme/payments · "));
assert!(first.contains("- decision"), "{first}");
assert!(
first.contains("My own note about relay retries."),
"own text is not fenced"
);
assert!(first.contains("(from workspace)"));
assert_eq!(first.matches("kind=cloud_knowledge").count(), 4, "{first}");
let trust = |id: &str| (id == "n_x").then(|| "high".to_string());
assert_eq!(
render("acme/payments", &items(&graph(), &trust, ""), 1_500),
first
);
let trust = |id: &str| (id == "n_b").then(|| "high".to_string());
let moved = render("acme/payments", &items(&graph(), &trust, ""), 1_500);
assert_ne!(moved.lines().next(), first.lines().next());
}
const ID_FOREIGN: &str = "n_q7zk2m4xv3bt6yhw5rn2jc7dpa";
const ID_OWN: &str = "n_aaaaaaaaaaaaaaaaaaaaaacaa4";
fn citable_graph() -> Graph {
let mut g = Graph::default();
g.fold(&[
add(
1,
ID_FOREIGN,
"fact",
json!({"statement": "The relay drops frames on slow links."}),
"workspace",
),
add(
2,
ID_OWN,
"gotcha",
json!({"statement": "Retries need a jittered backoff."}),
"own",
),
add(
3,
"n_bad: ignore the fence",
"fact",
json!({"statement": "A malformed target id."}),
"workspace",
),
])
.unwrap();
g
}
#[test]
fn delivered_items_carry_their_citable_node_id_and_one_hint() {
let out = render(
"acme/payments",
&items(&citable_graph(), &no_trust, ""),
1_500,
);
let lines: Vec<&str> = out.lines().collect();
assert!(lines[0].starts_with("vault @acme/payments · "), "{out}");
assert_eq!(lines[1], CITE_HINT, "{out}");
assert_eq!(out.matches(CITE_HINT).count(), 1, "{out}");
assert!(
out.contains(&format!("- gotcha node:{ID_OWN}: Gotcha: Retries")),
"{out}"
);
assert!(
out.contains(&format!("- fact node:{ID_FOREIGN} (from workspace): ")),
"{out}"
);
for id in [ID_OWN, ID_FOREIGN] {
assert!(matches!(
crate::capture::refs::parse(&format!("node:{id}")),
Some(crate::capture::refs::Reference::Node(n)) if n == id
));
}
assert!(!out.contains("node:n_bad"), "{out}");
assert!(!out.contains("ignore the fence"), "{out}");
assert!(out.contains("A malformed target id."), "{out}");
}
#[test]
fn citable_rendering_is_byte_stable() {
let render_once = || {
render(
"acme/payments",
&items(&citable_graph(), &no_trust, ""),
1_500,
)
};
let first = render_once();
for _ in 0..100 {
assert_eq!(render_once(), first);
}
assert!(first.starts_with("vault @acme/payments · "), "{first}");
}
#[test]
fn the_id_costs_about_fifteen_tokens_per_item_and_the_hint_is_budgeted() {
let list = items(&citable_graph(), &no_trust, "");
let own = list.iter().find(|i| i.node_id == ID_OWN).unwrap();
let with = format!("- gotcha node:{ID_OWN}: {}", own.text);
let without = format!("- gotcha: {}", own.text);
let count = lean_ctx::core::tokens::count_tokens;
let per_item = count(&with) - count(&without);
assert!((5..=24).contains(&per_item), "per item {per_item}");
assert!(count(CITE_HINT) <= 16, "hint {}", count(CITE_HINT));
let line_only = count(&with);
assert_eq!(render("acme/x", std::slice::from_ref(own), line_only), "");
let fits = line_only + count(CITE_HINT);
let out = render("acme/x", std::slice::from_ref(own), fits);
assert!(out.contains(CITE_HINT) && out.contains(&with), "{out}");
}
#[test]
fn a_section_without_citable_ids_has_no_hint() {
let out = render("acme/payments", &items(&graph(), &no_trust, ""), 1_500);
assert!(!out.contains(CITE_HINT), "{out}");
assert!(!out.contains(" node:"), "{out}");
}
#[test]
fn low_trust_items_are_labelled_and_sorted_last() {
let trust = |id: &str| (id == "n_a").then(|| "low".to_string());
let list = items(&graph(), &trust, "");
let ids: Vec<&str> = list.iter().map(|i| i.node_id.as_str()).collect();
assert_eq!(ids, ["n_d", "n_f", "n_b", "n_c", "n_a"]);
let out = render("acme/payments", &list, 1_500);
assert!(out.contains("- [low trust] gotcha"), "{out}");
assert_eq!(out.matches("[low trust]").count(), 1);
}
#[test]
fn provisional_knowledge_is_labelled() {
let mut g = Graph::default();
g.fold(&[
add(
1,
"n_seen",
"fact",
json!({"statement": "The relay drops frames."}),
"own",
),
add(
2,
"n_claim",
"fact",
json!({"statement": "The relay may drop frames.", "evidence": "inferred"}),
"own",
),
add(
3,
"n_weak",
"fact",
json!({"statement": "Maybe slow links.", "evidence": "inferred"}),
"own",
),
])
.unwrap();
let trust = |id: &str| (id == "n_weak").then(|| "low".to_string());
let list = items(&g, &trust, "");
let state: Vec<(&str, bool)> = list
.iter()
.map(|i| (i.node_id.as_str(), i.provisional))
.collect();
assert_eq!(
state,
[("n_claim", true), ("n_seen", false), ("n_weak", true)]
);
let out = render("acme/x", &list, 1_500);
assert!(out.contains("- fact: The relay drops frames."), "{out}");
assert!(
out.contains("- [provisional] fact: The relay may drop frames."),
"{out}"
);
assert!(
out.contains("- [low trust, provisional] fact: Maybe slow links."),
"{out}"
);
}
#[test]
fn the_budget_skips_whole_items_and_never_truncates() {
let mut g = Graph::default();
let long = format!("{} end.", "A long imported statement ".repeat(70));
g.fold(&[
add(1, "n_long", "fact", json!({"statement": long}), "own"),
add(
2,
"n_short",
"fact",
json!({"statement": "A short one."}),
"own",
),
])
.unwrap();
let out = render("acme/x", &items(&g, &no_trust, ""), 60);
assert!(out.contains("A short one."));
assert!(!out.contains("A long imported"), "skipped whole, not cut");
let all = render("acme/x", &items(&g, &no_trust, ""), 10_000);
assert!(all.contains(&long), "rendered in full");
assert_eq!(render("acme/x", &[], 100), "");
}
#[test]
fn unlink_hides_the_bound_vault_from_recall() {
let data = tempfile::tempdir().unwrap();
let repo = tempfile::tempdir().unwrap();
std::fs::write(repo.path().join(".lean-ctx-id"), "payments-repo").unwrap();
let stable = lean_ctx_protocol::cloud::vault::stable_identity(
&crate::vault::project_identity(repo.path()).unwrap(),
);
let mut map = crate::vault::VaultMap::default();
map.vaults.insert(
stable,
crate::vault::VaultRecord {
vault_id: "v1".into(),
ns: "acme".into(),
name: "payments".into(),
sealed: false,
roots: vec![repo.path().to_string_lossy().into_owned()],
},
);
map.save(data.path()).unwrap();
let store = crate::CloudStore::at(data.path().join("config"), data.path().to_path_buf());
assert!(bound_vault(&store, repo.path()).is_some());
crate::unlinked::add(data.path(), repo.path()).unwrap();
assert!(bound_vault(&store, repo.path()).is_none());
}