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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use std::sync::Arc;

use axum::Json;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use chrono::{DateTime, Utc};
use second_brain_adapters::markdown;
use second_brain_core::redact::redact_for_store;
use second_brain_core::schema::{AGENT_NOTE_SOURCE, EXPLICIT_SOURCES, Memory, MemoryType, Scope};
use second_brain_core::sqlite_store::{Principal, RetireOutcome, SqliteStore};
use second_brain_core::store::Store;
use serde::de::IntoDeserializer;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::{
    MemoryResponse, bad_request, error_response, internal_error, parse_memory_type, retry_write,
    to_response,
};
use crate::AppState;
use crate::associate::{LinkError, link};

#[derive(Deserialize)]
pub(super) struct RememberRequest {
    content: String,
    memory_type: Option<String>,
    source: Option<String>,
    related_to: Option<Vec<String>>,
    project: Option<String>,
    /// Set by a client that may send the same note twice (the MCP write
    /// queue); a second write with an id the store has seen writes nothing.
    id: Option<String>,
    session_at: Option<String>,
    /// "private" (the default) or "shared".
    scope: Option<String>,
}

#[derive(Serialize)]
struct RememberResponse {
    id: String,
    memory_type: String,
    #[serde(default)]
    duplicate: bool,
    /// A duplicate given a project it was not filed under is moved there.
    project_updated: bool,
    /// Likewise for a scope asked for explicitly.
    scope_updated: bool,
    /// Entities the new memory was linked to; a duplicate links none.
    entities: usize,
}

pub(super) async fn remember(
    State(state): State<Arc<AppState>>,
    Json(req): Json<RememberRequest>,
) -> impl IntoResponse {
    let memory_type = match req.memory_type.as_deref().map(parse_memory_type) {
        None => MemoryType::Semantic,
        Some(Ok(t)) => t,
        Some(Err(message)) => return bad_request(message),
    };

    // Every remember is explicit by definition; a transcript source here
    // would hand the note to consolidation, which paraphrases it away; vault
    // sync owns every row of the markdown source, and /v1/notes every agent
    // note, whose content must parse back into its fields.
    let source = req.source.unwrap_or_else(|| "api".to_string());
    if let Err(message) = check_written_source("remember", &source) {
        return bad_request(message);
    }
    let client_id = match parse_client_id(req.id.as_deref()) {
        Ok(id) => id,
        Err(message) => return bad_request(message),
    };
    let session_at = match parse_session_at(req.session_at.as_deref()) {
        Ok(at) => at,
        Err(message) => return bad_request(message),
    };
    let scope = match req.scope.as_deref().map(parse_scope).transpose() {
        Ok(scope) => scope,
        Err(message) => return bad_request(message),
    };
    let content = redact_for_store(&req.content);
    let related_to: Vec<String> = req
        .related_to
        .unwrap_or_default()
        .iter()
        .map(|n| redact_for_store(n))
        .collect();
    let project = req.project;

    let result = tokio::task::spawn_blocking(move || -> anyhow::Result<RememberResponse> {
        let sqlite = &state.sqlite;
        if let Some(written) = replayed(sqlite, client_id, memory_type)? {
            return Ok(remember_outcome(written));
        }

        // Exact-match dedup guard: every caller of /v1/remember shares this,
        // including the autonomous "ask-auto" trigger, which has no other
        // volume limit. Embedding-similarity (paraphrase-level) dedup
        // should replace this once the embedder is initialized on the Pi
        // (embedder_available: false today); exact-match string comparison
        // is what's feasible with what's actually running now.
        if let Some(existing) =
            sqlite.find_exact_duplicate_outside_source(&content, None, markdown::SOURCE)?
        {
            let project_updated = match project.as_deref() {
                Some(p) => sqlite.refile_memory(existing.id, p)?,
                None => false,
            };
            let scope_updated = match scope {
                Some(scope) if scope != existing.scope => {
                    sqlite.set_memory_scope(existing.id, scope, &Principal::Owner)?
                }
                _ => false,
            };
            return Ok(RememberResponse {
                duplicate: true,
                project_updated,
                scope_updated,
                ..RememberResponse::new(existing.id, existing.memory_type)
            });
        }

        let mut memory = Memory::new(content, memory_type, source, String::new())
            .with_project_path(project)
            .with_machine_id(state.machine.id.clone());
        memory.scope = scope.unwrap_or_default();
        let written = store_explicit(&state, memory, client_id, session_at, &related_to)?;
        Ok(remember_outcome(written))
    })
    .await;

    match result {
        Ok(Ok(response)) => Json(response).into_response(),
        Ok(Err(e)) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
    }
}

