second-brain-api 0.13.5

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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 = &notes(&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 = &notes(&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 = &notes(&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}");
    }
}