Skip to main content

qualia_client_core/
chat_agents.rs

1//! Group-chat sub-agent hierarchy — local LLM / Webizen agents are bound to human principals.
2//!
3//! Each participant may run a different model/backend. Processed outcomes (not raw prompts)
4//! can be shared with other participants when an explicit `OutcomeSharingPolicy` permits it.
5
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use qualia_core_db::q_hash;
10use serde::{Deserialize, Serialize};
11
12use crate::chat_session::{self, ChatMessage, Role, SessionKind};
13
14#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
15#[serde(rename_all = "snake_case")]
16pub enum AgentBackendKind {
17    /// Native in-process GGUF / wgpu Qualia engine (primary).
18    #[default]
19    Local,
20    /// Remote provider path (Nym / MCP); consent + metering.
21    Remote,
22    /// Local first; optional remote or Ollama fallback per settings.
23    Hybrid,
24    /// Optional Ollama HTTP harness (opt-in; not the primary Qualia engine).
25    Ollama,
26}
27
28impl AgentBackendKind {
29    /// `str` form.
30    pub fn as_str(self) -> &'static str {
31        match self {
32            AgentBackendKind::Local => "local",
33            AgentBackendKind::Remote => "remote",
34            AgentBackendKind::Hybrid => "hybrid",
35            AgentBackendKind::Ollama => "ollama",
36        }
37    }
38
39    /// Constructs from str.
40    pub fn from_str(s: &str) -> Self {
41        match s.to_lowercase().as_str() {
42            "remote" => AgentBackendKind::Remote,
43            "hybrid" => AgentBackendKind::Hybrid,
44            "ollama" => AgentBackendKind::Ollama,
45            _ => AgentBackendKind::Local,
46        }
47    }
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51#[serde(rename_all = "snake_case")]
52pub enum OutcomeVisibility {
53    OwnerOnly,
54    SessionParticipants,
55    SpecificDids,
56}
57
58impl OutcomeVisibility {
59    /// `str` form.
60    pub fn as_str(&self) -> &'static str {
61        match self {
62            OutcomeVisibility::OwnerOnly => "owner_only",
63            OutcomeVisibility::SessionParticipants => "session_participants",
64            OutcomeVisibility::SpecificDids => "specific_dids",
65        }
66    }
67
68    /// Constructs from str.
69    pub fn from_str(s: &str) -> Result<Self, String> {
70        match s {
71            "owner_only" => Ok(OutcomeVisibility::OwnerOnly),
72            "session_participants" => Ok(OutcomeVisibility::SessionParticipants),
73            "specific_dids" => Ok(OutcomeVisibility::SpecificDids),
74            _ => Err(format!("unknown outcome visibility: {s}")),
75        }
76    }
77}
78
79/// Permission for sharing Webizen-processed outcomes (summaries, grounded answers) with peers.
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
81pub struct OutcomeSharingPolicy {
82    pub visibility: OutcomeVisibility,
83    /// Include provenance / citation hashes when relaying to peers.
84    pub share_provenance: bool,
85    /// Attribute which model produced the outcome (respects `share_active_model` on profile card).
86    pub share_model_attribution: bool,
87    /// Other participants' sub-agents may use this outcome in their inference context.
88    pub allow_peer_llm_context: bool,
89    #[serde(default)]
90    pub allowed_dids: Vec<String>,
91}
92
93impl Default for OutcomeSharingPolicy {
94    fn default() -> Self {
95        Self {
96            visibility: OutcomeVisibility::OwnerOnly,
97            share_provenance: true,
98            share_model_attribution: false,
99            allow_peer_llm_context: false,
100            allowed_dids: vec![],
101        }
102    }
103}
104
105/// Local user's sub-agent binding for a chat session.
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct ParticipantAgentConfig {
108    /// Human principal DID (owner of the sub-agent).
109    pub principal_did: String,
110    /// Derived sub-agent DID — not an independent chat actor.
111    pub sub_agent_did: String,
112    /// Stable roster binding for the agent that most recently answered in this
113    /// session.  Older session files omit it and retain the default local
114    /// assistant behaviour.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub roster_agent_slug: Option<String>,
117    /// User-defined roster name captured with the turn so chat attribution
118    /// does not fall back to the principal's generic Webizen-agent label.
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub roster_agent_display_name: Option<String>,
121    pub model_id: Option<String>,
122    pub backend: AgentBackendKind,
123    pub outcome_sharing: OutcomeSharingPolicy,
124    pub updated_at: u64,
125}
126
127/// Summary of a peer's disclosed agent for cooperative multi-LLM briefing.
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct PeerAgentSummary {
130    pub principal_did: String,
131    pub principal_name: Option<String>,
132    pub sub_agent_did: String,
133    pub model_id: Option<String>,
134    pub backend: AgentBackendKind,
135    pub shares_outcomes: bool,
136}
137
138fn agent_config_path(storage_root: &Path, session_id: &str) -> PathBuf {
139    chat_session::chats_dir(storage_root)
140        .join(session_id)
141        .join("agent_config.json")
142}
143
144fn unix_now() -> u64 {
145    std::time::SystemTime::now()
146        .duration_since(std::time::UNIX_EPOCH)
147        .unwrap_or_default()
148        .as_secs()
149}
150
151/// Deterministic sub-agent DID scoped to principal + session.
152pub fn compile_sub_agent_did(principal_did: &str, session_id: &str) -> String {
153    let p = q_hash(principal_did);
154    let s = q_hash(&format!("qualia:chat:subagent:{session_id}"));
155    format!("did:qualia:subagent:{p:016x}:{s:016x}")
156}
157
158/// Default outcome-sharing policy.
159pub fn default_outcome_sharing(kind: SessionKind) -> OutcomeSharingPolicy {
160    let profile = crate::user_profile::load_profile();
161    default_outcome_sharing_for_profile(kind, &profile)
162}
163
164/// Default outcome-sharing for a profile.
165pub fn default_outcome_sharing_for_profile(
166    kind: SessionKind,
167    profile: &crate::user_profile::UserProfile,
168) -> OutcomeSharingPolicy {
169    match kind {
170        SessionKind::Solo => OutcomeSharingPolicy::default(),
171        SessionKind::Group => {
172            if profile.sharing.share_llm_outcomes {
173                OutcomeSharingPolicy {
174                    visibility: OutcomeVisibility::SessionParticipants,
175                    share_provenance: true,
176                    share_model_attribution: profile.sharing.share_active_model,
177                    allow_peer_llm_context: true,
178                    allowed_dids: vec![],
179                }
180            } else {
181                OutcomeSharingPolicy::default()
182            }
183        }
184    }
185}
186
187/// Loads local-agent-config.
188pub fn load_local_agent_config(
189    storage_root: &Path,
190    session_id: &str,
191) -> Result<ParticipantAgentConfig, String> {
192    let path = agent_config_path(storage_root, session_id);
193    if path.is_file() {
194        let text = fs::read_to_string(&path).map_err(|e| e.to_string())?;
195        return serde_json::from_str(&text).map_err(|e| e.to_string());
196    }
197
198    let profile = crate::user_profile::load_profile();
199    let session =
200        chat_session::load_session(storage_root, session_id).map_err(|e| e.to_string())?;
201    let active = crate::context_binding::load_active_model_record();
202    Ok(fresh_local_agent_config(
203        &profile.public_did,
204        session_id,
205        session.meta.session_kind,
206        active.as_ref().map(|r| r.model_id.as_str()),
207        &profile,
208    ))
209}
210
211/// Fresh local agent config.
212pub fn fresh_local_agent_config(
213    principal_did: &str,
214    session_id: &str,
215    kind: SessionKind,
216    model_id: Option<&str>,
217    profile: &crate::user_profile::UserProfile,
218) -> ParticipantAgentConfig {
219    ParticipantAgentConfig {
220        principal_did: principal_did.to_string(),
221        sub_agent_did: compile_sub_agent_did(principal_did, session_id),
222        roster_agent_slug: None,
223        roster_agent_display_name: None,
224        model_id: model_id.map(|s| s.to_string()),
225        backend: crate::inference_backend::load_inference_backend_settings().backend,
226        outcome_sharing: default_outcome_sharing_for_profile(kind, profile),
227        updated_at: unix_now(),
228    }
229}
230
231/// Bind the local session projection to a named roster agent immediately
232/// before its turn.  The roster remains the source of truth; this small
233/// session record is used solely to attribute the persisted chat message.
234pub fn bind_local_roster_agent(
235    storage_root: &Path,
236    session_id: &str,
237    agent: &crate::agent_registry::AgentDefinition,
238) -> Result<(), String> {
239    let model_id = match &agent.backend {
240        crate::agent_registry::AgentBackendSpec::LocalEngine { model_id } => model_id.clone(),
241        crate::agent_registry::AgentBackendSpec::RemoteMcp { .. } => {
242            return Err("remote roster agents are not local session bindings".to_string());
243        }
244    };
245    let mut config = load_local_agent_config(storage_root, session_id)?;
246    config.roster_agent_slug = Some(agent.slug.clone());
247    config.roster_agent_display_name = Some(agent.display_name.clone());
248    // A blank roster model explicitly means "use the active local default";
249    // clear any earlier agent's pin rather than carrying it into attribution.
250    config.model_id = model_id;
251    config.backend = AgentBackendKind::Local;
252    save_local_agent_config(storage_root, session_id, &config)
253}
254
255/// Ensures local-agent-config.
256pub fn ensure_local_agent_config(storage_root: &Path, session_id: &str) -> Result<(), String> {
257    let path = agent_config_path(storage_root, session_id);
258    if path.is_file() {
259        return Ok(());
260    }
261    let cfg = load_local_agent_config(storage_root, session_id)?;
262    save_local_agent_config(storage_root, session_id, &cfg)
263}
264
265/// Saves local-agent-config.
266pub fn save_local_agent_config(
267    storage_root: &Path,
268    session_id: &str,
269    config: &ParticipantAgentConfig,
270) -> Result<(), String> {
271    let path = agent_config_path(storage_root, session_id);
272    if let Some(parent) = path.parent() {
273        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
274    }
275    let mut cfg = config.clone();
276    cfg.updated_at = unix_now();
277    let text = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
278    fs::write(path, text).map_err(|e| e.to_string())
279}
280
281/// Updates outcome-sharing policy.
282pub fn update_outcome_sharing(
283    storage_root: &Path,
284    session_id: &str,
285    policy: OutcomeSharingPolicy,
286) -> Result<ParticipantAgentConfig, String> {
287    let mut cfg = load_local_agent_config(storage_root, session_id)?;
288    cfg.outcome_sharing = policy;
289    save_local_agent_config(storage_root, session_id, &cfg)?;
290    Ok(cfg)
291}
292
293/// Apply sub-agent metadata to an agent-role message from the local principal.
294pub fn decorate_local_agent_message(
295    storage_root: &Path,
296    session_id: &str,
297    msg: &mut ChatMessage,
298) -> Result<(), String> {
299    if msg.role != Role::Agent {
300        return Ok(());
301    }
302    if msg.sub_agent_of.is_some() {
303        return Ok(());
304    }
305
306    let cfg = load_local_agent_config(storage_root, session_id)?;
307    msg.sub_agent_of = Some(cfg.principal_did.clone());
308    msg.agent_did = Some(cfg.sub_agent_did.clone());
309    msg.model_id = cfg.model_id.clone();
310    msg.agent_backend = Some(cfg.backend.as_str().to_string());
311    msg.outcome_sharing = Some(cfg.outcome_sharing.clone());
312    msg.author_did = Some(cfg.sub_agent_did.clone());
313    msg.author_name = Some(local_agent_display_name(&cfg));
314    Ok(())
315}
316
317/// Local agent-display-name.
318pub fn local_agent_display_name(cfg: &ParticipantAgentConfig) -> String {
319    if let Some(name) = cfg.roster_agent_display_name.as_deref() {
320        if let Some(model) = cfg.model_id.as_deref() {
321            return format!("{name} ({model})");
322        }
323        return name.to_string();
324    }
325    let profile = crate::user_profile::load_profile();
326    let base = if profile.public_did == cfg.principal_did {
327        profile.display_name.clone()
328    } else {
329        cfg.principal_did.clone()
330    };
331    if let Some(ref model) = cfg.model_id {
332        format!("{base}'s agent ({model})")
333    } else {
334        format!("{base}'s Webizen agent")
335    }
336}
337
338// ---------------------------------------------------------------------------
339// R7 — @mention roster resolution
340// ---------------------------------------------------------------------------
341
342/// A parsed `@mention` extracted from a chat prompt.
343///
344/// `@slug` at the start of (or anywhere in) a user message directs the turn
345/// at a named roster agent. The mention is stripped from the prompt before
346/// inference so the agent receives a clean user turn.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct Mention {
349    /// The roster slug, without the leading `@`.
350    pub slug: String,
351    /// Byte offset in the original prompt where the `@slug` token began.
352    pub start: usize,
353    /// Byte offset one past the end of the `@slug` token.
354    pub end: usize,
355}
356
357impl Mention {
358    /// The raw `@slug` text, including the leading `@`.
359    pub fn raw(&self) -> String {
360        format!("@{}", self.slug)
361    }
362}
363
364/// Parse the first `@mention` from a prompt.
365///
366/// A mention is `@` followed by one or more slug characters (`[a-z0-9_-]`,
367/// starting with a letter). The mention may appear anywhere in the message
368/// but is typically at the start (e.g. `@researcher summarize the thread`).
369///
370/// Returns `None` if no valid mention is found. A `@` not followed by a
371/// valid slug character is treated as literal text (not a mention).
372pub fn parse_mention(prompt: &str) -> Option<Mention> {
373    let bytes = prompt.as_bytes();
374    let mut i = 0;
375    while i < bytes.len() {
376        if bytes[i] != b'@' {
377            i += 1;
378            continue;
379        }
380        // A mention must be at the start of the string or preceded by a
381        // word boundary (whitespace). This rejects `@@foo` and `x@foo`.
382        let at_word_boundary = i == 0 || bytes[i - 1].is_ascii_whitespace();
383        if !at_word_boundary {
384            i += 1;
385            continue;
386        }
387        // Must be followed by a letter (slug starts with a letter).
388        let slug_start = i + 1;
389        if slug_start >= bytes.len() || !bytes[slug_start].is_ascii_alphabetic() {
390            i += 1;
391            continue;
392        }
393        // Scan the slug body: [a-z0-9_-]
394        let mut j = slug_start;
395        while j < bytes.len()
396            && (bytes[j].is_ascii_alphanumeric() || bytes[j] == b'_' || bytes[j] == b'-')
397        {
398            j += 1;
399        }
400        let slug = &prompt[slug_start..j];
401        return Some(Mention {
402            slug: slug.to_string(),
403            start: i,
404            end: j,
405        });
406    }
407    None
408}
409
410/// Strip the first `@mention` from a prompt, returning the cleaned text.
411///
412/// If the mention is at the start of the prompt, leading whitespace after it
413/// is also trimmed. If the mention is mid-prompt, only the `@slug` token is
414/// removed and surrounding whitespace is collapsed.
415pub fn strip_mention(prompt: &str) -> String {
416    match parse_mention(prompt) {
417        None => prompt.to_string(),
418        Some(m) => {
419            let before = &prompt[..m.start];
420            let after = &prompt[m.end..];
421            // If the mention is at the start, trim leading whitespace after it.
422            if before.trim().is_empty() {
423                after.trim_start().to_string()
424            } else {
425                // Mid-prompt: remove the token, collapse whitespace.
426                format!("{}{}", before.trim_end(), after).trim().to_string()
427            }
428        }
429    }
430}
431
432/// Resolve a parsed mention against the roster.
433///
434/// Returns the matching `AgentDefinition()` if the slug exists and is
435/// enabled, or `None` if the slug is not in the roster or the agent is
436/// disabled.
437pub fn resolve_mention(
438    storage_root: &Path,
439    mention: &Mention,
440) -> Option<crate::agent_registry::AgentDefinition> {
441    let agent = crate::agent_registry::get_agent(storage_root, &mention.slug)?;
442    if agent.enabled {
443        Some(agent)
444    } else {
445        None
446    }
447}
448
449/// The outcome of parsing a prompt for agent dispatch.
450#[derive(Debug, Clone)]
451pub enum PromptDispatch {
452    /// No mention found — use the default inference path.
453    Default,
454    /// A mention was found and resolved to a roster agent.
455    Agent {
456        agent: crate::agent_registry::AgentDefinition,
457        /// The prompt with the mention stripped.
458        clean_prompt: String,
459    },
460    /// A mention was found but the slug is unknown or disabled.
461    UnknownAgent {
462        slug: String,
463        /// The original prompt (unmodified).
464        prompt: String,
465    },
466}
467
468/// Parse a prompt and resolve any `@mention` against the roster.
469///
470/// This is the single entry point for the chat layer: call this with the
471/// raw user prompt, then dispatch based on the result.
472pub fn resolve_prompt_dispatch(storage_root: &Path, prompt: &str) -> PromptDispatch {
473    match parse_mention(prompt) {
474        None => PromptDispatch::Default,
475        Some(m) => match resolve_mention(storage_root, &m) {
476            Some(agent) => PromptDispatch::Agent {
477                agent,
478                clean_prompt: strip_mention(prompt),
479            },
480            None => PromptDispatch::UnknownAgent {
481                slug: m.slug,
482                prompt: prompt.to_string(),
483            },
484        },
485    }
486}
487
488/// Participant DIDs.
489pub fn participant_dids(participants: &[chat_session::ChatParticipant]) -> Vec<String> {
490    participants.iter().map(|p| p.did.clone()).collect()
491}
492
493/// `true` when participant.
494pub fn is_participant(did: &str, participants: &[chat_session::ChatParticipant]) -> bool {
495    participants.iter().any(|p| p.did == did)
496}
497
498/// Whether a processed agent outcome may be relayed to group peers.
499pub fn can_relay_agent_outcome(
500    msg: &ChatMessage,
501    participants: &[chat_session::ChatParticipant],
502) -> bool {
503    if msg.role != Role::Agent {
504        return true;
505    }
506    let Some(ref principal) = msg.sub_agent_of else {
507        return false;
508    };
509    if !is_participant(principal, participants) {
510        return false;
511    }
512    let policy = msg.outcome_sharing.as_ref().cloned().unwrap_or_default();
513    match policy.visibility {
514        OutcomeVisibility::OwnerOnly => false,
515        OutcomeVisibility::SessionParticipants => true,
516        OutcomeVisibility::SpecificDids => !policy.allowed_dids.is_empty(),
517    }
518}
519
520/// Whether `viewer_did` may read a peer's shared agent outcome in relay / UI.
521pub fn can_view_agent_outcome(
522    msg: &ChatMessage,
523    viewer_did: &str,
524    participants: &[chat_session::ChatParticipant],
525) -> bool {
526    if msg.role != Role::Agent {
527        return true;
528    }
529    if msg.sub_agent_of.as_deref() == Some(viewer_did) {
530        return true;
531    }
532    let policy = msg.outcome_sharing.as_ref().cloned().unwrap_or_default();
533    match policy.visibility {
534        OutcomeVisibility::OwnerOnly => false,
535        OutcomeVisibility::SessionParticipants => is_participant(viewer_did, participants),
536        OutcomeVisibility::SpecificDids => policy.allowed_dids.iter().any(|d| d == viewer_did),
537    }
538}
539
540/// Whether another participant's sub-agent may cite this outcome in inference context.
541pub fn can_use_in_peer_llm_context(
542    msg: &ChatMessage,
543    viewer_did: &str,
544    participants: &[chat_session::ChatParticipant],
545) -> bool {
546    if msg.role != Role::Agent {
547        return true;
548    }
549    if !can_view_agent_outcome(msg, viewer_did, participants) {
550        return false;
551    }
552    msg.outcome_sharing
553        .as_ref()
554        .map(|p| p.allow_peer_llm_context)
555        .unwrap_or(false)
556}
557
558/// Collect peer agent disclosures from committed, shareable agent messages in the session.
559pub fn collect_peer_agent_summaries(
560    messages: &[ChatMessage],
561    participants: &[chat_session::ChatParticipant],
562    local_principal_did: &str,
563) -> Vec<PeerAgentSummary> {
564    let mut out = Vec::new();
565    let mut seen = std::collections::HashSet::new();
566
567    for msg in messages {
568        if msg.role != Role::Agent {
569            continue;
570        }
571        let Some(ref principal) = msg.sub_agent_of else {
572            continue;
573        };
574        if principal == local_principal_did {
575            continue;
576        }
577        if !can_view_agent_outcome(msg, local_principal_did, participants) {
578            continue;
579        }
580        if !seen.insert(principal.clone()) {
581            continue;
582        }
583        let name = participants
584            .iter()
585            .find(|p| p.did == *principal)
586            .map(|p| p.display_name.clone());
587        let shares = msg
588            .outcome_sharing
589            .as_ref()
590            .map(|p| p.visibility != OutcomeVisibility::OwnerOnly)
591            .unwrap_or(false);
592        out.push(PeerAgentSummary {
593            principal_did: principal.clone(),
594            principal_name: name,
595            sub_agent_did: msg.agent_did.clone().unwrap_or_default(),
596            model_id: msg.model_id.clone(),
597            backend: msg
598                .agent_backend
599                .as_deref()
600                .map(AgentBackendKind::from_str)
601                .unwrap_or_default(),
602            shares_outcomes: shares,
603        });
604    }
605    out
606}
607
608/// Builds cooperative-agents-block.
609pub fn build_cooperative_agents_block(
610    storage_root: &Path,
611    session_id: &str,
612    messages: &[ChatMessage],
613    participants: &[chat_session::ChatParticipant],
614) -> String {
615    let profile = crate::user_profile::load_profile();
616    let local = match load_local_agent_config(storage_root, session_id) {
617        Ok(c) => c,
618        Err(_) => return String::new(),
619    };
620
621    let mut lines = vec![
622        "[Cooperative group agents]".to_string(),
623        format!(
624            "local_sub_agent: {} (principal={}, backend={}, model={})",
625            local.sub_agent_did,
626            local.principal_did,
627            local.backend.as_str(),
628            local.model_id.as_deref().unwrap_or("none")
629        ),
630        format!(
631            "local_outcome_sharing: {}",
632            local.outcome_sharing.visibility.as_str()
633        ),
634        "note: Sub-agents are not independent participants — they act on behalf of their human principal.".to_string(),
635    ];
636
637    let peers = collect_peer_agent_summaries(messages, participants, &profile.public_did);
638    if peers.is_empty() {
639        lines.push("peer_agents: none disclosed".to_string());
640    } else {
641        lines.push("peer_agents:".to_string());
642        for p in peers {
643            let label = p.principal_name.as_deref().unwrap_or(&p.principal_did);
644            let model = p.model_id.as_deref().unwrap_or("hidden");
645            lines.push(format!(
646                "  - {label} → sub_agent={} backend={} model={} shares_outcomes={}",
647                p.sub_agent_did,
648                p.backend.as_str(),
649                model,
650                p.shares_outcomes
651            ));
652        }
653    }
654
655    let shareable: Vec<_> = messages
656        .iter()
657        .filter(|m| {
658            m.role == Role::Agent
659                && can_use_in_peer_llm_context(m, &profile.public_did, participants)
660        })
661        .collect();
662    if !shareable.is_empty() {
663        lines.push("shared_peer_outcomes (for your agent context only):".to_string());
664        for m in shareable.iter().take(8) {
665            let principal = m.sub_agent_of.as_deref().unwrap_or("unknown");
666            let preview: String = m.content.chars().take(240).collect();
667            lines.push(format!("  - [{principal}]: {preview}"));
668        }
669    }
670
671    lines.join("\n")
672}
673
674/// Validates an ingested agent message.
675pub fn validate_ingested_agent_message(
676    msg: &ChatMessage,
677    participants: &[chat_session::ChatParticipant],
678) -> Result<(), String> {
679    if msg.role != Role::Agent {
680        return Ok(());
681    }
682    let principal = msg
683        .sub_agent_of
684        .as_deref()
685        .ok_or_else(|| "Agent message missing sub_agent_of principal".to_string())?;
686    if !is_participant(principal, participants) {
687        return Err(format!(
688            "Agent principal {principal} is not a session participant"
689        ));
690    }
691    if let Some(ref agent_did) = msg.agent_did {
692        if !agent_did.starts_with("did:qualia:subagent:") {
693            return Err(format!("Invalid sub-agent DID: {agent_did}"));
694        }
695    }
696    Ok(())
697}
698
699#[cfg(test)]
700mod tests {
701    use super::*;
702    use crate::chat_session::ChatParticipant;
703
704    fn tmp_storage() -> std::path::PathBuf {
705        let path = std::env::temp_dir().join(format!("qualia-chat-agents-test-{}", unix_now()));
706        let _ = fs::create_dir_all(&path);
707        path
708    }
709
710    #[test]
711    fn sub_agent_did_is_deterministic() {
712        let a = compile_sub_agent_did("did:qualia:root:abc", "sess-1");
713        let b = compile_sub_agent_did("did:qualia:root:abc", "sess-1");
714        assert_eq!(a, b);
715        assert!(a.starts_with("did:qualia:subagent:"));
716    }
717
718    #[test]
719    fn outcome_sharing_defaults_private_in_group() {
720        let mut profile = crate::user_profile::UserProfile::default();
721        profile.sharing.share_llm_outcomes = false;
722        let policy = default_outcome_sharing_for_profile(SessionKind::Group, &profile);
723        assert_eq!(policy.visibility, OutcomeVisibility::OwnerOnly);
724    }
725
726    #[test]
727    fn outcome_sharing_opens_when_profile_allows() {
728        let mut profile = crate::user_profile::UserProfile::default();
729        profile.sharing.share_llm_outcomes = true;
730        let policy = default_outcome_sharing_for_profile(SessionKind::Group, &profile);
731        assert_eq!(policy.visibility, OutcomeVisibility::SessionParticipants);
732        assert!(policy.allow_peer_llm_context);
733    }
734
735    #[test]
736    fn relay_gate_blocks_owner_only_agent_outcomes() {
737        let participants = vec![ChatParticipant {
738            did: "did:p1".to_string(),
739            display_name: "Alice".to_string(),
740            actor_id: "a1".to_string(),
741            role: "owner".to_string(),
742            joined_at: 0,
743        }];
744        let msg = ChatMessage {
745            lamport: 1,
746            role: Role::Agent,
747            content: "answer".to_string(),
748            timestamp: 0,
749            content_hash: 0,
750            author_did: None,
751            author_name: None,
752            reply_to_fragment: None,
753            source: None,
754            sub_agent_of: Some("did:p1".to_string()),
755            agent_did: Some(compile_sub_agent_did("did:p1", "s1")),
756            model_id: None,
757            agent_backend: None,
758            outcome_sharing: Some(OutcomeSharingPolicy::default()),
759        };
760        assert!(!can_relay_agent_outcome(&msg, &participants));
761    }
762
763    #[test]
764    fn peer_context_requires_allow_flag() {
765        let participants = vec![
766            ChatParticipant {
767                did: "did:p1".to_string(),
768                display_name: "Alice".to_string(),
769                actor_id: "a1".to_string(),
770                role: "owner".to_string(),
771                joined_at: 0,
772            },
773            ChatParticipant {
774                did: "did:p2".to_string(),
775                display_name: "Bob".to_string(),
776                actor_id: "b1".to_string(),
777                role: "member".to_string(),
778                joined_at: 0,
779            },
780        ];
781        let msg = ChatMessage {
782            lamport: 1,
783            role: Role::Agent,
784            content: "shared insight".to_string(),
785            timestamp: 0,
786            content_hash: 0,
787            author_did: None,
788            author_name: None,
789            reply_to_fragment: None,
790            source: None,
791            sub_agent_of: Some("did:p1".to_string()),
792            agent_did: None,
793            model_id: None,
794            agent_backend: None,
795            outcome_sharing: Some(OutcomeSharingPolicy {
796                visibility: OutcomeVisibility::SessionParticipants,
797                share_provenance: true,
798                share_model_attribution: false,
799                allow_peer_llm_context: false,
800                allowed_dids: vec![],
801            }),
802        };
803        assert!(can_view_agent_outcome(&msg, "did:p2", &participants));
804        assert!(!can_use_in_peer_llm_context(&msg, "did:p2", &participants));
805    }
806
807    #[test]
808    fn local_agent_config_roundtrip() {
809        let storage = tmp_storage();
810        let session_id = chat_session::create_session(&storage, Some("t".into()), None).unwrap();
811        let cfg = load_local_agent_config(&storage, &session_id).unwrap();
812        assert!(cfg.sub_agent_did.starts_with("did:qualia:subagent:"));
813        save_local_agent_config(&storage, &session_id, &cfg).unwrap();
814        let again = load_local_agent_config(&storage, &session_id).unwrap();
815        assert_eq!(again.sub_agent_did, cfg.sub_agent_did);
816    }
817
818    // ── R7: @mention parsing ────────────────────────────────────────────
819
820    #[test]
821    fn parse_mention_at_start() {
822        let m = parse_mention("@researcher summarize the thread").unwrap();
823        assert_eq!(m.slug, "researcher");
824        assert_eq!(m.start, 0);
825        assert_eq!(m.end, 11);
826    }
827
828    #[test]
829    fn parse_mention_mid_prompt() {
830        let m = parse_mention("hey @researcher can you help?").unwrap();
831        assert_eq!(m.slug, "researcher");
832        assert_eq!(m.start, 4);
833        assert_eq!(m.end, 15);
834    }
835
836    #[test]
837    fn parse_mention_with_hyphen_and_underscore() {
838        let m = parse_mention("@data-miner_2 run the query").unwrap();
839        assert_eq!(m.slug, "data-miner_2");
840    }
841
842    #[test]
843    fn parse_mention_none_for_plain_text() {
844        assert!(parse_mention("just a regular message").is_none());
845    }
846
847    #[test]
848    fn parse_mention_none_for_at_without_slug() {
849        assert!(parse_mention("see you @ 5pm").is_none());
850    }
851
852    #[test]
853    fn parse_mention_none_for_double_at() {
854        assert!(parse_mention("@@researcher").is_none());
855    }
856
857    #[test]
858    fn parse_mention_none_for_slug_starting_with_digit() {
859        assert!(parse_mention("@2fast look at this").is_none());
860    }
861
862    #[test]
863    fn parse_mention_at_end_of_string() {
864        let m = parse_mention("summarize @researcher").unwrap();
865        assert_eq!(m.slug, "researcher");
866        assert_eq!(m.start, 10);
867        assert_eq!(m.end, 21);
868    }
869
870    #[test]
871    fn strip_mention_at_start_trims_whitespace() {
872        let clean = strip_mention("@researcher summarize the thread");
873        assert_eq!(clean, "summarize the thread");
874    }
875
876    #[test]
877    fn strip_mention_mid_prompt() {
878        let clean = strip_mention("hey @researcher can you help?");
879        assert_eq!(clean, "hey can you help?");
880    }
881
882    #[test]
883    fn strip_mention_no_mention_returns_original() {
884        let clean = strip_mention("just a regular message");
885        assert_eq!(clean, "just a regular message");
886    }
887
888    #[test]
889    fn resolve_prompt_dispatch_default() {
890        let storage = tmp_storage();
891        match resolve_prompt_dispatch(&storage, "no mention here") {
892            PromptDispatch::Default => {}
893            other => panic!("expected Default, got {:?}", other),
894        }
895    }
896
897    #[test]
898    fn resolve_prompt_dispatch_unknown_agent() {
899        let storage = tmp_storage();
900        match resolve_prompt_dispatch(&storage, "@nonexistent do something") {
901            PromptDispatch::UnknownAgent { slug, .. } => {
902                assert_eq!(slug, "nonexistent");
903            }
904            other => panic!("expected UnknownAgent, got {:?}", other),
905        }
906    }
907
908    #[test]
909    fn resolve_prompt_dispatch_known_agent() {
910        use crate::agent_registry::{upsert_agent, AgentBackendSpec, AgentDefinition};
911        let storage = tmp_storage();
912        let agent = AgentDefinition::new(
913            "researcher",
914            "Researcher",
915            "research assistant",
916            AgentBackendSpec::LocalEngine { model_id: None },
917            "you are a research assistant",
918        );
919        upsert_agent(&storage, agent).unwrap();
920
921        match resolve_prompt_dispatch(&storage, "@researcher summarize the thread") {
922            PromptDispatch::Agent {
923                agent,
924                clean_prompt,
925            } => {
926                assert_eq!(agent.slug, "researcher");
927                assert_eq!(clean_prompt, "summarize the thread");
928            }
929            other => panic!("expected Agent, got {:?}", other),
930        }
931    }
932
933    #[test]
934    fn resolve_prompt_dispatch_disabled_agent() {
935        use crate::agent_registry::{upsert_agent, AgentBackendSpec, AgentDefinition};
936        let storage = tmp_storage();
937        let mut agent = AgentDefinition::new(
938            "disabled-one",
939            "Disabled",
940            "test",
941            AgentBackendSpec::LocalEngine { model_id: None },
942            "test",
943        );
944        agent.enabled = false;
945        upsert_agent(&storage, agent).unwrap();
946
947        match resolve_prompt_dispatch(&storage, "@disabled-one hello") {
948            PromptDispatch::UnknownAgent { slug, .. } => {
949                assert_eq!(slug, "disabled-one");
950            }
951            other => panic!("expected UnknownAgent for disabled agent, got {:?}", other),
952        }
953    }
954}