//! Where the host keeps its socket, its scrollback and its index — named once,//! here.//!//! The data directory is the Mac's: `$COTTON_MAC_DATA_DIR`, else//! `~/CottonDB` for the real app and `~/CottonDev` for Cotton Dev — WHICH app//! is `$COTTON_FLAVOR` ([`Flavor`]; anything but exactly `real` is Cotton//! Dev), and a folder that is the OTHER app's is refused//! ([`Flavor::refusal_for_data_dir`]). That rule is `cotton-client`'s//! (`crates/cotton-client/src/data_dir/paths.rs`) and this crate MIRRORS it//! rather than depending on it: `cotton-client` links `cotton-store`,//! `cotton-core` and `cotton-tools`, which is a bundled SQLite and the whole//! domain, for a helper whose entire relationship with the database is that it//! puts three files beside it. The two copies are held equal by//! [`the_data_dir_is_the_same_rule_cotton_client_keeps`] in `data_dir_tests.rs`,//! which restates the rule in the form a reader can compare by eye.//!//! [`the_data_dir_is_the_same_rule_cotton_client_keeps`]: ../../src/data_dir_tests.rs//!//! Like `cotton-client`'s, every function here is PURE: `home` and the//! override are passed in, never read from the process, so a test points them//! at a synthetic folder and `main.rs` is the one place that reads the//! environment.use std::path::{Path, PathBuf};/// The REAL app's product name, and its directory's own name — the real/// flavor's, never a second spelling of it.pubconst PRODUCT_NAME: &str = Flavor::Real.data_dir_name();/// The environment variable this helper reads its app from.pubconst FLAVOR_ENV: &str = "COTTON_FLAVOR";/// **Which app this helper serves — a MIRROR of `cotton_core::flavor`**, for/// the reason in the module header: this crate does not link the domain for/// three paths. Only what the helper needs is restated — which folder, and/// whether a folder is the other app's — and `data_dir_tests.rs` holds every/// answer here equal to `cotton_core`'s, sentence for sentence.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pubenumFlavor {/// CottonDB — the owner's household.Real,/// Cotton Dev — every development build.Dev,Business,}implFlavor {/// Both, for a test that walks them.pubconst ALL: [Flavor; 3] = [Flavor::Real, Flavor::Dev, Flavor::Business];/// The spelling handed to a Cotton child process.pubconstfn as_str(self) -> &'static str {matchself {Flavor::Real => "real",Flavor::Dev => "dev",Flavor::Business => "business", } }/// Exact real and business declarations opt in; every other value is Dev.pubfn from_declared(value: Option<&str>) -> Flavor {match value.map(str::trim) {Some("real") => Flavor::Real,Some("business") => Flavor::Business, _ => Flavor::Dev, } }/// The REAL app's bundle identifier — `apps/cotton/scripts/lib/flavor.sh`'s/// `FLAVOR_BUNDLE_ID` for `real`. Cotton Dev's is this plus `.dev`.pubconst REAL_BUNDLE_ID: &'static str = "com.decemberfm.cottondb.mac";/// Which app, from what the environment declared and, when it declared/// NOTHING, the identifier of the app bundle this binary sits in.////// WHY THE BUNDLE TOO (a Mac, 11 Oct 2026). launchd runs the helper/// from the registration SMAppService IMPORTED, not from the plist in the/// bundle as it is today: that Mac's registration came from a bundle whose/// plist carried no `COTTON_FLAVOR`, so the real app's helper read an unset/// flavor as Cotton Dev for a week — it served `~/CottonDev` (and kept Cotton/// Dev's own helper from binding there), while the real app dialled a dead/// `~/CottonDB/session-host.sock` and the Mac's sample stopped on 4 Oct./// The bundle's own identifier cannot be stale that way. A declared value,/// empty included, still wins; and only the EXACT real identifier is the/// real app, so a Cotton Dev bundle, a binary outside any bundle or a/// plist that cannot be read are all Cotton Dev — the safe side.pubfn resolve(declared: Option<&str>, bundle_id: Option<&str>) -> Flavor {match declared {Some(_) => Flavor::from_declared(declared),None => match bundle_id.map(str::trim) {Some(id) if id == Flavor::REAL_BUNDLE_ID => Flavor::Real, _ => Flavor::Dev, }, } }/// The folder's own name, under the person's home.pubconstfn data_dir_name(self) -> &'static str {matchself {Flavor::Real => "CottonDB",Flavor::Dev => "CottonDev",Flavor::Business => "CottonBusiness", } }/// The other app.pubconstfn other(self) -> Flavor {matchself {Flavor::Real => Flavor::Dev,Flavor::Dev => Flavor::Real,Flavor::Business => Flavor::Real, } }/// Why `data_dir` is the other app's folder (or inside it), or `None` —/// the same folders, the same comparison (every form of the path: lexical,/// canonical-prefix, case-folded) and the same sentence as/// `cotton_core::flavor::Flavor::refusal_for_data_dir`.pubfn refusal_for_data_dir(self, home: implAsRef<Path>, data_dir: &Path) -> Option<String> {let home = home.as_ref();let other = self.other();letmut foreign = vec![home.join(other.data_dir_name())];ifself == Flavor::Business { foreign.push(home.join(Flavor::Dev.data_dir_name())); } else { foreign.push(home.join(Flavor::Business.data_dir_name())); }if other == Flavor::Real { foreign.push( home.join("Library") .join("Application Support") .join(other.data_dir_name()), ); }let given = path_forms(data_dir);let hit = foreign.iter().flat_map(|candidate| path_forms(candidate)).any(|candidate| { given.iter().any(|form| form.starts_with(&candidate)) }); hit.then(|| matchself {Flavor::Business => format!("Business will not open {} — another app owns that folder.", data_dir.display()),Flavor::Dev => format!("Cotton Dev will not open {} — that folder is Cotton's, the real household's database. Cotton Dev keeps its own data in ~/{}.", data_dir.display(),Flavor::Dev.data_dir_name() ),Flavor::Real => format!("Cotton will not open {} — that folder is Cotton Dev's. Cotton keeps its data in ~/{}.", data_dir.display(),Flavor::Real.data_dir_name() ), }) }}/// Every form a folder's path can take, case-folded — `cotton_core::flavor`'s/// `path_forms`, restated.fn path_forms(path: &Path) -> Vec<PathBuf> {let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());let lexical = lexical(&absolute);letmut forms = vec![lexical.clone()]; forms.extend(canonical_prefix(&lexical)); forms.extend(std::fs::canonicalize(path).ok()); forms .iter() .map(|form| PathBuf::from(form.to_string_lossy().to_lowercase())) .collect()}/// `a/b/`, `a/b/.` and `a/c/../b` are `a/b` — by the letters alone.fn lexical(path: &Path) -> PathBuf {use std::path::Component;letmut out = PathBuf::new();for component in path.components() {match component {Component::CurDir => {}Component::ParentDir => {if !out.pop() { out.push(component); } } other => out.push(other), } } out}/// The path with its deepest EXISTING ancestor canonicalised and the rest/// put back. `None` when no ancestor exists.fn canonical_prefix(path: &Path) -> Option<PathBuf> {letmut rest = Vec::new();letmut at = path;loop {ifletOk(found) = std::fs::canonicalize(at) {returnSome(rest.iter().rev().fold(found, |acc: PathBuf, part| acc.join(part))); } rest.push(at.file_name()?.to_os_string()); at = at.parent()?; }}/// The environment variable that overrides the data directory.pubconst DATA_DIR_ENV: &str = "COTTON_MAC_DATA_DIR";/// The socket's name inside the host's own folder ([`Layout::socket`]).////// One socket per data directory, exactly as there is one server per data/// directory — the helper's `serve` refuses a second daemon by failing to bind/// rather than by unlinking somebody else's socket.pubconst SOCKET_NAME: &str = "session-host.sock";/// The log's name beside the socket ([`Layout::log`]).////// **The helper writes its own log, and the launchd plist names no path at/// all.** `StandardOutPath`/`StandardErrorPath` want an ABSOLUTE path, and the/// plist that would carry one is inside an app bundle that is the same bytes on/// every Mac — so stamping a home directory into it at build time would ship/// one person's path to everybody. The process knows its own data directory/// (it is the same rule as the socket beside it), so `serve` points its own/// stderr here and the plist stays machine-agnostic.pubconst LOG_NAME: &str = "session-host.log";/// The socket's mode: the owner, and nobody else.////// Anything that can write this socket can spawn a process as the person and/// read their terminal. There is no group and no other on it.pubconst SOCKET_MODE: u32 = 0o600;/// The data directory this run will use.////// A blank override reads as no override: an unset variable and one set to the/// empty string mean the same thing to a person typing the command. Resolving/// is not admitting — [`Flavor::refusal_for_data_dir`] is asked after./// `CFBundleIdentifier` out of an app bundle's XML `Info.plist` — the string/// that follows the key, with nothing but whitespace between them. `None` for/// anything else (no key, a binary plist, an empty string), which/// [`Flavor::resolve`] reads as Cotton Dev.pubfn bundle_identifier(info_plist: &str) -> Option<&str> {const KEY: &str = "<key>CFBundleIdentifier</key>";let after = &info_plist[info_plist.find(KEY)? + KEY.len()..];let value = after.trim_start().strip_prefix("<string>")?;let id = value[..value.find("</string>")?].trim(); (!id.is_empty()).then_some(id)}pubfn resolve_data_dir(flavor: Flavor, home: implAsRef<Path>, over: Option<&str>) -> PathBuf {ifletSome(value) = over {let trimmed = value.trim();if !trimmed.is_empty() {returnPathBuf::from(trimmed); } } home.as_ref().join(flavor.data_dir_name())}/// The folder this helper may use, or the sentence that says why not: the/// resolved folder, refused when it is the other app's. What `main` runs/// before any subcommand touches a socket or a file.pubfn admitted_data_dir( flavor: Flavor, home: implAsRef<Path>, over: Option<&str>,) -> Result<PathBuf, String> {let home = home.as_ref();let data_dir = resolve_data_dir(flavor, home, over);match flavor.refusal_for_data_dir(home, &data_dir) {Some(refusal) => Err(refusal),None => Ok(data_dir), }}/// The folder an overridden data directory's sessions live in: beside it, never/// inside it — `/x/CottonDB` keeps them in `/x/CottonDB-sessions`. Each host on/// a Mac (every lane runs its own over a synthetic folder) keeps its own, as it/// keeps its own socket.pubconst SESSIONS_BESIDE_SUFFIX: &str = "-sessions";/// The app's own support folder — `~/Library/Application Support/Cotton`/// for the real app, the folder the Mac's Cotton keeps its importer in/// (`apps/cotton/Mac/Sources/AppModel.swift`), and `…/CottonDev` for Cotton/// Dev: the host's socket, log, utilities and sessions, outside the data/// folder. `~/CottonDB` is retired on every Mac, so nothing the host keeps/// for itself is under it.pubfn app_support_dir(flavor: Flavor, home: implAsRef<Path>) -> PathBuf {let name = match flavor {Flavor::Real => "Cotton", other => other.data_dir_name(), }; home.as_ref().join("Library").join("Application Support").join(name)}/// Every path the host owns, named once: for the app, its socket, log,/// utilities and sessions in the app's support folder ([`app_support_dir`]),/// and only the browser's profile in the data directory; for a synthetic/// folder, everything in or beside it.////// **A SESSION'S FILES ARE NOT THE OWNER'S DATA** (architect, 15 Oct 2026)./// A session's settings, MCP config, transcript, scrollback and the index of/// sessions live in the app's support folder, apart from the databases. The/// data folder is never an ancestor of a session.////// The same shape as `cotton_client::layout::Layout`, and for the same reason:/// nothing else in this crate spells a path.#[derive(Debug, Clone, PartialEq, Eq)]pubstructLayout { root: PathBuf,/// The socket, the log and the utilities. own: PathBuf, sessions: PathBuf,}implLayout {/// The layout rooted at a data directory, its sessions beside it/// ([`SESSIONS_BESIDE_SUFFIX`]) — an overridden or synthetic folder's.pubfn new(root: implInto<PathBuf>) -> Self {let root = root.into();letmut beside = root.clone().into_os_string(); beside.push(SESSIONS_BESIDE_SUFFIX);Self { own: root.clone(), root, sessions: PathBuf::from(beside) } }/// The app's own layout: the flavor's data folder (or the override), and/// its socket, log, utilities and sessions in the app's support folder/// when the data folder is the app's own ([`app_support_dir`]), in and/// beside an overridden one otherwise.pubfn for_app(flavor: Flavor, home: implAsRef<Path>, data_dir: PathBuf) -> Self {let home = home.as_ref();if data_dir == resolve_data_dir(flavor, home, None) {let own = app_support_dir(flavor, home);Self { root: data_dir, sessions: own.join("sessions"), own } } else {Self::new(data_dir) } }/// The data directory itself.pubfn root(&self) -> &Path { &self.root }/// The folder the host's own files are in: the socket, the log, the/// utilities — the app's support folder, or a synthetic data folder.pubfn own(&self) -> &Path { &self.own }/// `<own>/session-host.sock`.pubfn socket(&self) -> PathBuf {self.own.join(SOCKET_NAME) }/// `<own>/session-host.log` — everything `serve` writes to stderr.pubfn log(&self) -> PathBuf {self.own.join(LOG_NAME) }/// Where sessions lived before 15 Oct 2026, `<dataDir>/sessions` — read/// once, by the move into [`Layout::sessions_dir`].pubfn sessions_in_the_data_folder(&self) -> PathBuf {self.root.join("sessions") }/// One directory per session under it, outside the data folder.pubfn sessions_dir(&self) -> PathBuf {self.sessions.clone() }/// `<sessions>/index.json` — what `list` answers from after a restart.pubfn index(&self) -> PathBuf {self.sessions_dir().join("index.json") }/// `<sessions>/<id>` — a session's own directory: its scrollback, and the/// hook files written for its one launch.pubfn session_dir(&self, id: &str) -> PathBuf {self.sessions_dir().join(id) }/// `<sessions>/<id>/scrollback.log`.pubfn scrollback(&self, id: &str) -> PathBuf {self.session_dir(id).join("scrollback.log") }/// `<own>/utilities` — one directory per PURPOSE under it.////// Beside `sessions/` rather than inside it, because a utility terminal is/// not a session and a directory that held both would be the first place/// somebody went looking for one and found the other/// ([`crate::utility`]).pubfn utilities_dir(&self) -> PathBuf {self.own.join("utilities") }/// `<own>/utilities/<purpose>/scrollback.log`.////// **BY PURPOSE, NOT BY ID.** One installer's output replaces the last/// one's, so the set of these directories is bounded by the set of things/// the app can ask for rather than growing by one per button press. The/// one-at-a-time rule is what makes it safe: two utilities of one purpose/// never run at once, so nothing ever shares this file.pubfn utility_scrollback(&self, purpose: &str) -> PathBuf {self.utilities_dir().join(purpose).join("scrollback.log") }/// `<dataDir>/browser` — the browser tool's profile and its launch lock/// ([`crate::browser`]).pubfn browser_dir(&self) -> PathBuf {self.root.join("browser") }/// `<dataDir>/browser/chrome-profile` — Cotton's own Chrome profile, the/// one the owner signs into once. Never Chrome's default directory/// ([`crate::browser::check_profile`]).pubfn browser_profile(&self) -> PathBuf {self.browser_dir().join("chrome-profile") }}#[cfg(test)]#[path = "data_dir_tests.rs"]mod data_dir_tests;