impl RememberResponse {
    fn new(id: Uuid, memory_type: MemoryType) -> Self {
        Self {
            id: id.to_string(),
            memory_type: format!("{memory_type:?}").to_lowercase(),
            duplicate: false,
            project_updated: false,
            scope_updated: false,
            entities: 0,
        }
    }
}

fn remember_outcome(written: Written) -> RememberResponse {
    match written {
        Written::Stored {
            id,
            memory_type,
            entities,
        } => RememberResponse {
            entities,
            ..RememberResponse::new(id, memory_type)
        },
        Written::Replayed { id, memory_type } => RememberResponse {
            duplicate: true,
            ..RememberResponse::new(id, memory_type)
        },
    }
}

pub(super) enum Written {
    Stored {
        id: Uuid,
        memory_type: MemoryType,
        entities: usize,
    },
    /// The client id named a row already stored or deleted, so nothing was written.
    Replayed { id: Uuid, memory_type: MemoryType },
}

/// Sources a caller may write under: explicit ones, minus those another
/// route owns.
pub(super) fn check_written_source(route: &str, source: &str) -> Result<(), String> {
    let writable =
        |s: &str| EXPLICIT_SOURCES.contains(&s) && s != markdown::SOURCE && s != AGENT_NOTE_SOURCE;
    if writable(source) {
        return Ok(());
    }
    let valid: Vec<&str> = EXPLICIT_SOURCES
        .iter()
        .copied()
        .filter(|s| writable(s))
        .collect();
    Err(format!(
        "{route} accepts only an explicit source ({}), not '{source}'",
        valid.join(", ")
    ))
}

pub(super) fn parse_client_id(id: Option<&str>) -> Result<Option<Uuid>, String> {
    id.map(Uuid::parse_str)
        .transpose()
        .map_err(|_| format!("invalid memory id: {}", id.unwrap_or_default()))
}

fn parse_scope(scope: &str) -> Result<Scope, String> {
    Scope::deserialize(scope.into_deserializer()).map_err(|_: serde::de::value::Error| {
        format!("unknown scope '{scope}'; valid values: private, shared")
    })
}

pub(super) fn parse_session_at(at: Option<&str>) -> Result<Option<DateTime<Utc>>, String> {
    at.map(DateTime::parse_from_rfc3339)
        .transpose()
        .map(|at| at.map(|at| at.with_timezone(&Utc)))
        .map_err(|e| format!("invalid session_at: {e}"))
}

/// Reader pre-check so a replay skips the caller's own lookups; the insert
/// in `store_explicit` repeats it inside its own transaction.
pub(super) fn replayed(
    sqlite: &SqliteStore,
    client_id: Option<Uuid>,
    memory_type: MemoryType,
) -> anyhow::Result<Option<Written>> {
    let Some(id) = client_id else {
        return Ok(None);
    };
    if let Some(known) = sqlite.get_memory(id)? {
        return Ok(Some(Written::Replayed {
            id,
            memory_type: known.memory_type,
        }));
    }
    if sqlite.tombstone_exists(id)? {
        return Ok(Some(Written::Replayed { id, memory_type }));
    }
    Ok(None)
}

/// Stores an explicit write under the client's id when it sent one, embeds
/// it when the embedder is loaded and links the entities it mentions.
pub(super) fn store_explicit(
    state: &AppState,
    mut memory: Memory,
    client_id: Option<Uuid>,
    session_at: Option<DateTime<Utc>>,
    related_to: &[String],
) -> anyhow::Result<Written> {
    if let Some(id) = client_id {
        memory.id = id;
    }
    // Dated by when it was written, because the write runs inside the
    // session it describes; a queued write carries its call time.
    memory.session_at = Some(session_at.unwrap_or(memory.created_at));
    if let Some(ref emb) = state.embedder
        && let Ok(embedding) = emb.embed(&memory.content)
    {
        memory.embedding = embedding;
    }

    let id = memory.id;
    let memory_type = memory.memory_type;
    if client_id.is_some() {
        if !retry_write(|| state.sqlite.store_memory_if_absent(&memory))? {
            let stored_type = state
                .sqlite
                .get_memory(id)?
                .map_or(memory_type, |m| m.memory_type);
            return Ok(Written::Replayed {
                id,
                memory_type: stored_type,
            });
        }
    } else {
        retry_write(|| state.store.store_memory(&memory))?;
    }

    let entities = retry_write(|| {
        crate::mentions::link_mentions(state.store.as_ref(), id, &memory.content, related_to)
    })?;
    Ok(Written::Stored {
        id,
        memory_type,
        entities,
    })
}

#[derive(Deserialize)]
pub(super) struct AssociateRequest {
    /// A memory id, an entity id, or an entity name.
    #[serde(alias = "from")]
    from_id: String,
    #[serde(alias = "to")]
    to_id: String,
    relation: String,
    context: Option<String>,
}

