| 1 | use std::path::{Path, PathBuf}; |
| 2 | use std::sync::Arc; |
| 3 | |
| 4 | use anyhow::{Context, Result, ensure}; |
| 5 | use codewhale_config::private_directory::PrivateDirectory; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | |
| 8 | const ID: &str = "default"; |
| 9 | const FILE: &str = "SOUL.md"; |
| 10 | pub const MAX_BYTES: usize = 16 * 1024; |
| 11 | |
| 12 | #[derive(Serialize)] |
| 13 | pub struct Soul { |
| 14 | pub path: PathBuf, |
| 15 | pub text: String, |
| 16 | pub revision: String, |
| 17 | pub writable: bool, |
| 18 | } |
| 19 | |
| 20 | #[derive(Deserialize)] |
| 21 | struct LocalWhale { |
| 22 | id: String, |
| 23 | account_agent_id: Option<String>, |
| 24 | } |
| 25 | |
| 26 | fn directory() -> Result<PathBuf> { |
| 27 | Ok(codewhale_config::codewhale_home()?.join("whales").join(ID)) |
| 28 | } |
| 29 | |
| 30 | fn read_file(dir: &PrivateDirectory, name: &str) -> Result<Option<String>> { |
| 31 | let bytes = dir.read_private_receipt(name, MAX_BYTES)?; |
| 32 | bytes |
| 33 | .map(|(bytes, _)| String::from_utf8(bytes).context("Whale documents must be UTF-8")) |
| 34 | .transpose() |
| 35 | } |
| 36 | |
| 37 | fn snapshot(path: &Path, dir: Option<&PrivateDirectory>) -> Result<Soul> { |
| 38 | let manifest = dir |
| 39 | .map(|dir| read_file(dir, "whale.toml")) |
| 40 | .transpose()? |
| 41 | .flatten(); |
| 42 | let identity = manifest |
| 43 | .as_deref() |
| 44 | .map(toml::from_str::<LocalWhale>) |
| 45 | .transpose() |
| 46 | .context("Invalid whale identity file")?; |
| 47 | ensure!( |
| 48 | identity.as_ref().is_none_or(|whale| whale.id == ID), |
| 49 | "Whale identity changed" |
| 50 | ); |
| 51 | let writable = identity |
| 52 | .as_ref() |
| 53 | .is_none_or(|whale| whale.account_agent_id.is_none()); |
| 54 | let text = dir.map(|dir| read_file(dir, FILE)).transpose()?.flatten(); |
| 55 | ensure!( |
| 56 | text.is_none() || identity.is_some(), |
| 57 | "An existing SOUL.md requires whale.toml with its local whale identity" |
| 58 | ); |
| 59 | let revision = text.as_ref().map_or_else( |
| 60 | || "new".to_owned(), |
| 61 | |text| codewhale_runtime::hashing::sha256_hex(text.as_bytes()), |
| 62 | ); |
| 63 | Ok(Soul { |
| 64 | path: path.join(FILE), |
| 65 | text: text.unwrap_or_default(), |
| 66 | revision, |
| 67 | writable, |
| 68 | }) |
| 69 | } |
| 70 | |
| 71 | pub fn load() -> Result<Soul> { |
| 72 | let path = directory()?; |
| 73 | match std::fs::symlink_metadata(&path) { |
| 74 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => return snapshot(&path, None), |
| 75 | Err(error) => return Err(error.into()), |
| 76 | Ok(_) => {} |
| 77 | } |
| 78 | let dir = PrivateDirectory::inspect(&path)?; |
| 79 | snapshot(&path, Some(&dir)) |
| 80 | } |
| 81 | |
| 82 | pub fn save(expected: &str, text: &str) -> Result<Option<Soul>> { |
| 83 | ensure!( |
| 84 | text.len() <= MAX_BYTES, |
| 85 | "SOUL.md exceeds the local whale file limit" |
| 86 | ); |
| 87 | let path = directory()?; |
| 88 | let dir = PrivateDirectory::admit(&path)?; |
| 89 | let lock = dir.open_internal_file("soul.lock")?; |
| 90 | lock.try_lock() |
| 91 | .context("The local whale voice is being edited or cannot be locked; retry the edit")?; |
| 92 | ensure!(dir.is_at_selected_path()?, "Whale directory changed"); |
| 93 | let current = snapshot(&path, Some(&dir))?; |
| 94 | if current.revision != expected { |
| 95 | return Ok(None); |
| 96 | } |
| 97 | ensure!(current.writable, "The account owns this imported whale"); |
| 98 | if read_file(&dir, "whale.toml")?.is_none() { |
| 99 | dir.write_owned_file("whale.toml", b"id = \"default\"\n", false)?; |
| 100 | } |
| 101 | dir.write_owned_file(FILE, text.as_bytes(), true)?; |
| 102 | Ok(Some(snapshot(&path, Some(&dir))?)) |
| 103 | } |
| 104 | |
| 105 | #[derive(Clone, PartialEq, Eq)] |
| 106 | pub(crate) struct Voice { |
| 107 | path: PathBuf, |
| 108 | revision: String, |
| 109 | text: String, |
| 110 | } |
| 111 | |
| 112 | impl std::fmt::Debug for Voice { |
| 113 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 114 | f.debug_struct("WhaleVoice") |
| 115 | .field("revision", &self.revision) |
| 116 | .finish_non_exhaustive() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | impl Voice { |
| 121 | pub(crate) fn segment(&self) -> crate::project_context::InstructionSegment { |
| 122 | use crate::project_context::{InstructionOrigin, InstructionScope, InstructionSegment}; |
| 123 | let mut segment = InstructionSegment::new( |
| 124 | InstructionScope::Global, |
| 125 | InstructionOrigin::WhaleSoul, |
| 126 | Some(self.path.clone()), |
| 127 | self.text.clone(), |
| 128 | ); |
| 129 | segment.label = Some("SOUL.md".into()); |
| 130 | segment.canonical_path = Some(self.path.clone()); |
| 131 | segment |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | pub(crate) async fn capture() -> Result<Option<Arc<Voice>>> { |
| 136 | codewhale_runtime::runtime_control::owner_work(|| { |
| 137 | let soul = load().context("Could not read the local whale identity and SOUL.md safely")?; |
| 138 | Ok((soul.writable && !soul.text.trim().is_empty()).then(|| { |
| 139 | Arc::new(Voice { |
| 140 | path: soul.path, |
| 141 | revision: soul.revision, |
| 142 | text: soul.text, |
| 143 | }) |
| 144 | })) |
| 145 | }) |
| 146 | .await |
| 147 | } |
| 148 |