1use std::fs;
35use std::path::{Path, PathBuf};
36
37use serde::{Deserialize, Serialize};
38
39pub use crate::chat_agents::OutcomeSharingPolicy as OutcomeSharing;
46
47pub const SENSITIVITY_PUBLIC: u8 = 0;
53
54pub const SENSITIVITY_LOCAL_DEFAULT: u8 = u8::MAX;
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum McpTransport {
68 Tcp { host: String, port: u16 },
70 Http {
72 url: String,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
76 credential_id: Option<String>,
77 },
78 Stdio { command: String, args: Vec<String> },
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(rename_all = "snake_case")]
87pub enum AgentBackendSpec {
88 LocalEngine { model_id: Option<String> },
91 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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
144pub struct AgentSemanticProfile {
145 #[serde(default)]
146 pub tags: Vec<AgentSemanticTag>,
147}
148
149impl AgentSemanticProfile {
150 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 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#[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#[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#[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#[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#[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 #[serde(default)]
240 pub allowed_source_agents: Vec<String>,
241 #[serde(default)]
242 pub default_visibility: ContextVisibility,
243 #[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 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
285pub struct AgentDataPolicy {
286 #[serde(default)]
289 pub allowed_ontology_ids: Vec<String>,
290}
291
292#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362pub struct AgentDefinition {
363 pub slug: String,
365 pub display_name: String,
367 pub description: String,
369 pub backend: AgentBackendSpec,
371 pub system_prompt: String,
373 #[serde(default)]
376 pub allowed_mcp_tools: Vec<String>,
377 #[serde(default)]
379 pub max_sensitivity: u8,
380 #[serde(default)]
382 pub outcome_sharing: OutcomeSharing,
383 #[serde(default)]
386 pub semantic_profile: AgentSemanticProfile,
387 #[serde(default)]
390 pub context_policy: AgentContextPolicy,
391 #[serde(default)]
394 pub data_policy: AgentDataPolicy,
395 #[serde(default)]
398 pub execution_policy: AgentExecutionPolicy,
399 #[serde(default)]
401 pub roster_version: u16,
402 #[serde(default)]
407 pub dag_pipeline_json: String,
408 pub enabled: bool,
410 pub created_at_unix: u64,
412 pub updated_at_unix: u64,
414}
415
416impl AgentDefinition {
417 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 pub fn has_tool(&self, tool: &str) -> bool {
456 self.allowed_mcp_tools.iter().any(|t| t == "*" || t == tool)
457 }
458}
459
460pub 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
503pub 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
518fn 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
533pub 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
553pub 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
564pub fn upsert_agent(storage_root: &Path, agent: AgentDefinition) -> Result<(), String> {
573 upsert_agent_at(storage_root, agent, unix_now())
574}
575
576pub 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 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
596pub 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
668pub 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
679pub 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#[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 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 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 save_blob(dir.path(), " \n");
850 assert_eq!(load_roster(dir.path())[0].slug, "local");
851 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 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 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 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; 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 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 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 save_roster(dir.path(), &[default_local_agent()]).unwrap();
971 remove_agent(dir.path(), "local").unwrap();
972 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 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}