use crate::config::Config;
use crate::error::Result;
use crate::merge;
pub use crate::merge::UnifyArgs;
use crate::mutation::{mutation_response, MutationBudget};
use crate::payload::ToolOutput;
pub use crate::search::RecallArgs;
use crate::search::{self, is_schema_catalog_labels, validate_recall_args, SearchArgs};
pub use crate::semantic::SemanticSearchArgs;
use crate::semantic::{self, SemanticRuntime};
use crate::tools;
pub use crate::tools::{JudgeArgs, PlaceArgs, ReviseArgs, WithdrawArgs, WriteArgs};
use neo4rs::Graph;
use serde_json::{json, Value};
use std::path::PathBuf;
#[derive(Clone)]
pub struct MemoryService {
graph: Graph,
semantic: Option<SemanticRuntime>,
secrets_path: PathBuf,
}
impl MemoryService {
pub fn new(graph: Graph, config: &Config) -> Result<Self> {
Ok(Self {
graph,
semantic: SemanticRuntime::from_config(config)?,
secrets_path: config.secrets_path(),
})
}
#[cfg(feature = "developer-tools")]
pub fn with_semantic_runtime(
graph: Graph,
semantic: SemanticRuntime,
secrets_path: PathBuf,
) -> Self {
Self {
graph,
semantic: Some(semantic),
secrets_path,
}
}
pub async fn recall_semantic(&self, args: SemanticSearchArgs) -> Result<ToolOutput> {
semantic::memory_semantic_search(
&self.graph,
self.semantic.as_ref(),
self.secrets_path.clone(),
args,
)
.await
}
pub async fn recall(&self, args: RecallArgs) -> Result<ToolOutput> {
validate_recall_args(&args)?;
let scope = args.scope.clone();
let detail = crate::payload::Detail::parse(args.detail.as_deref())?;
let has_iris = args.iris.is_some();
let effective_at = args.effective_at.clone();
let result = if let Some(history) = args
.history
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
{
tools::memory_recall_history(
&self.graph,
history,
scope.clone(),
args.limit.unwrap_or(20),
)
.await?
} else if let Some(around) = args
.around
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
{
tools::memory_recall_around(&self.graph, around, &args).await?
} else if let Some(iris) = args
.iris
.filter(|values| values.iter().any(|value| !value.trim().is_empty()))
{
tools::memory_recall_iris(
&self.graph,
iris,
scope.clone(),
args.hops.unwrap_or(0),
args.limit.unwrap_or(20),
effective_at.clone(),
)
.await?
} else if let Some(labels) = args
.labels
.filter(|values| values.iter().any(|value| !value.trim().is_empty()))
{
if is_schema_catalog_labels(&labels) {
let mut items = Vec::new();
if labels.iter().any(|label| label.trim() == "Class") {
let catalog = tools::list_schema_catalog(&self.graph, "class").await?;
let nodes = catalog
.get("items")
.and_then(Value::as_array)
.ok_or_else(|| crate::operation_error!("Class catalog is missing items"))?;
items.extend(nodes.iter().cloned());
}
if labels.iter().any(|label| label.trim() == "Property") {
let catalog = tools::list_schema_catalog(&self.graph, "property").await?;
let nodes =
catalog
.get("items")
.and_then(Value::as_array)
.ok_or_else(|| {
crate::operation_error!("Property catalog is missing items")
})?;
items.extend(nodes.iter().cloned());
}
let truncated = items.len() > args.limit.unwrap_or(20) as usize;
items.truncate(args.limit.unwrap_or(20) as usize);
json!({
"ok": true,
"mode": "catalog",
"scope": scope,
"facts": [],
"nodes": items,
"paths": [],
"about": [],
"lookups": [],
"truncated": truncated,
})
} else {
search::memory_search(
&self.graph,
SearchArgs {
layers: scope.clone(),
text: None,
labels: Some(labels),
limit: args.limit,
effective_at: effective_at.clone(),
},
)
.await?
}
} else {
search::memory_search(
&self.graph,
SearchArgs {
layers: scope.clone(),
text: args.text,
labels: None,
limit: args.limit,
effective_at,
},
)
.await?
};
let mut result = result;
if has_iris && detail == crate::payload::Detail::Concise {
crate::payload::omit_iris_top_level_facts(&mut result);
}
ToolOutput::from_value(crate::payload::finish_recall(result, &scope, detail)?)
}
#[cfg(feature = "developer-tools")]
pub async fn write(&self, args: WriteArgs) -> Result<ToolOutput> {
mutation_tool_output("write", tools::memory_write(&self.graph, args).await?)
}
pub(crate) async fn write_with_budget(
&self,
args: WriteArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"write",
tools::memory_write_with_budget(&self.graph, args, budget).await?,
)
}
#[cfg(feature = "developer-tools")]
pub async fn revise(&self, args: ReviseArgs) -> Result<ToolOutput> {
mutation_tool_output("revise", tools::memory_revise(&self.graph, args).await?)
}
pub(crate) async fn revise_with_budget(
&self,
args: ReviseArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"revise",
tools::memory_revise_with_budget(&self.graph, args, budget).await?,
)
}
#[cfg(feature = "developer-tools")]
pub async fn withdraw(&self, args: WithdrawArgs) -> Result<ToolOutput> {
mutation_tool_output("withdraw", tools::memory_withdraw(&self.graph, args).await?)
}
pub(crate) async fn withdraw_with_budget(
&self,
args: WithdrawArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"withdraw",
tools::memory_withdraw_with_budget(&self.graph, args, budget).await?,
)
}
#[cfg(feature = "developer-tools")]
pub async fn judge(&self, args: JudgeArgs) -> Result<ToolOutput> {
mutation_tool_output("judge", tools::memory_judge(&self.graph, args).await?)
}
pub(crate) async fn judge_with_budget(
&self,
args: JudgeArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"judge",
tools::memory_judge_with_budget(&self.graph, args, budget).await?,
)
}
#[cfg(feature = "developer-tools")]
pub async fn place(&self, args: PlaceArgs) -> Result<ToolOutput> {
mutation_tool_output("place", tools::memory_place(&self.graph, args).await?)
}
pub(crate) async fn place_with_budget(
&self,
args: PlaceArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"place",
tools::memory_place_with_budget(&self.graph, args, budget).await?,
)
}
#[cfg(feature = "developer-tools")]
pub async fn unify(&self, args: UnifyArgs) -> Result<ToolOutput> {
mutation_tool_output("unify", merge::memory_unify(&self.graph, args).await?)
}
pub(crate) async fn unify_with_budget(
&self,
args: UnifyArgs,
budget: MutationBudget,
) -> Result<ToolOutput> {
mutation_tool_output(
"unify",
merge::memory_unify_with_budget(&self.graph, args, budget).await?,
)
}
}
fn mutation_tool_output(operation: &'static str, value: Value) -> Result<ToolOutput> {
let applied = value
.get("noop")
.and_then(Value::as_bool)
.is_none_or(|noop| !noop);
mutation_response(operation, applied, ToolOutput::from_value(value))
}