use std::collections::{HashMap, HashSet};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration, Instant};
const KEEP_FOR: Duration = Duration::from_secs(6 * 60 * 60);
const MAX_PER_SESSION: usize = 64;
const MAX_URLS_PER_TEXT: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SiteProvenance {
OwnerNamed,
WorkOwned,
}
#[derive(Debug, Clone, Copy)]
struct Noted {
at: Instant,
provenance: SiteProvenance,
}
static SITES: LazyLock<Mutex<HashMap<String, HashMap<String, Noted>>>> =
LazyLock::new(Mutex::default);
static DAEMON_PORTS: LazyLock<Mutex<HashSet<u16>>> = LazyLock::new(Mutex::default);
pub fn note_daemon_ports(ports: &[u16]) {
let Ok(mut known) = DAEMON_PORTS.lock() else {
return;
};
known.extend(ports.iter().copied().filter(|port| *port != 0));
}
pub fn is_daemon_listener(site: &str) -> bool {
let port = if site.contains("://") {
reqwest::Url::parse(site)
.ok()
.and_then(|url| url.port_or_known_default())
} else {
site.rsplit_once(':')
.and_then(|(host, port)| (!host.is_empty()).then_some(port))
.and_then(|port| port.parse::<u16>().ok())
};
port.is_some_and(|port| DAEMON_PORTS.lock().is_ok_and(|known| known.contains(&port)))
}
static FOLDERS: LazyLock<Mutex<HashMap<String, Vec<String>>>> = LazyLock::new(Mutex::default);
fn urls_in(text: &str) -> Vec<String> {
let mut urls = Vec::new();
let mut rest = text;
while let Some(at) = ["http://", "https://"]
.iter()
.filter_map(|scheme| rest.find(scheme))
.min()
{
let tail = &rest[at..];
let end = tail
.find(|c: char| {
c.is_whitespace() || matches!(c, '"' | '\'' | '<' | '>' | '`' | '|' | '\\')
})
.unwrap_or(tail.len());
let url = tail[..end].trim_end_matches(['.', ',', ';', ':', ')', ']', '}', '!', '?']);
if !url.is_empty() && !urls.iter().any(|known| known == url) {
urls.push(url.to_string());
if urls.len() == MAX_URLS_PER_TEXT {
break;
}
}
rest = &tail[end.max(1)..];
}
urls
}
pub fn local_sites_in(text: &str) -> Vec<String> {
sites_in(text, false)
}
fn sites_in(text: &str, skip_daemon: bool) -> Vec<String> {
let mut keys: Vec<String> = Vec::new();
for url in urls_in(text) {
if skip_daemon && is_daemon_listener(&url) {
continue;
}
if let Some(key) = crate::web::local_site_key(&url)
&& !keys.contains(&key)
{
keys.push(key);
}
}
keys
}
const LOCAL_SETUP: crate::semantics::ToolMutationEffects =
crate::semantics::ToolMutationEffects::LOCAL_SOURCE_WRITE
.union(crate::semantics::ToolMutationEffects::LOCAL_WORKSPACE_WRITE)
.union(crate::semantics::ToolMutationEffects::LOCAL_DERIVED_WRITE)
.union(crate::semantics::ToolMutationEffects::PROCESS_STATE);
pub fn set_up_locally(
status: crate::semantics::ToolOutcomeStatus,
semantics: &crate::semantics::ToolCallSemantics,
) -> bool {
let effects = semantics.mutation_effects;
!status.is_failure() && !effects.is_empty() && LOCAL_SETUP.contains(effects)
}
pub fn served_within(cwd: &str, write_roots: &[String]) -> bool {
let normal = |path: &str| {
let expanded = shellexpand::tilde(path.trim()).into_owned();
let path = std::path::PathBuf::from(expanded);
path.is_absolute().then(|| {
path.components()
.filter(|part| !matches!(part, std::path::Component::CurDir))
.collect::<std::path::PathBuf>()
})
};
let Some(cwd) = normal(cwd) else {
return false;
};
if cwd
.components()
.any(|part| matches!(part, std::path::Component::ParentDir))
{
return false;
}
write_roots
.iter()
.filter_map(|root| normal(root))
.any(|root| root.parent().is_some() && cwd.starts_with(&root))
}
pub fn note(grant_session: &str, keys: &[String]) {
note_with(grant_session, keys, SiteProvenance::OwnerNamed);
}
pub fn note_work_owned(grant_session: &str, keys: &[String]) {
let (daemon, own): (Vec<String>, Vec<String>) = keys
.iter()
.cloned()
.partition(|key| is_daemon_listener(key));
note_with(grant_session, &own, SiteProvenance::WorkOwned);
note_with(grant_session, &daemon, SiteProvenance::OwnerNamed);
}
fn note_with(grant_session: &str, keys: &[String], provenance: SiteProvenance) {
if grant_session.trim().is_empty() || keys.is_empty() {
return;
}
let Ok(mut sites) = SITES.lock() else {
return;
};
let now = Instant::now();
let session = sites.entry(grant_session.to_string()).or_default();
session.retain(|_, noted| now.duration_since(noted.at) < KEEP_FOR);
for key in keys {
let noted = session.entry(key.clone()).or_insert(Noted {
at: now,
provenance,
});
noted.at = now;
noted.provenance = noted.provenance.max(provenance);
}
while session.len() > MAX_PER_SESSION {
let Some(oldest) = session
.iter()
.min_by_key(|(_, noted)| noted.at)
.map(|(key, _)| key.clone())
else {
break;
};
session.remove(&oldest);
}
}
pub async fn note_sites_in(grant_session: &str, text: &str) {
note_sites_in_as(grant_session, text, SiteProvenance::OwnerNamed).await;
}
pub async fn note_work_owned_sites_in(grant_session: &str, text: &str) {
note_sites_in_as(grant_session, text, SiteProvenance::WorkOwned).await;
}
async fn note_sites_in_as(grant_session: &str, text: &str, provenance: SiteProvenance) {
if grant_session.trim().is_empty() || !text.contains("http") {
return;
}
let text = text.to_string();
let skip_daemon = provenance == SiteProvenance::WorkOwned;
let keys = tokio::task::spawn_blocking(move || sites_in(&text, skip_daemon))
.await
.unwrap_or_default();
match provenance {
SiteProvenance::WorkOwned => note_work_owned(grant_session, &keys),
SiteProvenance::OwnerNamed => note(grant_session, &keys),
}
}
pub fn provenance(grant_session: &str, key: &str) -> Option<SiteProvenance> {
let noted = SITES.lock().ok().and_then(|sites| {
sites
.get(grant_session)
.and_then(|session| session.get(key))
.filter(|noted| noted.at.elapsed() < KEEP_FOR)
.map(|noted| noted.provenance)
});
if noted == Some(SiteProvenance::WorkOwned) {
return noted;
}
if served_from_owned(grant_session, key) {
return Some(SiteProvenance::WorkOwned);
}
noted
}
pub fn is_noted(grant_session: &str, key: &str) -> bool {
provenance(grant_session, key).is_some()
}
pub fn is_work_owned(grant_session: &str, key: &str) -> bool {
!is_daemon_listener(key) && provenance(grant_session, key) == Some(SiteProvenance::WorkOwned)
}
pub fn note_folders(grant_session: &str, folders: &[String]) {
if grant_session.trim().is_empty() || folders.is_empty() {
return;
}
let Ok(mut known) = FOLDERS.lock() else {
return;
};
let kept = known.entry(grant_session.to_string()).or_default();
for folder in folders {
if std::path::Path::new(folder.trim()).is_absolute() && !kept.contains(folder) {
kept.push(folder.clone());
}
}
let excess = kept.len().saturating_sub(MAX_PER_SESSION);
kept.drain(..excess);
}
fn served_from_owned(grant_session: &str, key: &str) -> bool {
let folders = FOLDERS
.lock()
.ok()
.and_then(|known| known.get(grant_session).cloned())
.unwrap_or_default();
!folders_serving(key, &folders).is_empty()
}
pub fn folders_serving(host: &str, folders: &[String]) -> Vec<String> {
let host = host.trim().trim_end_matches('.').to_lowercase();
if host.is_empty() {
return Vec::new();
}
folders
.iter()
.filter(|folder| project_hosts(std::path::Path::new(folder.trim())).contains(&host))
.cloned()
.collect()
}
pub fn name_serving_folders(
semantics: &mut crate::semantics::ToolCallSemantics,
folders: &[String],
) {
if !semantics.observes_state() || folders.is_empty() {
return;
}
let hosts: Vec<String> = semantics
.target_hints
.iter()
.filter(|hint| hint.kind == crate::semantics::ToolTargetHintKind::Url)
.filter_map(|hint| reqwest::Url::parse(&hint.value).ok())
.filter_map(|url| url.host_str().map(str::to_string))
.collect();
for host in hosts {
for folder in folders_serving(&host, folders) {
let named = semantics.target_hints.iter().any(|hint| {
hint.kind == crate::semantics::ToolTargetHintKind::Path && hint.value == folder
});
if !named {
*semantics = std::mem::take(semantics)
.with_target_hint(crate::semantics::ToolTargetHintKind::Path, folder);
}
}
}
}
pub fn project_hosts(folder: &std::path::Path) -> Vec<String> {
const DDEV_DEFAULT_TLD: &str = "ddev.site";
let config_dir = folder.join(".ddev");
let Ok(base) = std::fs::read_to_string(config_dir.join("config.yaml")) else {
return Vec::new();
};
let mut overrides: Vec<std::path::PathBuf> = std::fs::read_dir(&config_dir)
.map(|entries| {
entries
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.starts_with("config.")
&& name.ends_with(".yaml")
&& name != "config.yaml"
})
})
.collect()
})
.unwrap_or_default();
overrides.sort();
let mut config = TopLevel::default();
config.apply(&base);
for path in overrides {
if let Ok(text) = std::fs::read_to_string(path) {
config.apply(&text);
}
}
let name = config
.scalar("name")
.or_else(|| {
folder
.file_name()
.and_then(|name| name.to_str())
.map(str::to_string)
})
.unwrap_or_default();
let tld = config
.scalar("project_tld")
.or_else(|| {
let home = dirs::home_dir()?;
let text = std::fs::read_to_string(home.join(".ddev/global_config.yaml")).ok()?;
let mut global = TopLevel::default();
global.apply(&text);
global.scalar("project_tld")
})
.unwrap_or_else(|| DDEV_DEFAULT_TLD.to_string());
let tld = tld.trim_matches('.');
let mut hosts: Vec<String> = Vec::new();
let mut add = |host: String| {
let host = host.trim().trim_end_matches('.').to_lowercase();
if !host.is_empty() && !hosts.contains(&host) {
hosts.push(host);
}
};
if !name.trim().is_empty() {
add(format!("{}.{tld}", name.trim()));
}
for extra in config.list("additional_hostnames") {
add(format!("{extra}.{tld}"));
}
for fqdn in config.list("additional_fqdns") {
add(fqdn);
}
hosts
}
#[derive(Default)]
struct TopLevel {
values: HashMap<String, Vec<String>>,
}
impl TopLevel {
fn apply(&mut self, text: &str) {
let mut current: Option<String> = None;
for line in text.lines() {
let content = strip_comment(line);
if content.trim().is_empty() {
continue;
}
let indented = content.starts_with([' ', '\t']);
let trimmed = content.trim();
if indented || trimmed.starts_with('-') {
if let (Some(key), Some(item)) = (current.as_ref(), trimmed.strip_prefix('-')) {
let item = unquote(item.trim());
if !item.is_empty() {
self.values.entry(key.clone()).or_default().push(item);
}
}
continue;
}
current = None;
let Some((key, value)) = trimmed.split_once(':') else {
continue;
};
let key = key.trim().to_string();
let value = value.trim();
let items: Vec<String> = match value.strip_prefix('[').and_then(|v| v.strip_suffix(']'))
{
Some(flow) => flow
.split(',')
.map(|item| unquote(item.trim()))
.filter(|item| !item.is_empty())
.collect(),
None if value.is_empty() => {
current = Some(key.clone());
Vec::new()
}
None => vec![unquote(value)],
};
self.values.insert(key, items);
}
}
fn scalar(&self, key: &str) -> Option<String> {
match self.values.get(key).map(Vec::as_slice) {
Some([one]) if !one.is_empty() => Some(one.clone()),
_ => None,
}
}
fn list(&self, key: &str) -> Vec<String> {
self.values.get(key).cloned().unwrap_or_default()
}
}
fn strip_comment(line: &str) -> &str {
let mut quote: Option<char> = None;
let mut previous = ' ';
for (at, c) in line.char_indices() {
match quote {
Some(open) if c == open => quote = None,
Some(_) => {}
None if c == '"' || c == '\'' => quote = Some(c),
None if c == '#' && previous.is_whitespace() => return &line[..at],
None => {}
}
previous = c;
}
line
}
fn unquote(value: &str) -> String {
let value = value.trim();
for q in ['"', '\''] {
if let Some(inner) = value.strip_prefix(q).and_then(|v| v.strip_suffix(q)) {
return inner.to_string();
}
}
value.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_call_that_set_something_up_locally_brings_its_sites() {
use crate::semantics::{ToolCallSemantics, ToolMutationEffects, ToolOutcomeStatus};
let changed = |effects| ToolCallSemantics::observation_and_mutation_with(effects);
let install = changed(
ToolMutationEffects::LOCAL_WORKSPACE_WRITE.union(ToolMutationEffects::PROCESS_STATE),
);
for status in [
ToolOutcomeStatus::Succeeded,
ToolOutcomeStatus::CompletedWithNegativeResult,
ToolOutcomeStatus::Backgrounded,
] {
assert!(set_up_locally(status, &install), "{status:?}");
}
for status in [
ToolOutcomeStatus::FailedPermanent,
ToolOutcomeStatus::FailedRetryable,
ToolOutcomeStatus::Blocked,
] {
assert!(!set_up_locally(status, &install), "{status:?}");
}
let succeeded = ToolOutcomeStatus::Succeeded;
assert!(!set_up_locally(
succeeded,
&ToolCallSemantics::observation()
));
for elsewhere in [
ToolMutationEffects::EXTERNAL_DELIVERY,
ToolMutationEffects::REMOTE_MUTATION,
ToolMutationEffects::UNSPECIFIED,
ToolMutationEffects::PROCESS_STATE.union(ToolMutationEffects::EXTERNAL_DELIVERY),
] {
assert!(
!set_up_locally(succeeded, &changed(elsewhere)),
"{elsewhere:?}"
);
}
}
#[test]
fn a_run_may_open_a_site_served_from_inside_its_own_scope_only() {
let scope = vec!["/Users/someone/projects/claude-drupal".to_string()];
assert!(served_within(
"/Users/someone/projects/claude-drupal",
&scope
));
assert!(served_within(
"/Users/someone/projects/claude-drupal/web",
&scope
));
assert!(served_within(
"/Users/someone/projects/claude-drupal/./web",
&scope
));
assert!(!served_within(
"/Users/someone/projects/claude-drupal-2",
&scope
));
assert!(!served_within(
"/Users/someone/projects/claude-wordpress",
&scope
));
assert!(!served_within("/Users/someone/projects", &scope));
assert!(!served_within(
"/Users/someone/projects/claude-drupal/../claude-wordpress",
&scope
));
assert!(!served_within("relative/claude-drupal", &scope));
assert!(!served_within("/Users/someone/projects/claude-drupal", &[]));
assert!(!served_within("/Users/someone", &["/".to_string()]));
}
#[test]
fn addresses_are_read_out_of_command_output() {
let output = "Successfully started claude-drupal-2\n\
Your project can be reached at https://claude-drupal-2.ddev.site \
and http://127.0.0.1:32770.\n(see \"https://claude-drupal-2.ddev.site\")";
assert_eq!(
urls_in(output),
vec![
"https://claude-drupal-2.ddev.site".to_string(),
"http://127.0.0.1:32770".to_string(),
]
);
}
#[test]
fn only_sites_on_this_computer_are_noted() {
let keys = local_sites_in(
"dev server on http://localhost:5173/ and docs at https://docs.example.invalid/x \
and http://shop.localhost:8080/admin and http://10.0.0.5/",
);
assert_eq!(
keys,
vec!["localhost:5173".to_string(), "shop.localhost".to_string()]
);
}
fn ddev_project(root: &std::path::Path, folder: &str, config: &str) -> String {
let folder = root.join(folder);
std::fs::create_dir_all(folder.join(".ddev")).unwrap();
std::fs::write(folder.join(".ddev/config.yaml"), config).unwrap();
folder.display().to_string()
}
#[test]
fn a_project_serves_the_names_its_configuration_gives() {
let root = tempfile::tempdir().unwrap();
let site = ddev_project(
root.path(),
"claude-company-wordpress-20261113",
"name: claude-company-wordpress-20261113 # the project\n\
type: wordpress\n\
additional_hostnames:\n - \"admin\"\n\
additional_fqdns: [shop.example.test]\n\
web_environment: []\n\
hooks:\n post-start:\n - exec: echo hi\n",
);
assert_eq!(
project_hosts(std::path::Path::new(&site)),
vec![
"claude-company-wordpress-20261113.ddev.site".to_string(),
"admin.ddev.site".to_string(),
"shop.example.test".to_string(),
]
);
std::fs::write(
std::path::Path::new(&site).join(".ddev/config.local.yaml"),
"name: renamed\nproject_tld: test\nadditional_hostnames: []\n",
)
.unwrap();
assert_eq!(
project_hosts(std::path::Path::new(&site)),
vec!["renamed.test".to_string(), "shop.example.test".to_string()]
);
let plain = root.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
assert!(project_hosts(&plain).is_empty());
}
#[test]
fn a_site_served_from_an_owned_folder_is_the_requests_own() {
let root = tempfile::tempdir().unwrap();
let own = ddev_project(root.path(), "own-site", "name: own-site\n");
ddev_project(root.path(), "other-site", "name: other-site\n");
let grant = "test:local-sites-owned";
assert!(!is_noted(grant, "own-site.ddev.site"));
note_folders(grant, std::slice::from_ref(&own));
assert!(is_noted(grant, "own-site.ddev.site"));
assert!(is_noted(grant, "OWN-SITE.ddev.site"));
assert!(!is_noted(grant, "other-site.ddev.site"));
assert!(!is_noted(
"test:local-sites-elsewhere",
"own-site.ddev.site"
));
}
#[test]
fn an_observation_of_a_site_names_the_folder_that_serves_it() {
use crate::semantics::{ToolCallSemantics, ToolTargetHintKind};
let root = tempfile::tempdir().unwrap();
let site = ddev_project(root.path(), "site-a", "name: site-a\n");
let other = ddev_project(root.path(), "site-b", "name: site-b\n");
let folders = vec![site.clone(), other];
let paths = |semantics: &ToolCallSemantics| -> Vec<String> {
semantics
.target_hints
.iter()
.filter(|hint| hint.kind == ToolTargetHintKind::Path)
.map(|hint| hint.value.clone())
.collect()
};
let mut check = ToolCallSemantics::observation()
.with_target_hint(ToolTargetHintKind::Url, "https://site-a.ddev.site/");
name_serving_folders(&mut check, &folders);
assert_eq!(paths(&check), vec![site.clone()]);
name_serving_folders(&mut check, &folders);
assert_eq!(paths(&check), vec![site], "named once");
let mut change = ToolCallSemantics::mutation()
.with_target_hint(ToolTargetHintKind::Url, "https://site-a.ddev.site/");
name_serving_folders(&mut change, &folders);
assert!(paths(&change).is_empty());
let mut elsewhere = ToolCallSemantics::observation()
.with_target_hint(ToolTargetHintKind::Url, "https://site-c.ddev.site/");
name_serving_folders(&mut elsewhere, &folders);
assert!(paths(&elsewhere).is_empty());
}
#[tokio::test]
async fn a_noted_site_counts_only_for_its_own_session() {
note_sites_in(
"test:local-sites-a",
"Started: http://blog-synthetic.localhost/",
)
.await;
assert!(is_noted("test:local-sites-a", "blog-synthetic.localhost"));
assert!(!is_noted("test:local-sites-b", "blog-synthetic.localhost"));
assert!(!is_noted("test:local-sites-a", "localhost:8080"));
note("", &["other.localhost".to_string()]);
assert!(!is_noted("", "other.localhost"));
}
#[test]
fn work_owned_and_owner_named_sites_are_kept_apart() {
let session = "app:synthetic-provenance-1";
note(session, &["named.localhost".to_string()]);
note_work_owned(session, &["built.localhost".to_string()]);
assert!(is_noted(session, "named.localhost"));
assert!(!is_work_owned(session, "named.localhost"));
assert_eq!(
provenance(session, "named.localhost"),
Some(SiteProvenance::OwnerNamed)
);
assert!(is_noted(session, "built.localhost"));
assert!(is_work_owned(session, "built.localhost"));
note(session, &["built.localhost".to_string()]);
assert!(is_work_owned(session, "built.localhost"));
note_work_owned(session, &["named.localhost".to_string()]);
assert!(is_work_owned(session, "named.localhost"));
assert!(!is_noted("app:synthetic-provenance-2", "built.localhost"));
assert!(!is_work_owned(
"app:synthetic-provenance-2",
"built.localhost"
));
}
#[tokio::test]
async fn the_daemons_own_listener_is_never_the_works_own() {
note_daemon_ports(&[48_123]);
assert!(is_daemon_listener("127.0.0.1:48123"));
assert!(is_daemon_listener("http://localhost:48123/health"));
assert!(!is_daemon_listener("127.0.0.1:48124"));
assert!(!is_daemon_listener("shop.localhost"));
let session = "app:synthetic-provenance-daemon";
note_work_owned(
session,
&["127.0.0.1:48123".to_string(), "127.0.0.1:48124".to_string()],
);
assert!(!is_work_owned(session, "127.0.0.1:48123"));
assert!(is_noted(session, "127.0.0.1:48123"));
assert!(is_work_owned(session, "127.0.0.1:48124"));
let other = "app:synthetic-provenance-daemon-2";
note_work_owned_sites_in(
other,
"dev server on http://127.0.0.1:48125/ and status at http://127.0.0.1:48123/",
)
.await;
assert!(is_work_owned(other, "127.0.0.1:48125"));
assert!(!is_noted(other, "127.0.0.1:48123"));
}
}