Skip to main content

qualia_client_core/
directory.rs

1//! Personal directory — an **"Active Directory"-like** service for a person's relationships.
2//!
3//! It hosts the **addressbook** (Parties) organised into **categories** (organisational units / groups —
4//! a Party may be in several, like AD groups), and is the home for the **agreements** governing each
5//! relationship. It unifies the two pre-existing stores — directory [`Actor`]s and
6//! chat [`ChatContact`]s — into ONE categorised view joined by pairwise
7//! DID, **without a destructive migration**: it reads both and persists only the additive parts (custom
8//! categories + per-entry category assignments) in their own files under [`app_meta_dir`].
9//!
10//! Agreement links are surfaced per entry from the first-class agreement store ([`crate::agreements`]) —
11//! see `docs/plans/rights-aware-peer-agreement-addressbook.md`. This module is the **P0** foundation of
12//! that plan (the directory that hosts the addressbook); the agreement store is **P1**, and
13//! [`build_view_core`] joins the two by DID so each Party carries the ids of the Agreements governing its
14//! relationship.
15
16use std::collections::BTreeMap;
17use std::fs;
18use std::path::PathBuf;
19
20use serde::{Deserialize, Serialize};
21
22use crate::agreements::Agreement;
23use crate::social_connect::ChatContact;
24use crate::state::{app_meta_dir, Actor};
25
26/// A directory category — an organisational unit / group (AD-style). Built-in ones are always present;
27/// users can add their own.
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
29pub struct DirectoryCategory {
30    pub id: String,
31    pub label: String,
32    /// A grouping/iconography hint (not a hard type).
33    pub kind: String,
34    pub builtin: bool,
35}
36
37/// The built-in categories. `people` is the catch-all every entry falls into.
38pub fn builtin_categories() -> Vec<DirectoryCategory> {
39    let mk = |id: &str, label: &str, kind: &str| DirectoryCategory {
40        id: id.into(),
41        label: label.into(),
42        kind: kind.into(),
43        builtin: true,
44    };
45    vec![
46        mk("people", "People", "people"),
47        mk("health", "Health practitioners", "health"),
48        mk("cooperative", "Cooperative", "cooperative"),
49        mk("organizations", "Organizations", "organization"),
50        mk("agents", "Agents", "agent"),
51        mk("family-friends", "Family & friends", "personal"),
52    ]
53}
54
55/// One unified addressbook entry (a Party), joined across the directory-actor + chat-contact stores by DID.
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
57pub struct DirectoryEntry {
58    /// Pairwise DID — the join key and the party's identifier.
59    pub did: String,
60    pub display_name: String,
61    /// actor_type / roles / contact tags — descriptive labels, not a hard type.
62    pub kinds: Vec<String>,
63    pub organization: Option<String>,
64    pub verification_status: String,
65    pub front_door_did: Option<String>,
66    /// Which store(s) this entry was found in ("directory-actor", "contact").
67    pub sources: Vec<String>,
68    /// Category ids this entry belongs to (an entry may be in several).
69    pub categories: Vec<String>,
70    /// Agreements governing this relationship (ids). Empty until the agreement store lands (plan P1).
71    pub agreement_ids: Vec<String>,
72    /// Who-kind for humans-first listing: `human` | `organization` | `tool`.
73    /// Organization = legal person / persona ficta. Tool = agent/bot. Never collapse those into "human".
74    #[serde(default)]
75    pub who_kind: String,
76    /// Optional Nym mixnet address for decentralized mixnet routing.
77    #[serde(default)]
78    pub nym_address: Option<String>,
79}
80
81/// The whole categorised directory returned to the UI.
82#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
83pub struct DirectoryView {
84    pub categories: Vec<DirectoryCategory>,
85    pub entries: Vec<DirectoryEntry>,
86}
87
88fn categories_path() -> PathBuf {
89    app_meta_dir().join("directory_categories.json")
90}
91fn assignments_path() -> PathBuf {
92    app_meta_dir().join("directory_assignments.json")
93}
94
95fn load_custom_categories() -> Vec<DirectoryCategory> {
96    fs::read_to_string(categories_path())
97        .ok()
98        .and_then(|t| serde_json::from_str(&t).ok())
99        .unwrap_or_default()
100}
101
102fn save_custom_categories(cats: &[DirectoryCategory]) -> Result<(), String> {
103    let path = categories_path();
104    if let Some(p) = path.parent() {
105        fs::create_dir_all(p).map_err(|e| e.to_string())?;
106    }
107    let text = serde_json::to_string_pretty(cats).map_err(|e| e.to_string())?;
108    fs::write(path, text).map_err(|e| e.to_string())
109}
110
111fn load_assignments() -> BTreeMap<String, Vec<String>> {
112    fs::read_to_string(assignments_path())
113        .ok()
114        .and_then(|t| serde_json::from_str(&t).ok())
115        .unwrap_or_default()
116}
117
118fn save_assignments(a: &BTreeMap<String, Vec<String>>) -> Result<(), String> {
119    let path = assignments_path();
120    if let Some(p) = path.parent() {
121        fs::create_dir_all(p).map_err(|e| e.to_string())?;
122    }
123    let text = serde_json::to_string_pretty(a).map_err(|e| e.to_string())?;
124    fs::write(path, text).map_err(|e| e.to_string())
125}
126
127/// All categories: built-in + user-created.
128pub fn list_categories() -> Vec<DirectoryCategory> {
129    let mut cats = builtin_categories();
130    for c in load_custom_categories() {
131        if !cats.iter().any(|e| e.id == c.id) {
132            cats.push(c);
133        }
134    }
135    cats
136}
137
138fn slugify(s: &str) -> String {
139    s.chars()
140        .map(|c| {
141            if c.is_ascii_alphanumeric() {
142                c.to_ascii_lowercase()
143            } else {
144                '-'
145            }
146        })
147        .collect::<String>()
148        .split('-')
149        .filter(|x| !x.is_empty())
150        .collect::<Vec<_>>()
151        .join("-")
152}
153
154/// Create a custom category. Idempotent by slug; errors if the slug already exists.
155pub fn create_category(label: &str) -> Result<DirectoryCategory, String> {
156    let label = label.trim();
157    if label.is_empty() {
158        return Err("category label is empty".into());
159    }
160    let id = slugify(label);
161    if id.is_empty() {
162        return Err("category label has no usable characters".into());
163    }
164    if list_categories().iter().any(|c| c.id == id) {
165        return Err(format!("a category '{label}' already exists"));
166    }
167    let cat = DirectoryCategory {
168        id,
169        label: label.to_string(),
170        kind: "custom".into(),
171        builtin: false,
172    };
173    let mut custom = load_custom_categories();
174    custom.push(cat.clone());
175    save_custom_categories(&custom)?;
176    Ok(cat)
177}
178
179/// Set the categories an entry (by DID) belongs to. Unknown category ids are dropped; an empty set clears
180/// the explicit assignment (the entry falls back to inferred categories).
181pub fn set_entry_categories(did: &str, categories: Vec<String>) -> Result<(), String> {
182    let valid: std::collections::HashSet<String> =
183        list_categories().into_iter().map(|c| c.id).collect();
184    let cleaned: Vec<String> = categories
185        .into_iter()
186        .map(|c| c.trim().to_string())
187        .filter(|c| valid.contains(c))
188        .collect();
189    let mut a = load_assignments();
190    if cleaned.is_empty() {
191        a.remove(did);
192    } else {
193        a.insert(did.to_string(), cleaned);
194    }
195    save_assignments(&a)
196}
197
198/// Who-kind of a directory entry. Chrome must say **human**, not law's "person",
199/// for living beings; orgs are Organization (legal person); chatbots are tools.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201pub enum WhoKind {
202    Human,
203    Organization,
204    Tool,
205}
206
207impl WhoKind {
208    /// `str` form.
209    pub fn as_str(self) -> &'static str {
210        match self {
211            Self::Human => "human",
212            Self::Organization => "organization",
213            Self::Tool => "tool",
214        }
215    }
216
217    /// Chrome label — never call a company or bot "a person".
218    pub fn chrome_label(self) -> &'static str {
219        match self {
220            Self::Human => "Human",
221            Self::Organization => "Organization · legal person",
222            Self::Tool => "Tool",
223        }
224    }
225
226    /// Directory sort rank.
227    pub fn sort_rank(self) -> u8 {
228        match self {
229            Self::Human => 0,
230            Self::Organization => 1,
231            Self::Tool => 2,
232        }
233    }
234}
235
236fn kind_tokens(kinds: &[String]) -> Vec<String> {
237    kinds
238        .iter()
239        .flat_map(|k| {
240            k.split(|c: char| !c.is_ascii_alphanumeric())
241                .map(|s| s.to_ascii_lowercase())
242                .filter(|s| !s.is_empty())
243                .collect::<Vec<_>>()
244        })
245        .collect()
246}
247
248/// Classify who-kind from actor/contact labels. Affiliation (`organization` field
249/// on a human practitioner) does not by itself make the entry an Organization.
250pub fn classify_who_kind(kinds: &[String], organization: &Option<String>) -> WhoKind {
251    let tokens = kind_tokens(kinds);
252    let has_tok = |needles: &[&str]| tokens.iter().any(|t| needles.iter().any(|n| t == n));
253    if has_tok(&[
254        "agent",
255        "ai",
256        "bot",
257        "assistant",
258        "subagent",
259        "chatbot",
260        "llm",
261    ]) {
262        return WhoKind::Tool;
263    }
264    if has_tok(&[
265        "organization",
266        "organisation",
267        "org",
268        "company",
269        "institution",
270        "business",
271        "ngo",
272    ]) {
273        return WhoKind::Organization;
274    }
275    if kinds.is_empty() && organization.is_some() {
276        return WhoKind::Organization;
277    }
278    WhoKind::Human
279}
280
281/// Parses who-kind.
282pub fn parse_who_kind(raw: &str) -> WhoKind {
283    match raw.trim().to_ascii_lowercase().as_str() {
284        "organization" | "organisation" | "org" => WhoKind::Organization,
285        "tool" | "agent" | "bot" => WhoKind::Tool,
286        _ => WhoKind::Human,
287    }
288}
289
290/// Default category inference from an entry's kinds/organisation (used when no explicit assignment exists).
291fn infer_categories(kinds: &[String], organization: &Option<String>) -> Vec<String> {
292    let hay = kinds.join(" ").to_lowercase();
293    let has = |needle: &str| hay.contains(needle);
294    let who = classify_who_kind(kinds, organization);
295    let mut cats = Vec::new();
296    match who {
297        WhoKind::Human => cats.push("people".into()),
298        WhoKind::Organization => cats.push("organizations".into()),
299        WhoKind::Tool => cats.push("agents".into()),
300    }
301    if who == WhoKind::Human {
302        if has("clinician")
303            || has("practitioner")
304            || has("doctor")
305            || has("health")
306            || has("nurse")
307            || has("therapist")
308        {
309            cats.push("health".into());
310        }
311        if has("cooperative") || has("coop") {
312            cats.push("cooperative".into());
313        }
314        if has("friend") || has("family") {
315            cats.push("family-friends".into());
316        }
317        // Affiliation group — the human is still who-kind Human.
318        if organization.is_some() {
319            cats.push("organizations".into());
320        }
321    }
322    cats.sort();
323    cats.dedup();
324    cats
325}
326
327fn merge_kinds(dst: &mut Vec<String>, src: Vec<String>) {
328    for s in src {
329        let s = s.trim().to_string();
330        if !s.is_empty() && !dst.iter().any(|d| d.eq_ignore_ascii_case(&s)) {
331            dst.push(s);
332        }
333    }
334}
335
336fn push_unique(dst: &mut Vec<String>, v: &str) {
337    if !dst.iter().any(|d| d == v) {
338        dst.push(v.to_string());
339    }
340}
341
342/// Pure core: merge directory actors + chat contacts into one categorised view, given the persisted
343/// category assignments and the category list. Kept pure (no filesystem) so it is deterministically
344/// testable; [`build_view`] wires it to the persisted stores.
345pub fn build_view_core(
346    actors: &[Actor],
347    contacts: &[ChatContact],
348    assignments: &BTreeMap<String, Vec<String>>,
349    categories: Vec<DirectoryCategory>,
350    agreements: &[Agreement],
351) -> DirectoryView {
352    let mut by_did: BTreeMap<String, DirectoryEntry> = BTreeMap::new();
353
354    for a in actors {
355        let did = if a.pairwise_did.is_empty() {
356            a.id.clone()
357        } else {
358            a.pairwise_did.clone()
359        };
360        let entry = by_did.entry(did.clone()).or_insert_with(|| DirectoryEntry {
361            did: did.clone(),
362            display_name: a.name.clone(),
363            kinds: vec![],
364            organization: a.organization.clone(),
365            verification_status: a.verification_status.clone(),
366            front_door_did: a.root_did_uri.clone(),
367            sources: vec![],
368            categories: vec![],
369            agreement_ids: vec![],
370            who_kind: WhoKind::Human.as_str().into(),
371            nym_address: None,
372        });
373        if entry.display_name.is_empty() {
374            entry.display_name = a.name.clone();
375        }
376        if entry.organization.is_none() {
377            entry.organization = a.organization.clone();
378        }
379        let mut kinds = vec![a.actor_type.clone()];
380        kinds.extend(a.roles.iter().cloned());
381        merge_kinds(&mut entry.kinds, kinds);
382        push_unique(&mut entry.sources, "directory-actor");
383    }
384
385    for c in contacts {
386        let entry = by_did
387            .entry(c.did.clone())
388            .or_insert_with(|| DirectoryEntry {
389                did: c.did.clone(),
390                display_name: c.display_name.clone(),
391                kinds: vec![],
392                organization: None,
393                verification_status: "INVITE_ACCEPTED".into(),
394                front_door_did: None,
395                sources: vec![],
396                categories: vec![],
397                agreement_ids: vec![],
398                who_kind: WhoKind::Human.as_str().into(),
399                nym_address: c.nym_address.clone(),
400            });
401        if entry.display_name.is_empty() {
402            entry.display_name = c.display_name.clone();
403        }
404        if entry.nym_address.is_none() {
405            entry.nym_address = c.nym_address.clone();
406        }
407        merge_kinds(&mut entry.kinds, c.categories.clone());
408        push_unique(&mut entry.sources, "contact");
409    }
410
411    let mut entries: Vec<DirectoryEntry> = by_did
412        .into_values()
413        .map(|mut e| {
414            e.categories = match assignments.get(&e.did) {
415                Some(cats) if !cats.is_empty() => cats.clone(),
416                _ => infer_categories(&e.kinds, &e.organization),
417            };
418            // Join P1: the agreements governing this relationship — the entry is a party to them, or the
419            // agreement names this DID as the relationship it governs.
420            e.agreement_ids = agreements
421                .iter()
422                .filter(|a| a.relationship_did == e.did || a.parties.iter().any(|p| *p == e.did))
423                .map(|a| a.id.clone())
424                .collect();
425            e.who_kind = classify_who_kind(&e.kinds, &e.organization)
426                .as_str()
427                .to_string();
428            e
429        })
430        .collect();
431    entries.sort_by(|a, b| {
432        parse_who_kind(&a.who_kind)
433            .sort_rank()
434            .cmp(&parse_who_kind(&b.who_kind).sort_rank())
435            .then(
436                a.display_name
437                    .to_lowercase()
438                    .cmp(&b.display_name.to_lowercase()),
439            )
440    });
441
442    DirectoryView {
443        categories,
444        entries,
445    }
446}
447
448/// Build the unified, categorised directory view over the persisted directory-actor + chat-contact stores,
449/// joined against the persisted agreement store so each entry carries its governing agreement ids.
450pub fn build_view(actors: &[Actor], contacts: &[ChatContact]) -> DirectoryView {
451    build_view_core(
452        actors,
453        contacts,
454        &load_assignments(),
455        list_categories(),
456        &crate::agreements::list_agreements(),
457    )
458}
459
460// ===========================================================================
461// Faceted + concept-aware search — for a directory that grows large over time.
462// ===========================================================================
463
464/// One selectable value within a facet, with its count in the current result and whether it's selected.
465#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
466pub struct FacetValue {
467    pub value: String,
468    pub label: String,
469    pub count: usize,
470    pub selected: bool,
471}
472
473/// A facet (a filterable dimension of the directory) and its values.
474#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
475pub struct Facet {
476    pub id: String,
477    pub label: String,
478    pub values: Vec<FacetValue>,
479}
480
481/// A search result: the ranked matching entries, the facet counts (drill-down), and the categories.
482#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
483pub struct DirectorySearchResult {
484    pub categories: Vec<DirectoryCategory>,
485    pub facets: Vec<Facet>,
486    pub entries: Vec<DirectoryEntry>,
487    pub total: usize,
488    pub query: String,
489}
490
491/// The facet dimensions, in display order.
492const FACET_IDS: [&str; 5] = ["category", "kind", "source", "verification", "agreements"];
493
494/// Concept clusters for **meaning-aware search**: a query token that hits any member of a cluster matches
495/// the whole cluster, so "doctor" finds a "clinician". This is honest concept expansion over the
496/// role/category space — NOT embedding similarity. (The scale path — entries as quins queried through the
497/// semantic graph engine / embeddings — is noted in the plan.)
498fn concept_clusters() -> &'static [&'static [&'static str]] {
499    &[
500        &[
501            "doctor",
502            "clinician",
503            "physician",
504            "gp",
505            "practitioner",
506            "medic",
507            "medical",
508            "health",
509            "nurse",
510            "therapist",
511            "care",
512            "psychiatrist",
513            "psychologist",
514            "counsellor",
515        ],
516        &[
517            "cooperative",
518            "coop",
519            "co-op",
520            "member",
521            "collective",
522            "union",
523        ],
524        &["friend", "family", "personal", "kin", "mate"],
525        &[
526            "organization",
527            "organisation",
528            "org",
529            "company",
530            "institution",
531            "business",
532            "ngo",
533        ],
534        &["agent", "ai", "bot", "assistant", "subagent", "sub-agent"],
535    ]
536}
537
538/// Expand a single query token to itself plus any concept cluster it belongs to.
539fn expand_token(tok: &str) -> Vec<String> {
540    let t = tok.trim().to_lowercase();
541    let mut out = vec![t.clone()];
542    if !t.is_empty() {
543        for cluster in concept_clusters() {
544            if cluster.iter().any(|w| *w == t) {
545                out.extend(cluster.iter().map(|w| w.to_string()));
546            }
547        }
548    }
549    out.sort();
550    out.dedup();
551    out
552}
553
554fn facet_label(id: &str) -> &'static str {
555    match id {
556        "category" => "Category",
557        "kind" => "Kind",
558        "source" => "Source",
559        "verification" => "Verification",
560        "agreements" => "Agreements",
561        _ => "",
562    }
563}
564
565fn entry_facet_values(e: &DirectoryEntry, facet: &str) -> Vec<String> {
566    match facet {
567        "category" => e.categories.clone(),
568        "kind" => e.kinds.clone(),
569        "source" => e.sources.clone(),
570        "verification" => vec![e.verification_status.clone()],
571        "agreements" => vec![if e.agreement_ids.is_empty() {
572            "without".to_string()
573        } else {
574            "with".to_string()
575        }],
576        _ => vec![],
577    }
578}
579
580fn value_label(fid: &str, value: &str, categories: &[DirectoryCategory]) -> String {
581    match fid {
582        "category" => categories
583            .iter()
584            .find(|c| c.id == value)
585            .map(|c| c.label.clone())
586            .unwrap_or_else(|| value.to_string()),
587        "agreements" => {
588            if value == "with" {
589                "With agreements".to_string()
590            } else {
591                "Without agreements".to_string()
592            }
593        }
594        _ => value.to_string(),
595    }
596}
597
598fn searchable_text(e: &DirectoryEntry, categories: &[DirectoryCategory]) -> String {
599    let mut parts = vec![
600        e.display_name.clone(),
601        e.did.clone(),
602        e.verification_status.clone(),
603    ];
604    if let Some(o) = &e.organization {
605        parts.push(o.clone());
606    }
607    parts.extend(e.kinds.iter().cloned());
608    for c in &e.categories {
609        parts.push(c.clone());
610        if let Some(cat) = categories.iter().find(|x| &x.id == c) {
611            parts.push(cat.label.clone());
612        }
613    }
614    parts.join(" ").to_lowercase()
615}
616
617/// Score an entry against the expanded query tokens. `None` = no match (AND across tokens); higher = better
618/// (name-field hits weighted heavier). An empty query matches everything with score 0.
619fn query_score(text: &str, name: &str, expanded: &[Vec<String>]) -> Option<i32> {
620    if expanded.is_empty() {
621        return Some(0);
622    }
623    let name_l = name.to_lowercase();
624    let mut score = 0i32;
625    for token_exp in expanded {
626        let mut hit = false;
627        for w in token_exp {
628            if !w.is_empty() && text.contains(w.as_str()) {
629                hit = true;
630                score += if name_l.contains(w.as_str()) { 3 } else { 1 };
631            }
632        }
633        if !hit {
634            return None; // every query token must match (recall comes from concept expansion)
635        }
636    }
637    Some(score)
638}
639
640/// Does the entry pass the selected facets (AND across facet groups, OR within a group)? `except` skips one
641/// group — used to compute drill-down counts for that group.
642fn passes_facets(
643    e: &DirectoryEntry,
644    selected: &BTreeMap<String, Vec<String>>,
645    except: Option<&str>,
646) -> bool {
647    for (fid, vals) in selected {
648        if vals.is_empty() || Some(fid.as_str()) == except {
649            continue;
650        }
651        let ev = entry_facet_values(e, fid);
652        if !vals.iter().any(|v| ev.iter().any(|x| x == v)) {
653            return false;
654        }
655    }
656    true
657}
658
659/// Pure search core: rank entries by a concept-expanded query and narrow by selected facets, returning the
660/// entries plus drill-down facet counts. Kept pure (no filesystem) for deterministic testing.
661pub fn search_core(
662    entries: Vec<DirectoryEntry>,
663    categories: Vec<DirectoryCategory>,
664    query: &str,
665    selected: &BTreeMap<String, Vec<String>>,
666) -> DirectorySearchResult {
667    let expanded: Vec<Vec<String>> = query.split_whitespace().map(expand_token).collect();
668
669    // Entries matching the text query (facets not yet applied), with scores.
670    let scored: Vec<(DirectoryEntry, i32)> = entries
671        .into_iter()
672        .filter_map(|e| {
673            let text = searchable_text(&e, &categories);
674            query_score(&text, &e.display_name, &expanded).map(|s| (e, s))
675        })
676        .collect();
677
678    // Facet counts: for each group, count over (query-matched ∩ every OTHER selected group) — the standard
679    // drill-down count so selecting a value shows how many you'd get.
680    let mut facets = Vec::new();
681    for fid in FACET_IDS {
682        let mut counts: BTreeMap<String, usize> = BTreeMap::new();
683        for (e, _) in scored
684            .iter()
685            .filter(|(e, _)| passes_facets(e, selected, Some(fid)))
686        {
687            for v in entry_facet_values(e, fid) {
688                *counts.entry(v).or_insert(0) += 1;
689            }
690        }
691        let sel = selected.get(fid).cloned().unwrap_or_default();
692        let mut values: Vec<FacetValue> = counts
693            .into_iter()
694            .map(|(value, count)| {
695                let label = value_label(fid, &value, &categories);
696                let is_sel = sel.iter().any(|x| x == &value);
697                FacetValue {
698                    value,
699                    label,
700                    count,
701                    selected: is_sel,
702                }
703            })
704            .collect();
705        values.sort_by(|a, b| {
706            b.count
707                .cmp(&a.count)
708                .then(a.label.to_lowercase().cmp(&b.label.to_lowercase()))
709        });
710        if !values.is_empty() {
711            facets.push(Facet {
712                id: fid.to_string(),
713                label: facet_label(fid).to_string(),
714                values,
715            });
716        }
717    }
718
719    // Narrow by all selected facets, then rank (score desc, then name).
720    let mut narrowed: Vec<(DirectoryEntry, i32)> = scored
721        .into_iter()
722        .filter(|(e, _)| passes_facets(e, selected, None))
723        .collect();
724    narrowed.sort_by(|a, b| {
725        b.1.cmp(&a.1)
726            .then(
727                parse_who_kind(&a.0.who_kind)
728                    .sort_rank()
729                    .cmp(&parse_who_kind(&b.0.who_kind).sort_rank()),
730            )
731            .then(
732                a.0.display_name
733                    .to_lowercase()
734                    .cmp(&b.0.display_name.to_lowercase()),
735            )
736    });
737    let entries: Vec<DirectoryEntry> = narrowed.into_iter().map(|(e, _)| e).collect();
738    let total = entries.len();
739
740    DirectorySearchResult {
741        categories,
742        facets,
743        entries,
744        total,
745        query: query.to_string(),
746    }
747}
748
749/// Search the persisted directory: build the unified view, then run [`search_core`].
750pub fn search(
751    actors: &[Actor],
752    contacts: &[ChatContact],
753    query: &str,
754    selected: &BTreeMap<String, Vec<String>>,
755) -> DirectorySearchResult {
756    let view = build_view(actors, contacts);
757    search_core(view.entries, view.categories, query, selected)
758}
759
760#[cfg(test)]
761mod tests {
762    use super::*;
763
764    fn actor(id: &str, name: &str, did: &str, ty: &str, roles: &[&str]) -> Actor {
765        Actor {
766            id: id.into(),
767            actor_type: ty.into(),
768            name: name.into(),
769            organization: None,
770            qualifications: vec![],
771            roles: roles.iter().map(|s| s.to_string()).collect(),
772            verification_status: "VERIFIED".into(),
773            pairwise_did: did.into(),
774            root_did_uri: None,
775            routing_hints: vec![],
776        }
777    }
778
779    fn contact(name: &str, did: &str, categories: &[&str]) -> ChatContact {
780        ChatContact {
781            actor_id: format!("contact-{did}"),
782            display_name: name.into(),
783            did: did.into(),
784            source: "connect".into(),
785            added_at: 0,
786            relay_endpoint: None,
787            nym_address: None,
788            categories: categories.iter().map(|s| s.to_string()).collect(),
789        }
790    }
791
792    #[test]
793    fn slugify_makes_stable_ids() {
794        assert_eq!(slugify("Health Practitioners"), "health-practitioners");
795        assert_eq!(slugify("  My Co-op!! "), "my-co-op");
796        assert_eq!(slugify("A/B\\C"), "a-b-c");
797    }
798
799    #[test]
800    fn inference_routes_by_kind_and_org() {
801        assert!(infer_categories(&["clinician".into()], &None).contains(&"health".to_string()));
802        assert!(infer_categories(&["AGENT".into()], &None).contains(&"agents".to_string()));
803        assert!(
804            !infer_categories(&["AGENT".into()], &None).contains(&"people".to_string()),
805            "tools are not listed as humans"
806        );
807        assert!(infer_categories(&["FRIEND".into()], &None).contains(&"family-friends".to_string()));
808        assert!(infer_categories(&[], &Some("Acme".into())).contains(&"organizations".to_string()));
809        assert!(
810            !infer_categories(&[], &Some("Acme".into())).contains(&"people".to_string()),
811            "org-only signal is Organization who-kind, not a human"
812        );
813        // Unlabelled entries default to humans.
814        assert!(infer_categories(&[], &None).contains(&"people".to_string()));
815        // Human with an org affiliation stays human and also sits in Organizations.
816        let affiliated = infer_categories(&["clinician".into()], &Some("Acme".into()));
817        assert!(affiliated.contains(&"people".to_string()));
818        assert!(affiliated.contains(&"organizations".to_string()));
819    }
820
821    #[test]
822    fn who_kind_cuts_human_org_tool() {
823        assert_eq!(classify_who_kind(&["FRIEND".into()], &None), WhoKind::Human);
824        assert_eq!(
825            classify_who_kind(&["ORGANIZATION".into()], &None),
826            WhoKind::Organization
827        );
828        assert_eq!(classify_who_kind(&["AGENT".into()], &None), WhoKind::Tool);
829        assert_eq!(
830            classify_who_kind(&["chatbot".into()], &None),
831            WhoKind::Tool,
832            "chatbot is a tool, not a human"
833        );
834        assert_eq!(
835            classify_who_kind(&["clinician".into()], &Some("Acme Hospital".into())),
836            WhoKind::Human,
837            "affiliation is not who-kind"
838        );
839        assert_eq!(
840            WhoKind::Organization.chrome_label(),
841            "Organization · legal person"
842        );
843        assert_eq!(WhoKind::Tool.chrome_label(), "Tool");
844        assert_eq!(WhoKind::Human.chrome_label(), "Human");
845    }
846
847    #[test]
848    fn directory_lists_humans_first() {
849        let actors = vec![
850            actor("org", "Acme Ltd", "did:wf:acme", "ORGANIZATION", &[]),
851            actor("bot", "HelpBot", "did:wf:bot", "AGENT", &["chatbot"]),
852            actor("zed", "Zed", "did:wf:zed", "FRIEND", &[]),
853            actor("ann", "Ann", "did:wf:ann", "FRIEND", &[]),
854        ];
855        let view = build_view_core(&actors, &[], &BTreeMap::new(), builtin_categories(), &[]);
856        let names: Vec<&str> = view
857            .entries
858            .iter()
859            .map(|e| e.display_name.as_str())
860            .collect();
861        assert_eq!(names, vec!["Ann", "Zed", "Acme Ltd", "HelpBot"]);
862        assert_eq!(view.entries[0].who_kind, "human");
863        assert_eq!(view.entries[2].who_kind, "organization");
864        assert_eq!(view.entries[3].who_kind, "tool");
865    }
866
867    #[test]
868    fn same_did_in_both_stores_merges_to_one_entry() {
869        let actors = vec![actor(
870            "a1",
871            "Dr Smith",
872            "did:wf:smith",
873            "PRACTITIONER",
874            &["clinician"],
875        )];
876        let contacts = vec![contact("Dr Smith", "did:wf:smith", &["health"])];
877        let view = build_view_core(
878            &actors,
879            &contacts,
880            &BTreeMap::new(),
881            builtin_categories(),
882            &[],
883        );
884        assert_eq!(
885            view.entries.len(),
886            1,
887            "two stores for same DID produce 1 entry"
888        );
889        let e = &view.entries[0];
890        assert_eq!(e.sources, vec!["directory-actor", "contact"]);
891        assert!(e.categories.contains(&"health".to_string()));
892    }
893
894    #[test]
895    fn directory_entry_carries_nym_address_from_contact() {
896        let mut c = contact("Bob", "did:qi:bob", &[]);
897        c.nym_address = Some("bob_client.bob_sphinx@nym_gateway".into());
898        let view = build_view_core(&[], &[c], &BTreeMap::new(), builtin_categories(), &[]);
899        assert_eq!(view.entries.len(), 1);
900        assert_eq!(
901            view.entries[0].nym_address,
902            Some("bob_client.bob_sphinx@nym_gateway".into())
903        );
904    }
905
906    #[test]
907    fn explicit_assignment_overrides_inference() {
908        let actors = vec![actor("a1", "Bob", "did:wf:bob", "FRIEND", &[])];
909        let mut assignments = BTreeMap::new();
910        assignments.insert("did:wf:bob".to_string(), vec!["cooperative".to_string()]);
911        let view = build_view_core(&actors, &[], &assignments, builtin_categories(), &[]);
912        assert_eq!(view.entries[0].categories, vec!["cooperative".to_string()]);
913    }
914
915    #[test]
916    fn distinct_dids_stay_separate_and_sorted() {
917        let actors = vec![
918            actor("a1", "Zed", "did:wf:z", "FRIEND", &[]),
919            actor("a2", "Ann", "did:wf:a", "FRIEND", &[]),
920        ];
921        let view = build_view_core(&actors, &[], &BTreeMap::new(), builtin_categories(), &[]);
922        assert_eq!(view.entries.len(), 2);
923        assert_eq!(view.entries[0].display_name, "Ann"); // sorted case-insensitively
924        assert_eq!(view.entries[1].display_name, "Zed");
925    }
926
927    fn entries_of(actors: &[Actor], contacts: &[ChatContact]) -> Vec<DirectoryEntry> {
928        build_view_core(
929            actors,
930            contacts,
931            &BTreeMap::new(),
932            builtin_categories(),
933            &[],
934        )
935        .entries
936    }
937
938    fn agreement(id: &str, relationship_did: &str, parties: &[&str]) -> Agreement {
939        Agreement {
940            id: id.into(),
941            title: "Care relationship".into(),
942            relationship_did: relationship_did.into(),
943            parties: parties.iter().map(|s| s.to_string()).collect(),
944            values_anchors: vec!["urn:qualia:values:udhr".into()],
945            undertakings: vec![],
946            consents: vec![],
947            stage: crate::agreements::FormationStage::Draft,
948            jurisdiction: None,
949            intents: Vec::new(),
950            artifact_context: None,
951            created_at: 0,
952            updated_at: 0,
953        }
954    }
955
956    #[test]
957    fn agreements_join_onto_the_governed_party() {
958        let actors = vec![
959            actor(
960                "a1",
961                "Dr Smith",
962                "did:wf:smith",
963                "PRACTITIONER",
964                &["clinician"],
965            ),
966            actor("a2", "Bob", "did:wf:bob", "FRIEND", &[]),
967        ];
968        // One agreement governs the relationship with Dr Smith (as relationship_did AND as a party);
969        // none touches Bob.
970        let ags = vec![agreement(
971            "ag-1",
972            "did:wf:smith",
973            &["did:wf:me", "did:wf:smith"],
974        )];
975        let view = build_view_core(&actors, &[], &BTreeMap::new(), builtin_categories(), &ags);
976
977        let smith = view
978            .entries
979            .iter()
980            .find(|e| e.did == "did:wf:smith")
981            .unwrap();
982        assert_eq!(
983            smith.agreement_ids,
984            vec!["ag-1".to_string()],
985            "agreement joins onto its party"
986        );
987        let bob = view.entries.iter().find(|e| e.did == "did:wf:bob").unwrap();
988        assert!(
989            bob.agreement_ids.is_empty(),
990            "unrelated party has no agreements"
991        );
992
993        // The 'agreements' facet now distinguishes with/without.
994        let r = search_core(view.entries, builtin_categories(), "", &BTreeMap::new());
995        let facet = r
996            .facets
997            .iter()
998            .find(|f| f.id == "agreements")
999            .expect("agreements facet");
1000        assert!(facet
1001            .values
1002            .iter()
1003            .any(|v| v.value == "with" && v.count == 1));
1004        assert!(facet
1005            .values
1006            .iter()
1007            .any(|v| v.value == "without" && v.count == 1));
1008    }
1009
1010    #[test]
1011    fn concept_search_matches_by_meaning() {
1012        let actors = vec![actor(
1013            "a1",
1014            "Dr Smith",
1015            "did:wf:smith",
1016            "PRACTITIONER",
1017            &["clinician"],
1018        )];
1019        let entries = entries_of(&actors, &[]);
1020        // "doctor" is not a literal token on the entry, but it shares a concept cluster with "clinician".
1021        let hit = search_core(
1022            entries.clone(),
1023            builtin_categories(),
1024            "doctor",
1025            &BTreeMap::new(),
1026        );
1027        assert_eq!(
1028            hit.total, 1,
1029            "concept expansion: 'doctor' finds a 'clinician'"
1030        );
1031        // An unrelated concept does not match.
1032        let miss = search_core(
1033            entries,
1034            builtin_categories(),
1035            "cooperative",
1036            &BTreeMap::new(),
1037        );
1038        assert_eq!(miss.total, 0);
1039    }
1040
1041    #[test]
1042    fn query_tokens_are_anded() {
1043        let actors = vec![
1044            actor("a1", "Dr Smith", "did:wf:smith", "FRIEND", &[]),
1045            actor("a2", "Dr Jones", "did:wf:jones", "FRIEND", &[]),
1046        ];
1047        let entries = entries_of(&actors, &[]);
1048        let r = search_core(entries, builtin_categories(), "dr smith", &BTreeMap::new());
1049        assert_eq!(r.total, 1);
1050        assert_eq!(r.entries[0].display_name, "Dr Smith");
1051    }
1052
1053    #[test]
1054    fn facets_count_and_narrow() {
1055        let actors = vec![
1056            actor(
1057                "a1",
1058                "Dr Smith",
1059                "did:wf:smith",
1060                "PRACTITIONER",
1061                &["clinician"],
1062            ), // → health
1063            actor("a2", "Bob", "did:wf:bob", "FRIEND", &[]), // → family-friends
1064        ];
1065        let entries = entries_of(&actors, &[]);
1066        let all = search_core(entries.clone(), builtin_categories(), "", &BTreeMap::new());
1067        let cat_facet = all
1068            .facets
1069            .iter()
1070            .find(|f| f.id == "category")
1071            .expect("category facet");
1072        let health = cat_facet
1073            .values
1074            .iter()
1075            .find(|v| v.value == "health")
1076            .expect("health value");
1077        assert_eq!(health.count, 1);
1078
1079        // Selecting the health category narrows to just the clinician.
1080        let mut sel = BTreeMap::new();
1081        sel.insert("category".to_string(), vec!["health".to_string()]);
1082        let narrowed = search_core(entries, builtin_categories(), "", &sel);
1083        assert_eq!(narrowed.total, 1);
1084        assert_eq!(narrowed.entries[0].display_name, "Dr Smith");
1085        // The category facet still reports drill-down counts (health selected, count preserved).
1086        let cat_facet = narrowed.facets.iter().find(|f| f.id == "category").unwrap();
1087        assert!(cat_facet
1088            .values
1089            .iter()
1090            .any(|v| v.value == "health" && v.selected));
1091    }
1092}