返回 CodeWhale
saved_whales.rs
根目录 / crates / engine / src / saved_whales.rs
1 use std::path::{Path, PathBuf};
2
3 use anyhow::{Context, Result, ensure};
4 use serde::{Deserialize, Serialize};
5 use serde_json::{Map, Value};
6 use toml_edit::{DocumentMut, Item, Table, value};
7
8 use crate::fleet::profile::{
9 AgentProfile, FleetProfileScope, MAX_PROFILE_DOCUMENT_BYTES, agent_document_entries,
10 parse_agent_profile_text, personal_agent_profile_dir, read_agent_profile_document,
11 retire_personal_profile, save_agent_profile_document,
12 };
13
14 #[derive(Debug, Default, Deserialize, Serialize)]
15 #[serde(default, deny_unknown_fields)]
16 pub struct WhaleSettings {
17 #[serde(skip_serializing)]
18 pub instance_id: Option<uuid::Uuid>,
19 pub color: Option<String>,
20 pub external_agent_id: Option<String>,
21 pub permission_posture: Option<String>,
22 pub child_posture: Option<String>,
23 #[serde(skip_serializing)]
24 account_agent_id: Option<String>,
25 pub home_thread_id: Option<String>,
26 }
27
28 impl WhaleSettings {
29 pub(crate) fn validate(&self) -> Result<()> {
30 let ranks = ["ask", "accept_edits", "auto_review", "full_access"];
31 let rank = |s: &str| {
32 ranks
33 .iter()
34 .position(|candidate| *candidate == s)
35 .context("Unknown whale permission posture")
36 };
37 let parent = self.permission_posture.as_deref().map(rank).transpose()?;
38 let child = self.child_posture.as_deref().map(rank).transpose()?;
39 ensure!(
40 parent.zip(child).is_none_or(|(p, c)| c <= p),
41 "Child posture exceeds the saved parent posture"
42 );
43 ensure!(
44 self.external_agent_id
45 .as_deref()
46 .is_none_or(crate::external_agents::valid_agent_id),
47 "Invalid external agent ID"
48 );
49 for id in [&self.account_agent_id, &self.home_thread_id]
50 .into_iter()
51 .flatten()
52 {
53 ensure!(
54 !id.is_empty()
55 && id.len() <= 256
56 && id
57 .bytes()
58 .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b)),
59 "Invalid linked agent or thread ID"
60 );
61 }
62 Ok(())
63 }
64 }
65
66 #[derive(Debug, Serialize)]
67 pub struct SavedWhale {
68 pub id: String,
69 pub name: String,
70 pub purpose: Option<String>,
71 pub soul: Option<String>,
72 pub model: Option<String>,
73 pub model_provider_id: Option<String>,
74 pub revision: String,
75 pub scope: &'static str,
76 #[serde(skip_serializing_if = "Option::is_none")]
77 pub fleet_member_selector: Option<String>,
78 pub fleet_role: String,
79 #[serde(skip_serializing_if = "Option::is_none")]
80 pub fleet_unavailable_reason: Option<&'static str>,
81 #[serde(flatten)]
82 pub settings: WhaleSettings,
83 }
84
85 #[derive(Debug, thiserror::Error)]
86 #[error("Saved whale does not exist")]
87 pub struct Missing;
88
89 #[derive(Debug, thiserror::Error)]
90 #[error("The saved profile changed. Reopen it and retry.")]
91 pub struct Stale;
92
93 pub fn valid_id(id: &str) -> bool {
94 id.len() <= 64
95 && id
96 .bytes()
97 .next()
98 .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
99 && id
100 .bytes()
101 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
102 && id != "default"
103 }
104
105 fn path_for(id: &str) -> Result<PathBuf> {
106 ensure!(valid_id(id), "Invalid specialist whale ID");
107 Ok(personal_agent_profile_dir()?.join(format!("{id}.toml")))
108 }
109
110 fn read(path: &Path) -> Result<Option<String>> {
111 read_agent_profile_document(FleetProfileScope::Personal, Path::new(""), path)
112 }
113
114 fn projection(path: &Path, raw: &str) -> Result<SavedWhale> {
115 #[derive(Deserialize)]
116 struct Metadata {
117 whale: Option<WhaleSettings>,
118 }
119 let meta: Metadata = toml::from_str(raw)?;
120 let settings = meta.whale.ok_or(Missing)?;
121 let profile = parse_agent_profile_text(path, raw)?;
122 ensure!(
123 path.file_stem().and_then(|s| s.to_str()) == Some(profile.id.as_str()),
124 "Whale filename and ID differ"
125 );
126 let fleet_unavailable_reason =
127 if settings.permission_posture.is_some() || settings.child_posture.is_some() {
128 Some("Saved permission posture requires a session child")
129 } else if settings.instance_id.is_none() {
130 Some("Save the whale again to establish its Fleet identity")
131 } else {
132 None
133 };
134 let fleet_member_selector = settings
135 .instance_id
136 .filter(|_| fleet_unavailable_reason.is_none())
137 .map(|instance| format!("whale:{}:{instance}", profile.id));
138 let fleet_role = crate::fleet::profile::canonical_public_role_name(&profile.profile.role.name);
139 Ok(SavedWhale {
140 name: profile.display_name.unwrap_or_else(|| profile.id.clone()),
141 id: profile.id,
142 purpose: profile.description,
143 soul: profile.profile.role.instructions,
144 model: profile.profile.model,
145 model_provider_id: profile.profile.provider,
146 settings,
147 scope: "personal",
148 revision: codewhale_runtime::hashing::sha256_hex(raw.as_bytes()),
149 fleet_member_selector,
150 fleet_role,
151 fleet_unavailable_reason,
152 })
153 }
154
155 #[derive(Default, Serialize)]
156 pub struct SavedWhaleList {
157 pub whales: Vec<SavedWhale>,
158 pub unreadable_profiles: usize,
159 }
160
161 pub fn list() -> Result<SavedWhaleList> {
162 let dir = personal_agent_profile_dir()?;
163 let entries = match agent_document_entries(&dir) {
164 Ok(entries) => entries,
165 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
166 return Ok(SavedWhaleList::default());
167 }
168 Err(err) => return Err(err.into()),
169 };
170 let mut result = SavedWhaleList::default();
171 for entry in entries {
172 let Ok(path) = entry else {
173 result.unreadable_profiles += 1;
174 continue;
175 };
176 if path.extension().is_none_or(|ext| ext != "toml") {
177 continue;
178 }
179 match read(&path).and_then(|raw| raw.map(|text| projection(&path, &text)).transpose()) {
180 Ok(Some(row)) => result.whales.push(row),
181 Ok(None) => {}
182 Err(e) if e.is::<Missing>() => {}
183 Err(_) => result.unreadable_profiles += 1,
184 }
185 }
186 result.whales.sort_by(|a, b| a.id.cmp(&b.id));
187 Ok(result)
188 }
189
190 pub fn get(id: &str) -> Result<SavedWhale> {
191 let path = path_for(id)?;
192 projection(&path, &read(&path)?.ok_or(Missing)?)
193 }
194
195 pub fn fleet_selector_identity(selector: &str) -> Option<(&str, uuid::Uuid)> {
196 let (id, instance) = selector.strip_prefix("whale:")?.split_once(':')?;
197 if !valid_id(id) {
198 return None;
199 }
200 let uuid = uuid::Uuid::parse_str(instance).ok()?;
201 (uuid.to_string() == instance).then_some((id, uuid))
202 }
203
204 pub(crate) fn read_fleet_member(selector: &str) -> Result<AgentProfile> {
205 let (id, _) =
206 fleet_selector_identity(selector).context("Invalid saved whale Fleet selector")?;
207 let path = path_for(id)?;
208 let raw = read(&path)?.ok_or(Missing)?;
209 let whale = projection(&path, &raw)?;
210 ensure!(
211 whale.fleet_member_selector.as_deref() == Some(selector),
212 "Saved whale Fleet identity or permission posture changed"
213 );
214 let mut profile = parse_agent_profile_text(&path, &raw)?;
215 profile.origin = crate::fleet::roster::ProfileOrigin::Personal;
216 if let Some(external_agent) = whale.settings.external_agent_id {
217 profile.profile.external_agent = Some(external_agent);
218 }
219 Ok(profile)
220 }
221
222 pub fn save(id: &str, fields: Map<String, Value>, revision: Option<&str>) -> Result<SavedWhale> {
223 let path = path_for(id)?;
224 let current = read(&path)?;
225 let mut doc = match (&current, revision) {
226 (None, None) => {
227 let mut doc = DocumentMut::new();
228 doc["id"] = value(id);
229 doc["base_role"] = value("general");
230 doc["whale"] = Item::Table(Table::new());
231 doc["whale"]["instance_id"] = value(uuid::Uuid::new_v4().to_string());
232 doc
233 }
234 (None, Some(_)) => return Err(Missing.into()),
235 (Some(_), None) => return Err(Stale.into()),
236 (Some(raw), Some(expected)) => {
237 if projection(&path, raw)?.revision != expected {
238 return Err(Stale.into());
239 }
240 raw.parse::<DocumentMut>()?
241 }
242 };
243 for (field, input) in fields {
244 let (parent, key) = match field.as_str() {
245 "name" => (None, "display_name"),
246 "purpose" => (None, "description"),
247 "soul" => (Some("instructions"), "text"),
248 "model" => (None, "model"),
249 "model_provider_id" => (None, "provider"),
250 "color" | "external_agent_id" | "permission_posture" | "child_posture"
251 | "home_thread_id" => (Some("whale"), field.as_str()),
252 _ => anyhow::bail!("Unknown whale field: {field}"),
253 };
254 let table = if let Some(parent) = parent {
255 if !doc.contains_key(parent) {
256 doc[parent] = Item::Table(Table::new());
257 }
258 doc[parent]
259 .as_table_like_mut()
260 .context("Invalid whale metadata table")?
261 } else {
262 doc.as_table_mut()
263 };
264 if input.is_null() {
265 table.remove(key);
266 } else {
267 let text = input
268 .as_str()
269 .context("Whale fields must be strings or null")?;
270 ensure!(
271 text.len() <= MAX_PROFILE_DOCUMENT_BYTES,
272 "Whale field is too large"
273 );
274 table.insert(key, value(text));
275 }
276 }
277 if !doc["whale"]
278 .as_table_like()
279 .is_some_and(|table| table.contains_key("instance_id"))
280 {
281 doc["whale"]["instance_id"] = value(uuid::Uuid::new_v4().to_string());
282 }
283 let raw = doc.to_string();
284 let result = projection(&path, &raw)?;
285 ensure!(
286 result.settings.external_agent_id.is_none() || result.soul.is_none(),
287 "External agent sessions use the agent’s own instructions"
288 );
289 save_agent_profile_document(
290 FleetProfileScope::Personal,
291 Path::new(""),
292 &path,
293 current.as_deref(),
294 id,
295 &raw,
296 )?;
297 Ok(result)
298 }
299
300 pub fn remove(id: &str, revision: Option<&str>) -> Result<()> {
301 let path = path_for(id)?;
302 let raw = read(&path)?.ok_or(Missing)?;
303 let row = projection(&path, &raw)?;
304 if revision.is_some_and(|r| r != row.revision) {
305 return Err(Stale.into());
306 }
307 retire_personal_profile(&path, &raw)
308 }
309
310 #[cfg(test)]
311 mod tests {
312 use super::*;
313 use serde_json::json;
314
315 #[test]
316 fn fleet_selector_uses_the_personal_instance_and_rejects_recreation() {
317 let _home = crate::test_support::SealedHome::new();
318 let first = save(
319 "reader",
320 json!({"name":"Reader", "soul":"Check the source", "model":"fast", "model_provider_id":"local"})
321 .as_object().unwrap().clone(),
322 None,
323 ).unwrap();
324 let selector = first.fleet_member_selector.as_deref().unwrap();
325 assert_eq!(first.fleet_role, "general");
326 let changed = save(
327 "reader",
328 Map::from_iter([("name".into(), json!("Renamed"))]),
329 Some(&first.revision),
330 )
331 .unwrap();
332 assert_eq!(changed.fleet_member_selector.as_deref(), Some(selector));
333 let member = read_fleet_member(selector).unwrap();
334 assert_eq!(member.origin, crate::fleet::roster::ProfileOrigin::Personal);
335 assert_eq!(
336 member.profile.role.instructions.as_deref(),
337 Some("Check the source")
338 );
339 assert_eq!(member.profile.provider.as_deref(), Some("local"));
340 assert_eq!(member.profile.model.as_deref(), Some("fast"));
341 let restricted = save(
342 "reader",
343 Map::from_iter([("child_posture".into(), json!("ask"))]),
344 Some(&changed.revision),
345 )
346 .unwrap();
347 assert!(restricted.fleet_member_selector.is_none());
348 assert!(read_fleet_member(selector).is_err());
349 remove("reader", Some(&restricted.revision)).unwrap();
350 let recreated = save("reader", Map::new(), None).unwrap();
351 assert_ne!(recreated.fleet_member_selector.as_deref(), Some(selector));
352 assert!(read_fleet_member(selector).is_err());
353 }
354
355 #[test]
356 fn listing_keeps_valid_profiles_and_skips_malformed_neighbors() {
357 let _guard = crate::test_support::lock_test_env();
358 let home = tempfile::tempdir().unwrap();
359 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
360 let fields = Map::from_iter([("name".into(), json!("Reader"))]);
361 let whale = save("reader", fields, None).unwrap();
362 let bad = path_for("invalid").unwrap();
363 std::fs::write(&bad, "[broken").unwrap();
364 let listed = list().unwrap();
365 assert_eq!(listed.whales.len(), 1);
366 assert_eq!(listed.whales[0].id, whale.id);
367 assert_eq!(listed.unreadable_profiles, 1);
368 std::fs::remove_file(&bad).unwrap();
369 for fields in [
370 json!({"external_agent_id":"../reader"}),
371 json!({"account_agent_id":"different-account"}),
372 json!({"external_agent_id":"codex","soul":"Use these instructions"}),
373 ] {
374 assert!(
375 save(
376 "reader",
377 fields.as_object().unwrap().clone(),
378 Some(&whale.revision)
379 )
380 .is_err()
381 );
382 }
383 let path = path_for("reader").unwrap();
384 let raw = read(&path).unwrap().unwrap() + "\naccount_agent_id = \"foreign\"\n";
385 let local = projection(&path, &raw).unwrap();
386 assert!(
387 serde_json::to_value(local)
388 .unwrap()
389 .get("account_agent_id")
390 .is_none()
391 );
392 }
393
394 #[test]
395 fn specialist_edits_share_the_native_profile_and_require_the_observed_revision() {
396 let _guard = crate::test_support::lock_test_env();
397 let home = tempfile::tempdir().unwrap();
398 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
399 let fields = json!({"name":"Review","purpose":"Inspect changes","soul":"Read the diff.","model":"my-model","model_provider_id":"local","permission_posture":"auto_review","child_posture":"ask"});
400 let row = save("reviewer", fields.as_object().unwrap().clone(), None).unwrap();
401 assert_eq!(list().unwrap().whales.len(), 1);
402 let path = path_for("reviewer").unwrap();
403 let raw = read(&path).unwrap().unwrap();
404 let profile = parse_agent_profile_text(&path, &raw).unwrap();
405 assert_eq!(profile.id, "reviewer");
406 assert_eq!(
407 profile.profile.role.instructions.as_deref(),
408 Some("Read the diff.")
409 );
410 assert_eq!(profile.profile.provider.as_deref(), Some("local"));
411 let change = Map::from_iter([("name".into(), json!("Code reviewer"))]);
412 let next = save("reviewer", change.clone(), Some(&row.revision)).unwrap();
413 assert_ne!(row.revision, next.revision);
414 assert!(
415 save("reviewer", change, Some(&row.revision))
416 .unwrap_err()
417 .is::<Stale>()
418 );
419 assert!(
420 remove("reviewer", Some(&row.revision))
421 .unwrap_err()
422 .is::<Stale>()
423 );
424 assert!(
425 save(
426 "reviewer",
427 Map::from_iter([("child_posture".into(), json!("full_access"))]),
428 Some(&next.revision)
429 )
430 .is_err()
431 );
432 assert_eq!(get("reviewer").unwrap().name, "Code reviewer");
433 assert!(get("../reviewer").is_err());
434 remove("reviewer", Some(&next.revision)).unwrap();
435 assert!(list().unwrap().whales.is_empty());
436 assert!(get("reviewer").unwrap_err().is::<Missing>());
437 }
438 }
439
439 lines RUST