Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(hooks): session-sticky attribution + V27 fragment repair + hollow sweep
AkitaOnRailsd43e85907b9f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6abcb21..351fb665 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Mid-session events can no longer scatter observations into basename+ "fragment" projects (`sources`, `desktop`, …). The hook router now uses+ session-sticky attribution: when an event's session already exists, its+ observations inherit the session's project instead of re-deriving one+ from the event's cwd — closing the hole left between the v0.12.2+ cwd-prefix guard (which keys on `repo_path`) and the #103 rule that+ non-git parents never record one, which together left plain-directory+ projects unprotected against every mid-session `cd subdir/`. Explicit+ `.ai-memory.toml` overrides still win, and cwd derivation still decides+ for session-creating events.+- V27 data-repair migration re-runs the idempotent V19 repair on upgrade,+ re-attributing the fragment observations that accumulated since V19 to+ their sessions' projects and deleting the emptied fragment rows.+ Reserved projects (`scratch`, `_global`) are exempt.++### Added+- The maintenance scheduler now sweeps "hollow" project rows — zero+ pages, sessions, observations, and handoffs — once they are older than+ seven days, shortly after startup and then daily. Nothing exists to+ lose in a hollow row (probe/rename residue), so the sweep needs no+ config; rows holding any data are never touched, and reserved projects+ are exempt.+## [1.10.1] - 2026-07-09### Fixeddiff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 586cd55f..fba7e286 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -501,6 +501,43 @@ async fn start_maintenance_scheduler(}));}+ // Hollow-project sweep: deletes project rows with zero data of any+ // kind (pages, sessions, observations, handoffs) once they are older+ // than HOLLOW_PROJECT_MIN_AGE_DAYS. Safe by construction — nothing+ // exists to lose — which is why it runs unconditionally under the+ // maintenance flag with no extra config. Runs once shortly after+ // startup (so upgrades clean up immediately) and then daily.+ if maintenance_enabled {+ /// A week of grace before a hollow row is considered noise, so a+ /// project created moments before its first real event is never+ /// racing the sweep.+ const HOLLOW_PROJECT_MIN_AGE_DAYS: u32 = 7;+ const HOLLOW_SWEEP_INTERVAL: std::time::Duration =+ std::time::Duration::from_secs(24 * 60 * 60);+ /// Short startup delay so the sweep never competes with migration+ /// and first-request work on boot.+ const HOLLOW_SWEEP_STARTUP_DELAY: std::time::Duration = std::time::Duration::from_secs(60);+ let writer = writer.clone();+ tasks.push(tokio::spawn(async move {+ tokio::time::sleep(HOLLOW_SWEEP_STARTUP_DELAY).await;+ loop {+ match writer+ .sweep_hollow_projects(HOLLOW_PROJECT_MIN_AGE_DAYS)+ .await+ {+ Ok(deleted) if deleted.is_empty() => {}+ Ok(deleted) => info!(+ count = deleted.len(),+ projects = deleted.join(", "),+ "hollow-project sweep deleted empty project rows"+ ),+ Err(e) => tracing::warn!(error = %e, "hollow-project sweep failed"),+ }+ tokio::time::sleep(HOLLOW_SWEEP_INTERVAL).await;+ }+ }));+ }+if maintenance_enabled && lint_interval_secs > 0 {let reader = reader.clone();let wiki = wiki.clone();diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex fa0d0fff..4f5b0de9 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -902,6 +902,40 @@ async fn resolve_project_ids(Ok(ids)}+/// Whether session-sticky attribution may apply: the event's cwd must sit+/// inside the session's own cwd subtree, and the session's cwd must be a+/// meaningful anchor — not missing, not the filesystem root, and not the+/// user's home directory (broad roots would fold every project beneath+/// them into one bucket, the #103 catch-all failure mode).+fn sticky_within_session_tree(+ session_cwd: Option<&str>,+ event_cwd: Option<&str>,+ home_dir: Option<&str>,+) -> bool {+ let Some(session_cwd) = session_cwd.filter(|s| !s.trim().is_empty()) else {+ return false;+ };+ let session_norm = normalize_project_path_key(session_cwd);+ if session_norm == "/" {+ return false;+ }+ if let Some(home) = home_dir+ && normalize_project_path_key(home) == session_norm+ {+ return false;+ }+ // A cwd-less event inside a known session still belongs to it — there+ // is no directory evidence to contradict the session (and per-event+ // resolution would only shrug it into the server default anyway).+ let Some(event_cwd) = event_cwd.filter(|s| !s.trim().is_empty()) else {+ return true;+ };+ let event_norm = normalize_project_path_key(event_cwd);+ // Component-wise containment: "/a/b" contains "/a/b/c" but not+ // "/a/bc" (Path::starts_with is component-based, not string-based).+ std::path::Path::new(&event_norm).starts_with(std::path::Path::new(&session_norm))+}+async fn process_envelope(state: Arc<HookState>, env: HookEnvelope, actor_user: Option<String>) {if let Err(e) = process(&state, env, actor_user).await {warn!(error = %e, "hook processing failed");@@ -927,15 +961,62 @@ async fn process(user: actor_user.clone(),session_id: env.session_id.clone(),};- let (mut ws, mut proj) = resolve_project_ids(- state,- env.cwd.as_deref(),- env.workspace_override.as_deref(),- env.project_override.as_deref(),- env.project_strategy,- &actor_key,- )- .await?;+ // Session-sticky attribution: for an event whose session already+ // exists, the session's own scope is the source of truth (the same+ // rationale as the V19 repair). Per-event cwd derivation only decides+ // for session-CREATING events. Without this, a mid-session `cd subdir/`+ // inside a NON-GIT project scattered observations into basename+ // fragments ("sources", "desktop", …): the v0.12.2 prefix match keys on+ // `repo_path`, and #103 deliberately never records one for non-git+ // parents, so the match had nothing to anchor to.+ //+ // Stickiness is bounded so it can never become a catch-all:+ // - Explicit marker-file overrides still win — a `.ai-memory.toml`+ // naming a project is a deliberate rescope, not drift.+ // - The event's cwd must sit INSIDE the session's own cwd subtree;+ // `cd`-ing out of the session's tree (into a different project)+ // falls back to per-event resolution as before.+ // - A session rooted at a broad directory — the filesystem root or+ // the user's home — never sticks, or a stray session started in+ // `$HOME` would fold every project beneath it into one bucket+ // (the same catch-all failure #103 healed for repo_path keys).+ let sticky_scope = if env.project_override.is_none() && env.workspace_override.is_none() {+ state+ .reader+ .find_session_scope(session_id)+ .await?+ .filter(|(_, _, session_cwd)| {+ sticky_within_session_tree(+ session_cwd.as_deref(),+ env.cwd.as_deref(),+ state.home_dir.as_deref(),+ )+ })+ } else {+ None+ };+ let (mut ws, mut proj) = match sticky_scope {+ Some((session_ws, session_proj, _)) => {+ // Publish the pointer like resolve_project_ids does on a cache+ // hit: this session being active is exactly what the MCP read+ // tools should default to.+ state+ .active_project+ .set_for(&actor_key, session_ws, session_proj);+ (session_ws, session_proj)+ }+ None => {+ resolve_project_ids(+ state,+ env.cwd.as_deref(),+ env.workspace_override.as_deref(),+ env.project_override.as_deref(),+ env.project_strategy,+ &actor_key,+ )+ .await?+ }+ };if matches!(env.event, HookEvent::SessionEnd) {match state@@ -1480,6 +1561,160 @@ mod tests {assert_eq!(state.active_project.get(), Some((ws_b, proj_b)));}+ // Catch-all guards on stickiness: a session accidentally started at a+ // broad root (`/`, `$HOME`) must NOT fold everything beneath it into+ // one project, and `cd`-ing OUT of the session's tree must fall back+ // to per-event resolution.+ #[test]+ fn sticky_never_applies_to_broad_roots_or_out_of_tree_cwds() {+ // Session rooted at the filesystem root: never sticky.+ assert!(!sticky_within_session_tree(+ Some("/"),+ Some("/mnt/data/Projects/real-project"),+ Some("/home/user"),+ ));+ // Session rooted at $HOME: never sticky.+ assert!(!sticky_within_session_tree(+ Some("/home/user"),+ Some("/home/user/Projects/real-project"),+ Some("/home/user"),+ ));+ // Missing session cwd: no anchor, no stickiness.+ assert!(!sticky_within_session_tree(+ None,+ Some("/a/b/c"),+ Some("/home/user"),+ ));+ // Event cwd OUTSIDE the session tree: falls back to per-event+ // resolution (a real `cd` into a different project).+ assert!(!sticky_within_session_tree(+ Some("/a/b"),+ Some("/a/other"),+ Some("/home/user"),+ ));+ // Component-wise containment, not string-prefix: /a/bc is NOT+ // inside /a/b.+ assert!(!sticky_within_session_tree(+ Some("/a/b"),+ Some("/a/bc"),+ Some("/home/user"),+ ));++ // The intended case: subdirectory of a normal session cwd sticks.+ assert!(sticky_within_session_tree(+ Some("/a/b"),+ Some("/a/b/c"),+ Some("/home/user"),+ ));+ // Same dir sticks; cwd-less events inside a known session stick.+ assert!(sticky_within_session_tree(+ Some("/a/b"),+ Some("/a/b"),+ Some("/home/user"),+ ));+ assert!(sticky_within_session_tree(+ Some("/a/b"),+ None,+ Some("/home/user"),+ ));+ }++ // Session-sticky attribution: a mid-session `cd subdir/` inside a+ // NON-GIT project must keep observations in the session's project.+ // This is the exact production failure behind the fragment cleanup:+ // non-git parents have no repo_path, so the v0.12.2 prefix match+ // can't anchor subdir cwds, and per-event basename derivation minted+ // "sources"/"desktop"/… fragment projects daily.+ #[tokio::test]+ async fn mid_session_subdir_cwd_sticks_to_the_sessions_project() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let sid = "44444444-4444-4444-4444-444444444444";+ // Plain directory, deliberately NOT a git repo.+ let parent = tmp.path().join("tiktok_analysis");+ let subdir = parent.join("sources");+ std::fs::create_dir_all(&subdir).unwrap();+ let fire = |event: &str, cwd: std::path::PathBuf| {+ HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("claude-code".into()),+ cwd: Some(cwd.to_string_lossy().into_owned()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": sid,+ "cwd": cwd.to_string_lossy(),+ "tool_name": "Bash",+ }),+ )+ };++ // Session starts at the parent; a later tool event reports the+ // subdirectory cwd (agent shells keep their working directory).+ process(&state, fire("session-start", parent.clone()), None)+ .await+ .unwrap();+ process(&state, fire("post-tool-use", subdir.clone()), None)+ .await+ .unwrap();++ let parent_proj = state+ .reader+ .find_project(state.workspace_id, "tiktok_analysis".to_string())+ .await+ .unwrap()+ .expect("parent project exists");+ assert_eq!(+ state+ .reader+ .find_project(state.workspace_id, "sources".to_string())+ .await+ .unwrap(),+ None,+ "the subdir event must not mint a fragment project"+ );+ let session_id: SessionId = sid.parse().unwrap();+ let observations = state+ .reader+ .observations_for_session(session_id)+ .await+ .unwrap();+ assert_eq!(observations.len(), 2);+ assert!(+ observations.iter().all(|o| o.project_id == parent_proj),+ "every observation must carry the session's project"+ );++ // An explicit marker override mid-session is a deliberate rescope+ // and must still win over stickiness.+ let env = HookEnvelope::from_query_and_body(+ HookQuery {+ event: "post-tool-use".into(),+ agent: Some("claude-code".into()),+ cwd: Some(subdir.to_string_lossy().into_owned()),+ project: Some("declared-elsewhere".into()),+ workspace: Some("default".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": sid,+ "cwd": subdir.to_string_lossy(),+ "tool_name": "Bash",+ }),+ );+ process(&state, env, None).await.unwrap();+ assert!(+ state+ .reader+ .find_project(state.workspace_id, "declared-elsewhere".to_string())+ .await+ .unwrap()+ .is_some(),+ "marker-file overrides must still rescope"+ );+ }+// Issue #154: event capture must never create or attribute to the// reserved `_global` preferences scope — not from a directory that// happens to carry the reserved name, and not from a marker-filediff --git a/crates/ai-memory-store/migrations/V27__repair_nongit_fragment_attribution.sql b/crates/ai-memory-store/migrations/V27__repair_nongit_fragment_attribution.sqlnew file mode 100644index 00000000..a9786eb5--- /dev/null+++ b/crates/ai-memory-store/migrations/V27__repair_nongit_fragment_attribution.sql@@ -0,0 +1,61 @@+-- Data-repair migration: re-run the V19 orphan-attribution repair.+--+-- V19 fixed the historical fragment-project class and v0.12.2 added the+-- runtime prefix-match guard — but that guard keys on `projects.repo_path`,+-- and #103 deliberately never records a repo_path for NON-GIT parents (a+-- bare cwd as a prefix key turned $HOME into a catch-all). So sessions+-- rooted in plain directories kept scattering mid-session subdirectory+-- events into basename fragments ("sources", "desktop", …) after V19 ran.+-- The runtime fix that closes the class for good is session-sticky+-- attribution in the hook router (an existing session's scope wins over+-- per-event cwd derivation); this migration drains what accumulated+-- between V19 and that fix.+--+-- Same idempotent shape as V19: re-running on a repaired DB updates zero+-- rows and deletes zero rows. The session is the source of truth.++-- Step 1: re-attribute observations to their session's scope.++UPDATE observations+SET project_id = (SELECT project_id FROM sessions WHERE sessions.id = observations.session_id),+ workspace_id = (SELECT workspace_id FROM sessions WHERE sessions.id = observations.session_id)+WHERE EXISTS (+ SELECT 1 FROM sessions+ WHERE sessions.id = observations.session_id+ AND sessions.project_id != observations.project_id+);++-- Step 2: re-attribute handoffs that carry a from_session_id. Standalone+-- handoffs (from_session_id IS NULL) were deliberately scoped and stay put.++UPDATE handoffs+SET project_id = (SELECT project_id FROM sessions WHERE sessions.id = handoffs.from_session_id),+ workspace_id = (SELECT workspace_id FROM sessions WHERE sessions.id = handoffs.from_session_id)+WHERE from_session_id IS NOT NULL+ AND EXISTS (+ SELECT 1 FROM sessions+ WHERE sessions.id = handoffs.from_session_id+ AND sessions.project_id != handoffs.project_id+ );++-- Step 3: delete project rows that are now truly empty. Unlike V19's+-- check, "empty" here also requires zero auto-improve runs, proposals,+-- and rejections — those tables didn't exist when V19 was written, and a+-- project holding staged proposals is NOT empty (deleting it would+-- cascade the proposals away). The per-project scheduler-state row is+-- deliberately NOT counted: ensure_scheduler_state creates one for every+-- project, so it is bookkeeping, not data. Reserved names are exempt:+-- `scratch` is the documented cwd-less fallback (V19's carve-out), and+-- `_global` is the reserved preferences scope added in v1.9.0 — it holds+-- pages so it would survive anyway, but the explicit carve-out is+-- defensive against any future code that assumes it is always present.++DELETE FROM projects+WHERE name NOT IN ('scratch', '_global')+ AND NOT EXISTS (SELECT 1 FROM pages WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM sessions WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM observations WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM handoffs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_runs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_proposals WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_rejections WHERE project_id = projects.id);diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex c438219d..b9e34b57 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -146,6 +146,62 @@ pub fn get_or_create_project(Ok(id)}+/// Delete "hollow" project rows: zero pages (any version), zero sessions,+/// zero observations, zero handoffs, zero auto-improve runs/proposals/+/// rejections, and older than `min_age_days`. (The per-project+/// scheduler-state row is bookkeeping created for every project and does+/// not count as data.) These+/// are pure bookkeeping noise left behind by probes, renames, and failed+/// first events — nothing exists to lose, which is what makes this safe to+/// run on a schedule (the operator-driven `purge-project` covers everything+/// that actually holds data). Reserved projects (`scratch`, the cwd-less+/// fallback; `_global`, the preferences scope) are exempt even when empty.+/// Returns the deleted names for logging.+///+/// # Errors+/// Propagates SQLite failures.+pub fn sweep_hollow_projects(conn: &mut Connection, min_age_days: u32) -> StoreResult<Vec<String>> {+ let cutoff =+ Timestamp::now().as_microsecond() - i64::from(min_age_days) * 24 * 60 * 60 * 1_000_000;+ let tx = conn.transaction()?;+ let names: Vec<String> = {+ let mut stmt = tx.prepare(+ "SELECT name FROM projects+ WHERE name NOT IN ('scratch', ?1)+ AND created_at < ?2+ AND NOT EXISTS (SELECT 1 FROM pages WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM sessions WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM observations WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM handoffs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_runs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_proposals WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_rejections WHERE project_id = projects.id)",+ )?;+ let rows = stmt.query_map(+ params![ai_memory_core::GLOBAL_SCOPE_PROJECT, cutoff],+ |row| row.get::<_, String>(0),+ )?;+ rows.collect::<Result<_, _>>()?+ };+ if !names.is_empty() {+ tx.execute(+ "DELETE FROM projects+ WHERE name NOT IN ('scratch', ?1)+ AND created_at < ?2+ AND NOT EXISTS (SELECT 1 FROM pages WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM sessions WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM observations WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM handoffs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_runs WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_proposals WHERE project_id = projects.id)+ AND NOT EXISTS (SELECT 1 FROM auto_improve_rejections WHERE project_id = projects.id)",+ params![ai_memory_core::GLOBAL_SCOPE_PROJECT, cutoff],+ )?;+ }+ tx.commit()?;+ Ok(names)+}+/// NULL out `repo_path` values that act as longest-prefix-match catch-alls/// (issue #103), so every project nested beneath them stops resolving to the/// wrong row after upgrade. A one-shot startup heal; idempotent (a healed row@@ -2553,6 +2609,165 @@ mod tests {assert_eq!(parent_rows, 1);}+ // Hollow-project sweep: deletes only rows with zero data of any kind+ // and past the age cutoff; reserved names survive even when hollow.+ #[test]+ fn sweep_hollow_projects_deletes_only_old_dataless_rows() {+ use ai_memory_core::{AgentKind, NewSession, SessionId};+ let (_tmp, mut conn, ws, _scratch) = fresh_db();++ // Hollow + old: delete. (Backdate created_at 8 days.)+ let hollow = get_or_create_project(&mut conn, &ws, "zt", None).unwrap();+ // Hollow + fresh: keep (inside the grace window).+ let fresh = get_or_create_project(&mut conn, &ws, "new-probe", None).unwrap();+ // Old but has a session: keep (not hollow).+ let with_data = get_or_create_project(&mut conn, &ws, "one-off", None).unwrap();+ // Reserved + hollow + old: keep.+ let global =+ get_or_create_project(&mut conn, &ws, ai_memory_core::GLOBAL_SCOPE_PROJECT, None)+ .unwrap();++ let eight_days_us: i64 = 8 * 24 * 60 * 60 * 1_000_000;+ for id in [&hollow, &with_data, &global] {+ conn.execute(+ "UPDATE projects SET created_at = created_at - ?1 WHERE id = ?2",+ params![eight_days_us, &id.as_bytes()[..]],+ )+ .unwrap();+ }+ begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id: ws,+ project_id: with_data,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ },+ )+ .unwrap();++ let deleted = sweep_hollow_projects(&mut conn, 7).unwrap();+ assert_eq!(deleted, vec!["zt".to_string()]);++ let exists = |id: &ai_memory_core::ProjectId| -> i64 {+ conn.query_row(+ "SELECT COUNT(*) FROM projects WHERE id = ?1",+ params![&id.as_bytes()[..]],+ |r| r.get(0),+ )+ .unwrap()+ };+ assert_eq!(exists(&hollow), 0, "old hollow row deleted");+ assert_eq!(exists(&fresh), 1, "fresh hollow row kept (grace window)");+ assert_eq!(exists(&with_data), 1, "data-bearing row kept");+ assert_eq!(exists(&global), 1, "reserved _global kept even when hollow");++ // Idempotent: a second pass deletes nothing.+ assert!(sweep_hollow_projects(&mut conn, 7).unwrap().is_empty());+ }++ /// V27 re-runs the V19 repair for the fragments that accumulated+ /// after V19: non-git parents have no repo_path, so the v0.12.2+ /// prefix guard couldn't anchor subdirectory cwds and per-event+ /// basename derivation kept minting fragment projects. Idempotent:+ /// a second pass repairs nothing.+ #[test]+ fn v27_reattributes_nongit_fragments_and_preserves_reserved_projects() {+ use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};++ let tmp = TempDir::new().unwrap();+ let db_path = tmp.path().join("test.sqlite");+ let mut conn = Connection::open(&db_path).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ crate::migrations::run_to(&mut conn, 26).unwrap();++ // Non-git parent (repo_path NULL — the production shape) plus a+ // basename fragment holding misattributed observations, and the+ // reserved projects that must survive even when empty.+ let ws = get_or_create_workspace(&mut conn, "default").unwrap();+ let parent = get_or_create_project(&mut conn, &ws, "tiktok_analysis", None).unwrap();+ let fragment = get_or_create_project(&mut conn, &ws, "sources", None).unwrap();+ let scratch = get_or_create_project(&mut conn, &ws, "scratch", None).unwrap();+ let global = get_or_create_project(&mut conn, &ws, "_global", None).unwrap();++ let sid = SessionId::new();+ begin_session(+ &mut conn,+ &NewSession {+ id: sid,+ workspace_id: ws,+ project_id: parent,+ agent_kind: AgentKind::ClaudeCode,+ cwd: Some("/home/user/tiktok_analysis".into()),+ },+ )+ .unwrap();+ for i in 0..4 {+ insert_observation(+ &mut conn,+ &NewObservation {+ session_id: sid,+ workspace_id: ws,+ project_id: fragment,+ kind: ObservationKind::PostToolUse,+ extension: None,+ source_event: None,+ title: format!("call {i}"),+ body: "body".into(),+ importance: 5,+ },+ )+ .unwrap();+ }++ crate::migrations::run_to(&mut conn, 27).unwrap();++ let count = |sql: &str, id: &ai_memory_core::ProjectId| -> i64 {+ conn.query_row(sql, params![&id.as_bytes()[..]], |r| r.get(0))+ .unwrap()+ };+ assert_eq!(+ count(+ "SELECT COUNT(*) FROM observations WHERE project_id = ?1",+ &parent+ ),+ 4,+ "observations re-attributed to the non-git parent"+ );+ assert_eq!(+ count("SELECT COUNT(*) FROM projects WHERE id = ?1", &fragment),+ 0,+ "emptied fragment row deleted"+ );+ assert_eq!(+ count("SELECT COUNT(*) FROM projects WHERE id = ?1", &scratch),+ 1,+ "scratch is reserved and survives empty"+ );+ assert_eq!(+ count("SELECT COUNT(*) FROM projects WHERE id = ?1", &global),+ 1,+ "_global is reserved and survives empty"+ );++ // Idempotency: replay V27's statements directly (refinery won't+ // re-run an applied version); zero rows change.+ let sql = include_str!("../migrations/V27__repair_nongit_fragment_attribution.sql");+ conn.execute_batch(sql).unwrap();+ assert_eq!(+ count(+ "SELECT COUNT(*) FROM observations WHERE project_id = ?1",+ &parent+ ),+ 4+ );+ assert_eq!(+ count("SELECT COUNT(*) FROM projects WHERE id = ?1", &scratch),+ 1+ );+ }+#[test]fn v20_adds_grok_and_preserves_sessions_invariants_on_upgraded_db() {use ai_memory_core::{AgentKind, NewObservation, NewSession, ObservationKind, SessionId};diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8bf2af44..884ec25c 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1083,6 +1083,48 @@ impl ReaderPool {.await}+ /// The `(workspace_id, project_id, cwd)` a session was created under,+ /// or `None` when no such session exists. The hook router uses this for+ /// session-sticky attribution: mid-session events inherit the session's+ /// scope instead of re-deriving a project from the event's cwd, so a+ /// `cd subdir/` inside a non-git project (whose parent has no+ /// `repo_path` for the prefix match to key on) can no longer scatter+ /// observations into basename-fragment projects. The session's own cwd+ /// is returned so the router can bound stickiness to the session's+ /// directory subtree.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn find_session_scope(+ &self,+ session_id: SessionId,+ ) -> StoreResult<Option<(WorkspaceId, ProjectId, Option<String>)>> {+ self.with_conn(move |conn| {+ let row = conn+ .query_row(+ "SELECT workspace_id, project_id, cwd FROM sessions WHERE id = ?1",+ params![session_id.as_bytes()],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, Option<String>>(2)?,+ ))+ },+ )+ .optional()?;+ match row {+ Some((ws, proj, cwd)) => Ok(Some((+ WorkspaceId::from_slice(&ws)?,+ ProjectId::from_slice(&proj)?,+ cwd,+ ))),+ None => Ok(None),+ }+ })+ .await+ }+/// How a `SessionEnd` should treat its target session (issue #152).////// The old boolean ("is the session open?") conflated two very differentdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 62c5eeba..28391813 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -77,6 +77,10 @@ pub(crate) enum WriteCmd {summary_page_id: Option<PageId>,reply: oneshot::Sender<StoreResult<()>>,},+ SweepHollowProjects {+ min_age_days: u32,+ reply: oneshot::Sender<StoreResult<Vec<String>>>,+ },InsertObservation {obs: NewObservation,reply: oneshot::Sender<StoreResult<ObservationId>>,@@ -394,6 +398,22 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Delete hollow project rows (no data of any kind) older than+ /// `min_age_days`; returns the deleted names. See+ /// [`ops::sweep_hollow_projects`].+ ///+ /// # Errors+ /// Propagates store failures.+ pub async fn sweep_hollow_projects(&self, min_age_days: u32) -> StoreResult<Vec<String>> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::SweepHollowProjects {+ min_age_days,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Append an observation row.////// # Errors@@ -1033,6 +1053,13 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::end_session(&mut conn, &session_id, summary_page_id.as_ref());send_or_warn(reply, result, "end_session");}+ WriteCmd::SweepHollowProjects {+ min_age_days,+ reply,+ } => {+ let result = ops::sweep_hollow_projects(&mut conn, min_age_days);+ send_or_warn(reply, result, "sweep_hollow_projects");+ }WriteCmd::InsertObservation { obs, reply } => {let result = ops::insert_observation(&mut conn, &obs);send_or_warn(reply, result, "insert_observation");