use std::path::{Path, PathBuf};
use super::super::text::say;
use super::policy::{Rule, escape, resolve, text};
pub const CONVERSATIONS_NAMED: usize = 2048;
const USER: [&str; 11] = [
".gemini/config/hooks.json",
".gemini/config/mcp_config.json",
".gemini/config/plugins",
".gemini/AGENTS.md",
".gemini/GEMINI.md",
".gemini/config/AGENTS.md",
".gemini/config/GEMINI.md",
".gemini/config/rules",
".gemini/config/skills",
".gemini/antigravity-cli/skills",
".gemini/skills",
];
const PROJECT: [&str; 3] = [
".agents/hooks.json",
".agents/mcp_config.json",
".agents/plugins",
];
pub fn root(home: &Path) -> PathBuf {
home.join(".gemini/antigravity-cli")
}
pub struct Rules {
pub allow: Vec<Rule>,
pub protect: Vec<Rule>,
pub hidden: Vec<String>,
}
const JOURNALS: [&str; 3] = ["-journal", "-wal", "-shm"];
pub fn rules(home: &Path, directory: &Path, conversation: Option<&str>) -> Result<Rules, String> {
let dir = root(home).join("conversations");
let linked = dir
.ancestors()
.take_while(|path| *path != home)
.any(|path| {
path.symlink_metadata()
.is_ok_and(|metadata| metadata.file_type().is_symlink())
});
if linked || resolve(&dir).as_deref() != Some(&dir) {
return Err(say(
"agy_conversations_path",
&[("directory", text(&dir)?.as_str())],
));
}
let (allow, protect) = match conversation {
Some(id) => (own(&dir, id)?, Vec::new()),
None => first(&dir)?,
};
Ok(Rules {
allow,
protect,
hidden: hidden(home, directory)?,
})
}
fn own(dir: &Path, id: &str) -> Result<Vec<Rule>, String> {
use std::os::unix::fs::MetadataExt;
let file = dir.join(format!("{id}.db"));
let refused = |path: &Path| {
say(
"agy_conversation_file",
&[("path", &path.display().to_string())],
)
};
if uuid::Uuid::parse_str(id)
.map(|u| u.to_string())
.ok()
.as_deref()
!= Some(id)
{
return Err(refused(&file));
}
let single = |path: &Path| {
path.symlink_metadata()
.is_ok_and(|m| m.file_type().is_file() && m.nlink() == 1)
};
if !single(&file) {
return Err(refused(&file));
}
let mut rules = vec![Rule::Literal(text(&file)?)];
for journal in JOURNALS {
let path = dir.join(format!("{id}.db{journal}"));
if path.symlink_metadata().is_ok() && !single(&path) {
return Err(refused(&path));
}
rules.push(Rule::Literal(text(&path)?));
}
Ok(rules)
}
fn first(dir: &Path) -> Result<(Vec<Rule>, Vec<Rule>), String> {
let shown = text(dir)?;
let hex = |n: usize| "[0-9a-f]".repeat(n);
let uuid = [hex(8), hex(4), hex(4), hex(4), hex(12)].join("-");
let mut allow: Vec<Rule> = [""]
.iter()
.chain(JOURNALS.iter())
.map(|journal| Rule::Pattern(format!("^{}/{uuid}\\.db{journal}$", escape(&shown))))
.collect();
let protect = match std::fs::read_dir(dir) {
Ok(entries) => existing(dir, entries)?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
allow.push(Rule::Literal(shown));
Vec::new()
}
Err(error) => {
let shown = dir.display().to_string();
let error = error.to_string();
let said = [("directory", shown.as_str()), ("error", error.as_str())];
return Err(say("agy_conversations_unlisted", &said));
}
};
Ok((allow, protect))
}
fn existing(dir: &Path, entries: std::fs::ReadDir) -> Result<Vec<Rule>, String> {
let mut rules = Vec::new();
for entry in entries {
let entry = entry.map_err(|error| {
let (shown, error) = (dir.display().to_string(), error.to_string());
say(
"agy_conversations_unlisted",
&[("directory", &shown), ("error", &error)],
)
})?;
if rules.len() == CONVERSATIONS_NAMED {
let most = CONVERSATIONS_NAMED.to_string();
let shown = dir.display().to_string();
return Err(say(
"agy_conversations_many",
&[("directory", &shown), ("most", &most)],
));
}
rules.push(Rule::Subpath(text(&entry.path())?));
}
Ok(rules)
}
fn hidden(home: &Path, directory: &Path) -> Result<Vec<String>, String> {
let mut places: Vec<PathBuf> = USER.iter().map(|name| home.join(name)).collect();
for ancestor in directory.ancestors() {
places.extend(PROJECT.iter().map(|name| ancestor.join(name)));
}
let mut out = Vec::new();
for place in places {
for found in [Some(place.clone()), resolve(&place)].into_iter().flatten() {
let found = text(&found)?;
if !out.contains(&found) {
out.push(found);
}
}
}
Ok(out)
}