Skip to main content

codewhale_memory/
store.rs

1use crate::{
2    Error, Result,
3    auth::{Access, Capability},
4    model::*,
5    policy,
6};
7use rusqlite::{Connection, OptionalExtension, Row, TransactionBehavior, named_params, params};
8use std::{
9    collections::BTreeMap,
10    fs,
11    io::Write,
12    path::Path,
13    sync::Arc,
14    time::{Duration, SystemTime, UNIX_EPOCH},
15};
16use uuid::Uuid;
17
18/// Whether this path's directory refuses the mode a file is created with *and*
19/// the one it is then asked for.
20///
21/// Some mounts synthesise mode bits instead of storing them: HarmonyOS hmdfs
22/// (the 2in1 user directory) reports a group-readable mode for every file an
23/// app creates, and `chmod` answers `EPERM` because that owner is not the
24/// calling process. There the mode says nothing about who can
25/// read the database, and refusing the store would leave the platform with no
26/// memory database at all. This creates one probe file at `0600` beside `path`,
27/// and — when the mode came back wider — asks the mount to narrow it and looks
28/// again. A default ACL or a setgid parent widens a new file on a filesystem
29/// that stores modes perfectly well; such a mount honours the second request
30/// and keeps the strict refusal, because its mode really does describe access.
31///
32/// Any failure to run the probe answers `false`, so a directory we cannot write
33/// to keeps the strict check rather than being reclassified as a mount limit.
34///
35/// The same rule, with the same reasoning, lives in
36/// `codewhale_config::private_directory::private_footing`; this crate has no
37/// dependency on it and the probe is a dozen lines, so it is repeated here
38/// rather than widening this crate's dependency graph.
39#[cfg(unix)]
40fn mount_ignores_unix_modes(path: &Path) -> bool {
41    use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
42
43    let Some(parent) = path
44        .parent()
45        .filter(|parent| !parent.as_os_str().is_empty())
46    else {
47        return false;
48    };
49    let probe = parent.join(format!(
50        ".codewhale-mode-probe-{}-{}",
51        std::process::id(),
52        SystemTime::now()
53            .duration_since(UNIX_EPOCH)
54            .map_or(0, |elapsed| elapsed.subsec_nanos())
55    ));
56    let created = fs::OpenOptions::new()
57        .write(true)
58        .create_new(true)
59        .mode(0o600)
60        .open(&probe);
61    let Ok(file) = created else { return false };
62    let private = |file: &fs::File| {
63        file.metadata()
64            .is_ok_and(|metadata| metadata.permissions().mode() & 0o077 == 0)
65    };
66    let wider = file
67        .metadata()
68        .is_ok_and(|metadata| metadata.permissions().mode() & 0o077 != 0);
69    let refuses_narrowing = wider
70        && match file.set_permissions(fs::Permissions::from_mode(0o600)) {
71            Ok(()) => !private(&file),
72            Err(_) => true,
73        };
74    drop(file);
75    let _ = fs::remove_file(&probe);
76    refuses_narrowing
77}
78
79/// Nesting-safe transaction scope for `&self` methods. rusqlite's
80/// `unchecked_transaction` issues a literal `BEGIN`, which fails inside an
81/// already-open transaction; engine methods compose inside each other's
82/// scopes (e.g. `prepare_context` → `recall`), so this issues a `SAVEPOINT`
83/// instead — a top-level savepoint behaves as a deferred transaction, and a
84/// nested one rolls back only its own work when dropped uncommitted.
85pub(crate) struct Tx<'c> {
86    conn: &'c Connection,
87    name: String,
88    done: bool,
89}
90static TX_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
91impl<'c> Tx<'c> {
92    pub(crate) fn begin(conn: &'c Connection) -> Result<Self> {
93        let name = format!(
94            "tx_{}",
95            TX_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
96        );
97        conn.execute_batch(&format!("SAVEPOINT \"{name}\""))?;
98        Ok(Self {
99            conn,
100            name,
101            done: false,
102        })
103    }
104    pub(crate) fn commit(mut self) -> Result<()> {
105        self.conn
106            .execute_batch(&format!("RELEASE \"{}\"", self.name))?;
107        self.done = true;
108        Ok(())
109    }
110}
111impl Drop for Tx<'_> {
112    fn drop(&mut self) {
113        if !self.done {
114            let _ = self
115                .conn
116                .execute_batch(&format!("ROLLBACK TO \"{0}\"; RELEASE \"{0}\"", self.name));
117        }
118    }
119}
120
121const APP_ID: i64 = 1129794866;
122const SCHEMA: &str = include_str!("sql/schema.sql");
123const ELIGIBLE: &str = include_str!("sql/eligible.sql");
124const SELECT: &str = "m.id,m.revision,m.status,m.payload,m.created_at,m.updated_at,m.content_hash";
125
126/// Vendor-neutral lifecycle seam. Transport adapters must preserve authorization,
127/// revision checks, freshness, correction and forgetting, not just store/search.
128pub trait MemoryBackend: Send {
129    fn capture(&mut self, access: &Access, request: &str, draft: Draft) -> Result<CaptureReceipt>;
130    fn get(&self, access: &Access, id: &str) -> Result<Memory>;
131    fn recall(&self, access: &Access, query: &Recall) -> Result<RecallReport>;
132    fn approve(
133        &mut self,
134        access: &Access,
135        id: &str,
136        revision: i64,
137        validation: Option<&ValidationReceipt>,
138        snapshot: &Snapshot,
139    ) -> Result<Memory>;
140    fn reject(&mut self, access: &Access, id: &str, revision: i64) -> Result<Memory>;
141    fn supersede(
142        &mut self,
143        access: &Access,
144        old: (&str, i64),
145        new: (&str, i64),
146        validation: Option<&ValidationReceipt>,
147        snapshot: &Snapshot,
148    ) -> Result<Memory>;
149    fn forget(&mut self, access: &Access, id: &str, revision: i64) -> Result<ForgetReport>;
150    fn save_checkpoint(
151        &mut self,
152        access: &Access,
153        draft: CheckpointDraft,
154        expected_revision: Option<i64>,
155        snapshot: &Snapshot,
156    ) -> Result<Checkpoint>;
157    fn resume(
158        &self,
159        access: &Access,
160        scope: &Scope,
161        key: &str,
162        snapshot: &Snapshot,
163    ) -> Result<Resume>;
164}
165
166pub struct Store {
167    pub(crate) conn: Connection,
168    clock: Arc<dyn Fn() -> i64 + Send + Sync>,
169}
170fn now() -> i64 {
171    SystemTime::now()
172        .duration_since(UNIX_EPOCH)
173        .unwrap_or_default()
174        .as_secs() as i64
175}
176fn row_memory(row: &Row<'_>) -> rusqlite::Result<Memory> {
177    let json: String = row.get(3)?;
178    let status: String = row.get(2)?;
179    let decode = |e: Box<dyn std::error::Error + Send + Sync>| {
180        rusqlite::Error::FromSqlConversionFailure(3, rusqlite::types::Type::Text, e)
181    };
182    Ok(Memory {
183        id: row.get(0)?,
184        revision: row.get(1)?,
185        status: Status::parse(&status).map_err(|e| decode(Box::new(e)))?,
186        draft: serde_json::from_str(&json).map_err(|e| decode(Box::new(e)))?,
187        created_at: row.get(4)?,
188        updated_at: row.get(5)?,
189        content_hash: row.get(6)?,
190    })
191}
192fn event(
193    conn: &Connection,
194    access: &Access,
195    id: &str,
196    action: &str,
197    revision: i64,
198    now: i64,
199) -> Result<()> {
200    conn.execute(
201        "INSERT INTO events(entity_id,action,actor_hash,revision,at) VALUES(?1,?2,?3,?4,?5)",
202        params![id, action, access.actor_hash(), revision, now],
203    )?;
204    Ok(())
205}
206fn get_at(conn: &Connection, access: &Access, id: &str) -> Result<Memory> {
207    access.require(Capability::Read)?;
208    let sql = format!(
209        "SELECT {SELECT} FROM memories m WHERE m.id=?1 AND m.scope IN (SELECT value FROM json_each(?2))"
210    );
211    conn.query_row(&sql, params![id, access.scope_json()?], row_memory)
212        .optional()?
213        .ok_or(Error::NotFound)
214}
215pub(crate) fn effective_freshness(
216    conn: &Connection,
217    access: &Access,
218    memory: &Memory,
219    snapshot: &Snapshot,
220    now: i64,
221) -> Result<Freshness> {
222    let own = memory.freshness(snapshot, now);
223    if own != Freshness::Current {
224        return Ok(own);
225    }
226    let mut pending = memory.draft.parent_ids.clone();
227    let mut seen = std::collections::BTreeSet::new();
228    while let Some(id) = pending.pop() {
229        if !seen.insert(id.clone()) {
230            continue;
231        }
232        if seen.len() > 4096 {
233            return Ok(Freshness::Unknown);
234        }
235        let parent = match get_at(conn, access, &id) {
236            Ok(m) => m,
237            Err(Error::NotFound) => return Ok(Freshness::Unknown),
238            Err(e) => return Err(e),
239        };
240        let freshness = parent.freshness(snapshot, now);
241        if freshness != Freshness::Current {
242            return Ok(if freshness == Freshness::Inactive {
243                Freshness::Changed
244            } else {
245                freshness
246            });
247        }
248        pending.extend(parent.draft.parent_ids);
249    }
250    Ok(Freshness::Current)
251}
252fn require_revision(m: &Memory, expected: i64) -> Result<()> {
253    if m.revision == expected {
254        Ok(())
255    } else {
256        Err(Error::RevisionConflict)
257    }
258}
259fn ensure_key_available(
260    conn: &Connection,
261    access: &Access,
262    draft: &Draft,
263    except: Option<&str>,
264    now: i64,
265) -> Result<()> {
266    if let Some(key) = &draft.key {
267        let old: Option<(String,i64,Option<i64>)> = conn.query_row(
268            "SELECT id,revision,expires_at FROM memories WHERE scope=?1 AND semantic_key=?2 AND status='active'",
269            params![draft.scope.key()?,key],|r| Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
270        if let Some((id, rev, expiry)) = old {
271            if Some(id.as_str()) == except {
272                return Ok(());
273            }
274            if expiry.is_some_and(|t| t <= now) {
275                conn.execute("UPDATE memories SET status='stale',revision=revision+1,updated_at=?2 WHERE id=?1",params![id,now])?;
276                event(conn, access, &id, "expired", rev + 1, now)?;
277                invalidate_descendants(conn, access, &id, now)?;
278            } else {
279                return Err(Error::KeyConflict);
280            }
281        }
282    }
283    Ok(())
284}
285fn descendants(conn: &Connection, id: &str) -> Result<Vec<String>> {
286    let mut q = conn.prepare("WITH RECURSIVE children(id) AS (SELECT child_id FROM lineage WHERE parent_id=?1 UNION SELECT l.child_id FROM lineage l JOIN children c ON l.parent_id=c.id) SELECT id FROM children ORDER BY id")?;
287    Ok(q.query_map([id], |r| r.get(0))?
288        .collect::<rusqlite::Result<Vec<_>>>()?)
289}
290fn invalidate_descendants(conn: &Connection, access: &Access, id: &str, now: i64) -> Result<()> {
291    for child in descendants(conn, id)? {
292        let m = get_at(conn, access, &child)?;
293        if m.status == Status::Active {
294            conn.execute(
295                "UPDATE memories SET status='stale',revision=revision+1,updated_at=?2 WHERE id=?1",
296                params![child, now],
297            )?;
298            event(
299                conn,
300                access,
301                &child,
302                "parent_invalidated",
303                m.revision + 1,
304                now,
305            )?;
306        }
307    }
308    Ok(())
309}
310fn check_activation(
311    conn: &Connection,
312    access: &Access,
313    m: &Memory,
314    receipt: Option<&ValidationReceipt>,
315    snapshot: &Snapshot,
316    now: i64,
317) -> Result<()> {
318    if m.status != Status::Candidate {
319        return Err(Error::InvalidState);
320    }
321    let mut projected = m.clone();
322    projected.status = Status::Active;
323    if effective_freshness(conn, access, &projected, snapshot, now)? != Freshness::Current {
324        return Err(Error::InvalidState);
325    }
326    for parent in &m.draft.parent_ids {
327        let p = get_at(conn, access, parent)?;
328        if p.status != Status::Active
329            || effective_freshness(conn, access, &p, snapshot, now)? != Freshness::Current
330        {
331            return Err(Error::InvalidParent);
332        }
333    }
334    if matches!(m.draft.kind, Kind::Procedure | Kind::Lesson) && receipt.is_none() {
335        return Err(Error::ValidationRequired);
336    }
337    if let Some(receipt) = receipt {
338        if !receipt.passed || receipt.content_hash != m.content_hash {
339            return Err(Error::ValidationRequired);
340        }
341        policy::bounded(&receipt.validator, "validator", 256, true)?;
342        policy::bounded(&receipt.evidence_uri, "validation evidence URI", 1024, true)?;
343        policy::ensure_no_secret(&serde_json::to_string(receipt)?)?;
344    }
345    Ok(())
346}
347fn activate(
348    conn: &Connection,
349    access: &Access,
350    m: &Memory,
351    receipt: Option<&ValidationReceipt>,
352    now: i64,
353) -> Result<()> {
354    conn.execute(
355        "UPDATE memories SET status='active',revision=revision+1,updated_at=?2 WHERE id=?1",
356        params![m.id, now],
357    )?;
358    if let Some(r) = receipt {
359        conn.execute(
360            "INSERT INTO validations(memory_id,receipt) VALUES(?1,?2)",
361            params![m.id, serde_json::to_string(r)?],
362        )?;
363    }
364    event(conn, access, &m.id, "approved", m.revision + 1, now)?;
365    Ok(())
366}
367impl Store {
368    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
369        let path = path.as_ref();
370        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty())
371            && !parent.exists()
372        {
373            #[cfg(unix)]
374            {
375                use std::os::unix::fs::DirBuilderExt;
376                fs::DirBuilder::new()
377                    .recursive(true)
378                    .mode(0o700)
379                    .create(parent)?;
380            }
381            #[cfg(not(unix))]
382            fs::create_dir_all(parent)?;
383        }
384        // Explicit local file security. No URI filenames and no extension loading.
385        match fs::symlink_metadata(path) {
386            Ok(meta) => Self::check_database_file(path, &meta)?,
387            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
388                let mut opts = fs::OpenOptions::new();
389                opts.write(true).create_new(true);
390                #[cfg(unix)]
391                {
392                    use std::os::unix::fs::OpenOptionsExt;
393                    opts.mode(0o600);
394                }
395                match opts.open(path) {
396                    Ok(_) => (),
397                    Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
398                        return Self::open(path);
399                    }
400                    Err(e) => return Err(e.into()),
401                }
402            }
403            Err(e) => return Err(e.into()),
404        }
405        let conn = Connection::open_with_flags(
406            path,
407            rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
408        )?;
409        Self::from_connection(conn, Arc::new(now))
410    }
411    fn check_database_file(_path: &Path, meta: &fs::Metadata) -> Result<()> {
412        if meta.file_type().is_symlink() || !meta.is_file() {
413            return Err(Error::Invalid(
414                "database must be a regular, non-symlink file".into(),
415            ));
416        }
417        #[cfg(unix)]
418        {
419            use std::os::unix::fs::PermissionsExt;
420            if meta.permissions().mode() & 0o077 != 0 && !mount_ignores_unix_modes(_path) {
421                return Err(Error::Invalid(
422                    "database permissions must exclude group and world access".into(),
423                ));
424            }
425        }
426        Ok(())
427    }
428    pub fn open_for_listing(path: &Path) -> Result<Option<Self>> {
429        let meta = match fs::symlink_metadata(path) {
430            Ok(meta) => meta,
431            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
432            Err(err) => return Err(err.into()),
433        };
434        Self::check_database_file(path, &meta)?;
435        let canonical_parent = path
436            .parent()
437            .filter(|parent| !parent.as_os_str().is_empty())
438            .unwrap_or(Path::new("."))
439            .canonicalize()?;
440        let db = canonical_parent.join(
441            path.file_name()
442                .ok_or_else(|| Error::Invalid("database filename required".into()))?,
443        );
444        let conn = Connection::open_with_flags(
445            db,
446            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY
447                | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX
448                | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW,
449        )?;
450        conn.busy_timeout(Duration::from_secs(5))?;
451        conn.execute_batch("PRAGMA temp_store=MEMORY; BEGIN")?;
452        let app: i64 = conn.query_row("PRAGMA application_id", [], |r| r.get(0))?;
453        let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
454        if app != APP_ID || !(1..=2).contains(&version) {
455            return Err(Error::DatabaseMismatch);
456        }
457        if version == 1 {
458            conn.execute_batch("CREATE TEMP VIEW memory_numeric_aliases AS SELECT row_number() OVER (ORDER BY rowid) AS id, id AS memory_id FROM main.memories")?;
459        }
460        conn.execute_batch("PRAGMA query_only=ON")?;
461        Ok(Some(Self {
462            conn,
463            clock: Arc::new(now),
464        }))
465    }
466    pub fn in_memory() -> Result<Self> {
467        Self::from_connection(Connection::open_in_memory()?, Arc::new(now))
468    }
469    pub fn in_memory_with_clock(clock: impl Fn() -> i64 + Send + Sync + 'static) -> Result<Self> {
470        Self::from_connection(Connection::open_in_memory()?, Arc::new(clock))
471    }
472    fn from_connection(
473        mut conn: Connection,
474        clock: Arc<dyn Fn() -> i64 + Send + Sync>,
475    ) -> Result<Self> {
476        let app: i64 = conn.query_row("PRAGMA application_id", [], |r| r.get(0))?;
477        let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?;
478        let count: i64 = conn.query_row(
479            "SELECT count(*) FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'",
480            [],
481            |r| r.get(0),
482        )?;
483        if !((app == 0 && version == 0 && count == 0)
484            || (app == APP_ID && (1..=2).contains(&version)))
485        {
486            return Err(Error::DatabaseMismatch);
487        }
488        conn.busy_timeout(Duration::from_secs(5))?;
489        conn.execute_batch("PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON; PRAGMA temp_store=MEMORY; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;")?;
490        if version < 2 {
491            let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
492            let v: i64 = tx.query_row("PRAGMA user_version", [], |r| r.get(0))?;
493            if v == 0 {
494                tx.execute_batch(SCHEMA)?;
495            } else if !(1..=2).contains(&v) {
496                return Err(Error::DatabaseMismatch);
497            }
498            if v < 2 {
499                tx.execute_batch(include_str!("sql/migrate_002.sql"))?;
500            }
501            tx.commit()?;
502        }
503        Ok(Self { conn, clock })
504    }
505    pub fn timestamp(&self) -> i64 {
506        (self.clock)()
507    }
508    /// Validate the complete provenance chain, not just this record's own hashes.
509    pub fn freshness(
510        &self,
511        access: &Access,
512        memory: &Memory,
513        snapshot: &Snapshot,
514    ) -> Result<Freshness> {
515        access.read(&memory.draft.scope)?;
516        effective_freshness(&self.conn, access, memory, snapshot, self.timestamp())
517    }
518    pub fn list(&self, access: &Access, after: Option<&str>, limit: usize) -> Result<Vec<Memory>> {
519        self.list_rows(access, after, limit, false)
520    }
521    pub fn list_current(&self, access: &Access, limit: usize) -> Result<Vec<Memory>> {
522        self.list_rows(access, None, limit, true)
523    }
524    fn list_rows(
525        &self,
526        access: &Access,
527        after: Option<&str>,
528        limit: usize,
529        current_only: bool,
530    ) -> Result<Vec<Memory>> {
531        access.require(Capability::Read)?;
532        let sql = format!(
533            "SELECT {SELECT} FROM memories m WHERE m.scope IN (SELECT value FROM json_each(?1)) AND m.id>?2 AND (NOT ?4 OR m.status IN ('active','stale')) ORDER BY m.id LIMIT ?3"
534        );
535        let mut stmt = self.conn.prepare(&sql)?;
536        Ok(stmt
537            .query_map(
538                params![
539                    access.scope_json()?,
540                    after.unwrap_or(""),
541                    limit.clamp(1, 500) as i64,
542                    current_only
543                ],
544                row_memory,
545            )?
546            .collect::<rusqlite::Result<Vec<_>>>()?)
547    }
548    pub fn dependency_paths(&self, access: &Access) -> Result<Vec<String>> {
549        access.require(Capability::Read)?;
550        let mut q = self.conn.prepare("SELECT DISTINCT d.path FROM dependencies d JOIN memories m ON m.id=d.memory_id WHERE m.scope IN (SELECT value FROM json_each(?1)) ORDER BY d.path LIMIT 4096")?;
551        Ok(q.query_map([access.scope_json()?], |r| r.get(0))?
552            .collect::<rusqlite::Result<Vec<_>>>()?)
553    }
554    pub fn status(&self, access: &Access) -> Result<serde_json::Value> {
555        access.require(Capability::Read)?;
556        let mut q = self.conn.prepare("SELECT status,count(*) FROM memories WHERE scope IN (SELECT value FROM json_each(?1)) GROUP BY status")?;
557        let counts = q
558            .query_map([access.scope_json()?], |r| {
559                Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
560            })?
561            .collect::<rusqlite::Result<BTreeMap<_, _>>>()?;
562        Ok(
563            serde_json::json!({"schema_version":2,"backend":"sqlite-local-v2","counts":counts,"network_calls":false,"encrypted_at_rest":false}),
564        )
565    }
566    pub fn link(
567        &mut self,
568        access: &Access,
569        from: &str,
570        to: &str,
571        relation: Relation,
572    ) -> Result<()> {
573        let now = self.timestamp();
574        let tx = self
575            .conn
576            .transaction_with_behavior(TransactionBehavior::Immediate)?;
577        let a = get_at(&tx, access, from)?;
578        let b = get_at(&tx, access, to)?;
579        access.write(&a.draft.scope, Capability::Link)?;
580        access.write(&b.draft.scope, Capability::Link)?;
581        if a.draft.scope != b.draft.scope || from == to {
582            return Err(Error::Invalid(
583                "relations must join distinct memories in one exact scope".into(),
584            ));
585        }
586        if tx.execute(
587            "INSERT OR IGNORE INTO links(from_id,to_id,relation) VALUES(?1,?2,?3)",
588            params![from, to, relation.as_str()],
589        )? > 0
590        {
591            event(&tx, access, from, "linked", a.revision, now)?;
592        }
593        tx.commit()?;
594        Ok(())
595    }
596    pub fn set_embedding(
597        &mut self,
598        access: &Access,
599        id: &str,
600        expected_hash: &str,
601        embedding: &Embedding,
602    ) -> Result<()> {
603        let normalized = policy::normalize_embedding(embedding)?;
604        let bytes: Vec<u8> = normalized.iter().flat_map(|v| v.to_le_bytes()).collect();
605        let now = self.timestamp();
606        let tx = self
607            .conn
608            .transaction_with_behavior(TransactionBehavior::Immediate)?;
609        let m = get_at(&tx, access, id)?;
610        access.write(&m.draft.scope, Capability::Index)?;
611        if m.content_hash != expected_hash {
612            return Err(Error::RevisionConflict);
613        }
614        tx.execute("INSERT INTO embeddings(memory_id,model,dimensions,content_hash,vector) VALUES(?1,?2,?3,?4,?5) ON CONFLICT(memory_id) DO UPDATE SET model=excluded.model,dimensions=excluded.dimensions,content_hash=excluded.content_hash,vector=excluded.vector",params![id,embedding.model,normalized.len() as i64,expected_hash,bytes])?;
615        event(&tx, access, id, "embedded", m.revision, now)?;
616        tx.commit()?;
617        Ok(())
618    }
619    pub fn reindex(&mut self, access: &Access) -> Result<()> {
620        access.require(Capability::Maintenance)?;
621        let tx = self
622            .conn
623            .transaction_with_behavior(TransactionBehavior::Immediate)?;
624        tx.execute_batch("INSERT INTO memory_fts(memory_fts) VALUES('rebuild'); INSERT INTO memory_grams(memory_grams) VALUES('rebuild'); INSERT INTO memory_fts(memory_fts,rank) VALUES('integrity-check',1); INSERT INTO memory_grams(memory_grams,rank) VALUES('integrity-check',1);")?;
625        tx.commit()?;
626        Ok(())
627    }
628    pub fn export_jsonl(&self, access: &Access, mut output: impl Write) -> Result<usize> {
629        access.require(Capability::Export)?;
630        let _read_snapshot = Tx::begin(&self.conn)?;
631        let mut count = 0;
632        let mut after = None;
633        loop {
634            let batch = self.list(access, after.as_deref(), 500)?;
635            if batch.is_empty() {
636                break;
637            }
638            for memory in &batch {
639                serde_json::to_writer(
640                    &mut output,
641                    &serde_json::json!({"schema":"codewhale.memory.export.v1","memory":memory}),
642                )?;
643                output.write_all(b"\n")?;
644                count += 1;
645            }
646            after = batch.last().map(|m| m.id.clone());
647        }
648        Ok(count)
649    }
650    /// Mark active expired records and their dependents stale. Expiry is already
651    /// enforced in recall; correctness does not depend on scheduling this sweep.
652    pub fn expire(&mut self, access: &Access) -> Result<usize> {
653        access.require(Capability::Maintenance)?;
654        let now = self.timestamp();
655        let tx = self
656            .conn
657            .transaction_with_behavior(TransactionBehavior::Immediate)?;
658        let ids: Vec<String> = {
659            let mut q = tx.prepare("SELECT id FROM memories WHERE scope IN (SELECT value FROM json_each(?1)) AND status='active' AND expires_at<=?2")?;
660            q.query_map(params![access.scope_json()?, now], |r| r.get(0))?
661                .collect::<rusqlite::Result<Vec<_>>>()?
662        };
663        for id in &ids {
664            let m = get_at(&tx, access, id)?;
665            access.write(&m.draft.scope, Capability::Maintenance)?;
666            tx.execute(
667                "UPDATE memories SET status='stale',revision=revision+1,updated_at=?2 WHERE id=?1",
668                params![id, now],
669            )?;
670            invalidate_descendants(&tx, access, id, now)?;
671            event(&tx, access, id, "expired", m.revision + 1, now)?;
672        }
673        tx.commit()?;
674        Ok(ids.len())
675    }
676}
677
678impl MemoryBackend for Store {
679    fn capture(
680        &mut self,
681        access: &Access,
682        request: &str,
683        mut draft: Draft,
684    ) -> Result<CaptureReceipt> {
685        access.write(&draft.scope, Capability::Propose)?;
686        policy::bounded(request, "request id", 1024, true)?;
687        let now = self.timestamp();
688        draft.title = draft.title.trim().to_owned();
689        draft.body = draft.body.trim().to_owned();
690        draft.tags.sort();
691        draft.tags.dedup();
692        draft.parent_ids.sort();
693        draft.parent_ids.dedup();
694        policy::validate_draft(&draft, now)?;
695        let scope = draft.scope.key()?;
696        let request_hash = policy::sha256(request.as_bytes());
697        let request_draft_hash = policy::sha256(&serde_json::to_vec(&draft)?);
698        let tx = self
699            .conn
700            .transaction_with_behavior(TransactionBehavior::Immediate)?;
701        let existing: Option<(String, Option<String>)> = tx
702            .query_row(
703                "SELECT draft_hash,memory_id FROM requests WHERE scope=?1 AND request_hash=?2",
704                params![scope, request_hash],
705                |r| Ok((r.get(0)?, r.get(1)?)),
706            )
707            .optional()?;
708        if let Some((old_hash, id)) = existing {
709            if old_hash != request_draft_hash {
710                return Err(Error::IdempotencyConflict);
711            }
712            let id = id.ok_or(Error::Forgotten)?;
713            let memory = get_at(&tx, access, &id)?;
714            return Ok(CaptureReceipt {
715                memory,
716                created: false,
717            });
718        }
719        let content_hash = policy::content_hash(&draft)?;
720        let forgotten: bool = tx.query_row(
721            "SELECT EXISTS(SELECT 1 FROM tombstones WHERE scope=?1 AND content_hash=?2)",
722            params![scope, content_hash],
723            |r| r.get(0),
724        )?;
725        if forgotten {
726            return Err(Error::Forgotten);
727        }
728        for parent in &draft.parent_ids {
729            let p = get_at(&tx, access, parent)?;
730            if p.draft.scope != draft.scope {
731                return Err(Error::Invalid(
732                    "derived memories cannot cross scope boundaries".into(),
733                ));
734            }
735            if let Some(expiry) = p.draft.expires_at {
736                draft.expires_at = Some(draft.expires_at.map_or(expiry, |e| e.min(expiry)));
737            }
738            // Inherit dependency fingerprints, not merely prose. Otherwise a
739            // summary could remain "fresh" after its supporting file changed.
740            for (path, digest) in &p.draft.dependencies {
741                if draft.dependencies.get(path).is_some_and(|h| h != digest) {
742                    return Err(Error::InvalidParent);
743                }
744                draft.dependencies.insert(path.clone(), digest.clone());
745            }
746            if draft.repository_revision.is_none() {
747                draft.repository_revision = p.draft.repository_revision.clone();
748            } else if p.draft.dependencies.is_empty()
749                && p.draft.repository_revision.is_some()
750                && p.draft.repository_revision != draft.repository_revision
751            {
752                return Err(Error::InvalidParent);
753            }
754        }
755        if draft.expires_at.is_some_and(|t| t <= now) {
756            return Err(Error::InvalidParent);
757        }
758        policy::validate_draft(&draft, now)?;
759        let id = Uuid::new_v4().to_string();
760        tx.execute("INSERT INTO memories(id,scope,kind,semantic_key,status,revision,title,body,tags,payload,content_hash,repo_revision,importance,confidence,created_at,updated_at,expires_at) VALUES(?1,?2,?3,?4,'candidate',1,?5,?6,?7,?8,?9,?10,?11,?12,?13,?13,?14)",
761            params![id,scope,draft.kind.as_str(),draft.key,draft.title,draft.body,draft.tags.join(" "),serde_json::to_string(&draft)?,content_hash,draft.repository_revision,draft.importance,draft.confidence,now,draft.expires_at])?;
762        for (path, digest) in &draft.dependencies {
763            tx.execute(
764                "INSERT INTO dependencies(memory_id,path,digest) VALUES(?1,?2,?3)",
765                params![id, path, digest],
766            )?;
767        }
768        for parent in &draft.parent_ids {
769            tx.execute(
770                "INSERT INTO lineage(parent_id,child_id) VALUES(?1,?2)",
771                params![parent, id],
772            )?;
773        }
774        tx.execute(
775            "INSERT INTO requests(scope,request_hash,draft_hash,memory_id) VALUES(?1,?2,?3,?4)",
776            params![scope, request_hash, request_draft_hash, id],
777        )?;
778        event(&tx, access, &id, "proposed", 1, now)?;
779        let memory = get_at(&tx, access, &id)?;
780        tx.commit()?;
781        Ok(CaptureReceipt {
782            memory,
783            created: true,
784        })
785    }
786    fn get(&self, access: &Access, id: &str) -> Result<Memory> {
787        get_at(&self.conn, access, id)
788    }
789    fn approve(
790        &mut self,
791        access: &Access,
792        id: &str,
793        revision: i64,
794        validation: Option<&ValidationReceipt>,
795        snapshot: &Snapshot,
796    ) -> Result<Memory> {
797        let now = self.timestamp();
798        let tx = self
799            .conn
800            .transaction_with_behavior(TransactionBehavior::Immediate)?;
801        let m = get_at(&tx, access, id)?;
802        access.write(&m.draft.scope, Capability::Review)?;
803        require_revision(&m, revision)?;
804        check_activation(&tx, access, &m, validation, snapshot, now)?;
805        ensure_key_available(&tx, access, &m.draft, None, now)?;
806        activate(&tx, access, &m, validation, now)?;
807        let updated = get_at(&tx, access, id)?;
808        tx.commit()?;
809        Ok(updated)
810    }
811    fn reject(&mut self, access: &Access, id: &str, revision: i64) -> Result<Memory> {
812        let now = self.timestamp();
813        let tx = self
814            .conn
815            .transaction_with_behavior(TransactionBehavior::Immediate)?;
816        let m = get_at(&tx, access, id)?;
817        access.write(&m.draft.scope, Capability::Review)?;
818        require_revision(&m, revision)?;
819        if m.status != Status::Candidate {
820            return Err(Error::InvalidState);
821        }
822        tx.execute(
823            "UPDATE memories SET status='rejected',revision=revision+1,updated_at=?2 WHERE id=?1",
824            params![id, now],
825        )?;
826        event(&tx, access, id, "rejected", m.revision + 1, now)?;
827        let updated = get_at(&tx, access, id)?;
828        tx.commit()?;
829        Ok(updated)
830    }
831    fn supersede(
832        &mut self,
833        access: &Access,
834        old: (&str, i64),
835        new: (&str, i64),
836        validation: Option<&ValidationReceipt>,
837        snapshot: &Snapshot,
838    ) -> Result<Memory> {
839        let now = self.timestamp();
840        let tx = self
841            .conn
842            .transaction_with_behavior(TransactionBehavior::Immediate)?;
843        let a = get_at(&tx, access, old.0)?;
844        let b = get_at(&tx, access, new.0)?;
845        access.write(&a.draft.scope, Capability::Correct)?;
846        access.write(&b.draft.scope, Capability::Review)?;
847        require_revision(&a, old.1)?;
848        require_revision(&b, new.1)?;
849        if old.0 == new.0
850            || a.draft.scope != b.draft.scope
851            || a.draft.key != b.draft.key
852            || a.draft.kind != b.draft.kind
853            || !matches!(a.status, Status::Active | Status::Stale)
854        {
855            return Err(Error::InvalidState);
856        }
857        if descendants(&tx, old.0)?.iter().any(|id| id == new.0) {
858            return Err(Error::Invalid(
859                "a correction cannot depend on the memory it invalidates".into(),
860            ));
861        }
862        check_activation(&tx, access, &b, validation, snapshot, now)?;
863        ensure_key_available(&tx, access, &b.draft, Some(old.0), now)?;
864        tx.execute(
865            "UPDATE memories SET status='superseded',revision=revision+1,updated_at=?2 WHERE id=?1",
866            params![old.0, now],
867        )?;
868        invalidate_descendants(&tx, access, old.0, now)?;
869        tx.execute(
870            "INSERT INTO replacements(old_id,new_id) VALUES(?1,?2)",
871            params![old.0, new.0],
872        )?;
873        activate(&tx, access, &b, validation, now)?;
874        event(&tx, access, old.0, "superseded", a.revision + 1, now)?;
875        let updated = get_at(&tx, access, new.0)?;
876        tx.commit()?;
877        Ok(updated)
878    }
879    fn forget(&mut self, access: &Access, id: &str, revision: i64) -> Result<ForgetReport> {
880        let now = self.timestamp();
881        let tx = self
882            .conn
883            .transaction_with_behavior(TransactionBehavior::Immediate)?;
884        let root = get_at(&tx, access, id)?;
885        access.write(&root.draft.scope, Capability::Forget)?;
886        require_revision(&root, revision)?;
887        let ids: Vec<String> = {
888            let mut q = tx.prepare(include_str!("sql/forget_closure.sql"))?;
889            q.query_map(named_params! {":id":id}, |r| r.get(0))?
890                .collect::<rusqlite::Result<Vec<_>>>()?
891        };
892        for id in &ids {
893            let m = get_at(&tx, access, id)?;
894            access.write(&m.draft.scope, Capability::Forget)?;
895            tx.execute("INSERT OR IGNORE INTO tombstones(scope,content_hash,forgotten_at) VALUES(?1,?2,?3)",params![m.draft.scope.key()?,m.content_hash,now])?;
896            event(&tx, access, id, "forgotten", m.revision + 1, now)?;
897        }
898        let ids_json = serde_json::to_string(&ids)?;
899        // A cited memory retracts dependent checkpoints, including their summaries.
900        // Scope-crossing checkpoint references are same-tenant/user only (Access).
901        let checkpoints_deleted=tx.execute("DELETE FROM checkpoints WHERE id IN (SELECT checkpoint_id FROM checkpoint_refs WHERE memory_id IN (SELECT value FROM json_each(?1)))",[&ids_json])?;
902        let memories_deleted = tx.execute(
903            "DELETE FROM memories WHERE id IN (SELECT value FROM json_each(?1))",
904            [&ids_json],
905        )?;
906        tx.commit()?;
907        // A busy reader may retain the WAL. Logical deletion still succeeded;
908        // report that condition instead of claiming physical erasure or failing
909        // the already-committed operation.
910        let wal_truncated = self
911            .conn
912            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| {
913                r.get::<_, i64>(0)
914            })
915            .map(|busy| busy == 0)
916            .unwrap_or(false);
917        Ok(ForgetReport {
918            memories_deleted,
919            checkpoints_deleted,
920            wal_truncated,
921            physical_erasure_guaranteed: false,
922        })
923    }
924    fn recall(&self, access: &Access, query: &Recall) -> Result<RecallReport> {
925        self.recall_impl(access, query)
926    }
927    fn save_checkpoint(
928        &mut self,
929        access: &Access,
930        mut draft: CheckpointDraft,
931        expected_revision: Option<i64>,
932        snapshot: &Snapshot,
933    ) -> Result<Checkpoint> {
934        access.write(&draft.scope, Capability::Checkpoint)?;
935        if draft.scope.session.is_none() {
936            return Err(Error::Invalid(
937                "working state requires a session scope".into(),
938            ));
939        }
940        policy::bounded(&draft.key, "checkpoint key", 256, true)?;
941        policy::bounded(&draft.state.summary, "checkpoint summary", 8192, false)?;
942        if draft.memory_ids.len() > 128
943            || draft.state.next_steps.len() > 64
944            || draft.state.artifact_refs.len() > 64
945            || draft.state.pending_operations.len() > 64
946        {
947            return Err(Error::Invalid(
948                "checkpoint collection limit exceeded".into(),
949            ));
950        }
951        for item in draft
952            .state
953            .next_steps
954            .iter()
955            .chain(draft.state.artifact_refs.iter())
956        {
957            policy::bounded(item, "checkpoint item", 1024, true)?;
958        }
959        for op in &draft.state.pending_operations {
960            policy::bounded(&op.operation_id, "operation id", 256, true)?;
961            policy::bounded(&op.state, "operation state", 128, true)?;
962        }
963        let encoded = serde_json::to_string(&draft)?;
964        policy::bounded(&encoded, "checkpoint", 32768, false)?;
965        policy::ensure_no_secret(&encoded)?;
966        draft.memory_ids.sort();
967        draft.memory_ids.dedup();
968        let now = self.timestamp();
969        let expires = draft.expires_at.unwrap_or(now.saturating_add(7 * 86400));
970        if expires <= now {
971            return Err(Error::Invalid(
972                "checkpoint expiry must be in the future".into(),
973            ));
974        }
975        let tx = self
976            .conn
977            .transaction_with_behavior(TransactionBehavior::Immediate)?;
978        let old: Option<(String, i64)> = tx
979            .query_row(
980                "SELECT id,revision FROM checkpoints WHERE scope=?1 AND checkpoint_key=?2",
981                params![draft.scope.key()?, draft.key],
982                |r| Ok((r.get(0)?, r.get(1)?)),
983            )
984            .optional()?;
985        let (id, revision) = match old {
986            None if expected_revision.is_none() => (Uuid::new_v4().to_string(), 1),
987            Some((id, rev)) if expected_revision == Some(rev) => (id, rev + 1),
988            _ => return Err(Error::RevisionConflict),
989        };
990        let mut memories = Vec::new();
991        for mid in &draft.memory_ids {
992            let m = get_at(&tx, access, mid)?;
993            if effective_freshness(&tx, access, &m, snapshot, now)? != Freshness::Current {
994                return Err(Error::InvalidParent);
995            }
996            memories.push(MemoryRef {
997                id: m.id,
998                revision: m.revision,
999                content_hash: m.content_hash,
1000            });
1001        }
1002        tx.execute("INSERT INTO checkpoints(id,scope,checkpoint_key,revision,payload,updated_at,expires_at) VALUES(?1,?2,?3,?4,?5,?6,?7) ON CONFLICT(scope,checkpoint_key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload,updated_at=excluded.updated_at,expires_at=excluded.expires_at",params![id,draft.scope.key()?,draft.key,revision,serde_json::to_string(&draft)?,now,expires])?;
1003        tx.execute("DELETE FROM checkpoint_refs WHERE checkpoint_id=?1", [&id])?;
1004        for m in &memories {
1005            tx.execute("INSERT INTO checkpoint_refs(checkpoint_id,memory_id,revision,content_hash) VALUES(?1,?2,?3,?4)",params![id,m.id,m.revision,m.content_hash])?;
1006        }
1007        event(&tx, access, &id, "checkpoint_saved", revision, now)?;
1008        tx.commit()?;
1009        Ok(Checkpoint {
1010            id,
1011            revision,
1012            draft,
1013            memories,
1014            updated_at: now,
1015            expires_at: expires,
1016        })
1017    }
1018    fn resume(
1019        &self,
1020        access: &Access,
1021        scope: &Scope,
1022        key: &str,
1023        snapshot: &Snapshot,
1024    ) -> Result<Resume> {
1025        access.read(scope)?;
1026        let _read_snapshot = Tx::begin(&self.conn)?;
1027        let row: Option<(String,i64,String,i64,i64)>=self.conn.query_row("SELECT id,revision,payload,updated_at,expires_at FROM checkpoints WHERE scope=?1 AND checkpoint_key=?2 AND expires_at>?3",params![scope.key()?,key,self.timestamp()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?))).optional()?;
1028        let (id, revision, payload, updated_at, expires_at) = row.ok_or(Error::NotFound)?;
1029        let mut q=self.conn.prepare("SELECT memory_id,revision,content_hash FROM checkpoint_refs WHERE checkpoint_id=?1 ORDER BY memory_id")?;
1030        let memories = q
1031            .query_map([&id], |r| {
1032                Ok(MemoryRef {
1033                    id: r.get(0)?,
1034                    revision: r.get(1)?,
1035                    content_hash: r.get(2)?,
1036                })
1037            })?
1038            .collect::<rusqlite::Result<Vec<_>>>()?;
1039        let mut invalidated = Vec::new();
1040        for reference in &memories {
1041            match self.get(access, &reference.id) {
1042                Ok(m) => {
1043                    let current = m.revision == reference.revision
1044                        && m.content_hash == reference.content_hash
1045                        && effective_freshness(&self.conn, access, &m, snapshot, self.timestamp())?
1046                            == Freshness::Current;
1047                    if !current {
1048                        invalidated.push(reference.id.clone());
1049                    }
1050                }
1051                Err(Error::NotFound) => invalidated.push(reference.id.clone()),
1052                Err(error) => return Err(error),
1053            }
1054        }
1055        Ok(Resume {
1056            checkpoint: Checkpoint {
1057                id,
1058                revision,
1059                draft: serde_json::from_str(&payload)?,
1060                memories,
1061                updated_at,
1062                expires_at,
1063            },
1064            invalidated_memory_ids: invalidated,
1065            reconcile_pending_operations: true,
1066        })
1067    }
1068}
1069
1070fn add_ranking(
1071    target: &mut BTreeMap<String, Hit>,
1072    rows: Vec<Memory>,
1073    reason: &str,
1074    weight: f64,
1075    snapshot: &Snapshot,
1076    now: i64,
1077) {
1078    for (rank, memory) in rows.into_iter().enumerate() {
1079        let freshness = memory.freshness(snapshot, now);
1080        let score = weight / (60.0 + rank as f64 + 1.0);
1081        let hit = target.entry(memory.id.clone()).or_insert(Hit {
1082            memory,
1083            freshness,
1084            score: 0.0,
1085            reasons: Vec::new(),
1086        });
1087        hit.score += score;
1088        hit.reasons.push(reason.to_string());
1089    }
1090}
1091impl Store {
1092    fn recall_impl(&self, access: &Access, query: &Recall) -> Result<RecallReport> {
1093        access.require(Capability::Read)?;
1094        policy::bounded(&query.query, "query", 1024, false)?;
1095        let scopes = access.scope_json()?;
1096        let files = serde_json::to_string(&query.snapshot.files)?;
1097        let now = self.timestamp();
1098        let limit = query.limit.clamp(1, 64);
1099        let candidates = (limit * 8).clamp(64, 512) as i64;
1100        let include_stale = if query.include_stale { 1_i64 } else { 0_i64 };
1101        // All retrieval branches share a consistent read transaction. A later
1102        // use still needs a revision/freshness check at the host execution boundary.
1103        let _read_snapshot = Tx::begin(&self.conn)?;
1104        let mut hits = BTreeMap::new();
1105        let run_text = |sql: &str, text: &str| -> Result<Vec<Memory>> {
1106            let mut q = self.conn.prepare(sql)?;
1107            Ok(q.query_map(named_params!{":scopes":scopes,":now":now,":include_stale":include_stale,":files":files,":repo":query.snapshot.revision,":query":text,":limit":candidates},row_memory)?.collect::<rusqlite::Result<Vec<_>>>()?)
1108        };
1109        if let Some(fts) = policy::fts_query(&query.query)? {
1110            let sql = format!(
1111                "SELECT {SELECT} FROM memory_fts JOIN memories m ON m.rowid=memory_fts.rowid WHERE ({ELIGIBLE}) AND memory_fts MATCH :query ORDER BY bm25(memory_fts,3.0,1.0,2.0),m.id LIMIT :limit"
1112            );
1113            add_ranking(
1114                &mut hits,
1115                run_text(&sql, &fts)?,
1116                "lexical",
1117                1.0,
1118                &query.snapshot,
1119                now,
1120            );
1121            let chars = query.query.trim().chars().count();
1122            if (3..=256).contains(&chars) {
1123                let sql = format!(
1124                    "SELECT {SELECT} FROM memory_grams JOIN memories m ON m.rowid=memory_grams.rowid WHERE ({ELIGIBLE}) AND memory_grams MATCH :query ORDER BY bm25(memory_grams,2.0,1.0),m.id LIMIT :limit"
1125                );
1126                let literal = format!("\"{}\"", query.query.trim().replace('"', "\"\""));
1127                add_ranking(
1128                    &mut hits,
1129                    run_text(&sql, &literal)?,
1130                    "substring",
1131                    0.6,
1132                    &query.snapshot,
1133                    now,
1134                );
1135            } else if chars <= 2 {
1136                let sql = format!(
1137                    "SELECT {SELECT} FROM memories m WHERE ({ELIGIBLE}) AND instr(lower(m.title || ' ' || m.body),lower(:query))>0 ORDER BY m.importance DESC,m.id LIMIT :limit"
1138                );
1139                add_ranking(
1140                    &mut hits,
1141                    run_text(&sql, query.query.trim())?,
1142                    "short_substring",
1143                    0.5,
1144                    &query.snapshot,
1145                    now,
1146                );
1147            }
1148        } else if query.query.trim().is_empty() && query.embedding.is_none() {
1149            let sql = format!(
1150                "SELECT {SELECT} FROM memories m WHERE ({ELIGIBLE}) AND :query='' ORDER BY m.importance DESC,m.updated_at DESC,m.id LIMIT :limit"
1151            );
1152            add_ranking(
1153                &mut hits,
1154                run_text(&sql, "")?,
1155                "working_set",
1156                1.0,
1157                &query.snapshot,
1158                now,
1159            );
1160        }
1161        let mut vector_candidates = 0;
1162        let mut vector_scan_truncated = false;
1163        if let Some(embedding) = &query.embedding {
1164            let normalized = policy::normalize_embedding(embedding)?;
1165            let scan_limit = query.vector_scan_limit.clamp(1, 20_000);
1166            let sql = format!(
1167                "SELECT {SELECT},e.vector FROM embeddings e JOIN memories m ON m.id=e.memory_id WHERE ({ELIGIBLE}) AND e.model=:model AND e.dimensions=:dimensions AND e.content_hash=m.content_hash ORDER BY m.id LIMIT :limit"
1168            );
1169            let mut q = self.conn.prepare(&sql)?;
1170            let rows=q.query_map(named_params!{":scopes":scopes,":now":now,":include_stale":include_stale,":files":files,":repo":query.snapshot.revision,":model":embedding.model,":dimensions":normalized.len() as i64,":limit":(scan_limit+1) as i64},|r|Ok((row_memory(r)?,r.get::<_,Vec<u8>>(7)?)))?.collect::<rusqlite::Result<Vec<_>>>()?;
1171            vector_scan_truncated = rows.len() > scan_limit;
1172            let mut dense = Vec::new();
1173            for (m, bytes) in rows.into_iter().take(scan_limit) {
1174                vector_candidates += 1;
1175                if bytes.len() != normalized.len() * 4 {
1176                    return Err(Error::Invalid("stored embedding length mismatch".into()));
1177                }
1178                let mut cosine = 0.0_f64;
1179                for (chunk, q) in bytes.as_chunks::<4>().0.iter().zip(&normalized) {
1180                    let v = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
1181                    if !v.is_finite() {
1182                        return Err(Error::Invalid("stored embedding is non-finite".into()));
1183                    }
1184                    cosine += v as f64 * *q as f64;
1185                }
1186                if cosine > 0.0 {
1187                    dense.push((m, cosine));
1188                }
1189            }
1190            dense.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.id.cmp(&b.0.id)));
1191            add_ranking(
1192                &mut hits,
1193                dense
1194                    .into_iter()
1195                    .take(candidates as usize)
1196                    .map(|(m, _)| m)
1197                    .collect(),
1198                "semantic",
1199                1.0,
1200                &query.snapshot,
1201                now,
1202            );
1203        }
1204        if query.expand_graph && !hits.is_empty() {
1205            let mut ordered: Vec<_> = hits.values().collect();
1206            ordered.sort_by(|a, b| {
1207                b.score
1208                    .total_cmp(&a.score)
1209                    .then_with(|| a.memory.id.cmp(&b.memory.id))
1210            });
1211            let seeds = serde_json::to_string(
1212                &ordered
1213                    .iter()
1214                    .take(8)
1215                    .map(|h| &h.memory.id)
1216                    .collect::<Vec<_>>(),
1217            )?;
1218            let sql = format!(
1219                "SELECT DISTINCT {SELECT} FROM memories m JOIN links l ON ((l.from_id IN (SELECT value FROM json_each(:seeds)) AND l.to_id=m.id) OR (l.to_id IN (SELECT value FROM json_each(:seeds)) AND l.from_id=m.id)) WHERE ({ELIGIBLE}) ORDER BY m.id LIMIT 32"
1220            );
1221            let mut q = self.conn.prepare(&sql)?;
1222            let rows=q.query_map(named_params!{":scopes":scopes,":now":now,":include_stale":include_stale,":files":files,":repo":query.snapshot.revision,":seeds":seeds},row_memory)?.collect::<rusqlite::Result<Vec<_>>>()?;
1223            add_ranking(
1224                &mut hits,
1225                rows,
1226                "graph_neighbor",
1227                0.25,
1228                &query.snapshot,
1229                now,
1230            );
1231        }
1232        let mut hits: Vec<_> = hits.into_values().collect();
1233        for hit in &mut hits {
1234            hit.freshness =
1235                effective_freshness(&self.conn, access, &hit.memory, &query.snapshot, now)?;
1236            // Small, explainable tie-breakers. Retrieval never writes reinforcement
1237            // or turns model confidence into a probability of correctness.
1238            hit.score += 0.002 * hit.memory.draft.importance + 0.0005 * hit.memory.draft.confidence;
1239        }
1240        hits.sort_by(|a, b| {
1241            b.score
1242                .total_cmp(&a.score)
1243                .then_with(|| a.memory.id.cmp(&b.memory.id))
1244        });
1245        hits.truncate(limit);
1246        Ok(RecallReport {
1247            hits,
1248            vector_candidates,
1249            vector_scan_truncated,
1250        })
1251    }
1252}