mod common;
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use serde_json::{Value, json};
use tower::ServiceExt;
use uuid::Uuid;
use common::{app_with_store, get, json_body, post_json};
use second_brain_core::schema::{AGENT_NOTE_SOURCE, MemoryType};
use second_brain_core::store::Store;
async fn call(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {
let response = app.clone().oneshot(req).await.unwrap();
let status = response.status();
(status, json_body(response).await)
}
async fn note(app: &axum::Router, body: Value) -> Value {
let (status, reply) = call(app, post_json("/v1/notes", body)).await;
assert_eq!(status, StatusCode::OK, "{reply}");
reply
}
async fn notes(app: &axum::Router, query: &str) -> Vec<Value> {
let (status, reply) = call(app, get(&format!("/v1/notes?{query}"))).await;
assert_eq!(status, StatusCode::OK, "{reply}");
reply["notes"].as_array().unwrap().clone()
}
fn id_of(body: &Value) -> Uuid {
Uuid::parse_str(body["id"].as_str().unwrap()).unwrap()
}
fn fake_github_token(body: &str) -> String {
["gh", "p_"].concat() + &body.repeat(6)
}
#[tokio::test]
async fn a_note_is_found_by_its_session_with_its_fields() {
let (app, store) = app_with_store();
let written = note(
&app,
json!({
"session_id": "sess-1",
"decision": "keep one build dir per worktree",
"reason": "a shared dir\nmixed crates",
"dead_ends": ["one shared target"],
"open_items": ["rebase onto main", " "],
"blocked_on_user": ["approve the release"],
"project": "second-brain",
"session_at": "2026-11-01T10:00:00Z",
}),
)
.await;
assert_eq!(written["kind"], "session-end");
assert_eq!(written["duplicate"], false);
note(
&app,
json!({"session_id": "sess-2", "decision": "another session"}),
)
.await;
let found = notes(&app, "session_id=sess-1").await;
assert_eq!(found.len(), 1, "{found:?}");
let found = &found[0];
assert_eq!(found["id"], written["id"]);
assert_eq!(found["kind"], "session-end");
assert_eq!(found["decision"], "keep one build dir per worktree");
assert_eq!(found["reason"], "a shared dir mixed crates");
assert_eq!(found["dead_ends"], json!(["one shared target"]));
assert_eq!(found["open_items"], json!(["rebase onto main"]));
assert_eq!(found["blocked_on_user"], json!(["approve the release"]));
assert_eq!(found["session_id"], "sess-1");
assert_eq!(found["project"], "second-brain");
assert!(
found["session_at"]
.as_str()
.unwrap()
.starts_with("2026-11-01T10:00:00"),
"{found}"
);
assert!(found["created_at"].is_string());
let stored = store.get_memory(id_of(&written)).unwrap().unwrap();
assert_eq!(stored.source, AGENT_NOTE_SOURCE);
assert_eq!(stored.source_id, "sess-1");
assert_eq!(stored.memory_type, MemoryType::Decision);
assert!(
stored
.content
.starts_with("Session-end note: keep one build dir per worktree"),
"{}",
stored.content
);
}
#[tokio::test]
async fn notes_are_listed_oldest_first_and_filtered_by_kind() {
let (app, _) = app_with_store();
let end = note(&app, json!({"session_id": "s", "decision": "first"})).await;
let fact = note(
&app,
json!({"session_id": "s", "kind": "fact", "decision": "the port is 7300"}),
)
.await;
assert_eq!(fact["kind"], "fact");
let all: Vec<_> = notes(&app, "session_id=s")
.await
.into_iter()
.map(|n| n["id"].clone())
.collect();
assert_eq!(all, vec![end["id"].clone(), fact["id"].clone()]);
let facts = notes(&app, "session_id=s&kind=fact").await;
assert_eq!(facts.len(), 1);
assert_eq!(facts[0]["id"], fact["id"]);
assert_eq!(facts[0]["kind"], "fact");
assert!(notes(&app, "session_id=s&kind=dead_end").await.is_empty());
assert!(notes(&app, "session_id=other").await.is_empty());
}
#[tokio::test]
async fn a_secret_in_any_field_is_stored_redacted() {
let (app, store) = app_with_store();
let token = fake_github_token("Rr5sS6");
let written = note(
&app,
json!({
"session_id": "s",
"decision": format!("push with {token}"),
"reason": format!("the bot token is {token}"),
"dead_ends": [format!("tried {token}")],
"open_items": [format!("rotate {token}")],
"blocked_on_user": [format!("revoke {token}")],
}),
)
.await;
let stored = store.get_memory(id_of(&written)).unwrap().unwrap();
assert!(!stored.content.contains(&token), "{}", stored.content);
let found = ¬es(&app, "session_id=s").await[0];
assert!(!found.to_string().contains(&token), "{found}");
assert_eq!(found["decision"], "push with [REDACTED:github_token]");
assert_eq!(
found["blocked_on_user"],
json!(["revoke [REDACTED:github_token]"])
);
}
#[tokio::test]
async fn a_replayed_note_is_a_duplicate_and_stores_one_row() {
let (app, store) = app_with_store();
let id = Uuid::new_v4();
let body = json!({"id": id.to_string(), "session_id": "s", "decision": "sent twice"});
let first = note(&app, body.clone()).await;
assert_eq!(first["id"], id.to_string());
assert_eq!(first["duplicate"], false);
let again = note(&app, body).await;
assert_eq!(again["id"], id.to_string());
assert_eq!(again["duplicate"], true);
assert_eq!(notes(&app, "session_id=s").await.len(), 1);
assert_eq!(store.all_memory_ids().unwrap().len(), 1);
}
#[tokio::test]
async fn notes_skip_the_exact_content_dedup() {
let (app, _) = app_with_store();
let a = note(&app, json!({"session_id": "a", "decision": "same words"})).await;
let b = note(&app, json!({"session_id": "b", "decision": "same words"})).await;
assert_ne!(a["id"], b["id"]);
assert_eq!(b["duplicate"], false);
assert_eq!(notes(&app, "session_id=b").await.len(), 1);
}
#[tokio::test]
async fn an_invalid_note_is_a_bad_request() {
let (app, store) = app_with_store();
for body in [
json!({"decision": "no session"}),
json!({"session_id": " ", "decision": "blank session"}),
json!({"session_id": "s"}),
json!({"session_id": "s", "decision": " \n "}),
json!({"session_id": "s", "decision": "d", "kind": "summary"}),
json!({"session_id": "s", "decision": "d", "id": "not-a-uuid"}),
json!({"session_id": "s", "decision": "d", "session_at": "yesterday"}),
json!({"session_id": "s", "decision": "d", "dead_ends": "not a list"}),
] {
let (status, reply) = call(&app, post_json("/v1/notes", body.clone())).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{body}: {reply}");
assert!(reply["error"].is_string(), "{body}: {reply}");
}
assert!(store.all_memory_ids().unwrap().is_empty());
}
#[tokio::test]
async fn a_lookup_without_a_session_or_with_an_unknown_kind_is_a_bad_request() {
let (app, _) = app_with_store();
for query in ["", "session_id=", "session_id=s&kind=summary"] {
let (status, reply) = call(&app, get(&format!("/v1/notes?{query}"))).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {reply}");
assert!(reply["error"].is_string(), "{query}: {reply}");
}
}
#[tokio::test]
async fn a_note_written_during_store_maintenance_is_queued_with_an_id() {
const TOKEN: &str = "notes-test-token";
let dir = tempfile::tempdir().unwrap();
let state = common::state_with_queue(dir.path().join("queue"));
let app = second_brain_api::app(state.clone(), TOKEN.to_string());
let _closed = state.gate.close();
let request = Request::builder()
.method("POST")
.uri("/v1/notes")
.header(header::AUTHORIZATION, format!("Bearer {TOKEN}"))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
json!({"session_id": "s", "decision": "queued"}).to_string(),
))
.unwrap();
let (status, reply) = call(&app, request).await;
assert_eq!(status, StatusCode::ACCEPTED, "{reply}");
assert_eq!(reply["queued"], true);
Uuid::parse_str(reply["id"].as_str().unwrap()).unwrap();
}
#[tokio::test]
async fn a_padded_session_id_is_stored_trimmed() {
let (app, _store) = app_with_store();
note(&app, json!({"session_id": " sess-9 ", "decision": "x"})).await;
assert_eq!(notes(&app, "session_id=sess-9").await.len(), 1);
}
async fn ids(app: &axum::Router, query: &str) -> Vec<Value> {
notes(app, query)
.await
.into_iter()
.map(|n| n["id"].clone())
.collect()
}
async fn filed(app: &axum::Router, project: &str, count: usize) -> Vec<Value> {
let mut written = Vec::new();
for i in 0..count {
let body = json!({"session_id": format!("s{i}"), "decision": format!("note {i}"), "project": project});
written.push(note(app, body).await["id"].clone());
}
written
}
#[tokio::test]
async fn project_notes_are_listed_newest_first_and_filtered_by_kind() {
let (app, _) = app_with_store();
let mut ends = filed(&app, "p", 3).await;
let fact = note(
&app,
json!({"session_id": "s9", "kind": "fact", "decision": "the port is 7300", "project": "p"}),
)
.await["id"]
.clone();
let elsewhere = filed(&app, "q", 1).await;
ends.reverse();
let mut all = vec![fact.clone()];
all.extend(ends.clone());
assert_eq!(ids(&app, "project=p").await, all);
assert_eq!(ids(&app, "project=p&kind=fact").await, vec![fact]);
assert_eq!(
ids(&app, "project=p&kind=session-end&limit=2").await,
ends[..2]
);
assert_eq!(ids(&app, "project=q").await, elsewhere);
assert!(ids(&app, "project=p&kind=dead_end").await.is_empty());
assert!(ids(&app, "project=none").await.is_empty());
let found = ¬es(&app, "project=p&kind=fact").await[0];
assert_eq!(found["decision"], "the port is 7300");
assert_eq!(found["session_id"], "s9");
assert_eq!(found["project"], "p");
}
#[tokio::test]
async fn a_project_lookup_returns_ten_by_default_and_at_most_fifty() {
let (app, _) = app_with_store();
let mut written = filed(&app, "p", 52).await;
written.reverse();
assert_eq!(ids(&app, "project=p").await, written[..10]);
assert_eq!(ids(&app, "project=p&limit=3").await, written[..3]);
assert_eq!(ids(&app, "project=p&limit=50").await, written[..50]);
assert_eq!(ids(&app, "project=p&limit=51").await, written[..50]);
}
#[tokio::test]
async fn a_lookup_needs_exactly_one_of_session_and_project_and_a_positive_limit() {
let (app, _) = app_with_store();
for query in [
"project=",
"session_id=s&project=p",
"project=p&limit=0",
"project=p&limit=-1",
"project=p&limit=ten",
"project=p&limit=",
"project=p&kind=summary",
"session_id=s&limit=3",
] {
let (status, reply) = call(&app, get(&format!("/v1/notes?{query}"))).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {reply}");
assert!(reply["error"].is_string(), "{query}: {reply}");
}
}
#[tokio::test]
async fn a_padded_project_is_looked_up_trimmed() {
let (app, _store) = app_with_store();
note(
&app,
json!({"session_id": "s", "decision": "x", "project": "-srv-app"}),
)
.await;
assert_eq!(notes(&app, "project=%20-srv-app%20").await.len(), 1);
}
fn since(at: &Value) -> String {
format!("since={}", at.as_str().unwrap().replace('+', "%2B"))
}
async fn created_at(app: &axum::Router, project: &str, id: &Value) -> Value {
notes(app, &format!("project={project}&limit=50"))
.await
.into_iter()
.find(|n| n["id"] == *id)
.unwrap()["created_at"]
.clone()
}
#[tokio::test]
async fn a_since_lookup_returns_project_notes_created_at_or_after_it_newest_first() {
let (app, _) = app_with_store();
let ends = filed(&app, "p", 3).await;
let fact = note(
&app,
json!({"session_id": "s9", "kind": "fact", "decision": "the port is 7300", "project": "p"}),
)
.await["id"]
.clone();
let elsewhere = filed(&app, "q", 1).await;
let from = since(&created_at(&app, "p", &ends[1]).await);
assert_eq!(
ids(&app, &format!("project=p&{from}")).await,
vec![fact.clone(), ends[2].clone(), ends[1].clone()]
);
assert_eq!(
ids(&app, &format!("project=p&{from}&kind=fact")).await,
vec![fact.clone()]
);
assert_eq!(
ids(&app, &format!("project=p&{from}&kind=session-end")).await,
ends[1..].iter().rev().cloned().collect::<Vec<_>>()
);
assert_eq!(
ids(&app, &format!("project=p&{from}&limit=2")).await,
vec![fact.clone(), ends[2].clone()]
);
assert_eq!(ids(&app, &format!("project=q&{from}")).await, elsewhere);
assert!(
ids(&app, "project=p&since=2999-01-01T00:00:00Z")
.await
.is_empty()
);
let found = ¬es(&app, &format!("project=p&{from}&kind=fact")).await[0];
assert_eq!(found["decision"], "the port is 7300");
assert_eq!(found["session_id"], "s9");
assert_eq!(found["project"], "p");
assert!(found["created_at"].is_string());
}
#[tokio::test]
async fn a_since_lookup_returns_ten_by_default_and_at_most_fifty() {
let (app, _) = app_with_store();
let mut written = filed(&app, "p", 52).await;
let from = since(&created_at(&app, "p", &written[2]).await);
let narrow = since(&created_at(&app, "p", &written[47]).await);
written.reverse();
assert_eq!(ids(&app, &format!("project=p&{from}")).await, written[..10]);
assert_eq!(
ids(&app, &format!("project=p&{from}&limit=51")).await,
written[..50]
);
assert_eq!(
ids(&app, &format!("project=p&{narrow}")).await,
written[..5]
);
}
#[tokio::test]
async fn a_since_with_a_session_or_that_does_not_parse_is_a_bad_request() {
let (app, _) = app_with_store();
for (query, names) in [
("session_id=s&since=2026-11-02T00:00:00Z", "project"),
("project=p&since=yesterday", "yesterday"),
("project=p&since=2026-11-02", "2026-11-02"),
("project=p&since=", "since"),
] {
let (status, reply) = call(&app, get(&format!("/v1/notes?{query}"))).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{query}: {reply}");
let error = reply["error"].as_str().unwrap_or_default();
assert!(error.contains(names), "{query}: {reply}");
}
}