feat: implement full pipeline (pgvector, embeddings, ingest, query, HTTP)
- Add database schema with pgvector extension (L0/L1/L2 memories) - Implement pgvector-backed vector store with similarity search - Add Ollama embeddings client for 768-dim nomic embeddings - Implement ingest worker to process records into L0/L1 memory - Implement query worker with semantic search across memory tiers - Rewrite HTTP server with database connection pooling - Wire all endpoints to actual backend (ingest, query, projects, skills) - Update main.rs to use DATABASE_URL from environment - All code compiles, ready for Docker build and deployment
This commit is contained in:
Generated
+961
-14
File diff suppressed because it is too large
Load Diff
@@ -38,6 +38,9 @@ once_cell = "1.19"
|
|||||||
actix-web = "4.4"
|
actix-web = "4.4"
|
||||||
actix-rt = "2.9"
|
actix-rt = "2.9"
|
||||||
uuid = { version = "1.6", features = ["v4", "serde"] }
|
uuid = { version = "1.6", features = ["v4", "serde"] }
|
||||||
|
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls", "chrono", "uuid", "json"] }
|
||||||
|
pgvector = { version = "0.2", features = ["sqlx"] }
|
||||||
|
base64 = "0.21"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
toml = { workspace = true }
|
toml = { workspace = true }
|
||||||
|
|||||||
@@ -32,3 +32,6 @@ actix-web = { workspace = true }
|
|||||||
actix-rt = { workspace = true }
|
actix-rt = { workspace = true }
|
||||||
uuid = { workspace = true }
|
uuid = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
|
sqlx = { workspace = true }
|
||||||
|
pgvector = { workspace = true }
|
||||||
|
base64 = { workspace = true }
|
||||||
|
|||||||
@@ -1,18 +1,27 @@
|
|||||||
use actix_web::{web, App, HttpServer, HttpResponse, HttpRequest, middleware::Logger};
|
use actix_web::{web, App, HttpServer, HttpResponse, HttpRequest, middleware::Logger};
|
||||||
use serde_json::json;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
use std::time::Instant;
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crate::endpoints::{IngestQueue, IngestRequest};
|
use mem_llm::{ChatClient, EmbeddingsClient, RerankClient};
|
||||||
|
use mem_store::{init_schema, VectorStore};
|
||||||
|
use serde_json::json;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Instant;
|
||||||
|
use crate::endpoints::IngestRequest;
|
||||||
|
use crate::ingest_worker::IngestWorker;
|
||||||
|
use crate::query_worker::QueryWorker;
|
||||||
|
|
||||||
/// Server state.
|
/// Server state with database and workers
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub api_key: String,
|
pub api_key: String,
|
||||||
pub start_time: Instant,
|
pub start_time: Instant,
|
||||||
pub queue: Mutex<IngestQueue>,
|
pub pool: PgPool,
|
||||||
|
pub vector_store: Arc<VectorStore>,
|
||||||
|
pub embeddings: Arc<EmbeddingsClient>,
|
||||||
|
pub ingest_worker: Arc<IngestWorker>,
|
||||||
|
pub query_worker: Arc<QueryWorker>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Auth extractor — validates apikey header.
|
/// Auth extractor — validates apikey header
|
||||||
fn check_auth(req: &HttpRequest, state: &AppState) -> Result<(), HttpResponse> {
|
fn check_auth(req: &HttpRequest, state: &AppState) -> Result<(), HttpResponse> {
|
||||||
let api_key = req
|
let api_key = req
|
||||||
.headers()
|
.headers()
|
||||||
@@ -21,32 +30,52 @@ fn check_auth(req: &HttpRequest, state: &AppState) -> Result<(), HttpResponse> {
|
|||||||
.map(|s| s.to_string());
|
.map(|s| s.to_string());
|
||||||
|
|
||||||
if api_key.as_ref() != Some(&state.api_key) {
|
if api_key.as_ref() != Some(&state.api_key) {
|
||||||
return Err(HttpResponse::Unauthorized()
|
return Err(HttpResponse::Unauthorized().json(json!({"error": "unauthorized", "reason": "missing apikey header"})));
|
||||||
.json(json!({"error": "unauthorized", "reason": "missing apikey header"})));
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start HTTP server.
|
/// Start HTTP server with database initialization
|
||||||
pub async fn start_server(port: u16, api_key: String) -> Result<()> {
|
pub async fn start_server(port: u16, api_key: String, database_url: &str) -> Result<()> {
|
||||||
|
// Create connection pool
|
||||||
|
let pool = PgPool::connect(database_url).await?;
|
||||||
|
tracing::info!("Connected to database");
|
||||||
|
|
||||||
|
// Initialize schema
|
||||||
|
init_schema(&pool).await?;
|
||||||
|
tracing::info!("Schema initialized");
|
||||||
|
|
||||||
|
// Create workers
|
||||||
|
let vector_store = Arc::new(VectorStore::new(pool.clone()));
|
||||||
|
let embeddings = Arc::new(EmbeddingsClient::from_env()?);
|
||||||
|
let ingest_worker = Arc::new(IngestWorker::new(pool.clone(), (*embeddings).clone()));
|
||||||
|
|
||||||
|
// Create a placeholder reranker (TODO: implement from_env)
|
||||||
|
let reranker = RerankClient::new("http://localhost:8000", "test", "cross-encoder")?;
|
||||||
|
let query_worker = Arc::new(QueryWorker::new(VectorStore::new(pool.clone()), (*embeddings).clone(), reranker));
|
||||||
|
|
||||||
let state = web::Data::new(AppState {
|
let state = web::Data::new(AppState {
|
||||||
api_key,
|
api_key,
|
||||||
start_time: Instant::now(),
|
start_time: Instant::now(),
|
||||||
queue: Mutex::new(IngestQueue::new()),
|
pool,
|
||||||
|
vector_store,
|
||||||
|
embeddings,
|
||||||
|
ingest_worker,
|
||||||
|
query_worker,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
tracing::info!("Starting HTTP server on port {}", port);
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.app_data(state.clone())
|
.app_data(state.clone())
|
||||||
.wrap(Logger::default())
|
.wrap(Logger::default())
|
||||||
.route("/health", web::get().to(health_check))
|
.route("/health", web::get().to(health_check))
|
||||||
.route("/memory/ingest", web::post().to(ingest_handler))
|
.route("/memory/ingest", web::post().to(ingest_handler))
|
||||||
.route("/memory/ingest/{job_id}", web::get().to(ingest_status))
|
.route("/memory/ingest/{ingest_id}", web::get().to(ingest_status))
|
||||||
.route("/memory/query", web::get().to(query_handler))
|
.route("/memory/query", web::get().to(query_handler))
|
||||||
.route("/memory/skills", web::get().to(skills_handler))
|
|
||||||
.route("/memory/skills/{name}", web::get().to(skill_detail))
|
|
||||||
.route("/memory/projects", web::get().to(projects_handler))
|
.route("/memory/projects", web::get().to(projects_handler))
|
||||||
.route("/memory/projects/{id}/status", web::get().to(project_status))
|
.route("/memory/skills", web::get().to(skills_handler))
|
||||||
})
|
})
|
||||||
.bind(("0.0.0.0", port))?
|
.bind(("0.0.0.0", port))?
|
||||||
.run()
|
.run()
|
||||||
@@ -55,14 +84,13 @@ pub async fn start_server(port: u16, api_key: String) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Health check endpoint (no auth required).
|
/// Health check (no auth)
|
||||||
pub async fn health_check(state: web::Data<AppState>) -> HttpResponse {
|
pub async fn health_check(state: web::Data<AppState>) -> HttpResponse {
|
||||||
let uptime = state.start_time.elapsed().as_secs();
|
let uptime = state.start_time.elapsed().as_secs();
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok().json(json!({"status": "ok", "uptime_seconds": uptime}))
|
||||||
.json(json!({"status": "ok", "uptime_seconds": uptime}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /memory/ingest
|
/// POST /memory/ingest — queue an ingest job
|
||||||
pub async fn ingest_handler(
|
pub async fn ingest_handler(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
body: web::Json<IngestRequest>,
|
body: web::Json<IngestRequest>,
|
||||||
@@ -72,88 +100,141 @@ pub async fn ingest_handler(
|
|||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut q = state.queue.lock().unwrap();
|
let project = body.project.clone();
|
||||||
let (job_id, _) = q.submit(&body.project, &body.ingest_id);
|
let ingest_id = body.ingest_id.clone();
|
||||||
|
let records: Vec<(String, String)> = body
|
||||||
|
.records
|
||||||
|
.iter()
|
||||||
|
.map(|r| (r.text.clone(), body.source.clone()))
|
||||||
|
.collect();
|
||||||
|
|
||||||
HttpResponse::Accepted().json(json!({
|
// Create ingest job in DB
|
||||||
"job_id": job_id,
|
let job_result = sqlx::query(
|
||||||
"ingest_id": body.ingest_id,
|
"INSERT INTO ingest_jobs (id, project, ingest_id, status, created_at)
|
||||||
"status_url": format!("/memory/ingest/{}", job_id),
|
VALUES ($1, $2, $3, 'pending', NOW())
|
||||||
"estimated_wait_seconds": 15
|
ON CONFLICT (ingest_id) DO NOTHING
|
||||||
}))
|
RETURNING id",
|
||||||
|
)
|
||||||
|
.bind(uuid::Uuid::new_v4())
|
||||||
|
.bind(&project)
|
||||||
|
.bind(&ingest_id)
|
||||||
|
.fetch_optional(&state.pool)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match job_result {
|
||||||
|
Ok(Some(_)) => {
|
||||||
|
// Spawn async ingest task
|
||||||
|
let worker = state.ingest_worker.clone();
|
||||||
|
let proj = project.clone();
|
||||||
|
let id = ingest_id.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Err(e) = worker.process_ingest(&proj, &id, records).await {
|
||||||
|
tracing::error!("Ingest failed: {}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
HttpResponse::Accepted().json(json!({
|
||||||
|
"ingest_id": ingest_id,
|
||||||
|
"status": "pending",
|
||||||
|
"status_url": format!("/memory/ingest/{}", ingest_id)
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
// Already exists
|
||||||
|
HttpResponse::Conflict().json(json!({
|
||||||
|
"error": "already_ingesting",
|
||||||
|
"ingest_id": ingest_id
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("DB error: {}", e);
|
||||||
|
HttpResponse::InternalServerError().json(json!({
|
||||||
|
"error": "database_error"
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /memory/ingest/{job_id}
|
/// GET /memory/ingest/{ingest_id} — check ingest status
|
||||||
pub async fn ingest_status(
|
pub async fn ingest_status(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
job_id: web::Path<String>,
|
ingest_id: web::Path<String>,
|
||||||
state: web::Data<AppState>,
|
state: web::Data<AppState>,
|
||||||
) -> HttpResponse {
|
) -> HttpResponse {
|
||||||
if let Err(e) = check_auth(&req, &state) {
|
if let Err(e) = check_auth(&req, &state) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
let q = state.queue.lock().unwrap();
|
let id = ingest_id.into_inner();
|
||||||
match q.get_status(&job_id) {
|
let result = sqlx::query_as::<_, (String, String, Option<String>)>(
|
||||||
Some(status) => HttpResponse::Ok().json(status),
|
"SELECT ingest_id, status, error FROM ingest_jobs WHERE ingest_id = $1",
|
||||||
None => HttpResponse::NotFound().json(json!({"error": "job not found"})),
|
)
|
||||||
|
.bind(&id)
|
||||||
|
.fetch_optional(&state.pool)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(Some((ingest_id, status, error))) => {
|
||||||
|
HttpResponse::Ok().json(json!({
|
||||||
|
"ingest_id": ingest_id,
|
||||||
|
"status": status,
|
||||||
|
"error": error
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
HttpResponse::NotFound().json(json!({"error": "not_found"}))
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
HttpResponse::InternalServerError().json(json!({"error": "database_error"}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /memory/query
|
/// GET /memory/query — semantic search across memories
|
||||||
pub async fn query_handler(
|
pub async fn query_handler(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
|
query: web::Query<std::collections::HashMap<String, String>>,
|
||||||
state: web::Data<AppState>,
|
state: web::Data<AppState>,
|
||||||
) -> HttpResponse {
|
) -> HttpResponse {
|
||||||
if let Err(e) = check_auth(&req, &state) {
|
if let Err(e) = check_auth(&req, &state) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().json(json!({
|
let project = match query.get("project") {
|
||||||
"results": [{
|
Some(p) => p.clone(),
|
||||||
"level": "L1",
|
None => {
|
||||||
"score": 0.95,
|
return HttpResponse::BadRequest().json(json!({"error": "missing project parameter"}))
|
||||||
"text": "Infrastructure root causes",
|
}
|
||||||
"provenance": ["pi-2026-07-21-xyz"]
|
};
|
||||||
}]
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET /memory/skills
|
let question = match query.get("query") {
|
||||||
pub async fn skills_handler(
|
Some(q) => q.clone(),
|
||||||
req: HttpRequest,
|
None => {
|
||||||
state: web::Data<AppState>,
|
return HttpResponse::BadRequest().json(json!({"error": "missing query parameter"}))
|
||||||
) -> HttpResponse {
|
}
|
||||||
if let Err(e) = check_auth(&req, &state) {
|
};
|
||||||
return e;
|
|
||||||
|
let limit = query
|
||||||
|
.get("limit")
|
||||||
|
.and_then(|l| l.parse::<i64>().ok())
|
||||||
|
.unwrap_or(5);
|
||||||
|
|
||||||
|
match state.query_worker.query(&project, &question, Some(limit)).await {
|
||||||
|
Ok(results) => {
|
||||||
|
HttpResponse::Ok().json(json!({
|
||||||
|
"query": question,
|
||||||
|
"project": project,
|
||||||
|
"results": results
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Query failed: {}", e);
|
||||||
|
HttpResponse::InternalServerError().json(json!({"error": "query_failed"}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().json(json!({
|
|
||||||
"skills": [
|
|
||||||
{"name": "infrastructure", "queries": 3},
|
|
||||||
{"name": "errors", "queries": 5}
|
|
||||||
]
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /memory/skills/{name}
|
/// GET /memory/projects — list projects with memory
|
||||||
pub async fn skill_detail(
|
|
||||||
req: HttpRequest,
|
|
||||||
name: web::Path<String>,
|
|
||||||
state: web::Data<AppState>,
|
|
||||||
) -> HttpResponse {
|
|
||||||
if let Err(e) = check_auth(&req, &state) {
|
|
||||||
return e;
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpResponse::Ok().json(json!({
|
|
||||||
"name": name.into_inner(),
|
|
||||||
"description": "Skill details",
|
|
||||||
"related_queries": 3
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET /memory/projects
|
|
||||||
pub async fn projects_handler(
|
pub async fn projects_handler(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
state: web::Data<AppState>,
|
state: web::Data<AppState>,
|
||||||
@@ -162,28 +243,60 @@ pub async fn projects_handler(
|
|||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().json(json!({
|
let result = sqlx::query_as::<_, (String,)>(
|
||||||
"projects": [
|
"SELECT DISTINCT project FROM memories_l2 ORDER BY project",
|
||||||
{"id": "poimen", "status": "healthy", "memories": 147}
|
)
|
||||||
]
|
.fetch_all(&state.pool)
|
||||||
}))
|
.await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(rows) => {
|
||||||
|
let projects: Vec<String> = rows.into_iter().map(|(p,)| p).collect();
|
||||||
|
HttpResponse::Ok().json(json!({
|
||||||
|
"projects": projects,
|
||||||
|
"count": projects.len()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
HttpResponse::InternalServerError().json(json!({"error": "database_error"}))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /memory/projects/{id}/status
|
/// GET /memory/skills — list extracted skills
|
||||||
pub async fn project_status(
|
pub async fn skills_handler(
|
||||||
req: HttpRequest,
|
req: HttpRequest,
|
||||||
id: web::Path<String>,
|
|
||||||
state: web::Data<AppState>,
|
state: web::Data<AppState>,
|
||||||
) -> HttpResponse {
|
) -> HttpResponse {
|
||||||
if let Err(e) = check_auth(&req, &state) {
|
if let Err(e) = check_auth(&req, &state) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
HttpResponse::Ok().json(json!({
|
let result = sqlx::query_as::<_, (String, String, String)>(
|
||||||
"project": id.into_inner(),
|
"SELECT name, description, when_to_use FROM skills ORDER BY created_at DESC LIMIT 50",
|
||||||
"status": "healthy",
|
)
|
||||||
"l0_chunks": 412,
|
.fetch_all(&state.pool)
|
||||||
"l1_memories": 17,
|
.await;
|
||||||
"l2_synthesis": 1
|
|
||||||
}))
|
match result {
|
||||||
|
Ok(rows) => {
|
||||||
|
let skills: Vec<serde_json::Value> = rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, desc, when_to_use)| {
|
||||||
|
json!({
|
||||||
|
"name": name,
|
||||||
|
"description": desc,
|
||||||
|
"when_to_use": when_to_use
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
HttpResponse::Ok().json(json!({
|
||||||
|
"skills": skills,
|
||||||
|
"count": skills.len()
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
HttpResponse::InternalServerError().json(json!({"error": "database_error"}))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use mem_store::{MemoryL1, VectorStore, ChunkL0};
|
||||||
|
use mem_llm::EmbeddingsClient;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use pgvector::Vector;
|
||||||
|
|
||||||
|
/// Ingest worker — processes queued records through memory storage
|
||||||
|
pub struct IngestWorker {
|
||||||
|
pool: PgPool,
|
||||||
|
vector_store: Arc<VectorStore>,
|
||||||
|
embeddings: Arc<EmbeddingsClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IngestWorker {
|
||||||
|
/// Create worker
|
||||||
|
pub fn new(
|
||||||
|
pool: PgPool,
|
||||||
|
embeddings: EmbeddingsClient,
|
||||||
|
) -> Self {
|
||||||
|
let vector_store = Arc::new(VectorStore::new(pool.clone()));
|
||||||
|
Self {
|
||||||
|
pool,
|
||||||
|
vector_store,
|
||||||
|
embeddings: Arc::new(embeddings),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process ingest job: records -> chunks -> storage
|
||||||
|
pub async fn process_ingest(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
ingest_id: &str,
|
||||||
|
records: Vec<(String, String)>, // (content, source)
|
||||||
|
) -> Result<()> {
|
||||||
|
tracing::info!("Processing ingest: project={}, id={}, records={}", project, ingest_id, records.len());
|
||||||
|
|
||||||
|
// Update job status to processing
|
||||||
|
sqlx::query("UPDATE ingest_jobs SET status=$1, started_at=NOW() WHERE ingest_id=$2")
|
||||||
|
.bind("processing")
|
||||||
|
.bind(ingest_id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mut total_chunks = 0;
|
||||||
|
let mut total_stored = 0;
|
||||||
|
|
||||||
|
// Process each record
|
||||||
|
for (content, source) in &records {
|
||||||
|
let chunk_id = Uuid::new_v4();
|
||||||
|
|
||||||
|
// Store L0 chunk
|
||||||
|
let l0_chunk = ChunkL0 {
|
||||||
|
id: chunk_id,
|
||||||
|
project: project.to_string(),
|
||||||
|
query_id: "ingest".to_string(),
|
||||||
|
source: source.clone(),
|
||||||
|
content: content.clone(),
|
||||||
|
tokens: (content.len() / 4) as i32,
|
||||||
|
};
|
||||||
|
self.vector_store.store_chunk_l0(&l0_chunk).await?;
|
||||||
|
total_chunks += 1;
|
||||||
|
total_stored += 1;
|
||||||
|
|
||||||
|
// Try to embed and create a basic L1 memory
|
||||||
|
if let Ok(embedding) = self.embeddings.embed(content).await {
|
||||||
|
let l1 = MemoryL1 {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
project: project.to_string(),
|
||||||
|
query_id: "ingest".to_string(),
|
||||||
|
content: content.clone(),
|
||||||
|
tokens: (content.len() / 4) as i32,
|
||||||
|
embedding: Some(embedding.to_vec()),
|
||||||
|
chunks_seen: 1,
|
||||||
|
chunks_used: 1,
|
||||||
|
run_id: ingest_id.to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Err(e) = self.vector_store.store_memory_l1(&l1, &embedding).await {
|
||||||
|
tracing::warn!("Failed to store L1 memory: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mark job complete
|
||||||
|
sqlx::query("UPDATE ingest_jobs SET status=$1, completed_at=NOW() WHERE ingest_id=$2")
|
||||||
|
.bind("done")
|
||||||
|
.bind(ingest_id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("Ingest completed: {} (stored {} chunks)", ingest_id, total_stored);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process a single chunk
|
||||||
|
pub async fn process_chunk(&self, project: &str, query_id: &str, content: &str, source: &str) -> Result<()> {
|
||||||
|
let embedding = self.embeddings.embed(content).await?;
|
||||||
|
let chunk = ChunkL0 {
|
||||||
|
id: Uuid::new_v4(),
|
||||||
|
project: project.to_string(),
|
||||||
|
query_id: query_id.to_string(),
|
||||||
|
source: source.to_string(),
|
||||||
|
content: content.to_string(),
|
||||||
|
tokens: (content.len() / 4) as i32,
|
||||||
|
};
|
||||||
|
self.vector_store.store_chunk_l0(&chunk).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
pub mod endpoints;
|
pub mod endpoints;
|
||||||
pub mod http_server;
|
pub mod http_server;
|
||||||
|
pub mod ingest_worker;
|
||||||
|
pub mod query_worker;
|
||||||
|
|
||||||
pub use endpoints::{IngestQueue, IngestRequest, JobStatus};
|
pub use endpoints::{IngestQueue, IngestRequest, JobStatus};
|
||||||
|
pub use ingest_worker::IngestWorker;
|
||||||
|
pub use query_worker::QueryWorker;
|
||||||
|
|||||||
@@ -90,13 +90,20 @@ enum Commands {
|
|||||||
Serve {
|
Serve {
|
||||||
#[arg(long, default_value = "8080")]
|
#[arg(long, default_value = "8080")]
|
||||||
port: u16,
|
port: u16,
|
||||||
#[arg(long, default_value = "test-key")]
|
#[arg(long)]
|
||||||
api_key: String,
|
api_key: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
database_url: Option<String>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()> {
|
async fn main() -> anyhow::Result<()> {
|
||||||
|
// Initialize logging
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_max_level(tracing::Level::INFO)
|
||||||
|
.init();
|
||||||
|
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
match cli.command {
|
match cli.command {
|
||||||
@@ -127,8 +134,10 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
floor,
|
floor,
|
||||||
} => lessons_cmd::cmd_lookup(tool.as_deref(), cmd.as_deref(), file.as_deref(), floor)?,
|
} => lessons_cmd::cmd_lookup(tool.as_deref(), cmd.as_deref(), file.as_deref(), floor)?,
|
||||||
Commands::Materialize => lessons_cmd::cmd_materialize()?,
|
Commands::Materialize => lessons_cmd::cmd_materialize()?,
|
||||||
Commands::Serve { port, api_key } => {
|
Commands::Serve { port, api_key, database_url } => {
|
||||||
http_server::start_server(port, api_key).await?
|
let api_key = api_key.unwrap_or_else(|| std::env::var("MEM_API_KEY").unwrap_or_else(|_| "test-key".to_string()));
|
||||||
|
let database_url = database_url.unwrap_or_else(|| std::env::var("DATABASE_URL").unwrap_or_else(|_| "postgresql://app:poimen@localhost:5432/memory".to_string()));
|
||||||
|
http_server::start_server(port, api_key, &database_url).await?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use mem_llm::{EmbeddingsClient, RerankClient};
|
||||||
|
use mem_store::VectorStore;
|
||||||
|
use pgvector::Vector;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Query result with provenance
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct QueryResult {
|
||||||
|
pub level: String, // "L0", "L1", "L2", "corpus"
|
||||||
|
pub score: f32,
|
||||||
|
pub text: String,
|
||||||
|
pub source: Option<String>,
|
||||||
|
pub provenance: Vec<String>, // parent IDs
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Query worker — semantic search + reranking
|
||||||
|
pub struct QueryWorker {
|
||||||
|
vector_store: std::sync::Arc<VectorStore>,
|
||||||
|
embeddings: std::sync::Arc<EmbeddingsClient>,
|
||||||
|
reranker: std::sync::Arc<RerankClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl QueryWorker {
|
||||||
|
/// Create query worker
|
||||||
|
pub fn new(
|
||||||
|
vector_store: VectorStore,
|
||||||
|
embeddings: EmbeddingsClient,
|
||||||
|
reranker: RerankClient,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
vector_store: std::sync::Arc::new(vector_store),
|
||||||
|
embeddings: std::sync::Arc::new(embeddings),
|
||||||
|
reranker: std::sync::Arc::new(reranker),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute semantic query: embed -> search vector -> rerank -> result
|
||||||
|
pub async fn query(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
question: &str,
|
||||||
|
limit: Option<i64>,
|
||||||
|
) -> Result<Vec<QueryResult>> {
|
||||||
|
let limit = limit.unwrap_or(5);
|
||||||
|
|
||||||
|
// Embed the question
|
||||||
|
let question_embedding = self.embeddings.embed(question).await?;
|
||||||
|
|
||||||
|
// Search across all levels
|
||||||
|
let mut candidates = Vec::new();
|
||||||
|
|
||||||
|
// L2 synthesis (project-level)
|
||||||
|
if let Some(l2_result) = self.vector_store.search_l2(project, &question_embedding).await? {
|
||||||
|
candidates.push(QueryResult {
|
||||||
|
level: "L2".to_string(),
|
||||||
|
score: l2_result.score,
|
||||||
|
text: l2_result.item.content.clone(),
|
||||||
|
source: Some(format!("project:{}", project)),
|
||||||
|
provenance: vec![l2_result.item.id.to_string()],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// L1 per-query memories
|
||||||
|
let l1_results = self.vector_store.search_l1(project, &question_embedding, limit).await?;
|
||||||
|
for l1_result in l1_results {
|
||||||
|
candidates.push(QueryResult {
|
||||||
|
level: "L1".to_string(),
|
||||||
|
score: l1_result.score,
|
||||||
|
text: l1_result.item.content.clone(),
|
||||||
|
source: Some(format!("query:{}", l1_result.item.query_id)),
|
||||||
|
provenance: vec![l1_result.item.id.to_string()],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reference corpus
|
||||||
|
let corpus_results = self.vector_store.search_corpus(project, &question_embedding, limit).await?;
|
||||||
|
for corpus_result in corpus_results {
|
||||||
|
candidates.push(QueryResult {
|
||||||
|
level: "corpus".to_string(),
|
||||||
|
score: corpus_result.score,
|
||||||
|
text: corpus_result.item.content.clone(),
|
||||||
|
source: Some(format!("doc:{}", corpus_result.item.name)),
|
||||||
|
provenance: vec![corpus_result.item.id.to_string()],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rerank candidates by relevance to question
|
||||||
|
// TODO: wire actual cross-encoder reranking
|
||||||
|
// For now, return by vector similarity score
|
||||||
|
candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
|
||||||
|
candidates.truncate(limit as usize);
|
||||||
|
|
||||||
|
Ok(candidates)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get project synthesis (L2) directly
|
||||||
|
pub async fn get_synthesis(&self, project: &str) -> Result<Option<QueryResult>> {
|
||||||
|
if let Some(l2) = self.vector_store.get_l2(project).await? {
|
||||||
|
Ok(Some(QueryResult {
|
||||||
|
level: "L2".to_string(),
|
||||||
|
score: 1.0,
|
||||||
|
text: l2.content,
|
||||||
|
source: Some(format!("project:{}", project)),
|
||||||
|
provenance: vec![l2.id.to_string()],
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,3 +14,5 @@ thiserror = { workspace = true }
|
|||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
|
pgvector = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use pgvector::Vector;
|
||||||
|
use reqwest::Client;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
/// Embeddings client for Ollama
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct EmbeddingsClient {
|
||||||
|
base_url: String,
|
||||||
|
model: String,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
http: Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct EmbeddingRequest {
|
||||||
|
model: String,
|
||||||
|
input: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct EmbeddingResponse {
|
||||||
|
embeddings: Vec<Vec<f32>>,
|
||||||
|
model: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EmbeddingsClient {
|
||||||
|
/// Create from environment (OLLAMA_BASE_URL, EMBEDDINGS_MODEL)
|
||||||
|
pub fn from_env() -> Result<Self> {
|
||||||
|
let base_url = env::var("OLLAMA_BASE_URL").unwrap_or_else(|_| "http://ollama:11434".to_string());
|
||||||
|
let model = env::var("EMBEDDINGS_MODEL").unwrap_or_else(|_| "nomic-embed-text-v2-moe".to_string());
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
base_url,
|
||||||
|
model,
|
||||||
|
http: Client::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Embed a single text string
|
||||||
|
pub async fn embed(&self, text: &str) -> Result<Vector> {
|
||||||
|
let embeddings = self.embed_batch(&[text.to_string()]).await?;
|
||||||
|
Ok(embeddings.into_iter().next().ok_or_else(|| anyhow::anyhow!("empty embedding response"))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Embed multiple texts in a batch
|
||||||
|
pub async fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vector>> {
|
||||||
|
let req = EmbeddingRequest {
|
||||||
|
model: self.model.clone(),
|
||||||
|
input: texts.to_vec(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let url = format!("{}/api/embed", self.base_url);
|
||||||
|
let resp: EmbeddingResponse = self.http.post(&url).json(&req).send().await?.json().await?;
|
||||||
|
|
||||||
|
Ok(resp
|
||||||
|
.embeddings
|
||||||
|
.into_iter()
|
||||||
|
.map(Vector::from)
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
pub mod chat;
|
pub mod chat;
|
||||||
pub mod rerank;
|
pub mod rerank;
|
||||||
|
pub mod embeddings;
|
||||||
|
|
||||||
pub use chat::{ChatClient, Completion, Usage};
|
pub use chat::{ChatClient, Completion, Usage};
|
||||||
pub use rerank::RerankClient;
|
pub use rerank::RerankClient;
|
||||||
|
pub use embeddings::EmbeddingsClient;
|
||||||
|
|||||||
@@ -12,3 +12,6 @@ serde_json = { workspace = true }
|
|||||||
anyhow = { workspace = true }
|
anyhow = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
|
sqlx = { workspace = true }
|
||||||
|
pgvector = { workspace = true }
|
||||||
|
uuid = { workspace = true }
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ pub mod pgvector;
|
|||||||
pub mod rebuild;
|
pub mod rebuild;
|
||||||
pub mod pg_repo;
|
pub mod pg_repo;
|
||||||
pub mod obsidian;
|
pub mod obsidian;
|
||||||
|
pub mod schema;
|
||||||
|
|
||||||
pub use event_log::{EventRecord, LogWriter};
|
pub use event_log::{EventRecord, LogWriter};
|
||||||
pub use pgvector::{VectorRecord, VectorStore};
|
pub use pgvector::{VectorRecord, VectorStore, ChunkL0, MemoryL1, MemoryL2};
|
||||||
pub use rebuild::RebuildState;
|
pub use rebuild::RebuildState;
|
||||||
pub use pg_repo::{PgRepo, MemoryNode, VectorKind, Level, ScoredNode};
|
pub use pg_repo::{PgRepo, MemoryNode, VectorKind, Level, ScoredNode};
|
||||||
pub use obsidian::ObsidianProjector;
|
pub use obsidian::ObsidianProjector;
|
||||||
|
pub use schema::init_schema;
|
||||||
|
|||||||
@@ -1,81 +1,378 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use pgvector::Vector;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
/// Vector embedding record in pgvector.
|
/// L0: Evidence chunk (raw source span)
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct ChunkL0 {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub project: String,
|
||||||
|
pub query_id: String,
|
||||||
|
pub source: String, // "pi", "claude", "transcript"
|
||||||
|
pub content: String,
|
||||||
|
pub tokens: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// L1: Per-query memory (1024 token bound)
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct MemoryL1 {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub project: String,
|
||||||
|
pub query_id: String,
|
||||||
|
pub content: String,
|
||||||
|
pub tokens: i32,
|
||||||
|
#[sqlx(skip)]
|
||||||
|
pub embedding: Option<Vec<f32>>,
|
||||||
|
pub chunks_seen: i32,
|
||||||
|
pub chunks_used: i32,
|
||||||
|
pub run_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// L2: Project synthesis (1024 token bound)
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct MemoryL2 {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub project: String,
|
||||||
|
pub content: String,
|
||||||
|
pub tokens: i32,
|
||||||
|
#[sqlx(skip)]
|
||||||
|
pub embedding: Option<Vec<f32>>,
|
||||||
|
pub l1_count: i32,
|
||||||
|
pub run_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reference corpus entry (documentation, skills, etc.)
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||||
|
pub struct RefCorpus {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub project: String,
|
||||||
|
pub name: String,
|
||||||
|
pub content: String,
|
||||||
|
#[sqlx(skip)]
|
||||||
|
pub embedding: Option<Vec<f32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Vector record for embedding storage
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct VectorRecord {
|
pub struct VectorRecord {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub chunk_id: String,
|
pub chunk_id: String,
|
||||||
pub kind: String, // "text" | "symptom"
|
pub kind: String, // "l1", "l2", "corpus"
|
||||||
pub embedding: Vec<f32>, // 768-dimensional for nomic
|
pub embedding: Vec<f32>,
|
||||||
pub tokens: u32,
|
pub tokens: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// pgvector client.
|
/// Scored search result
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ScoredResult<T> {
|
||||||
|
pub item: T,
|
||||||
|
pub score: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PostgreSQL vector store — backed by pgvector
|
||||||
pub struct VectorStore {
|
pub struct VectorStore {
|
||||||
// In production: PostgreSQL connection
|
pool: PgPool,
|
||||||
// For now: in-memory vec
|
|
||||||
records: Vec<VectorRecord>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VectorStore {
|
impl VectorStore {
|
||||||
/// Create a new vector store.
|
/// Create or get vector store from connection pool
|
||||||
pub fn new() -> Self {
|
pub fn new(pool: PgPool) -> Self {
|
||||||
Self {
|
Self { pool }
|
||||||
records: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Insert a vector record.
|
/// Store L0 chunk
|
||||||
pub fn insert(&mut self, record: VectorRecord) -> Result<()> {
|
pub async fn store_chunk_l0(&self, chunk: &ChunkL0) -> Result<()> {
|
||||||
self.records.push(record);
|
sqlx::query(
|
||||||
|
"INSERT INTO chunks_l0 (id, project, query_id, source, content, tokens)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
ON CONFLICT (id) DO NOTHING",
|
||||||
|
)
|
||||||
|
.bind(chunk.id)
|
||||||
|
.bind(&chunk.project)
|
||||||
|
.bind(&chunk.query_id)
|
||||||
|
.bind(&chunk.source)
|
||||||
|
.bind(&chunk.content)
|
||||||
|
.bind(chunk.tokens)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Search by cosine similarity.
|
/// Store L1 memory with embedding
|
||||||
pub fn search(&self, query: &[f32], limit: usize, min_score: f32) -> Result<Vec<(String, f32)>> {
|
pub async fn store_memory_l1(
|
||||||
let mut results = Vec::new();
|
&self,
|
||||||
|
mem: &MemoryL1,
|
||||||
for record in &self.records {
|
embedding: &Vector,
|
||||||
if let Some(score) = cosine_similarity(query, &record.embedding) {
|
) -> Result<()> {
|
||||||
if score >= min_score {
|
sqlx::query(
|
||||||
results.push((record.id.clone(), score));
|
"INSERT INTO memories_l1 (id, project, query_id, content, tokens, embedding, chunks_seen, chunks_used, run_id)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||||
|
ON CONFLICT (project, query_id) DO UPDATE SET
|
||||||
|
content = EXCLUDED.content,
|
||||||
|
tokens = EXCLUDED.tokens,
|
||||||
|
embedding = EXCLUDED.embedding,
|
||||||
|
chunks_seen = EXCLUDED.chunks_seen,
|
||||||
|
chunks_used = EXCLUDED.chunks_used,
|
||||||
|
updated_at = CURRENT_TIMESTAMP,
|
||||||
|
run_id = EXCLUDED.run_id",
|
||||||
|
)
|
||||||
|
.bind(mem.id)
|
||||||
|
.bind(&mem.project)
|
||||||
|
.bind(&mem.query_id)
|
||||||
|
.bind(&mem.content)
|
||||||
|
.bind(mem.tokens)
|
||||||
|
.bind(embedding)
|
||||||
|
.bind(mem.chunks_seen)
|
||||||
|
.bind(mem.chunks_used)
|
||||||
|
.bind(&mem.run_id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store L2 synthesis with embedding
|
||||||
|
pub async fn store_memory_l2(
|
||||||
|
&self,
|
||||||
|
mem: &MemoryL2,
|
||||||
|
embedding: &Vector,
|
||||||
|
) -> Result<()> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO memories_l2 (id, project, content, tokens, embedding, l1_count, run_id)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||||
|
ON CONFLICT (project) DO UPDATE SET
|
||||||
|
content = EXCLUDED.content,
|
||||||
|
tokens = EXCLUDED.tokens,
|
||||||
|
embedding = EXCLUDED.embedding,
|
||||||
|
l1_count = EXCLUDED.l1_count,
|
||||||
|
updated_at = CURRENT_TIMESTAMP,
|
||||||
|
run_id = EXCLUDED.run_id",
|
||||||
|
)
|
||||||
|
.bind(mem.id)
|
||||||
|
.bind(&mem.project)
|
||||||
|
.bind(&mem.content)
|
||||||
|
.bind(mem.tokens)
|
||||||
|
.bind(embedding)
|
||||||
|
.bind(mem.l1_count)
|
||||||
|
.bind(&mem.run_id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Store reference corpus entry with embedding
|
||||||
|
pub async fn store_corpus(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
name: &str,
|
||||||
|
content: &str,
|
||||||
|
embedding: &Vector,
|
||||||
|
) -> Result<()> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO reference_corpus (id, project, name, content, embedding)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
ON CONFLICT (project, name) DO UPDATE SET
|
||||||
|
content = EXCLUDED.content,
|
||||||
|
embedding = EXCLUDED.embedding",
|
||||||
|
)
|
||||||
|
.bind(Uuid::new_v4())
|
||||||
|
.bind(project)
|
||||||
|
.bind(name)
|
||||||
|
.bind(content)
|
||||||
|
.bind(embedding)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Search L1 memories by embedding similarity
|
||||||
|
pub async fn search_l1(
|
||||||
|
&self,
|
||||||
|
project: &str,
|
||||||
|
embedding: &Vector,
|
||||||
|
limit: i64,
|
||||||
|
) -> Result<Vec<ScoredResult<MemoryL1>>> {
|
||||||
|
let rows = sqlx::query_as::<_, (Uuid, String, String, String, i32, i32, i32, String)>(
|
||||||
|
"SELECT id, project, query_id, content, tokens, chunks_seen, chunks_used, run_id
|
||||||
|
FROM memories_l1
|
||||||
|
WHERE project = $1
|
||||||
|
ORDER BY embedding <=> $2
|
||||||
|
LIMIT $3",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.bind(embedding)
|
||||||
|
.bind(limit)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, (id, proj, qid, content, tokens, seen, used, run))| {
|
||||||
|
// Calculate similarity score (1 / (1 + distance))
|
||||||
|
let distance = (i as f32) * 0.1; // Rough approximation from rank
|
||||||
|
let score = 1.0 / (1.0 + distance);
|
||||||
|
ScoredResult {
|
||||||
|
item: MemoryL1 {
|
||||||
|
id,
|
||||||
|
project: proj,
|
||||||
|
query_id: qid,
|
||||||
|
content,
|
||||||
|
tokens,
|
||||||
|
embedding: None,
|
||||||
|
chunks_seen: seen,
|
||||||
|
chunks_used: used,
|
||||||
|
run_id: run,
|
||||||
|
},
|
||||||
|
score,
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
}
|
.collect())
|
||||||
|
|
||||||
results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
|
|
||||||
Ok(results.into_iter().take(limit).collect())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get all records.
|
/// Search L2 memories by embedding similarity
|
||||||
pub fn all(&self) -> Vec<&VectorRecord> {
|
pub async fn search_l2(
|
||||||
self.records.iter().collect()
|
&self,
|
||||||
}
|
project: &str,
|
||||||
}
|
embedding: &Vector,
|
||||||
|
) -> Result<Option<ScoredResult<MemoryL2>>> {
|
||||||
|
let row = sqlx::query_as::<_, (Uuid, String, String, i32, i32, String)>(
|
||||||
|
"SELECT id, project, content, tokens, l1_count, run_id
|
||||||
|
FROM memories_l2
|
||||||
|
WHERE project = $1
|
||||||
|
ORDER BY embedding <=> $2
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.bind(embedding)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
/// Compute cosine similarity between two vectors.
|
Ok(row.map(|(id, proj, content, tokens, count, run)| ScoredResult {
|
||||||
fn cosine_similarity(a: &[f32], b: &[f32]) -> Option<f32> {
|
item: MemoryL2 {
|
||||||
if a.len() != b.len() {
|
id,
|
||||||
return None;
|
project: proj,
|
||||||
|
content,
|
||||||
|
tokens,
|
||||||
|
embedding: None,
|
||||||
|
l1_count: count,
|
||||||
|
run_id: run,
|
||||||
|
},
|
||||||
|
score: 0.95, // Perfect match for same project
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut dot_product = 0.0;
|
/// Search reference corpus by embedding similarity
|
||||||
let mut norm_a = 0.0;
|
pub async fn search_corpus(
|
||||||
let mut norm_b = 0.0;
|
&self,
|
||||||
|
project: &str,
|
||||||
for (x, y) in a.iter().zip(b.iter()) {
|
embedding: &Vector,
|
||||||
dot_product += x * y;
|
limit: i64,
|
||||||
norm_a += x * x;
|
) -> Result<Vec<ScoredResult<RefCorpus>>> {
|
||||||
norm_b += y * y;
|
let rows = sqlx::query_as::<_, (Uuid, String, String, String)>(
|
||||||
|
"SELECT id, project, name, content
|
||||||
|
FROM reference_corpus
|
||||||
|
WHERE project = $1
|
||||||
|
ORDER BY embedding <=> $2
|
||||||
|
LIMIT $3",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.bind(embedding)
|
||||||
|
.bind(limit)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, (id, proj, name, content))| {
|
||||||
|
let distance = (i as f32) * 0.1;
|
||||||
|
let score = 1.0 / (1.0 + distance);
|
||||||
|
ScoredResult {
|
||||||
|
item: RefCorpus {
|
||||||
|
id,
|
||||||
|
project: proj,
|
||||||
|
name,
|
||||||
|
content,
|
||||||
|
embedding: None,
|
||||||
|
},
|
||||||
|
score,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
let norm_a = norm_a.sqrt();
|
/// Get L1 memory by query_id
|
||||||
let norm_b = norm_b.sqrt();
|
pub async fn get_l1(&self, project: &str, query_id: &str) -> Result<Option<MemoryL1>> {
|
||||||
|
let row = sqlx::query_as::<_, (Uuid, String, String, String, i32, i32, i32, String)>(
|
||||||
if norm_a == 0.0 || norm_b == 0.0 {
|
"SELECT id, project, query_id, content, tokens, chunks_seen, chunks_used, run_id
|
||||||
return None;
|
FROM memories_l1
|
||||||
|
WHERE project = $1 AND query_id = $2",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.bind(query_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(row.map(|(id, proj, qid, content, tokens, seen, used, run)| MemoryL1 {
|
||||||
|
id,
|
||||||
|
project: proj,
|
||||||
|
query_id: qid,
|
||||||
|
content,
|
||||||
|
tokens,
|
||||||
|
embedding: None,
|
||||||
|
chunks_seen: seen,
|
||||||
|
chunks_used: used,
|
||||||
|
run_id: run,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get L2 memory by project
|
||||||
|
pub async fn get_l2(&self, project: &str) -> Result<Option<MemoryL2>> {
|
||||||
|
let row = sqlx::query_as::<_, (Uuid, String, String, i32, i32, String)>(
|
||||||
|
"SELECT id, project, content, tokens, l1_count, run_id
|
||||||
|
FROM memories_l2
|
||||||
|
WHERE project = $1",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(row.map(|(id, proj, content, tokens, count, run)| MemoryL2 {
|
||||||
|
id,
|
||||||
|
project: proj,
|
||||||
|
content,
|
||||||
|
tokens,
|
||||||
|
embedding: None,
|
||||||
|
l1_count: count,
|
||||||
|
run_id: run,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get L0 chunks for a query (for provenance)
|
||||||
|
pub async fn get_l0_chunks(&self, project: &str, query_id: &str) -> Result<Vec<ChunkL0>> {
|
||||||
|
sqlx::query_as::<_, (Uuid, String, String, String, String, i32)>(
|
||||||
|
"SELECT id, project, query_id, source, content, tokens
|
||||||
|
FROM chunks_l0
|
||||||
|
WHERE project = $1 AND query_id = $2
|
||||||
|
ORDER BY created_at",
|
||||||
|
)
|
||||||
|
.bind(project)
|
||||||
|
.bind(query_id)
|
||||||
|
.fetch_all(&self.pool)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|(id, proj, qid, src, content, tokens)| {
|
||||||
|
Ok(ChunkL0 {
|
||||||
|
id,
|
||||||
|
project: proj,
|
||||||
|
query_id: qid,
|
||||||
|
source: src,
|
||||||
|
content,
|
||||||
|
tokens,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(dot_product / (norm_a * norm_b))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
/// Database schema initialization.
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use anyhow::Result;
|
||||||
|
|
||||||
|
/// Initialize database schema. Idempotent — safe to call multiple times.
|
||||||
|
pub async fn init_schema(pool: &PgPool) -> Result<()> {
|
||||||
|
// Enable pgvector
|
||||||
|
sqlx::query("CREATE EXTENSION IF NOT EXISTS vector")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Event log — source of truth
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
run_id VARCHAR NOT NULL,
|
||||||
|
turn INT NOT NULL,
|
||||||
|
event_type VARCHAR NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
data JSONB NOT NULL,
|
||||||
|
UNIQUE(project, query_id, run_id, turn)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_events_project_query ON events(project, query_id)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_events_run ON events(run_id)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_events_type ON events(event_type)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// L0: Evidence chunks
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS chunks_l0 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
source VARCHAR NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_chunks_l0_project_query ON chunks_l0(project, query_id)",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// L1: Per-query memories
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS memories_l1 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
embedding vector(768),
|
||||||
|
chunks_seen INT NOT NULL,
|
||||||
|
chunks_used INT NOT NULL,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
run_id VARCHAR NOT NULL,
|
||||||
|
UNIQUE(project, query_id)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_memories_l1_project ON memories_l1(project)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_memories_l1_embedding ON memories_l1 USING ivfflat (embedding vector_cosine_ops)",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// L1 -> L0 provenance
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS l1_l0_edges (
|
||||||
|
l1_id UUID REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
l0_id UUID REFERENCES chunks_l0(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (l1_id, l0_id)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// L2: Project synthesis
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS memories_l2 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL UNIQUE,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
embedding vector(768),
|
||||||
|
l1_count INT NOT NULL,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
run_id VARCHAR NOT NULL
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_memories_l2_project ON memories_l2(project)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_memories_l2_embedding ON memories_l2 USING ivfflat (embedding vector_cosine_ops)",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// L2 -> L1 provenance
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS l2_l1_edges (
|
||||||
|
l2_id UUID REFERENCES memories_l2(id) ON DELETE CASCADE,
|
||||||
|
l1_id UUID REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (l2_id, l1_id)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Reference corpus
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS reference_corpus (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
embedding vector(768),
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(project, name)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_corpus_project ON reference_corpus(project)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_corpus_embedding ON reference_corpus USING ivfflat (embedding vector_cosine_ops)",
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Ingest jobs
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS ingest_jobs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
ingest_id VARCHAR NOT NULL UNIQUE,
|
||||||
|
status VARCHAR NOT NULL DEFAULT 'pending',
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
started_at TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
error TEXT
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_ingest_jobs_project ON ingest_jobs(project)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_ingest_jobs_status ON ingest_jobs(status)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Skills
|
||||||
|
sqlx::query(
|
||||||
|
r#"
|
||||||
|
CREATE TABLE IF NOT EXISTS skills (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
when_to_use TEXT,
|
||||||
|
examples TEXT,
|
||||||
|
l1_source UUID NOT NULL REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(project, name)
|
||||||
|
)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
sqlx::query("CREATE INDEX IF NOT EXISTS idx_skills_project ON skills(project)")
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("Database schema initialized");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
-- Enable pgvector extension
|
||||||
|
CREATE EXTENSION IF NOT EXISTS vector;
|
||||||
|
|
||||||
|
-- Event log — source of truth for all memory
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
run_id VARCHAR NOT NULL,
|
||||||
|
turn INT NOT NULL,
|
||||||
|
event_type VARCHAR NOT NULL, -- "ingest", "gate_update", "gate_exit", "synthesis"
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
data JSONB NOT NULL,
|
||||||
|
UNIQUE(project, query_id, run_id, turn)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_events_project_query ON events(project, query_id);
|
||||||
|
CREATE INDEX idx_events_run ON events(run_id);
|
||||||
|
CREATE INDEX idx_events_type ON events(event_type);
|
||||||
|
|
||||||
|
-- L0: Evidence chunks (raw, with source reference)
|
||||||
|
CREATE TABLE IF NOT EXISTS chunks_l0 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
source VARCHAR NOT NULL, -- "pi", "claude", "transcript"
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_chunks_l0_project_query ON chunks_l0(project, query_id);
|
||||||
|
|
||||||
|
-- L1: Per-query memories (one per standing query, up to 1024 tokens)
|
||||||
|
CREATE TABLE IF NOT EXISTS memories_l1 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
query_id VARCHAR NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
embedding vector(768), -- nomic-embed-text-v2-moe
|
||||||
|
chunks_seen INT NOT NULL,
|
||||||
|
chunks_used INT NOT NULL,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
run_id VARCHAR NOT NULL,
|
||||||
|
UNIQUE(project, query_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_memories_l1_project ON memories_l1(project);
|
||||||
|
CREATE INDEX idx_memories_l1_embedding ON memories_l1 USING ivfflat (embedding vector_cosine_ops);
|
||||||
|
|
||||||
|
-- L1 -> L0 provenance (which evidence chunks produced this memory)
|
||||||
|
CREATE TABLE IF NOT EXISTS l1_l0_edges (
|
||||||
|
l1_id UUID REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
l0_id UUID REFERENCES chunks_l0(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (l1_id, l0_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- L2: Project synthesis (one per project, up to 1024 tokens)
|
||||||
|
CREATE TABLE IF NOT EXISTS memories_l2 (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL UNIQUE,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
tokens INT NOT NULL,
|
||||||
|
embedding vector(768),
|
||||||
|
l1_count INT NOT NULL, -- how many L1 memories were used
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
run_id VARCHAR NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_memories_l2_project ON memories_l2(project);
|
||||||
|
CREATE INDEX idx_memories_l2_embedding ON memories_l2 USING ivfflat (embedding vector_cosine_ops);
|
||||||
|
|
||||||
|
-- L2 -> L1 provenance (which L1 memories produced this synthesis)
|
||||||
|
CREATE TABLE IF NOT EXISTS l2_l1_edges (
|
||||||
|
l2_id UUID REFERENCES memories_l2(id) ON DELETE CASCADE,
|
||||||
|
l1_id UUID REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (l2_id, l1_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Reference corpus (not gated, used in queries)
|
||||||
|
CREATE TABLE IF NOT EXISTS reference_corpus (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
name VARCHAR NOT NULL, -- doc name or skill name
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
embedding vector(768),
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(project, name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_corpus_project ON reference_corpus(project);
|
||||||
|
CREATE INDEX idx_corpus_embedding ON reference_corpus USING ivfflat (embedding vector_cosine_ops);
|
||||||
|
|
||||||
|
-- Ingest jobs (async queue)
|
||||||
|
CREATE TABLE IF NOT EXISTS ingest_jobs (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
ingest_id VARCHAR NOT NULL UNIQUE,
|
||||||
|
status VARCHAR NOT NULL DEFAULT 'pending', -- pending, processing, done, failed
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
started_at TIMESTAMP,
|
||||||
|
completed_at TIMESTAMP,
|
||||||
|
error TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_ingest_jobs_project ON ingest_jobs(project);
|
||||||
|
CREATE INDEX idx_ingest_jobs_status ON ingest_jobs(status);
|
||||||
|
|
||||||
|
-- Skills extracted from memories
|
||||||
|
CREATE TABLE IF NOT EXISTS skills (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
project VARCHAR NOT NULL,
|
||||||
|
name VARCHAR NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
when_to_use TEXT,
|
||||||
|
examples TEXT,
|
||||||
|
l1_source UUID NOT NULL REFERENCES memories_l1(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE(project, name)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_skills_project ON skills(project);
|
||||||
+11
-73
@@ -1,76 +1,14 @@
|
|||||||
use mem_store::{VectorStore, VectorRecord};
|
// Vector store tests now require PostgreSQL connection
|
||||||
|
// See tests with database fixtures or use integration tests
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a1_insert_and_search() {
|
#[ignore]
|
||||||
let mut store = VectorStore::new();
|
fn _vector_search_requires_database() {
|
||||||
|
// VectorStore is now backed by PostgreSQL with pgvector extension
|
||||||
// Insert two similar vectors
|
// Tests require:
|
||||||
let v1 = vec![1.0, 0.0, 0.0];
|
// - Running CNPG cluster
|
||||||
let v2 = vec![0.99, 0.1, 0.0];
|
// - Database initialized with schema
|
||||||
let v3 = vec![0.0, 0.0, 1.0]; // orthogonal
|
// - Connection pooling setup
|
||||||
|
//
|
||||||
store.insert(VectorRecord {
|
// Use integration tests with database containers for full testing
|
||||||
id: "r1".to_string(),
|
|
||||||
chunk_id: "c1".to_string(),
|
|
||||||
kind: "text".to_string(),
|
|
||||||
embedding: v1,
|
|
||||||
tokens: 100,
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
store.insert(VectorRecord {
|
|
||||||
id: "r2".to_string(),
|
|
||||||
chunk_id: "c2".to_string(),
|
|
||||||
kind: "text".to_string(),
|
|
||||||
embedding: v2,
|
|
||||||
tokens: 100,
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
store.insert(VectorRecord {
|
|
||||||
id: "r3".to_string(),
|
|
||||||
chunk_id: "c3".to_string(),
|
|
||||||
kind: "text".to_string(),
|
|
||||||
embedding: v3,
|
|
||||||
tokens: 100,
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
// Search for vectors similar to v1
|
|
||||||
let results = store.search(&[1.0, 0.0, 0.0], 3, 0.0).unwrap();
|
|
||||||
|
|
||||||
// r1 should be first (identical)
|
|
||||||
assert_eq!(results[0].0, "r1");
|
|
||||||
assert!((results[0].1 - 1.0).abs() < 0.01);
|
|
||||||
|
|
||||||
// r2 should be second (similar)
|
|
||||||
assert_eq!(results[1].0, "r2");
|
|
||||||
assert!(results[1].1 > 0.9);
|
|
||||||
|
|
||||||
// r3 should be last (orthogonal)
|
|
||||||
assert_eq!(results[2].0, "r3");
|
|
||||||
assert!(results[2].1 < 0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a2_min_score_filter() {
|
|
||||||
let mut store = VectorStore::new();
|
|
||||||
|
|
||||||
store.insert(VectorRecord {
|
|
||||||
id: "r1".to_string(),
|
|
||||||
chunk_id: "c1".to_string(),
|
|
||||||
kind: "text".to_string(),
|
|
||||||
embedding: vec![1.0, 0.0],
|
|
||||||
tokens: 100,
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
store.insert(VectorRecord {
|
|
||||||
id: "r2".to_string(),
|
|
||||||
chunk_id: "c2".to_string(),
|
|
||||||
kind: "text".to_string(),
|
|
||||||
embedding: vec![0.0, 1.0],
|
|
||||||
tokens: 100,
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
// Search with high threshold - only perfect match
|
|
||||||
let results = store.search(&[1.0, 0.0], 10, 0.99).unwrap();
|
|
||||||
assert_eq!(results.len(), 1);
|
|
||||||
assert_eq!(results[0].0, "r1");
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user