pub(super) async fn associate(
    State(state): State<Arc<AppState>>,
    Json(req): Json<AssociateRequest>,
) -> impl IntoResponse {
    let store = state.sqlite.clone();
    let relation = req.relation.clone();
    let result = tokio::task::spawn_blocking(move || {
        link(&store, &req.from_id, &req.to_id, &req.relation, req.context)
    })
    .await;

    match result {
        Ok(Ok(linked)) => (
            StatusCode::CREATED,
            Json(serde_json::json!({
                "from_id": linked.from_id,
                "to_id": linked.to_id,
                "relation": relation,
                "superseded": linked.superseded,
            })),
        )
            .into_response(),
        Ok(Err(LinkError::BadRequest(message))) => bad_request(message),
        Ok(Err(LinkError::NotFound(message))) => error_response(StatusCode::NOT_FOUND, message),
        Ok(Err(LinkError::Conflict(message))) => error_response(StatusCode::CONFLICT, message),
        Ok(Err(LinkError::Store(e))) => internal_error(e),
        Err(e) => internal_error(e),
    }
}

pub(super) async fn get_memory(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    let uuid = match Uuid::parse_str(&id) {
        Ok(u) => u,
        Err(_) => return (StatusCode::BAD_REQUEST, "invalid uuid").into_response(),
    };

    let sqlite = state.sqlite.clone();
    let result = tokio::task::spawn_blocking(move || sqlite.get_memory_full(uuid)).await;

    let machine_names = state.store.get_all_machines().unwrap_or_default();

    match result {
        Ok(Ok(Some(m))) => {
            state.health.memories_used(&[uuid], Utc::now());
            Json(to_response(m, None, None, &machine_names)).into_response()
        }
        Ok(Ok(None)) => StatusCode::NOT_FOUND.into_response(),
        Ok(Err(e)) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
    }
}

#[derive(Deserialize, Default)]
pub(super) struct ForgetParams {
    #[serde(default)]
    hard: bool,
    reason: Option<String>,
}

const DEFAULT_FORGET_REASON: &str = "forgotten";

/// Retires by default: the row is archived with its reason and replicated,
/// so it leaves recall everywhere but can still be read and restored.
/// `hard=true` deletes and tombstones it, for content that must not survive.
pub(super) async fn forget(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Query(params): Query<ForgetParams>,
) -> impl IntoResponse {
    let uuid = match Uuid::parse_str(&id) {
        Ok(u) => u,
        Err(_) => return bad_request(format!("invalid memory id: {id}")),
    };

    let store = state.sqlite.clone();
    let reason = params
        .reason
        .filter(|r| !r.trim().is_empty())
        .map(|r| redact_for_store(&r))
        .unwrap_or_else(|| DEFAULT_FORGET_REASON.to_string());
    let hard = params.hard;
    let result = tokio::task::spawn_blocking(move || -> anyhow::Result<Option<&'static str>> {
        if hard {
            return Ok(store.remove_memory(uuid)?.then_some("deleted"));
        }
        Ok(match store.retire_memory(uuid, &reason)? {
            RetireOutcome::Retired => Some("retired"),
            RetireOutcome::AlreadyRetired => Some("already_retired"),
            RetireOutcome::NotFound => None,
        })
    })
    .await;

    match result {
        Ok(Ok(Some(action))) => {
            Json(serde_json::json!({"id": uuid.to_string(), "action": action})).into_response()
        }
        Ok(Ok(None)) => error_response(StatusCode::NOT_FOUND, format!("no memory with id {uuid}")),
        Ok(Err(e)) => internal_error(e),
        Err(e) => internal_error(e),
    }
}

#[derive(Deserialize)]
pub(super) struct TraverseParams {
    start_id: String,
    depth: Option<u32>,
}

pub(super) async fn traverse(
    State(state): State<Arc<AppState>>,
    Query(params): Query<TraverseParams>,
) -> impl IntoResponse {
    let uuid = match Uuid::parse_str(&params.start_id) {
        Ok(u) => u,
        Err(_) => return (StatusCode::BAD_REQUEST, "invalid start_id").into_response(),
    };

    let depth = params.depth.unwrap_or(2);
    let store = state.store.clone();

    let result = tokio::task::spawn_blocking(move || store.traverse(uuid, depth)).await;

    let machine_names = state.store.get_all_machines().unwrap_or_default();

    match result {
        Ok(Ok(results)) => {
            let memories: Vec<MemoryResponse> = results
                .into_iter()
                .map(|(m, _)| to_response(m, None, None, &machine_names))
                .collect();
            Json(serde_json::json!({"memories": memories})).into_response()
        }
        Ok(Err(e)) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
    }
}