返回 CodeWhale
profile.rs
根目录 / crates / engine / src / fleet / profile.rs
1 //! Fleet profile vocabulary, local profile discovery, and config-facing aliases.
2
3 use std::collections::BTreeSet;
4 use std::path::{Path, PathBuf};
5
6 use anyhow::{Context, Result, anyhow, bail};
7 use serde::{Deserialize, Serialize};
8
9 use crate::reasoning_preference::ReasoningEffort;
10
11 pub use codewhale_config::{
12 FleetDelegationHints, FleetLoadout, FleetProfile, FleetProfilePermissions, FleetRole, FleetSlot,
13 };
14
15 pub use super::roster::ProfileOrigin;
16
17 pub const WORKSPACE_AGENT_PROFILE_DIR: &str = ".codewhale/agents";
18 pub const PERSONAL_AGENT_PROFILE_DIR: &str = "agents";
19 /// Claude Code agent definitions, read from both the project and the home
20 /// directory (`<workspace>/.claude/agents`, `~/.claude/agents`).
21 pub const CLAUDE_AGENT_DIR: &str = ".claude/agents";
22
23 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
24 pub enum FleetProfileScope {
25 Project,
26 Personal,
27 }
28
29 impl FleetProfileScope {
30 #[must_use]
31 pub fn label(self) -> &'static str {
32 match self {
33 Self::Project => "project",
34 Self::Personal => "personal",
35 }
36 }
37
38 #[must_use]
39 pub fn display_dir(self) -> &'static str {
40 match self {
41 Self::Project => WORKSPACE_AGENT_PROFILE_DIR,
42 Self::Personal => "$CODEWHALE_HOME/agents",
43 }
44 }
45
46 #[must_use]
47 pub fn toggled(self) -> Self {
48 match self {
49 Self::Project => Self::Personal,
50 Self::Personal => Self::Project,
51 }
52 }
53 }
54
55 pub fn personal_agent_profile_dir() -> Result<PathBuf> {
56 #[cfg(any(test, feature = "test-support"))]
57 if !crate::test_support::guarded_environment_provides_state_paths() {
58 return Ok(crate::test_support::unsealed_test_state_root().join(PERSONAL_AGENT_PROFILE_DIR));
59 }
60 Ok(codewhale_config::codewhale_home()?.join(PERSONAL_AGENT_PROFILE_DIR))
61 }
62
63 pub fn agent_profile_dir_for_scope(scope: FleetProfileScope, workspace: &Path) -> Result<PathBuf> {
64 match scope {
65 FleetProfileScope::Project => Ok(workspace.join(WORKSPACE_AGENT_PROFILE_DIR)),
66 FleetProfileScope::Personal => personal_agent_profile_dir(),
67 }
68 }
69
70 pub const MAX_PROFILE_DOCUMENT_BYTES: usize = 1024 * 1024;
71
72 #[derive(Debug, thiserror::Error)]
73 #[error("Profile source changed; reopen {} before saving", path.display())]
74 pub struct AgentProfileWriteConflict {
75 pub path: PathBuf,
76 }
77
78 #[derive(Debug, thiserror::Error)]
79 #[error("Profile {id} is already defined in {}", path.display())]
80 pub struct AgentProfileIdentityConflict {
81 pub id: String,
82 pub path: PathBuf,
83 }
84
85 #[derive(Debug, thiserror::Error)]
86 #[error("Profile save outcome is unconfirmed for {}; read the file before saving again: {source}", path.display())]
87 pub struct AgentProfileWriteUnconfirmed {
88 pub path: PathBuf,
89 #[source]
90 source: std::io::Error,
91 }
92
93 fn profile_document_location(
94 scope: FleetProfileScope,
95 workspace: &Path,
96 path: &Path,
97 ) -> Result<(PathBuf, PathBuf)> {
98 let directory = agent_profile_dir_for_scope(scope, workspace)?;
99 let root = match scope {
100 FleetProfileScope::Project => workspace.to_path_buf(),
101 FleetProfileScope::Personal => directory
102 .parent()
103 .context("Personal profile directory has no state root")?
104 .to_path_buf(),
105 };
106 anyhow::ensure!(
107 root.is_absolute() && path.parent() == Some(directory.as_path()) && is_agent_document(path),
108 "Profile source is outside its selected directory"
109 );
110 let relative = path.strip_prefix(&root)?.to_path_buf();
111 anyhow::ensure!(
112 codewhale_util::files::path_is_confined(&relative),
113 "Profile source is outside its selected directory"
114 );
115 Ok((root, relative))
116 }
117
118 fn read_profile_document_file(
119 file: &codewhale_util::files::WorkspaceFile,
120 ) -> Result<Option<String>> {
121 use std::io::Read as _;
122 let handle = match file.open_file_shared() {
123 Ok(file) => file,
124 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
125 Err(error) => return Err(error.into()),
126 };
127 let mut raw = String::new();
128 handle
129 .take((MAX_PROFILE_DOCUMENT_BYTES + 1) as u64)
130 .read_to_string(&mut raw)?;
131 anyhow::ensure!(
132 raw.len() <= MAX_PROFILE_DOCUMENT_BYTES,
133 "Profile document exceeds the one MiB editing limit"
134 );
135 Ok(Some(raw))
136 }
137
138 pub fn read_agent_profile_document(
139 scope: FleetProfileScope,
140 workspace: &Path,
141 path: &Path,
142 ) -> Result<Option<String>> {
143 let (root, relative) = profile_document_location(scope, workspace, path)?;
144 read_profile_document_at(&root, &relative)
145 }
146
147 fn read_profile_document_at(root: &Path, relative: &Path) -> Result<Option<String>> {
148 let file = match codewhale_util::files::WorkspaceFile::open(root, relative, false) {
149 Ok(file) => file,
150 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
151 Err(error) => return Err(error.into()),
152 };
153 read_profile_document_file(&file)
154 }
155
156 pub fn read_agent_profile_source_document(
157 scope: FleetProfileScope,
158 workspace: &Path,
159 path: &Path,
160 ) -> Result<Option<String>> {
161 let directory = agent_profile_dir_for_scope(scope, workspace)?;
162 if path.parent() == Some(directory.as_path()) {
163 return read_agent_profile_document(scope, workspace, path);
164 }
165 let root = match scope {
166 FleetProfileScope::Project => workspace.to_path_buf(),
167 FleetProfileScope::Personal => directory
168 .parent()
169 .context("Personal profile directory has no state root")?
170 .to_path_buf(),
171 };
172 let fleet_directory = match scope {
173 FleetProfileScope::Project => root.join(".codewhale").join(super::store::FLEET_DIR),
174 FleetProfileScope::Personal => root.join(super::store::FLEET_DIR),
175 };
176 anyhow::ensure!(
177 root.is_absolute()
178 && path.parent() == Some(fleet_directory.as_path())
179 && path.extension().and_then(|value| value.to_str()) == Some("toml"),
180 "Profile source is outside its selected directory"
181 );
182 let relative = path.strip_prefix(&root)?;
183 anyhow::ensure!(
184 codewhale_util::files::path_is_confined(relative),
185 "Profile source is outside its selected directory"
186 );
187 read_profile_document_at(&root, relative)
188 }
189
190 pub fn save_agent_profile_document(
191 scope: FleetProfileScope,
192 workspace: &Path,
193 path: &Path,
194 expected: Option<&str>,
195 id: &str,
196 text: &str,
197 ) -> Result<()> {
198 anyhow::ensure!(
199 text.len() <= MAX_PROFILE_DOCUMENT_BYTES,
200 "Profile document exceeds the one MiB editing limit"
201 );
202 anyhow::ensure!(
203 scope != FleetProfileScope::Project || super::roster::project_agent_profiles_enabled(),
204 "Project profiles are disabled for this launch"
205 );
206 mutate_profile_document(scope, workspace, path, expected, Some((id, text)))
207 }
208
209 pub fn retire_personal_profile(path: &Path, expected: &str) -> Result<()> {
210 mutate_profile_document(
211 FleetProfileScope::Personal,
212 Path::new(""),
213 path,
214 Some(expected),
215 None,
216 )
217 }
218
219 fn mutate_profile_document(
220 scope: FleetProfileScope,
221 workspace: &Path,
222 path: &Path,
223 expected: Option<&str>,
224 edit: Option<(&str, &str)>,
225 ) -> Result<()> {
226 let (root, relative) = profile_document_location(scope, workspace, path)?;
227 let file = match scope {
228 FleetProfileScope::Project => {
229 codewhale_util::files::WorkspaceFile::open_shared(&root, &relative, true)?
230 }
231 FleetProfileScope::Personal => {
232 codewhale_util::files::WorkspaceFile::open(&root, &relative, true)?
233 }
234 };
235 let lock_relative = relative
236 .parent()
237 .context("Profile source has no directory")?
238 .join(".codewhale-profile-write.lock");
239 let lock_entry = file.sibling(".codewhale-profile-write.lock")?;
240 let lock_file = lock_entry.open_update(true, false)?;
241 codewhale_config::private_directory::tighten_mode_of(
242 &lock_file,
243 &root.join(&lock_relative),
244 0o600,
245 )?;
246 let mut lock = fd_lock::RwLock::new(lock_file);
247 let guard = lock.write()?;
248 anyhow::ensure!(
249 codewhale_util::files::same_file(
250 &guard,
251 &codewhale_util::files::WorkspaceFile::open(&root, &lock_relative, false)?
252 .open_file_shared()?,
253 )?,
254 "Profile write lock changed; reopen the source"
255 );
256 let current = read_profile_document_file(&file)?;
257 if current.as_deref() != expected {
258 return Err(AgentProfileWriteConflict {
259 path: path.to_path_buf(),
260 }
261 .into());
262 }
263 if let Some((id, text)) = edit {
264 let profile = parse_agent_profile_text(path, text)?;
265 anyhow::ensure!(
266 profile.id == id,
267 "Profile identity changed; reopen the source"
268 );
269 let identities = match scope {
270 FleetProfileScope::Project => load_workspace_agent_profile_identities(workspace)?,
271 FleetProfileScope::Personal => load_agent_profile_identities_from_dir(
272 path.parent().context("Profile source has no directory")?,
273 )?,
274 };
275 if let Some(other) = identities
276 .into_iter()
277 .find(|other| other.id.eq_ignore_ascii_case(id) && other.source != path)
278 {
279 return Err(AgentProfileIdentityConflict {
280 id: id.to_owned(),
281 path: other.source,
282 }
283 .into());
284 }
285 }
286 anyhow::ensure!(
287 codewhale_util::files::same_file(
288 &guard,
289 &codewhale_util::files::WorkspaceFile::open(&root, &lock_relative, false)?
290 .open_file_shared()?,
291 )?,
292 "Profile write lock changed; reopen the source"
293 );
294 if let Some((_, text)) = edit {
295 file.replace(text.as_bytes())
296 .map_err(|source| AgentProfileWriteUnconfirmed {
297 path: path.to_path_buf(),
298 source,
299 })?;
300 } else {
301 let opened = file.open_retained()?;
302 let retired = file.sibling(&format!(".retired-{}", uuid::Uuid::new_v4()))?;
303 file.move_opened_to_sibling(&opened, &retired)?;
304 file.sync_parent()?;
305 }
306 Ok(())
307 }
308
309 #[derive(Debug, Clone, PartialEq, Eq)]
310 pub struct AgentProfile {
311 pub id: String,
312 pub display_name: Option<String>,
313 pub description: Option<String>,
314 /// Closed capability requirements carried by selected v2 Fleet members.
315 /// Legacy/profile sources leave this empty; consumers must never infer a
316 /// capability from the member name or model prefix.
317 pub requires: Vec<String>,
318 pub profile: FleetProfile,
319 pub source: PathBuf,
320 /// Roster layer this profile came from (#fleet-roster cutover (v0.8.67)).
321 /// File-based loading in this module always yields `Workspace`; the
322 /// roster stamps `BuiltIn` / `Config` for the other layers.
323 pub origin: ProfileOrigin,
324 /// Runtime authority for a profile loaded from an immutable plugin
325 /// snapshot. Rechecked at Agent spawn so another process can revoke it.
326 pub plugin_authority: Option<codewhale_config::PluginAuthority>,
327 pub native_preset: Option<codewhale_plugins::composition_scope::NativePresetRef>,
328 }
329
330 /// The minimum profile information needed to prevent a save from clobbering
331 /// another file. Identity discovery intentionally accepts otherwise legacy
332 /// profile keys: an old route-policy field must not block authoring an
333 /// unrelated, current profile, but malformed TOML or an invalid id still fails
334 /// closed because the collision check cannot be trusted.
335 #[derive(Debug, Clone, PartialEq, Eq)]
336 pub struct AgentProfileIdentity {
337 pub id: String,
338 pub source: PathBuf,
339 }
340
341 /// Keep a failed definition's identity so selecting it cannot run a lower
342 /// roster layer by accident. Parser excerpts stay in logs, not tool output.
343 #[derive(Debug, Clone, Serialize)]
344 pub struct AgentProfileLoadIssue {
345 pub id: String,
346 pub source: PathBuf,
347 pub origin: ProfileOrigin,
348 #[serde(skip_serializing)]
349 pub detail: String,
350 }
351
352 impl AgentProfileLoadIssue {
353 fn new(path: &Path, id: Option<&str>, origin: ProfileOrigin, detail: String) -> Self {
354 Self {
355 id: id
356 .or_else(|| path.file_stem().and_then(|stem| stem.to_str()))
357 .unwrap_or("profile")
358 .to_string(),
359 source: path.to_path_buf(),
360 origin,
361 detail,
362 }
363 }
364 }
365
366 impl std::fmt::Display for AgentProfileLoadIssue {
367 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 f.write_str(&self.detail)
369 }
370 }
371
372 #[derive(Debug, Deserialize)]
373 #[serde(deny_unknown_fields)]
374 struct AgentProfileToml {
375 #[serde(default)]
376 id: Option<String>,
377 #[serde(default)]
378 name: Option<String>,
379 #[serde(default)]
380 display_name: Option<String>,
381 #[serde(default)]
382 description: Option<String>,
383 #[serde(default)]
384 role_hint: Option<String>,
385 #[serde(default)]
386 base_role: Option<String>,
387 #[serde(default)]
388 persona: Option<String>,
389 #[serde(default)]
390 loadout: Option<String>,
391 #[serde(default, alias = "model_hint", alias = "model_id")]
392 model: Option<String>,
393 /// Explicit provider id for `model` (#4093), e.g. `"deepseek"` or
394 /// `"openrouter"`. Validated against the known `ProviderKind` vocabulary at
395 /// load time — never inferred by sniffing `model` for a provider-shaped
396 /// substring (EPIC #2608). `deny_unknown_fields` no longer needs to guard
397 /// this name: it is now a first-class, validated field instead of a
398 /// smuggled one.
399 #[serde(default)]
400 provider: Option<String>,
401 /// Optional saved thinking tier for this profile (#4137). TOML may use
402 /// the canonical `reasoning_effort` spelling or the UI-facing `thinking`
403 /// / `reasoning` aliases; loading normalizes to a canonical setting label.
404 #[serde(default, alias = "thinking", alias = "reasoning")]
405 reasoning_effort: Option<String>,
406 #[serde(default)]
407 whale: Option<crate::saved_whales::WhaleSettings>,
408 #[serde(default)]
409 instructions: Option<AgentProfileInstructions>,
410 #[serde(default)]
411 tools: Option<AgentProfileTools>,
412 #[serde(default)]
413 permissions: Option<AgentProfilePermissionsToml>,
414 }
415
416 #[derive(Debug, Deserialize)]
417 struct AgentProfileIdentityToml {
418 #[serde(default)]
419 id: Option<String>,
420 #[serde(default)]
421 name: Option<String>,
422 }
423
424 #[derive(Debug, Deserialize)]
425 #[serde(deny_unknown_fields)]
426 struct AgentProfileInstructions {
427 #[serde(default)]
428 text: Option<String>,
429 }
430
431 #[derive(Debug, Deserialize)]
432 #[serde(deny_unknown_fields)]
433 struct AgentProfileTools {
434 #[serde(default)]
435 posture: Option<String>,
436 }
437
438 #[derive(Debug, Deserialize)]
439 #[serde(deny_unknown_fields)]
440 struct AgentProfilePermissionsToml {
441 #[serde(default)]
442 allow_shell: Option<bool>,
443 #[serde(default)]
444 trust: Option<bool>,
445 #[serde(default)]
446 approval_required: Option<bool>,
447 }
448
449 pub fn load_workspace_agent_profiles(workspace: impl AsRef<Path>) -> Result<Vec<AgentProfile>> {
450 let workspace = workspace.as_ref();
451 let (root, dir) = workspace_agent_profile_dir(workspace);
452 load_agent_profiles_from_dir_in(Some(&root), dir)
453 }
454
455 /// Confinement root and profile directory for a workspace.
456 ///
457 /// A home workspace keeps its `.codewhale` state wherever the user put it, so
458 /// the resolved state directory is the root; links below it are still refused.
459 /// Any other workspace keeps the workspace as the root with `.codewhale`
460 /// inside the walked path, so a repository-supplied link is still refused.
461 fn workspace_agent_profile_dir(workspace: &Path) -> (PathBuf, PathBuf) {
462 codewhale_util::files::workspace_state_path(workspace, Path::new("agents"))
463 }
464
465 /// Read one profile file. Under a workspace `root` a linked file or linked
466 /// parent is refused (the shared confined-file refusal), so a repository
467 /// cannot make a profile read land outside itself. `None` is for the user's
468 /// own directories and installed plugins, which are not workspace content.
469 fn read_profile_text(root: Option<&Path>, path: &Path) -> std::io::Result<String> {
470 match root {
471 Some(root) => codewhale_util::fs_confined::read_to_string(root, path),
472 None => std::fs::read_to_string(path),
473 }
474 }
475
476 /// Refuse a profile directory that reaches outside `root` through a link.
477 fn check_profile_dir_confined(root: Option<&Path>, dir: &Path) -> Result<()> {
478 match root {
479 Some(root) => codewhale_util::files::reject_linked_path(root, dir)
480 .with_context(|| format!("agent profile directory {}", dir.display())),
481 None => Ok(()),
482 }
483 }
484
485 /// Load every valid workspace profile while reporting invalid neighbors
486 /// individually. The runtime roster uses this path so one stale profile does
487 /// not hide a newly-authored valid profile (or the rest of the party).
488 pub fn load_workspace_agent_profiles_tolerant(
489 workspace: impl AsRef<Path>,
490 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
491 let workspace = workspace.as_ref();
492 let (root, dir) = workspace_agent_profile_dir(workspace);
493 load_agent_profiles_from_dir_tolerant_in(Some(&root), dir, ProfileOrigin::Workspace, false)
494 }
495
496 pub fn load_agent_profiles_from_dir_tolerant(
497 dir: impl AsRef<Path>,
498 origin: ProfileOrigin,
499 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
500 load_agent_profiles_from_dir_tolerant_in(None, dir, origin, false)
501 }
502
503 pub(super) fn load_personal_agent_profiles(
504 dir: &Path,
505 include_saved_whales: bool,
506 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
507 load_agent_profiles_from_dir_tolerant_in(
508 None,
509 dir,
510 ProfileOrigin::Personal,
511 include_saved_whales,
512 )
513 }
514
515 fn load_agent_profiles_from_dir_tolerant_in(
516 root: Option<&Path>,
517 dir: impl AsRef<Path>,
518 origin: ProfileOrigin,
519 include_saved_whales: bool,
520 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
521 let dir = dir.as_ref();
522 let paths = agent_profile_paths(root, dir)?;
523 let mut profiles = Vec::new();
524 let mut issues = Vec::new();
525 let mut seen = BTreeSet::new();
526 let mut duplicates = BTreeSet::new();
527 let mut identified = Vec::new();
528
529 // Resolve identities first so duplicate ids fail closed as a group rather
530 // than allowing whichever filename happens to sort first to win.
531 for path in paths {
532 if origin == ProfileOrigin::Plugin && path.extension().is_some_and(|ext| ext == "md") {
533 continue;
534 }
535 match load_agent_profile_identity_file(root, &path) {
536 Ok(None) => continue,
537 Ok(Some(identity)) => {
538 let canonical_id = identity.id.to_ascii_lowercase();
539 if !seen.insert(canonical_id.clone()) {
540 duplicates.insert(canonical_id.clone());
541 }
542 identified.push((path, identity, canonical_id));
543 }
544 Err(err) => issues.push(AgentProfileLoadIssue::new(
545 &path,
546 None,
547 origin,
548 format!("{err:#}"),
549 )),
550 }
551 }
552
553 for (path, identity, canonical_id) in identified {
554 if duplicates.contains(&canonical_id) {
555 issues.push(AgentProfileLoadIssue::new(
556 &path,
557 Some(&identity.id),
558 origin,
559 format!(
560 "duplicate agent profile id {} includes {}",
561 canonical_id,
562 path.display()
563 ),
564 ));
565 continue;
566 }
567 match read_profile_text(root, &path)
568 .with_context(|| format!("reading agent profile {}", path.display()))
569 .and_then(|raw| parse_agent_profile_document(&path, &raw))
570 {
571 Ok((_, true)) if !include_saved_whales => {}
572 Ok((mut profile, _)) => {
573 profile.origin = origin;
574 profiles.push(profile);
575 }
576 Err(err) => issues.push(AgentProfileLoadIssue::new(
577 &path,
578 Some(&identity.id),
579 origin,
580 format!("{err:#}"),
581 )),
582 }
583 }
584
585 Ok((profiles, issues))
586 }
587
588 pub fn load_plugin_agent_profiles_from_component(
589 component: &Path,
590 authority: &codewhale_config::PluginAuthority,
591 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
592 let (mut profiles, issues) = if component.is_dir() {
593 load_agent_profiles_from_dir_tolerant(component, ProfileOrigin::Plugin)?
594 } else if component.is_file() {
595 match load_agent_profile_file(None, component) {
596 Ok(mut profile) => {
597 profile.origin = ProfileOrigin::Plugin;
598 (vec![profile], Vec::new())
599 }
600 Err(error) => {
601 let identity = load_agent_profile_identity_file(None, component)
602 .ok()
603 .flatten();
604 (
605 Vec::new(),
606 vec![AgentProfileLoadIssue::new(
607 component,
608 identity.as_ref().map(|identity| identity.id.as_str()),
609 ProfileOrigin::Plugin,
610 format!("{error:#}"),
611 )],
612 )
613 }
614 }
615 } else {
616 return Err(anyhow!(
617 "plugin Agent component is unavailable: {}",
618 component.display()
619 ));
620 };
621 for profile in &mut profiles {
622 profile.plugin_authority = Some(authority.clone());
623 }
624 Ok((profiles, issues))
625 }
626
627 /// Claude Code's user-level agent directory (`~/.claude/agents`). Tests never
628 /// read the developer's real home directory.
629 pub fn claude_user_agent_dir() -> Option<PathBuf> {
630 if cfg!(any(test, feature = "test-support")) {
631 return None;
632 }
633 dirs::home_dir().map(|home| home.join(CLAUDE_AGENT_DIR))
634 }
635
636 /// Claude Code tools that only read. An agent whose `tools:` list stays inside
637 /// this set runs on the read-only `explore` posture.
638 const CLAUDE_READ_ONLY_TOOLS: &[&str] = &[
639 "read",
640 "grep",
641 "glob",
642 "ls",
643 "webfetch",
644 "websearch",
645 "notebookread",
646 "todowrite",
647 "todoread",
648 ];
649
650 /// Claude Code tools that change files. Any of these in `tools:` maps the
651 /// agent to the `implement` posture.
652 const CLAUDE_WRITE_TOOLS: &[&str] = &["write", "edit", "multiedit", "notebookedit"];
653
654 /// Load Claude Code agent definitions (`*.md` with YAML frontmatter) from one
655 /// directory. Frontmatter is read by the same parser as `SKILL.md`.
656 ///
657 /// The mapping is deliberately small: `name` → id, `description` →
658 /// description, the Markdown body → role instructions, `tools` → the closest
659 /// role posture, `model` → model hint (Claude's `inherit`/`sonnet`/`opus`/
660 /// `haiku` aliases inherit the session route). `color` is cosmetic and
661 /// ignored. Any other key would change behavior Codewhale cannot reproduce, so
662 /// that file becomes a load issue instead of silently loading as something
663 /// else. Permissions stay at the floor: a Markdown agent can never grant shell
664 /// or trust — only a `.codewhale/agents/*.toml` profile can.
665 pub fn load_claude_agent_profiles_from_dir(
666 dir: impl AsRef<Path>,
667 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
668 load_claude_agent_profiles_from_dir_in(None, dir)
669 }
670
671 /// [`load_claude_agent_profiles_from_dir`] for a directory that belongs to a
672 /// workspace: with a `root`, links below it are refused.
673 pub fn load_claude_agent_profiles_from_dir_in(
674 root: Option<&Path>,
675 dir: impl AsRef<Path>,
676 ) -> Result<(Vec<AgentProfile>, Vec<AgentProfileLoadIssue>)> {
677 let dir = dir.as_ref();
678 check_profile_dir_confined(root, dir)?;
679 if !dir.is_dir() {
680 return Ok((Vec::new(), Vec::new()));
681 }
682 let mut paths = std::fs::read_dir(dir)
683 .with_context(|| format!("reading Claude agent dir {}", dir.display()))?
684 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
685 .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("md"))
686 .collect::<Vec<_>>();
687 paths.sort();
688
689 let origin = ProfileOrigin::ClaudeCode;
690 let mut profiles: Vec<AgentProfile> = Vec::new();
691 let mut issues = Vec::new();
692 for path in paths {
693 match load_claude_agent_file(root, &path) {
694 Ok(profile) => {
695 if profiles
696 .iter()
697 .any(|existing| existing.id.eq_ignore_ascii_case(&profile.id))
698 {
699 issues.push(AgentProfileLoadIssue::new(
700 &path,
701 Some(&profile.id),
702 origin,
703 format!(
704 "duplicate Claude agent name {} in {}",
705 profile.id,
706 dir.display()
707 ),
708 ));
709 continue;
710 }
711 profiles.push(profile);
712 }
713 Err(err) => issues.push(AgentProfileLoadIssue::new(
714 &path,
715 None,
716 origin,
717 format!("{err:#}")
718 .split_whitespace()
719 .collect::<Vec<_>>()
720 .join(" "),
721 )),
722 }
723 }
724 Ok((profiles, issues))
725 }
726
727 const CLAUDE_AGENT_KEYS: &[&str] = &[
728 "name",
729 "description",
730 "tools",
731 "disallowedtools",
732 "model",
733 "permissionmode",
734 "skills",
735 "hooks",
736 "color",
737 "mcpservers",
738 "maxturns",
739 "memory",
740 "background",
741 "isolation",
742 "effort",
743 "initialprompt",
744 ];
745
746 fn is_claude_agent_key_line(line: &str) -> bool {
747 if line.starts_with([' ', '\t']) {
748 return false;
749 }
750 let Some((key, value)) = line.split_once(':') else {
751 return false;
752 };
753 if CLAUDE_AGENT_KEYS.contains(&key.trim().to_ascii_lowercase().as_str()) {
754 return true;
755 }
756 let mut chars = key.chars();
757 let is_identifier = chars.next().is_some_and(|ch| ch.is_ascii_alphabetic())
758 && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-'));
759 is_identifier && !value.trim().is_empty()
760 }
761
762 fn lenient_claude_description(raw: &str) -> std::borrow::Cow<'_, str> {
763 let lines: Vec<&str> = raw.lines().collect();
764 let Some(open) = lines
765 .iter()
766 .position(|line| !line.trim_matches('\u{feff}').trim().is_empty())
767 else {
768 return raw.into();
769 };
770 if lines[open].trim_matches('\u{feff}').trim_end() != "---" {
771 return raw.into();
772 }
773 let Some(close) = lines[open + 1..]
774 .iter()
775 .position(|line| line.trim_end() == "---")
776 .map(|offset| open + 1 + offset)
777 else {
778 return raw.into();
779 };
780 let Some(description) = (open + 1..close).find(|&index| {
781 let line = lines[index];
782 !line.starts_with([' ', '\t'])
783 && line
784 .split_once(':')
785 .is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case("description"))
786 }) else {
787 return raw.into();
788 };
789 let value = lines[description]
790 .split_once(':')
791 .map_or("", |(_, value)| value.trim());
792 if value.starts_with(['|', '>']) {
793 return raw.into();
794 }
795 let end = (description + 1..close)
796 .find(|&index| is_claude_agent_key_line(lines[index]))
797 .unwrap_or(close);
798 let continuation = &lines[description + 1..end];
799 if !continuation.iter().any(|line| {
800 !line.trim().is_empty()
801 && !line.starts_with([' ', '\t'])
802 && !line.trim_start().starts_with('#')
803 }) {
804 return raw.into();
805 }
806 let value = [('"', '"'), ('\'', '\'')]
807 .iter()
808 .find_map(|(open, close)| {
809 value
810 .strip_prefix(*open)
811 .and_then(|inner| inner.strip_suffix(*close))
812 })
813 .unwrap_or(value);
814 let mut rebuilt: Vec<String> = lines[..description]
815 .iter()
816 .map(|line| (*line).to_string())
817 .collect();
818 rebuilt.push("description: |-".into());
819 if !value.is_empty() {
820 rebuilt.push(format!(" {value}"));
821 }
822 rebuilt.extend(
823 continuation
824 .iter()
825 .filter(|line| !line.trim_start().starts_with('#'))
826 .map(|line| {
827 if line.trim().is_empty() {
828 String::new()
829 } else {
830 format!(" {}", line.trim_end())
831 }
832 }),
833 );
834 rebuilt.extend(lines[end..].iter().map(|line| (*line).to_string()));
835 let mut text = rebuilt.join("\n");
836 if raw.ends_with('\n') {
837 text.push('\n');
838 }
839 text.into()
840 }
841
842 fn load_claude_agent_file(root: Option<&Path>, path: &Path) -> Result<AgentProfile> {
843 let raw = read_profile_text(root, path)
844 .with_context(|| format!("reading Claude agent {}", path.display()))?;
845 parse_markdown_agent(path, &raw, ProfileOrigin::ClaudeCode)
846 }
847
848 fn markdown_agent_id(path: &Path, name: Option<&str>) -> Result<String> {
849 let fallback_id = path
850 .file_stem()
851 .and_then(|value| value.to_str())
852 .unwrap_or("agent");
853 let id = non_empty_trimmed(name).unwrap_or(fallback_id).to_string();
854 validate_agent_profile_token(path, "name", &id)?;
855
856 Ok(id)
857 }
858
859 pub fn set_markdown_profile_route(
860 path: &Path,
861 raw: &str,
862 provider: Option<&str>,
863 model: Option<&str>,
864 reasoning: Option<&str>,
865 ) -> Result<String> {
866 let header = raw.trim_start_matches('\u{feff}').trim_start();
867 let (opening, rest) = header
868 .split_once('\n')
869 .context("Missing Markdown frontmatter")?;
870 anyhow::ensure!(opening.trim_end() == "---", "Missing Markdown frontmatter");
871 let newline = if opening.ends_with('\r') {
872 "\r\n"
873 } else {
874 "\n"
875 };
876 let indent = rest
877 .lines()
878 .take_while(|line| line.trim_end() != "---")
879 .filter(|line| !line.trim().is_empty() && !line.trim_start().starts_with('#'))
880 .map(|line| &line[..line.len() - line.trim_start().len()])
881 .min_by_key(|space| space.len())
882 .unwrap_or("");
883 let mut expected = parse_agent_profile_text(path, raw)?;
884 expected.profile.provider = provider.map(str::to_owned);
885 expected.profile.model = model.map(str::to_owned);
886 expected.profile.reasoning_effort = normalize_agent_profile_reasoning_effort(path, reasoning)?;
887 let mut output = raw[..raw.len() - rest.len()].to_owned();
888 let mut lines = rest.split_inclusive('\n');
889 let mut skip_value = false;
890 for line in lines.by_ref() {
891 if line.trim_end() == "---" {
892 for (key, value) in [
893 ("model", model),
894 ("provider", provider),
895 ("reasoning_effort", reasoning),
896 ] {
897 if let Some(value) = value {
898 output.push_str(&format!(
899 "{indent}{key}: {}{newline}",
900 serde_json::to_string(value)?
901 ));
902 }
903 }
904 output.push_str(line);
905 output.extend(lines);
906 anyhow::ensure!(
907 parse_agent_profile_text(path, &output)? == expected,
908 "The edited route cannot be represented in this profile"
909 );
910
911 return Ok(output);
912 }
913 if let Some(key_line) = line.strip_prefix(indent)
914 && !key_line.starts_with(char::is_whitespace)
915 && !key_line.starts_with('#')
916 {
917 skip_value = key_line.split_once(':').is_some_and(|(key, _)| {
918 matches!(
919 key.trim().to_ascii_lowercase().as_str(),
920 "model" | "provider" | "reasoning_effort"
921 )
922 });
923 }
924 if !skip_value || line.trim().is_empty() || line.trim_start().starts_with('#') {
925 output.push_str(line);
926 }
927 }
928 bail!("Missing Markdown frontmatter closing delimiter")
929 }
930
931 fn parse_markdown_agent(path: &Path, raw: &str, origin: ProfileOrigin) -> Result<AgentProfile> {
932 let raw = lenient_claude_description(raw);
933 let (metadata, body) = codewhale_skill_install::frontmatter::parse_frontmatter(&raw)
934 .map_err(|err| anyhow!("parsing Claude agent {}: {err}", path.display()))?
935 .ok_or_else(|| {
936 anyhow!(
937 "Claude agent {} has no `---` frontmatter block",
938 path.display()
939 )
940 })?;
941
942 let mut unmapped: Vec<&str> = metadata
943 .keys()
944 .map(String::as_str)
945 .filter(|key| {
946 !(matches!(*key, "name" | "description" | "tools" | "model" | "color")
947 || (origin != ProfileOrigin::ClaudeCode
948 && matches!(*key, "provider" | "reasoning_effort")))
949 })
950 .collect();
951 if !unmapped.is_empty() {
952 unmapped.sort_unstable();
953 bail!(
954 "Claude agent {} uses frontmatter Codewhale cannot honor ({}); remove it, or define this agent as a .codewhale/agents/*.toml profile",
955 path.display(),
956 unmapped.join(", ")
957 );
958 }
959
960 let id = markdown_agent_id(path, metadata.get("name").map(String::as_str))?;
961 let role_name = claude_tools_role(metadata.get("tools").map(String::as_str)).to_string();
962 let model = non_empty_trimmed(metadata.get("model").map(String::as_str))
963 .filter(|model| {
964 !model.eq_ignore_ascii_case("inherit")
965 && (metadata.contains_key("provider")
966 || !matches!(
967 model.to_ascii_lowercase().as_str(),
968 "sonnet" | "opus" | "haiku"
969 ))
970 })
971 .map(str::to_string);
972 validate_agent_profile_model_hint(path, model.as_deref())?;
973
974 let provider = metadata.get("provider").cloned();
975 if let Some(value) = provider.as_deref() {
976 validate_agent_profile_provider(path, value)?;
977 }
978 let reasoning_effort = normalize_agent_profile_reasoning_effort(
979 path,
980 metadata.get("reasoning_effort").map(String::as_str),
981 )?;
982 let description =
983 non_empty_trimmed(metadata.get("description").map(String::as_str)).map(str::to_string);
984 let instructions = trimmed_non_empty(body).map(str::to_string);
985 Ok(AgentProfile {
986 native_preset: None,
987 id,
988 display_name: None,
989 description: description.clone(),
990 requires: Vec::new(),
991 profile: FleetProfile {
992 slot: FleetSlot::from_name(&role_name),
993 role: FleetRole {
994 name: role_name,
995 description,
996 instructions,
997 },
998 loadout: FleetLoadout::default(),
999 model,
1000 provider,
1001 reasoning_effort,
1002 external_agent: None,
1003 external_agent_transport: None,
1004 permissions: FleetProfilePermissions::default(),
1005 delegation: FleetDelegationHints::default(),
1006 },
1007 source: path.to_path_buf(),
1008 origin,
1009 plugin_authority: None,
1010 })
1011 }
1012
1013 /// Closest Codewhale role posture for a Claude `tools:` allowlist. No list
1014 /// means Claude's "all tools", which is the documented `general` default.
1015 fn claude_tools_role(tools: Option<&str>) -> &'static str {
1016 let Some(tools) = tools.and_then(trimmed_non_empty) else {
1017 return "general";
1018 };
1019 let names: Vec<String> = tools
1020 .split([',', ' ', '\t'])
1021 .map(|tool| {
1022 tool.trim()
1023 .trim_matches(['[', ']', '"', '\''])
1024 .to_ascii_lowercase()
1025 })
1026 .filter(|tool| !tool.is_empty())
1027 .collect();
1028 if names
1029 .iter()
1030 .any(|tool| CLAUDE_WRITE_TOOLS.contains(&tool.as_str()))
1031 {
1032 "implement"
1033 } else if names
1034 .iter()
1035 .all(|tool| CLAUDE_READ_ONLY_TOOLS.contains(&tool.as_str()))
1036 {
1037 "explore"
1038 } else {
1039 // Bash or MCP tools without file writes: the shell-capable posture.
1040 "test"
1041 }
1042 }
1043
1044 /// Read only the identity-bearing fields from workspace profiles for the
1045 /// authoring collision gate. Unknown legacy fields are harmless here because
1046 /// no profile behavior is loaded or executed from this representation.
1047 pub fn load_workspace_agent_profile_identities(
1048 workspace: impl AsRef<Path>,
1049 ) -> Result<Vec<AgentProfileIdentity>> {
1050 let workspace = workspace.as_ref();
1051 let (root, dir) = workspace_agent_profile_dir(workspace);
1052 load_agent_profile_identities_from_dir_in(Some(&root), dir)
1053 }
1054
1055 pub fn load_agent_profile_identities_from_dir(
1056 dir: impl AsRef<Path>,
1057 ) -> Result<Vec<AgentProfileIdentity>> {
1058 load_agent_profile_identities_from_dir_in(None, dir)
1059 }
1060
1061 fn load_agent_profile_identities_from_dir_in(
1062 root: Option<&Path>,
1063 dir: impl AsRef<Path>,
1064 ) -> Result<Vec<AgentProfileIdentity>> {
1065 let dir = dir.as_ref();
1066 agent_profile_paths(root, dir)?
1067 .into_iter()
1068 .filter_map(|path| load_agent_profile_identity_file(root, &path).transpose())
1069 .collect()
1070 }
1071
1072 pub fn load_agent_profiles_from_dir(dir: impl AsRef<Path>) -> Result<Vec<AgentProfile>> {
1073 load_agent_profiles_from_dir_in(None, dir)
1074 }
1075
1076 fn load_agent_profiles_from_dir_in(
1077 root: Option<&Path>,
1078 dir: impl AsRef<Path>,
1079 ) -> Result<Vec<AgentProfile>> {
1080 let dir = dir.as_ref();
1081 let mut profiles = Vec::new();
1082 let mut seen = BTreeSet::new();
1083 for path in agent_profile_paths(root, dir)? {
1084 let raw = read_profile_text(root, &path)
1085 .with_context(|| format!("reading agent profile {}", path.display()))?;
1086 if is_plain_markdown(&path, &raw) {
1087 continue;
1088 }
1089 let profile = parse_agent_profile_text(&path, &raw)?;
1090 if !seen.insert(profile.id.to_ascii_lowercase()) {
1091 bail!("duplicate agent profile id {}", profile.id);
1092 }
1093 profiles.push(profile);
1094 }
1095 Ok(profiles)
1096 }
1097
1098 fn is_agent_document(path: &Path) -> bool {
1099 matches!(
1100 path.extension().and_then(|ext| ext.to_str()),
1101 Some("toml" | "md")
1102 )
1103 }
1104
1105 fn agent_profile_paths(root: Option<&Path>, dir: &Path) -> Result<Vec<PathBuf>> {
1106 check_profile_dir_confined(root, dir)?;
1107 if !dir.exists() {
1108 return Ok(Vec::new());
1109 }
1110 if !dir.is_dir() {
1111 bail!("agent profile path {} is not a directory", dir.display());
1112 }
1113
1114 let mut paths = agent_document_entries(dir)
1115 .with_context(|| format!("reading agent profile dir {}", dir.display()))?
1116 .collect::<std::io::Result<Vec<_>>>()
1117 .with_context(|| format!("reading agent profile entries in {}", dir.display()))?;
1118 paths.sort();
1119 Ok(paths)
1120 }
1121
1122 pub(crate) fn agent_document_entries(
1123 dir: &Path,
1124 ) -> std::io::Result<impl Iterator<Item = std::io::Result<PathBuf>>> {
1125 Ok(std::fs::read_dir(dir)?.filter_map(|entry| match entry {
1126 Ok(entry) => {
1127 let path = entry.path();
1128 is_agent_document(&path).then_some(Ok(path))
1129 }
1130 Err(error) => Some(Err(error)),
1131 }))
1132 }
1133
1134 fn is_plain_markdown(path: &Path, raw: &str) -> bool {
1135 path.extension().is_some_and(|ext| ext == "md")
1136 && raw
1137 .trim_start_matches('\u{feff}')
1138 .trim_start()
1139 .lines()
1140 .next()
1141 .map(str::trim_end)
1142 != Some("---")
1143 }
1144
1145 fn load_agent_profile_identity_file(
1146 root: Option<&Path>,
1147 path: &Path,
1148 ) -> Result<Option<AgentProfileIdentity>> {
1149 let raw = read_profile_text(root, path)
1150 .with_context(|| format!("reading agent profile identity {}", path.display()))?;
1151 if is_plain_markdown(path, &raw) {
1152 return Ok(None);
1153 }
1154 if path.extension().is_some_and(|ext| ext == "md") {
1155 let raw = lenient_claude_description(&raw);
1156 let (metadata, _) = codewhale_skill_install::frontmatter::parse_frontmatter(&raw)
1157 .map_err(|error| anyhow!("parsing agent profile {}: {error}", path.display()))?
1158 .with_context(|| format!("missing frontmatter in {}", path.display()))?;
1159 let id = markdown_agent_id(path, metadata.get("name").map(String::as_str))?;
1160 return Ok(Some(AgentProfileIdentity {
1161 id,
1162 source: path.to_owned(),
1163 }));
1164 }
1165 let parsed: AgentProfileIdentityToml = toml::from_str(&raw)
1166 .map_err(|err| anyhow!("parsing agent profile identity {}: {err}", path.display()))?;
1167 let fallback_id = path
1168 .file_stem()
1169 .and_then(|value| value.to_str())
1170 .unwrap_or("profile");
1171 let id = first_present([parsed.id.as_deref(), parsed.name.as_deref()])
1172 .unwrap_or(fallback_id)
1173 .to_string();
1174 validate_agent_profile_token(path, "id/name", &id)?;
1175 Ok(Some(AgentProfileIdentity {
1176 id,
1177 source: path.to_path_buf(),
1178 }))
1179 }
1180
1181 fn load_agent_profile_file(root: Option<&Path>, path: &Path) -> Result<AgentProfile> {
1182 let raw = read_profile_text(root, path)
1183 .with_context(|| format!("reading agent profile {}", path.display()))?;
1184 parse_agent_profile_text(path, &raw)
1185 }
1186
1187 pub fn parse_agent_profile_text(path: &Path, raw: &str) -> Result<AgentProfile> {
1188 parse_agent_profile_document(path, raw).map(|(profile, _)| profile)
1189 }
1190
1191 pub fn parse_agent_profile_document(path: &Path, raw: &str) -> Result<(AgentProfile, bool)> {
1192 if path.extension().is_some_and(|ext| ext == "md") {
1193 return parse_markdown_agent(path, raw, ProfileOrigin::Workspace)
1194 .map(|profile| (profile, false));
1195 }
1196 let parsed: AgentProfileToml = toml::from_str(raw)
1197 .map_err(|err| anyhow!("parsing agent profile {}: {err}", path.display()))?;
1198 let saved_whale = parsed.whale.is_some();
1199 agent_profile_from_toml(path, parsed).map(|profile| (profile, saved_whale))
1200 }
1201
1202 fn agent_profile_from_toml(path: &Path, parsed: AgentProfileToml) -> Result<AgentProfile> {
1203 reject_permission_expansion(path, parsed.tools.as_ref(), parsed.permissions.as_ref())?;
1204
1205 let whale = parsed.whale.unwrap_or_default();
1206 whale.validate()?;
1207 let fallback_id = path
1208 .file_stem()
1209 .and_then(|value| value.to_str())
1210 .unwrap_or("profile");
1211 let id = first_present([parsed.id.as_deref(), parsed.name.as_deref()])
1212 .unwrap_or(fallback_id)
1213 .to_string();
1214 validate_agent_profile_token(path, "id/name", &id)?;
1215
1216 let role_name = canonical_public_role_name(
1217 first_present([
1218 parsed.base_role.as_deref(),
1219 parsed.role_hint.as_deref(),
1220 parsed.name.as_deref(),
1221 ])
1222 .unwrap_or(&id),
1223 );
1224 validate_agent_profile_token(path, "base_role/role_hint", &role_name)?;
1225
1226 let loadout = first_present([parsed.loadout.as_deref()])
1227 .map(FleetLoadout::from_name)
1228 .unwrap_or_default();
1229 let model = non_empty_trimmed(parsed.model.as_deref()).map(str::to_string);
1230 validate_agent_profile_model_hint(path, model.as_deref())?;
1231
1232 let provider = non_empty_trimmed(parsed.provider.as_deref())
1233 .map(str::to_string)
1234 .map(|provider| validate_agent_profile_provider(path, &provider).map(|()| provider))
1235 .transpose()?;
1236 let reasoning_effort =
1237 normalize_agent_profile_reasoning_effort(path, parsed.reasoning_effort.as_deref())?;
1238
1239 let instructions = parsed
1240 .instructions
1241 .as_ref()
1242 .and_then(|instructions| non_empty_trimmed(instructions.text.as_deref()))
1243 .or_else(|| non_empty_trimmed(parsed.persona.as_deref()))
1244 .map(str::to_string);
1245
1246 let description = non_empty_trimmed(parsed.description.as_deref()).map(str::to_string);
1247 let profile = FleetProfile {
1248 slot: FleetSlot::from_name(&role_name),
1249 role: FleetRole {
1250 name: role_name,
1251 description: description.clone(),
1252 instructions,
1253 },
1254 loadout,
1255 model,
1256 provider,
1257 reasoning_effort,
1258 external_agent: whale.external_agent_id,
1259 external_agent_transport: None,
1260 permissions: FleetProfilePermissions::default(),
1261 delegation: FleetDelegationHints::default(),
1262 };
1263
1264 Ok(AgentProfile {
1265 native_preset: None,
1266 id,
1267 display_name: non_empty_trimmed(parsed.display_name.as_deref()).map(str::to_string),
1268 description,
1269 requires: Vec::new(),
1270 profile,
1271 source: path.to_path_buf(),
1272 origin: ProfileOrigin::Workspace,
1273 plugin_authority: None,
1274 })
1275 }
1276
1277 /// Canonicalize renamed public Fleet roles at profile load boundaries.
1278 ///
1279 /// Profile ids remain untouched so an older file can still be addressed by
1280 /// its saved id. Only the semantic role is migrated; every new receipt and UI
1281 /// label derived from it therefore uses the canonical public token.
1282 pub fn canonical_public_role_name(role: &str) -> String {
1283 codewhale_agent_contract::role::public_role_label(role)
1284 }
1285
1286 fn reject_permission_expansion(
1287 path: &Path,
1288 tools: Option<&AgentProfileTools>,
1289 permissions: Option<&AgentProfilePermissionsToml>,
1290 ) -> Result<()> {
1291 if let Some(posture) = tools
1292 .and_then(|tools| tools.posture.as_deref())
1293 .and_then(trimmed_non_empty)
1294 {
1295 match posture {
1296 "read-only" | "readonly" | "read_only" => {}
1297 other => bail!(
1298 "agent profile {} tools.posture={other:?} would widen permissions; use FleetProfile policy for grants",
1299 path.display()
1300 ),
1301 }
1302 }
1303
1304 if let Some(permissions) = permissions {
1305 if permissions.allow_shell.unwrap_or(false) {
1306 bail!(
1307 "agent profile {} may not request allow_shell=true",
1308 path.display()
1309 );
1310 }
1311 if permissions.trust.unwrap_or(false) {
1312 bail!(
1313 "agent profile {} may not request trust=true",
1314 path.display()
1315 );
1316 }
1317 if permissions.approval_required == Some(false) {
1318 bail!(
1319 "agent profile {} may not disable approval_required",
1320 path.display()
1321 );
1322 }
1323 }
1324 Ok(())
1325 }
1326
1327 fn validate_agent_profile_token(path: &Path, field: &str, value: &str) -> Result<()> {
1328 let trimmed = value.trim();
1329 if trimmed.is_empty() {
1330 bail!("agent profile {} {field} cannot be empty", path.display());
1331 }
1332 if trimmed != value || !trimmed.chars().all(is_agent_profile_token_char) {
1333 bail!(
1334 "agent profile {} {field} must be a simple token",
1335 path.display()
1336 );
1337 }
1338 Ok(())
1339 }
1340
1341 fn validate_agent_profile_model_hint(path: &Path, value: Option<&str>) -> Result<()> {
1342 let Some(value) = value else {
1343 return Ok(());
1344 };
1345 if !is_model_hint(value) {
1346 bail!(
1347 "agent profile {} model must be a visible model id without whitespace or secrets",
1348 path.display()
1349 );
1350 }
1351 Ok(())
1352 }
1353
1354 /// Validate an explicit `provider` field as a safe provider id (#4093).
1355 ///
1356 /// Built-in providers are accepted by the runtime vocabulary, and user-named
1357 /// OpenAI-compatible custom providers are accepted as simple tokens so the
1358 /// launch path can resolve `[providers.<id>]` from the session config (#3965).
1359 /// This field remains the ONLY place a profile's provider is established:
1360 /// callers never infer it from `model` (EPIC #2608).
1361 fn validate_agent_profile_provider(path: &Path, value: &str) -> Result<()> {
1362 let trimmed = value.trim();
1363 if trimmed.is_empty() {
1364 bail!("agent profile {} provider cannot be empty", path.display());
1365 }
1366 if trimmed != value || !trimmed.chars().all(is_agent_profile_token_char) {
1367 bail!(
1368 "agent profile {} provider must be a simple provider id",
1369 path.display()
1370 );
1371 }
1372 Ok(())
1373 }
1374
1375 fn normalize_agent_profile_reasoning_effort(
1376 path: &Path,
1377 value: Option<&str>,
1378 ) -> Result<Option<String>> {
1379 let Some(value) = non_empty_trimmed(value) else {
1380 return Ok(None);
1381 };
1382 if matches!(
1383 value.to_ascii_lowercase().as_str(),
1384 "inherit" | "parent" | "same" | "current" | "default" | "unset"
1385 ) {
1386 return Ok(None);
1387 }
1388 ReasoningEffort::parse_strict(value)
1389 .map(|effort| Some(effort.as_setting().to_string()))
1390 .map_err(|_| {
1391 anyhow!(
1392 "agent profile {} reasoning_effort {value:?} must be one of: inherit, auto, off, low, medium, high, max",
1393 path.display()
1394 )
1395 })
1396 }
1397
1398 fn is_agent_profile_token_char(ch: char) -> bool {
1399 ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')
1400 }
1401
1402 fn is_model_hint(value: &str) -> bool {
1403 let trimmed = value.trim();
1404 !trimmed.is_empty()
1405 && trimmed == value
1406 && trimmed
1407 .chars()
1408 .all(|ch| ch.is_ascii_graphic() && !matches!(ch, '=' | '\'' | '"'))
1409 }
1410
1411 fn first_present<'a>(values: impl IntoIterator<Item = Option<&'a str>>) -> Option<&'a str> {
1412 values.into_iter().flatten().find_map(trimmed_non_empty)
1413 }
1414
1415 fn non_empty_trimmed(value: Option<&str>) -> Option<&str> {
1416 value.and_then(trimmed_non_empty)
1417 }
1418
1419 fn trimmed_non_empty(value: &str) -> Option<&str> {
1420 let trimmed = value.trim();
1421 (!trimmed.is_empty()).then_some(trimmed)
1422 }
1423
1424 /// Outcome of parsing untrusted model output into a fleet profile draft.
1425 /// Mirrors `UntrustedDraftParse` from the constitution pipeline: the reply is
1426 /// data, never trusted, and any failure is a reason string for the status
1427 /// line — drafting failures degrade to the manual authoring flow.
1428 #[derive(Debug)]
1429 pub enum UntrustedProfileParse {
1430 Drafted(Box<FleetProfileDraft>),
1431 Empty,
1432 Invalid(String),
1433 }
1434
1435 /// A model-drafted fleet agent profile that has passed the untrusted gate:
1436 /// balanced-JSON extraction, serde parse with `deny_unknown_fields` (so
1437 /// provider/base_url/api_key/permissions/tools cannot ride along), the same
1438 /// escalation rejections the profile loader applies, token and model-hint
1439 /// validation, prose bounds, and control-character stripping. The persisted
1440 /// TOML is rendered deterministically from this struct — model bytes are
1441 /// never written to disk verbatim.
1442 ///
1443 /// `provider` (#4093) is set ONLY by the structured Fleet setup picker (a
1444 /// user's explicit, credential-checked selection) — never by
1445 /// [`Self::from_untrusted_json`], whose wire schema
1446 /// ([`FleetProfileDraftJson`]) has no `provider` field and rejects one via
1447 /// `deny_unknown_fields`. A model's untrusted reply can never smuggle a
1448 /// provider; only an interactive pick can set this field.
1449 #[derive(Debug, Clone, PartialEq, Eq)]
1450 pub struct FleetProfileDraft {
1451 pub id: String,
1452 pub display_name: Option<String>,
1453 pub description: Option<String>,
1454 pub role_hint: String,
1455 pub model_class_hint: Option<String>,
1456 pub model: Option<String>,
1457 /// Explicit provider id for `model` (e.g. `"deepseek"`), set only by the
1458 /// structured picker. `None` means "no route pin" (inherit) — matching
1459 /// `model: None` — or a legacy/untrusted draft that predates this field.
1460 pub provider: Option<String>,
1461 /// Explicit saved thinking tier, set only by structured setup controls.
1462 /// `None` means inherit the operator/session reasoning tier.
1463 pub reasoning_effort: Option<String>,
1464 pub instructions: Option<String>,
1465 }
1466
1467 /// Bounds for model-drafted profile prose. Same philosophy as the
1468 /// constitution bounds: roomy enough for a real profile, hard enough that a
1469 /// misbehaving provider cannot bloat the store.
1470 pub const MAX_PROFILE_DESCRIPTION_LEN: usize = 1000;
1471 pub const MAX_PROFILE_INSTRUCTIONS_LEN: usize = 4000;
1472 const MAX_PROFILE_DISPLAY_NAME_LEN: usize = 80;
1473 const MAX_PROFILE_TOKEN_LEN: usize = 64;
1474
1475 /// The JSON shape the drafting prompt asks for. `deny_unknown_fields` is the
1476 /// first escalation gate: a draft that tries to smuggle `permissions`,
1477 /// `tools`, `provider`, `base_url`, or `api_key` fails the parse outright
1478 /// instead of being silently stripped.
1479 #[derive(Debug, Deserialize)]
1480 #[serde(deny_unknown_fields)]
1481 struct FleetProfileDraftJson {
1482 #[serde(default)]
1483 id: Option<String>,
1484 #[serde(default)]
1485 display_name: Option<String>,
1486 #[serde(default)]
1487 description: Option<String>,
1488 #[serde(default)]
1489 role_hint: Option<String>,
1490 #[serde(default)]
1491 model_class_hint: Option<String>,
1492 #[serde(default)]
1493 model: Option<String>,
1494 #[serde(default)]
1495 instructions: Option<String>,
1496 }
1497
1498 impl FleetProfileDraft {
1499 /// Parse untrusted model output. Any structural problem is `Invalid`
1500 /// with a short reason; a parse that carries no usable content is
1501 /// `Empty`.
1502 #[must_use]
1503 pub fn from_untrusted_json(raw: &str) -> UntrustedProfileParse {
1504 let Some(json) = extract_first_json_object(raw) else {
1505 return UntrustedProfileParse::Invalid("no JSON object found".to_string());
1506 };
1507 let parsed: FleetProfileDraftJson = match serde_json::from_str(json) {
1508 Ok(parsed) => parsed,
1509 Err(err) => return UntrustedProfileParse::Invalid(err.to_string()),
1510 };
1511
1512 let role_hint = match parsed
1513 .role_hint
1514 .as_deref()
1515 .and_then(trimmed_non_empty)
1516 .map(sanitize_profile_token)
1517 {
1518 Some(token) if !token.is_empty() => canonical_public_role_name(&token),
1519 _ => return UntrustedProfileParse::Invalid("role_hint missing".to_string()),
1520 };
1521 let id = parsed
1522 .id
1523 .as_deref()
1524 .and_then(trimmed_non_empty)
1525 .map(sanitize_profile_token)
1526 .filter(|token| !token.is_empty())
1527 .unwrap_or_else(|| role_hint.clone());
1528 let model_class_hint = parsed
1529 .model_class_hint
1530 .as_deref()
1531 .and_then(trimmed_non_empty)
1532 .map(sanitize_profile_token)
1533 .filter(|token| !token.is_empty());
1534 let model = parsed
1535 .model
1536 .as_deref()
1537 .and_then(trimmed_non_empty)
1538 .map(str::to_string);
1539 if let Some(ref model) = model
1540 && !is_model_hint(model)
1541 {
1542 return UntrustedProfileParse::Invalid(
1543 "model must be a visible model id without whitespace or secrets".to_string(),
1544 );
1545 }
1546 let display_name = parsed
1547 .display_name
1548 .as_deref()
1549 .map(|text| sanitize_profile_prose(text, MAX_PROFILE_DISPLAY_NAME_LEN))
1550 .and_then(|text| trimmed_non_empty(&text).map(str::to_string));
1551 let description = parsed
1552 .description
1553 .as_deref()
1554 .map(|text| sanitize_profile_prose(text, MAX_PROFILE_DESCRIPTION_LEN))
1555 .and_then(|text| trimmed_non_empty(&text).map(str::to_string));
1556 let instructions = parsed
1557 .instructions
1558 .as_deref()
1559 .map(|text| sanitize_profile_prose(text, MAX_PROFILE_INSTRUCTIONS_LEN))
1560 .and_then(|text| trimmed_non_empty(&text).map(str::to_string));
1561
1562 let draft = FleetProfileDraft {
1563 id,
1564 display_name,
1565 description,
1566 role_hint,
1567 model_class_hint,
1568 model,
1569 // Never set from untrusted model output — `FleetProfileDraftJson`
1570 // has no `provider` field, so there is nothing to read here.
1571 provider: None,
1572 reasoning_effort: None,
1573 instructions,
1574 };
1575 if draft.description.is_none() && draft.instructions.is_none() {
1576 return UntrustedProfileParse::Empty;
1577 }
1578 UntrustedProfileParse::Drafted(Box::new(draft))
1579 }
1580
1581 /// Deterministic TOML rendering — the exact bytes the ratify keypress
1582 /// would persist. Loading this back through the profile loader must
1583 /// succeed with the default (floor) permissions.
1584 #[must_use]
1585 pub fn render_toml(&self) -> String {
1586 let mut root = toml::value::Table::new();
1587 root.insert("id".to_string(), toml::Value::String(self.id.clone()));
1588 if let Some(ref display_name) = self.display_name {
1589 root.insert(
1590 "display_name".to_string(),
1591 toml::Value::String(display_name.clone()),
1592 );
1593 }
1594 if let Some(ref description) = self.description {
1595 root.insert(
1596 "description".to_string(),
1597 toml::Value::String(description.clone()),
1598 );
1599 }
1600 root.insert(
1601 "role_hint".to_string(),
1602 toml::Value::String(self.role_hint.clone()),
1603 );
1604 if let Some(ref hint) = self.model_class_hint {
1605 root.insert("loadout".to_string(), toml::Value::String(hint.clone()));
1606 }
1607 if let Some(ref model) = self.model {
1608 root.insert("model".to_string(), toml::Value::String(model.clone()));
1609 // A provider pin is only meaningful alongside a concrete model
1610 // (#4093): an `inherit` draft (`model: None`) never carries one,
1611 // so the rendered TOML can't imply a route it doesn't have.
1612 if let Some(ref provider) = self.provider {
1613 root.insert(
1614 "provider".to_string(),
1615 toml::Value::String(provider.clone()),
1616 );
1617 }
1618 }
1619 if let Some(ref reasoning_effort) = self.reasoning_effort {
1620 root.insert(
1621 "reasoning_effort".to_string(),
1622 toml::Value::String(reasoning_effort.clone()),
1623 );
1624 }
1625 if let Some(ref instructions) = self.instructions {
1626 let mut table = toml::value::Table::new();
1627 table.insert(
1628 "text".to_string(),
1629 toml::Value::String(instructions.clone()),
1630 );
1631 root.insert("instructions".to_string(), toml::Value::Table(table));
1632 }
1633 toml::to_string_pretty(&toml::Value::Table(root))
1634 .unwrap_or_else(|_| String::from("# failed to render profile"))
1635 }
1636
1637 /// File name (stem + `.toml`) for this draft, always derived from the
1638 /// sanitized id — never a model-chosen free-form path.
1639 #[must_use]
1640 pub fn file_name(&self) -> String {
1641 format!("{}.toml", self.id)
1642 }
1643 }
1644
1645 /// Keep only the loader's token alphabet, lowercased, bounded.
1646 fn sanitize_profile_token(value: &str) -> String {
1647 value
1648 .trim()
1649 .chars()
1650 .map(|ch| ch.to_ascii_lowercase())
1651 .filter(|ch| is_agent_profile_token_char(*ch))
1652 .take(MAX_PROFILE_TOKEN_LEN)
1653 .collect()
1654 }
1655
1656 /// Strip control characters (newline/tab survive) and bound length by chars.
1657 fn sanitize_profile_prose(text: &str, max_len: usize) -> String {
1658 text.chars()
1659 .filter(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'))
1660 .take(max_len)
1661 .collect()
1662 }
1663
1664 /// Extract the first balanced `{...}` object from untrusted output, so fenced
1665 /// or prose-wrapped JSON still parses. Mirrors the constitution pipeline's
1666 /// extractor (which is private to codewhale-config).
1667 fn extract_first_json_object(raw: &str) -> Option<&str> {
1668 let start = raw.find('{')?;
1669 let mut depth = 0usize;
1670 let mut in_string = false;
1671 let mut escaped = false;
1672 for (offset, ch) in raw[start..].char_indices() {
1673 if escaped {
1674 escaped = false;
1675 continue;
1676 }
1677 match ch {
1678 '\\' if in_string => escaped = true,
1679 '"' => in_string = !in_string,
1680 '{' if !in_string => depth += 1,
1681 '}' if !in_string => {
1682 depth -= 1;
1683 if depth == 0 {
1684 return Some(&raw[start..=start + offset]);
1685 }
1686 }
1687 _ => {}
1688 }
1689 }
1690 None
1691 }
1692
1693 #[cfg(test)]
1694 mod tests {
1695 use super::*;
1696 use tempfile::TempDir;
1697
1698 #[test]
1699 fn draft_gate_rejects_unknown_and_escalation_fields() {
1700 for raw in [
1701 r#"{"id":"x","role_hint":"reviewer","description":"d","permissions":{"allow_shell":true}}"#,
1702 r#"{"id":"x","role_hint":"reviewer","description":"d","tools":{"posture":"full"}}"#,
1703 r#"{"id":"x","role_hint":"reviewer","description":"d","provider":"openai"}"#,
1704 r#"{"id":"x","role_hint":"reviewer","description":"d","api_key":"sk-nope"}"#,
1705 ] {
1706 assert!(
1707 matches!(
1708 FleetProfileDraft::from_untrusted_json(raw),
1709 UntrustedProfileParse::Invalid(_)
1710 ),
1711 "{raw} must be rejected, not stripped"
1712 );
1713 }
1714 }
1715
1716 #[test]
1717 fn draft_gate_bounds_and_sanitizes() {
1718 let huge = "x".repeat(MAX_PROFILE_INSTRUCTIONS_LEN + 500);
1719 // \u0007 (BEL) inside the description must be stripped by the
1720 // prose sanitizer; the oversized instructions must be bounded.
1721 let raw = format!(
1722 "{{\"id\":\" Weird ID!! \",\"role_hint\":\"Code Reviewer\",\"description\":\"has\\u0007control\",\"instructions\":\"{huge}\"}}"
1723 );
1724 let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(&raw)
1725 else {
1726 panic!("draft should parse");
1727 };
1728 assert_eq!(draft.id, "weirdid");
1729 assert_eq!(draft.role_hint, "codereviewer");
1730 assert_eq!(draft.description.as_deref(), Some("hascontrol"));
1731 assert_eq!(
1732 draft.instructions.as_deref().unwrap().chars().count(),
1733 MAX_PROFILE_INSTRUCTIONS_LEN
1734 );
1735 }
1736
1737 #[test]
1738 fn draft_gate_rejects_secret_shaped_model_and_missing_role() {
1739 assert!(matches!(
1740 FleetProfileDraft::from_untrusted_json(
1741 r#"{"id":"x","role_hint":"reviewer","description":"d","model":"has secret ="}"#
1742 ),
1743 UntrustedProfileParse::Invalid(_)
1744 ));
1745 assert!(matches!(
1746 FleetProfileDraft::from_untrusted_json(r#"{"id":"x","description":"d"}"#),
1747 UntrustedProfileParse::Invalid(_)
1748 ));
1749 assert!(matches!(
1750 FleetProfileDraft::from_untrusted_json(r#"{"id":"x","role_hint":"reviewer"}"#),
1751 UntrustedProfileParse::Empty
1752 ));
1753 }
1754
1755 #[test]
1756 fn draft_gate_accepts_fenced_output() {
1757 let raw = "Here you go:\n```json\n{\"id\":\"reviewer\",\"role_hint\":\"reviewer\",\"description\":\"Reviews diffs.\"}\n```";
1758 assert!(matches!(
1759 FleetProfileDraft::from_untrusted_json(raw),
1760 UntrustedProfileParse::Drafted(_)
1761 ));
1762 }
1763
1764 #[test]
1765 fn rendered_draft_round_trips_through_the_loader_with_floor_permissions() {
1766 let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(
1767 r#"{"id":"reviewer","display_name":"Reviewer","description":"Reviews diffs for correctness.","role_hint":"reviewer","model_class_hint":"cheap","model":"glm-5.2","instructions":"Read the diff.\nReport findings, then stop."}"#,
1768 ) else {
1769 panic!("draft should parse");
1770 };
1771
1772 let dir = TempDir::new().unwrap();
1773 let path = write_profile(dir.path(), &draft.file_name(), &draft.render_toml());
1774 let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
1775 assert_eq!(profiles.len(), 1);
1776 let loaded = &profiles[0];
1777 assert_eq!(loaded.id, "reviewer");
1778 assert_eq!(loaded.display_name.as_deref(), Some("Reviewer"));
1779 assert_eq!(loaded.profile.model.as_deref(), Some("glm-5.2"));
1780 assert_eq!(
1781 loaded.profile.role.instructions.as_deref(),
1782 Some("Read the diff.\nReport findings, then stop.")
1783 );
1784 // The loader always installs the permission floor, no matter what.
1785 assert_eq!(
1786 loaded.profile.permissions,
1787 FleetProfilePermissions::default()
1788 );
1789 assert_eq!(path, loaded.source);
1790 }
1791
1792 #[test]
1793 fn draft_with_explicit_provider_round_trips_through_the_loader() {
1794 // A structured (picker-driven) draft that pins a model on a provider
1795 // other than whatever the parent session happens to use (#4093): the
1796 // rendered TOML must carry both fields explicitly, and the loader
1797 // must read the provider back out verbatim — never re-derive it by
1798 // sniffing `model` for a provider-shaped substring.
1799 let draft = FleetProfileDraft {
1800 id: "scout-deepseek".to_string(),
1801 display_name: Some("Scout".to_string()),
1802 description: Some("Cross-provider scout profile.".to_string()),
1803 role_hint: "scout".to_string(),
1804 model_class_hint: None,
1805 model: Some("deepseek-v4-flash".to_string()),
1806 provider: Some("deepseek".to_string()),
1807 reasoning_effort: None,
1808 instructions: None,
1809 };
1810
1811 let rendered = draft.render_toml();
1812 assert!(
1813 rendered.contains("provider = \"deepseek\""),
1814 "rendered TOML must persist the explicit provider: {rendered}"
1815 );
1816 assert!(rendered.contains("model = \"deepseek-v4-flash\""));
1817
1818 let dir = TempDir::new().unwrap();
1819 write_profile(dir.path(), &draft.file_name(), &rendered);
1820 let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
1821 assert_eq!(profiles.len(), 1);
1822 let loaded = &profiles[0];
1823 assert_eq!(loaded.profile.model.as_deref(), Some("deepseek-v4-flash"));
1824 assert_eq!(loaded.profile.provider.as_deref(), Some("deepseek"));
1825 }
1826
1827 #[test]
1828 fn draft_with_reasoning_effort_round_trips_through_the_loader() {
1829 let draft = FleetProfileDraft {
1830 id: "scout-deep".to_string(),
1831 display_name: Some("Scout".to_string()),
1832 description: Some("Deep scout profile.".to_string()),
1833 role_hint: "scout".to_string(),
1834 model_class_hint: None,
1835 model: Some("deepseek-v4-pro".to_string()),
1836 provider: Some("deepseek".to_string()),
1837 reasoning_effort: Some("max".to_string()),
1838 instructions: None,
1839 };
1840
1841 let rendered = draft.render_toml();
1842 assert!(
1843 rendered.contains("reasoning_effort = \"max\""),
1844 "rendered TOML must persist explicit reasoning: {rendered}"
1845 );
1846
1847 let dir = TempDir::new().unwrap();
1848 write_profile(dir.path(), &draft.file_name(), &rendered);
1849 let profiles = load_agent_profiles_from_dir(dir.path()).expect("rendered TOML loads");
1850 assert_eq!(profiles.len(), 1);
1851 let loaded = &profiles[0];
1852 assert_eq!(loaded.profile.provider.as_deref(), Some("deepseek"));
1853 assert_eq!(loaded.profile.model.as_deref(), Some("deepseek-v4-pro"));
1854 assert_eq!(loaded.profile.reasoning_effort.as_deref(), Some("max"));
1855 }
1856
1857 #[test]
1858 fn profile_loader_normalizes_reasoning_aliases() {
1859 let dir = TempDir::new().unwrap();
1860 write_profile(
1861 dir.path(),
1862 "scout.toml",
1863 r#"
1864 id = "scout"
1865 role_hint = "scout"
1866 thinking = "ultracode"
1867
1868 [instructions]
1869 text = "Scout deeply."
1870 "#,
1871 );
1872
1873 let profiles = load_agent_profiles_from_dir(dir.path()).expect("profile TOML loads");
1874 assert_eq!(profiles.len(), 1);
1875 // `xhigh` used to land here too; the thinking ladder made it a rung of
1876 // its own, so `ultracode` is the alias left to exercise.
1877 assert_eq!(
1878 profiles[0].profile.reasoning_effort.as_deref(),
1879 Some("ultra")
1880 );
1881 }
1882
1883 #[test]
1884 fn profile_loader_migrates_advisory_role_aliases_to_consultant() {
1885 let dir = tempfile::tempdir().unwrap();
1886 for alias in ["oracle", "advisor"] {
1887 let path = dir.path().join(format!("{alias}.toml"));
1888 std::fs::write(
1889 &path,
1890 format!("id = \"{alias}\"\nrole_hint = \"{alias}\"\n"),
1891 )
1892 .unwrap();
1893 let loaded = load_agent_profile_file(None, &path).expect("load compatibility profile");
1894 assert_eq!(loaded.id, alias, "saved identity remains addressable");
1895 assert_eq!(loaded.profile.role.name, "advisor");
1896 assert_eq!(loaded.profile.slot.as_str(), "advisor");
1897 }
1898 }
1899
1900 #[test]
1901 fn model_draft_migrates_advisory_role_alias_to_consultant() {
1902 let UntrustedProfileParse::Drafted(draft) = FleetProfileDraft::from_untrusted_json(
1903 r#"{"id":"second-opinion","role_hint":"oracle","description":"Counsel."}"#,
1904 ) else {
1905 panic!("expected a drafted profile");
1906 };
1907 assert_eq!(draft.role_hint, "advisor");
1908 assert!(draft.render_toml().contains("role_hint = \"advisor\""));
1909 }
1910
1911 #[test]
1912 fn profile_loader_rejects_unknown_reasoning_effort() {
1913 let dir = TempDir::new().unwrap();
1914 write_profile(
1915 dir.path(),
1916 "scout.toml",
1917 r#"
1918 id = "scout"
1919 role_hint = "scout"
1920 reasoning = "expensive"
1921 "#,
1922 );
1923
1924 let err = load_agent_profiles_from_dir(dir.path()).expect_err("invalid effort must fail");
1925 assert!(
1926 err.to_string().contains("reasoning_effort"),
1927 "unexpected error: {err}"
1928 );
1929 }
1930
1931 #[test]
1932 fn inherit_draft_never_renders_a_provider_without_a_model() {
1933 // `provider` is only meaningful alongside a concrete model pin; an
1934 // `inherit` draft (no `model`) must never render one even if a stale
1935 // caller sets the field.
1936 let draft = FleetProfileDraft {
1937 id: "inherit".to_string(),
1938 display_name: None,
1939 description: None,
1940 role_hint: "general".to_string(),
1941 model_class_hint: None,
1942 model: None,
1943 provider: Some("deepseek".to_string()),
1944 reasoning_effort: None,
1945 instructions: None,
1946 };
1947 let rendered = draft.render_toml();
1948 assert!(!rendered.contains("provider"), "{rendered}");
1949 }
1950
1951 #[test]
1952 fn claude_tools_map_to_the_closest_role_posture() {
1953 assert_eq!(claude_tools_role(None), "general");
1954 assert_eq!(claude_tools_role(Some(" ")), "general");
1955 assert_eq!(
1956 claude_tools_role(Some("Read, Grep, Glob, WebFetch")),
1957 "explore"
1958 );
1959 assert_eq!(claude_tools_role(Some("[Read, Grep]")), "explore");
1960 assert_eq!(claude_tools_role(Some("Read, Bash")), "test");
1961 assert_eq!(claude_tools_role(Some("Read, mcp__github__search")), "test");
1962 assert_eq!(claude_tools_role(Some("Read, Edit")), "implement");
1963 assert_eq!(claude_tools_role(Some("Bash MultiEdit")), "implement");
1964 }
1965
1966 #[test]
1967 fn claude_agent_without_frontmatter_or_name_is_handled() {
1968 let tmp = tempfile::TempDir::new().unwrap();
1969 write_profile(tmp.path(), "plain.md", "# Just a heading\nno frontmatter\n");
1970 write_profile(
1971 tmp.path(),
1972 "from-stem.md",
1973 "---\ndescription: >\n Folded\n description\nmodel: deepseek-v4-pro\n---\nBody.\n",
1974 );
1975 let (profiles, issues) = load_claude_agent_profiles_from_dir(tmp.path()).unwrap();
1976 assert_eq!(profiles.len(), 1);
1977 assert_eq!(profiles[0].id, "from-stem");
1978 assert_eq!(
1979 profiles[0].description.as_deref(),
1980 Some("Folded description")
1981 );
1982 assert_eq!(
1983 profiles[0].profile.model.as_deref(),
1984 Some("deepseek-v4-pro")
1985 );
1986 assert_eq!(issues.len(), 1);
1987 assert_eq!(issues[0].id, "plain");
1988 assert!(
1989 issues[0].detail.contains("no `---` frontmatter"),
1990 "{}",
1991 issues[0].detail
1992 );
1993 }
1994
1995 #[test]
1996 fn claude_agent_unquoted_multiline_description_loads_like_claude_code() {
1997 let tmp = tempfile::TempDir::new().unwrap();
1998 write_profile(
1999 tmp.path(),
2000 "dev-planner.md",
2001 "---\nname: dev-planner\ndescription: Plans work. Use when planning.\n\nExamples:\n- <example>\n Context: a feature\n user: \"Plan it\"\n assistant: \"I'll plan\"\n </example>\n# trailing note\n\ntools: Read, Grep\nmodel: opus\n---\nYou plan.\n",
2002 );
2003 write_profile(
2004 tmp.path(),
2005 "comment-only.md",
2006 "---\nname: comment-only\ndescription: Reviewer\n# todo\ntools: Read\n---\nReview.\n",
2007 );
2008 write_profile(
2009 tmp.path(),
2010 "unknown-after-description.md",
2011 "---\nname: guarded\ndescription: Read-only reviewer\nallowed-tools: Read, Grep\n---\nReview.\n",
2012 );
2013 write_profile(
2014 tmp.path(),
2015 "broken.md",
2016 "---\nname: broken\ndescription: never closed\n",
2017 );
2018 let (profiles, issues) = load_claude_agent_profiles_from_dir(tmp.path()).unwrap();
2019 assert_eq!(profiles.len(), 2, "{issues:?}");
2020 let planner = profiles.iter().find(|p| p.id == "dev-planner").unwrap();
2021 let description = planner.description.as_deref().unwrap();
2022 assert!(
2023 description.starts_with(
2024 "Plans work. Use when planning.\n\nExamples:\n- <example>\n Context: a feature"
2025 ),
2026 "{description}"
2027 );
2028 assert!(description.ends_with("</example>"), "{description}");
2029 assert!(!description.contains("# trailing note"), "{description}");
2030 assert_eq!(planner.profile.role.name, "explore");
2031 assert_eq!(
2032 planner.profile.role.instructions.as_deref(),
2033 Some("You plan.")
2034 );
2035 let comment_only = profiles.iter().find(|p| p.id == "comment-only").unwrap();
2036 assert_eq!(comment_only.description.as_deref(), Some("Reviewer"));
2037 assert_eq!(issues.len(), 2);
2038 let broken = issues.iter().find(|i| i.id == "broken").unwrap();
2039 assert!(!broken.detail.contains('\n'), "{}", broken.detail);
2040 assert!(
2041 broken.detail.contains("closing delimiter"),
2042 "{}",
2043 broken.detail
2044 );
2045 let unknown = issues
2046 .iter()
2047 .find(|i| i.id == "unknown-after-description")
2048 .unwrap();
2049 assert!(
2050 unknown.detail.contains("allowed-tools"),
2051 "{}",
2052 unknown.detail
2053 );
2054 }
2055
2056 #[test]
2057 fn claude_agent_tools_as_a_yaml_list_keep_the_read_only_posture() {
2058 let tmp = tempfile::TempDir::new().unwrap();
2059 write_profile(
2060 tmp.path(),
2061 "reader.md",
2062 "---\nname: reader\ntools:\n - Read\n - \"Grep\"\ndescription: Reads\n---\nBody.\n",
2063 );
2064 write_profile(
2065 tmp.path(),
2066 "writer.md",
2067 "---\nname: writer\ntools:\n- Read\n- Edit\n---\nBody.\n",
2068 );
2069 let (mut profiles, issues) = load_claude_agent_profiles_from_dir(tmp.path()).unwrap();
2070 assert!(issues.is_empty(), "{issues:?}");
2071 profiles.sort_by(|a, b| a.id.cmp(&b.id));
2072 assert_eq!(profiles[0].id, "reader");
2073 assert_eq!(profiles[0].profile.role.name, "explore");
2074 assert_eq!(profiles[0].description.as_deref(), Some("Reads"));
2075 assert_eq!(profiles[1].id, "writer");
2076 assert_eq!(profiles[1].profile.role.name, "implement");
2077 }
2078
2079 fn write_profile(dir: &Path, filename: &str, contents: &str) -> PathBuf {
2080 let path = dir.join(filename);
2081 std::fs::write(&path, contents).unwrap();
2082 path
2083 }
2084
2085 #[test]
2086 fn fleet_profile_round_trips_through_serde_with_safe_defaults() {
2087 let profile = FleetProfile::default();
2088
2089 let serialized = toml::to_string(&profile).expect("profile serializes");
2090 let round_tripped: FleetProfile =
2091 toml::from_str(&serialized).expect("profile deserializes");
2092
2093 assert_eq!(round_tripped, profile);
2094 assert_eq!(round_tripped.role.name, "general");
2095 assert_eq!(round_tripped.loadout, FleetLoadout::Inherit);
2096 assert!(!round_tripped.permissions.allow_shell);
2097 assert!(!round_tripped.permissions.trust);
2098 assert!(round_tripped.permissions.approval_required);
2099 assert_eq!(round_tripped.delegation.max_spawn_depth, None);
2100 assert_eq!(round_tripped.delegation.max_concurrency, None);
2101 }
2102
2103 #[test]
2104 fn fleet_profile_explicit_toml_parses_role_loadout_permissions() {
2105 let profile: FleetProfile = toml::from_str(
2106 r#"
2107 slot = "reviewer"
2108 loadout = "deep-reasoning"
2109
2110 [role]
2111 name = "verifier"
2112 instructions = "Review the patch and produce verification evidence."
2113
2114 [permissions]
2115 allow_shell = true
2116 trust = true
2117 approval_required = false
2118
2119 [delegation]
2120 max_spawn_depth = 1
2121 concurrency = 2
2122 "#,
2123 )
2124 .expect("explicit fleet profile parses");
2125
2126 assert_eq!(profile.slot, FleetSlot::Reviewer);
2127 assert_eq!(profile.role.name, "verifier");
2128 assert_eq!(
2129 profile.role.instructions.as_deref(),
2130 Some("Review the patch and produce verification evidence.")
2131 );
2132 assert_eq!(
2133 profile.loadout,
2134 FleetLoadout::Custom("deep-reasoning".to_string())
2135 );
2136 assert!(profile.permissions.allow_shell);
2137 assert!(profile.permissions.trust);
2138 assert!(!profile.permissions.approval_required);
2139 assert_eq!(profile.delegation.max_spawn_depth, Some(1));
2140 assert_eq!(profile.delegation.max_concurrency, Some(2));
2141 }
2142
2143 #[test]
2144 fn fleet_profile_accepts_compact_role_string() {
2145 let profile: FleetProfile = toml::from_str(
2146 r#"
2147 role = "scout"
2148 loadout = "fast"
2149 model = "deepseek-v4-flash"
2150 "#,
2151 )
2152 .expect("compact fleet profile parses");
2153
2154 assert_eq!(profile.role.name, "scout");
2155 assert_eq!(profile.loadout, FleetLoadout::Fast);
2156 assert_eq!(profile.model.as_deref(), Some("deepseek-v4-flash"));
2157 assert_eq!(profile.permissions, FleetProfilePermissions::default());
2158 }
2159
2160 #[test]
2161 fn agent_profile_loader_returns_empty_for_missing_workspace_dir() {
2162 let tmp = TempDir::new().unwrap();
2163
2164 let profiles = load_workspace_agent_profiles(tmp.path()).unwrap();
2165
2166 assert!(profiles.is_empty());
2167 }
2168
2169 #[test]
2170 fn profile_identity_loader_accepts_legacy_route_policy_fields() {
2171 let tmp = TempDir::new().unwrap();
2172 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2173 std::fs::create_dir_all(&agents_dir).unwrap();
2174 let source = write_profile(
2175 &agents_dir,
2176 "reviewer.toml",
2177 r#"
2178 id = "reviewer"
2179 role_hint = "reviewer"
2180 model_class_hint = "heavy"
2181 models = ["glm-5.2", "deepseek-v4-pro"]
2182 "#,
2183 );
2184
2185 let identities = load_workspace_agent_profile_identities(tmp.path())
2186 .expect("legacy fields do not obscure identity");
2187
2188 assert_eq!(
2189 identities,
2190 vec![AgentProfileIdentity {
2191 id: "reviewer".to_string(),
2192 source,
2193 }]
2194 );
2195 }
2196
2197 #[test]
2198 fn profile_identity_loader_fails_closed_for_malformed_toml() {
2199 let tmp = TempDir::new().unwrap();
2200 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2201 std::fs::create_dir_all(&agents_dir).unwrap();
2202 write_profile(&agents_dir, "broken.toml", "id = [\n");
2203
2204 let err = load_workspace_agent_profile_identities(tmp.path())
2205 .expect_err("malformed TOML cannot prove collision safety")
2206 .to_string();
2207
2208 assert!(err.contains("broken.toml"), "unexpected error: {err}");
2209 assert!(err.contains("profile identity"), "unexpected error: {err}");
2210 }
2211
2212 #[test]
2213 fn tolerant_loader_keeps_valid_profile_beside_legacy_profile() {
2214 let tmp = TempDir::new().unwrap();
2215 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2216 std::fs::create_dir_all(&agents_dir).unwrap();
2217 write_profile(
2218 &agents_dir,
2219 "reviewer.toml",
2220 "id = \"reviewer\"\nmodel_class_hint = \"heavy\"\n",
2221 );
2222 write_profile(
2223 &agents_dir,
2224 "scout.toml",
2225 "id = \"scout\"\nrole_hint = \"scout\"\nprovider = \"deepseek\"\nmodel = \"deepseek-v4-flash\"\n",
2226 );
2227
2228 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
2229 .expect("directory discovery succeeds");
2230
2231 assert_eq!(profiles.len(), 1);
2232 assert_eq!(profiles[0].id, "scout");
2233 assert_eq!(
2234 profiles[0].profile.model.as_deref(),
2235 Some("deepseek-v4-flash")
2236 );
2237 assert_eq!(issues.len(), 1);
2238 assert!(issues[0].detail.contains("reviewer.toml"), "{issues:?}");
2239 assert!(issues[0].detail.contains("model_class_hint"), "{issues:?}");
2240 }
2241
2242 /// A workspace must not make a profile read land outside itself: a linked
2243 /// profile file, or a linked profile directory, is refused and the content
2244 /// behind the link never loads.
2245 #[cfg(unix)]
2246 #[test]
2247 fn workspace_profiles_do_not_follow_links_out_of_the_workspace() {
2248 use std::os::unix::fs::symlink;
2249 let tmp = TempDir::new().unwrap();
2250 let outside = TempDir::new().unwrap();
2251 let hidden = "id = \"smuggled\"\nrole_hint = \"scout\"\n";
2252 write_profile(outside.path(), "smuggled.toml", hidden);
2253
2254 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2255 std::fs::create_dir_all(&agents_dir).unwrap();
2256 write_profile(
2257 &agents_dir,
2258 "scout.toml",
2259 "id = \"scout\"\nrole_hint = \"scout\"\n",
2260 );
2261 symlink(
2262 outside.path().join("smuggled.toml"),
2263 agents_dir.join("linked.toml"),
2264 )
2265 .unwrap();
2266
2267 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
2268 .expect("directory discovery succeeds");
2269 assert_eq!(
2270 profiles.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
2271 vec!["scout"]
2272 );
2273 assert_eq!(issues.len(), 1, "{issues:?}");
2274 assert!(issues[0].detail.contains("linked.toml"), "{issues:?}");
2275 assert!(
2276 load_workspace_agent_profile_identities(tmp.path()).is_err(),
2277 "the identity reader refuses the linked file too"
2278 );
2279 assert!(load_workspace_agent_profiles(tmp.path()).is_err());
2280
2281 // A linked profile directory is refused as a whole.
2282 let other = TempDir::new().unwrap();
2283 std::fs::create_dir_all(other.path().join(".codewhale")).unwrap();
2284 symlink(
2285 outside.path(),
2286 other.path().join(WORKSPACE_AGENT_PROFILE_DIR),
2287 )
2288 .unwrap();
2289 let error = load_workspace_agent_profiles_tolerant(other.path())
2290 .expect_err("a linked profile directory is refused");
2291 assert!(
2292 format!("{error:#}").contains("Refusing symlinked"),
2293 "{error:#}"
2294 );
2295
2296 // The same directory is the user's own when no workspace root applies.
2297 let (personal, _) = load_agent_profiles_from_dir_tolerant(
2298 other.path().join(WORKSPACE_AGENT_PROFILE_DIR),
2299 ProfileOrigin::Personal,
2300 )
2301 .expect("an operator-owned directory may be a link");
2302 assert_eq!(personal.len(), 1);
2303 }
2304
2305 #[cfg(unix)]
2306 #[test]
2307 fn workspace_claude_agent_files_do_not_follow_links_out_of_the_workspace() {
2308 use std::os::unix::fs::symlink;
2309 let tmp = TempDir::new().unwrap();
2310 let outside = TempDir::new().unwrap();
2311 write_profile(
2312 outside.path(),
2313 "smuggled.md",
2314 "---\nname: smuggled\ndescription: x\n---\nBody.\n",
2315 );
2316 let dir = tmp.path().join(CLAUDE_AGENT_DIR);
2317 std::fs::create_dir_all(&dir).unwrap();
2318 symlink(outside.path().join("smuggled.md"), dir.join("linked.md")).unwrap();
2319
2320 let (profiles, issues) =
2321 load_claude_agent_profiles_from_dir_in(Some(tmp.path()), &dir).unwrap();
2322 assert!(profiles.is_empty(), "{profiles:?}");
2323 assert_eq!(issues.len(), 1, "{issues:?}");
2324 // Without a workspace root the same file still loads: only workspace
2325 // content is confined.
2326 let (profiles, _) = load_claude_agent_profiles_from_dir(&dir).unwrap();
2327 assert_eq!(profiles.len(), 1);
2328 }
2329
2330 #[test]
2331 fn indented_markdown_route_preserves_the_exact_pin_and_instruction_bytes() {
2332 let path = Path::new("reviewer.md");
2333 let raw = "---\r\n name: reviewer\r\n model: old\r\n tools: Read\r\n---\r\nReview.\r\n";
2334 let updated =
2335 set_markdown_profile_route(path, raw, Some("custom"), Some("sonnet"), None).unwrap();
2336 assert_eq!(updated.matches("model:").count(), 1);
2337 assert!(updated.ends_with("---\r\nReview.\r\n"));
2338 let cleared = set_markdown_profile_route(path, &updated, None, None, None).unwrap();
2339 assert!(!cleared.contains("model:"));
2340 assert!(!cleared.contains("provider:"));
2341 }
2342
2343 #[test]
2344 fn markdown_profiles_share_scope_and_identity_checks_with_toml() {
2345 let tmp = TempDir::new().unwrap();
2346 let dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2347 std::fs::create_dir_all(&dir).unwrap();
2348 let text = "---\nname: reviewer\ntools: Read, Grep\n---\nInspect the diff.\n";
2349 write_profile(&dir, "README.md", "# Our agents\n");
2350 let path = write_profile(&dir, "worker.md", text);
2351 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path()).unwrap();
2352 assert!(issues.is_empty());
2353 assert_eq!(profiles.len(), 1);
2354 let profile = &profiles[0];
2355 assert_eq!(profile.origin, ProfileOrigin::Workspace);
2356 assert_eq!(profile.id, "reviewer");
2357 assert_eq!(
2358 profile.profile.role.instructions.as_deref(),
2359 Some("Inspect the diff.")
2360 );
2361 assert_eq!(profile.profile.role.name, "explore");
2362 assert_eq!(
2363 read_agent_profile_document(FleetProfileScope::Project, tmp.path(), &path)
2364 .unwrap()
2365 .as_deref(),
2366 Some(text)
2367 );
2368 let updated = set_markdown_profile_route(
2369 &path,
2370 text,
2371 Some("deepseek"),
2372 Some("custom-model"),
2373 Some("high"),
2374 )
2375 .unwrap();
2376 let parsed = parse_agent_profile_text(&path, &updated).unwrap();
2377 assert_eq!(parsed.profile.provider.as_deref(), Some("deepseek"));
2378 assert_eq!(parsed.profile.reasoning_effort.as_deref(), Some("high"));
2379 assert_eq!(parsed.profile.model.as_deref(), Some("custom-model"));
2380 assert_eq!(parsed.profile.role, profile.profile.role);
2381 assert_eq!(
2382 load_workspace_agent_profile_identities(tmp.path())
2383 .unwrap()
2384 .len(),
2385 1
2386 );
2387 write_profile(&dir, "other.toml", "id = \"reviewer\"\n");
2388 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path()).unwrap();
2389 assert!(profiles.is_empty());
2390 assert_eq!(issues.len(), 2);
2391 assert!(
2392 issues
2393 .iter()
2394 .all(|issue| issue.detail.contains("duplicate agent profile id reviewer"))
2395 );
2396 }
2397
2398 #[test]
2399 fn tolerant_loader_skips_every_duplicate_id_but_keeps_unique_neighbors() {
2400 let tmp = TempDir::new().unwrap();
2401 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2402 std::fs::create_dir_all(&agents_dir).unwrap();
2403 write_profile(&agents_dir, "a.toml", "id = \"reviewer\"\n");
2404 write_profile(&agents_dir, "b.toml", "name = \"reviewer\"\n");
2405 write_profile(&agents_dir, "scout.toml", "id = \"scout\"\n");
2406
2407 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
2408 .expect("directory discovery succeeds");
2409
2410 assert_eq!(
2411 profiles
2412 .iter()
2413 .map(|profile| profile.id.as_str())
2414 .collect::<Vec<_>>(),
2415 vec!["scout"]
2416 );
2417 assert_eq!(issues.len(), 2);
2418 assert!(
2419 issues
2420 .iter()
2421 .all(|issue| issue.detail.contains("duplicate agent profile id reviewer")),
2422 "{issues:?}"
2423 );
2424 }
2425
2426 #[test]
2427 fn profile_identity_loader_fails_closed_for_invalid_id_token() {
2428 let tmp = TempDir::new().unwrap();
2429 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2430 std::fs::create_dir_all(&agents_dir).unwrap();
2431 write_profile(&agents_dir, "broken.toml", "id = \"bad id\"\n");
2432
2433 let err = load_workspace_agent_profile_identities(tmp.path())
2434 .expect_err("invalid identity tokens cannot prove collision safety")
2435 .to_string();
2436
2437 assert!(err.contains("broken.toml"), "unexpected error: {err}");
2438 assert!(err.contains("simple token"), "unexpected error: {err}");
2439 }
2440
2441 #[test]
2442 fn scout_save_succeeds_beside_untouched_legacy_reviewer() {
2443 let tmp = TempDir::new().unwrap();
2444 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2445 std::fs::create_dir_all(&agents_dir).unwrap();
2446 let legacy = r#"
2447 id = "reviewer"
2448 role_hint = "reviewer"
2449 model_class_hint = "heavy"
2450 models = ["glm-5.2", "deepseek-v4-pro"]
2451 "#;
2452 let reviewer_path = write_profile(&agents_dir, "reviewer.toml", legacy);
2453 let before = std::fs::read_to_string(&reviewer_path).unwrap();
2454
2455 let identities = load_workspace_agent_profile_identities(tmp.path())
2456 .expect("legacy neighbor must not block identity discovery");
2457 assert_eq!(identities.len(), 1);
2458 assert_eq!(identities[0].id, "reviewer");
2459 assert!(
2460 identities
2461 .iter()
2462 .all(|identity| !identity.id.eq_ignore_ascii_case("scout")),
2463 "scout id must be free beside legacy reviewer"
2464 );
2465
2466 let draft = FleetProfileDraft {
2467 id: "scout".to_string(),
2468 display_name: Some("Scout".to_string()),
2469 description: Some("Workspace scout.".to_string()),
2470 role_hint: "scout".to_string(),
2471 model_class_hint: None,
2472 model: Some("deepseek-v4-flash".to_string()),
2473 provider: Some("deepseek".to_string()),
2474 reasoning_effort: None,
2475 instructions: None,
2476 };
2477 let scout_path = write_profile(&agents_dir, &draft.file_name(), &draft.render_toml());
2478
2479 let after = std::fs::read_to_string(&reviewer_path).unwrap();
2480 assert_eq!(before, after, "legacy reviewer must remain unmodified");
2481 assert!(scout_path.exists());
2482
2483 let (profiles, issues) = load_workspace_agent_profiles_tolerant(tmp.path())
2484 .expect("directory discovery succeeds");
2485 assert_eq!(profiles.len(), 1);
2486 assert_eq!(profiles[0].id, "scout");
2487 assert_eq!(
2488 profiles[0].profile.model.as_deref(),
2489 Some("deepseek-v4-flash")
2490 );
2491 assert_eq!(issues.len(), 1);
2492 assert!(issues[0].detail.contains("reviewer.toml"), "{issues:?}");
2493 }
2494
2495 #[test]
2496 fn agent_profile_loader_normalizes_project_agent_toml() {
2497 let tmp = TempDir::new().unwrap();
2498 let agents_dir = tmp.path().join(WORKSPACE_AGENT_PROFILE_DIR);
2499 std::fs::create_dir_all(&agents_dir).unwrap();
2500 let source = write_profile(
2501 &agents_dir,
2502 "reviewer.toml",
2503 r#"
2504 name = "adversarial_reviewer"
2505 display_name = "Adversarial Reviewer"
2506 description = "Skeptical read-only review posture"
2507 role_hint = "reviewer"
2508 loadout = "balanced"
2509 model = "deepseek-v4-pro"
2510
2511 [instructions]
2512 text = "Focus on regressions, missing tests, and fragile assumptions."
2513
2514 [tools]
2515 posture = "read-only"
2516 "#,
2517 );
2518
2519 let profiles = load_workspace_agent_profiles(tmp.path()).unwrap();
2520
2521 assert_eq!(profiles.len(), 1);
2522 let profile = &profiles[0];
2523 assert_eq!(profile.id, "adversarial_reviewer");
2524 assert_eq!(
2525 profile.display_name.as_deref(),
2526 Some("Adversarial Reviewer")
2527 );
2528 assert_eq!(
2529 profile.description.as_deref(),
2530 Some("Skeptical read-only review posture")
2531 );
2532 assert_eq!(profile.profile.slot, FleetSlot::Reviewer);
2533 assert_eq!(profile.profile.role.name, "reviewer");
2534 assert_eq!(
2535 profile.profile.role.instructions.as_deref(),
2536 Some("Focus on regressions, missing tests, and fragile assumptions.")
2537 );
2538 assert_eq!(
2539 profile.profile.loadout,
2540 FleetLoadout::Custom("balanced".to_string())
2541 );
2542 assert_eq!(profile.profile.model.as_deref(), Some("deepseek-v4-pro"));
2543 assert_eq!(
2544 profile.profile.permissions,
2545 FleetProfilePermissions::default()
2546 );
2547 assert_eq!(profile.source, source);
2548 }
2549
2550 #[test]
2551 fn agent_profile_loader_rejects_retired_model_policy_aliases() {
2552 for (field, value) in [("model_class_hint", "balanced"), ("route_tier", "fast")] {
2553 let tmp = TempDir::new().unwrap();
2554 write_profile(
2555 tmp.path(),
2556 "reviewer.toml",
2557 &format!(
2558 r#"
2559 name = "reviewer"
2560 role_hint = "reviewer"
2561 {field} = "{value}"
2562 "#
2563 ),
2564 );
2565
2566 let err = load_agent_profiles_from_dir(tmp.path())
2567 .unwrap_err()
2568 .to_string();
2569
2570 assert!(
2571 err.contains(field) || err.contains("unknown field"),
2572 "unexpected error for {field}: {err}"
2573 );
2574 }
2575 }
2576
2577 #[test]
2578 fn agent_profile_loader_accepts_and_round_trips_explicit_provider_field() {
2579 // #4093: `provider` is now a first-class, validated field — a Fleet
2580 // profile can name its own route explicitly, independent of whatever
2581 // provider is active when the profile is later loaded/launched.
2582 let tmp = TempDir::new().unwrap();
2583 write_profile(
2584 tmp.path(),
2585 "reviewer.toml",
2586 r#"
2587 name = "reviewer"
2588 provider = "openrouter"
2589 model = "deepseek/deepseek-v4-pro"
2590 "#,
2591 );
2592
2593 let profiles = load_agent_profiles_from_dir(tmp.path()).expect("profile loads");
2594 assert_eq!(profiles.len(), 1);
2595 assert_eq!(profiles[0].profile.provider.as_deref(), Some("openrouter"));
2596 assert_eq!(
2597 profiles[0].profile.model.as_deref(),
2598 Some("deepseek/deepseek-v4-pro")
2599 );
2600 }
2601
2602 #[test]
2603 fn agent_profile_loader_accepts_custom_provider_name() {
2604 // #3965: LM Studio and other user-named OpenAI-compatible providers
2605 // are resolved from `[providers.<id>]` at launch time, so the profile
2606 // loader must preserve the safe id instead of requiring a built-in.
2607 let tmp = TempDir::new().unwrap();
2608 write_profile(
2609 tmp.path(),
2610 "reviewer.toml",
2611 r#"
2612 name = "reviewer"
2613 provider = "lm-studio"
2614 model = "qwen-2.5-7b"
2615 "#,
2616 );
2617
2618 let profiles = load_agent_profiles_from_dir(tmp.path()).expect("profile loads");
2619
2620 assert_eq!(profiles[0].profile.provider.as_deref(), Some("lm-studio"));
2621 assert_eq!(profiles[0].profile.model.as_deref(), Some("qwen-2.5-7b"));
2622 }
2623
2624 #[test]
2625 fn agent_profile_loader_rejects_malformed_provider_name() {
2626 let tmp = TempDir::new().unwrap();
2627 write_profile(
2628 tmp.path(),
2629 "reviewer.toml",
2630 r#"
2631 name = "reviewer"
2632 provider = "lm studio"
2633 model = "some-model"
2634 "#,
2635 );
2636
2637 let err = load_agent_profiles_from_dir(tmp.path())
2638 .unwrap_err()
2639 .to_string();
2640
2641 assert!(
2642 err.contains("provider must be a simple provider id"),
2643 "unexpected error: {err}"
2644 );
2645 }
2646
2647 #[test]
2648 fn agent_profile_loader_rejects_permission_expansion() {
2649 let tmp = TempDir::new().unwrap();
2650 write_profile(
2651 tmp.path(),
2652 "builder.toml",
2653 r#"
2654 name = "builder"
2655
2656 [tools]
2657 posture = "read-write"
2658 "#,
2659 );
2660
2661 let err = load_agent_profiles_from_dir(tmp.path())
2662 .unwrap_err()
2663 .to_string();
2664
2665 assert!(
2666 err.contains("would widen permissions"),
2667 "unexpected error: {err}"
2668 );
2669 }
2670
2671 #[test]
2672 fn agent_profile_loader_rejects_secret_like_model_hint() {
2673 let tmp = TempDir::new().unwrap();
2674 write_profile(
2675 tmp.path(),
2676 "reviewer.toml",
2677 r#"
2678 name = "reviewer"
2679 model = "deepseek-v4-pro api_key=secret"
2680 "#,
2681 );
2682
2683 let err = load_agent_profiles_from_dir(tmp.path())
2684 .unwrap_err()
2685 .to_string();
2686
2687 assert!(
2688 err.contains("model must be a visible model id"),
2689 "unexpected error: {err}"
2690 );
2691 }
2692
2693 #[test]
2694 fn agent_profile_loader_rejects_duplicate_ids() {
2695 let tmp = TempDir::new().unwrap();
2696 write_profile(tmp.path(), "a.toml", "name = \"reviewer\"\n");
2697 write_profile(tmp.path(), "b.toml", "id = \"reviewer\"\n");
2698
2699 let err = load_agent_profiles_from_dir(tmp.path())
2700 .unwrap_err()
2701 .to_string();
2702
2703 assert!(
2704 err.contains("duplicate agent profile id reviewer"),
2705 "unexpected error: {err}"
2706 );
2707 }
2708 }
2709
2709 lines RUST