use axum::{
Json,
extract::{FromRef, Path, Query, Request, State},
http::{HeaderMap, StatusCode},
middleware::Next,
response::IntoResponse,
};
use chrono::{Duration, Utc};
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;
use crate::config::{ResolvedTtl, TierConfig};
use crate::db;
use crate::embeddings::Embedder;
use crate::hnsw::VectorIndex;
use crate::models::{
CreateMemory, ForgetQuery, LinkBody, ListQuery, Memory, MemoryLink, RecallBody, RecallQuery,
RegisterAgentBody, SearchQuery, Tier, UpdateMemory,
};
use crate::validate;
pub type Db = Arc<Mutex<(rusqlite::Connection, std::path::PathBuf, ResolvedTtl, bool)>>;
#[derive(Clone)]
pub struct AppState {
pub db: Db,
pub embedder: Arc<Option<Embedder>>,
pub vector_index: Arc<Mutex<Option<VectorIndex>>>,
pub federation: Arc<Option<crate::federation::FederationConfig>>,
pub tier_config: Arc<TierConfig>,
pub scoring: Arc<crate::config::ResolvedScoring>,
}
impl FromRef<AppState> for Db {
fn from_ref(app: &AppState) -> Self {
app.db.clone()
}
}
const MAX_BULK_SIZE: usize = 1000;
const BULK_FANOUT_CONCURRENCY: usize = 8;
#[derive(Clone)]
pub struct ApiKeyState {
pub key: Option<String>,
}
#[inline]
fn percent_decode_lossy(input: &str) -> String {
let bytes = input.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let h = (bytes[i + 1] as char).to_digit(16);
let l = (bytes[i + 2] as char).to_digit(16);
if let (Some(h), Some(l)) = (h, l) {
out.push(u8::try_from(h * 16 + l).unwrap_or(0));
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
#[inline]
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff: u8 = 0;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
pub async fn api_key_auth(
State(auth): State<ApiKeyState>,
req: Request,
next: Next,
) -> impl IntoResponse {
let Some(ref expected) = auth.key else {
return next.run(req).await.into_response();
};
if req.uri().path() == "/api/v1/health" {
return next.run(req).await.into_response();
}
if let Some(header_val) = req.headers().get("x-api-key")
&& let Ok(val) = header_val.to_str()
&& constant_time_eq(val.as_bytes(), expected.as_bytes())
{
return next.run(req).await.into_response();
}
if let Some(query) = req.uri().query() {
for pair in query.split('&') {
if let Some(val) = pair.strip_prefix("api_key=") {
let decoded = percent_decode_lossy(val);
if constant_time_eq(decoded.as_bytes(), expected.as_bytes()) {
return next.run(req).await.into_response();
}
}
}
}
(
StatusCode::UNAUTHORIZED,
Json(json!({"error": "missing or invalid API key"})),
)
.into_response()
}
pub async fn health(State(app): State<AppState>) -> impl IntoResponse {
let lock = app.db.lock().await;
let ok = db::health_check(&lock.0).unwrap_or(false);
drop(lock);
let embedder_ready = app.embedder.as_ref().is_some();
let federation_enabled = app.federation.as_ref().is_some();
let code = if ok {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
(
code,
Json(json!({
"status": if ok { "ok" } else { "error" },
"service": "ai-memory",
"version": env!("CARGO_PKG_VERSION"),
"embedder_ready": embedder_ready,
"federation_enabled": federation_enabled,
})),
)
.into_response()
}
pub async fn prometheus_metrics(State(state): State<Db>) -> impl IntoResponse {
{
let lock = state.lock().await;
if let Ok(stats) = db::stats(&lock.0, &lock.1) {
crate::metrics::registry()
.memories_gauge
.set(stats.total.try_into().unwrap_or(i64::MAX));
}
}
let body = crate::metrics::render();
(
StatusCode::OK,
[(
axum::http::header::CONTENT_TYPE,
"text/plain; version=0.0.4; charset=utf-8",
)],
body,
)
.into_response()
}
#[allow(clippy::too_many_lines)]
pub async fn create_memory(
State(app): State<AppState>,
headers: HeaderMap,
Json(body): Json<CreateMemory>,
) -> impl IntoResponse {
let state = app.db.clone();
if let Err(e) = validate::validate_create(&body) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let agent_id =
match crate::identity::resolve_http_agent_id(body.agent_id.as_deref(), header_agent_id) {
Ok(id) => id,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let mut metadata = body.metadata;
if let Some(obj) = metadata.as_object_mut() {
obj.insert("agent_id".to_string(), serde_json::Value::String(agent_id));
}
if let Some(ref s) = body.scope {
if let Err(e) = validate::validate_scope(s) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
if let Some(obj) = metadata.as_object_mut() {
obj.insert("scope".to_string(), serde_json::Value::String(s.clone()));
}
}
let embedding_text = format!("{} {}", body.title, body.content);
let embedding: Option<Vec<f32>> =
app.embedder
.as_ref()
.as_ref()
.and_then(|emb| match emb.embed(&embedding_text) {
Ok(v) => Some(v),
Err(e) => {
tracing::warn!("embedding generation failed: {e}");
None
}
});
let now = Utc::now();
let lock = state.lock().await;
let expires_at = body.expires_at.or_else(|| {
body.ttl_secs
.or(lock.2.ttl_for_tier(&body.tier))
.map(|s| (now + Duration::seconds(s)).to_rfc3339())
});
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: body.tier,
namespace: body.namespace,
title: body.title,
content: body.content,
tags: body.tags,
priority: body.priority.clamp(1, 10),
confidence: body.confidence.clamp(0.0, 1.0),
source: body.source,
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at,
metadata,
};
{
use crate::models::{GovernanceDecision, GovernedAction};
let agent_for_gov = mem
.metadata
.get("agent_id")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let payload = serde_json::to_value(&mem).unwrap_or_default();
match db::enforce_governance(
&lock.0,
GovernedAction::Store,
&mem.namespace,
&agent_for_gov,
None,
None,
&payload,
) {
Ok(GovernanceDecision::Allow) => {}
Ok(GovernanceDecision::Deny(reason)) => {
return (
StatusCode::FORBIDDEN,
Json(json!({"error": format!("store denied by governance: {reason}")})),
)
.into_response();
}
Ok(GovernanceDecision::Pending(pending_id)) => {
let pending_row = db::get_pending_action(&lock.0, &pending_id).ok().flatten();
let namespace = mem.namespace.clone();
drop(lock);
if let (Some(pa), Some(fed)) = (pending_row.as_ref(), app.federation.as_ref()) {
match crate::federation::broadcast_pending_quorum(fed, pa).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload =
crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
return (
StatusCode::ACCEPTED,
Json(json!({
"status": "pending",
"pending_id": pending_id,
"reason": "governance requires approval",
"action": "store",
"namespace": namespace,
})),
)
.into_response();
}
Err(e) => {
tracing::error!("governance error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "governance check failed"})),
)
.into_response();
}
}
}
let contradictions =
db::find_contradictions(&lock.0, &mem.title, &mem.namespace).unwrap_or_default();
let contradiction_ids: Vec<String> = contradictions
.iter()
.filter(|c| c.id != mem.id)
.map(|c| c.id.clone())
.collect();
match db::insert(&lock.0, &mem) {
Ok(actual_id) => {
if let Some(ref vec) = embedding
&& let Err(e) = db::set_embedding(&lock.0, &actual_id, vec)
{
tracing::warn!("failed to store embedding for {actual_id}: {e}");
}
drop(lock);
if let Some(vec) = embedding {
let mut idx_lock = app.vector_index.lock().await;
if let Some(idx) = idx_lock.as_mut() {
idx.insert(actual_id.clone(), vec);
}
}
let resolved_agent_id = mem
.metadata
.get("agent_id")
.and_then(|v| v.as_str())
.map(str::to_string);
let mut response = json!({
"id": actual_id,
"tier": mem.tier,
"namespace": mem.namespace,
"title": mem.title,
"agent_id": resolved_agent_id,
});
if !contradiction_ids.is_empty() {
response["potential_contradictions"] = json!(contradiction_ids);
}
if let Some(fed) = app.federation.as_ref() {
let mut mem_echo = mem.clone();
mem_echo.id = actual_id.clone();
match crate::federation::broadcast_store_quorum(fed, &mem_echo).await {
Ok(tracker) => match crate::federation::finalise_quorum(&tracker) {
Ok(got) => {
response["quorum_acks"] = json!(got);
return (StatusCode::CREATED, Json(response)).into_response();
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
},
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
(StatusCode::CREATED, Json(response)).into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn register_agent(
State(app): State<AppState>,
Json(body): Json<RegisterAgentBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_agent_id(&body.agent_id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
if let Err(e) = validate::validate_agent_type(&body.agent_type) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let capabilities = body.capabilities.unwrap_or_default();
if let Err(e) = validate::validate_capabilities(&capabilities) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = app.db.lock().await;
let register_result =
db::register_agent(&lock.0, &body.agent_id, &body.agent_type, &capabilities);
let registered_mem = match ®ister_result {
Ok(id) => db::get(&lock.0, id).ok().flatten(),
Err(_) => None,
};
drop(lock);
match register_result {
Ok(id) => {
if let (Some(fed), Some(mem)) = (app.federation.as_ref(), registered_mem.as_ref()) {
match crate::federation::broadcast_store_quorum(fed, mem).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(e) => {
tracing::warn!("register_agent fanout error (local committed): {e:?}");
}
}
}
(
StatusCode::CREATED,
Json(json!({
"registered": true,
"id": id,
"agent_id": body.agent_id,
"agent_type": body.agent_type,
"capabilities": capabilities,
})),
)
.into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Deserialize)]
pub struct PendingListQuery {
#[serde(default)]
pub status: Option<String>,
#[serde(default = "default_pending_limit")]
pub limit: Option<usize>,
}
#[allow(clippy::unnecessary_wraps)]
fn default_pending_limit() -> Option<usize> {
Some(100)
}
pub async fn list_pending(
State(state): State<Db>,
Query(p): Query<PendingListQuery>,
) -> impl IntoResponse {
let limit = p.limit.unwrap_or(100).min(1000);
let lock = state.lock().await;
match db::list_pending_actions(&lock.0, p.status.as_deref(), limit) {
Ok(items) => Json(json!({"count": items.len(), "pending": items})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[allow(clippy::too_many_lines)]
pub async fn approve_pending(
State(app): State<AppState>,
headers: HeaderMap,
Path(id): Path<String>,
) -> impl IntoResponse {
use crate::db::ApproveOutcome;
use crate::models::PendingDecision;
let state = app.db.clone();
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let agent_id = match crate::identity::resolve_http_agent_id(None, header_agent_id) {
Ok(a) => a,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let lock = state.lock().await;
match db::approve_with_approver_type(&lock.0, &id, &agent_id) {
Ok(ApproveOutcome::Approved) => match db::execute_pending_action(&lock.0, &id) {
Ok(memory_id) => {
let produced_mem = memory_id
.as_deref()
.and_then(|mid| db::get(&lock.0, mid).ok().flatten());
drop(lock);
if let Some(fed) = app.federation.as_ref() {
let decision = PendingDecision {
id: id.clone(),
approved: true,
decider: agent_id.clone(),
};
match crate::federation::broadcast_pending_decision_quorum(fed, &decision).await
{
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload =
crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
if let Some(ref mem) = produced_mem
&& let Some(resp) = fanout_or_503(&app, mem).await
{
return resp;
}
}
Json(json!({
"approved": true,
"id": id,
"decided_by": agent_id,
"executed": true,
"memory_id": memory_id,
}))
.into_response()
}
Err(e) => {
tracing::error!("execute pending error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "approved but execution failed"})),
)
.into_response()
}
},
Ok(ApproveOutcome::Pending { votes, quorum }) => (
StatusCode::ACCEPTED,
Json(json!({
"approved": false,
"status": "pending",
"id": id,
"votes": votes,
"quorum": quorum,
"reason": "consensus threshold not yet reached",
})),
)
.into_response(),
Ok(ApproveOutcome::Rejected(reason)) => (
StatusCode::FORBIDDEN,
Json(json!({"error": format!("approve rejected: {reason}")})),
)
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn reject_pending(
State(app): State<AppState>,
headers: HeaderMap,
Path(id): Path<String>,
) -> impl IntoResponse {
use crate::models::PendingDecision;
let state = app.db.clone();
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let agent_id = match crate::identity::resolve_http_agent_id(None, header_agent_id) {
Ok(a) => a,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let lock = state.lock().await;
match db::decide_pending_action(&lock.0, &id, false, &agent_id) {
Ok(true) => {
drop(lock);
if let Some(fed) = app.federation.as_ref() {
let decision = PendingDecision {
id: id.clone(),
approved: false,
decider: agent_id.clone(),
};
match crate::federation::broadcast_pending_decision_quorum(fed, &decision).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
Json(json!({"rejected": true, "id": id, "decided_by": agent_id})).into_response()
}
Ok(false) => (
StatusCode::NOT_FOUND,
Json(json!({"error": "pending action not found or already decided"})),
)
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn list_agents(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match db::list_agents(&lock.0) {
Ok(agents) => (
StatusCode::OK,
Json(json!({"count": agents.len(), "agents": agents})),
)
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn get_memory(State(state): State<Db>, Path(id): Path<String>) -> impl IntoResponse {
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = state.lock().await;
match db::resolve_id(&lock.0, &id) {
Ok(Some(mem)) => {
let links = db::get_links(&lock.0, &mem.id).unwrap_or_default();
Json(json!({"memory": mem, "links": links})).into_response()
}
Ok(None) => (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response(),
Err(e) => {
let msg = e.to_string();
if msg.contains("ambiguous ID prefix") {
return (StatusCode::BAD_REQUEST, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[allow(clippy::too_many_lines)]
pub async fn update_memory(
State(app): State<AppState>,
Path(id): Path<String>,
Json(body): Json<UpdateMemory>,
) -> impl IntoResponse {
let state = app.db.clone();
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
if let Err(e) = validate::validate_update(&body) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = state.lock().await;
let resolved_id = match db::resolve_id(&lock.0, &id) {
Ok(Some(mem)) => mem.id,
Ok(None) => {
return (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response();
}
Err(e) => {
let msg = e.to_string();
if msg.contains("ambiguous ID prefix") {
return (StatusCode::BAD_REQUEST, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
let preserved_metadata = body.metadata.as_ref().map(|new_meta| {
let existing_meta = db::get(&lock.0, &resolved_id).ok().flatten().map_or_else(
|| serde_json::Value::Object(serde_json::Map::new()),
|m| m.metadata,
);
crate::identity::preserve_agent_id(&existing_meta, new_meta)
});
match db::update(
&lock.0,
&resolved_id,
body.title.as_deref(),
body.content.as_deref(),
body.tier.as_ref(),
body.namespace.as_deref(),
body.tags.as_ref(),
body.priority,
body.confidence,
body.expires_at.as_deref(),
preserved_metadata.as_ref(),
) {
Ok((true, _)) => {
let mem = db::get(&lock.0, &resolved_id).ok().flatten();
let content_changed = body.title.is_some() || body.content.is_some();
let mut lock_opt = Some(lock);
if content_changed && let Some(ref m) = mem {
let text = format!("{} {}", m.title, m.content);
if let Some(emb) = app.embedder.as_ref().as_ref() {
match emb.embed(&text) {
Ok(vec) => {
if let Some(ref l) = lock_opt
&& let Err(e) = db::set_embedding(&l.0, &resolved_id, &vec)
{
tracing::warn!(
"failed to refresh embedding for {resolved_id}: {e}"
);
}
lock_opt.take();
let mut idx_lock = app.vector_index.lock().await;
if let Some(idx) = idx_lock.as_mut() {
idx.remove(&resolved_id);
idx.insert(resolved_id.clone(), vec);
}
}
Err(e) => tracing::warn!("embedding regeneration failed: {e}"),
}
}
}
drop(lock_opt);
if let (Some(fed), Some(m)) = (app.federation.as_ref(), mem.as_ref())
&& let Ok(tracker) = crate::federation::broadcast_store_quorum(fed, m).await
&& let Err(err) = crate::federation::finalise_quorum(&tracker)
{
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
Json(json!(mem)).into_response()
}
Ok((false, _)) => {
(StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response()
}
Err(e) => {
let msg = e.to_string();
if msg.contains("already exists in namespace") {
return (StatusCode::CONFLICT, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[allow(clippy::too_many_lines)]
pub async fn delete_memory(
State(app): State<AppState>,
headers: HeaderMap,
Path(id): Path<String>,
) -> impl IntoResponse {
let state = app.db.clone();
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = state.lock().await;
let target = match db::resolve_id(&lock.0, &id) {
Ok(Some(m)) => m,
Ok(None) => {
return (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response();
}
Err(e) => {
let msg = e.to_string();
if msg.contains("ambiguous ID prefix") {
return (StatusCode::BAD_REQUEST, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
{
use crate::models::{GovernanceDecision, GovernedAction};
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let agent_id = match crate::identity::resolve_http_agent_id(None, header_agent_id) {
Ok(a) => a,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let mem_owner = target
.metadata
.get("agent_id")
.and_then(|v| v.as_str())
.map(str::to_string);
let payload = json!({"id": target.id, "title": target.title});
match db::enforce_governance(
&lock.0,
GovernedAction::Delete,
&target.namespace,
&agent_id,
Some(&target.id),
mem_owner.as_deref(),
&payload,
) {
Ok(GovernanceDecision::Allow) => {}
Ok(GovernanceDecision::Deny(reason)) => {
return (
StatusCode::FORBIDDEN,
Json(json!({"error": format!("delete denied by governance: {reason}")})),
)
.into_response();
}
Ok(GovernanceDecision::Pending(pending_id)) => {
let pending_row = db::get_pending_action(&lock.0, &pending_id).ok().flatten();
let target_id = target.id.clone();
drop(lock);
if let (Some(pa), Some(fed)) = (pending_row.as_ref(), app.federation.as_ref()) {
match crate::federation::broadcast_pending_quorum(fed, pa).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload =
crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
return (
StatusCode::ACCEPTED,
Json(json!({
"status": "pending",
"pending_id": pending_id,
"reason": "governance requires approval",
"action": "delete",
"memory_id": target_id,
})),
)
.into_response();
}
Err(e) => {
tracing::error!("governance error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "governance check failed"})),
)
.into_response();
}
}
}
let delete_outcome = db::delete(&lock.0, &target.id);
drop(lock);
match delete_outcome {
Ok(true) => {
if let Some(fed) = app.federation.as_ref()
&& let Ok(tracker) =
crate::federation::broadcast_delete_quorum(fed, &target.id).await
&& let Err(err) = crate::federation::finalise_quorum(&tracker)
{
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
Json(json!({"deleted": true})).into_response()
}
_ => (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response(),
}
}
#[allow(clippy::too_many_lines)]
pub async fn promote_memory(
State(app): State<AppState>,
headers: HeaderMap,
Path(id): Path<String>,
) -> impl IntoResponse {
let state = app.db.clone();
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = state.lock().await;
let target = match db::resolve_id(&lock.0, &id) {
Ok(Some(mem)) => mem,
Ok(None) => {
return (StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response();
}
Err(e) => {
let msg = e.to_string();
if msg.contains("ambiguous ID prefix") {
return (StatusCode::BAD_REQUEST, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
{
use crate::models::{GovernanceDecision, GovernedAction};
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let agent_id = match crate::identity::resolve_http_agent_id(None, header_agent_id) {
Ok(a) => a,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let mem_owner = target
.metadata
.get("agent_id")
.and_then(|v| v.as_str())
.map(str::to_string);
let payload = json!({"id": target.id});
match db::enforce_governance(
&lock.0,
GovernedAction::Promote,
&target.namespace,
&agent_id,
Some(&target.id),
mem_owner.as_deref(),
&payload,
) {
Ok(GovernanceDecision::Allow) => {}
Ok(GovernanceDecision::Deny(reason)) => {
return (
StatusCode::FORBIDDEN,
Json(json!({"error": format!("promote denied by governance: {reason}")})),
)
.into_response();
}
Ok(GovernanceDecision::Pending(pending_id)) => {
let pending_row = db::get_pending_action(&lock.0, &pending_id).ok().flatten();
let target_id = target.id.clone();
drop(lock);
if let (Some(pa), Some(fed)) = (pending_row.as_ref(), app.federation.as_ref()) {
match crate::federation::broadcast_pending_quorum(fed, pa).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload =
crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
return (
StatusCode::ACCEPTED,
Json(json!({
"status": "pending",
"pending_id": pending_id,
"reason": "governance requires approval",
"action": "promote",
"memory_id": target_id,
})),
)
.into_response();
}
Err(e) => {
tracing::error!("governance error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "governance check failed"})),
)
.into_response();
}
}
}
let resolved_id = target.id.clone();
match db::update(
&lock.0,
&resolved_id,
None,
None,
Some(&Tier::Long),
None,
None,
None,
None,
None,
None,
) {
Ok((true, _)) => {
if let Err(e) = lock.0.execute(
"UPDATE memories SET expires_at = NULL WHERE id = ?1",
rusqlite::params![resolved_id],
) {
tracing::error!("promote clear expiry failed: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
let promoted_mem = db::get(&lock.0, &resolved_id).ok().flatten();
drop(lock);
if let (Some(fed), Some(m)) = (app.federation.as_ref(), promoted_mem.as_ref())
&& let Ok(tracker) = crate::federation::broadcast_store_quorum(fed, m).await
&& let Err(err) = crate::federation::finalise_quorum(&tracker)
{
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
Json(json!({"promoted": true, "id": resolved_id, "tier": "long"})).into_response()
}
Ok((false, _)) => {
(StatusCode::NOT_FOUND, Json(json!({"error": "not found"}))).into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn list_memories(
State(state): State<Db>,
Query(p): Query<ListQuery>,
) -> impl IntoResponse {
if let Some(ref aid) = p.agent_id
&& let Err(e) = validate::validate_agent_id(aid)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id filter: {e}")})),
)
.into_response();
}
let lock = state.lock().await;
let limit = p.limit.unwrap_or(20).min(MAX_BULK_SIZE);
match db::list(
&lock.0,
p.namespace.as_deref(),
p.tier.as_ref(),
limit,
p.offset.unwrap_or(0),
p.min_priority,
p.since.as_deref(),
p.until.as_deref(),
p.tags.as_deref(),
p.agent_id.as_deref(),
) {
Ok(mems) => Json(json!({"memories": mems, "count": mems.len()})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn search_memories(
State(state): State<Db>,
Query(p): Query<SearchQuery>,
) -> impl IntoResponse {
if p.q.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "query is required"})),
)
.into_response();
}
if let Some(ref aid) = p.agent_id
&& let Err(e) = validate::validate_agent_id(aid)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id filter: {e}")})),
)
.into_response();
}
if let Some(ref a) = p.as_agent
&& let Err(e) = validate::validate_namespace(a)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid as_agent: {e}")})),
)
.into_response();
}
let lock = state.lock().await;
let limit = p.limit.unwrap_or(20).min(MAX_BULK_SIZE);
match db::search(
&lock.0,
&p.q,
p.namespace.as_deref(),
p.tier.as_ref(),
limit,
p.min_priority,
p.since.as_deref(),
p.until.as_deref(),
p.tags.as_deref(),
p.agent_id.as_deref(),
p.as_agent.as_deref(),
) {
Ok(r) => Json(json!({"results": r, "count": r.len(), "query": p.q})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn recall_memories_get(
State(app): State<AppState>,
Query(p): Query<RecallQuery>,
) -> impl IntoResponse {
let ctx = p.context.unwrap_or_default();
if ctx.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "context is required"})),
)
.into_response();
}
if p.budget_tokens == Some(0) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "budget_tokens must be >= 1"})),
)
.into_response();
}
if let Some(ref a) = p.as_agent
&& let Err(e) = validate::validate_namespace(a)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid as_agent: {e}")})),
)
.into_response();
}
let limit = p.limit.unwrap_or(10).min(50);
recall_response(
&app,
&ctx,
p.namespace.as_deref(),
limit,
p.tags.as_deref(),
p.since.as_deref(),
p.until.as_deref(),
p.as_agent.as_deref(),
p.budget_tokens,
)
.await
}
pub async fn recall_memories_post(
State(app): State<AppState>,
Json(body): Json<RecallBody>,
) -> impl IntoResponse {
if body.context.trim().is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "context is required"})),
)
.into_response();
}
if body.budget_tokens == Some(0) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "budget_tokens must be >= 1"})),
)
.into_response();
}
if let Some(ref a) = body.as_agent
&& let Err(e) = validate::validate_namespace(a)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid as_agent: {e}")})),
)
.into_response();
}
let limit = body.limit.unwrap_or(10).min(50);
recall_response(
&app,
&body.context,
body.namespace.as_deref(),
limit,
body.tags.as_deref(),
body.since.as_deref(),
body.until.as_deref(),
body.as_agent.as_deref(),
body.budget_tokens,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn recall_response(
app: &AppState,
context: &str,
namespace: Option<&str>,
limit: usize,
tags: Option<&str>,
since: Option<&str>,
until: Option<&str>,
as_agent: Option<&str>,
budget_tokens: Option<usize>,
) -> axum::response::Response {
let query_emb: Option<Vec<f32>> = if let Some(emb) = app.embedder.as_ref().as_ref() {
match emb.embed(context) {
Ok(v) => Some(v),
Err(e) => {
tracing::warn!("recall: embedder query failed, falling back to keyword-only: {e}");
None
}
}
} else {
None
};
let lock = app.db.lock().await;
let short_extend = lock.2.short_extend_secs;
let mid_extend = lock.2.mid_extend_secs;
let (result, mode) = if let Some(ref qe) = query_emb {
let vi_guard = app.vector_index.lock().await;
let vi_ref = vi_guard.as_ref();
let r = db::recall_hybrid(
&lock.0,
context,
qe,
namespace,
limit,
tags,
since,
until,
vi_ref,
short_extend,
mid_extend,
as_agent,
budget_tokens,
app.scoring.as_ref(),
);
drop(vi_guard);
(r, "hybrid")
} else {
let r = db::recall(
&lock.0,
context,
namespace,
limit,
tags,
since,
until,
short_extend,
mid_extend,
as_agent,
budget_tokens,
);
(r, "keyword")
};
match result {
Ok((r, tokens_used)) => {
let scored: Vec<serde_json::Value> = r
.iter()
.map(|(m, s)| {
let mut v = serde_json::to_value(m).unwrap_or_default();
if let Some(obj) = v.as_object_mut() {
obj.insert("score".to_string(), json!((*s * 1000.0).round() / 1000.0));
}
v
})
.collect();
let mut resp = json!({
"memories": scored,
"count": scored.len(),
"tokens_used": tokens_used,
"mode": mode,
});
if let Some(b) = budget_tokens {
resp["budget_tokens"] = json!(b);
}
Json(resp).into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn forget_memories(
State(state): State<Db>,
Json(body): Json<ForgetQuery>,
) -> impl IntoResponse {
let lock = state.lock().await;
match db::forget(
&lock.0,
body.namespace.as_deref(),
body.pattern.as_deref(),
body.tier.as_ref(),
lock.3, ) {
Ok(n) => Json(json!({"deleted": n})).into_response(),
Err(e) => (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response(),
}
}
#[derive(Deserialize)]
pub struct ContradictionsQuery {
pub topic: Option<String>,
pub namespace: Option<String>,
pub limit: Option<usize>,
}
#[allow(clippy::too_many_lines)]
pub async fn detect_contradictions(
State(state): State<Db>,
Query(q): Query<ContradictionsQuery>,
) -> impl IntoResponse {
if q.topic.is_none() && q.namespace.is_none() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "at least one of `topic` or `namespace` is required"})),
)
.into_response();
}
if let Some(ref ns) = q.namespace
&& let Err(e) = validate::validate_namespace(ns)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let limit = q.limit.unwrap_or(50).min(MAX_BULK_SIZE);
let lock = state.lock().await;
let all = match db::list(
&lock.0,
q.namespace.as_deref(),
None,
limit,
0,
None,
None,
None,
None,
None,
) {
Ok(v) => v,
Err(e) => {
tracing::error!("detect_contradictions list error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
let candidates: Vec<Memory> = match q.topic.as_deref() {
Some(t) => all
.into_iter()
.filter(|m| {
m.metadata
.get("topic")
.and_then(|v| v.as_str())
.is_some_and(|s| s == t)
|| m.title == t
})
.collect(),
None => all,
};
let candidate_ids: std::collections::HashSet<String> =
candidates.iter().map(|m| m.id.clone()).collect();
let mut existing_links: Vec<serde_json::Value> = Vec::new();
for id in &candidate_ids {
if let Ok(links) = db::get_links(&lock.0, id) {
for link in links {
if link.relation.contains("contradict")
&& candidate_ids.contains(&link.source_id)
&& candidate_ids.contains(&link.target_id)
{
existing_links.push(json!({
"source_id": link.source_id,
"target_id": link.target_id,
"relation": link.relation,
"synthesized": false,
}));
}
}
}
}
existing_links.sort_by_key(|v| {
(
v.get("source_id")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
v.get("target_id")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
v.get("relation")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
)
});
existing_links.dedup_by_key(|v| {
(
v.get("source_id")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
v.get("target_id")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
v.get("relation")
.and_then(|s| s.as_str())
.unwrap_or("")
.to_string(),
)
});
let mut synth_links: Vec<serde_json::Value> = Vec::new();
for (i, a) in candidates.iter().enumerate() {
for b in candidates.iter().skip(i + 1) {
let same_topic = match q.topic.as_deref() {
Some(_) => true,
None => a.title == b.title,
};
if same_topic && a.content != b.content && a.id != b.id {
synth_links.push(json!({
"source_id": a.id,
"target_id": b.id,
"relation": "contradicts",
"synthesized": true,
}));
}
}
}
let mut links = existing_links;
links.extend(synth_links);
Json(json!({
"memories": candidates,
"links": links,
}))
.into_response()
}
pub async fn list_namespaces(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match db::list_namespaces(&lock.0) {
Ok(ns) => Json(json!({"namespaces": ns})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct TaxonomyQuery {
pub prefix: Option<String>,
pub depth: Option<usize>,
pub limit: Option<usize>,
}
pub async fn get_taxonomy(
State(state): State<Db>,
Query(p): Query<TaxonomyQuery>,
) -> impl IntoResponse {
let prefix_owned: Option<String> = p
.prefix
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|s| s.trim_end_matches('/').to_string());
if let Some(pref) = prefix_owned.as_deref()
&& let Err(e) = validate::validate_namespace(pref)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid namespace_prefix: {e}")})),
)
.into_response();
}
let depth = p
.depth
.unwrap_or(crate::models::MAX_NAMESPACE_DEPTH)
.min(crate::models::MAX_NAMESPACE_DEPTH);
let limit = p.limit.unwrap_or(1000).clamp(1, 10_000);
let lock = state.lock().await;
match db::get_taxonomy(&lock.0, prefix_owned.as_deref(), depth, limit) {
Ok(tax) => Json(json!({
"tree": tax.tree,
"total_count": tax.total_count,
"truncated": tax.truncated,
}))
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckDuplicateBody {
pub title: String,
pub content: String,
pub namespace: Option<String>,
pub threshold: Option<f32>,
}
pub async fn check_duplicate(
State(app): State<AppState>,
Json(body): Json<CheckDuplicateBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_title(&body.title) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid title: {e}")})),
)
.into_response();
}
if let Err(e) = validate::validate_content(&body.content) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid content: {e}")})),
)
.into_response();
}
let namespace = body
.namespace
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
if let Some(ns) = namespace
&& let Err(e) = validate::validate_namespace(ns)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid namespace: {e}")})),
)
.into_response();
}
let threshold = body.threshold.unwrap_or(db::DUPLICATE_THRESHOLD_DEFAULT);
let embedding_text = format!("{} {}", body.title, body.content);
let query_embedding = match app.embedder.as_ref().as_ref() {
Some(emb) => match emb.embed(&embedding_text) {
Ok(v) => v,
Err(e) => {
tracing::warn!("embedding generation failed: {e}");
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"error": "embedder failed to encode input"})),
)
.into_response();
}
},
None => {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({
"error": "memory_check_duplicate requires the embedder; daemon must be started with semantic tier or above"
})),
)
.into_response();
}
};
let lock = app.db.lock().await;
let check = match db::check_duplicate(&lock.0, &query_embedding, namespace, threshold) {
Ok(c) => c,
Err(e) => {
tracing::error!("handler error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
let nearest_json = check.nearest.as_ref().map(|m| {
json!({
"id": m.id,
"title": m.title,
"namespace": m.namespace,
"similarity": (m.similarity * 1000.0).round() / 1000.0,
})
});
let suggested_merge = if check.is_duplicate {
check.nearest.as_ref().map(|m| m.id.clone())
} else {
None
};
Json(json!({
"is_duplicate": check.is_duplicate,
"threshold": check.threshold,
"nearest": nearest_json,
"suggested_merge": suggested_merge,
"candidates_scanned": check.candidates_scanned,
}))
.into_response()
}
#[derive(Debug, Deserialize)]
pub struct EntityRegisterBody {
pub canonical_name: String,
pub namespace: String,
#[serde(default)]
pub aliases: Vec<String>,
#[serde(default)]
pub metadata: serde_json::Value,
pub agent_id: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct EntityByAliasQuery {
pub alias: String,
pub namespace: Option<String>,
}
pub async fn entity_register(
State(state): State<Db>,
headers: HeaderMap,
Json(body): Json<EntityRegisterBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_title(&body.canonical_name) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid canonical_name: {e}")})),
)
.into_response();
}
if let Err(e) = validate::validate_namespace(&body.namespace) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid namespace: {e}")})),
)
.into_response();
}
let agent_id = body
.agent_id
.as_deref()
.or_else(|| headers.get("x-agent-id").and_then(|v| v.to_str().ok()))
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string);
if let Some(aid) = agent_id.as_deref()
&& let Err(e) = validate::validate_agent_id(aid)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
let extra_metadata = if body.metadata.is_object() {
body.metadata.clone()
} else {
json!({})
};
let lock = state.lock().await;
match db::entity_register(
&lock.0,
&body.canonical_name,
&body.namespace,
&body.aliases,
&extra_metadata,
agent_id.as_deref(),
) {
Ok(reg) => {
let status = if reg.created {
StatusCode::CREATED
} else {
StatusCode::OK
};
(
status,
Json(json!({
"entity_id": reg.entity_id,
"canonical_name": reg.canonical_name,
"namespace": reg.namespace,
"aliases": reg.aliases,
"created": reg.created,
})),
)
.into_response()
}
Err(e) => {
let msg = e.to_string();
if msg.contains("non-entity memory") {
return (StatusCode::CONFLICT, Json(json!({"error": msg}))).into_response();
}
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn entity_get_by_alias(
State(state): State<Db>,
Query(p): Query<EntityByAliasQuery>,
) -> impl IntoResponse {
let alias = p.alias.trim();
if alias.is_empty() {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "alias is required"})),
)
.into_response();
}
let namespace = p
.namespace
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
if let Some(ns) = namespace
&& let Err(e) = validate::validate_namespace(ns)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid namespace: {e}")})),
)
.into_response();
}
let lock = state.lock().await;
match db::entity_get_by_alias(&lock.0, alias, namespace) {
Ok(Some(rec)) => Json(json!({
"found": true,
"entity_id": rec.entity_id,
"canonical_name": rec.canonical_name,
"namespace": rec.namespace,
"aliases": rec.aliases,
}))
.into_response(),
Ok(None) => Json(json!({
"found": false,
"entity_id": null,
"canonical_name": null,
"namespace": null,
"aliases": [],
}))
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct KgTimelineQuery {
pub source_id: String,
pub since: Option<String>,
pub until: Option<String>,
pub limit: Option<usize>,
}
pub async fn kg_timeline(
State(state): State<Db>,
Query(p): Query<KgTimelineQuery>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_id(&p.source_id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid source_id: {e}")})),
)
.into_response();
}
let since = p.since.as_deref().map(str::trim).filter(|s| !s.is_empty());
let until = p.until.as_deref().map(str::trim).filter(|s| !s.is_empty());
if let Some(s) = since
&& let Err(e) = validate::validate_expires_at_format(s)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid since: {e}")})),
)
.into_response();
}
if let Some(u) = until
&& let Err(e) = validate::validate_expires_at_format(u)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid until: {e}")})),
)
.into_response();
}
let lock = state.lock().await;
match db::kg_timeline(&lock.0, &p.source_id, since, until, p.limit) {
Ok(events) => {
let events_json: Vec<serde_json::Value> = events
.iter()
.map(|e| {
json!({
"target_id": e.target_id,
"relation": e.relation,
"valid_from": e.valid_from,
"valid_until": e.valid_until,
"observed_by": e.observed_by,
"title": e.title,
"target_namespace": e.target_namespace,
})
})
.collect();
Json(json!({
"source_id": p.source_id,
"events": events_json,
"count": events.len(),
}))
.into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct KgInvalidateBody {
pub source_id: String,
pub target_id: String,
pub relation: String,
pub valid_until: Option<String>,
}
pub async fn kg_invalidate(
State(state): State<Db>,
Json(body): Json<KgInvalidateBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_link(&body.source_id, &body.target_id, &body.relation) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let valid_until = body
.valid_until
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
if let Some(ts) = valid_until
&& let Err(e) = validate::validate_expires_at_format(ts)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid valid_until: {e}")})),
)
.into_response();
}
let lock = state.lock().await;
match db::invalidate_link(
&lock.0,
&body.source_id,
&body.target_id,
&body.relation,
valid_until,
) {
Ok(Some(res)) => (
StatusCode::OK,
Json(json!({
"found": true,
"source_id": body.source_id,
"target_id": body.target_id,
"relation": body.relation,
"valid_until": res.valid_until,
"previous_valid_until": res.previous_valid_until,
})),
)
.into_response(),
Ok(None) => (
StatusCode::NOT_FOUND,
Json(json!({
"found": false,
"source_id": body.source_id,
"target_id": body.target_id,
"relation": body.relation,
})),
)
.into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct KgQueryBody {
pub source_id: String,
pub max_depth: Option<usize>,
pub valid_at: Option<String>,
pub allowed_agents: Option<Vec<String>>,
pub limit: Option<usize>,
}
pub async fn kg_query(State(state): State<Db>, Json(body): Json<KgQueryBody>) -> impl IntoResponse {
if let Err(e) = validate::validate_id(&body.source_id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid source_id: {e}")})),
)
.into_response();
}
let max_depth = body.max_depth.unwrap_or(1);
let valid_at = body
.valid_at
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty());
if let Some(t) = valid_at
&& let Err(e) = validate::validate_expires_at_format(t)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid valid_at: {e}")})),
)
.into_response();
}
let allowed_agents: Option<Vec<String>> = body.allowed_agents.as_ref().map(|v| {
v.iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
});
if let Some(agents) = allowed_agents.as_ref() {
for a in agents {
if let Err(e) = validate::validate_agent_id(a) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid allowed_agents entry: {e}")})),
)
.into_response();
}
}
}
let lock = state.lock().await;
match db::kg_query(
&lock.0,
&body.source_id,
max_depth,
valid_at,
allowed_agents.as_deref(),
body.limit,
) {
Ok(nodes) => {
let memories_json: Vec<serde_json::Value> = nodes
.iter()
.map(|n| {
json!({
"target_id": n.target_id,
"relation": n.relation,
"valid_from": n.valid_from,
"valid_until": n.valid_until,
"observed_by": n.observed_by,
"title": n.title,
"target_namespace": n.target_namespace,
"depth": n.depth,
"path": n.path,
})
})
.collect();
let paths_json: Vec<&str> = nodes.iter().map(|n| n.path.as_str()).collect();
Json(json!({
"source_id": body.source_id,
"max_depth": max_depth,
"memories": memories_json,
"paths": paths_json,
"count": nodes.len(),
}))
.into_response()
}
Err(e) => {
let msg = e.to_string();
if msg.contains("max_depth") {
return (
StatusCode::UNPROCESSABLE_ENTITY,
Json(json!({"error": msg})),
)
.into_response();
}
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn create_link(
State(app): State<AppState>,
Json(body): Json<LinkBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_link(&body.source_id, &body.target_id, &body.relation) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = app.db.lock().await;
let create_result = db::create_link(&lock.0, &body.source_id, &body.target_id, &body.relation);
drop(lock);
match create_result {
Ok(()) => {
if let Some(fed) = app.federation.as_ref() {
let link = crate::models::MemoryLink {
source_id: body.source_id.clone(),
target_id: body.target_id.clone(),
relation: body.relation.clone(),
created_at: chrono::Utc::now().to_rfc3339(),
};
match crate::federation::broadcast_link_quorum(fed, &link).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(e) => {
tracing::warn!("link fanout error (local committed): {e:?}");
}
}
}
(StatusCode::CREATED, Json(json!({"linked": true}))).into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn delete_link(
State(app): State<AppState>,
Json(body): Json<LinkBody>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_link(&body.source_id, &body.target_id, &body.relation) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = app.db.lock().await;
let delete_result = db::delete_link(&lock.0, &body.source_id, &body.target_id);
drop(lock);
match delete_result {
Ok(removed) => Json(json!({"deleted": removed})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn get_links(State(state): State<Db>, Path(id): Path<String>) -> impl IntoResponse {
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let lock = state.lock().await;
match db::get_links(&lock.0, &id) {
Ok(links) => Json(json!({"links": links})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn get_stats(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match db::stats(&lock.0, &lock.1) {
Ok(s) => Json(json!(s)).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn run_gc(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match db::gc(&lock.0, lock.3) {
Ok(n) => Json(json!({"expired_deleted": n})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn export_memories(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match (db::export_all(&lock.0), db::export_links(&lock.0)) {
(Ok(memories), Ok(links)) => {
let count = memories.len();
Json(json!({"memories": memories, "links": links, "count": count, "exported_at": Utc::now().to_rfc3339()})).into_response()
}
(Err(e), _) | (_, Err(e)) => {
tracing::error!("export error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn import_memories(
State(state): State<Db>,
Json(body): Json<ImportBody>,
) -> impl IntoResponse {
if body.memories.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("import limited to {} memories", MAX_BULK_SIZE)})),
)
.into_response();
}
let lock = state.lock().await;
let mut imported = 0usize;
let mut errors = Vec::new();
for mem in body.memories {
if let Err(e) = validate::validate_memory(&mem) {
errors.push(format!("{}: {}", mem.id, e));
continue;
}
match db::insert(&lock.0, &mem) {
Ok(_) => imported += 1,
Err(e) => errors.push(format!("{}: {}", mem.id, e)),
}
}
for link in body.links.unwrap_or_default() {
if validate::validate_link(&link.source_id, &link.target_id, &link.relation).is_err() {
continue;
}
let _ = db::create_link(&lock.0, &link.source_id, &link.target_id, &link.relation);
}
Json(json!({"imported": imported, "errors": errors})).into_response()
}
#[derive(serde::Deserialize)]
pub struct ImportBody {
pub memories: Vec<Memory>,
#[serde(default)]
pub links: Option<Vec<MemoryLink>>,
}
#[derive(serde::Deserialize)]
pub struct ConsolidateBody {
pub ids: Vec<String>,
pub title: String,
pub summary: String,
#[serde(default = "default_ns")]
pub namespace: String,
#[serde(default)]
pub tier: Option<Tier>,
#[serde(default)]
pub agent_id: Option<String>,
}
fn default_ns() -> String {
"global".to_string()
}
pub async fn consolidate_memories(
State(app): State<AppState>,
headers: HeaderMap,
Json(body): Json<ConsolidateBody>,
) -> impl IntoResponse {
if let Err(e) =
validate::validate_consolidate(&body.ids, &body.title, &body.summary, &body.namespace)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let consolidator_agent_id =
match crate::identity::resolve_http_agent_id(body.agent_id.as_deref(), header_agent_id) {
Ok(id) => id,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
};
let lock = app.db.lock().await;
let tier = body.tier.unwrap_or(Tier::Long);
let source_ids = body.ids.clone();
let consolidate_result = db::consolidate(
&lock.0,
&body.ids,
&body.title,
&body.summary,
&body.namespace,
&tier,
"consolidation",
&consolidator_agent_id,
);
let new_mem = match &consolidate_result {
Ok(new_id) => db::get(&lock.0, new_id).ok().flatten(),
Err(_) => None,
};
drop(lock);
match consolidate_result {
Ok(new_id) => {
if let (Some(fed), Some(mem)) = (app.federation.as_ref(), new_mem) {
match crate::federation::broadcast_consolidate_quorum(fed, &mem, &source_ids).await
{
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(e) => {
tracing::warn!("consolidate fanout error (local committed): {e:?}");
}
}
}
(
StatusCode::CREATED,
Json(json!({"id": new_id, "consolidated": body.ids.len()})),
)
.into_response()
}
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn bulk_create(
State(app): State<AppState>,
Json(bodies): Json<Vec<CreateMemory>>,
) -> impl IntoResponse {
if bodies.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("bulk operations limited to {} items", MAX_BULK_SIZE)})),
)
.into_response();
}
let now = Utc::now();
let mut created_mems: Vec<Memory> = Vec::new();
let mut errors: Vec<String> = Vec::new();
{
let lock = app.db.lock().await;
for body in bodies {
if let Err(e) = validate::validate_create(&body) {
errors.push(format!("{}: {}", body.title, e));
continue;
}
let expires_at = body.expires_at.or_else(|| {
body.ttl_secs
.or(lock.2.ttl_for_tier(&body.tier))
.map(|s| (now + Duration::seconds(s)).to_rfc3339())
});
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: body.tier,
namespace: body.namespace,
title: body.title,
content: body.content,
tags: body.tags,
priority: body.priority.clamp(1, 10),
confidence: body.confidence.clamp(0.0, 1.0),
source: body.source,
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at,
metadata: body.metadata,
};
match db::insert(&lock.0, &mem) {
Ok(_) => created_mems.push(mem),
Err(e) => errors.push(e.to_string()),
}
}
}
if let Some(fed) = app.federation.as_ref() {
let sem = Arc::new(tokio::sync::Semaphore::new(BULK_FANOUT_CONCURRENCY));
let mut joins: tokio::task::JoinSet<(String, Result<(), String>)> =
tokio::task::JoinSet::new();
for mem in &created_mems {
let fed = fed.clone();
let mem = mem.clone();
let sem = sem.clone();
joins.spawn(async move {
let Ok(_permit) = sem.acquire_owned().await else {
return (mem.id.clone(), Err("fanout semaphore closed".to_string()));
};
let id = mem.id.clone();
let outcome = match crate::federation::broadcast_store_quorum(&fed, &mem).await {
Ok(tracker) => match crate::federation::finalise_quorum(&tracker) {
Ok(_) => Ok(()),
Err(err) => Err(err.to_string()),
},
Err(e) => {
tracing::warn!(
"bulk_create: fanout for {id} failed (local committed): {e:?}"
);
Ok(())
}
};
(id, outcome)
});
}
while let Some(res) = joins.join_next().await {
match res {
Ok((id, Err(err))) => errors.push(format!("{id}: {err}")),
Ok((_, Ok(()))) => {}
Err(e) => tracing::warn!("bulk_create: fanout task join error: {e:?}"),
}
}
if !created_mems.is_empty() {
let catchup_errors = crate::federation::bulk_catchup_push(fed, &created_mems).await;
for (peer_id, err) in catchup_errors {
errors.push(format!("catchup to {peer_id}: {err}"));
}
}
}
Json(json!({"created": created_mems.len(), "errors": errors})).into_response()
}
#[derive(Debug, Deserialize)]
pub struct ArchiveListQuery {
pub namespace: Option<String>,
#[serde(default = "default_archive_limit")]
pub limit: Option<usize>,
#[serde(default)]
pub offset: Option<usize>,
}
#[allow(clippy::unnecessary_wraps)]
fn default_archive_limit() -> Option<usize> {
Some(50)
}
pub async fn list_archive(
State(state): State<Db>,
Query(q): Query<ArchiveListQuery>,
) -> impl IntoResponse {
if matches!(q.limit, Some(0)) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "limit must be >= 1"})),
)
.into_response();
}
let lock = state.lock().await;
let limit = q.limit.unwrap_or(50).clamp(1, 1000);
let offset = q.offset.unwrap_or(0);
match db::list_archived(&lock.0, q.namespace.as_deref(), limit, offset) {
Ok(items) => Json(json!({"archived": items, "count": items.len()})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn restore_archive(
State(app): State<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
if let Err(e) = validate::validate_id(&id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": e.to_string()})),
)
.into_response();
}
let restored = {
let lock = app.db.lock().await;
match db::restore_archived(&lock.0, &id) {
Ok(v) => v,
Err(e) => {
tracing::error!("handler error: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
}
};
if !restored {
return (
StatusCode::NOT_FOUND,
Json(json!({"error": "not found in archive"})),
)
.into_response();
}
if let Some(fed) = app.federation.as_ref() {
match crate::federation::broadcast_restore_quorum(fed, &id).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(e) => {
tracing::warn!("restore fanout error (local committed): {e:?}");
}
}
}
Json(json!({"restored": true, "id": id})).into_response()
}
#[derive(Debug, Deserialize)]
pub struct PurgeQuery {
pub older_than_days: Option<i64>,
}
pub async fn purge_archive(
State(state): State<Db>,
Query(q): Query<PurgeQuery>,
) -> impl IntoResponse {
let lock = state.lock().await;
match db::purge_archive(&lock.0, q.older_than_days) {
Ok(n) => Json(json!({"purged": n})).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
pub async fn archive_stats(State(state): State<Db>) -> impl IntoResponse {
let lock = state.lock().await;
match db::archive_stats(&lock.0) {
Ok(archive_stats) => Json(archive_stats).into_response(),
Err(e) => {
tracing::error!("handler error: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Debug, Deserialize)]
pub struct ArchiveByIdsBody {
pub ids: Vec<String>,
#[serde(default)]
pub reason: Option<String>,
}
pub async fn archive_by_ids(
State(app): State<AppState>,
Json(body): Json<ArchiveByIdsBody>,
) -> impl IntoResponse {
if body.ids.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("archive limited to {} ids per request", MAX_BULK_SIZE)})),
)
.into_response();
}
for id in &body.ids {
if let Err(e) = validate::validate_id(id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid id {id}: {e}")})),
)
.into_response();
}
}
let reason = body.reason.as_deref().unwrap_or("archive").to_string();
let mut archived: Vec<String> = Vec::new();
let mut missing: Vec<String> = Vec::new();
for id in &body.ids {
let moved = {
let lock = app.db.lock().await;
match db::archive_memory(&lock.0, id, Some(&reason)) {
Ok(v) => v,
Err(e) => {
tracing::error!("archive_by_ids: archive_memory({id}) failed: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
}
};
if !moved {
missing.push(id.clone());
continue;
}
if let Some(fed) = app.federation.as_ref() {
match crate::federation::broadcast_archive_quorum(fed, id).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(e) => {
tracing::warn!("archive fanout error (local committed): {e:?}");
}
}
}
archived.push(id.clone());
}
(
StatusCode::OK,
Json(json!({
"archived": archived,
"missing": missing,
"count": archived.len(),
"reason": reason,
})),
)
.into_response()
}
#[derive(Deserialize)]
pub struct SyncPushBody {
pub sender_agent_id: String,
#[serde(default)]
#[allow(dead_code)] pub sender_clock: crate::models::VectorClock,
pub memories: Vec<Memory>,
#[serde(default)]
pub deletions: Vec<String>,
#[serde(default)]
pub archives: Vec<String>,
#[serde(default)]
pub restores: Vec<String>,
#[serde(default)]
pub links: Vec<MemoryLink>,
#[serde(default)]
pub pendings: Vec<crate::models::PendingAction>,
#[serde(default)]
pub pending_decisions: Vec<crate::models::PendingDecision>,
#[serde(default)]
pub namespace_meta: Vec<crate::models::NamespaceMetaEntry>,
#[serde(default)]
pub namespace_meta_clears: Vec<String>,
#[serde(default)]
pub dry_run: bool,
}
#[derive(Deserialize)]
pub struct SyncSinceQuery {
pub since: Option<String>,
pub limit: Option<usize>,
pub peer: Option<String>,
}
#[allow(clippy::too_many_lines)]
pub async fn sync_push(
State(app): State<AppState>,
headers: HeaderMap,
Json(body): Json<SyncPushBody>,
) -> impl IntoResponse {
let state = app.db.clone();
if let Err(e) = validate::validate_agent_id(&body.sender_agent_id) {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid sender_agent_id: {e}")})),
)
.into_response();
}
if body.memories.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("sync_push limited to {} memories per request", MAX_BULK_SIZE)
})),
)
.into_response();
}
if body.deletions.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("sync_push limited to {} deletions per request", MAX_BULK_SIZE)
})),
)
.into_response();
}
if body.archives.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("sync_push limited to {} archives per request", MAX_BULK_SIZE)
})),
)
.into_response();
}
if body.restores.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("sync_push limited to {} restores per request", MAX_BULK_SIZE)
})),
)
.into_response();
}
if body.pendings.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!("sync_push limited to {} pendings per request", MAX_BULK_SIZE)
})),
)
.into_response();
}
if body.pending_decisions.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!(
"sync_push limited to {} pending_decisions per request",
MAX_BULK_SIZE
)
})),
)
.into_response();
}
if body.namespace_meta.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!(
"sync_push limited to {} namespace_meta per request",
MAX_BULK_SIZE
)
})),
)
.into_response();
}
if body.namespace_meta_clears.len() > MAX_BULK_SIZE {
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": format!(
"sync_push limited to {} namespace_meta_clears per request",
MAX_BULK_SIZE
)
})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let local_agent_id = match crate::identity::resolve_http_agent_id(None, header_agent_id) {
Ok(id) => id,
Err(e) => {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid x-agent-id: {e}")})),
)
.into_response();
}
};
let lock = state.lock().await;
let mut applied = 0usize;
let mut noop = 0usize;
let mut skipped = 0usize;
let mut deleted = 0usize;
let mut archived = 0usize;
let mut restored = 0usize;
let mut latest_seen: Option<String> = None;
let mut embedding_refresh: Vec<(String, String)> = Vec::new();
for mem in &body.memories {
if let Err(e) = validate::validate_memory(mem) {
tracing::warn!("sync_push: skipping memory {} ({}): {e}", mem.id, mem.title);
skipped += 1;
continue;
}
if latest_seen
.as_deref()
.is_none_or(|current| mem.updated_at.as_str() > current)
{
latest_seen = Some(mem.updated_at.clone());
}
if body.dry_run {
noop += 1;
continue;
}
match db::insert_if_newer(&lock.0, mem) {
Ok(actual_id) => {
applied += 1;
embedding_refresh.push((actual_id, format!("{} {}", mem.title, mem.content)));
}
Err(e) => {
tracing::warn!("sync_push: insert_if_newer failed for {}: {e}", mem.id);
skipped += 1;
}
}
}
for del_id in &body.deletions {
if validate::validate_id(del_id).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::delete(&lock.0, del_id) {
Ok(true) => deleted += 1,
Ok(false) => noop += 1,
Err(e) => {
tracing::warn!("sync_push: delete failed for {del_id}: {e}");
skipped += 1;
}
}
}
for arch_id in &body.archives {
if validate::validate_id(arch_id).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::archive_memory(&lock.0, arch_id, Some("sync_push")) {
Ok(true) => archived += 1,
Ok(false) => noop += 1,
Err(e) => {
tracing::warn!("sync_push: archive_memory failed for {arch_id}: {e}");
skipped += 1;
}
}
}
for res_id in &body.restores {
if validate::validate_id(res_id).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::restore_archived(&lock.0, res_id) {
Ok(true) => restored += 1,
Ok(false) => noop += 1,
Err(e) => {
tracing::warn!("sync_push: restore_archived failed for {res_id}: {e}");
skipped += 1;
}
}
}
let mut links_applied = 0usize;
for link in &body.links {
if validate::validate_link(&link.source_id, &link.target_id, &link.relation).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::create_link(&lock.0, &link.source_id, &link.target_id, &link.relation) {
Ok(()) => links_applied += 1,
Err(e) => {
tracing::warn!(
"sync_push: create_link failed ({} -> {} / {}): {e}",
link.source_id,
link.target_id,
link.relation
);
skipped += 1;
}
}
}
let mut pendings_applied = 0usize;
for pa in &body.pendings {
if validate::validate_id(&pa.id).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::upsert_pending_action(&lock.0, pa) {
Ok(()) => pendings_applied += 1,
Err(e) => {
tracing::warn!("sync_push: upsert_pending_action failed for {}: {e}", pa.id);
skipped += 1;
}
}
}
let mut pending_decisions_applied = 0usize;
for dec in &body.pending_decisions {
if validate::validate_id(&dec.id).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::decide_pending_action(&lock.0, &dec.id, dec.approved, &dec.decider) {
Ok(true) => {
pending_decisions_applied += 1;
if dec.approved {
match db::execute_pending_action(&lock.0, &dec.id) {
Ok(_) => {}
Err(e) => {
tracing::warn!(
"sync_push: execute_pending_action failed for {}: {e}",
dec.id
);
}
}
}
}
Ok(false) => noop += 1, Err(e) => {
tracing::warn!(
"sync_push: decide_pending_action failed for {}: {e}",
dec.id
);
skipped += 1;
}
}
}
let mut namespace_meta_applied = 0usize;
for entry in &body.namespace_meta {
if validate::validate_namespace(&entry.namespace).is_err()
|| validate::validate_id(&entry.standard_id).is_err()
{
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::set_namespace_standard(
&lock.0,
&entry.namespace,
&entry.standard_id,
entry.parent_namespace.as_deref(),
) {
Ok(()) => namespace_meta_applied += 1,
Err(e) => {
tracing::warn!(
"sync_push: set_namespace_standard failed for {}: {e}",
entry.namespace
);
skipped += 1;
}
}
}
let mut namespace_meta_cleared = 0usize;
for ns in &body.namespace_meta_clears {
if validate::validate_namespace(ns).is_err() {
skipped += 1;
continue;
}
if body.dry_run {
noop += 1;
continue;
}
match db::clear_namespace_standard(&lock.0, ns) {
Ok(true) => namespace_meta_cleared += 1,
Ok(false) => noop += 1,
Err(e) => {
tracing::warn!("sync_push: clear_namespace_standard failed for {ns}: {e}");
skipped += 1;
}
}
}
if !body.dry_run
&& let Some(at) = latest_seen.as_deref()
&& let Err(e) = db::sync_state_observe(&lock.0, &local_agent_id, &body.sender_agent_id, at)
{
tracing::warn!("sync_push: sync_state_observe failed: {e}");
}
let mut hnsw_updates: Vec<(String, Vec<f32>)> = Vec::new();
if !body.dry_run
&& !embedding_refresh.is_empty()
&& let Some(emb) = app.embedder.as_ref().as_ref()
{
for (id, text) in &embedding_refresh {
match emb.embed(text) {
Ok(vec) => {
if let Err(e) = db::set_embedding(&lock.0, id, &vec) {
tracing::warn!("sync_push: set_embedding failed for {id}: {e}");
continue;
}
hnsw_updates.push((id.clone(), vec));
}
Err(e) => {
tracing::warn!("sync_push: embed failed for {id}: {e}");
}
}
}
}
let receiver_clock = db::sync_state_load(&lock.0, &local_agent_id)
.unwrap_or_else(|_| crate::models::VectorClock::default());
drop(lock);
if !hnsw_updates.is_empty() {
let mut idx_lock = app.vector_index.lock().await;
if let Some(idx) = idx_lock.as_mut() {
for (id, vec) in hnsw_updates {
idx.remove(&id);
idx.insert(id, vec);
}
}
}
(
StatusCode::OK,
Json(json!({
"applied": applied,
"deleted": deleted,
"archived": archived,
"restored": restored,
"links_applied": links_applied,
"pendings_applied": pendings_applied,
"pending_decisions_applied": pending_decisions_applied,
"namespace_meta_applied": namespace_meta_applied,
"namespace_meta_cleared": namespace_meta_cleared,
"noop": noop,
"skipped": skipped,
"dry_run": body.dry_run,
"receiver_agent_id": local_agent_id,
"receiver_clock": receiver_clock,
})),
)
.into_response()
}
pub async fn sync_since(
State(state): State<Db>,
headers: HeaderMap,
Query(q): Query<SyncSinceQuery>,
) -> impl IntoResponse {
if let Some(ref s) = q.since
&& !s.is_empty()
&& chrono::DateTime::parse_from_rfc3339(s).is_err()
{
return (
StatusCode::BAD_REQUEST,
Json(json!({
"error": "invalid `since` parameter — expected RFC 3339 timestamp"
})),
)
.into_response();
}
let limit = q.limit.unwrap_or(500).min(10_000);
let lock = state.lock().await;
let mems = match db::memories_updated_since(&lock.0, q.since.as_deref(), limit) {
Ok(v) => v,
Err(e) => {
tracing::error!("sync_since: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
if let (Some(peer), Ok(local_agent_id)) = (
q.peer.as_deref(),
crate::identity::resolve_http_agent_id(None, header_agent_id),
) && validate::validate_agent_id(peer).is_ok()
&& let Some(last) = mems.last()
&& let Err(e) = db::sync_state_observe(&lock.0, &local_agent_id, peer, &last.updated_at)
{
tracing::debug!("sync_since: sync_state_observe failed: {e}");
}
let earliest_updated_at = mems.first().map(|m| m.updated_at.clone());
let latest_updated_at = mems.last().map(|m| m.updated_at.clone());
(
StatusCode::OK,
Json(json!({
"count": mems.len(),
"limit": limit,
"updated_since": q.since,
"earliest_updated_at": earliest_updated_at,
"latest_updated_at": latest_updated_at,
"memories": mems,
})),
)
.into_response()
}
async fn fanout_or_503(app: &AppState, mem: &Memory) -> Option<axum::response::Response> {
let fed = app.federation.as_ref().as_ref()?;
match crate::federation::broadcast_store_quorum(fed, mem).await {
Ok(tracker) => match crate::federation::finalise_quorum(&tracker) {
Ok(_) => None,
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
Some(
(
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response(),
)
}
},
Err(e) => {
tracing::warn!("fanout error (local committed): {e:?}");
None
}
}
}
fn resolve_caller_agent_id(
body: Option<&str>,
headers: &HeaderMap,
query: Option<&str>,
) -> Result<String, String> {
if let Some(id) = body
&& !id.is_empty()
{
validate::validate_agent_id(id).map_err(|e| format!("invalid agent_id: {e}"))?;
return Ok(id.to_string());
}
if let Some(id) = query
&& !id.is_empty()
{
validate::validate_agent_id(id).map_err(|e| format!("invalid agent_id: {e}"))?;
return Ok(id.to_string());
}
let header_val = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
crate::identity::resolve_http_agent_id(None, header_val)
.map_err(|e| format!("invalid agent_id: {e}"))
}
pub async fn get_capabilities(State(app): State<AppState>) -> impl IntoResponse {
let embedder_loaded = app.embedder.as_ref().is_some();
let lock = app.db.lock().await;
let conn = &lock.0;
let result = crate::mcp::handle_capabilities_with_conn(
app.tier_config.as_ref(),
None,
embedder_loaded,
Some(conn),
);
drop(lock);
match result {
Ok(v) => (StatusCode::OK, Json(v)).into_response(),
Err(e) => {
tracing::error!("capabilities: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Deserialize)]
pub struct NotifyBody {
pub target_agent_id: String,
pub title: String,
#[serde(default)]
pub payload: Option<String>,
#[serde(default)]
pub content: Option<String>,
#[serde(default)]
pub priority: Option<i64>,
#[serde(default)]
pub tier: Option<String>,
#[serde(default)]
pub agent_id: Option<String>,
}
pub async fn notify(
State(app): State<AppState>,
headers: HeaderMap,
Json(body): Json<NotifyBody>,
) -> impl IntoResponse {
let Some(payload) = body.payload.or(body.content) else {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "payload or content is required"})),
)
.into_response();
};
let sender = match resolve_caller_agent_id(body.agent_id.as_deref(), &headers, None) {
Ok(id) => id,
Err(e) => {
return (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response();
}
};
let mut params = json!({
"target_agent_id": body.target_agent_id,
"title": body.title,
"payload": payload,
});
if let Some(p) = body.priority {
params["priority"] = json!(p);
}
if let Some(t) = body.tier {
params["tier"] = json!(t);
}
let lock = app.db.lock().await;
let resolved_ttl = lock.2.clone();
let mcp_client = sender.clone();
let result = crate::mcp::handle_notify(&lock.0, ¶ms, &resolved_ttl, Some(&mcp_client));
let fanout_mem = match &result {
Ok(v) => v
.get("id")
.and_then(|x| x.as_str())
.and_then(|id| db::get(&lock.0, id).ok().flatten()),
Err(_) => None,
};
drop(lock);
match result {
Ok(v) => {
if let Some(mem) = fanout_mem
&& let Some(resp) = fanout_or_503(&app, &mem).await
{
return resp;
}
(StatusCode::CREATED, Json(v)).into_response()
}
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
#[derive(Deserialize)]
pub struct InboxQuery {
#[serde(default)]
pub agent_id: Option<String>,
#[serde(default)]
pub unread_only: Option<bool>,
#[serde(default)]
pub limit: Option<u64>,
}
pub async fn get_inbox(
State(app): State<AppState>,
headers: HeaderMap,
Query(q): Query<InboxQuery>,
) -> impl IntoResponse {
let owner = match resolve_caller_agent_id(None, &headers, q.agent_id.as_deref()) {
Ok(id) => id,
Err(e) => {
return (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response();
}
};
let mut params = json!({"agent_id": owner});
if let Some(u) = q.unread_only {
params["unread_only"] = json!(u);
}
if let Some(l) = q.limit {
params["limit"] = json!(l);
}
let lock = app.db.lock().await;
let result = crate::mcp::handle_inbox(&lock.0, ¶ms, None);
drop(lock);
match result {
Ok(v) => (StatusCode::OK, Json(v)).into_response(),
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
#[derive(Deserialize)]
pub struct SubscribeBody {
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub events: Option<String>,
#[serde(default)]
pub secret: Option<String>,
#[serde(default)]
pub namespace_filter: Option<String>,
#[serde(default)]
pub agent_filter: Option<String>,
#[serde(default)]
pub namespace: Option<String>,
#[serde(default)]
pub agent_id: Option<String>,
}
pub async fn subscribe(
State(app): State<AppState>,
headers: HeaderMap,
Json(body): Json<SubscribeBody>,
) -> impl IntoResponse {
let caller = match resolve_caller_agent_id(body.agent_id.as_deref(), &headers, None) {
Ok(id) => id,
Err(e) => {
return (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response();
}
};
let (url, namespace_filter, agent_filter) = if let Some(u) = body.url {
(u, body.namespace_filter, body.agent_filter)
} else {
let Some(ns) = body.namespace.clone() else {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "url or namespace is required"})),
)
.into_response();
};
let synthetic = format!("http://localhost/_ns/{caller}/{ns}");
(
synthetic,
Some(ns),
body.agent_filter.or_else(|| Some(caller.clone())),
)
};
let events = body.events.unwrap_or_else(|| "*".to_string());
let lock = app.db.lock().await;
let already = db::list_agents(&lock.0)
.ok()
.is_some_and(|a| a.iter().any(|x| x.agent_id == caller));
if !already {
let _ = db::register_agent(&lock.0, &caller, "ai:generic", &[]);
}
let sub_result: Result<serde_json::Value, String> = (|| {
crate::subscriptions::validate_url(&url).map_err(|e| e.to_string())?;
let id = crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: &url,
events: &events,
secret: body.secret.as_deref(),
namespace_filter: namespace_filter.as_deref(),
agent_filter: agent_filter.as_deref(),
created_by: Some(&caller),
},
)
.map_err(|e| e.to_string())?;
Ok(json!({
"id": id,
"url": url,
"events": events,
"namespace_filter": namespace_filter,
"agent_filter": agent_filter,
"created_by": caller,
}))
})();
let registered_mem = if already {
None
} else {
db::list(
&lock.0,
Some("_agents"),
None,
1000,
0,
None,
None,
None,
None,
None,
)
.ok()
.and_then(|rows| {
rows.into_iter()
.find(|m| m.title == format!("agent:{caller}"))
})
};
drop(lock);
if let Some(ref mem) = registered_mem
&& let Some(resp) = fanout_or_503(&app, mem).await
{
return resp;
}
match sub_result {
Ok(mut v) => {
if let Some(obj) = v.as_object_mut() {
if let Some(ref ns) = namespace_filter {
obj.insert("namespace".into(), json!(ns));
}
obj.insert("agent_id".into(), json!(caller));
}
(StatusCode::CREATED, Json(v)).into_response()
}
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
#[derive(Deserialize)]
pub struct UnsubscribeQuery {
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub agent_id: Option<String>,
#[serde(default)]
pub namespace: Option<String>,
}
pub async fn unsubscribe(
State(app): State<AppState>,
headers: HeaderMap,
Query(q): Query<UnsubscribeQuery>,
) -> impl IntoResponse {
if let Some(id) = q.id.clone() {
let mut params = json!({"id": id});
let _ = params.as_object_mut();
let lock = app.db.lock().await;
let result = crate::mcp::handle_unsubscribe(&lock.0, ¶ms);
drop(lock);
return match result {
Ok(v) => (StatusCode::OK, Json(v)).into_response(),
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
};
}
let caller = match resolve_caller_agent_id(None, &headers, q.agent_id.as_deref()) {
Ok(id) => id,
Err(e) => {
return (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response();
}
};
let Some(ns) = q.namespace else {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "id or (agent_id, namespace) required"})),
)
.into_response();
};
let lock = app.db.lock().await;
let subs = crate::subscriptions::list(&lock.0).unwrap_or_default();
let target = subs.into_iter().find(|s| {
s.namespace_filter.as_deref() == Some(ns.as_str())
&& (s.agent_filter.as_deref() == Some(caller.as_str())
|| s.created_by.as_deref() == Some(caller.as_str()))
});
let outcome = match target {
Some(s) => crate::subscriptions::delete(&lock.0, &s.id).map(|r| (s.id, r)),
None => Ok((String::new(), false)),
};
drop(lock);
match outcome {
Ok((id, removed)) => {
(StatusCode::OK, Json(json!({"id": id, "removed": removed}))).into_response()
}
Err(e) => {
tracing::error!("unsubscribe: {e}");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response()
}
}
}
#[derive(Deserialize)]
pub struct ListSubscriptionsQuery {
#[serde(default)]
pub agent_id: Option<String>,
}
pub async fn list_subscriptions(
State(state): State<Db>,
Query(q): Query<ListSubscriptionsQuery>,
) -> impl IntoResponse {
let lock = state.lock().await;
let subs = match crate::subscriptions::list(&lock.0) {
Ok(s) => s,
Err(e) => {
tracing::error!("list_subscriptions: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
};
drop(lock);
let filtered: Vec<_> = match q.agent_id.as_deref() {
Some(aid) => subs
.into_iter()
.filter(|s| {
s.agent_filter.as_deref() == Some(aid) || s.created_by.as_deref() == Some(aid)
})
.collect(),
None => subs,
};
let rows: Vec<serde_json::Value> = filtered
.iter()
.map(|s| {
json!({
"id": s.id,
"url": s.url,
"events": s.events,
"namespace": s.namespace_filter,
"namespace_filter": s.namespace_filter,
"agent_filter": s.agent_filter,
"agent_id": s.agent_filter.clone().or(s.created_by.clone()),
"created_by": s.created_by,
"created_at": s.created_at,
"dispatch_count": s.dispatch_count,
"failure_count": s.failure_count,
})
})
.collect();
let count = rows.len();
(
StatusCode::OK,
Json(json!({"count": count, "subscriptions": rows})),
)
.into_response()
}
#[derive(Deserialize)]
pub struct NamespaceStandardBody {
#[serde(default)]
pub id: Option<String>,
#[serde(default)]
pub parent: Option<String>,
#[serde(default)]
pub governance: Option<serde_json::Value>,
#[serde(default)]
pub namespace: Option<String>,
#[serde(default)]
pub standard: Option<Box<NamespaceStandardBody>>,
}
fn flatten_standard_body(body: NamespaceStandardBody) -> NamespaceStandardBody {
if let Some(inner) = body.standard {
let mut merged = *inner;
if merged.namespace.is_none() {
merged.namespace = body.namespace;
}
if merged.id.is_none() {
merged.id = body.id;
}
if merged.parent.is_none() {
merged.parent = body.parent;
}
if merged.governance.is_none() {
merged.governance = body.governance;
}
merged
} else {
body
}
}
fn namespace_standard_params(ns: &str, body: &NamespaceStandardBody) -> serde_json::Value {
let mut params = json!({"namespace": ns});
if let Some(ref id) = body.id {
params["id"] = json!(id);
}
if let Some(ref p) = body.parent {
params["parent"] = json!(p);
}
if let Some(ref g) = body.governance {
params["governance"] = g.clone();
}
params
}
async fn set_namespace_standard_inner(
app: &AppState,
ns: &str,
body: NamespaceStandardBody,
) -> axum::response::Response {
let body = flatten_standard_body(body);
let lock = app.db.lock().await;
let resolved_id = if let Some(id) = body.id.clone() {
id
} else {
let existing = db::list(
&lock.0,
Some(ns),
None,
1,
0,
None,
None,
None,
Some("_namespace_standard"),
None,
)
.ok()
.and_then(|v| v.into_iter().next());
if let Some(m) = existing {
m.id
} else {
let now = Utc::now().to_rfc3339();
let placeholder = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: ns.to_string(),
title: format!("_standard:{ns}"),
content: format!("namespace standard for {ns}"),
tags: vec!["_namespace_standard".to_string()],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "system"}),
};
match db::insert(&lock.0, &placeholder) {
Ok(id) => id,
Err(e) => {
tracing::error!("namespace_standard: placeholder insert failed: {e}");
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "internal server error"})),
)
.into_response();
}
}
}
};
let mut effective = body;
effective.id = Some(resolved_id.clone());
let params = namespace_standard_params(ns, &effective);
let result = crate::mcp::handle_namespace_set_standard(&lock.0, ¶ms);
let standard_mem = db::get(&lock.0, &resolved_id).ok().flatten();
let meta_entry = db::get_namespace_meta_entry(&lock.0, ns).ok().flatten();
drop(lock);
match result {
Ok(v) => {
if let Some(ref mem) = standard_mem
&& let Some(resp) = fanout_or_503(app, mem).await
{
return resp;
}
if let (Some(entry), Some(fed)) = (meta_entry.as_ref(), app.federation.as_ref()) {
match crate::federation::broadcast_namespace_meta_quorum(fed, entry).await {
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
(StatusCode::CREATED, Json(v)).into_response()
}
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
pub async fn set_namespace_standard(
State(app): State<AppState>,
Path(ns): Path<String>,
Json(body): Json<NamespaceStandardBody>,
) -> impl IntoResponse {
set_namespace_standard_inner(&app, &ns, body).await
}
#[derive(Deserialize)]
pub struct NamespaceStandardQuery {
#[serde(default)]
pub namespace: Option<String>,
#[serde(default)]
pub inherit: Option<bool>,
}
pub async fn get_namespace_standard(
State(state): State<Db>,
Path(ns): Path<String>,
Query(q): Query<NamespaceStandardQuery>,
) -> impl IntoResponse {
let mut params = json!({"namespace": ns});
if let Some(inh) = q.inherit {
params["inherit"] = json!(inh);
}
let lock = state.lock().await;
let result = crate::mcp::handle_namespace_get_standard(&lock.0, ¶ms);
drop(lock);
match result {
Ok(v) => (StatusCode::OK, Json(v)).into_response(),
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
pub async fn clear_namespace_standard(
State(app): State<AppState>,
Path(ns): Path<String>,
) -> impl IntoResponse {
clear_namespace_standard_inner(&app, &ns).await
}
pub async fn set_namespace_standard_qs(
State(app): State<AppState>,
Json(body): Json<NamespaceStandardBody>,
) -> impl IntoResponse {
let Some(ns) = body
.namespace
.clone()
.or_else(|| body.standard.as_ref().and_then(|s| s.namespace.clone()))
else {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "namespace is required"})),
)
.into_response();
};
set_namespace_standard_inner(&app, &ns, body).await
}
pub async fn get_namespace_standard_qs(
State(state): State<Db>,
Query(q): Query<NamespaceStandardQuery>,
) -> impl IntoResponse {
let Some(ns) = q.namespace.clone() else {
return list_namespaces(State(state)).await.into_response();
};
let mut params = json!({"namespace": ns});
if let Some(inh) = q.inherit {
params["inherit"] = json!(inh);
}
let lock = state.lock().await;
let result = crate::mcp::handle_namespace_get_standard(&lock.0, ¶ms);
drop(lock);
match result {
Ok(v) => (StatusCode::OK, Json(v)).into_response(),
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
pub async fn clear_namespace_standard_qs(
State(app): State<AppState>,
Query(q): Query<NamespaceStandardQuery>,
) -> impl IntoResponse {
let Some(ns) = q.namespace else {
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": "namespace is required"})),
)
.into_response();
};
clear_namespace_standard_inner(&app, &ns).await
}
async fn clear_namespace_standard_inner(app: &AppState, ns: &str) -> axum::response::Response {
let params = json!({"namespace": ns});
let lock = app.db.lock().await;
let result = crate::mcp::handle_namespace_clear_standard(&lock.0, ¶ms);
drop(lock);
match result {
Ok(v) => {
if let Some(fed) = app.federation.as_ref() {
let namespaces = vec![ns.to_string()];
match crate::federation::broadcast_namespace_meta_clear_quorum(fed, &namespaces)
.await
{
Ok(tracker) => {
if let Err(err) = crate::federation::finalise_quorum(&tracker) {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
Err(err) => {
let payload = crate::federation::QuorumNotMetPayload::from_err(&err);
return (
StatusCode::SERVICE_UNAVAILABLE,
[("Retry-After", "2")],
Json(serde_json::to_value(&payload).unwrap_or_default()),
)
.into_response();
}
}
}
(StatusCode::OK, Json(v)).into_response()
}
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
#[derive(Deserialize)]
pub struct SessionStartBody {
#[serde(default)]
pub namespace: Option<String>,
#[serde(default)]
pub limit: Option<u64>,
#[serde(default)]
pub agent_id: Option<String>,
}
pub async fn session_start(
State(state): State<Db>,
headers: HeaderMap,
Json(body): Json<SessionStartBody>,
) -> impl IntoResponse {
if let Some(ref id) = body.agent_id
&& let Err(e) = validate::validate_agent_id(id)
{
return (
StatusCode::BAD_REQUEST,
Json(json!({"error": format!("invalid agent_id: {e}")})),
)
.into_response();
}
let header_agent_id = headers.get("x-agent-id").and_then(|v| v.to_str().ok());
let _ = header_agent_id; let mut params = json!({});
if let Some(ref n) = body.namespace {
params["namespace"] = json!(n);
}
if let Some(l) = body.limit {
params["limit"] = json!(l);
}
let lock = state.lock().await;
let result = crate::mcp::handle_session_start(&lock.0, ¶ms, None);
drop(lock);
match result {
Ok(mut v) => {
if let Some(obj) = v.as_object_mut() {
obj.entry("session_id")
.or_insert_with(|| json!(Uuid::new_v4().to_string()));
if let Some(ref a) = body.agent_id {
obj.insert("agent_id".into(), json!(a));
}
}
(StatusCode::OK, Json(v)).into_response()
}
Err(e) => (StatusCode::BAD_REQUEST, Json(json!({"error": e}))).into_response(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_state() -> Db {
let conn = db::open(std::path::Path::new(":memory:")).unwrap();
let path = std::path::PathBuf::from(":memory:");
Arc::new(Mutex::new((conn, path, ResolvedTtl::default(), true)))
}
#[tokio::test]
async fn health_returns_ok() {
let state = test_state();
let lock = state.lock().await;
let ok = db::health_check(&lock.0).unwrap_or(false);
assert!(ok);
}
#[tokio::test]
async fn store_and_retrieve_via_state() {
let state = test_state();
let lock = state.lock().await;
let now = Utc::now();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "test".into(),
title: "Handler test".into(),
content: "Testing handlers.".into(),
tags: vec!["test".into()],
priority: 7,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
let id = db::insert(&lock.0, &mem).unwrap();
let got = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(got.title, "Handler test");
}
#[tokio::test]
async fn recall_via_state() {
let state = test_state();
let lock = state.lock().await;
let now = Utc::now();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "test".into(),
title: "Recall handler test".into(),
content: "Content for recall.".into(),
tags: vec![],
priority: 8,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
let (results, _tokens) = db::recall(
&lock.0,
"recall handler",
Some("test"),
10,
None,
None,
None,
crate::models::SHORT_TTL_EXTEND_SECS,
crate::models::MID_TTL_EXTEND_SECS,
None,
None,
)
.unwrap();
assert!(!results.is_empty());
assert!(results[0].1 > 0.0); }
#[tokio::test]
async fn stats_via_state() {
let state = test_state();
let lock = state.lock().await;
let path = std::path::Path::new(":memory:");
let s = db::stats(&lock.0, path).unwrap();
assert_eq!(s.total, 0);
}
#[tokio::test]
async fn bulk_size_limit() {
assert_eq!(MAX_BULK_SIZE, 1000);
}
#[tokio::test]
async fn list_empty_namespace() {
let state = test_state();
let lock = state.lock().await;
let results = db::list(
&lock.0,
Some("nonexistent"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert!(results.is_empty());
}
#[tokio::test]
async fn create_and_update_with_metadata() {
let state = test_state();
let lock = state.lock().await;
let now = Utc::now();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "test".into(),
title: "HTTP metadata test".into(),
content: "Testing metadata through handler layer.".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"http_test": true, "version": 1}),
};
let id = db::insert(&lock.0, &mem).unwrap();
let got = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(got.metadata["http_test"], true);
assert_eq!(got.metadata["version"], 1);
let new_meta =
serde_json::json!({"http_test": true, "version": 2, "updated_by": "handler"});
let (found, _) = db::update(
&lock.0,
&id,
None,
None,
None,
None,
None,
None,
None,
None,
Some(&new_meta),
)
.unwrap();
assert!(found);
let got = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(got.metadata["version"], 2);
assert_eq!(got.metadata["updated_by"], "handler");
}
use axum::{Router, body::Body, routing::get as axum_get, routing::post as axum_post};
use tower::ServiceExt as _;
fn test_app_state(db: Db) -> AppState {
AppState {
db,
embedder: Arc::new(None),
vector_index: Arc::new(Mutex::new(None)),
federation: Arc::new(None),
tier_config: Arc::new(crate::config::FeatureTier::Keyword.config()),
scoring: Arc::new(crate::config::ResolvedScoring::default()),
}
}
#[tokio::test]
async fn http_create_memory_uses_appstate_and_persists() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"tier": "long",
"namespace": "http-embed-test",
"title": "Semantic-ready via HTTP",
"content": "HTTP-authored memories must now participate in semantic recall.",
"tags": ["issue-219"],
"priority": 7,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("http-embed-test"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert!(!rows.is_empty(), "HTTP-authored memory must be persisted");
assert_eq!(rows[0].title, "Semantic-ready via HTTP");
}
#[tokio::test]
async fn http_update_memory_uses_appstate() {
let state = test_state();
let now = Utc::now();
let id = {
let lock = state.lock().await;
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "http-embed-test".into(),
title: "Before update".into(),
content: "Original content.".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state.clone()));
let patch = serde_json::json!({"content": "Updated content for semantic refresh."});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&patch).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_push_applies_and_advances_clock() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let now = Utc::now().to_rfc3339();
let body = serde_json::json!({
"sender_agent_id": "peer-alice",
"sender_clock": {"entries": {}},
"memories": [{
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "sync-smoke",
"title": "From peer",
"content": "Pushed via HTTP sync endpoint.",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now,
"updated_at": now,
"last_accessed_at": null,
"expires_at": null,
"metadata": {"agent_id": "peer-alice"}
}],
"dry_run": false
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "local-receiver")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("sync-smoke"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows.len(), 1);
let clock = db::sync_state_load(&lock.0, "local-receiver").unwrap();
assert!(
clock.latest_from("peer-alice").is_some(),
"push must record sender in sync_state; got: {:?}",
clock.entries
);
}
#[tokio::test]
async fn http_sync_push_applies_archives() {
let state = test_state();
let id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "s29".into(),
title: "Archive M1".into(),
content: "body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"sender_agent_id": "peer-a",
"sender_clock": {"entries": {}},
"memories": [],
"archives": [id, "missing-on-peer"],
"dry_run": false
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["archived"], 1, "live row must be archived");
assert_eq!(v["noop"], 1, "missing id must no-op");
let lock = state.lock().await;
assert!(db::get(&lock.0, &id).unwrap().is_none());
let archived = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert_eq!(archived.len(), 1);
assert_eq!(archived[0]["id"], id);
assert_eq!(archived[0]["archive_reason"], "sync_push");
}
#[tokio::test]
async fn http_archive_by_ids_happy_path() {
let state = test_state();
let live_id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "s29".into(),
title: "Live for archive".into(),
content: "will be archived".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"ids": [live_id, "does-not-exist"],
"reason": "scenario_s29"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
assert_eq!(v["archived"].as_array().unwrap().len(), 1);
assert_eq!(v["missing"].as_array().unwrap().len(), 1);
assert_eq!(v["reason"], "scenario_s29");
let lock = state.lock().await;
assert!(db::get(&lock.0, &live_id).unwrap().is_none());
let archived = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert_eq!(archived.len(), 1);
assert_eq!(archived[0]["id"], live_id);
assert_eq!(archived[0]["archive_reason"], "scenario_s29");
}
#[tokio::test]
async fn http_archive_by_ids_default_reason() {
let state = test_state();
let live_id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "s29-default".into(),
title: "Default reason".into(),
content: "c".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"ids": [live_id]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["reason"], "archive");
let lock = state.lock().await;
let archived = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert_eq!(archived[0]["archive_reason"], "archive");
}
#[tokio::test]
async fn http_bulk_create_uses_appstate_and_persists() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(test_app_state(state.clone()));
let bodies: Vec<serde_json::Value> = (0..5)
.map(|i| {
serde_json::json!({
"tier": "long",
"namespace": "bulk-appstate",
"title": format!("bulk-{i}"),
"content": format!("body-{i}"),
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
})
})
.collect();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&bodies).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], 5);
assert!(v["errors"].as_array().unwrap().is_empty());
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("bulk-appstate"),
None,
100,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows.len(), 5, "bulk rows must persist via AppState");
}
#[tokio::test]
async fn http_bulk_create_fans_out_with_federation() {
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::net::TcpListener;
let state = test_state();
let count = Arc::new(AtomicUsize::new(0));
let count_for_peer = count.clone();
#[derive(Clone)]
struct MockState {
count: Arc<AtomicUsize>,
}
async fn mock_sync_push(
axum::extract::State(s): axum::extract::State<MockState>,
Json(_body): Json<serde_json::Value>,
) -> (StatusCode, Json<serde_json::Value>) {
s.count.fetch_add(1, Ordering::Relaxed);
(
StatusCode::OK,
Json(json!({"applied":1,"noop":0,"skipped":0})),
)
}
let peer_app = Router::new()
.route("/api/v1/sync/push", axum_post(mock_sync_push))
.with_state(MockState {
count: count_for_peer,
});
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, peer_app).await.ok();
});
let peer_url = format!("http://{addr}");
let fed = crate::federation::FederationConfig::build(
2, &[peer_url],
std::time::Duration::from_secs(2),
None,
None,
None,
"ai:bulk-test".to_string(),
)
.unwrap()
.expect("federation must be built");
let app_state = AppState {
db: state.clone(),
embedder: Arc::new(None),
vector_index: Arc::new(Mutex::new(None)),
federation: Arc::new(Some(fed)),
tier_config: Arc::new(crate::config::FeatureTier::Keyword.config()),
scoring: Arc::new(crate::config::ResolvedScoring::default()),
};
let router = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(app_state);
let n = 4;
let bodies: Vec<serde_json::Value> = (0..n)
.map(|i| {
serde_json::json!({
"tier": "long",
"namespace": "bulk-fanout",
"title": format!("bulk-fanout-{i}"),
"content": "c",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
})
})
.collect();
let resp = router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&bodies).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], n);
let expected = n + 1;
for _ in 0..20 {
if count.load(Ordering::Relaxed) >= expected {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(
count.load(Ordering::Relaxed),
expected,
"mock peer must receive one sync_push POST per bulk row plus one terminal catchup batch"
);
}
#[tokio::test]
async fn http_sync_push_rejects_oversized_batch_redteam_242() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let now = Utc::now().to_rfc3339();
let mems: Vec<serde_json::Value> = (0..=MAX_BULK_SIZE)
.map(|i| {
serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "oversize",
"title": format!("m{i}"),
"content": "x",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now,
"updated_at": now,
"last_accessed_at": null,
"expires_at": null,
"metadata": {}
})
})
.collect();
let body = serde_json::json!({
"sender_agent_id": "peer-flood",
"sender_clock": {"entries": {}},
"memories": mems,
"dry_run": false,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_sync_push_dry_run_applies_nothing() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let now = Utc::now().to_rfc3339();
let body = serde_json::json!({
"sender_agent_id": "peer-bob",
"sender_clock": {"entries": {}},
"memories": [{
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "sync-dryrun",
"title": "Must not land",
"content": "Preview only.",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now,
"updated_at": now,
"last_accessed_at": null,
"expires_at": null,
"metadata": {}
}],
"dry_run": true
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("sync-dryrun"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert!(rows.is_empty(), "dry_run must not write rows");
}
#[tokio::test]
async fn http_contradictions_surfaces_same_topic_candidates_and_synth_link() {
let state = test_state();
let now = Utc::now().to_rfc3339();
{
let lock = state.lock().await;
let topic = "sky-color-test";
for (title, agent, content) in [
("sky-color-test-alice", "ai:alice", "sky-color-test is blue"),
("sky-color-test-bob", "ai:bob", "sky-color-test is red"),
] {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "contradictions-test".into(),
title: title.into(),
content: content.into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({
"agent_id": agent,
"topic": topic,
}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(
"/api/v1/contradictions?topic=sky-color-test&namespace=contradictions-test",
)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let memories = v["memories"].as_array().unwrap();
assert_eq!(memories.len(), 2, "both candidates should be returned");
let links = v["links"].as_array().unwrap();
let synth_contradict = links.iter().find(|l| {
l["relation"].as_str() == Some("contradicts")
&& l["synthesized"].as_bool() == Some(true)
});
assert!(
synth_contradict.is_some(),
"expected a synthesized contradicts link between alice and bob"
);
}
#[tokio::test]
async fn http_contradictions_requires_topic_or_namespace() {
let state = test_state();
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_sync_push_applies_deletions() {
let state = test_state();
let now = Utc::now().to_rfc3339();
let seeded_id = {
let lock = state.lock().await;
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "delete-fanout".into(),
title: "to-be-deleted".into(),
content: "body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "ai:seeder"}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"sender_agent_id": "peer-alice",
"sender_clock": {"entries": {}},
"memories": [],
"deletions": [seeded_id.clone()],
"dry_run": false
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "local-receiver")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 1);
let lock = state.lock().await;
let gone = db::get(&lock.0, &seeded_id).unwrap();
assert!(
gone.is_none(),
"row should have been tombstoned by sync_push"
);
}
#[tokio::test]
async fn http_sync_push_applies_incoming_links() {
let state = test_state();
let now = Utc::now().to_rfc3339();
let (m1, m2) = {
let lock = state.lock().await;
let m1 = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "link-fanout".into(),
title: "source".into(),
content: "a".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "ai:seeder"}),
};
let m1_id = db::insert(&lock.0, &m1).unwrap();
let m2 = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "link-fanout".into(),
title: "target".into(),
content: "b".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "ai:seeder"}),
};
let m2_id = db::insert(&lock.0, &m2).unwrap();
(m1_id, m2_id)
};
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"sender_agent_id": "peer-alice",
"sender_clock": {"entries": {}},
"memories": [],
"links": [{
"source_id": m1,
"target_id": m2,
"relation": "related_to",
"created_at": now,
}],
"dry_run": false
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "local-receiver")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["links_applied"], 1);
let lock = state.lock().await;
let links = db::get_links(&lock.0, &m1).unwrap();
assert_eq!(links.len(), 1);
assert_eq!(links[0].target_id, m2);
assert_eq!(links[0].relation, "related_to");
}
#[tokio::test]
async fn http_sync_since_streams_new_memories_only() {
let state = test_state();
let old_ts = "2020-01-01T00:00:00+00:00";
let new_ts = Utc::now().to_rfc3339();
{
let lock = state.lock().await;
for (title, ts) in [("old-mem", old_ts), ("new-mem", new_ts.as_str())] {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "since-test".into(),
title: title.into(),
content: "body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: ts.to_string(),
updated_at: ts.to_string(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/sync/since", axum_get(sync_since))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?since=2020-06-01T00:00:00%2B00:00")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let titles: Vec<String> = v["memories"]
.as_array()
.unwrap()
.iter()
.filter_map(|m| m["title"].as_str().map(str::to_string))
.collect();
assert_eq!(titles, vec!["new-mem".to_string()]);
}
#[tokio::test]
async fn http_sync_since_includes_s39_diagnostic_fields() {
let state = test_state();
let mid_ts = "2024-06-01T00:00:00+00:00";
let newer_ts = "2025-06-01T00:00:00+00:00";
let newest_ts = "2026-01-01T00:00:00+00:00";
{
let lock = state.lock().await;
for (title, ts) in [("mid", mid_ts), ("newer", newer_ts), ("newest", newest_ts)] {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "s39-diag".into(),
title: title.into(),
content: "c".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: ts.to_string(),
updated_at: ts.to_string(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/sync/since", axum_get(sync_since))
.with_state(state.clone());
let since = "2024-01-01T00:00:00%2B00:00";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/sync/since?since={since}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 3);
assert_eq!(v["updated_since"], "2024-01-01T00:00:00+00:00");
assert_eq!(v["earliest_updated_at"], mid_ts);
assert_eq!(v["latest_updated_at"], newest_ts);
let empty_app = Router::new()
.route("/api/v1/sync/since", axum_get(sync_since))
.with_state(state);
let resp = empty_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?since=2099-01-01T00:00:00%2B00:00")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert!(v["earliest_updated_at"].is_null());
assert!(v["latest_updated_at"].is_null());
assert_eq!(v["updated_since"], "2099-01-01T00:00:00+00:00");
}
#[tokio::test]
async fn sync_since_rejects_garbage_timestamp_with_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/since", axum_get(sync_since))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?since=not-a-date")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("RFC 3339"));
}
#[tokio::test]
async fn sync_state_observe_is_monotonic() {
let conn = db::open(std::path::Path::new(":memory:")).unwrap();
let older = "2020-01-01T00:00:00+00:00";
let newer = "2026-04-17T00:00:00+00:00";
db::sync_state_observe(&conn, "local", "peer-a", newer).unwrap();
db::sync_state_observe(&conn, "local", "peer-a", older).unwrap();
let clock = db::sync_state_load(&conn, "local").unwrap();
assert_eq!(clock.latest_from("peer-a"), Some(newer));
}
async fn dummy_handler() -> impl IntoResponse {
(StatusCode::OK, "ok")
}
fn auth_app(api_key: Option<&str>) -> Router {
let auth_state = ApiKeyState {
key: api_key.map(String::from),
};
Router::new()
.route("/api/v1/health", axum_get(dummy_handler))
.route("/api/v1/memories", axum_get(dummy_handler))
.layer(axum::middleware::from_fn_with_state(
auth_state,
api_key_auth,
))
}
#[tokio::test]
async fn api_key_no_key_configured_allows_all() {
let app = auth_app(None);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_valid_header_allows() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.header("x-api-key", "secret123")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_invalid_header_rejected() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.header("x-api-key", "wrong")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_missing_header_rejected() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_valid_query_param_allows() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?api_key=secret123")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_health_exempt() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn create_memory_rejects_invalid_json() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(b"not valid json".to_vec()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn create_memory_rejects_missing_required_fields() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"content": "body text",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.clone()
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn create_memory_rejects_empty_title() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "",
"content": "body text",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("title"));
}
#[tokio::test]
async fn create_memory_rejects_oversized_content() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let oversized = "x".repeat(65537);
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "Test",
"content": oversized,
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("exceeds max size"));
}
#[tokio::test]
async fn create_memory_rejects_invalid_tier() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body_str = r#"{"tier":"invalid_tier","namespace":"test","title":"Test","content":"body","tags":[],"priority":5,"confidence":1.0,"source":"api","metadata":{}}"#;
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(body_str.as_bytes().to_vec()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn create_memory_rejects_invalid_priority() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "Test",
"content": "body",
"tags": [],
"priority": 0, "confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn create_memory_rejects_invalid_confidence() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "Test",
"content": "body",
"tags": [],
"priority": 5,
"confidence": 1.5, "source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn create_memory_rejects_invalid_source() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "Test",
"content": "body",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "invalid_source",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn update_memory_rejects_invalid_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({"content": "new content"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/@@@@@@@@@@@@") .method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status() == StatusCode::BAD_REQUEST || resp.status() == StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn update_memory_rejects_oversized_content() {
let state = test_state();
let now = Utc::now();
let id = {
let lock = state.lock().await;
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "test".into(),
title: "To Update".into(),
content: "Original".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state));
let oversized = "x".repeat(65537);
let body = serde_json::json!({"content": oversized});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn update_memory_rejects_invalid_confidence() {
let state = test_state();
let now = Utc::now();
let id = {
let lock = state.lock().await;
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "test".into(),
title: "To Update".into(),
content: "Original".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({"confidence": -0.5});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn link_rejects_self_link() {
let state = test_state();
let app = Router::new()
.route("/api/v1/links", axum_post(create_link))
.with_state(test_app_state(state));
let same_id = Uuid::new_v4().to_string();
let body = serde_json::json!({
"source_id": same_id,
"target_id": same_id,
"relation": "related_to"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"]
.as_str()
.unwrap()
.contains("cannot link a memory to itself")
);
}
#[tokio::test]
async fn link_rejects_unknown_relation() {
let state = test_state();
let app = Router::new()
.route("/api/v1/links", axum_post(create_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": Uuid::new_v4().to_string(),
"target_id": Uuid::new_v4().to_string(),
"relation": "invalid_relation"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("relation"));
}
#[tokio::test]
async fn recall_post_rejects_empty_context() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({
"context": "",
"limit": 10
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn recall_post_rejects_zero_budget_tokens() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({
"context": "search term",
"limit": 10,
"budget_tokens": 0
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("budget_tokens"));
}
#[tokio::test]
async fn recall_get_rejects_empty_context() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/recall",
axum::routing::get(recall_memories_get),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall?context=")
.method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn register_agent_rejects_invalid_agent_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "x".repeat(129), "agent_type": "human",
"capabilities": []
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn register_agent_rejects_invalid_agent_type() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "test-agent",
"agent_type": "invalid_type",
"capabilities": []
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn subscribe_rejects_private_ip() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "http://10.0.0.1/webhook",
"events": "*"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let error_msg = v["error"].as_str().unwrap();
assert!(
error_msg.contains("private")
|| error_msg.contains("link-local")
|| error_msg.contains("https")
|| error_msg.contains("non-loopback")
);
}
#[tokio::test]
async fn subscribe_rejects_file_url() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "file:///etc/passwd",
"events": "*"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn subscribe_accepts_localhost_loopback() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "http://localhost/webhook",
"events": "*"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status() == StatusCode::CREATED || resp.status() == StatusCode::OK);
}
#[tokio::test]
async fn notify_rejects_missing_payload() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"target_agent_id": "bob",
"title": "A message"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"].as_str().unwrap().contains("payload")
|| v["error"].as_str().unwrap().contains("content")
);
}
#[tokio::test]
async fn create_memory_handles_missing_content_type() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "Test",
"content": "body",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status() != StatusCode::CREATED);
}
#[tokio::test]
async fn list_memories_handles_limit_zero() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum::routing::get(list_memories))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?limit=0")
.method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn list_memories_clamps_oversized_limit() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum::routing::get(list_memories))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?limit=10000") .method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn search_memories_handles_negative_limit() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/search",
axum::routing::get(search_memories),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/search?query=test&limit=-1")
.method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(resp.status() == StatusCode::OK || resp.status() == StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn api_key_missing_when_required_rejects() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_wrong_value_rejects() {
let app = auth_app(Some("secret123"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("GET")
.header("x-api-key", "wrong_secret")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
async fn insert_test_memory(state: &Db, namespace: &str, title: &str) -> String {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: namespace.into(),
title: title.into(),
content: format!("content for {title}"),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
}
#[tokio::test]
async fn http_list_archive_rejects_limit_zero() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?limit=0")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("limit"));
}
#[tokio::test]
async fn http_list_archive_clamps_oversized_limit() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?limit=99999")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_list_archive_filters_by_namespace() {
let state = test_state();
let id = insert_test_memory(&state, "arch-ns-a", "to-archive").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?namespace=arch-ns-a&limit=10")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
}
#[tokio::test]
async fn http_restore_archive_404_for_unknown_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/00000000-0000-0000-0000-000000000000/restore")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_restore_archive_rejects_empty_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/%01/restore")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_restore_archive_double_restore_returns_404() {
let state = test_state();
let id = insert_test_memory(&state, "restore-twice", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state.clone()));
let resp = app
.clone()
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_purge_archive_zero_days_purges_all() {
let state = test_state();
let id = insert_test_memory(&state, "purge-zero", "x").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/purge", axum_post(purge_archive))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/purge?older_than_days=0")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["purged"].as_u64().is_some());
}
#[tokio::test]
async fn http_purge_archive_negative_days_returns_500() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/purge", axum_post(purge_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/purge?older_than_days=-1")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn http_purge_archive_no_days_purges_unconditional() {
let state = test_state();
let id = insert_test_memory(&state, "purge-all", "x").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/purge", axum_post(purge_archive))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/purge")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["purged"], 1);
}
#[tokio::test]
async fn http_archive_stats_reports_per_namespace_counts() {
let state = test_state();
let id_a = insert_test_memory(&state, "stats-a", "a").await;
let id_b = insert_test_memory(&state, "stats-b", "b").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id_a, Some("t")).unwrap();
db::archive_memory(&lock.0, &id_b, Some("t")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/stats", axum::routing::get(archive_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["archived_total"], 2);
assert_eq!(v["by_namespace"].as_array().unwrap().len(), 2);
}
#[tokio::test]
async fn http_archive_by_ids_rejects_oversized_batch() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let big_ids: Vec<String> = (0..=MAX_BULK_SIZE)
.map(|_| Uuid::new_v4().to_string())
.collect();
let body = serde_json::json!({"ids": big_ids});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("archive limited"));
}
#[tokio::test]
async fn http_archive_by_ids_rejects_invalid_id_in_batch() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let body = serde_json::json!({"ids": [" "]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("invalid id"));
}
#[tokio::test]
async fn http_archive_by_ids_all_missing() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let ids: Vec<String> = (0..3).map(|_| Uuid::new_v4().to_string()).collect();
let body = serde_json::json!({"ids": ids});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert_eq!(v["archived"].as_array().unwrap().len(), 0);
assert_eq!(v["missing"].as_array().unwrap().len(), 3);
}
#[tokio::test]
async fn http_bulk_create_oversized_batch_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(test_app_state(state));
let bodies: Vec<serde_json::Value> = (0..=MAX_BULK_SIZE)
.map(|i| {
serde_json::json!({
"tier": "long",
"namespace": "bulk-overflow",
"title": format!("t-{i}"),
"content": "c",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
})
})
.collect();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&bodies).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_bulk_create_partial_success_collects_errors() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(test_app_state(state.clone()));
let bodies = serde_json::json!([
{
"tier": "long",
"namespace": "bulk-mixed",
"title": "good row",
"content": "ok",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
},
{
"tier": "long",
"namespace": "bulk-mixed",
"title": "",
"content": "bad: empty title",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
}
]);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&bodies).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], 1);
assert_eq!(v["errors"].as_array().unwrap().len(), 1);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("bulk-mixed"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].title, "good row");
}
#[tokio::test]
async fn http_bulk_create_empty_body_succeeds_with_zero_created() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(test_app_state(state));
let bodies: Vec<serde_json::Value> = vec![];
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&bodies).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], 0);
assert!(v["errors"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn http_list_pending_empty_returns_zero_count() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending", axum::routing::get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
}
#[tokio::test]
async fn http_list_pending_with_status_filter() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending", axum::routing::get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending?status=approved&limit=5")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_approve_pending_unknown_id_returns_403_or_500() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state));
let unknown = Uuid::new_v4().to_string();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{unknown}/approve"))
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
resp.status() == StatusCode::FORBIDDEN
|| resp.status() == StatusCode::INTERNAL_SERVER_ERROR
|| resp.status() == StatusCode::ACCEPTED,
"unexpected status {}",
resp.status()
);
}
#[tokio::test]
async fn http_approve_pending_rejects_invalid_agent_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state));
let id = Uuid::new_v4().to_string();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{id}/approve"))
.method("POST")
.header("x-agent-id", "bad agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_reject_pending_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state));
let unknown = Uuid::new_v4().to_string();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{unknown}/reject"))
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_reject_pending_rejects_invalid_agent_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state));
let id = Uuid::new_v4().to_string();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{id}/reject"))
.method("POST")
.header("x-agent-id", "bad agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_search_rejects_blank_query() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/search",
axum::routing::get(search_memories),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/search?q=%20%20%20") .body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_search_long_query_succeeds() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/search",
axum::routing::get(search_memories),
)
.with_state(state);
let q = "a".repeat(2_000);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/search?q={q}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
resp.status() == StatusCode::OK
|| resp.status() == StatusCode::BAD_REQUEST
|| resp.status() == StatusCode::INTERNAL_SERVER_ERROR,
"unexpected status {}",
resp.status()
);
}
#[tokio::test]
async fn http_search_normal_query_returns_results_array() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/search",
axum::routing::get(search_memories),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/search?q=hello")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["results"].is_array());
assert_eq!(v["query"], "hello");
}
#[tokio::test]
async fn http_search_invalid_agent_id_filter_rejected() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/search",
axum::routing::get(search_memories),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/search?q=test&agent_id=bad%20agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_recall_get_rejects_blank_context() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/recall",
axum::routing::get(recall_memories_get),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall?context=%20")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_recall_get_rejects_zero_budget_tokens() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/recall",
axum::routing::get(recall_memories_get),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall?context=hi&budget_tokens=0")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("budget_tokens"));
}
#[tokio::test]
async fn http_recall_post_rejects_blank_context() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({"context": " "});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_recall_post_keyword_mode_returns_mode_field() {
let state = test_state();
let _id = insert_test_memory(&state, "recall-mode", "the title").await;
let app = Router::new()
.route("/api/v1/memories/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({"context": "title", "namespace": "recall-mode"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["mode"], "keyword");
}
#[tokio::test]
async fn http_sync_since_empty_db_returns_zero_count() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/since", axum::routing::get(sync_since))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?since=2000-01-01T00:00:00Z&limit=10")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert!(v["earliest_updated_at"].is_null());
assert!(v["latest_updated_at"].is_null());
}
#[tokio::test]
async fn http_sync_since_clamps_oversized_limit() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/since", axum::routing::get(sync_since))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?limit=999999")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["limit"].as_u64().unwrap() <= 10_000);
}
#[tokio::test]
async fn http_sync_since_empty_since_string_treated_as_full_snapshot() {
let state = test_state();
let _id = insert_test_memory(&state, "sync-empty", "row").await;
let app = Router::new()
.route("/api/v1/sync/since", axum::routing::get(sync_since))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?since=")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_since_records_peer_via_observe() {
let state = test_state();
let _id = insert_test_memory(&state, "sync-peer", "row").await;
let app = Router::new()
.route("/api/v1/sync/since", axum::routing::get(sync_since))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/since?peer=peer-x")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_capabilities_returns_features() {
let state = test_state();
let app = Router::new()
.route("/api/v1/capabilities", axum::routing::get(get_capabilities))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/capabilities")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["features"]["embedder_loaded"], false);
}
#[tokio::test]
async fn http_session_start_rejects_invalid_agent_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({"agent_id": "bad agent id with spaces"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_session_start_stamps_session_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["session_id"].as_str().is_some());
}
#[tokio::test]
async fn http_get_taxonomy_rejects_invalid_prefix() {
let state = test_state();
let app = Router::new()
.route("/api/v1/taxonomy", axum::routing::get(get_taxonomy))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/taxonomy?prefix=bad%20prefix")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_get_taxonomy_clamps_depth_and_limit() {
let state = test_state();
let app = Router::new()
.route("/api/v1/taxonomy", axum::routing::get(get_taxonomy))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/taxonomy?depth=1000&limit=999999")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_list_subscriptions_empty_returns_zero() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/subscriptions",
axum::routing::get(list_subscriptions),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert!(v["subscriptions"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn http_list_subscriptions_filters_by_agent_id() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/subscriptions",
axum::routing::get(list_subscriptions),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions?agent_id=alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_get_inbox_with_x_agent_id_header() {
let state = test_state();
let app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?unread_only=true&limit=20")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_check_duplicate_rejects_invalid_title() {
let state = test_state();
let app = Router::new()
.route("/api/v1/check_duplicate", axum_post(check_duplicate))
.with_state(test_app_state(state));
let body = serde_json::json!({"title": "", "content": "non-empty"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/check_duplicate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_check_duplicate_rejects_invalid_content() {
let state = test_state();
let app = Router::new()
.route("/api/v1/check_duplicate", axum_post(check_duplicate))
.with_state(test_app_state(state));
let body = serde_json::json!({"title": "ok", "content": ""});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/check_duplicate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_check_duplicate_rejects_invalid_namespace() {
let state = test_state();
let app = Router::new()
.route("/api/v1/check_duplicate", axum_post(check_duplicate))
.with_state(test_app_state(state));
let body = serde_json::json!({
"title": "ok",
"content": "ok content",
"namespace": "BAD NAMESPACE WITH SPACES",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/check_duplicate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_check_duplicate_503_when_no_embedder() {
let state = test_state();
let app = Router::new()
.route("/api/v1/check_duplicate", axum_post(check_duplicate))
.with_state(test_app_state(state));
let body = serde_json::json!({"title": "anchor", "content": "some long enough content"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/check_duplicate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn http_entity_register_creates_then_idempotent_returns_200() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state.clone());
let body = serde_json::json!({
"canonical_name": "Acme Corp",
"namespace": "kg-test",
"aliases": ["acme", "Acme"],
"metadata": {"region": "us"},
});
let resp = app
.clone()
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let resp2 = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp2.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_entity_register_rejects_invalid_canonical_name() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "",
"namespace": "kg-test",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_entity_register_rejects_invalid_namespace() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "Acme",
"namespace": "BAD NS!",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_entity_register_rejects_invalid_agent_id_header() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "Acme",
"namespace": "kg-test",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "BAD AGENT!")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_entity_register_collision_with_non_entity_returns_409() {
let state = test_state();
let now = Utc::now().to_rfc3339();
{
let lock = state.lock().await;
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "collide-ns".into(),
title: "Acme Squat".into(),
content: "this is a regular memory".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "Acme Squat",
"namespace": "collide-ns",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CONFLICT);
}
#[tokio::test]
async fn http_entity_get_by_alias_blank_alias_rejected() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/entities/by_alias",
axum::routing::get(entity_get_by_alias),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities/by_alias?alias=%20%20")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_entity_get_by_alias_invalid_namespace_rejected() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/entities/by_alias",
axum::routing::get(entity_get_by_alias),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities/by_alias?alias=acme&namespace=BAD%20NS!")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_entity_get_by_alias_returns_found_false_when_unknown() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/entities/by_alias",
axum::routing::get(entity_get_by_alias),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities/by_alias?alias=nonexistent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["found"], serde_json::json!(false));
}
#[tokio::test]
async fn http_entity_get_by_alias_returns_found_true_after_register() {
let state = test_state();
{
let lock = state.lock().await;
db::entity_register(
&lock.0,
"Acme Corp",
"kg-lookup",
&["acme".to_string(), "ACME".to_string()],
&serde_json::json!({}),
Some("alice"),
)
.unwrap();
}
let app = Router::new()
.route(
"/api/v1/entities/by_alias",
axum::routing::get(entity_get_by_alias),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities/by_alias?alias=acme&namespace=kg-lookup")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["found"], serde_json::json!(true));
assert_eq!(v["canonical_name"], serde_json::json!("Acme Corp"));
}
#[tokio::test]
async fn http_kg_timeline_rejects_invalid_source_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/timeline", axum::routing::get(kg_timeline))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/timeline?source_id=")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_timeline_rejects_invalid_since() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/timeline", axum::routing::get(kg_timeline))
.with_state(state);
let id = Uuid::new_v4().to_string();
let uri = format!("/api/v1/kg/timeline?source_id={id}&since=NOT-A-TIMESTAMP");
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(&uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_timeline_rejects_invalid_until() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/timeline", axum::routing::get(kg_timeline))
.with_state(state);
let id = Uuid::new_v4().to_string();
let uri = format!("/api/v1/kg/timeline?source_id={id}&until=garbage");
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(&uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_timeline_returns_empty_for_unlinked_source() {
let state = test_state();
let id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "kg-tl".into(),
title: "anchor".into(),
content: "anchor body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/kg/timeline", axum::routing::get(kg_timeline))
.with_state(state);
let uri = format!("/api/v1/kg/timeline?source_id={id}");
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(&uri)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], serde_json::json!(0));
assert!(v["events"].is_array());
}
#[tokio::test]
async fn http_kg_invalidate_rejects_invalid_link() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/invalidate", axum_post(kg_invalidate))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"target_id": "11111111-1111-4111-8111-111111111111",
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/invalidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_invalidate_rejects_invalid_valid_until() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/invalidate", axum_post(kg_invalidate))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"target_id": "22222222-2222-4222-8222-222222222222",
"relation": "related_to",
"valid_until": "garbage",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/invalidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_invalidate_404_when_link_missing() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/invalidate", axum_post(kg_invalidate))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"target_id": "22222222-2222-4222-8222-222222222222",
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/invalidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_kg_invalidate_marks_link_as_invalidated() {
let state = test_state();
let (a_id, b_id) = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mk = |title: &str| Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "kg-inv".into(),
title: title.into(),
content: format!("{title} body"),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
let a = db::insert(&lock.0, &mk("source-a")).unwrap();
let b = db::insert(&lock.0, &mk("target-b")).unwrap();
db::create_link(&lock.0, &a, &b, "related_to").unwrap();
(a, b)
};
let app = Router::new()
.route("/api/v1/kg/invalidate", axum_post(kg_invalidate))
.with_state(state);
let body = serde_json::json!({
"source_id": a_id,
"target_id": b_id,
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/invalidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["found"], serde_json::json!(true));
}
#[tokio::test]
async fn http_kg_query_rejects_invalid_source_id() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({"source_id": ""});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_query_rejects_invalid_valid_at() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"valid_at": "not-a-timestamp",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_query_rejects_invalid_allowed_agent() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"allowed_agents": ["BAD AGENT!"],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_kg_query_returns_422_for_oversized_max_depth() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"max_depth": 999_usize,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn http_kg_query_returns_422_for_zero_max_depth() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"max_depth": 0_usize,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
}
#[tokio::test]
async fn http_kg_query_returns_empty_for_unlinked_source() {
let state = test_state();
let id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "kg-q".into(),
title: "anchor".into(),
content: "anchor body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": id,
"max_depth": 1_usize,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], serde_json::json!(0));
assert_eq!(v["max_depth"], serde_json::json!(1));
}
#[tokio::test]
async fn http_kg_query_short_circuits_empty_allowed_agents() {
let state = test_state();
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"allowed_agents": [],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], serde_json::json!(0));
}
#[tokio::test]
async fn http_delete_link_rejects_self_link() {
let state = test_state();
let app = Router::new()
.route("/api/v1/links", axum::routing::delete(delete_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"target_id": "11111111-1111-4111-8111-111111111111",
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("DELETE")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_delete_link_returns_deleted_false_when_missing() {
let state = test_state();
let app = Router::new()
.route("/api/v1/links", axum::routing::delete(delete_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": "11111111-1111-4111-8111-111111111111",
"target_id": "22222222-2222-4222-8222-222222222222",
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("DELETE")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], serde_json::json!(false));
}
#[tokio::test]
async fn http_get_links_for_unknown_id_returns_empty_array() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}/links", axum::routing::get(get_links))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/nonexistent-id/links")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["links"].is_array());
assert_eq!(v["links"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_get_links_returns_empty_array_for_unlinked_id() {
let state = test_state();
let id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "links-test".into(),
title: "anchor".into(),
content: "no links yet".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/memories/{id}/links", axum::routing::get(get_links))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}/links"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["links"].is_array());
assert_eq!(v["links"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_list_namespaces_returns_empty_for_fresh_db() {
let state = test_state();
let app = Router::new()
.route("/api/v1/namespaces", axum::routing::get(list_namespaces))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["namespaces"].is_array());
}
#[tokio::test]
async fn http_forget_memories_with_namespace_filter_returns_count() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for i in 0..3 {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "forget-target".into(),
title: format!("row-{i}"),
content: format!("content {i}"),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({"namespace": "forget-target"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["deleted"].as_u64().is_some());
}
#[tokio::test]
async fn http_archive_stats_empty_db_returns_zero() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/stats", axum::routing::get(archive_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_purge_archive_returns_zero_for_empty_archive() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/purge", axum_post(purge_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/purge")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["purged"], serde_json::json!(0));
}
#[tokio::test]
async fn http_run_gc_returns_zero_for_clean_db() {
let state = test_state();
let app = Router::new()
.route("/api/v1/gc", axum_post(run_gc))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/gc")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_export_memories_empty_returns_zero_count() {
let state = test_state();
let app = Router::new()
.route("/api/v1/export", axum::routing::get(export_memories))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/export")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], serde_json::json!(0));
}
#[tokio::test]
async fn http_import_memories_oversized_batch_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/import", axum_post(import_memories))
.with_state(state);
let many: Vec<serde_json::Value> = (0..=MAX_BULK_SIZE)
.map(|i| {
serde_json::json!({
"id": format!("11111111-1111-4111-8111-{:012}", i),
"tier": "long",
"namespace": "imp",
"title": format!("t-{i}"),
"content": "x",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "import",
"access_count": 0,
"created_at": "2026-01-01T00:00:00Z",
"updated_at": "2026-01-01T00:00:00Z",
"last_accessed_at": null,
"expires_at": null,
"metadata": {},
})
})
.collect();
let body = serde_json::json!({"memories": many});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/import")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_import_memories_skips_invalid_rows() {
let state = test_state();
let app = Router::new()
.route("/api/v1/import", axum_post(import_memories))
.with_state(state);
let valid = serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "imp",
"title": "ok-row",
"content": "valid content",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "import",
"access_count": 0,
"created_at": "2026-01-01T00:00:00Z",
"updated_at": "2026-01-01T00:00:00Z",
"last_accessed_at": null,
"expires_at": null,
"metadata": {},
});
let invalid = serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "imp",
"title": "",
"content": "x",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "import",
"access_count": 0,
"created_at": "2026-01-01T00:00:00Z",
"updated_at": "2026-01-01T00:00:00Z",
"last_accessed_at": null,
"expires_at": null,
"metadata": {},
});
let body = serde_json::json!({"memories": [valid, invalid]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/import")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["imported"], serde_json::json!(1));
assert!(v["errors"].as_array().unwrap().len() >= 1);
}
#[tokio::test]
async fn http_get_stats_empty_db() {
let state = test_state();
let app = Router::new()
.route("/api/v1/stats", axum::routing::get(get_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_push_namespace_meta_clears_garbage_skipped() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "peer-x",
"memories": [],
"namespace_meta_clears": ["BAD NAMESPACE!"],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_push_pending_decision_invalid_id_skipped() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "peer-x",
"memories": [],
"pending_decisions": [
{"id": "BAD ID!", "approved": true, "decider": "alice"}
],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_push_namespace_meta_invalid_skipped() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "peer-x",
"memories": [],
"namespace_meta": [
{"namespace": "BAD NS!", "standard_id": "11111111-1111-4111-8111-111111111111", "parent_namespace": null}
],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_sync_push_dry_run_namespace_meta_no_apply() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"sender_agent_id": "peer-x",
"memories": [],
"dry_run": true,
"namespace_meta_clears": ["preview-ns"],
"pending_decisions": [
{"id": "11111111-1111-4111-8111-111111111111", "approved": true, "decider": "alice"}
],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_list_archive_empty_returns_empty_array() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert_eq!(v["archived"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_list_archive_with_items_returns_them() {
let state = test_state();
let id_a = insert_test_memory(&state, "h8a-list-items", "row-a").await;
let id_b = insert_test_memory(&state, "h8a-list-items", "row-b").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id_a, Some("test")).unwrap();
db::archive_memory(&lock.0, &id_b, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?limit=10")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
}
#[tokio::test]
async fn http_list_archive_pagination_offset_skips() {
let state = test_state();
let id1 = insert_test_memory(&state, "h8a-page", "row-1").await;
let id2 = insert_test_memory(&state, "h8a-page", "row-2").await;
let id3 = insert_test_memory(&state, "h8a-page", "row-3").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id1, Some("p")).unwrap();
db::archive_memory(&lock.0, &id2, Some("p")).unwrap();
db::archive_memory(&lock.0, &id3, Some("p")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?limit=1&offset=1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
}
#[tokio::test]
async fn http_list_archive_namespace_filter_excludes_others() {
let state = test_state();
let id_a = insert_test_memory(&state, "h8a-ns-a", "row-a").await;
let id_b = insert_test_memory(&state, "h8a-ns-b", "row-b").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id_a, Some("t")).unwrap();
db::archive_memory(&lock.0, &id_b, Some("t")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?namespace=h8a-ns-a&limit=10")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
let entries = v["archived"].as_array().unwrap();
assert_eq!(entries[0]["namespace"], "h8a-ns-a");
}
#[tokio::test]
async fn http_list_archive_namespace_filter_unknown_returns_empty() {
let state = test_state();
let id_a = insert_test_memory(&state, "h8a-ns-known", "row-a").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id_a, Some("t")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?namespace=h8a-no-such-ns")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
}
#[tokio::test]
async fn http_archive_by_ids_single_id_success() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-aby-single", "row").await;
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"ids": [id], "reason": "h8a-single"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
assert_eq!(v["missing"].as_array().unwrap().len(), 0);
assert_eq!(v["reason"], "h8a-single");
}
#[tokio::test]
async fn http_archive_by_ids_bulk_success() {
let state = test_state();
let id1 = insert_test_memory(&state, "h8a-bulk", "row-1").await;
let id2 = insert_test_memory(&state, "h8a-bulk", "row-2").await;
let id3 = insert_test_memory(&state, "h8a-bulk", "row-3").await;
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"ids": [id1, id2, id3]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 3);
assert_eq!(v["missing"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_archive_by_ids_empty_array_returns_ok_zero_count() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"ids": []});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert_eq!(v["archived"].as_array().unwrap().len(), 0);
assert_eq!(v["missing"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_archive_by_ids_missing_ids_field_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let body = serde_json::json!({"reason": "no-ids-field"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn http_archive_by_ids_malformed_json_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from("not-valid-json{{"))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn http_purge_archive_older_than_keeps_recent() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-purge-recent", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("recent")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::delete(purge_archive))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?older_than_days=365")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["purged"], 0);
let lock = state.lock().await;
let rows = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert_eq!(rows.len(), 1);
}
#[tokio::test]
async fn http_purge_archive_unfiltered_purges_everything() {
let state = test_state();
for i in 0..3 {
let id = insert_test_memory(&state, "h8a-purge-all", &format!("row-{i}")).await;
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("all")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::delete(purge_archive))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["purged"], 3);
let lock = state.lock().await;
let rows = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert!(rows.is_empty());
}
#[tokio::test]
async fn http_purge_archive_zero_days_purges_all_archived() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-purge-zero", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("zero")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum::routing::delete(purge_archive))
.with_state(state.clone());
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?older_than_days=0")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["purged"].as_u64().unwrap() >= 1);
}
#[tokio::test]
async fn http_purge_archive_response_shape_has_purged_key() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum::routing::delete(purge_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v.is_object());
assert!(v["purged"].is_number());
}
#[tokio::test]
async fn http_restore_archive_happy_path_and_listed_in_active() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-restore-ok", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("h8a")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["restored"], true);
assert_eq!(v["id"], id);
let lock = state.lock().await;
let got = db::get(&lock.0, &id).unwrap();
assert!(got.is_some());
let archived = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert!(archived.is_empty());
}
#[tokio::test]
async fn http_restore_archive_then_list_archive_excludes_restored() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-restore-list", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("h8a")).unwrap();
let rows = db::list_archived(&lock.0, None, 10, 0).unwrap();
assert_eq!(rows.len(), 1);
}
let restore_app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state.clone()));
let resp = restore_app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let list_app = Router::new()
.route("/api/v1/archive", axum::routing::get(list_archive))
.with_state(state);
let resp = list_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
}
#[tokio::test]
async fn http_restore_archive_preserves_namespace_and_title() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-rest-meta", "preserve-me").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let got = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(got.namespace, "h8a-rest-meta");
assert_eq!(got.title, "preserve-me");
}
#[tokio::test]
async fn http_restore_archive_after_purge_returns_404() {
let state = test_state();
let id = insert_test_memory(&state, "h8a-rest-purged", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
db::purge_archive(&lock.0, None).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_restore_archive_oversized_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let huge = "a".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{huge}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_archive_stats_with_data_reports_total_and_breakdown() {
let state = test_state();
let id_a1 = insert_test_memory(&state, "h8a-stats-a", "row-1").await;
let id_a2 = insert_test_memory(&state, "h8a-stats-a", "row-2").await;
let id_b1 = insert_test_memory(&state, "h8a-stats-b", "row-3").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id_a1, Some("t")).unwrap();
db::archive_memory(&lock.0, &id_a2, Some("t")).unwrap();
db::archive_memory(&lock.0, &id_b1, Some("t")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/stats", axum::routing::get(archive_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["archived_total"], 3);
let by_ns = v["by_namespace"].as_array().unwrap();
assert_eq!(by_ns.len(), 2);
assert_eq!(by_ns[0]["count"], 2);
assert_eq!(by_ns[0]["namespace"], "h8a-stats-a");
}
#[tokio::test]
async fn http_archive_stats_empty_returns_total_zero_empty_breakdown() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/stats", axum::routing::get(archive_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["archived_total"], 0);
assert!(v["by_namespace"].as_array().unwrap().is_empty());
}
#[tokio::test]
async fn http_archive_stats_unaffected_by_active_rows() {
let state = test_state();
for i in 0..5 {
insert_test_memory(&state, "h8a-stats-active", &format!("row-{i}")).await;
}
let app = Router::new()
.route("/api/v1/archive/stats", axum::routing::get(archive_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["archived_total"], 0);
}
#[tokio::test]
async fn http_forget_memories_no_filter_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_forget_memories_pattern_only_deletes_matches() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for (i, content) in ["delete-me alpha", "keep-this beta", "delete-me gamma"]
.iter()
.enumerate()
{
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "h8a-forget-pat".into(),
title: format!("row-{i}"),
content: (*content).into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({"pattern": "delete-me"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 2);
}
#[tokio::test]
async fn http_forget_memories_by_tier_only_targets_tier() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for (i, tier) in [Tier::Short, Tier::Short, Tier::Long].iter().enumerate() {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: tier.clone(),
namespace: "h8a-forget-tier".into(),
title: format!("row-{i}"),
content: format!("content {i}"),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({"tier": "short"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 2);
}
#[tokio::test]
async fn http_forget_memories_combined_filters_intersect() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for (ns, content) in [
("h8a-forget-and", "purge alpha"),
("h8a-forget-and", "purge beta"),
("h8a-forget-and", "keep gamma"),
("h8a-forget-other", "purge delta"),
] {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: ns.into(),
title: format!("row-{content}"),
content: content.into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({
"namespace": "h8a-forget-and",
"pattern": "purge"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 2);
}
#[tokio::test]
async fn http_forget_memories_malformed_json_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from("{not-json"))
.unwrap(),
)
.await
.unwrap();
assert!(resp.status().is_client_error());
}
#[tokio::test]
async fn http_forget_memories_no_match_returns_zero_deleted() {
let state = test_state();
for i in 0..3 {
insert_test_memory(&state, "h8a-forget-keep", &format!("k-{i}")).await;
}
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state.clone());
let body = serde_json::json!({"namespace": "h8a-forget-empty"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 0);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("h8a-forget-keep"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows.len(), 3);
}
#[tokio::test]
async fn h8b_subscribe_https_url_returns_created() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "https://example.com/webhook",
"events": "*",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["id"].as_str().is_some(), "id must be returned");
assert_eq!(v["url"], "https://example.com/webhook");
assert_eq!(v["created_by"], "alice");
}
#[tokio::test]
async fn h8b_subscribe_missing_url_and_namespace_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({"events": "*"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("url or namespace"),);
}
#[tokio::test]
async fn h8b_subscribe_invalid_url_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "not-a-url",
"events": "*",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn h8b_subscribe_rejects_link_local_metadata_ip() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "https://169.254.169.254/latest/meta-data/",
"events": "*",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let err = v["error"].as_str().unwrap();
assert!(
err.contains("private") || err.contains("link-local") || err.contains("non-loopback"),
"expected SSRF rejection, got: {err}",
);
}
#[tokio::test]
async fn h8b_subscribe_namespace_shape_synthesizes_url() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "alice",
"namespace": "team/research",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["agent_id"], "alice");
assert_eq!(v["namespace"], "team/research");
assert!(
v["url"]
.as_str()
.unwrap()
.starts_with("http://localhost/_ns/"),
"expected synthetic URL, got {}",
v["url"],
);
}
#[tokio::test]
async fn h8b_subscribe_event_filter_round_trips() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"url": "https://example.com/hook",
"events": "memory.created",
"namespace_filter": "global",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["events"], "memory.created");
assert_eq!(v["namespace_filter"], "global");
}
#[tokio::test]
async fn h8b_subscribe_persists_hmac_secret() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum_post(subscribe))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"url": "https://example.com/signed-hook",
"events": "*",
"secret": "topsecret-hmac-key",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v.get("secret").is_none(), "secret leaked into response");
let lock = state.lock().await;
let subs = crate::subscriptions::list(&lock.0).unwrap();
assert_eq!(subs.len(), 1);
assert_eq!(subs[0].url, "https://example.com/signed-hook");
}
#[tokio::test]
async fn h8b_unsubscribe_by_id_happy_path() {
let state = test_state();
let id = {
let lock = state.lock().await;
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "https://example.com/h",
events: "*",
secret: None,
namespace_filter: None,
agent_filter: None,
created_by: Some("alice"),
},
)
.unwrap()
};
let app = Router::new()
.route("/api/v1/subscriptions", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/subscriptions?id={id}"))
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["removed"], true);
let lock = state.lock().await;
assert!(crate::subscriptions::list(&lock.0).unwrap().is_empty());
}
#[tokio::test]
async fn h8b_unsubscribe_nonexistent_id_returns_removed_false() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions?id=does-not-exist")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["removed"], false);
}
#[tokio::test]
async fn h8b_unsubscribe_by_agent_and_namespace() {
let state = test_state();
{
let lock = state.lock().await;
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "http://localhost/_ns/alice/demo",
events: "*",
secret: None,
namespace_filter: Some("demo"),
agent_filter: Some("alice"),
created_by: Some("alice"),
},
)
.unwrap();
}
let app = Router::new()
.route("/api/v1/subscriptions", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions?namespace=demo")
.method("DELETE")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["removed"], true);
}
#[tokio::test]
async fn h8b_unsubscribe_missing_id_and_namespace_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscriptions", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.method("DELETE")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"]
.as_str()
.unwrap()
.contains("id or (agent_id, namespace)"),
);
}
#[tokio::test]
async fn h8b_list_subscriptions_returns_seeded_rows() {
let state = test_state();
{
let lock = state.lock().await;
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "https://example.com/a",
events: "*",
secret: None,
namespace_filter: Some("ns1"),
agent_filter: Some("alice"),
created_by: Some("alice"),
},
)
.unwrap();
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "https://example.com/b",
events: "memory.updated",
secret: None,
namespace_filter: Some("ns2"),
agent_filter: Some("bob"),
created_by: Some("bob"),
},
)
.unwrap();
}
let app = Router::new()
.route(
"/api/v1/subscriptions",
axum::routing::get(list_subscriptions),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
let subs = v["subscriptions"].as_array().unwrap();
assert_eq!(subs.len(), 2);
for s in subs {
assert!(s["namespace"].is_string());
assert!(s["namespace_filter"].is_string());
assert!(s["id"].is_string());
}
}
#[tokio::test]
async fn h8b_list_subscriptions_agent_id_filter_excludes_others() {
let state = test_state();
{
let lock = state.lock().await;
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "https://example.com/a",
events: "*",
secret: None,
namespace_filter: Some("ns1"),
agent_filter: Some("alice"),
created_by: Some("alice"),
},
)
.unwrap();
crate::subscriptions::insert(
&lock.0,
&crate::subscriptions::NewSubscription {
url: "https://example.com/b",
events: "*",
secret: None,
namespace_filter: Some("ns2"),
agent_filter: Some("bob"),
created_by: Some("bob"),
},
)
.unwrap();
}
let app = Router::new()
.route(
"/api/v1/subscriptions",
axum::routing::get(list_subscriptions),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions?agent_id=alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
assert_eq!(v["subscriptions"][0]["namespace"], "ns1");
}
#[tokio::test]
async fn h8b_notify_happy_path_creates_message() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"target_agent_id": "bob",
"title": "Hi bob",
"payload": "hello there",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["to"], "bob");
assert!(v["id"].as_str().is_some());
assert!(v["delivered_at"].as_str().is_some());
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("_messages/bob"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].title, "Hi bob");
}
#[tokio::test]
async fn h8b_notify_missing_target_agent_id_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"title": "stray",
"payload": "no target",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(
resp.status() == StatusCode::UNPROCESSABLE_ENTITY
|| resp.status() == StatusCode::BAD_REQUEST,
"expected 4xx for missing target_agent_id, got {}",
resp.status(),
);
}
#[tokio::test]
async fn h8b_notify_invalid_target_agent_id_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"target_agent_id": "bob with spaces",
"title": "Hi",
"payload": "hello",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn h8b_notify_oversized_payload_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let big = "a".repeat(65_537);
let body = serde_json::json!({
"target_agent_id": "bob",
"title": "huge",
"payload": big,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"].as_str().unwrap().contains("max"),
"expected size-limit error, got {:?}",
v["error"],
);
}
#[tokio::test]
async fn h8b_notify_accepts_content_alias_for_payload() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"target_agent_id": "bob",
"title": "alias",
"content": "via the content field",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn h8b_get_inbox_empty_returns_zero() {
let state = test_state();
let app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?agent_id=alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert_eq!(v["messages"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn h8b_get_inbox_returns_pending_after_notify() {
let state = test_state();
let notify_app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state.clone()));
let notify_body = serde_json::json!({
"target_agent_id": "bob",
"title": "ping",
"payload": "wake up",
});
let resp = notify_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "alice")
.body(Body::from(serde_json::to_vec(¬ify_body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let inbox_app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = inbox_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?agent_id=bob")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
let msg = &v["messages"][0];
assert_eq!(msg["title"], "ping");
let from = msg["from"].as_str().unwrap();
assert!(
from == "alice" || from.starts_with("ai:alice@"),
"unexpected sender: {from}",
);
assert_eq!(msg["read"], false);
}
#[tokio::test]
async fn h8b_get_inbox_unread_only_filter_excludes_read() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let unread = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "_messages/alice".into(),
title: "unread".into(),
content: "u".into(),
tags: vec!["_message".into()],
priority: 5,
confidence: 1.0,
source: "notify".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "bob"}),
};
let read = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "_messages/alice".into(),
title: "read".into(),
content: "r".into(),
tags: vec!["_message".into()],
priority: 5,
confidence: 1.0,
source: "notify".into(),
access_count: 5,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "bob"}),
};
db::insert(&lock.0, &unread).unwrap();
db::insert(&lock.0, &read).unwrap();
}
let app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?agent_id=alice&unread_only=true")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 1);
assert_eq!(v["messages"][0]["title"], "unread");
assert_eq!(v["unread_only"], true);
}
#[tokio::test]
async fn h8b_get_inbox_limit_clamps_returned_count() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for i in 0..3 {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Mid,
namespace: "_messages/alice".into(),
title: format!("msg-{i}"),
content: "c".into(),
tags: vec!["_message".into()],
priority: 5,
confidence: 1.0,
source: "notify".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "carol"}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?agent_id=alice&limit=2")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
}
#[tokio::test]
async fn h8b_get_inbox_invalid_agent_id_rejected() {
let state = test_state();
let app = Router::new()
.route("/api/v1/inbox", axum::routing::get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox?agent_id=bad%20agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn h8b_session_start_with_valid_agent_id_echoes() {
let state = test_state();
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({"agent_id": "alice"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["session_id"].as_str().is_some());
assert_eq!(v["agent_id"], "alice");
}
#[tokio::test]
async fn h8b_session_start_namespace_filter() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
for (ns, title) in [("target-ns", "in-scope"), ("other-ns", "out")] {
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: ns.into(),
title: title.into(),
content: "body".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "alice"}),
};
db::insert(&lock.0, &mem).unwrap();
}
}
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({"namespace": "target-ns", "limit": 5});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let mems = v["memories"].as_array().unwrap();
assert_eq!(mems.len(), 1);
assert_eq!(mems[0]["title"], "in-scope");
}
#[tokio::test]
async fn h8b_session_start_returns_session_id_without_agent() {
let state = test_state();
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let sid = v["session_id"].as_str().unwrap();
assert_eq!(sid.len(), 36);
assert!(v.get("agent_id").is_none() || v["agent_id"].is_null());
assert_eq!(v["mode"], "session_start");
}
#[tokio::test]
async fn h8b_session_start_preloads_recent_context() {
let state = test_state();
{
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "global".into(),
title: "preload-me".into(),
content: "context".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "alice"}),
};
db::insert(&lock.0, &mem).unwrap();
}
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body = serde_json::json!({"limit": 50});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let mems = v["memories"].as_array().unwrap();
assert!(
mems.iter().any(|m| m["title"] == "preload-me"),
"session_start must preload recent memories",
);
}
#[tokio::test]
async fn http_list_agents_empty_returns_zero_count() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_get(list_agents))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
assert_eq!(v["agents"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_list_agents_returns_registered_rows() {
let state = test_state();
{
let lock = state.lock().await;
db::register_agent(&lock.0, "alice", "human", &["read".into(), "write".into()])
.unwrap();
db::register_agent(&lock.0, "bob", "ai:claude-opus-4.7", &["recall".into()]).unwrap();
}
let app = Router::new()
.route("/api/v1/agents", axum_get(list_agents))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
let agents = v["agents"].as_array().unwrap();
let ids: Vec<&str> = agents
.iter()
.filter_map(|a| a["agent_id"].as_str())
.collect();
assert!(ids.contains(&"alice"));
assert!(ids.contains(&"bob"));
}
#[tokio::test]
async fn http_list_agents_includes_types_and_capabilities() {
let state = test_state();
{
let lock = state.lock().await;
db::register_agent(
&lock.0,
"alpha",
"ai:claude-opus-4.7",
&["read".into(), "store".into(), "recall".into()],
)
.unwrap();
}
let app = Router::new()
.route("/api/v1/agents", axum_get(list_agents))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let agents = v["agents"].as_array().unwrap();
assert_eq!(agents.len(), 1);
let a = &agents[0];
assert_eq!(a["agent_id"], "alpha");
assert_eq!(a["agent_type"], "ai:claude-opus-4.7");
let caps = a["capabilities"].as_array().unwrap();
assert_eq!(caps.len(), 3);
let cap_strs: Vec<&str> = caps.iter().filter_map(|c| c.as_str()).collect();
assert!(cap_strs.contains(&"read"));
assert!(cap_strs.contains(&"store"));
assert!(cap_strs.contains(&"recall"));
}
#[tokio::test]
async fn http_register_agent_happy_path_returns_created() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"agent_id": "alice",
"agent_type": "human",
"capabilities": ["read", "write"]
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["registered"], true);
assert_eq!(v["agent_id"], "alice");
assert_eq!(v["agent_type"], "human");
let lock = state.lock().await;
let agents = db::list_agents(&lock.0).unwrap();
assert_eq!(agents.len(), 1);
assert_eq!(agents[0].agent_id, "alice");
}
#[tokio::test]
async fn http_register_agent_missing_agent_type_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "alice"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert!(
resp.status().is_client_error(),
"expected 4xx for missing agent_type, got {}",
resp.status()
);
}
#[tokio::test]
async fn http_register_agent_invalid_agent_id_with_space_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "bad agent",
"agent_type": "human",
"capabilities": []
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_register_agent_duplicate_register_idempotent_preserves_registered_at() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"agent_id": "twice",
"agent_type": "human",
"capabilities": ["read"]
});
let r1 = app
.clone()
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r1.status(), StatusCode::CREATED);
let r2 = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(r2.status(), StatusCode::CREATED);
let lock = state.lock().await;
let agents = db::list_agents(&lock.0).unwrap();
let twice: Vec<_> = agents.iter().filter(|a| a.agent_id == "twice").collect();
assert_eq!(
twice.len(),
1,
"duplicate register must collapse to one row"
);
}
#[tokio::test]
async fn http_register_agent_capabilities_array_preserved() {
let state = test_state();
let app = Router::new()
.route("/api/v1/agents", axum_post(register_agent))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"agent_id": "capper",
"agent_type": "ai:claude-opus-4.7",
"capabilities": ["search", "store", "recall", "consolidate"]
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/agents")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let echoed = v["capabilities"].as_array().unwrap();
assert_eq!(echoed.len(), 4);
let lock = state.lock().await;
let agents = db::list_agents(&lock.0).unwrap();
let me = agents.iter().find(|a| a.agent_id == "capper").unwrap();
assert_eq!(me.capabilities.len(), 4);
assert!(me.capabilities.contains(&"search".to_string()));
assert!(me.capabilities.contains(&"store".to_string()));
assert!(me.capabilities.contains(&"recall".to_string()));
assert!(me.capabilities.contains(&"consolidate".to_string()));
}
#[tokio::test]
async fn http_list_pending_with_pending_actions_returns_them() {
use crate::models::GovernedAction;
let state = test_state();
{
let lock = state.lock().await;
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-a",
None,
"alice",
&serde_json::json!({"title": "first", "content": "c1"}),
)
.unwrap();
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-b",
None,
"bob",
&serde_json::json!({"title": "second", "content": "c2"}),
)
.unwrap();
}
let app = Router::new()
.route("/api/v1/pending", axum_get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
assert_eq!(v["pending"].as_array().unwrap().len(), 2);
}
#[tokio::test]
async fn http_list_pending_filters_by_status_pending() {
use crate::models::GovernedAction;
let state = test_state();
let kept_id = {
let lock = state.lock().await;
let id = db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-keep",
None,
"alice",
&serde_json::json!({"title": "stay", "content": "x"}),
)
.unwrap();
let other = db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-reject",
None,
"alice",
&serde_json::json!({"title": "out", "content": "x"}),
)
.unwrap();
db::decide_pending_action(&lock.0, &other, false, "alice").unwrap();
id
};
let app = Router::new()
.route("/api/v1/pending", axum_get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending?status=pending")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let items = v["pending"].as_array().unwrap();
assert_eq!(items.len(), 1);
assert_eq!(items[0]["id"], kept_id);
assert_eq!(items[0]["status"], "pending");
}
#[tokio::test]
async fn http_list_pending_filters_by_status_rejected() {
use crate::models::GovernedAction;
let state = test_state();
{
let lock = state.lock().await;
let id = db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-r",
None,
"alice",
&serde_json::json!({"title": "rejected", "content": "x"}),
)
.unwrap();
db::decide_pending_action(&lock.0, &id, false, "alice").unwrap();
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"ns-p",
None,
"alice",
&serde_json::json!({"title": "pending", "content": "x"}),
)
.unwrap();
}
let app = Router::new()
.route("/api/v1/pending", axum_get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending?status=rejected&limit=10")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let items = v["pending"].as_array().unwrap();
assert_eq!(items.len(), 1);
assert_eq!(items[0]["status"], "rejected");
}
#[tokio::test]
async fn http_list_pending_limit_clamped_to_1000() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending", axum_get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending?limit=99999")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_approve_pending_happy_path_executes_store() {
use crate::models::GovernedAction;
let state = test_state();
let now_rfc = Utc::now().to_rfc3339();
let pending_id = {
let lock = state.lock().await;
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"approve-ns",
None,
"alice",
&serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "approve-ns",
"title": "approved-store",
"content": "executed via approval",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now_rfc,
"updated_at": now_rfc,
"metadata": {}
}),
)
.unwrap()
};
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pending_id}/approve"))
.method("POST")
.header("x-agent-id", "approver-alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["approved"], true);
assert_eq!(v["executed"], true);
assert_eq!(v["decided_by"], "approver-alice");
let lock = state.lock().await;
let pa = db::get_pending_action(&lock.0, &pending_id)
.unwrap()
.unwrap();
assert_eq!(pa.status, "approved");
assert_eq!(pa.decided_by.as_deref(), Some("approver-alice"));
}
#[tokio::test]
async fn http_approve_pending_invalid_id_format_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending/bad%01id/approve")
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_approve_pending_already_approved_is_rejected() {
use crate::models::GovernedAction;
let state = test_state();
let pid = {
let lock = state.lock().await;
let id = db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"double-approve",
None,
"alice",
&serde_json::json!({
"tier": "long",
"namespace": "double-approve",
"title": "store",
"content": "x",
"tags": [], "priority": 5, "confidence": 1.0,
"source": "api", "metadata": {}
}),
)
.unwrap();
db::decide_pending_action(&lock.0, &id, true, "alice").unwrap();
id
};
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pid}/approve"))
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let err = v["error"].as_str().unwrap_or("");
assert!(
err.contains("already decided") || err.contains("rejected"),
"expected already-decided message, got {err}"
);
}
#[tokio::test]
async fn http_approve_pending_executor_records_decided_by() {
use crate::models::GovernedAction;
let state = test_state();
let now_rfc = Utc::now().to_rfc3339();
let pid = {
let lock = state.lock().await;
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"executor-ns",
None,
"requester-bob",
&serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "executor-ns",
"title": "e",
"content": "y",
"tags": [], "priority": 5, "confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now_rfc,
"updated_at": now_rfc,
"metadata": {}
}),
)
.unwrap()
};
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pid}/approve"))
.method("POST")
.header("x-agent-id", "executor-claude")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let pa = db::get_pending_action(&lock.0, &pid).unwrap().unwrap();
assert_eq!(pa.requested_by, "requester-bob");
assert_eq!(pa.decided_by.as_deref(), Some("executor-claude"));
assert_eq!(pa.status, "approved");
}
#[tokio::test]
async fn http_approve_pending_returns_memory_id_for_store_payload() {
use crate::models::GovernedAction;
let state = test_state();
let now_rfc = Utc::now().to_rfc3339();
let pid = {
let lock = state.lock().await;
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"executed-write",
None,
"alice",
&serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "executed-write",
"title": "executed-mem",
"content": "this exists after approval",
"tags": [], "priority": 5, "confidence": 1.0,
"source": "api",
"access_count": 0,
"created_at": now_rfc,
"updated_at": now_rfc,
"metadata": {}
}),
)
.unwrap()
};
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pid}/approve"))
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let mem_id = v["memory_id"].as_str().expect("memory_id present");
let lock = state.lock().await;
let mem = db::get(&lock.0, mem_id).unwrap().expect("memory exists");
assert_eq!(mem.title, "executed-mem");
assert_eq!(mem.namespace, "executed-write");
}
#[tokio::test]
async fn http_reject_pending_happy_path_marks_rejected_no_execution() {
use crate::models::GovernedAction;
let state = test_state();
let pid = {
let lock = state.lock().await;
db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"reject-ns",
None,
"alice",
&serde_json::json!({
"tier": "long",
"namespace": "reject-ns",
"title": "blocked",
"content": "must not be created",
"tags": [], "priority": 5, "confidence": 1.0,
"source": "api", "metadata": {}
}),
)
.unwrap()
};
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pid}/reject"))
.method("POST")
.header("x-agent-id", "rejector-alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["rejected"], true);
assert_eq!(v["decided_by"], "rejector-alice");
let lock = state.lock().await;
let pa = db::get_pending_action(&lock.0, &pid).unwrap().unwrap();
assert_eq!(pa.status, "rejected");
let rows = db::list(
&lock.0,
Some("reject-ns"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert!(
rows.is_empty(),
"rejection must not execute the queued payload"
);
}
#[tokio::test]
async fn http_reject_pending_already_rejected_returns_404() {
use crate::models::GovernedAction;
let state = test_state();
let pid = {
let lock = state.lock().await;
let id = db::queue_pending_action(
&lock.0,
GovernedAction::Store,
"double-reject",
None,
"alice",
&serde_json::json!({
"tier": "long",
"namespace": "double-reject",
"title": "x",
"content": "x",
"tags": [], "priority": 5, "confidence": 1.0,
"source": "api", "metadata": {}
}),
)
.unwrap();
db::decide_pending_action(&lock.0, &id, false, "alice").unwrap();
id
};
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{pid}/reject"))
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_reject_pending_invalid_id_format_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending/bad%01id/reject")
.method("POST")
.header("x-agent-id", "alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_consolidate_two_into_one_happy_path() {
let state = test_state();
let now = Utc::now().to_rfc3339();
let (id_a, id_b) = {
let lock = state.lock().await;
let mk = |title: &str| Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "merge-ns".into(),
title: title.into(),
content: format!("body for {title}"),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"agent_id": "alice"}),
};
let a = db::insert(&lock.0, &mk("draft-a")).unwrap();
let b = db::insert(&lock.0, &mk("draft-b")).unwrap();
(a, b)
};
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"ids": [id_a, id_b],
"title": "merged-result",
"summary": "a merge of two drafts",
"namespace": "merge-ns",
"tier": "long"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "consolidator")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["consolidated"], 2);
let new_id = v["id"].as_str().unwrap();
let lock = state.lock().await;
let merged = db::get(&lock.0, new_id).unwrap().unwrap();
assert_eq!(merged.title, "merged-result");
assert_eq!(merged.namespace, "merge-ns");
assert!(db::get(&lock.0, &id_a).unwrap().is_none());
assert!(db::get(&lock.0, &id_b).unwrap().is_none());
}
#[tokio::test]
async fn http_consolidate_single_id_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": [Uuid::new_v4().to_string()],
"title": "lone-merge",
"summary": "only one source",
"namespace": "merge-ns"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_consolidate_invalid_namespace_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": [Uuid::new_v4().to_string(), Uuid::new_v4().to_string()],
"title": "merge",
"summary": "x",
"namespace": "bad ns"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_consolidate_invalid_agent_id_400() {
let state = test_state();
let id_a = Uuid::new_v4().to_string();
let id_b = Uuid::new_v4().to_string();
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": [id_a, id_b],
"title": "merge",
"summary": "x",
"namespace": "merge-ns"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "bad agent id")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_consolidate_max_id_count_cap_exceeded_400() {
let state = test_state();
let ids: Vec<String> = (0..101).map(|_| Uuid::new_v4().to_string()).collect();
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": ids,
"title": "too-many",
"summary": "x",
"namespace": "merge-ns"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_consolidate_missing_source_500() {
let state = test_state();
let id_a = Uuid::new_v4().to_string();
let id_b = Uuid::new_v4().to_string();
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": [id_a, id_b],
"title": "merge",
"summary": "x",
"namespace": "merge-ns"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn http_contradictions_empty_no_pairs() {
let state = test_state();
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions?namespace=empty-ns")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["memories"].as_array().unwrap().len(), 0);
assert_eq!(v["links"].as_array().unwrap().len(), 0);
}
#[tokio::test]
async fn http_contradictions_synthesizes_links_for_same_title() {
let state = test_state();
let now = Utc::now().to_rfc3339();
{
let lock = state.lock().await;
let mk = |title: &str, content: &str| Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "contradict-ns".into(),
title: title.into(),
content: content.into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({"topic": "earth-shape"}),
};
db::insert(&lock.0, &mk("alice-says", "earth is round")).unwrap();
db::insert(&lock.0, &mk("bob-says", "earth is flat")).unwrap();
}
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions?namespace=contradict-ns&topic=earth-shape")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let memories = v["memories"].as_array().unwrap();
assert_eq!(memories.len(), 2);
let links = v["links"].as_array().unwrap();
assert!(links.iter().any(|l| {
l["relation"].as_str() == Some("contradicts")
&& l["synthesized"].as_bool() == Some(true)
}));
}
#[tokio::test]
async fn http_contradictions_namespace_filter_isolates_results() {
let state = test_state();
let now = Utc::now().to_rfc3339();
{
let lock = state.lock().await;
let mk = |ns: &str, content: &str| Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: ns.into(),
title: "shared-topic".into(),
content: content.into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "api".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now.clone(),
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mk("ns-iso-a", "first opinion")).unwrap();
db::insert(&lock.0, &mk("ns-iso-b", "different opinion")).unwrap();
}
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions?namespace=ns-iso-a")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let memories = v["memories"].as_array().unwrap();
assert_eq!(memories.len(), 1, "ns filter must isolate results");
assert_eq!(memories[0]["namespace"], "ns-iso-a");
}
#[tokio::test]
async fn http_contradictions_invalid_namespace_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions?namespace=bad%20ns")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_capabilities_returns_expected_shape() {
let state = test_state();
let app = Router::new()
.route("/api/v1/capabilities", axum_get(get_capabilities))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/capabilities")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v.get("tier").is_some(), "missing `tier`");
assert!(v.get("version").is_some(), "missing `version`");
assert!(v.get("features").is_some(), "missing `features`");
assert!(v.get("models").is_some(), "missing `models`");
assert_eq!(v["features"]["keyword_search"], true);
assert_eq!(v["features"]["semantic_search"], false);
assert_eq!(v["features"]["query_expansion"], false);
}
#[tokio::test]
async fn http_capabilities_v2_schema_includes_all_blocks() {
let state = test_state();
let app = Router::new()
.route("/api/v1/capabilities", axum_get(get_capabilities))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/capabilities")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["schema_version"], "2");
assert!(v["permissions"].is_object());
assert_eq!(v["permissions"]["mode"], "ask");
assert!(v["permissions"]["active_rules"].is_number());
assert!(v["permissions"]["rule_summary"].is_array());
assert!(v["hooks"].is_object());
assert!(v["hooks"]["registered_count"].is_number());
assert!(v["hooks"]["by_event"].is_object());
assert!(v["compaction"].is_object());
assert_eq!(v["compaction"]["enabled"], false);
assert!(v["approval"].is_object());
assert!(v["approval"]["pending_requests"].is_number());
assert_eq!(v["approval"]["default_timeout_seconds"], 30);
assert!(v["transcripts"].is_object());
assert_eq!(v["transcripts"]["enabled"], false);
}
#[tokio::test]
async fn http_capabilities_version_matches_pkg_version() {
let state = test_state();
let app = Router::new()
.route("/api/v1/capabilities", axum_get(get_capabilities))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/capabilities")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["version"], env!("CARGO_PKG_VERSION"));
assert_eq!(v["tier"], "keyword");
}
async fn h8d_spawn_mock_peer(
behaviour: H8dPeerBehaviour,
) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::net::TcpListener;
let count = Arc::new(AtomicUsize::new(0));
let count_for_peer = count.clone();
#[derive(Clone)]
struct PeerState {
count: Arc<AtomicUsize>,
behaviour: H8dPeerBehaviour,
}
async fn handler(
axum::extract::State(s): axum::extract::State<PeerState>,
Json(_body): Json<serde_json::Value>,
) -> (StatusCode, Json<serde_json::Value>) {
s.count.fetch_add(1, Ordering::Relaxed);
match s.behaviour {
H8dPeerBehaviour::Ack => (
StatusCode::OK,
Json(json!({"applied": 1, "noop": 0, "skipped": 0})),
),
H8dPeerBehaviour::Fail500 => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": "stub failure"})),
),
H8dPeerBehaviour::Fail503 => (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"error": "stub unavailable"})),
),
H8dPeerBehaviour::Fail400 => (
StatusCode::BAD_REQUEST,
Json(json!({"error": "stub bad request"})),
),
H8dPeerBehaviour::Hang => {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
(StatusCode::OK, Json(json!({"applied": 1})))
}
}
}
let app = Router::new()
.route("/api/v1/sync/push", axum_post(handler))
.with_state(PeerState {
count: count_for_peer,
behaviour,
});
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.ok();
});
(format!("http://{addr}"), count)
}
#[derive(Clone, Copy)]
enum H8dPeerBehaviour {
Ack,
Fail500,
Fail503,
Fail400,
Hang,
}
fn h8d_app_state_with_fed(
db: Db,
peer_urls: Vec<String>,
w: usize,
timeout_ms: u64,
) -> AppState {
let fed = crate::federation::FederationConfig::build(
w,
&peer_urls,
std::time::Duration::from_millis(timeout_ms),
None,
None,
None,
"ai:h8d-test".to_string(),
)
.unwrap()
.expect("federation must be built");
AppState {
db,
embedder: Arc::new(None),
vector_index: Arc::new(Mutex::new(None)),
federation: Arc::new(Some(fed)),
tier_config: Arc::new(crate::config::FeatureTier::Keyword.config()),
scoring: Arc::new(crate::config::ResolvedScoring::default()),
}
}
#[tokio::test]
async fn http_get_namespace_standard_qs_returns_standard_for_existing_ns() {
let state = test_state();
let app_state = test_app_state(state.clone());
let set_router = Router::new()
.route(
"/api/v1/namespaces/{ns}/standard",
axum_post(set_namespace_standard),
)
.with_state(app_state);
let resp = set_router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces/qs-existing/standard")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&json!({})).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let get_router = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::get(get_namespace_standard_qs),
)
.with_state(state);
let resp = get_router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=qs-existing")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "qs-existing");
assert!(v["standard_id"].is_string(), "standard_id must be set");
}
#[tokio::test]
async fn http_get_namespace_standard_qs_returns_null_for_missing_ns_record() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::get(get_namespace_standard_qs),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=qs-never-set")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "qs-never-set");
assert!(
v["standard_id"].is_null(),
"standard_id must be null for an unset namespace"
);
}
#[tokio::test]
async fn http_get_namespace_standard_qs_falls_through_to_list_on_missing_param() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::get(get_namespace_standard_qs),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["namespaces"].is_array(),
"fallthrough must produce the list shape, got {v:?}"
);
}
#[tokio::test]
async fn http_get_namespace_standard_qs_inherit_flag_returns_chain() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::get(get_namespace_standard_qs),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=child&inherit=true")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["chain"].is_array(), "inherit must surface the chain");
assert!(v["standards"].is_array());
}
#[tokio::test]
async fn http_get_namespace_standard_qs_invalid_namespace_returns_400() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::get(get_namespace_standard_qs),
)
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=bad%20ns")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_set_namespace_standard_qs_happy_path_creates_placeholder() {
let state = test_state();
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(test_app_state(state.clone()));
let body = json!({"namespace": "qs-set-happy"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "qs-set-happy");
assert_eq!(v["set"], true);
assert!(v["standard_id"].is_string());
}
#[tokio::test]
async fn http_set_namespace_standard_qs_missing_namespace_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(test_app_state(state));
let body = json!({"governance": {"approver": "human"}});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"].as_str().unwrap_or("").contains("namespace"),
"error must mention the missing namespace, got {v:?}"
);
}
#[tokio::test]
async fn http_set_namespace_standard_qs_invalid_governance_returns_400() {
let state = test_state();
let mem_id = {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: "qs-set-bad-policy".into(),
title: "anchor".into(),
content: "anchor".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(test_app_state(state));
let body = json!({
"namespace": "qs-set-bad-policy",
"id": mem_id,
"governance": {
"approver": {"consensus": 0},
"write": "approve",
"promote": "log",
"delete": "log"
}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_set_namespace_standard_qs_nested_standard_payload_works() {
let state = test_state();
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(test_app_state(state));
let body = json!({"standard": {"namespace": "qs-nested-ns"}});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "qs-nested-ns");
}
#[tokio::test]
async fn http_clear_namespace_standard_qs_happy_path_after_set() {
let state = test_state();
let app_state = test_app_state(state.clone());
let set_router = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state.clone());
let _ = set_router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-clear-happy"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
let clear_router = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::delete(clear_namespace_standard_qs),
)
.with_state(app_state);
let resp = clear_router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=qs-clear-happy")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "qs-clear-happy");
}
#[tokio::test]
async fn http_clear_namespace_standard_qs_idempotent_on_unset() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::delete(clear_namespace_standard_qs),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=qs-clear-noop")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_clear_namespace_standard_qs_missing_namespace_returns_400() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::delete(clear_namespace_standard_qs),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"].as_str().unwrap_or("").contains("namespace"),
"error must mention namespace, got {v:?}"
);
}
#[tokio::test]
async fn http_set_qs_fanout_503_when_all_peers_down() {
let state = test_state();
let (peer_url, _count) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-fed-down"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn http_set_qs_fanout_503_payload_shape_includes_quorum_fields() {
let state = test_state();
let (peer_url, _count) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-503-shape"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"], "quorum_not_met");
assert!(v["got"].as_u64().is_some(), "got must be a number");
assert!(v["needed"].as_u64().is_some(), "needed must be a number");
assert!(v["reason"].is_string(), "reason must be a string");
assert_eq!(v["needed"].as_u64().unwrap(), 2);
}
#[tokio::test]
async fn http_set_qs_fanout_503_includes_retry_after_header() {
let state = test_state();
let (peer_url, _count) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-503-retry-after"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let retry = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert_eq!(retry, "2", "503 must include Retry-After: 2");
}
#[tokio::test]
async fn http_set_qs_fanout_quorum_met_with_one_peer_down() {
let state = test_state();
let (peer_up, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Ack).await;
let (peer_down, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_up, peer_down], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-quorum-met"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_set_qs_fanout_quorum_not_met_strict_n_equals_w() {
let state = test_state();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-strict-quorum"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["needed"].as_u64().unwrap(), 2);
assert!(v["got"].as_u64().unwrap() < v["needed"].as_u64().unwrap());
}
#[tokio::test]
async fn http_set_qs_fanout_quorum_w_equals_one_any_success_writes_succeed() {
let state = test_state();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 1, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-w1-any"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_set_qs_fanout_503_when_peer_hangs_past_deadline() {
let state = test_state();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Hang).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 200);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-hang"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let reason = v["reason"].as_str().unwrap_or("");
assert!(
reason == "timeout" || reason == "unreachable",
"expected timeout/unreachable, got {reason:?}"
);
}
#[tokio::test]
async fn http_set_qs_fanout_503_when_peer_returns_503() {
let state = test_state();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail503).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-peer-503"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"], "quorum_not_met");
}
#[tokio::test]
async fn http_set_qs_fanout_503_when_peer_returns_4xx() {
let state = test_state();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail400).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-peer-400"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn http_set_qs_fanout_503_partition_minority_fails() {
let state = test_state();
let (up, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Ack).await;
let (down1, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let (down2, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![up, down1, down2], 3, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-minority"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["needed"].as_u64().unwrap(), 3);
assert!(v["got"].as_u64().unwrap() < 3);
}
#[tokio::test]
async fn http_set_qs_fanout_majority_tolerates_minority_partition() {
let state = test_state();
let (up1, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Ack).await;
let (up2, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Ack).await;
let (down, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![up1, up2, down], 3, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-majority"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_clear_qs_fanout_503_when_peer_down() {
let state = test_state();
let local_app_state = test_app_state(state.clone());
let set_router = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(local_app_state);
let _ = set_router
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-clear-fed"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
let (peer_url, _) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route(
"/api/v1/namespaces",
axum::routing::delete(clear_namespace_standard_qs),
)
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces?namespace=qs-clear-fed")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
let retry = resp
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.unwrap_or("");
assert_eq!(retry, "2", "clear 503 must include Retry-After: 2");
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["error"], "quorum_not_met");
}
#[tokio::test]
async fn http_set_qs_fanout_no_federation_returns_201_without_peers() {
let state = test_state();
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-no-fed"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_set_qs_fanout_peer_called_at_least_once_on_quorum_failure() {
use std::sync::atomic::Ordering;
let state = test_state();
let (peer_url, count) = h8d_spawn_mock_peer(H8dPeerBehaviour::Fail500).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-fanout-attempt"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
for _ in 0..50 {
if count.load(Ordering::Relaxed) >= 1 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(
count.load(Ordering::Relaxed) >= 1,
"leader must have attempted the fanout POST at least once"
);
}
#[tokio::test]
async fn http_set_qs_fanout_peer_receives_post_on_happy_path() {
use std::sync::atomic::Ordering;
let state = test_state();
let (peer_url, count) = h8d_spawn_mock_peer(H8dPeerBehaviour::Ack).await;
let app_state = h8d_app_state_with_fed(state, vec![peer_url], 2, 1500);
let app = Router::new()
.route("/api/v1/namespaces", axum_post(set_namespace_standard_qs))
.with_state(app_state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(
serde_json::to_vec(&json!({"namespace": "qs-fanout-happy"})).unwrap(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
for _ in 0..50 {
if count.load(Ordering::Relaxed) >= 1 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(count.load(Ordering::Relaxed) >= 1);
}
#[test]
fn percent_decode_lossy_passes_through_plain_ascii() {
let s = percent_decode_lossy("hello-world_123");
assert_eq!(s, "hello-world_123");
}
#[test]
fn percent_decode_lossy_decodes_basic_escape() {
let s = percent_decode_lossy("a%20b");
assert_eq!(s, "a b");
}
#[test]
fn percent_decode_lossy_decodes_plus_and_ampersand() {
let s = percent_decode_lossy("a%2Bb%26c");
assert_eq!(s, "a+b&c");
}
#[test]
fn percent_decode_lossy_handles_invalid_hex_passthrough() {
let s = percent_decode_lossy("a%ZZb");
assert_eq!(s, "a%ZZb");
}
#[test]
fn percent_decode_lossy_handles_truncated_escape() {
let s = percent_decode_lossy("a%2");
assert_eq!(s, "a%2");
let s2 = percent_decode_lossy("%");
assert_eq!(s2, "%");
}
#[test]
fn percent_decode_lossy_decodes_full_byte_range() {
let s = percent_decode_lossy("%41%42%43");
assert_eq!(s, "ABC");
}
#[test]
fn percent_decode_lossy_empty_input_returns_empty() {
let s = percent_decode_lossy("");
assert_eq!(s, "");
}
#[test]
fn constant_time_eq_returns_true_for_equal_bytes() {
assert!(constant_time_eq(b"hello", b"hello"));
assert!(constant_time_eq(b"", b""));
}
#[test]
fn constant_time_eq_returns_false_for_different_bytes() {
assert!(!constant_time_eq(b"hello", b"world"));
}
#[test]
fn constant_time_eq_returns_false_for_different_lengths() {
assert!(!constant_time_eq(b"a", b"ab"));
assert!(!constant_time_eq(b"abc", b""));
}
#[test]
fn constant_time_eq_compares_high_bytes_correctly() {
let a = [0x80u8, 0x81, 0x82, 0xFF];
let b = [0x80u8, 0x81, 0x82, 0xFF];
assert!(constant_time_eq(&a, &b));
let c = [0x80u8, 0x81, 0x82, 0xFE];
assert!(!constant_time_eq(&a, &c));
}
#[tokio::test]
async fn api_key_query_param_with_percent_encoded_chars_matches() {
let app = auth_app(Some("a+b"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?api_key=a%2Bb")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_query_param_wrong_value_rejected() {
let app = auth_app(Some("secret"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?api_key=wrong")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_query_param_with_other_pairs_still_matches() {
let app = auth_app(Some("secret"));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?other=val&api_key=secret&trailing=x")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_header_with_invalid_utf8_falls_through() {
let app = auth_app(Some("secret"));
let bytes = [0x80u8, 0x81u8];
let req = axum::http::Request::builder()
.uri("/api/v1/memories")
.header(
"x-api-key",
axum::http::HeaderValue::from_bytes(&bytes).unwrap(),
)
.body(Body::empty())
.unwrap();
let resp = app.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn http_health_route_returns_200_with_status_ok() {
let state = test_state();
let app = Router::new()
.route("/api/v1/health", axum_get(health))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/health")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["status"], "ok");
assert_eq!(v["service"], "ai-memory");
assert_eq!(v["embedder_ready"], false);
assert_eq!(v["federation_enabled"], false);
}
#[tokio::test]
async fn http_prometheus_metrics_returns_text_body() {
let state = test_state();
let app = Router::new()
.route("/api/v1/metrics", axum_get(prometheus_metrics))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/metrics")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
assert!(!bytes.is_empty());
}
#[tokio::test]
async fn http_list_namespaces_returns_seeded_namespaces() {
let state = test_state();
let _ = insert_test_memory(&state, "ns-foo", "t1").await;
let _ = insert_test_memory(&state, "ns-bar", "t2").await;
let app = Router::new()
.route("/api/v1/namespaces", axum_get(list_namespaces))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/namespaces")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let ns = v["namespaces"].as_array().expect("namespaces array");
assert!(!ns.is_empty());
}
#[tokio::test]
async fn http_get_taxonomy_no_prefix_returns_tree() {
let state = test_state();
let _ = insert_test_memory(&state, "tax/a", "t1").await;
let _ = insert_test_memory(&state, "tax/b", "t2").await;
let app = Router::new()
.route("/api/v1/taxonomy", axum_get(get_taxonomy))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/taxonomy")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["tree"].is_array() || v["tree"].is_object());
}
#[tokio::test]
async fn http_get_taxonomy_invalid_prefix_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/taxonomy", axum_get(get_taxonomy))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/taxonomy?prefix=foo%2F%2Fbar")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_get_taxonomy_with_depth_and_limit() {
let state = test_state();
let _ = insert_test_memory(&state, "tax2/a/b", "t").await;
let app = Router::new()
.route("/api/v1/taxonomy", axum_get(get_taxonomy))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/taxonomy?prefix=tax2&depth=4&limit=100")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_get_memory_invalid_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}", axum_get(get_memory))
.with_state(state);
let big = "a".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{big}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_get_memory_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}", axum_get(get_memory))
.with_state(state);
let id = "deadbeefdeadbeefdeadbeefdeadbeef";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_get_memory_after_insert_returns_payload() {
let state = test_state();
let id = insert_test_memory(&state, "ns-get", "t-get").await;
let app = Router::new()
.route("/api/v1/memories/{id}", axum_get(get_memory))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["memory"]["id"], id);
assert!(v["links"].is_array());
}
#[tokio::test]
async fn http_delete_memory_invalid_id_returns_400() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let big = "b".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{big}"))
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_delete_memory_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let id = "cafebabecafebabecafebabecafebabe";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_delete_memory_happy_path_returns_deleted_true() {
let state = test_state();
let id = insert_test_memory(&state, "ns-del", "t-del").await;
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], true);
}
#[tokio::test]
async fn http_delete_memory_invalid_x_agent_id_returns_400() {
let state = test_state();
let id = insert_test_memory(&state, "ns-del-bad", "t").await;
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("DELETE")
.header("x-agent-id", "bad agent id")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_promote_memory_invalid_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}/promote", axum_post(promote_memory))
.with_state(test_app_state(state));
let big = "p".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{big}/promote"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_promote_memory_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}/promote", axum_post(promote_memory))
.with_state(test_app_state(state));
let id = "facefacefacefacefacefacefaceface";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}/promote"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_promote_memory_happy_path_clears_expires_at() {
let state = test_state();
let id = {
let lock = state.lock().await;
let now = Utc::now();
let mem = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Short,
namespace: "ns-promote".into(),
title: "to-promote".into(),
content: "content".into(),
tags: vec![],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
last_accessed_at: None,
expires_at: Some((now + Duration::seconds(3600)).to_rfc3339()),
metadata: serde_json::json!({}),
};
db::insert(&lock.0, &mem).unwrap()
};
let app = Router::new()
.route("/api/v1/memories/{id}/promote", axum_post(promote_memory))
.with_state(test_app_state(state.clone()));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}/promote"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let m = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(m.tier, Tier::Long);
assert!(m.expires_at.is_none());
}
#[tokio::test]
async fn http_update_memory_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state));
let id = "1234567812345678123456781234567a";
let body = serde_json::json!({"title": "new title"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_update_memory_happy_path_returns_updated_payload() {
let state = test_state();
let id = insert_test_memory(&state, "ns-upd", "old title").await;
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"title": "new title", "content": "new content"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let lock = state.lock().await;
let m = db::get(&lock.0, &id).unwrap().unwrap();
assert_eq!(m.title, "new title");
assert_eq!(m.content, "new content");
}
#[tokio::test]
async fn http_create_link_happy_path_returns_201() {
let state = test_state();
let src = insert_test_memory(&state, "ns-link", "src").await;
let tgt = insert_test_memory(&state, "ns-link", "tgt").await;
let app = Router::new()
.route("/api/v1/links", axum_post(create_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": src,
"target_id": tgt,
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["linked"], true);
}
#[tokio::test]
async fn http_create_link_invalid_link_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/links", axum_post(create_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": "abc",
"target_id": "abc",
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_get_links_invalid_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/{id}/links", axum_get(get_links))
.with_state(state);
let big = "x".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{big}/links"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_get_links_after_create_returns_link() {
let state = test_state();
let src = insert_test_memory(&state, "ns-getlinks", "src").await;
let tgt = insert_test_memory(&state, "ns-getlinks", "tgt").await;
{
let lock = state.lock().await;
db::create_link(&lock.0, &src, &tgt, "related_to").unwrap();
}
let app = Router::new()
.route("/api/v1/memories/{id}/links", axum_get(get_links))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{src}/links"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let links = v["links"].as_array().expect("links array");
assert!(!links.is_empty());
}
#[tokio::test]
async fn http_delete_link_after_create_returns_deleted_true() {
let state = test_state();
let src = insert_test_memory(&state, "ns-dellink", "src").await;
let tgt = insert_test_memory(&state, "ns-dellink", "tgt").await;
{
let lock = state.lock().await;
db::create_link(&lock.0, &src, &tgt, "related_to").unwrap();
}
let app = Router::new()
.route("/api/v1/links", axum::routing::delete(delete_link))
.with_state(test_app_state(state));
let body = serde_json::json!({
"source_id": src,
"target_id": tgt,
"relation": "related_to",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/links")
.method("DELETE")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], true);
}
#[tokio::test]
async fn http_get_stats_with_data_returns_total() {
let state = test_state();
let _ = insert_test_memory(&state, "ns-stats", "t1").await;
let _ = insert_test_memory(&state, "ns-stats", "t2").await;
let app = Router::new()
.route("/api/v1/stats", axum_get(get_stats))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/stats")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["total"], 2);
}
#[tokio::test]
async fn http_export_memories_with_data_returns_count() {
let state = test_state();
let _ = insert_test_memory(&state, "ns-export", "t1").await;
let _ = insert_test_memory(&state, "ns-export", "t2").await;
let app = Router::new()
.route("/api/v1/export", axum_get(export_memories))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/export")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 256 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 2);
assert!(v["exported_at"].is_string());
}
#[tokio::test]
async fn http_import_memories_inserts_valid_rows() {
let state = test_state();
let app = Router::new()
.route("/api/v1/import", axum_post(import_memories))
.with_state(state);
let now = Utc::now().to_rfc3339();
let mem = serde_json::json!({
"id": Uuid::new_v4().to_string(),
"tier": "long",
"namespace": "imported",
"title": "imported-row",
"content": "imported content",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "import",
"access_count": 0,
"created_at": now,
"updated_at": now,
"last_accessed_at": null,
"expires_at": null,
"metadata": {},
});
let body = serde_json::json!({"memories": [mem]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/import")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["imported"], 1);
}
#[tokio::test]
async fn http_recall_get_invalid_as_agent_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/recall", axum_get(recall_memories_get))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/recall?context=hello&as_agent=bad%20agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_recall_post_invalid_as_agent_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({"context": "x", "as_agent": "bad agent"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_recall_post_zero_budget_tokens_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/recall", axum_post(recall_memories_post))
.with_state(test_app_state(state));
let body = serde_json::json!({"context": "x", "budget_tokens": 0});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/recall")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_search_invalid_as_agent_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/search", axum_get(search_memories))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/search?q=hello&as_agent=bad%20agent")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_forget_memories_with_nothing_to_match_returns_zero() {
let state = test_state();
let app = Router::new()
.route("/api/v1/forget", axum_post(forget_memories))
.with_state(state);
let body = serde_json::json!({"namespace": "no-such-ns"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/forget")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["deleted"], 0);
}
#[tokio::test]
async fn http_run_gc_after_insert_returns_zero_when_nothing_expired() {
let state = test_state();
let _ = insert_test_memory(&state, "gc-ns", "title").await;
let app = Router::new()
.route("/api/v1/gc", axum_post(run_gc))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/gc")
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["expired_deleted"], 0);
}
#[tokio::test]
async fn http_list_pending_default_limit_returns_count_zero_for_empty() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending", axum_get(list_pending))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/pending")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["count"], 0);
}
#[tokio::test]
async fn http_restore_archive_invalid_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let big = "r".repeat(200);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{big}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_restore_archive_unknown_id_returns_404() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let id = "0123456701234567012345670123456a";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn http_restore_archive_happy_path_returns_restored_true() {
let state = test_state();
let id = insert_test_memory(&state, "ns-restore", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive/{id}/restore", axum_post(restore_archive))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/archive/{id}/restore"))
.method("POST")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["restored"], true);
}
#[tokio::test]
async fn http_entity_get_by_alias_with_namespace_filter_returns_found_false() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities/by_alias", axum_get(entity_get_by_alias))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities/by_alias?alias=Acme&namespace=corp")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["found"], false);
}
#[tokio::test]
async fn http_kg_timeline_with_valid_since_and_until_succeeds() {
let state = test_state();
let id = insert_test_memory(&state, "kg-tl", "src").await;
let app = Router::new()
.route("/api/v1/kg/timeline", axum_get(kg_timeline))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!(
"/api/v1/kg/timeline?source_id={id}&since=2020-01-01T00:00:00Z&until=2030-01-01T00:00:00Z&limit=100"
))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_session_start_with_namespace_returns_session_id() {
let state = test_state();
let _ = insert_test_memory(&state, "session-ns", "row").await;
let app = Router::new()
.route("/api/v1/session/start", axum_post(session_start))
.with_state(state);
let body =
serde_json::json!({"namespace": "session-ns", "limit": 5, "agent_id": "ai:tester"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/session/start")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["session_id"].is_string());
assert_eq!(v["agent_id"], "ai:tester");
}
#[tokio::test]
async fn http_notify_missing_payload_and_content_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"target_agent_id": "ai:bob",
"title": "ping",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("x-agent-id", "ai:alice")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_notify_with_payload_field_returns_201() {
let state = test_state();
{
let lock = state.lock().await;
db::register_agent(&lock.0, "ai:alice", "ai:human", &[]).unwrap();
db::register_agent(&lock.0, "ai:bob", "ai:human", &[]).unwrap();
}
let app = Router::new()
.route("/api/v1/notify", axum_post(notify))
.with_state(test_app_state(state));
let body = serde_json::json!({
"target_agent_id": "ai:bob",
"title": "ping",
"payload": "hi bob",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/notify")
.method("POST")
.header("x-agent-id", "ai:alice")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_subscribe_missing_url_and_namespace_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscribe", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({"agent_id": "ai:alice"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_subscribe_with_namespace_synthesizes_loopback_url_and_returns_201() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscribe", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({"agent_id": "ai:alice", "namespace": "team/alice"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["namespace"], "team/alice");
assert_eq!(v["agent_id"], "ai:alice");
}
#[tokio::test]
async fn http_unsubscribe_missing_id_and_namespace_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscribe", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("DELETE")
.header("x-agent-id", "ai:alice")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_unsubscribe_by_agent_namespace_after_subscribe_returns_removed() {
let state = test_state();
let sub_app = Router::new()
.route("/api/v1/subscribe", axum_post(subscribe))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"agent_id": "ai:alice", "namespace": "team/alice"});
let resp = sub_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let app = Router::new()
.route("/api/v1/subscribe", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe?agent_id=ai:alice&namespace=team/alice")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["removed"], true);
}
#[tokio::test]
async fn http_list_subscriptions_returns_subscription_rows() {
let state = test_state();
let sub_app = Router::new()
.route("/api/v1/subscribe", axum_post(subscribe))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({"agent_id": "ai:carol", "namespace": "team/carol"});
let resp = sub_app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let app = Router::new()
.route("/api/v1/subscriptions", axum_get(list_subscriptions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscriptions")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["count"].as_u64().unwrap() >= 1);
}
#[tokio::test]
async fn http_kg_query_after_create_link_returns_node() {
let state = test_state();
let src = insert_test_memory(&state, "kg-q", "src").await;
let tgt = insert_test_memory(&state, "kg-q", "tgt").await;
{
let lock = state.lock().await;
db::create_link(&lock.0, &src, &tgt, "related_to").unwrap();
}
let app = Router::new()
.route("/api/v1/kg/query", axum_post(kg_query))
.with_state(state);
let body = serde_json::json!({"source_id": src, "max_depth": 1, "limit": 10});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/query")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["source_id"], src);
let mems = v["memories"].as_array().expect("memories array");
assert!(!mems.is_empty());
}
#[tokio::test]
async fn http_kg_invalidate_round_trip_marks_link() {
let state = test_state();
let src = insert_test_memory(&state, "kg-inv", "src").await;
let tgt = insert_test_memory(&state, "kg-inv", "tgt").await;
{
let lock = state.lock().await;
db::create_link(&lock.0, &src, &tgt, "related_to").unwrap();
}
let app = Router::new()
.route("/api/v1/kg/invalidate", axum_post(kg_invalidate))
.with_state(state);
let body = serde_json::json!({
"source_id": src,
"target_id": tgt,
"relation": "related_to",
"valid_until": "2030-01-01T00:00:00Z",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/kg/invalidate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["found"], true);
}
#[tokio::test]
async fn http_list_archive_returns_archived_rows() {
let state = test_state();
let id = insert_test_memory(&state, "ns-archive", "row").await;
{
let lock = state.lock().await;
db::archive_memory(&lock.0, &id, Some("test")).unwrap();
}
let app = Router::new()
.route("/api/v1/archive", axum_get(list_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive?namespace=ns-archive&limit=10&offset=0")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["count"].as_u64().unwrap() >= 1);
}
#[tokio::test]
async fn http_archive_by_ids_with_explicit_reason_records_it() {
let state = test_state();
let id = insert_test_memory(&state, "ns-arch", "row").await;
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let body = serde_json::json!({"ids": [id], "reason": "user requested"});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["reason"], "user requested");
assert_eq!(v["count"], 1);
}
fn over_max_string_vec(n: usize) -> Vec<String> {
(0..n).map(|i| format!("id-{i:040}")).collect()
}
#[tokio::test]
async fn http_sync_push_oversize_deletions_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"deletions": over_max_string_vec(MAX_BULK_SIZE + 1),
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"]
.as_str()
.unwrap()
.contains("deletions per request"),
"{v:?}"
);
}
#[tokio::test]
async fn http_sync_push_oversize_archives_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"archives": over_max_string_vec(MAX_BULK_SIZE + 1),
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("archives"));
}
#[tokio::test]
async fn http_sync_push_oversize_restores_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"restores": over_max_string_vec(MAX_BULK_SIZE + 1),
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("restores"));
}
#[tokio::test]
async fn http_sync_push_oversize_namespace_meta_clears_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"namespace_meta_clears": over_max_string_vec(MAX_BULK_SIZE + 1),
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(
v["error"]
.as_str()
.unwrap()
.contains("namespace_meta_clears")
);
}
#[tokio::test]
async fn http_sync_push_invalid_sender_agent_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "bad agent id",
"memories": [],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("sender_agent_id"));
}
#[tokio::test]
async fn http_sync_push_invalid_x_agent_id_header_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "bad agent id")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_sync_push_pending_invalid_id_skipped() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let bad_id = "x".repeat(200); let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"pendings": [{
"id": bad_id,
"action_type": "store",
"memory_id": null,
"namespace": "ns",
"payload": {},
"requested_by": "ai:peer",
"requested_at": "2024-01-01T00:00:00Z",
"status": "pending",
"approvals": [],
}],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["skipped"], 1);
assert_eq!(v["pendings_applied"], 0);
}
#[tokio::test]
async fn http_sync_push_links_invalid_id_skipped() {
let state = test_state();
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"links": [{
"source_id": "abc",
"target_id": "abc",
"relation": "related_to",
"created_at": "2024-01-01T00:00:00Z",
}],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["skipped"], 1);
assert_eq!(v["links_applied"], 0);
}
#[tokio::test]
async fn http_sync_push_dry_run_links_no_apply() {
let state = test_state();
let src = insert_test_memory(&state, "dryrun-links", "src").await;
let tgt = insert_test_memory(&state, "dryrun-links", "tgt").await;
let app = Router::new()
.route("/api/v1/sync/push", axum_post(sync_push))
.with_state(test_app_state(state));
let body = serde_json::json!({
"sender_agent_id": "ai:peer",
"memories": [],
"links": [{
"source_id": src,
"target_id": tgt,
"relation": "related_to",
"created_at": "2024-01-01T00:00:00Z",
}],
"dry_run": true,
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/sync/push")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["links_applied"], 0);
assert_eq!(v["dry_run"], true);
}
#[tokio::test]
async fn http_consolidate_invalid_title_returns_400() {
let state = test_state();
let id1 = insert_test_memory(&state, "ns-cons", "a").await;
let id2 = insert_test_memory(&state, "ns-cons", "b").await;
let app = Router::new()
.route("/api/v1/consolidate", axum_post(consolidate_memories))
.with_state(test_app_state(state));
let body = serde_json::json!({
"ids": [id1, id2],
"title": "",
"summary": "Summary text",
"namespace": "ns-cons",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/consolidate")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "ai:tester")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_bulk_create_zero_body_returns_zero_created() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories/bulk", axum_post(bulk_create))
.with_state(test_app_state(state));
let body: Vec<serde_json::Value> = Vec::new();
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories/bulk")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], 0);
}
#[tokio::test]
async fn http_entity_register_with_x_agent_id_header_succeeds() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "Acme Inc",
"namespace": "corp",
"aliases": ["acme", "ACME"],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "ai:tester")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["created"], true);
assert_eq!(v["canonical_name"], "Acme Inc");
}
#[tokio::test]
async fn http_get_inbox_without_caller_uses_anonymous_default() {
let state = test_state();
let app = Router::new()
.route("/api/v1/inbox", axum_get(get_inbox))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/inbox")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_approve_pending_with_bad_header_agent_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/approve", axum_post(approve_pending))
.with_state(test_app_state(state));
let id = "abcdef0123456789abcdef0123456789";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{id}/approve"))
.method("POST")
.header("x-agent-id", "bad agent id")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_reject_pending_with_bad_header_agent_id_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/pending/{id}/reject", axum_post(reject_pending))
.with_state(test_app_state(state));
let id = "abcdef0123456789abcdef0123456789";
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/pending/{id}/reject"))
.method("POST")
.header("x-agent-id", "bad agent id")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_create_memory_invalid_x_agent_id_header_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "t",
"content": "c",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {}
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "bad agent id")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("agent_id"));
}
#[tokio::test]
async fn http_create_memory_invalid_scope_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "test",
"title": "t",
"content": "c",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {},
"scope": "not-a-valid-scope-token"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_list_memories_invalid_agent_id_filter_returns_400() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_get(list_memories))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories?agent_id=bad%20id")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_check_duplicate_blank_namespace_treated_as_none() {
let state = test_state();
let app = Router::new()
.route("/api/v1/check_duplicate", axum_post(check_duplicate))
.with_state(test_app_state(state));
let body = serde_json::json!({"title": "t", "content": "c", "namespace": " "});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/check_duplicate")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn http_archive_by_ids_with_no_reason_defaults_to_archive() {
let state = test_state();
let id = insert_test_memory(&state, "ns-arch-default", "row").await;
let app = Router::new()
.route("/api/v1/archive", axum_post(archive_by_ids))
.with_state(test_app_state(state));
let body = serde_json::json!({"ids": [id]});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["reason"], "archive");
}
async fn seed_governance_policy(state: &Db, ns: &str, policy: serde_json::Value) {
let lock = state.lock().await;
let now = Utc::now().to_rfc3339();
let standard = Memory {
id: Uuid::new_v4().to_string(),
tier: Tier::Long,
namespace: ns.into(),
title: format!("_standard:{ns}"),
content: format!("standard for {ns}"),
tags: vec!["_namespace_standard".to_string()],
priority: 5,
confidence: 1.0,
source: "test".into(),
access_count: 0,
created_at: now.clone(),
updated_at: now,
last_accessed_at: None,
expires_at: None,
metadata: serde_json::json!({
"agent_id": "ai:owner",
"governance": policy,
}),
};
let standard_id = db::insert(&lock.0, &standard).unwrap();
db::set_namespace_standard(&lock.0, ns, &standard_id, None).unwrap();
}
#[tokio::test]
async fn http_create_memory_governance_pending_returns_202() {
let state = test_state();
seed_governance_policy(
&state,
"gov-create",
serde_json::json!({
"write": "approve",
"delete": "owner",
"promote": "any",
"approver": "human",
}),
)
.await;
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "gov-create",
"title": "queued",
"content": "should be queued, not stored",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {},
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "ai:caller")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["status"], "pending");
assert_eq!(v["action"], "store");
assert!(v["pending_id"].is_string());
}
#[tokio::test]
async fn http_create_memory_governance_deny_returns_403() {
let state = test_state();
seed_governance_policy(
&state,
"gov-deny",
serde_json::json!({"write": "registered", "approver": "human"}),
)
.await;
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "gov-deny",
"title": "rejected",
"content": "rejected content",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {},
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.header("x-agent-id", "ai:unregistered")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert!(v["error"].as_str().unwrap().contains("governance"));
}
#[tokio::test]
async fn http_delete_memory_governance_pending_returns_202() {
let state = test_state();
seed_governance_policy(
&state,
"gov-delete",
serde_json::json!({
"write": "any",
"delete": "approve",
"promote": "any",
"approver": "human",
}),
)
.await;
let id = insert_test_memory(&state, "gov-delete", "to-delete").await;
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("DELETE")
.header("x-agent-id", "ai:caller")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["status"], "pending");
assert_eq!(v["action"], "delete");
assert_eq!(v["memory_id"], id);
}
#[tokio::test]
async fn http_delete_memory_governance_deny_returns_403() {
let state = test_state();
seed_governance_policy(
&state,
"gov-delete-deny",
serde_json::json!({"write": "any", "delete": "owner", "approver": "human"}),
)
.await;
let id = insert_test_memory(&state, "gov-delete-deny", "row").await;
let app = Router::new()
.route(
"/api/v1/memories/{id}",
axum::routing::delete(delete_memory),
)
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("DELETE")
.header("x-agent-id", "ai:other")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn http_promote_memory_governance_pending_returns_202() {
let state = test_state();
seed_governance_policy(
&state,
"gov-promote",
serde_json::json!({
"write": "any",
"delete": "any",
"promote": "approve",
"approver": "human",
}),
)
.await;
let id = insert_test_memory(&state, "gov-promote", "to-promote").await;
let app = Router::new()
.route("/api/v1/memories/{id}/promote", axum_post(promote_memory))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}/promote"))
.method("POST")
.header("x-agent-id", "ai:caller")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::ACCEPTED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["status"], "pending");
assert_eq!(v["action"], "promote");
assert_eq!(v["memory_id"], id);
}
#[tokio::test]
async fn http_create_memory_with_top_level_scope_succeeds() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state));
let body = serde_json::json!({
"tier": "long",
"namespace": "scoped",
"title": "with scope",
"content": "scoped content",
"tags": [],
"priority": 5,
"confidence": 1.0,
"source": "api",
"metadata": {},
"scope": "private"
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_create_memory_clamps_extreme_priority_to_range() {
let state = test_state();
let app = Router::new()
.route("/api/v1/memories", axum_post(create_memory))
.with_state(test_app_state(state.clone()));
let body = serde_json::json!({
"tier": "long",
"namespace": "clamp",
"title": "clamp",
"content": "c",
"tags": [],
"priority": 10,
"confidence": 1.0,
"source": "api",
"metadata": {},
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/memories")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let lock = state.lock().await;
let rows = db::list(
&lock.0,
Some("clamp"),
None,
10,
0,
None,
None,
None,
None,
None,
)
.unwrap();
assert_eq!(rows[0].priority, 10);
}
#[tokio::test]
async fn http_update_memory_with_oversized_title_returns_400() {
let state = test_state();
let id = insert_test_memory(&state, "ns-bigtitle", "old").await;
let app = Router::new()
.route("/api/v1/memories/{id}", axum::routing::put(update_memory))
.with_state(test_app_state(state));
let big_title = "T".repeat(10_000);
let body = serde_json::json!({"title": big_title});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri(format!("/api/v1/memories/{id}"))
.method("PUT")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn http_purge_archive_no_query_returns_purged_zero_for_empty_archive() {
let state = test_state();
let app = Router::new()
.route("/api/v1/archive", axum::routing::delete(purge_archive))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/archive")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["purged"], 0);
}
#[tokio::test]
async fn http_contradictions_topic_only_returns_ok_empty() {
let state = test_state();
let app = Router::new()
.route("/api/v1/contradictions", axum_get(detect_contradictions))
.with_state(state);
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/contradictions?topic=missing-topic")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test]
async fn http_entity_register_aliases_with_blanks_filtered() {
let state = test_state();
let app = Router::new()
.route("/api/v1/entities", axum_post(entity_register))
.with_state(state);
let body = serde_json::json!({
"canonical_name": "Globex",
"namespace": "corp2",
"aliases": ["", "globex", " ", "GLOBEX"],
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/entities")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[tokio::test]
async fn http_subscribe_with_explicit_url_succeeds() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscribe", axum_post(subscribe))
.with_state(test_app_state(state));
let body = serde_json::json!({
"agent_id": "ai:webhook-user",
"url": "http://localhost:9999/webhook",
"events": "store",
"secret": "shhh",
"namespace_filter": "team",
});
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(serde_json::to_vec(&body).unwrap()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
let bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024)
.await
.unwrap();
let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(v["url"], "http://localhost:9999/webhook");
assert_eq!(v["events"], "store");
}
#[tokio::test]
async fn http_unsubscribe_by_unknown_id_returns_ok_unchanged() {
let state = test_state();
let app = Router::new()
.route("/api/v1/subscribe", axum::routing::delete(unsubscribe))
.with_state(test_app_state(state));
let resp = app
.oneshot(
axum::http::Request::builder()
.uri("/api/v1/subscribe?id=does-not-exist")
.method("DELETE")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(
resp.status() == StatusCode::OK || resp.status() == StatusCode::BAD_REQUEST,
"got {}",
resp.status()
);
}
}