Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(query,briefing): pin-before-search (pinned standing context)
AkitaOnRails28d1a8ca32c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af2ec2b6..466d6ae4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- "Pin before search": `memory_query` gained an opt-in `pin_first` argument and+ `memory_briefing` now carries a bounded `pinned` list (default off/absent;+ targets the 2.4 line). Pinned pages previously earned only a small post-RRF+ authority bump; they were never surfaced *ahead of* the search, and the+ briefing never listed them by the `pinned` column. With `pin_first: true`, a+ single-project `memory_query` prepends the project's bounded pinned latest+ pages (newest first, cap 10) ahead of the fused hits, deduped by page id so a+ pinned page that also matches the query appears once (marked `pinned: true`),+ and re-truncates to the requested limit; `scopes`, `global`, and `as_of`+ queries ignore it. A project-scoped `memory_briefing` snapshot now includes a+ bounded `pinned` list of pinned latest pages (distinct from the `_slots/`+ path-prefixed `slots`) so SessionStart hot-context can show standing context.+ Both are backed by the new `ReaderPool::list_pinned_pages`; default off/empty+ is byte-identical to the previous query ordering and briefing shape (#NNN).- `memory_read_page` gained an opt-in related-pages graph walk (default false;targets the 2.4 line). Passing `include_related: true` adds a `related` arrayof the pages reachable from the read page through the link graph — a boundeddiff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.mdindex e778e5a8..a6a0e90e 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md@@ -15,7 +15,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe- `memory_read_page` fetches a full page body after a search hit or direct path lookup. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.- `memory_read_session_observations` reads one session's raw hook observations (prompts, tool calls, stops) in capture order, paged and body-capped, when the user asks what actually happened in a session or wants to check a compiled page against its evidence.- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.-- `memory_briefing` returns a structured read-only snapshot for agent consumption.+- `memory_briefing` returns a structured read-only snapshot for agent consumption, including a bounded `pinned` list of the project's pinned standing-context pages (present only when the project has pins).- `memory_explore` returns a prose digest when the user asks for an open-ended catch-up.## Project scope@@ -56,6 +56,15 @@ labelled `superseded: true` so you can tell it from the live version; the currenversion is never marked. This applies to project and explicit-scope searches;`global=true` search and `as_of` time-travel are unaffected.+Pass `pin_first: true` to prepend the project's bounded pinned latest pages+ahead of the ranked search hits ("pin before search") when the user's task+should be anchored in standing operator-curated context first. The pins are+deduped against the search hits (a pinned page that also matches appears once,+marked `pinned: true`), the combined result stays within the requested limit,+and default `false` leaves the ordering unchanged. It applies to single-project+searches (default or `workspace`+`project`); `scopes`, `global`, and `as_of`+queries ignore it.+Use `explain: true` only when the user asks why project or explicit-scope hitsranked as they did. It adds FTS, lexical entity, optional vector, and graphscore provenance to compiled-page hits, including matched entity names.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex ece40e80..6d9f5d96 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -206,7 +206,10 @@ developer, user, and canonical project instructions.\n\expired historical memory. Superseded (older) page versions are hidden \by default; pass `include_superseded=true` when the user wants a page's \history or an answer a later edit removed — each older hit is labelled \- `superseded: true`. Use `explain=true` only when diagnosing \+ `superseded: true`. Pass `pin_first=true` to prepend the project's \+ bounded pinned latest pages ahead of the search hits (deduped, each \+ marked `pinned: true`) when standing operator-curated context should be \+ seen before the ranked matches. Use `explain=true` only when diagnosing \project/scopes ranking; it adds score provenance, while global search \reports only its distinct FTS stream.\n\- `memory_recent` — at session start, or when the user asks 'what's \@@ -214,7 +217,8 @@ developer, user, and canonical project instructions.\n\- `memory_status` — when the user asks 'is ai-memory healthy' or \'how big is the knowledge base'. Returns lifetime counts.\n\- `memory_briefing` — when the user wants a STRUCTURED snapshot \- (counts + 7d/30d activity + rules + recent pages, JSON, no LLM \+ (counts + 7d/30d activity + rules + recent pages + a bounded `pinned` \+ list of the project's pinned standing-context pages, JSON, no LLM \call). READ-ONLY: it never creates handoffs or mutates state. Use \over memory_status when more detail is wanted.\n\- `memory_explore` — when the user wants a PROSE digest. \@@ -512,6 +516,10 @@ pub struct AiMemoryServer {const MAX_QUERY_SCOPES: usize = 25;+/// Upper bound on how many pinned latest pages `memory_query(pin_first=true)`+/// prepends, so standing context never crowds out the search result entirely.+const PIN_FIRST_MAX: usize = 10;+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]struct MemoryScopeArg {/// Project to read inside the workspace.@@ -561,6 +569,15 @@ struct QueryArgs {/// search and folded into `as_of` time-travel. Default false.#[serde(default)]include_superseded: Option<bool>,+ /// Pin before search: prepend the project's bounded pinned latest pages+ /// ahead of the fused search hits, deduped against them so a pinned page+ /// that also matches the query appears once (marked `pinned: true`).+ /// Standing operator-curated context an agent should see first. Applies to+ /// single-project searches (default or `workspace`+`project`); ignored on+ /// `scopes`, `global`, and `as_of` queries. Default false → ordering+ /// unchanged.+ #[serde(default)]+ pin_first: Option<bool>,/// Attach `score_details` to project/scopes hits: per-stream ranks/// (FTS5, entity, vector, graph), raw scores, and RRF contributions, plus a/// top-level `streams_active` list. A `global=true` query uses a@@ -2341,13 +2358,46 @@ impl AiMemoryServer {streams.push("graph");streams});- let hits = hits+ let hits: Vec<QueryHit> = hits.into_iter().map(|(hit, score_details)| QueryHit {hit,score_details: score_details.filter(|_| explain),}).collect();+ // Pin before search: when the caller opts in AND this is a+ // single-project search (no `scopes`; `global`/`as_of` returned+ // earlier), prepend the project's bounded pinned latest pages ahead of+ // the fused hits. Deduped by page id so a pinned page that also matched+ // the query appears once, and the combined list is re-truncated to the+ // requested limit so the total stays bounded. Default off → this branch+ // never runs and the ordering is byte-identical.+ let hits = if args.pin_first.unwrap_or(false) && resolved_scopes.is_none() {+ let (ws, proj) = self+ .effective_ids_for_read_args_with_actor(+ args.workspace.as_deref(),+ args.project.as_deref(),+ &aps_actor,+ )+ .await?;+ let pins = self+ .reader+ .list_pinned_pages(ws, proj, limit.min(PIN_FIRST_MAX))+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ if pins.is_empty() {+ hits+ } else {+ let pin_ids: std::collections::HashSet<PageId> =+ pins.iter().map(|p| p.id).collect();+ let mut combined: Vec<QueryHit> = pins.into_iter().map(QueryHit::from).collect();+ combined.extend(hits.into_iter().filter(|h| !pin_ids.contains(&h.hit.id)));+ combined.truncate(limit);+ combined+ }+ } else {+ hits+ };let response = MemoryQueryResponse {hits,raw_hits,@@ -5337,6 +5387,7 @@ mod tests {snippet: format!("candidate {idx}"),rank: idx as f64,superseded: false,+ pinned: false,},Some(ai_memory_store::SearchExplain::default()),)@@ -5534,6 +5585,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: None,}),@@ -5566,6 +5618,7 @@ mod tests {global: Some(true),include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -7294,6 +7347,7 @@ mod tests {global,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of,};@@ -7333,6 +7387,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: Some(jiff::Timestamp::now().to_string()),}),@@ -7403,6 +7458,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -7429,6 +7485,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: None,}),@@ -7523,6 +7580,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: None,}),@@ -7611,6 +7669,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,};@@ -7689,6 +7748,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -7818,6 +7878,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -7898,6 +7959,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -7994,6 +8056,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -8061,6 +8124,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -8104,6 +8168,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -8180,6 +8245,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -8247,6 +8313,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -9301,6 +9368,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: None,}),@@ -9411,6 +9479,7 @@ mod tests {global: Some(true),include_expired: None,include_superseded: None,+ pin_first: None,explain: Some(true),as_of: None,}),@@ -9459,6 +9528,7 @@ mod tests {global: Some(true),include_expired: Some(true),include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -9540,6 +9610,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -9573,6 +9644,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -9610,6 +9682,7 @@ mod tests {global: Some(true),include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -12488,6 +12561,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),@@ -12523,6 +12597,7 @@ mod tests {global: None,include_expired: None,include_superseded: None,+ pin_first: None,explain: None,as_of: None,}),diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rsindex aca28f5d..07683cb4 100644--- a/crates/ai-memory-mcp/tests/suite/mod.rs+++ b/crates/ai-memory-mcp/tests/suite/mod.rs@@ -22,6 +22,7 @@ mod autoscope_multiuser;mod handoff_admission;mod handoff_identity;mod mcp_stateless_http;+mod query_pin_first;mod query_superseded;mod read_page_related;mod retrieval_via_tools;diff --git a/crates/ai-memory-mcp/tests/suite/query_pin_first.rs b/crates/ai-memory-mcp/tests/suite/query_pin_first.rsnew file mode 100644index 00000000..8345efc7--- /dev/null+++ b/crates/ai-memory-mcp/tests/suite/query_pin_first.rs@@ -0,0 +1,338 @@+//! 2.4 "pin before search": pinned pages become standing context that is+//! surfaced *ahead of* the fused search hits (opt-in `memory_query`+//! `pin_first=true`) and carried on the `memory_briefing` snapshot's `pinned`+//! list, proven end to end through the real MCP tools.+//!+//! Pinned pages otherwise only earn a small post-RRF authority bump; they are+//! never placed before the search result, and the briefing never listed them by+//! the `pinned` column. These tests seed the store through the write path, then+//! drive the production tools over the JSON-RPC HTTP transport and assert on the+//! decoded tool payload:+//!+//! 1. `memory_query(pin_first=false)` — default: a pinned page is NOT forced to+//! the front (byte-identical ordering to today).+//! 2. `memory_query(pin_first=true)` — bounded pinned latest pages lead the+//! result, deduped against the fused hits (a pinned page that also matches+//! the query appears exactly once), each marked `pinned: true`.+//! 3. `memory_briefing` — the `pinned` list carries only pinned latest pages+//! when pins exist, and is absent/empty when none do.++use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_mcp::AiMemoryServer;+use ai_memory_store::Store;+use ai_memory_wiki::Wiki;+use axum::Router;+use axum::body::Body;+use axum::http::Request;+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+use serde_json::{Value, json};+use tempfile::TempDir;+use tower::ServiceExt;++const WS: &str = "default";+const PROJ: &str = "scratch";++struct Harness {+ router: Router,+ store: Store,+ ws: WorkspaceId,+ proj: ProjectId,+ _tmp: TempDir,+}++fn mount(server: AiMemoryServer) -> Router {+ let service = StreamableHttpService::new(+ move || Ok(server.clone()),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(false)+ .with_json_response(true),+ );+ Router::new().nest_service("/mcp", service)+}++async fn harness() -> Harness {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");+ let proj = store+ .writer+ .get_or_create_project(ws, PROJ, None)+ .await+ .expect("proj");+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");+ let server =+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj).with_wiki(wiki);++ Harness {+ router: mount(server),+ store,+ ws,+ proj,+ _tmp: tmp,+ }+}++async fn call(router: &Router, name: &str, arguments: Value) -> Value {+ let body = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": { "name": name, "arguments": arguments },+ });+ let req = Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(Body::from(body.to_string()))+ .expect("mcp req");+ let resp = router.clone().oneshot(req).await.expect("oneshot");+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)+ .await+ .expect("body");+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));+ if let Some(err) = v.get("error") {+ panic!("JSON-RPC error: {err}\nfull: {text}");+ }+ let joined = v+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap_or_else(|| panic!("missing result.content: {text}"))+ .iter()+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))+ .collect::<Vec<_>>()+ .join("\n");+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))+}++fn page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str, pinned: bool) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: path.to_string(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ }+}++fn hits(resp: &Value) -> &Vec<Value> {+ resp.get("hits")+ .and_then(|h| h.as_array())+ .unwrap_or_else(|| panic!("no hits array: {resp}"))+}++fn hit_paths(resp: &Value) -> Vec<&str> {+ hits(resp)+ .iter()+ .filter_map(|h| h.get("path").and_then(|p| p.as_str()))+ .collect()+}++fn query_args(query: &str, extra: Value) -> Value {+ let mut base = json!({+ "query": query,+ "workspace": WS,+ "project": PROJ,+ "limit": 10,+ });+ let obj = base.as_object_mut().unwrap();+ for (k, v) in extra.as_object().unwrap() {+ obj.insert(k.clone(), v.clone());+ }+ base+}++/// 1 + 2. A pinned page that does NOT match the query only leads the result+/// when `pin_first=true`; by default the search ordering is untouched.+#[tokio::test]+async fn memory_query_pin_first_prepends_pinned_context() {+ let h = harness().await;++ // A pinned "standing context" page with no query term of its own.+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "_slots/current-focus.md",+ "the current sprint focus is unrelated standing context",+ true,+ ))+ .await+ .unwrap();++ // An unpinned page that actually matches the query.+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "notes/topic.md",+ "the widget subsystem needle lives here",+ false,+ ))+ .await+ .unwrap();++ // Default (pin_first absent / false): the pinned page must NOT be forced+ // ahead of the matching hit — it doesn't match "needle" at all.+ let default = call(&h.router, "memory_query", query_args("needle", json!({}))).await;+ assert!(+ !hit_paths(&default).contains(&"_slots/current-focus.md"),+ "default query must not surface a pinned page that doesn't match: {default}"+ );+ assert!(+ hit_paths(&default).contains(&"notes/topic.md"),+ "the matching page must surface: {default}"+ );++ // pin_first=true: the pinned page leads, then the fused hit follows.+ let pinned_first = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({ "pin_first": true })),+ )+ .await;+ let paths = hit_paths(&pinned_first);+ assert_eq!(+ paths.first(),+ Some(&"_slots/current-focus.md"),+ "pin_first must place standing pinned context first: {paths:?}"+ );+ assert!(+ paths.contains(&"notes/topic.md"),+ "the fused search hit must still be present: {paths:?}"+ );+ // The prepended pin is marked so a client can tell it apart.+ let lead = &hits(&pinned_first)[0];+ assert_eq!(+ lead.get("pinned").and_then(Value::as_bool),+ Some(true),+ "the prepended pin must be marked pinned:true: {lead}"+ );+}++/// 2 (dedup + bound). A pinned page that ALSO matches the query appears exactly+/// once, at the front; the pinned context is bounded.+#[tokio::test]+async fn memory_query_pin_first_dedups_and_bounds() {+ let h = harness().await;++ // A pinned page that DOES match the query.+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "_slots/pinned-match.md",+ "this pinned page mentions needle directly",+ true,+ ))+ .await+ .unwrap();+ // A second matching unpinned page so there is a fused hit too.+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "notes/other.md",+ "another needle match here",+ false,+ ))+ .await+ .unwrap();++ let resp = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({ "pin_first": true })),+ )+ .await;+ let paths = hit_paths(&resp);+ assert_eq!(+ paths.first(),+ Some(&"_slots/pinned-match.md"),+ "the pinned match must lead: {paths:?}"+ );+ let occurrences = paths+ .iter()+ .filter(|p| **p == "_slots/pinned-match.md")+ .count();+ assert_eq!(+ occurrences, 1,+ "a pinned page that also matches must appear exactly once (deduped): {paths:?}"+ );+ // Bounded: never exceeds the requested limit.+ assert!(+ hits(&resp).len() <= 10,+ "pin_first result must stay within the requested limit: {}",+ hits(&resp).len()+ );+}++/// 3. The briefing carries a `pinned` list of pinned latest pages when they+/// exist, and omits/empties it when none do.+#[tokio::test]+async fn memory_briefing_carries_pinned_list() {+ let h = harness().await;++ // No pins yet: the briefing must not carry a non-empty pinned list.+ let empty = call(+ &h.router,+ "memory_briefing",+ json!({ "workspace": WS, "project": PROJ }),+ )+ .await;+ assert!(+ empty+ .get("pinned")+ .and_then(|p| p.as_array())+ .is_none_or(|a| a.is_empty()),+ "briefing with no pins must not carry a pinned list: {empty}"+ );++ // A pinned page + an unpinned page.+ h.store+ .writer+ .upsert_page(page(h.ws, h.proj, "_slots/standing.md", "standing", true))+ .await+ .unwrap();+ h.store+ .writer+ .upsert_page(page(h.ws, h.proj, "notes/plain.md", "plain", false))+ .await+ .unwrap();++ let resp = call(+ &h.router,+ "memory_briefing",+ json!({ "workspace": WS, "project": PROJ }),+ )+ .await;+ let pinned = resp+ .get("pinned")+ .and_then(|p| p.as_array())+ .expect("briefing must carry a pinned list once pins exist");+ let paths: Vec<&str> = pinned+ .iter()+ .filter_map(|p| p.get("path").and_then(|x| x.as_str()))+ .collect();+ assert_eq!(+ paths,+ vec!["_slots/standing.md"],+ "only pinned latest pages appear in briefing.pinned: {paths:?}"+ );+}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex b564095f..8ffbcf52 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -102,6 +102,11 @@ const DESCRIPTOR_SCAN_CHARS: usize = 600;/// Maximum length of a synthesised page descriptor, in characters.const DESCRIPTOR_MAX_CHARS: usize = 240;+/// Upper bound on the pinned standing-context list carried by a project+/// [`BriefingSnapshot`] (`memory_briefing`), so SessionStart hot-context stays+/// bounded no matter how many pages a project has pinned.+const BRIEFING_PINNED_LIMIT: usize = 10;+/// SQL expression yielding the raw material for [`page_descriptor`]: the/// page's own frontmatter `summary` when it has a non-blank one, otherwise a/// prefix of the body. `NULLIF(TRIM(...), '')` keeps an empty summary from@@ -662,6 +667,14 @@ pub struct PageHit {/// retrieval output is unchanged.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub superseded: bool,+ /// True only when this hit is standing pinned context prepended by the+ /// opt-in `memory_query(pin_first=true)` path (via+ /// [`ReaderPool::list_pinned_pages`]). Ordinary search hits leave it+ /// `false` — the store's FTS/entity/vector/graph retrieval does not read+ /// the `pinned` column into the hit — so it is skipped in JSON when false+ /// and default retrieval output is unchanged.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub pinned: bool,}/// Completed session selected for scheduled auto-improvement.@@ -1208,6 +1221,15 @@ pub struct BriefingSnapshot {/// JSON otherwise so the default briefing shape is unchanged.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub settled: Vec<SettledPage>,+ /// The project's pinned latest pages (`pinned = 1`), newest first and+ /// bounded — standing operator-curated context so SessionStart hot-context+ /// can show it before any search ("pin before search", 2.4 line). Distinct+ /// from `slots`, which is keyed by the `_slots/` path prefix rather than+ /// the `pinned` column. Empty and omitted from JSON when the project has no+ /// pinned pages, so a project without pins keeps the previous briefing+ /// shape byte-for-byte.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub pinned: Vec<BriefingPage>,}/// Trimmed page view for the briefing — path, title, kind, updated_at@@ -1732,6 +1754,7 @@ impl ReaderPool {snippet,rank,superseded: false,+ pinned: false,},authority,));@@ -1950,6 +1973,7 @@ impl ReaderPool {snippet,rank,superseded: false,+ pinned: false,},authority,));@@ -2047,6 +2071,7 @@ impl ReaderPool {snippet,rank,superseded: false,+ pinned: false,},authority,));@@ -2182,6 +2207,7 @@ impl ReaderPool {snippet: entry.snippet,rank: -entry.score, // lower = better (matches FTS5 convention)superseded: false,+ pinned: false,},entry.explain,)@@ -2320,6 +2346,81 @@ impl ReaderPool {snippet,rank,superseded: false,+ pinned: false,+ });+ }+ Ok(hits)+ })+ .await+ }++ /// List the project's pinned latest pages, most-recently-updated first.+ ///+ /// This is the "list pinned pages" primitive behind the opt-in+ /// `memory_query(pin_first=true)` prepend and the briefing's `pinned`+ /// standing-context list (2.4 line): pages an operator explicitly pinned+ /// are standing context an agent should see *before* it searches. It+ /// returns only current pinned versions (`pinned = 1 AND is_latest = 1`),+ /// so an unpinned page and a superseded (older) pinned version are both+ /// excluded, and `limit` bounds the result.+ ///+ /// Recency has no FTS relevance score, so the reused [`PageHit::rank`]+ /// field carries `updated_at` (µs, cast to REAL) exactly as+ /// [`Self::recent_pages_for_project`] does — larger means "more recent";+ /// callers must not read it as an FTS rank. Each hit is marked+ /// `pinned: true`.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_pinned_pages(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ limit: usize,+ ) -> StoreResult<Vec<PageHit>> {+ let limit = limit.clamp(1, 100);+ self.with_conn(move |conn| {+ let sql = format!(+ "SELECT id, path, title, \+ {descriptor} AS snip, \+ CAST(updated_at AS REAL) AS rank \+ FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND is_latest = 1 AND pinned = 1{not_expired} \+ ORDER BY updated_at DESC \+ LIMIT ?3",+ descriptor = page_descriptor_expr("body", "frontmatter_json"),+ not_expired = not_expired("pages", "?4"),+ );+ let mut stmt = conn.prepare_cached(&sql)?;+ #[allow(clippy::cast_possible_wrap)]+ let rows = stmt.query_map(+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ limit as i64,+ now_us()+ ],+ |row| {+ let id_bytes: Vec<u8> = row.get(0)?;+ let path: String = row.get(1)?;+ let title: String = row.get(2)?;+ let snippet = page_descriptor(&row.get::<_, String>(3)?, &title);+ let rank: f64 = row.get(4)?;+ Ok((id_bytes, path, title, snippet, rank))+ },+ )?;+ let mut hits = Vec::new();+ for row in rows {+ let (id_bytes, path, title, snippet, rank) = row?;+ hits.push(PageHit {+ id: PageId::from_slice(&id_bytes)?,+ path: PagePath::new(path)?,+ title,+ snippet,+ rank,+ superseded: false,+ pinned: true,});}Ok(hits)@@ -2377,6 +2478,7 @@ impl ReaderPool {snippet,rank,superseded: false,+ pinned: false,});}Ok(hits)@@ -4237,6 +4339,7 @@ impl ReaderPool {snippet,rank: 0.0,superseded: false,+ pinned: false,},weight,matched,@@ -4436,6 +4539,7 @@ impl ReaderPool {snippet,rank: 0.0,superseded: false,+ pinned: false,},seed_ord,incoming: stream_ord % 2 == 1,@@ -5028,6 +5132,7 @@ impl ReaderPool {snippet: entry.snippet,rank: -entry.score, // lower = better (matches FTS5 convention)superseded: false,+ pinned: false,},entry.explain,)@@ -5550,6 +5655,9 @@ impl ReaderPool {cross_project_dependents: 0,cross_project_dependencies: 0,settled: Vec::new(),+ // The pinned standing-context list is a project-scoped signal;+ // an aggregate current/workspace briefing leaves it empty.+ pinned: Vec::new(),};filter_briefing_slots(&mut snapshot, &slot_visibility);Ok(snapshot)@@ -5764,6 +5872,25 @@ impl ReaderPool {Vec::new()};+ // Pinned latest pages (`pinned = 1`), newest first and bounded —+ // standing operator-curated context for SessionStart hot-context+ // ("pin before search"). Empty result → the field is skipped in+ // JSON, so a project with no pins keeps the prior briefing shape.+ let mut pinned_stmt = conn.prepare_cached(&format!(+ "SELECT path, title, {kind_expr} AS kind, \+ updated_at \+ FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1 AND pinned = 1{not_expired} \+ ORDER BY updated_at DESC \+ LIMIT {BRIEFING_PINNED_LIMIT}",+ not_expired = not_expired("pages", "?3"),+ ))?;+ let pinned: Vec<BriefingPage> = pinned_stmt+ .query_map(params![workspace_id.as_bytes(), project_id.as_bytes(), now_us], briefing_page_from_row)?+ .collect::<Result<Vec<_>, _>>()?+ .into_iter()+ .collect::<Result<Vec<_>, _>>()?;+let mut snapshot = BriefingSnapshot {counts,activity_7d,@@ -5777,6 +5904,7 @@ impl ReaderPool {cross_project_dependents,cross_project_dependencies,settled,+ pinned,};filter_briefing_slots(&mut snapshot, &slot_visibility);Ok(snapshot)@@ -6192,6 +6320,9 @@ impl ReaderPool {cross_project_dependents: 0,cross_project_dependencies: 0,settled: Vec::new(),+ // The pinned standing-context list is a project-scoped signal;+ // an aggregate current/workspace briefing leaves it empty.+ pinned: Vec::new(),};filter_briefing_slots(&mut snapshot, &slot_visibility);Ok(snapshot)diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rsindex a66c56df..ea791faa 100644--- a/crates/ai-memory-store/tests/suite/mod.rs+++ b/crates/ai-memory-store/tests/suite/mod.rs@@ -12,6 +12,7 @@ mod fts_drift_status;mod handoff_ownership;mod most_recently_active_scope;mod multi_session;+mod pinned_pages;mod related_walk;mod retrieval_superseded;mod retrieval_tuning_streams;diff --git a/crates/ai-memory-store/tests/suite/pinned_pages.rs b/crates/ai-memory-store/tests/suite/pinned_pages.rsnew file mode 100644index 00000000..cc04b46f--- /dev/null+++ b/crates/ai-memory-store/tests/suite/pinned_pages.rs@@ -0,0 +1,121 @@+//! `ReaderPool::list_pinned_pages`: the "list pinned latest pages" primitive+//! behind the opt-in `memory_query(pin_first=true)` prepend and the briefing's+//! `pinned` standing-context list (2.4 line).+//!+//! Invariants under test:+//! - **Only `pinned = 1 AND is_latest = 1`.** An unpinned latest page never+//! appears, and a *superseded* (older) pinned version never appears — only+//! the current pinned versions.+//! - **Recency-ordered.** Most-recently-updated pinned page first.+//! - **Bounded.** The requested limit caps the result.++use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_store::Store;++fn page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str, pinned: bool) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: path.to_string(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ }+}++async fn seeded() -> (tempfile::TempDir, Store, WorkspaceId, ProjectId) {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "app".to_string(), None)+ .await+ .unwrap();+ (tmp, store, ws, proj)+}++/// Only current pinned pages surface, newest first, and the limit bounds it.+#[tokio::test]+async fn list_pinned_pages_returns_only_pinned_latest_recency_ordered() {+ let (_tmp, store, ws, proj) = seeded().await;++ // An unpinned page that must never appear.+ store+ .writer+ .upsert_page(page(ws, proj, "notes/plain.md", "plain body", false))+ .await+ .unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;++ // A pinned page written first (older).+ store+ .writer+ .upsert_page(page(ws, proj, "_slots/older.md", "older pinned", true))+ .await+ .unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(2)).await;++ // A pinned page written last (newest) -> must rank first.+ store+ .writer+ .upsert_page(page(ws, proj, "_slots/newer.md", "newer pinned", true))+ .await+ .unwrap();++ let pins = store.reader.list_pinned_pages(ws, proj, 10).await.unwrap();+ let paths: Vec<&str> = pins.iter().map(|p| p.path.as_str()).collect();+ assert_eq!(+ paths,+ vec!["_slots/newer.md", "_slots/older.md"],+ "only pinned latest pages, newest first: {paths:?}"+ );++ // The limit bounds the result.+ let bounded = store.reader.list_pinned_pages(ws, proj, 1).await.unwrap();+ assert_eq!(bounded.len(), 1, "limit must bound the result");+ assert_eq!(bounded[0].path.as_str(), "_slots/newer.md");+}++/// A superseded pinned version (is_latest = 0) is excluded: only the current+/// pinned version of a path is listed.+#[tokio::test]+async fn list_pinned_pages_excludes_superseded_versions() {+ let (_tmp, store, ws, proj) = seeded().await;++ // v1 pinned, then v2 pinned supersedes it on the same path.+ store+ .writer+ .upsert_page(page(ws, proj, "_slots/focus.md", "focus v1", true))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(page(ws, proj, "_slots/focus.md", "focus v2", true))+ .await+ .unwrap();++ let pins = store.reader.list_pinned_pages(ws, proj, 10).await.unwrap();+ assert_eq!(+ pins.len(),+ 1,+ "only the latest pinned version of a path is listed: {:?}",+ pins.iter().map(|p| p.path.as_str()).collect::<Vec<_>>()+ );+ assert_eq!(pins[0].path.as_str(), "_slots/focus.md");+ assert!(+ pins[0].title.contains("focus"),+ "the current version answers"+ );+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 45728708..12d20768 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -369,12 +369,12 @@ invariants below.| Tool | Hint | Purpose ||---|---|---|-| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. |+| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. || `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. || `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). || `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. || `memory_status` | read-only | Counts, paths, version. |-| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |+| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Project-scoped snapshots also carry a bounded `pinned` list (up to 10) of the project's pinned latest pages (`pinned = 1`, newest first) as standing SessionStart hot-context — distinct from `slots`, which is keyed by the `_slots/` path prefix; empty and omitted from JSON when the project has no pins, so the default shape is unchanged. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. || `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. || `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. || `memory_handoff_list` | read-only | List open own/shared handoffs with inspectable body and identity fields; does not claim or expire. Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |