use super::{jsonedit, read, search_files::files, toml_key};
use crate::clients::{
context::Context,
hooks,
naming::{NEW, OLD},
};
use serde_json::Value;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug)]
pub struct Mention {
pub path: PathBuf,
pub line: usize,
pub allow: bool,
}
#[derive(Default)]
pub struct Found {
pub mentions: Vec<Mention>,
pub unreadable: Vec<PathBuf>,
}
impl Found {
pub fn blocks(&self) -> bool {
!self.unreadable.is_empty() || self.mentions.iter().any(|m| !m.allow)
}
}
#[derive(Clone, Copy)]
pub(super) enum How {
Json,
ClaudeState,
Toml,
Frontmatter,
}
fn names(text: &str) -> bool {
let lower = text.to_lowercase();
lower.contains("neosian-memory") || lower.contains("mcp__neosian")
}
fn path_key(segments: &[String]) -> bool {
matches!(segments, [projects] if projects == "projects")
}
fn line_at(text: &str, offset: usize) -> usize {
text[..offset.min(text.len())].matches('\n').count() + 1
}
fn allow(segments: &[String]) -> bool {
let s: Vec<&str> = segments.iter().map(String::as_str).collect();
matches!(
s.as_slice(),
["permissions", "allow", _]
| ["enabledMcpjsonServers", _]
| ["mcpAllowlist", _]
| [
"projects",
_,
"allowedTools" | "enabledMcpServers" | "enabledMcpjsonServers",
_
]
)
}
fn ours(segments: &[String], value: &Value) -> bool {
let s: Vec<&str> = segments.iter().map(String::as_str).collect();
let server = |key: &str| key == OLD || key == NEW;
match s.as_slice() {
["mcpServers" | "mcp" | "servers", key] => server(key),
["projects", _, "mcpServers", key] => server(key),
["enabledPlugins", "neosian-cache@neosian-local"] => true,
["extraKnownMarketplaces", "neosian-local"] => true,
["statusLine"] => value
.get("command")
.and_then(Value::as_str)
.is_some_and(|c| c.contains(" statusline --client ")),
_ => value
.get("command")
.and_then(Value::as_str)
.is_some_and(hooks::carries),
}
}
fn other_server(segments: &[String]) -> bool {
let s: Vec<&str> = segments.iter().map(String::as_str).collect();
matches!(
s.as_slice(),
["mcpServers" | "mcp", _] | ["projects", _, "mcpServers", _]
)
}
fn claude_state(segments: &[String]) -> bool {
let s: Vec<&str> = segments.iter().map(String::as_str).collect();
matches!(
s.as_slice(),
[] | ["projects"]
| ["projects", _]
| [
"projects",
_,
"disabledMcpServers"
| "enabledMcpServers"
| "enabledMcpjsonServers"
| "disabledMcpjsonServers"
| "allowedTools",
..
]
)
}
fn json(path: &Path, text: &str, value: &Value, state: bool, out: &mut Found) {
let mut stack: Vec<(Vec<String>, &Value)> = vec![(vec![], value)];
while let Some((segments, value)) = stack.pop() {
if ours(&segments, value) || other_server(&segments) || (state && !claude_state(&segments))
{
continue;
}
let hit = |segments: &[String]| {
let at = jsonedit::locate(text, segments).map_or(0, |(start, _)| start);
Mention {
path: path.to_path_buf(),
line: line_at(text, at),
allow: allow(segments),
}
};
match value {
Value::String(s) if names(s) => out.mentions.push(hit(&segments)),
Value::Object(members) => {
for (key, member) in members {
let mut inner = segments.clone();
inner.push(key.clone());
let counted =
!path_key(&segments) && !ours(&inner, member) && !other_server(&inner);
if names(key) && counted {
out.mentions.push(Mention {
allow: false,
..hit(&inner)
});
}
stack.push((inner, member));
}
}
Value::Array(items) => {
for (i, item) in items.iter().enumerate() {
let mut inner = segments.clone();
inner.push(i.to_string());
stack.push((inner, item));
}
}
_ => {}
}
}
}
fn frontmatter(path: &Path, text: &str, out: &mut Found) {
let delimiter = |line: &str| line.trim_end_matches(['\r', ' ', '\t']) == "---";
let mut lines = text.lines().enumerate();
if !lines
.next()
.is_some_and(|(_, l)| delimiter(l.trim_start_matches('\u{feff}')))
{
return;
}
for (index, line) in lines {
if delimiter(line) {
break;
}
if names(line) {
out.mentions.push(Mention {
path: path.to_path_buf(),
line: index + 1,
allow: false,
});
}
}
}
fn toml(path: &Path, text: &str, out: &mut Found) {
let ours = toml_key::regions(text, &[OLD, NEW]);
for (index, line) in text.lines().enumerate() {
let number = index + 1;
let inside = ours.iter().any(|(a, b)| (*a..=*b).contains(&number));
let trimmed = line.trim_start();
let project = trimmed.starts_with("[projects.") || trimmed.starts_with("[hooks.state.");
if !inside && !project && names(line) {
out.mentions.push(Mention {
path: path.to_path_buf(),
line: number,
allow: false,
});
}
}
}
fn jsonc_or_json(path: &Path, read: &read::Read) -> Option<Value> {
if path.extension().is_some_and(|e| e == "jsonc") {
read.jsonc()
} else {
read.json()
}
}
fn search(path: &Path, how: How, out: &mut Found) {
let Some(read) = read::file(path) else {
return;
};
if !names(&read.text) {
return;
}
match how {
How::Frontmatter => frontmatter(path, &read.text, out),
How::Toml => match read.text.parse::<toml::Table>() {
Ok(_) => toml(path, &read.text, out),
Err(_) => out.unreadable.push(path.to_path_buf()),
},
How::Json | How::ClaudeState => match jsonc_or_json(path, &read) {
Some(value) => json(
path,
&read::blank(&read.text),
&value,
matches!(how, How::ClaudeState),
out,
),
None => out.unreadable.push(path.to_path_buf()),
},
}
}
pub fn find(client: &str, context: &Context) -> Found {
let mut out = Found::default();
let mut seen = std::collections::BTreeSet::new();
for (path, how) in files(client, context) {
let real = path.canonicalize().unwrap_or_else(|_| path.clone());
if seen.insert(real) {
search(&path, how, &mut out);
}
}
out
}