Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix: per-project MCP resolution + OpenCode sessionID (#1, #2)

AkitaOnRailsff009eb4f776
diff --git a/CLAUDE.md b/CLAUDE.md
index e020eca8..56a473de 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -108,7 +108,14 @@ blocking issue:**
without a `cwd` (e.g. early startup or misconfigured agents).
Commands/handlers that bake in a `workspace_id`/`project_id` at
construction time MUST look up the session's actual project (via
- `ReaderPool::session_project_ids`) before writing.
+ `ReaderPool::session_project_ids`) before writing. The MCP read
+ tools have no cwd of their own (the protocol carries none), so they
+ resolve through `AiMemoryServer::effective_ids`: explicit `project`
+ arg → the hook-published `ActiveProject` (the cwd the agent is
+ working in, shared in-process between `/hook` and `/mcp`) → the
+ baked-in default. Never query a read tool against the static
+ `--project` alone — that re-introduces issue #2 (reads land in
+ `scratch` while hooks populate the real project).
b. **Storage layout**: wiki files live at
`<wiki_root>/<workspace_id>/<project_id>/<page-path>`. The mutable
@@ -147,6 +154,23 @@ blocking issue:**
Both use `sysinfo` to refuse if any sibling `ai-memory` is alive.
Use the shared `crate::http_client::{ServerEndpoint, get_json,
post_json}` plumbing for every new client subcommand.
+17. **Wiki-structure changes require a migration.** Any change to the
+ on-disk wiki layout (path scheme, directory names, mass page rewrites)
+ MUST be accompanied by a `WikiMigration` implementation registered in
+ `crates/ai-memory-wiki/src/migrations/mod.rs`. The migration runs at
+ server startup (after refinery, before the watcher), is tracked in the
+ `wiki_migrations` SQL table, and runs at most once per data directory.
+ Rules:
+ - Migration names are `YYYY_MM_DDTHH_MM_<snake_case>` (UTC, chosen at
+ authoring time). Never change a name after it ships.
+ - Implementations must be idempotent: detect whether the work is already
+ done and return `Ok(())` immediately if so.
+ - No LLM calls and no destructive deletes without a graveyard step
+ (move to `<wiki_root>/_graveyard/<migration_name>/…` first).
+ - No direct SQL — use `WriterHandle` methods (single-writer invariant).
+ - Append to the registry; never reorder or remove entries.
+ See [`docs/wiki-migrations.md`](docs/wiki-migrations.md) for the full
+ guide and an example implementation.
## Mistakes documented in the research — do NOT repeat
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 7d318565..ea523ad7 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -9,7 +9,7 @@ use ai_memory_llm::{build_embedder, build_provider, embedder_from_env, provider_
use ai_memory_mcp::{AdminState, AiMemoryServer, admin_router};
use ai_memory_store::Store;
use ai_memory_web;
-use ai_memory_wiki::{WatcherHandle, Wiki};
+use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::{DefaultBodyLimit, State};
@@ -44,6 +44,19 @@ const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
let store = Store::open(&config.data_dir)
.with_context(|| format!("opening store at {}", config.data_dir.display()))?;
+
+ // Run any outstanding wiki-structure migrations before the watcher starts
+ // so file moves and renames are never raced by the reconciler.
+ let wiki_root = config.data_dir.join("wiki");
+ run_wiki_migrations(
+ &store.writer,
+ &store.reader,
+ &wiki_root,
+ &migrations::registry(),
+ )
+ .await
+ .with_context(|| "applying wiki-structure migrations")?;
+
let ws = store
.writer
.get_or_create_workspace(args.workspace.clone())
@@ -102,9 +115,17 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
Some(WatcherHandle::start(wiki.clone())?)
};
+ // Shared between the MCP server and the hook router: the hook
+ // router publishes the cwd-resolved project on each event; the MCP
+ // read tools read it as their default so a shared HTTP server
+ // answers for the project the agent is actually in, not the static
+ // `--project` (issue #2). In stdio mode no hook router is built, so
+ // this stays empty and the baked-in default is used.
+ let active_project = ai_memory_core::ActiveProject::new();
let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
.with_wiki(wiki.clone())
.with_decay_params(config.decay)
+ .with_active_project(active_project.clone())
.with_sanitizer(sanitizer.clone());
if let Some(e) = embedder.clone() {
server = server.with_embedder(e);
@@ -178,6 +199,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
project_cache: std::sync::Arc::new(tokio::sync::Mutex::new(
std::collections::HashMap::new(),
)),
+ active_project: active_project.clone(),
});
let admin = admin_router(AdminState {
writer: store.writer.clone(),
diff --git a/crates/ai-memory-core/src/active_project.rs b/crates/ai-memory-core/src/active_project.rs
new file mode 100644
index 00000000..21a22ae2
--- /dev/null
+++ b/crates/ai-memory-core/src/active_project.rs
@@ -0,0 +1,104 @@
+//! A process-shared pointer to the project the user is currently active in.
+//!
+//! ## Why this exists (issue #2)
+//!
+//! The MCP protocol carries no working-directory context: a `memory_query`
+//! call arrives with its arguments and nothing else, so a tool handler has
+//! no way to know which project the agent is sitting in. The lifecycle hooks
+//! *do* know — every `/hook` event carries the agent's `cwd`, and the hook
+//! router resolves it to the correct per-cwd `(workspace_id, project_id)`.
+//!
+//! In HTTP mode the `/hook` ingress and the `/mcp` endpoint live in the same
+//! process, so the hook router can publish "the project the user is currently
+//! active in" to this shared pointer, and the MCP tools can read it as their
+//! default instead of falling back to the server's static `--project` (which
+//! defaults to `scratch` and made the read tools return empty memory even
+//! when the hooks were correctly populating a real project).
+//!
+//! The pointer reflects the most recently resolved cwd-based project. For the
+//! common single-user, one-project-at-a-time workflow this is exactly right.
+//! For the rarer case of one shared server fielding several projects
+//! concurrently, the MCP tools also accept an explicit `project` argument that
+//! takes precedence over this pointer.
+//!
+//! The lock is held only for the microseconds it takes to copy a small tuple;
+//! callers never `.await` while holding it, so a plain `std::sync::RwLock` is
+//! the right primitive (no async lock needed).
+
+use std::sync::{Arc, RwLock};
+
+use crate::ids::{ProjectId, WorkspaceId};
+
+/// Cheap, cloneable handle to the shared "currently active project" slot.
+///
+/// Clones share the same underlying slot. Starts empty; the hook router
+/// fills it as events arrive.
+#[derive(Clone, Default)]
+pub struct ActiveProject {
+ inner: Arc<RwLock<Option<(WorkspaceId, ProjectId)>>>,
+}
+
+impl ActiveProject {
+ /// Create an empty pointer (no project resolved yet).
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Publish the project the agent is currently active in. Called by the
+ /// hook router after it resolves an event's `cwd` to a real project.
+ pub fn set(&self, workspace_id: WorkspaceId, project_id: ProjectId) {
+ // A poisoned lock means a writer panicked mid-update. The slot holds
+ // only a Copy tuple, so there's no torn state to recover — recover the
+ // guard and overwrite rather than propagating the panic into a hook
+ // handler that must stay fire-and-forget.
+ let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
+ *guard = Some((workspace_id, project_id));
+ }
+
+ /// Read the currently active project, if any has been published yet.
+ #[must_use]
+ pub fn get(&self) -> Option<(WorkspaceId, ProjectId)> {
+ let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());
+ *guard
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn starts_empty() {
+ assert!(ActiveProject::new().get().is_none());
+ }
+
+ #[test]
+ fn set_then_get_round_trips() {
+ let ap = ActiveProject::new();
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ ap.set(ws, proj);
+ assert_eq!(ap.get(), Some((ws, proj)));
+ }
+
+ #[test]
+ fn set_overwrites_previous() {
+ let ap = ActiveProject::new();
+ ap.set(WorkspaceId::new(), ProjectId::new());
+ let ws2 = WorkspaceId::new();
+ let proj2 = ProjectId::new();
+ ap.set(ws2, proj2);
+ assert_eq!(ap.get(), Some((ws2, proj2)));
+ }
+
+ #[test]
+ fn clones_share_one_slot() {
+ let a = ActiveProject::new();
+ let b = a.clone();
+ let ws = WorkspaceId::new();
+ let proj = ProjectId::new();
+ a.set(ws, proj);
+ assert_eq!(b.get(), Some((ws, proj)), "clone must see the same slot");
+ }
+}
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 160a5115..fb3d285c 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -5,6 +5,7 @@
//! pure-compute, no IO). Nothing in here performs I/O, which keeps it
//! trivially unit-testable and free of platform concerns.
+pub mod active_project;
pub mod error;
pub mod handoff;
pub mod ids;
@@ -13,6 +14,7 @@ pub mod page;
pub mod routing_snippet;
pub mod sanitize;
+pub use active_project::ActiveProject;
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
pub use ids::{
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 9a795415..980da82c 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -113,7 +113,12 @@ impl HookEnvelope {
pub fn from_query_and_body(query: HookQuery, raw: serde_json::Value) -> Self {
let event = HookEvent::parse(&query.event);
let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);
- let session_id = extract_string(&raw, &["session_id", "sessionId", "session"]);
+ // OpenCode's plugin SDK sends `sessionID` (capital `ID`) on the
+ // tool.execute.*/session.* events; Claude Code uses `session_id`,
+ // Codex `sessionId`. JSON keys are case-sensitive, so all three
+ // spellings must be listed or OpenCode tool events fail the
+ // "missing session_id" check in the router (issue #1).
+ let session_id = extract_string(&raw, &["session_id", "sessionId", "sessionID", "session"]);
let cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir"]);
let title_hint = best_title_hint(event, &raw);
let body_excerpt = best_body_excerpt(event, &raw);
@@ -230,6 +235,25 @@ mod tests {
assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-6"));
}
+ /// OpenCode's plugin SDK sends `sessionID` (capital `ID`) on the
+ /// tool.execute.* / session.* events. Regression for issue #1: this
+ /// spelling must be extracted, otherwise non-session-start events
+ /// fail the router's "missing session_id" check.
+ #[test]
+ fn envelope_extracts_opencode_camelcase_session_id() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("open-code".into()),
+ };
+ let raw = serde_json::json!({
+ "sessionID": "ses_abc123",
+ "tool": "bash",
+ "callID": "call_1"
+ });
+ let env = HookEnvelope::from_query_and_body(q, raw);
+ assert_eq!(env.session_id.as_deref(), Some("ses_abc123"));
+ }
+
/// Alternative agent-name spellings all map to the same canonical
/// AgentKind. The hook scripts and the test e2e shim send slightly
/// different strings for historical reasons; this asserts we
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 0d66ab48..e1e22f29 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -13,8 +13,8 @@ use std::sync::Arc;
use ai_memory_consolidate::Consolidator;
use ai_memory_core::{
- AgentKind, Handoff, NewHandoff, NewObservation, NewSession, ObservationKind, ProjectId,
- Sanitized, Sanitizer, SessionId, WorkspaceId,
+ ActiveProject, AgentKind, Handoff, NewHandoff, NewObservation, NewSession, ObservationKind,
+ ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
};
use ai_memory_store::WriterHandle;
use ai_memory_wiki::Wiki;
@@ -60,6 +60,11 @@ pub struct HookState {
/// same agent session. Keyed by the raw cwd string; no
/// canonicalisation — two symlinked paths are separate buckets.
pub project_cache: Arc<tokio::sync::Mutex<HashMap<String, (WorkspaceId, ProjectId)>>>,
+ /// Pointer shared with the MCP server. Every cwd-resolved event
+ /// publishes its project here so the read tools (which have no cwd
+ /// of their own) default to the project the user is actually in
+ /// rather than the server's static `--project` (issue #2).
+ pub active_project: ActiveProject,
}
/// Build a router with `POST /hook` (event ingress) and `GET /handoff`
@@ -211,6 +216,10 @@ async fn resolve_project_ids(
{
let cache = state.project_cache.lock().await;
if let Some(ids) = cache.get(cwd) {
+ // Republish on every hit: a cache hit still means the agent
+ // is active in this project *now*, which is exactly what the
+ // MCP read tools need as their default.
+ state.active_project.set(ids.0, ids.1);
return Ok(*ids);
}
}
@@ -238,6 +247,7 @@ async fn resolve_project_ids(
.lock()
.await
.insert(cwd.to_string(), ids);
+ state.active_project.set(ws, proj);
Ok(ids)
}
@@ -560,6 +570,7 @@ mod tests {
consolidator: None,
sanitizer,
project_cache: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
+ active_project: ActiveProject::new(),
}
}
@@ -585,6 +596,10 @@ mod tests {
// Neither should match the server-default scratch project.
assert_ne!(proj_a, state.project_id);
assert_ne!(proj_b, state.project_id);
+
+ // The MCP-shared pointer reflects the most recently resolved
+ // project (issue #2) — here, project-beta.
+ assert_eq!(state.active_project.get(), Some((ws_b, proj_b)));
}
/// An event without a cwd must fall back to the server defaults.
@@ -601,6 +616,11 @@ mod tests {
let (ws2, proj2) = resolve_project_ids(&state, Some("")).await.unwrap();
assert_eq!(ws2, state.workspace_id);
assert_eq!(proj2, state.project_id);
+
+ // A cwd-less event must NOT publish the scratch fallback as the
+ // active project — that would re-introduce the issue #2 bug of
+ // MCP reads defaulting to an empty scratch bucket.
+ assert!(state.active_project.get().is_none());
}
/// A second call for the same cwd must hit the in-memory cache — no
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 90ee1850..ecc49a79 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -4,7 +4,9 @@ use std::str::FromStr;
use std::sync::Arc;
use ai_memory_consolidate::{Consolidator, run_lint, run_sweep};
-use ai_memory_core::{AgentKind, NewHandoff, PageId, ProjectId, SessionId, WorkspaceId};
+use ai_memory_core::{
+ ActiveProject, AgentKind, NewHandoff, PageId, ProjectId, SessionId, WorkspaceId,
+};
use ai_memory_llm::{Embedder, LlmProvider};
use ai_memory_store::{DecayParams, ReaderPool, WriterHandle};
use ai_memory_wiki::Wiki;
@@ -77,6 +79,14 @@ pub struct AiMemoryServer {
writer: WriterHandle,
workspace_id: WorkspaceId,
project_id: ProjectId,
+ /// Project the user is currently active in, published by the hook
+ /// router on each cwd-resolved event. The read tools prefer this
+ /// over the baked-in `(workspace_id, project_id)` so a shared HTTP
+ /// server queries the project the agent is actually in rather than
+ /// the static `--project` default (issue #2). Empty until the first
+ /// hook event arrives, or always-empty in stdio mode (no shared
+ /// hook ingress) — in which case the baked-in default is used.
+ active_project: ActiveProject,
default_limit: usize,
/// Optional LLM consolidator. When `None`, `memory_consolidate`
/// returns a "not configured" error.
@@ -112,6 +122,11 @@ struct QueryArgs {
/// Maximum number of hits to return (default 10, max 100).
#[serde(default, alias = "n", alias = "top_k")]
limit: Option<usize>,
+ /// Project to search. Omit to target the project you're currently
+ /// working in (resolved from recent hook activity). Only needed when
+ /// one shared server fields several projects at once.
+ #[serde(default)]
+ project: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -119,6 +134,18 @@ struct RecentArgs {
/// Maximum number of recent pages to return (default 10, max 100).
#[serde(default, alias = "n")]
limit: Option<usize>,
+ /// Project to read. Omit to target the project you're currently
+ /// working in (resolved from recent hook activity).
+ #[serde(default)]
+ project: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
+struct StatusArgs {
+ /// Project to report counts for. Omit to target the project you're
+ /// currently working in (resolved from recent hook activity).
+ #[serde(default)]
+ project: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -188,6 +215,10 @@ struct BriefingArgs {
/// How many recently-updated pages to include (default 10, max 100).
#[serde(default)]
recent_pages_limit: Option<usize>,
+ /// Project to brief on. Omit to target the project you're currently
+ /// working in (resolved from recent hook activity).
+ #[serde(default)]
+ project: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -201,6 +232,10 @@ struct ExploreArgs {
/// consider (default 10).
#[serde(default)]
recent_pages_limit: Option<usize>,
+ /// Project to explore. Omit to target the project you're currently
+ /// working in (resolved from recent hook activity).
+ #[serde(default)]
+ project: Option<String>,
}
#[tool_router]
@@ -219,6 +254,7 @@ impl AiMemoryServer {
writer,
workspace_id,
project_id,
+ active_project: ActiveProject::new(),
default_limit: 10,
consolidator: None,
llm: None,
@@ -246,6 +282,37 @@ impl AiMemoryServer {
self
}
+ /// Share the hook router's [`ActiveProject`] pointer so the read
+ /// tools default to the project the user is currently in (issue #2).
+ /// In stdio mode there is no shared hook ingress, so callers simply
+ /// don't set this and the baked-in default is used.
+ #[must_use]
+ pub fn with_active_project(mut self, active_project: ActiveProject) -> Self {
+ self.active_project = active_project;
+ self
+ }
+
+ /// Resolve which `(workspace_id, project_id)` a read tool should
+ /// query. Precedence (matches the documented resolution chain):
+ /// 1. an explicit `project` name argument (looked up read-only in
+ /// the server's workspace; ignored if no such project exists),
+ /// 2. the hook-published [`ActiveProject`] (the cwd the agent is
+ /// currently working in),
+ /// 3. the server's baked-in `--project` default.
+ async fn effective_ids(&self, explicit_project: Option<&str>) -> (WorkspaceId, ProjectId) {
+ if let Some(name) = explicit_project.map(str::trim).filter(|s| !s.is_empty())
+ && let Ok(Some(pid)) = self
+ .reader
+ .find_project(self.workspace_id, name.to_string())
+ .await
+ {
+ return (self.workspace_id, pid);
+ }
+ self.active_project
+ .get()
+ .unwrap_or((self.workspace_id, self.project_id))
+ }
+
/// Override the retention-sweep parameters (typically populated
/// from the user's config.toml `[decay]` table).
#[must_use]
@@ -314,6 +381,7 @@ impl AiMemoryServer {
Parameters(args): Parameters<QueryArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
// Hybrid path: try to embed the query; if it fails (provider
// outage, cold-start timeout, billing, etc.) degrade to BM25
// instead of erroring the whole query — losing semantic
@@ -323,8 +391,8 @@ impl AiMemoryServer {
Ok(qv) => {
self.reader
.hybrid_search(
- self.workspace_id,
- self.project_id,
+ ws,
+ proj,
args.query.clone(),
Some(qv),
embedder.provider().to_string(),
@@ -342,18 +410,13 @@ impl AiMemoryServer {
"embedder failed; degrading memory_query to BM25-only"
);
self.reader
- .search_pages_for_project(
- self.workspace_id,
- self.project_id,
- args.query,
- limit,
- )
+ .search_pages_for_project(ws, proj, args.query, limit)
.await
}
}
} else {
self.reader
- .search_pages_for_project(self.workspace_id, self.project_id, args.query, limit)
+ .search_pages_for_project(ws, proj, args.query, limit)
.await
};
let hits = hits.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -374,9 +437,10 @@ impl AiMemoryServer {
Parameters(args): Parameters<RecentArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
let hits = self
.reader
- .recent_pages_for_project(self.workspace_id, self.project_id, limit)
+ .recent_pages_for_project(ws, proj, limit)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
self.spawn_access_bump(hits.iter().map(|h| h.id).collect());
@@ -561,10 +625,14 @@ impl AiMemoryServer {
(pages latest, pages all versions, sessions, observations). \
Use this at session start to see how much context the agent has \
accumulated for this workspace.")]
- async fn memory_status(&self) -> Result<CallToolResult, McpError> {
+ async fn memory_status(
+ &self,
+ Parameters(args): Parameters<StatusArgs>,
+ ) -> Result<CallToolResult, McpError> {
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
let counts = self
.reader
- .status_counts_for_project(self.workspace_id, self.project_id)
+ .status_counts_for_project(ws, proj)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let response = StatusResponse { counts };
@@ -585,9 +653,10 @@ impl AiMemoryServer {
Parameters(args): Parameters<BriefingArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.recent_pages_limit.unwrap_or(10);
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
let snapshot = self
.reader
- .briefing_for_project(self.workspace_id, self.project_id, limit)
+ .briefing_for_project(ws, proj, limit)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
ok_json(&snapshot)
@@ -612,9 +681,10 @@ impl AiMemoryServer {
Parameters(args): Parameters<ExploreArgs>,
) -> Result<CallToolResult, McpError> {
let limit = args.recent_pages_limit.unwrap_or(10);
+ let (ws, proj) = self.effective_ids(args.project.as_deref()).await;
let snapshot = self
.reader
- .briefing_for_project(self.workspace_id, self.project_id, limit)
+ .briefing_for_project(ws, proj, limit)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
@@ -885,6 +955,46 @@ mod tests {
let (_tmp, _store, _server, _ws, _pj) = setup_server().await;
}
+ /// Read tools resolve the project in the order: explicit `project`
+ /// arg → hook-published active project → baked-in default (issue #2).
+ #[tokio::test]
+ async fn effective_ids_follows_precedence_chain() {
+ let (_tmp, store, server, ws, baked) = setup_server().await;
+
+ // Baseline: nothing published, no arg → baked-in default.
+ assert_eq!(server.effective_ids(None).await, (ws, baked));
+
+ // A second real project in the same workspace.
+ let other = store
+ .writer
+ .get_or_create_project(
+ ws,
+ "projeto_camera",
+ Some("/home/u/projeto_camera".to_string()),
+ )
+ .await
+ .unwrap();
+
+ // Hook publishes it → it becomes the default for cwd-less calls.
+ server.active_project.set(ws, other);
+ assert_eq!(server.effective_ids(None).await, (ws, other));
+
+ // An explicit (existing) project arg wins over the active pointer.
+ assert_eq!(
+ server.effective_ids(Some("scratch")).await,
+ (ws, baked),
+ "explicit project arg should override the active pointer"
+ );
+
+ // An explicit but unknown project name falls through to the
+ // active pointer rather than erroring or returning a bogus id.
+ assert_eq!(
+ server.effective_ids(Some("does-not-exist")).await,
+ (ws, other),
+ "unknown explicit project falls through to the active pointer"
+ );
+ }
+
#[tokio::test]
async fn memory_query_returns_hits_via_tool_method() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
@@ -892,6 +1002,7 @@ mod tests {
.memory_query(Parameters(QueryArgs {
query: "karpathy".into(),
limit: Some(5),
+ project: None,
}))
.await
.unwrap();
@@ -905,7 +1016,10 @@ mod tests {
#[tokio::test]
async fn memory_status_returns_counts() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
- let result = server.memory_status().await.unwrap();
+ let result = server
+ .memory_status(Parameters(StatusArgs { project: None }))
+ .await
+ .unwrap();
let text = result
.content
.first()
@@ -921,6 +1035,7 @@ mod tests {
let result = server
.memory_briefing(Parameters(BriefingArgs {
recent_pages_limit: Some(5),
+ project: None,
}))
.await
.unwrap();
@@ -963,6 +1078,7 @@ mod tests {
.memory_explore(Parameters(ExploreArgs {
focus: None,
recent_pages_limit: Some(5),
+ project: None,
}))
.await
.unwrap();
@@ -1019,7 +1135,10 @@ mod tests {
async fn memory_recent_returns_one_hit() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
let result = server
- .memory_recent(Parameters(RecentArgs { limit: Some(5) }))
+ .memory_recent(Parameters(RecentArgs {
+ limit: Some(5),
+ project: None,
+ }))
.await
.unwrap();
let text = result
@@ -1167,6 +1286,7 @@ mod tests {
.memory_query(Parameters(QueryArgs {
query: "Karpathy".into(),
limit: Some(99_999),
+ project: None,
}))
.await
.expect("oversized limit should be clamped, not refused");
@@ -1191,6 +1311,7 @@ mod tests {
.memory_query(Parameters(QueryArgs {
query: "\"unbalanced".into(),
limit: Some(10),
+ project: None,
}))
.await;
// Either a tidy 0-hit Ok (FTS5 is occasionally lenient) or