Skip to main content

qualia_client_core/
agent_registry.rs

1//! Per-principal roster of software agents.
2//!
3//! The chat graph is primarily human↔human. A *software agent* is never a
4//! free-standing chat actor — it is always defined **under** a human principal
5//! and is *invoked* into a conversation on that principal's behalf (see
6//! [`crate::chat_agents`], which binds a sub-agent DID to a session). This
7//! module is the durable **roster** of the agents a principal has configured:
8//! their persona, backend, tool allowlist, sensitivity ceiling, and
9//! outcome-sharing posture.
10//!
11//! Agents are diverse in backend (see [`AgentBackendSpec`]):
12//!
13//! - [`AgentBackendSpec::LocalEngine`] — runs in-process on the native
14//!   `p64`/`q42` engine. No outbound traffic; preferred for all work, and the
15//!   only backend suitable for the most sensitive material.
16//! - [`AgentBackendSpec::RemoteMcp`] — reached over an external provider's MCP
17//!   interface (e.g. a hosted Claude / Google / X model). This is opt-in and
18//!   costly, and by default handles only non-sensitive material. **Only the
19//!   *configuration* lives here** — the actual MCP client (transport, calls)
20//!   lives in the sibling `remote_mcp.rs`; this module never performs network
21//!   I/O.
22//!
23//! ## Persistence
24//!
25//! The roster is stored as pretty-printed JSON at
26//! `<storage_root>/Agents/roster.json`, mirroring the load/save-under-a-dir
27//! pattern used by [`crate::social_peers`] and [`crate::node_identity`]. The
28//! filesystem functions take an explicit `storage_root: &Path` so they are
29//! testable against a temporary directory. A missing or empty roster is treated
30//! as un-initialised and yields a roster seeded with a single default local
31//! agent ([`default_local_agent`]); the roster is therefore never observed
32//! empty, and a pure [`load_roster`] never writes to disk.
33
34use std::fs;
35use std::path::{Path, PathBuf};
36
37use serde::{Deserialize, Serialize};
38
39/// Outcome-sharing policy for an agent's processed results.
40///
41/// Re-exported from [`crate::chat_agents`] so a roster entry carries exactly the
42/// same shape (visibility owner-only / participants / specific DIDs,
43/// `share_provenance`, `share_model_attribution`, `allow_peer_llm_context`,
44/// `allowed_dids`) that the group-chat layer already understands.
45pub use crate::chat_agents::OutcomeSharingPolicy as OutcomeSharing;
46
47/// Sensitivity scale floor: public / non-sensitive material only.
48///
49/// `max_sensitivity` on an [`AgentDefinition`] is the *ceiling* of what an agent
50/// may handle: `0` = public, higher values = progressively more sensitive
51/// material the principal permits this agent to see.
52pub const SENSITIVITY_PUBLIC: u8 = 0;
53
54/// Default sensitivity ceiling for a fully-local agent.
55///
56/// A local agent runs in-process with no outbound traffic, so it may handle the
57/// principal's most sensitive material. Remote agents should be given a
58/// deliberately lower ceiling by the principal.
59pub const SENSITIVITY_LOCAL_DEFAULT: u8 = u8::MAX;
60
61/// How a [`AgentBackendSpec::RemoteMcp`] agent's MCP server is reached.
62///
63/// This is configuration only; the connection is made by the sibling
64/// `remote_mcp.rs`, never by this module.
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum McpTransport {
68    /// A raw TCP endpoint (`host:port`).
69    Tcp { host: String, port: u16 },
70    /// A streamable-HTTP MCP endpoint.
71    Http {
72        url: String,
73        /// Optional OS-keychain connection ID. The bearer token itself is
74        /// never represented in the roster.
75        #[serde(default, skip_serializing_if = "Option::is_none")]
76        credential_id: Option<String>,
77    },
78    /// A locally-launched MCP server spoken to over stdio.
79    Stdio { command: String, args: Vec<String> },
80}
81
82/// Which inference backend an agent uses.
83///
84/// Local is preferred; remote is opt-in and metered.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum AgentBackendSpec {
88    /// The native in-process engine. `model_id = None` means "use the
89    /// principal's currently-active model"; `Some` pins a specific model.
90    LocalEngine { model_id: Option<String> },
91    /// An external provider reached over its MCP interface.
92    ///
93    /// - `endpoint` — human-readable label / base address of the provider.
94    /// - `transport` — how the MCP client actually connects (see
95    ///   [`McpTransport`]).
96    /// - `infer_tool` — the MCP tool name to call for inference; `None` lets the
97    ///   client pick its default.
98    /// - `model` — the remote model identifier to request; `None` uses the
99    ///   provider's default.
100    /// - `supports_system_role` — declared tool-schema capability: does the
101    ///   inference tool accept a dedicated `system` argument? `None` means
102    ///   undeclared — the client discovers it via `tools/list` or flattens.
103    RemoteMcp {
104        endpoint: String,
105        transport: McpTransport,
106        infer_tool: Option<String>,
107        model: Option<String>,
108        #[serde(default)]
109        supports_system_role: Option<bool>,
110    },
111}
112
113/// The role played by a semantic tag in an agent's pointed study graph.
114/// Tags are declarative grounding hints and never confer data/tool authority.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub enum AgentSemanticFacet {
118    Classification,
119    Specialisation,
120    Geography,
121    Language,
122    Method,
123    Dataset,
124    Tool,
125    Constraint,
126}
127
128/// An ontology-addressable point in the agent's declared study graph.
129/// `broader_iri` links a specialization to its selected parent, giving a
130/// bounded path such as Researcher → History → Australian History.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132pub struct AgentSemanticTag {
133    pub iri: String,
134    pub label: String,
135    pub facet: AgentSemanticFacet,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub broader_iri: Option<String>,
138}
139
140/// Ontology-linked profile used to narrow routing and disclose an agent's
141/// declared scope.  The profile may recommend tools/datasets but permissions
142/// and tool allowlists remain separately authoritative.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
144pub struct AgentSemanticProfile {
145    #[serde(default)]
146    pub tags: Vec<AgentSemanticTag>,
147}
148
149impl AgentSemanticProfile {
150    /// Short human/model-readable focus terms used by ontology routing.  This
151    /// is bounded and cold-path only; it never loads or exports a dataset.
152    pub fn focus_terms(&self) -> Vec<String> {
153        self.tags
154            .iter()
155            .map(|tag| tag.label.trim().to_ascii_lowercase())
156            .filter(|label| !label.is_empty())
157            .take(32)
158            .collect()
159    }
160
161    /// Agent briefing.
162    pub fn briefing(&self) -> String {
163        if self.tags.is_empty() {
164            return String::new();
165        }
166        let mut lines = Vec::new();
167        lines.push("[Agent semantic study profile — use as a bounded routing focus; it does not grant permissions]".to_string());
168        for tag in self.tags.iter().take(32) {
169            let facet = match tag.facet {
170                AgentSemanticFacet::Classification => "classification",
171                AgentSemanticFacet::Specialisation => "specialisation",
172                AgentSemanticFacet::Geography => "geography",
173                AgentSemanticFacet::Language => "language",
174                AgentSemanticFacet::Method => "method",
175                AgentSemanticFacet::Dataset => "dataset",
176                AgentSemanticFacet::Tool => "tool capability",
177                AgentSemanticFacet::Constraint => "constraint",
178            };
179            lines.push(format!("- {facet}: {} ({})", tag.label, tag.iri));
180        }
181        lines.join("\n")
182    }
183}
184
185/// Conversation material an agent is permitted to receive for a turn.
186///
187/// This is deliberately narrower than the session itself.  Selecting an agent
188/// in a conversation never grants it the entire transcript by implication.
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
190#[serde(rename_all = "snake_case")]
191pub enum ConversationAccess {
192    None,
193    #[default]
194    AddressedMessage,
195    SessionSummary,
196    PermittedHistory,
197}
198
199/// Whether graph/retrieval results may be included in an agent context manifest.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
201#[serde(rename_all = "snake_case")]
202pub enum RetrievalAccess {
203    None,
204    #[default]
205    PermittedScopes,
206}
207
208/// Whether files selected in the conversation may enter an agent context manifest.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
210#[serde(rename_all = "snake_case")]
211pub enum AttachmentAccess {
212    None,
213    MetadataOnly,
214    #[default]
215    PermittedAttachments,
216}
217
218/// Default visibility of an agent's completed answer.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
220#[serde(rename_all = "snake_case")]
221pub enum ContextVisibility {
222    #[default]
223    OwnerOnly,
224    NamedAgents,
225    SessionParticipants,
226}
227
228/// Directional context contract for a named agent.
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct AgentContextPolicy {
231    #[serde(default)]
232    pub conversation: ConversationAccess,
233    #[serde(default)]
234    pub retrieval: RetrievalAccess,
235    #[serde(default)]
236    pub attachments: AttachmentAccess,
237    /// Stable roster slugs whose *completed summaries* may be supplied to this agent.
238    /// Empty means no other agent output is included.
239    #[serde(default)]
240    pub allowed_source_agents: Vec<String>,
241    #[serde(default)]
242    pub default_visibility: ContextVisibility,
243    /// Stable roster slugs permitted to receive this agent's output as context.
244    #[serde(default)]
245    pub allowed_recipient_agents: Vec<String>,
246    #[serde(default)]
247    pub may_share_raw_prompt: bool,
248    #[serde(default)]
249    pub may_share_attachments: bool,
250    #[serde(default)]
251    pub may_share_graph_records: bool,
252    #[serde(default = "default_share_provenance")]
253    pub may_share_provenance: bool,
254    /// Require a person to review a turn-specific context manifest before dispatch.
255    #[serde(default)]
256    pub require_turn_confirmation: bool,
257}
258
259const fn default_share_provenance() -> bool {
260    true
261}
262
263impl Default for AgentContextPolicy {
264    fn default() -> Self {
265        Self {
266            conversation: ConversationAccess::AddressedMessage,
267            retrieval: RetrievalAccess::PermittedScopes,
268            attachments: AttachmentAccess::PermittedAttachments,
269            allowed_source_agents: Vec::new(),
270            default_visibility: ContextVisibility::OwnerOnly,
271            allowed_recipient_agents: Vec::new(),
272            may_share_raw_prompt: false,
273            may_share_attachments: false,
274            may_share_graph_records: false,
275            may_share_provenance: true,
276            require_turn_confirmation: false,
277        }
278    }
279}
280
281/// Per-agent data boundary.  An empty allowlist means the agent may use only
282/// the ontology scopes already admitted to its chat session; a non-empty list
283/// further intersects that session scope.  It never widens access.
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
285pub struct AgentDataPolicy {
286    /// Installed ontology/data-source IDs this agent may retrieve from.
287    /// Stable IDs are used rather than labels so a rename cannot widen access.
288    #[serde(default)]
289    pub allowed_ontology_ids: Vec<String>,
290}
291
292/// Residency preference for a local model selected by an agent.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
294#[serde(rename_all = "snake_case")]
295pub enum ModelResidencyPreference {
296    #[default]
297    OnDemand,
298    KeepWarm,
299    Pinned,
300}
301
302/// Scheduler priority for work requested through an agent.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
304#[serde(rename_all = "snake_case")]
305pub enum AgentJobPriority {
306    #[default]
307    Interactive,
308    Normal,
309    Background,
310}
311
312/// Consent required before an agent may use its configured remote backend.
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
314#[serde(rename_all = "snake_case")]
315pub enum RemoteConsentPolicy {
316    Never,
317    #[default]
318    PerTurn,
319    Preapproved,
320}
321
322/// Per-agent scheduler and placement policy.  It describes a preference, not a
323/// reservation: the runtime may decline a pinned/keep-warm request when the
324/// caller's device budget cannot safely admit it.
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326pub struct AgentExecutionPolicy {
327    #[serde(default)]
328    pub residency: ModelResidencyPreference,
329    #[serde(default)]
330    pub priority: AgentJobPriority,
331    #[serde(default = "default_max_parallel_turns")]
332    pub max_parallel_turns: u8,
333    #[serde(default)]
334    pub remote_consent: RemoteConsentPolicy,
335    #[serde(default)]
336    pub allow_scheduled_runs: bool,
337}
338
339const fn default_max_parallel_turns() -> u8 {
340    1
341}
342
343impl Default for AgentExecutionPolicy {
344    fn default() -> Self {
345        Self {
346            residency: ModelResidencyPreference::OnDemand,
347            priority: AgentJobPriority::Interactive,
348            max_parallel_turns: 1,
349            remote_consent: RemoteConsentPolicy::PerTurn,
350            allow_scheduled_runs: false,
351        }
352    }
353}
354
355/// A single agent in a principal's roster.
356///
357/// Keyed by [`slug`](AgentDefinition::slug), a stable identifier that survives
358/// renames of `display_name`. All fields are public so callers (e.g. the
359/// command/API layer) can build and edit definitions directly; use
360/// [`AgentDefinition::new`] for a conservatively-defaulted, timestamped entry.
361#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct AgentDefinition {
363    /// Stable identifier for this agent (unique within the roster).
364    pub slug: String,
365    /// Human-friendly label shown in the UI.
366    pub display_name: String,
367    /// Free-form description of what the agent is for.
368    pub description: String,
369    /// The inference backend this agent uses.
370    pub backend: AgentBackendSpec,
371    /// The agent's persona / system prompt.
372    pub system_prompt: String,
373    /// MCP tool allowlist. Empty = no tools allowed; a single `"*"` entry = all
374    /// tools allowed. See [`AgentDefinition::has_tool`].
375    #[serde(default)]
376    pub allowed_mcp_tools: Vec<String>,
377    /// Ceiling of material sensitivity this agent may handle (`0` = public).
378    #[serde(default)]
379    pub max_sensitivity: u8,
380    /// How this agent's processed outcomes may be shared with peers.
381    #[serde(default)]
382    pub outcome_sharing: OutcomeSharing,
383    /// Pointed ontology-linked study graph: classification, specialization,
384    /// geographic/language scope, methods, datasets, tools and constraints.
385    #[serde(default)]
386    pub semantic_profile: AgentSemanticProfile,
387    /// Fine-grained, directional context contract.  Missing in pre-existing
388    /// roster files means the safe default above, preserving compatibility.
389    #[serde(default)]
390    pub context_policy: AgentContextPolicy,
391    /// Narrower per-agent data-source boundary, intersected with session
392    /// permissions at inference time.
393    #[serde(default)]
394    pub data_policy: AgentDataPolicy,
395    /// Model residency and remote-consent preferences, interpreted by the job
396    /// scheduler rather than by the inference hot path.
397    #[serde(default)]
398    pub execution_policy: AgentExecutionPolicy,
399    /// Persisted schema marker for future non-breaking roster migrations.
400    #[serde(default)]
401    pub roster_version: u16,
402    /// Optional DAG pipeline definition (JSON) for multi-step agent turns.
403    /// When present, the agent-turn handler executes the pipeline instead
404    /// of a single inference turn. The JSON format matches `DagPipeline`'s
405    /// CBOR serialization. Empty string = no pipeline (single-turn).
406    #[serde(default)]
407    pub dag_pipeline_json: String,
408    /// Whether the agent is currently available for invocation.
409    pub enabled: bool,
410    /// Unix seconds at which this agent was first created.
411    pub created_at_unix: u64,
412    /// Unix seconds at which this agent was last written.
413    pub updated_at_unix: u64,
414}
415
416impl AgentDefinition {
417    /// Construct a new agent with a conservative default posture: empty tool
418    /// allowlist, public-only sensitivity ([`SENSITIVITY_PUBLIC`]), default
419    /// (owner-only) outcome sharing, and `enabled = true`. Both timestamps are
420    /// stamped with the current wall-clock. Raise the sensitivity ceiling or
421    /// widen the allowlist deliberately after construction.
422    pub fn new(
423        slug: impl Into<String>,
424        display_name: impl Into<String>,
425        description: impl Into<String>,
426        backend: AgentBackendSpec,
427        system_prompt: impl Into<String>,
428    ) -> Self {
429        let now = unix_now();
430        Self {
431            slug: slug.into(),
432            display_name: display_name.into(),
433            description: description.into(),
434            backend,
435            system_prompt: system_prompt.into(),
436            allowed_mcp_tools: Vec::new(),
437            max_sensitivity: SENSITIVITY_PUBLIC,
438            outcome_sharing: OutcomeSharing::default(),
439            semantic_profile: AgentSemanticProfile::default(),
440            context_policy: AgentContextPolicy::default(),
441            data_policy: AgentDataPolicy::default(),
442            execution_policy: AgentExecutionPolicy::default(),
443            roster_version: 1,
444            dag_pipeline_json: String::new(),
445            enabled: true,
446            created_at_unix: now,
447            updated_at_unix: now,
448        }
449    }
450
451    /// Whether this agent is permitted to use the MCP tool named `tool`.
452    ///
453    /// An empty allowlist permits nothing; a `"*"` entry permits everything;
454    /// otherwise the tool must be listed by exact name.
455    pub fn has_tool(&self, tool: &str) -> bool {
456        self.allowed_mcp_tools.iter().any(|t| t == "*" || t == tool)
457    }
458}
459
460// ---------------------------------------------------------------------------
461// Seed
462// ---------------------------------------------------------------------------
463
464/// The default local agent that seeds an un-initialised roster.
465///
466/// Slug `"local"`, a fully-local ([`AgentBackendSpec::LocalEngine`] with no
467/// pinned model) backend, no MCP tools, the maximum sensitivity ceiling
468/// ([`SENSITIVITY_LOCAL_DEFAULT`], safe because nothing leaves the device), and
469/// enabled. Timestamps are stamped with the current wall-clock.
470pub fn default_local_agent() -> AgentDefinition {
471    let now = unix_now();
472    AgentDefinition {
473        slug: "local".to_string(),
474        display_name: "Your local agent".to_string(),
475        description: "Runs entirely on this device via the native Qualia inference engine. \
476             No data leaves the principal's control, so it is the preferred agent for all \
477             work — especially anything sensitive."
478            .to_string(),
479        backend: AgentBackendSpec::LocalEngine { model_id: None },
480        system_prompt: "You are a software agent acting on behalf of, and under the authority \
481             of, your human principal. You run locally on the principal's own device via the \
482             native engine; their data does not leave their control. Ground every answer in the \
483             principal's own records and cite the provenance you relied on; if you cannot ground \
484             a claim, say so plainly rather than inventing one. Spend the principal's time and \
485             resources only on the purpose they have declared, and defer to their explicit \
486             decisions at all times."
487            .to_string(),
488        allowed_mcp_tools: Vec::new(),
489        max_sensitivity: SENSITIVITY_LOCAL_DEFAULT,
490        outcome_sharing: OutcomeSharing::default(),
491        semantic_profile: AgentSemanticProfile::default(),
492        context_policy: AgentContextPolicy::default(),
493        data_policy: AgentDataPolicy::default(),
494        execution_policy: AgentExecutionPolicy::default(),
495        roster_version: 1,
496        dag_pipeline_json: String::new(),
497        enabled: true,
498        created_at_unix: now,
499        updated_at_unix: now,
500    }
501}
502
503// ---------------------------------------------------------------------------
504// Session binding
505// ---------------------------------------------------------------------------
506
507/// Derive the deterministic sub-agent DID under which an agent acts in a
508/// session, scoped to `principal_did` + `session_id`.
509///
510/// A thin wrapper over [`crate::chat_agents::compile_sub_agent_did`] — the same
511/// derivation the chat layer uses, so a roster agent and its in-session
512/// sub-agent share one DID. Writing the session's `agent_config.json` is the
513/// caller's responsibility; this only computes the DID.
514pub fn bind_agent_did(principal_did: &str, session_id: &str) -> String {
515    crate::chat_agents::compile_sub_agent_did(principal_did, session_id)
516}
517
518// ---------------------------------------------------------------------------
519// Persistence
520// ---------------------------------------------------------------------------
521
522fn roster_path(storage_root: &Path) -> PathBuf {
523    storage_root.join("Agents").join("roster.json")
524}
525
526fn unix_now() -> u64 {
527    std::time::SystemTime::now()
528        .duration_since(std::time::UNIX_EPOCH)
529        .unwrap_or_default()
530        .as_secs()
531}
532
533/// Load the principal's agent roster from `<storage_root>/Agents/roster.json`.
534///
535/// If the file is missing, empty, unreadable, unparseable, or parses to an empty
536/// list, a roster seeded with a single [`default_local_agent`] is returned. This
537/// is a **pure read**: it never writes to disk (the seed exists only in the
538/// returned value until something is explicitly saved).
539pub fn load_roster(storage_root: &Path) -> Vec<AgentDefinition> {
540    let roster = fs::read_to_string(roster_path(storage_root))
541        .ok()
542        .filter(|t| !t.trim().is_empty())
543        .and_then(|t| serde_json::from_str::<Vec<AgentDefinition>>(&t).ok())
544        .unwrap_or_default();
545
546    if roster.is_empty() {
547        vec![default_local_agent()]
548    } else {
549        roster
550    }
551}
552
553/// Persist `roster` to `<storage_root>/Agents/roster.json` as pretty JSON,
554/// creating the `Agents` directory if needed.
555pub fn save_roster(storage_root: &Path, roster: &[AgentDefinition]) -> Result<(), String> {
556    let path = roster_path(storage_root);
557    if let Some(parent) = path.parent() {
558        fs::create_dir_all(parent).map_err(|e| e.to_string())?;
559    }
560    let text = serde_json::to_string_pretty(roster).map_err(|e| e.to_string())?;
561    fs::write(path, text).map_err(|e| e.to_string())
562}
563
564/// Insert or update `agent` in the stored roster, keyed by
565/// [`slug`](AgentDefinition::slug), then persist.
566///
567/// If an agent with the same slug exists it is replaced in place (preserving its
568/// original `created_at_unix`); otherwise `agent` is appended. `updated_at_unix`
569/// is bumped to the current wall-clock in both cases. Because [`load_roster`]
570/// seeds the default local agent when the store is empty, the first upsert of a
571/// *new* agent also materialises that seed to disk.
572pub fn upsert_agent(storage_root: &Path, agent: AgentDefinition) -> Result<(), String> {
573    upsert_agent_at(storage_root, agent, unix_now())
574}
575
576/// [`upsert_agent`] with an explicit `now_unix` timestamp, for deterministic
577/// testing and callers that already hold a clock reading.
578pub fn upsert_agent_at(
579    storage_root: &Path,
580    mut agent: AgentDefinition,
581    now_unix: u64,
582) -> Result<(), String> {
583    validate_agent(&agent)?;
584    agent.updated_at_unix = now_unix;
585    let mut roster = load_roster(storage_root);
586    if let Some(slot) = roster.iter_mut().find(|a| a.slug == agent.slug) {
587        // A stable slug keeps its original creation time across edits.
588        agent.created_at_unix = slot.created_at_unix;
589        *slot = agent;
590    } else {
591        roster.push(agent);
592    }
593    save_roster(storage_root, &roster)
594}
595
596/// Validate values that cross the roster/UI boundary.  This is intentionally
597/// a cold-path check: it protects stable mention keys and prevents a malformed
598/// execution preference from becoming a scheduler ambiguity.
599pub fn validate_agent(agent: &AgentDefinition) -> Result<(), String> {
600    let slug = agent.slug.trim();
601    if slug.is_empty() || slug.len() > 64 {
602        return Err("agent slug must contain 1-64 characters".to_string());
603    }
604    if !slug
605        .bytes()
606        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
607    {
608        return Err(
609            "agent slug may contain only lowercase letters, digits, and hyphens".to_string(),
610        );
611    }
612    if agent.display_name.trim().is_empty() || agent.display_name.chars().count() > 96 {
613        return Err("agent name must contain 1-96 characters".to_string());
614    }
615    if agent.system_prompt.len() > 32 * 1024 {
616        return Err("agent instructions exceed the 32 KiB limit".to_string());
617    }
618    if agent.execution_policy.max_parallel_turns == 0
619        || agent.execution_policy.max_parallel_turns > 4
620    {
621        return Err("agent max_parallel_turns must be between 1 and 4".to_string());
622    }
623    if agent.semantic_profile.tags.len() > 32 {
624        return Err("agent semantic profile supports at most 32 tags".to_string());
625    }
626    for tag in &agent.semantic_profile.tags {
627        if tag.iri.trim().is_empty() || tag.iri.len() > 256 {
628            return Err(
629                "each agent semantic tag needs an IRI of at most 256 characters".to_string(),
630            );
631        }
632        if tag.label.trim().is_empty() || tag.label.chars().count() > 96 {
633            return Err("each agent semantic tag needs a label of 1-96 characters".to_string());
634        }
635        if tag
636            .broader_iri
637            .as_deref()
638            .is_some_and(|iri| iri.trim().is_empty() || iri.len() > 256)
639        {
640            return Err("agent semantic tag broader IRI is invalid".to_string());
641        }
642    }
643    if agent.data_policy.allowed_ontology_ids.len() > 32 {
644        return Err("agent data policy supports at most 32 ontology IDs".to_string());
645    }
646    if agent
647        .data_policy
648        .allowed_ontology_ids
649        .iter()
650        .any(|id| id.trim().is_empty() || id.len() > 160 || id.contains(['/', '\\', '\0']))
651    {
652        return Err("agent data policy has an invalid ontology ID".to_string());
653    }
654    match &agent.backend {
655        AgentBackendSpec::LocalEngine { model_id } => {
656            if model_id.as_deref().is_some_and(|id| id.trim().is_empty()) {
657                return Err("local agent model_id must not be blank".to_string());
658            }
659        }
660        AgentBackendSpec::RemoteMcp { endpoint, .. } if endpoint.trim().is_empty() => {
661            return Err("remote agent endpoint is required".to_string());
662        }
663        AgentBackendSpec::RemoteMcp { .. } => {}
664    }
665    Ok(())
666}
667
668/// Remove the agent with the given `slug` from the stored roster, then persist.
669///
670/// Removing an absent slug is a no-op success. Note that removing the *last*
671/// agent leaves an empty store, which [`load_roster`] will re-seed with the
672/// default local agent on the next read.
673pub fn remove_agent(storage_root: &Path, slug: &str) -> Result<(), String> {
674    let mut roster = load_roster(storage_root);
675    roster.retain(|a| a.slug != slug);
676    save_roster(storage_root, &roster)
677}
678
679/// Fetch a single agent by `slug`, if present in the (possibly seeded) roster.
680pub fn get_agent(storage_root: &Path, slug: &str) -> Option<AgentDefinition> {
681    load_roster(storage_root)
682        .into_iter()
683        .find(|a| a.slug == slug)
684}
685
686// ---------------------------------------------------------------------------
687// Tests — filesystem is confined to a tempdir; no network.
688// ---------------------------------------------------------------------------
689
690#[cfg(test)]
691mod tests {
692    use super::*;
693    use tempfile::tempdir;
694
695    fn remote(slug: &str, transport: McpTransport) -> AgentDefinition {
696        AgentDefinition {
697            slug: slug.to_string(),
698            display_name: format!("Remote {slug}"),
699            description: "external provider".to_string(),
700            backend: AgentBackendSpec::RemoteMcp {
701                endpoint: "https://provider.example/mcp".to_string(),
702                transport,
703                infer_tool: Some("infer".to_string()),
704                model: Some("big-model".to_string()),
705                supports_system_role: None,
706            },
707            system_prompt: "persona".to_string(),
708            allowed_mcp_tools: vec!["search".to_string()],
709            max_sensitivity: SENSITIVITY_PUBLIC,
710            outcome_sharing: OutcomeSharing::default(),
711            semantic_profile: AgentSemanticProfile::default(),
712            context_policy: AgentContextPolicy::default(),
713            data_policy: AgentDataPolicy::default(),
714            execution_policy: AgentExecutionPolicy::default(),
715            roster_version: 1,
716            dag_pipeline_json: String::new(),
717            enabled: true,
718            created_at_unix: 100,
719            updated_at_unix: 100,
720        }
721    }
722
723    #[test]
724    fn default_local_agent_shape() {
725        let a = default_local_agent();
726        assert_eq!(a.slug, "local");
727        assert_eq!(a.display_name, "Your local agent");
728        assert!(matches!(
729            a.backend,
730            AgentBackendSpec::LocalEngine { model_id: None }
731        ));
732        assert!(a.enabled);
733        assert!(a.allowed_mcp_tools.is_empty());
734        assert_eq!(a.max_sensitivity, SENSITIVITY_LOCAL_DEFAULT);
735        // Empty allowlist ⇒ no tool is permitted.
736        assert!(!a.has_tool("anything"));
737    }
738
739    #[test]
740    fn new_uses_conservative_defaults() {
741        let a = AgentDefinition::new(
742            "claude",
743            "Claude",
744            "remote",
745            AgentBackendSpec::RemoteMcp {
746                endpoint: "e".to_string(),
747                transport: McpTransport::Http {
748                    url: "https://x/mcp".to_string(),
749                    credential_id: None,
750                },
751                infer_tool: None,
752                model: None,
753                supports_system_role: None,
754            },
755            "persona",
756        );
757        assert!(a.enabled);
758        assert!(a.allowed_mcp_tools.is_empty());
759        assert_eq!(a.max_sensitivity, SENSITIVITY_PUBLIC);
760        assert_eq!(a.outcome_sharing, OutcomeSharing::default());
761        assert_eq!(a.context_policy, AgentContextPolicy::default());
762        assert_eq!(a.execution_policy, AgentExecutionPolicy::default());
763        assert!(a.semantic_profile.tags.is_empty());
764        assert_eq!(a.created_at_unix, a.updated_at_unix);
765    }
766
767    #[test]
768    fn legacy_roster_without_new_policies_loads_safe_defaults() {
769        let dir = tempdir().unwrap();
770        save_blob(
771            dir.path(),
772            r#"[{"slug":"legacy","display_name":"Legacy","description":"x","backend":{"local_engine":{"model_id":null}},"system_prompt":"","allowed_mcp_tools":[],"max_sensitivity":0,"outcome_sharing":{"visibility":"owner_only","share_provenance":true,"share_model_attribution":false,"allow_peer_llm_context":false,"allowed_dids":[]},"enabled":true,"created_at_unix":1,"updated_at_unix":1}]"#,
773        );
774        let legacy = get_agent(dir.path(), "legacy").unwrap();
775        assert_eq!(legacy.context_policy, AgentContextPolicy::default());
776        assert_eq!(legacy.execution_policy, AgentExecutionPolicy::default());
777        assert_eq!(legacy.roster_version, 0);
778    }
779
780    #[test]
781    fn rejects_invalid_stable_slug_and_parallelism() {
782        let dir = tempdir().unwrap();
783        let mut a = default_local_agent();
784        a.slug = "Not stable".to_string();
785        assert!(upsert_agent(dir.path(), a).is_err());
786
787        let mut a = default_local_agent();
788        a.execution_policy.max_parallel_turns = 5;
789        assert!(upsert_agent(dir.path(), a).is_err());
790    }
791
792    #[test]
793    fn semantic_profile_is_bounded_and_produces_routing_focus() {
794        let mut agent = default_local_agent();
795        agent.semantic_profile.tags = vec![
796            AgentSemanticTag {
797                iri: "q42:Researcher".to_string(),
798                label: "Researcher".to_string(),
799                facet: AgentSemanticFacet::Classification,
800                broader_iri: None,
801            },
802            AgentSemanticTag {
803                iri: "q42:AustralianHistory".to_string(),
804                label: "Australian History".to_string(),
805                facet: AgentSemanticFacet::Specialisation,
806                broader_iri: Some("q42:History".to_string()),
807            },
808        ];
809        assert_eq!(
810            agent.semantic_profile.focus_terms(),
811            vec!["researcher", "australian history"]
812        );
813        assert!(agent
814            .semantic_profile
815            .briefing()
816            .contains("Australian History"));
817        validate_agent(&agent).unwrap();
818    }
819
820    #[test]
821    fn has_tool_honors_membership_and_wildcard() {
822        let mut a = default_local_agent();
823        assert!(!a.has_tool("read"));
824
825        a.allowed_mcp_tools = vec!["read".to_string(), "write".to_string()];
826        assert!(a.has_tool("read"));
827        assert!(a.has_tool("write"));
828        assert!(!a.has_tool("delete"));
829
830        a.allowed_mcp_tools = vec!["*".to_string()];
831        assert!(a.has_tool("read"));
832        assert!(a.has_tool("literally-anything"));
833    }
834
835    #[test]
836    fn load_roster_seeds_when_missing_and_does_not_write() {
837        let dir = tempdir().unwrap();
838        let roster = load_roster(dir.path());
839        assert_eq!(roster.len(), 1);
840        assert_eq!(roster[0].slug, "local");
841        // A pure load must not create the file.
842        assert!(!roster_path(dir.path()).exists());
843    }
844
845    #[test]
846    fn load_roster_seeds_on_empty_and_empty_array_files() {
847        let dir = tempdir().unwrap();
848        // Whitespace-only content.
849        save_blob(dir.path(), "   \n");
850        assert_eq!(load_roster(dir.path())[0].slug, "local");
851        // An explicitly empty array.
852        save_blob(dir.path(), "[]");
853        assert_eq!(load_roster(dir.path()).len(), 1);
854        assert_eq!(load_roster(dir.path())[0].slug, "local");
855    }
856
857    fn save_blob(root: &Path, blob: &str) {
858        let path = roster_path(root);
859        fs::create_dir_all(path.parent().unwrap()).unwrap();
860        fs::write(path, blob).unwrap();
861    }
862
863    #[test]
864    fn save_then_load_roundtrip_all_transports() {
865        let dir = tempdir().unwrap();
866        let roster = vec![
867            default_local_agent(),
868            remote(
869                "tcp-agent",
870                McpTransport::Tcp {
871                    host: "10.0.0.1".to_string(),
872                    port: 9000,
873                },
874            ),
875            remote(
876                "http-agent",
877                McpTransport::Http {
878                    url: "https://x/mcp".to_string(),
879                    credential_id: None,
880                },
881            ),
882            remote(
883                "stdio-agent",
884                McpTransport::Stdio {
885                    command: "mcp-server".to_string(),
886                    args: vec!["--flag".to_string(), "v".to_string()],
887                },
888            ),
889        ];
890        save_roster(dir.path(), &roster).unwrap();
891        let back = load_roster(dir.path());
892        assert_eq!(back, roster);
893    }
894
895    #[test]
896    fn upsert_appends_new_then_replaces_by_slug() {
897        let dir = tempdir().unwrap();
898
899        // Append a new agent onto the (seeded) store.
900        let mut a = remote(
901            "worker",
902            McpTransport::Http {
903                url: "u".to_string(),
904                credential_id: None,
905            },
906        );
907        a.created_at_unix = 100;
908        a.updated_at_unix = 100;
909        upsert_agent_at(dir.path(), a, 555).unwrap();
910
911        let roster = load_roster(dir.path());
912        // Seed 'local' materialised + the new 'worker'.
913        assert!(roster.iter().any(|x| x.slug == "local"));
914        let stored = get_agent(dir.path(), "worker").unwrap();
915        assert_eq!(stored.created_at_unix, 100, "created preserved on append");
916        assert_eq!(stored.updated_at_unix, 555, "updated bumped to now_unix");
917
918        // Replace by slug: created preserved from the stored entry, updated bumped.
919        let mut edited = remote(
920            "worker",
921            McpTransport::Http {
922                url: "u2".to_string(),
923                credential_id: None,
924            },
925        );
926        edited.display_name = "renamed".to_string();
927        edited.created_at_unix = 9999; // should be ignored in favour of stored 100
928        upsert_agent_at(dir.path(), edited, 777).unwrap();
929
930        let after = get_agent(dir.path(), "worker").unwrap();
931        assert_eq!(after.display_name, "renamed");
932        assert_eq!(after.created_at_unix, 100, "created preserved on replace");
933        assert_eq!(after.updated_at_unix, 777);
934        // Replacement, not duplication.
935        let count = load_roster(dir.path())
936            .iter()
937            .filter(|x| x.slug == "worker")
938            .count();
939        assert_eq!(count, 1);
940    }
941
942    #[test]
943    fn remove_agent_removes_and_is_noop_for_absent() {
944        let dir = tempdir().unwrap();
945        upsert_agent_at(
946            dir.path(),
947            remote(
948                "gone",
949                McpTransport::Http {
950                    url: "u".to_string(),
951                    credential_id: None,
952                },
953            ),
954            1,
955        )
956        .unwrap();
957        assert!(get_agent(dir.path(), "gone").is_some());
958
959        remove_agent(dir.path(), "gone").unwrap();
960        assert!(get_agent(dir.path(), "gone").is_none());
961
962        // No-op success for an absent slug.
963        remove_agent(dir.path(), "never-existed").unwrap();
964    }
965
966    #[test]
967    fn removing_last_agent_reseeds_local_on_next_load() {
968        let dir = tempdir().unwrap();
969        // Persist just the local seed, then remove it.
970        save_roster(dir.path(), &[default_local_agent()]).unwrap();
971        remove_agent(dir.path(), "local").unwrap();
972        // File now holds an empty list; load re-seeds.
973        let roster = load_roster(dir.path());
974        assert_eq!(roster.len(), 1);
975        assert_eq!(roster[0].slug, "local");
976    }
977
978    #[test]
979    fn get_agent_found_and_missing() {
980        let dir = tempdir().unwrap();
981        // The seeded 'local' is reachable without any prior save.
982        assert!(get_agent(dir.path(), "local").is_some());
983        assert!(get_agent(dir.path(), "nope").is_none());
984    }
985
986    #[test]
987    fn bind_agent_did_matches_chat_layer_and_is_deterministic() {
988        let a = bind_agent_did("did:qualia:root:abc", "sess-1");
989        let b = bind_agent_did("did:qualia:root:abc", "sess-1");
990        assert_eq!(a, b);
991        assert!(a.starts_with("did:qualia:subagent:"));
992        assert_eq!(
993            a,
994            crate::chat_agents::compile_sub_agent_did("did:qualia:root:abc", "sess-1")
995        );
996    }
997}