Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(auto-improve,decay): scope proposal staging and reinforcement to the operator
Djalma Júnior5044af970256
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4f13b8ff..93eea781 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0exist", so a trusted-proxy deployment — which never writes a `users` row —gets root-only admin gating instead of waving every proxied caller throughthe single-operator escape hatch (#333).+- Pending auto-improve proposals record who staged them (V42+ `staged_by_actor_user`, the qualified identity key, surfaced on the proposal+ detail), and the one-pending-per-target rule is scoped per operator through+ a NULL-collapsing unique index, so one operator's pending suggestion stops+ blocking everybody else's for the same page while every unattributed caller+ — single-operator servers, the scheduler, the telemetry report, the curator+ — keeps the original one-per-page rule unchanged (#310).+- Page reinforcement is recorded per operator (V43 `page_access`, keyed on the+ identity storage key) beside the untouched shared counter, and the retention+ formula gains an opt-in breadth term: `[decay] breadth_weight` (default+ `0.0`) lets a page read by many distinct operators outrank one read as often+ by a single person. Provably identity at the default weight and at 0 or 1+ distinct readers under any weight, so no existing eviction decision moves+ until an operator deliberately turns it on; the per-operator access-bump+ throttle keys on (page, operator) so one reader cannot swallow a+ colleague's reinforcement inside the cooldown window (#310).++### Fixed+- A staged auto-improve proposal colliding with one already pending no longer+ aborts its whole staging run (losing the run row, its sibling proposals and+ the paid LLM review): the colliding proposal alone is skipped, and every+ staging surface — `memory_auto_improve`, `/admin/auto-improve`, the+ telemetry report, the curator, the CLI and the scheduler's log — names the+ skipped target and the reason instead of silently returning N-1 proposals+ (#310).## [1.21.0] - 2026-07-31diff --git a/Cargo.lock b/Cargo.lockindex ce2ace25..93f9a396 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -94,6 +94,7 @@ dependencies = ["thiserror 2.0.18","tokio","tracing",+ "tracing-subscriber",][[package]]diff --git a/crates/ai-memory-cli/src/commands/auto_improve.rs b/crates/ai-memory-cli/src/commands/auto_improve.rsindex 00563bf6..6812aff3 100644--- a/crates/ai-memory-cli/src/commands/auto_improve.rs+++ b/crates/ai-memory-cli/src/commands/auto_improve.rs@@ -1,5 +1,6 @@//! `ai-memory auto-improve` — review one session and apply durable wiki edits through the auto-improvement approval path.+use ai_memory_store::SkippedProposal;use anyhow::Result;use serde::{Deserialize, Serialize};@@ -45,6 +46,12 @@ struct StageResponse {warnings: Vec<String>,rejected_candidates_count: usize,proposals: Vec<ProposalOutcome>,+ /// Proposals the server staged nothing for, with the reason. Re-declared+ /// here because `--json` prints THIS struct, not the server's body: a key+ /// missing from it is dropped by serde and never reaches the operator.+ /// `default` keeps an older server (which sends no such key) parsing.+ #[serde(default)]+ skipped: Vec<SkippedProposal>,}#[derive(Debug, Deserialize, Serialize)]@@ -102,28 +109,105 @@ pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {if args.json {println!("{}", serde_json::to_string_pretty(&response)?);} else {- if response.approval_required {- println!(- "Staged auto-improve run {} for manual approval",- response.run_id- );+ println!("{}", render_human(&response));+ }+ Ok(())+}++fn render_human(response: &StageResponse) -> String {+ let mut lines = Vec::new();+ if response.approval_required {+ lines.push(format!(+ "Staged auto-improve run {} for manual approval",+ response.run_id+ ));+ } else {+ lines.push(format!(+ "Auto-approved auto-improve run {}",+ response.run_id+ ));+ }+ lines.push(format!("Approval policy: {}", response.approval_policy));+ for proposal in &response.proposals {+ if let Some(page_id) = &proposal.page_id {+ lines.push(format!(+ " - {} [{}] page {} ({})",+ proposal.id, proposal.status, page_id, proposal.sidecar_path+ ));} else {- println!("Auto-approved auto-improve run {}", response.run_id);- }- println!("Approval policy: {}", response.approval_policy);- for proposal in &response.proposals {- if let Some(page_id) = &proposal.page_id {- println!(- " - {} [{}] page {} ({})",- proposal.id, proposal.status, page_id, proposal.sidecar_path- );- } else {- println!(- " - {} [{}] ({})",- proposal.id, proposal.status, proposal.sidecar_path- );- }+ lines.push(format!(+ " - {} [{}] ({})",+ proposal.id, proposal.status, proposal.sidecar_path+ ));}}- Ok(())+ lines.extend(super::skipped_proposal_lines(&response.skipped));+ lines.join("\n")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn wire(skipped: serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "run_id": "run-1",+ "approval_required": true,+ "approval_policy": "manual",+ "session_id": "sess-1",+ "summary": "one durable procedure",+ "warnings": [],+ "rejected_candidates_count": 0,+ "proposals": [],+ "skipped": skipped,+ })+ }++ #[test]+ fn skipped_survives_the_response_round_trip_into_json_output() {+ let response: StageResponse = serde_json::from_value(wire(serde_json::json!([{+ "target_path": "procedures/release.md",+ "reason": "a proposal is already pending review for this path",+ }])))+ .expect("server body parses");++ // `--json` prints this struct, so the assertion has to be on what the+ // struct serialises back to, not on what arrived.+ let printed = serde_json::to_value(&response).expect("re-serialise");+ assert_eq!(+ printed["skipped"][0]["target_path"], "procedures/release.md",+ "--json dropped the skipped proposals: {printed}"+ );+ assert_eq!(+ printed["skipped"][0]["reason"],+ "a proposal is already pending review for this path"+ );+ }++ #[test]+ fn skipped_reaches_human_output_too() {+ let response: StageResponse = serde_json::from_value(wire(serde_json::json!([{+ "target_path": "procedures/release.md",+ "reason": "a proposal is already pending review for this path",+ }])))+ .expect("server body parses");+ let human = render_human(&response);+ assert!(human.contains("procedures/release.md"), "{human}");+ assert!(human.contains("already pending review"), "{human}");+ }++ #[test]+ fn a_clean_run_prints_no_skipped_section() {+ let response: StageResponse =+ serde_json::from_value(wire(serde_json::json!([]))).expect("server body parses");+ assert!(!render_human(&response).contains("Skipped"));+ }++ #[test]+ fn a_server_without_the_field_still_parses() {+ let mut body = wire(serde_json::json!([]));+ body.as_object_mut().unwrap().remove("skipped");+ let response: StageResponse = serde_json::from_value(body).expect("older server body");+ assert!(response.skipped.is_empty());+ }}diff --git a/crates/ai-memory-cli/src/commands/auto_improve_report.rs b/crates/ai-memory-cli/src/commands/auto_improve_report.rsindex e2455560..bb1ed9e8 100644--- a/crates/ai-memory-cli/src/commands/auto_improve_report.rs+++ b/crates/ai-memory-cli/src/commands/auto_improve_report.rs@@ -1,6 +1,7 @@//! `ai-memory auto-improve-report` — read-only telemetry for auto-improvement outcomes.use ai_memory_consolidate::AutoImproveTelemetryReport;+use ai_memory_store::SkippedProposal;use anyhow::Result;use serde::{Deserialize, Serialize};@@ -22,6 +23,13 @@ struct AutoImproveReportStageResponse {run_id: String,proposal_ids: Vec<String>,sidecar_paths: Vec<String>,+ /// The CLI is the only in-tree caller of `/admin/auto-improve/report`, so a+ /// key it does not declare reaches nobody at all. This run stages a single+ /// telemetry page: when that one collides, `Proposals:` below prints an+ /// empty line with nothing saying why. `default` keeps an older server+ /// (which sends no such key) parsing.+ #[serde(default)]+ skipped: Vec<SkippedProposal>,report: AutoImproveTelemetryReport,}@@ -47,11 +55,7 @@ pub async fn run(config: &Config, args: AutoImproveReportArgs) -> Result<()> {if args.json {println!("{}", serde_json::to_string_pretty(&response)?);} else {- println!("\nStaged auto-improve telemetry report for {project}\n");- println!("Run: {}", response.run_id);- println!("Proposals: {}", response.proposal_ids.join(", "));- println!("Sidecars: {}", response.sidecar_paths.join(", "));- println!("Summary: {}", response.report.summary);+ println!("{}", render_stage_human(&response, &project));println!("\n--- machine-readable ---");println!("{}", serde_json::to_string_pretty(&response)?);}@@ -70,6 +74,18 @@ pub async fn run(config: &Config, args: AutoImproveReportArgs) -> Result<()> {Ok(())}+fn render_stage_human(response: &AutoImproveReportStageResponse, project: &str) -> String {+ let mut lines = vec![+ format!("\nStaged auto-improve telemetry report for {project}\n"),+ format!("Run: {}", response.run_id),+ format!("Proposals: {}", response.proposal_ids.join(", ")),+ format!("Sidecars: {}", response.sidecar_paths.join(", ")),+ format!("Summary: {}", response.report.summary),+ ];+ lines.extend(super::skipped_proposal_lines(&response.skipped));+ lines.join("\n")+}+fn print_human_report(report: &AutoImproveTelemetryReport, project: &str) {println!("\nAuto-improve telemetry for {project}\n");println!("Summary: {}", report.summary);@@ -107,3 +123,100 @@ fn print_human_report(report: &AutoImproveTelemetryReport, project: &str) {println!(" ... {} more", report.findings.len() - 10);}}++#[cfg(test)]+mod tests {+ use super::*;++ fn wire(skipped: serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "run_id": "run-1",+ "proposal_ids": [],+ "sidecar_paths": [],+ "skipped": skipped,+ "report": {+ "workspace": "default",+ "project": "proj",+ "generated_at": "2026-01-01T00:00:00Z",+ "since_created_at": 0,+ "summary": "no learning proposals in window",+ "params": { "since_days": 30, "top_limit": 10 },+ "aggregate": {+ "run_count": 0,+ "runs_with_learning_proposals": 0,+ "proposals_by_status": [],+ "proposals_by_operation": [],+ "proposals_by_edit_mode": [],+ "proposals_by_kind": [],+ "maintenance_proposals_by_kind": [],+ "top_targets": [],+ "rejections_by_reason": [],+ "repeated_rejection_fingerprints": [],+ "rejected_targets": [],+ },+ "terminal_rates": {+ "denominator": 0,+ "approved_rate": 0.0,+ "rejected_rate": 0.0,+ "conflict_rate": 0.0,+ "failed_rate": 0.0,+ },+ "findings": [],+ "blind_spots": [],+ },+ })+ }++ fn colliding() -> serde_json::Value {+ serde_json::json!([{+ "target_path": "_pending/auto-improve/telemetry.md",+ "reason": "a proposal is already pending review for this path",+ }])+ }++ #[test]+ fn skipped_survives_the_response_round_trip_into_json_output() {+ let response: AutoImproveReportStageResponse =+ serde_json::from_value(wire(colliding())).expect("server body parses");++ // `--json` prints this struct, so the assertion has to be on what the+ // struct serialises back to, not on what arrived.+ let printed = serde_json::to_value(&response).expect("re-serialise");+ assert_eq!(+ printed["skipped"][0]["target_path"], "_pending/auto-improve/telemetry.md",+ "--json dropped the skipped proposals: {printed}"+ );+ }++ #[test]+ fn a_collision_explains_the_empty_proposals_line() {+ let response: AutoImproveReportStageResponse =+ serde_json::from_value(wire(colliding())).expect("server body parses");+ assert!(+ response.proposal_ids.is_empty(),+ "fixture must be the single-proposal collision case"+ );+ let human = render_stage_human(&response, "proj");+ assert!(+ human.contains("_pending/auto-improve/telemetry.md"),+ "{human}"+ );+ assert!(human.contains("already pending review"), "{human}");+ }++ #[test]+ fn a_clean_run_prints_no_skipped_section() {+ let response: AutoImproveReportStageResponse =+ serde_json::from_value(wire(serde_json::json!([]))).expect("server body parses");+ assert!(!render_stage_human(&response, "proj").contains("Skipped"));+ }++ #[test]+ fn a_server_without_the_field_still_parses() {+ let mut body = wire(serde_json::json!([]));+ body.as_object_mut().unwrap().remove("skipped");+ let response: AutoImproveReportStageResponse =+ serde_json::from_value(body).expect("older server body");+ assert!(response.skipped.is_empty());+ }+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 320481ec..0866f176 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -285,6 +285,27 @@ pub(crate) fn resolve_project_name(config: &Config, explicit: Option<&str>) -> R))}+/// Human-readable lines for the proposals the server refused to stage.+///+/// Empty when nothing was skipped, so a clean run prints nothing extra. Every+/// staging command shares this: a skipped proposal is otherwise+/// indistinguishable from one the reviewer never produced — the run reports+/// success either way, only with one proposal fewer — and the operator has no+/// way to learn that a paid review result was dropped.+pub(crate) fn skipped_proposal_lines(skipped: &[ai_memory_store::SkippedProposal]) -> Vec<String> {+ if skipped.is_empty() {+ return Vec::new();+ }+ let mut lines = Vec::with_capacity(skipped.len() + 1);+ lines.push(format!("Skipped {} proposal(s):", skipped.len()));+ lines.extend(+ skipped+ .iter()+ .map(|s| format!(" - {}: {}", s.target_path, s.reason)),+ );+ lines+}+#[cfg(test)]mod tests {use super::*;@@ -313,6 +334,27 @@ mod tests {assert_eq!(resolve_project_name(&config, None).unwrap(), "my-project");}+ #[test]+ fn skipped_proposal_lines_are_empty_on_a_clean_run() {+ assert!(skipped_proposal_lines(&[]).is_empty());+ }++ #[test]+ fn skipped_proposal_lines_name_the_path_and_the_reason() {+ let lines = skipped_proposal_lines(&[ai_memory_store::SkippedProposal {+ target_path: "procedures/release.md".into(),+ reason: "a proposal is already pending review for this path".into(),+ }]);+ assert_eq!(lines.len(), 2, "{lines:?}");+ assert!(lines[0].contains('1'), "{lines:?}");+ assert!(lines[1].contains("procedures/release.md"), "{lines:?}");+ assert!(+ lines[1].contains("already pending review"),+ "the reason has to travel with the path, or the operator only \+ learns that something vanished: {lines:?}"+ );+ }+/// Build a config whose scope resolution walks up from `cwd`, and drop a/// marker there when `marker` is given.fn config_at(dir: &std::path::Path, marker: Option<&str>) -> Config {diff --git a/crates/ai-memory-consolidate/Cargo.toml b/crates/ai-memory-consolidate/Cargo.tomlindex dccb2259..190413f3 100644--- a/crates/ai-memory-consolidate/Cargo.toml+++ b/crates/ai-memory-consolidate/Cargo.toml@@ -28,6 +28,7 @@ jiff.workspace = trueasync-trait.workspace = truetempfile.workspace = truerusqlite.workspace = true+tracing-subscriber.workspace = true[lints]workspace = truediff --git a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs b/crates/ai-memory-consolidate/src/auto_improve_schedule.rsindex dcf3590c..8ea60f89 100644--- a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs+++ b/crates/ai-memory-consolidate/src/auto_improve_schedule.rs@@ -19,7 +19,7 @@ use ai_memory_core::{ActorContext, PagePath, ProjectId, SessionId, WorkspaceId};use ai_memory_llm::LlmProvider;use ai_memory_store::{ApproveAutoImproveProposalResult, AutoImproveProposalOperation, NewAutoImproveProposal,- ReaderPool, StageAutoImproveRun, WriterHandle,+ ReaderPool, SkippedProposal, StageAutoImproveRun, WriterHandle,};use ai_memory_wiki::Wiki;use anyhow::Result;@@ -82,6 +82,12 @@ struct ScheduledAutoImproveOutcome {approved: usize,pending: usize,conflicts: usize,+ /// Proposals the store declined to stage (something is already pending for+ /// the same target). This is the unattended path: nobody reads a response,+ /// so a drop that does not reach the log reaches nobody at all — a run that+ /// lost its Nth proposal would otherwise be indistinguishable from a clean+ /// run of N-1.+ skipped: Vec<SkippedProposal>,}/// Aggregate counters for one scheduler tick across every scope.@@ -222,8 +228,23 @@ pub async fn run_auto_improve_scheduler_tick(approved = run.approved,pending = run.pending,conflicts = run.conflicts,+ skipped = run.skipped.len(),"scheduled auto-improve completed");+ // The count above keeps every completed run comparable;+ // this says WHICH proposal was lost and why, so the+ // operator can act on it without querying the store.+ for skipped in &run.skipped {+ tracing::warn!(+ workspace = %scope.workspace_name,+ project = %scope.project_name,+ session_id = %candidate.session_id,+ run_id = %run.run_id,+ target_path = %skipped.target_path,+ reason = %skipped.reason,+ "scheduled auto-improve proposal was not staged"+ );+ }}Err(e) => {outcome.errors += 1;@@ -299,6 +320,15 @@ async fn run_scheduled_auto_improve(..ActorContext::default()},proposals,+ // The scheduler stands in for nobody: an unattended run has no+ // caller to attribute, so it stages into the unattributed bucket of+ // the one-pending-per-target rule (V42). On a single-operator+ // server the interactive doors land in that same bucket too+ // (`owner_stamp` reports nobody unless the deployment distinguishes+ // operators) — bucketing either side differently would leave two+ // proposals pending for one page, the exact collision V42 promises+ // cannot happen.+ staged_by_actor_user: None,}).await?;@@ -345,6 +375,7 @@ async fn run_scheduled_auto_improve(approved,pending,conflicts,+ skipped: staged.skipped,})}@@ -408,11 +439,14 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {#[cfg(test)]mod tests {use super::*;- use ai_memory_core::{AgentKind, NewSession};+ use ai_memory_core::{+ AgentKind, NewObservation, NewSession, ObservationKind, Sanitized, Sanitizer,+ };use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult};use ai_memory_store::Store;use std::future::Future;use std::pin::Pin;+ use std::sync::Mutex;use tempfile::TempDir;struct PanicLlm;@@ -546,4 +580,257 @@ mod tests {);}}++ /// Proposes exactly one page, so a pre-existing pending proposal for that+ /// same page is guaranteed to collide.+ struct OneProposalLlm;++ impl LlmProvider for OneProposalLlm {+ fn name(&self) -> &'static str {+ "fake"+ }++ fn model(&self) -> &str {+ "fake-model"+ }++ fn complete<'life0, 'async_trait>(+ &'life0 self,+ _request: ChatRequest,+ ) -> Pin<Box<dyn Future<Output = LlmResult<ChatResponse>> + Send + 'async_trait>>+ where+ 'life0: 'async_trait,+ Self: 'async_trait,+ {+ Box::pin(async move {+ Ok(ChatResponse {+ text: "unused".into(),+ usage: None,+ model: "fake-model".into(),+ })+ })+ }++ fn complete_structured_raw<'life0, 'async_trait>(+ &'life0 self,+ _request: ChatRequest,+ _schema: serde_json::Value,+ ) -> Pin<Box<dyn Future<Output = LlmResult<serde_json::Value>> + Send + 'async_trait>>+ where+ 'life0: 'async_trait,+ Self: 'async_trait,+ {+ Box::pin(async move {+ Ok(serde_json::json!({+ "summary": "found one durable procedure",+ "proposals": [{+ "operation": "create_or_update",+ "path": COLLIDING_PATH,+ "title": "Release Procedure",+ "kind": "procedure",+ "confidence": 0.91,+ "rationale": "The session repeated a release workflow with verification.",+ "evidence": [{"page": "sessions/test.md", "quote": "run the full gate before release"}],+ "body_markdown": "# Release Procedure\n\nRun the full gate before release."+ }],+ "rejected_candidates": []+ }))+ })+ }+ }++ const COLLIDING_PATH: &str = "procedures/release.md";++ #[derive(Clone, Default)]+ struct CapturedLogs(Arc<Mutex<Vec<u8>>>);++ struct CapturedLogWriter(Arc<Mutex<Vec<u8>>>);++ impl std::io::Write for CapturedLogWriter {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(buf);+ Ok(buf.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLogs {+ type Writer = CapturedLogWriter;++ fn make_writer(&'a self) -> Self::Writer {+ CapturedLogWriter(Arc::clone(&self.0))+ }+ }++ async fn seed_reviewable_session(store: &Store, ws: WorkspaceId, proj: ProjectId) -> SessionId {+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ for i in 0..3 {+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: if i == 0 {+ ObservationKind::SessionStart+ } else {+ ObservationKind::UserPrompt+ },+ extension: None,+ source_event: None,+ title: format!("event {i}"),+ body: "run the full gate before release".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ }+ store.writer.end_session(session_id, None).await.unwrap();+ session_id+ }++ /// Stage a pending proposal for `COLLIDING_PATH` in the same unattributed+ /// bucket the scheduler stages into, so the scheduler's own proposal hits+ /// the one-pending-per-target rule.+ async fn stage_blocking_proposal(store: &Store, ws: WorkspaceId, proj: ProjectId) {+ let staged = store+ .writer+ .stage_auto_improve_run(StageAutoImproveRun {+ workspace_id: ws,+ project_id: proj,+ session_id: None,+ provider: None,+ model: None,+ summary: Some("pre-existing pending proposal".into()),+ warnings_json: serde_json::json!([]),+ rejected_candidates_json: serde_json::json!([]),+ config_json: serde_json::json!({}),+ proposal_actor: ActorContext::default(),+ staged_by_actor_user: None,+ proposals: vec![NewAutoImproveProposal {+ operation: AutoImproveProposalOperation::Create,+ target_path: PagePath::new(COLLIDING_PATH.to_string()).unwrap(),+ kind: "procedure".into(),+ title: "Release Procedure".into(),+ confidence: 0.9,+ rationale: "already awaiting review".into(),+ evidence_json: serde_json::json!([]),+ body_markdown: "# Release Procedure\n".into(),+ artifact_sha256: None,+ edit_mode: None,+ patch_json: None,+ expected_base_body_sha256: None,+ }],+ })+ .await+ .unwrap();+ assert_eq!(staged.proposal_ids.len(), 1, "fixture must actually stage");+ }++ /// The unattended path has no response for anyone to read, so a proposal the+ /// store declines has exactly two places left to surface: the run outcome+ /// and the log. Without both, a run that lost its only proposal to a+ /// collision is byte-identical to a run that produced nothing.+ #[tokio::test]+ async fn a_scheduled_run_reports_a_collision_in_its_outcome_and_its_log() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "proj", None)+ .await+ .unwrap();+ let session_id = seed_reviewable_session(&store, ws, proj).await;+ stage_blocking_proposal(&store, ws, proj).await;++ let settings = ScheduledAutoImproveSettings {+ review: AutoImproveReviewConfig {+ // The fixture session is short and small; the preflight gates+ // are not what this test is about.+ min_observations: 3,+ min_session_duration_secs: 0,+ ..AutoImproveReviewConfig::default()+ },+ require_approval: true,+ min_session_age_secs: 0,+ max_sessions_per_tick: 10,+ };+ let llm: Arc<dyn LlmProvider> = Arc::new(OneProposalLlm);+ let ctx = ScheduledAutoImproveContext {+ reader: &store.reader,+ writer: &store.writer,+ wiki: &wiki,+ llm: &llm,+ workspace_id: ws,+ project_id: proj,+ settings: &settings,+ };++ let run = run_scheduled_auto_improve(&ctx, session_id).await.unwrap();+ assert_eq!(run.proposals, 0, "the only proposal collided");+ assert_eq!(+ run.skipped.len(),+ 1,+ "the outcome must carry the drop, not just the surviving count"+ );+ assert_eq!(run.skipped[0].target_path, COLLIDING_PATH);++ // `#[tokio::test]` runs a current-thread runtime, so the thread-local+ // default subscriber installed here stays in force across the awaits.+ let logs = CapturedLogs::default();+ let subscriber = tracing_subscriber::fmt()+ .with_max_level(tracing::Level::INFO)+ .with_writer(logs.clone())+ .without_time()+ // ANSI escapes would split `skipped=1` across colour codes.+ .with_ansi(false)+ .finish();+ let tick_session = seed_reviewable_session(&store, ws, proj).await;+ let guard = tracing::subscriber::set_default(subscriber);+ let tick =+ run_auto_improve_scheduler_tick(&store.reader, &store.writer, &wiki, &llm, &settings)+ .await+ .unwrap();+ drop(guard);+ assert_eq!(tick.errors, 0);+ assert!(+ tick.reviewed >= 1,+ "the new session must have been reviewed"+ );+ assert_ne!(tick_session, session_id);++ let captured = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap();+ assert!(+ captured.contains("skipped=1"),+ "the completion line must count the drop: {captured}"+ );+ assert!(+ captured.contains("scheduled auto-improve proposal was not staged")+ && captured.contains(COLLIDING_PATH),+ "the log must name the dropped target: {captured}"+ );+ }}diff --git a/crates/ai-memory-consolidate/src/curator.rs b/crates/ai-memory-consolidate/src/curator.rsindex 990e3896..3c60e4bd 100644--- a/crates/ai-memory-consolidate/src/curator.rs+++ b/crates/ai-memory-consolidate/src/curator.rs@@ -3,10 +3,12 @@use std::collections::HashMap;use ai_memory_core::{ProjectId, Tier, WorkspaceId};-use ai_memory_store::{DecayParams, ReaderPool, retention_score};+use ai_memory_store::{DecayParams, ReaderPool, retention_score_with_breadth};use jiff::Timestamp;use serde::{Deserialize, Serialize};+use crate::sweep::access_breadth_for_scoring;+const US_PER_DAY: f64 = 86_400_000_000.0;/// Parameters for one curator report run.@@ -86,6 +88,12 @@ pub async fn run_curator_report(let mut findings = Vec::new();let candidates = reader.decay_candidates(workspace_id, project_id).await?;+ // `cold_episodic` is a prediction of what the forget sweep would evict, so+ // it has to score pages the way the sweep scores them. Scoring blind to+ // breadth reported pages as cold that the sweep, with `breadth_weight > 0`,+ // will never touch.+ let breadth =+ access_breadth_for_scoring(reader, workspace_id, project_id, ¶ms.decay_params).await?;let mut cold = Vec::new();for c in &candidates {if c.tier != Tier::Episodic || c.pinned || frontmatter_pinned(&c.frontmatter_json) {@@ -93,12 +101,13 @@ pub async fn run_curator_report(}let page_age_days = age_days(now_us, c.updated_at_us);let days_since_access = c.last_accessed_at_us.map(|us| age_days(now_us, us));- let score = retention_score(+ let score = retention_score_with_breadth(¶ms.decay_params,page_age_days,c.access_count,days_since_access,c.salience,+ breadth.get(&c.id).copied().unwrap_or(0),);if score < params.decay_params.cold_threshold {cold.push(CuratorFinding {diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rsindex 0c1a0160..7e6b6f69 100644--- a/crates/ai-memory-consolidate/src/sweep.rs+++ b/crates/ai-memory-consolidate/src/sweep.rs@@ -1,7 +1,7 @@//! M8 forget sweep — episodic-only retention pass.//!-//! Walks the `is_latest = 1` pages for a project, computes the-//! retention score for each via [`ai_memory_store::retention_score`],+//! Walks the `is_latest = 1` pages for a project, computes the retention score+//! for each via [`ai_memory_store::retention_score_with_breadth`],//! and soft-deletes those below threshold. Semantic / procedural ///! working tiers are skipped (M8 policy: semantic compounds, only//! episodic decays). Pinned pages (schema flag OR `pinned: true` in@@ -18,8 +18,12 @@//! M7 supersession rows are safe: they have `supersedes IS NOT NULL`//! and therefore never match the hard-delete predicate.+use std::collections::HashMap;+use ai_memory_core::{PageId, ProjectId, Tier, WorkspaceId};-use ai_memory_store::{DecayCandidate, DecayParams, ReaderPool, WriterHandle, retention_score};+use ai_memory_store::{+ DecayCandidate, DecayParams, ReaderPool, WriterHandle, retention_score_with_breadth,+};use ai_memory_wiki::Wiki;use jiff::Timestamp;use serde::Serialize;@@ -108,6 +112,7 @@ pub async fn run_sweep(dry_run: bool,) -> Result<SweepReport, SweepError> {let candidates = reader.decay_candidates(workspace_id, project_id).await?;+ let breadth = access_breadth_for_scoring(reader, workspace_id, project_id, params).await?;let now_us = Timestamp::now().as_microsecond();let mut evicted = Vec::new();@@ -133,12 +138,13 @@ pub async fn run_sweep(}let age_days = elapsed_days(now_us, c.updated_at_us);let days_since_access = c.last_accessed_at_us.map(|us| elapsed_days(now_us, us));- let score = retention_score(+ let score = retention_score_with_breadth(params,age_days,c.access_count,days_since_access,c.salience,+ breadth.get(&c.id).copied().unwrap_or(0),);if score < params.cold_threshold {evicted.push(EvictedPage {@@ -201,6 +207,32 @@ pub async fn run_sweep(})}+/// Distinct-actor counts keyed by page, for feeding+/// [`retention_score_with_breadth`].+///+/// One grouped query for the whole candidate set, not one per page — and none+/// at all while the breadth term is off, which is the default: the score is then+/// identical whatever the breakdown says, so a deployment that never enables it+/// never pays for reading it.+///+/// Shared with the curator rather than duplicated there: the curator's+/// `cold_episodic` verdict is a prediction of what the sweep will evict, so the+/// two must read the same input. A second lookup would be a second chance to+/// drift.+pub(crate) async fn access_breadth_for_scoring(+ reader: &ReaderPool,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ params: &DecayParams,+) -> ai_memory_store::StoreResult<HashMap<PageId, u32>> {+ if params.breadth_weight == 0.0 {+ return Ok(HashMap::new());+ }+ reader+ .access_breadth_for_project(workspace_id, project_id)+ .await+}+fn elapsed_days(now_us: i64, then_us: i64) -> f64 {#[allow(clippy::cast_precision_loss)]let raw = (now_us - then_us) as f64 / US_PER_DAY;diff --git a/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs b/crates/ai-memory-consolidate/tests/access_breadth_sweep.rsnew file mode 100644index 00000000..dbf8cd55--- /dev/null+++ b/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs@@ -0,0 +1,292 @@+//! The breadth term, end to end, for both readers of the retention formula.+//!+//! `pages.access_count` cannot tell "50 reads by one person" from "one read by+//! each of 50 people", although only the second says a page is load-bearing for+//! a team. `page_access` records that breakdown; these tests pin that the sweep+//! actually READS it — and that at the default `breadth_weight = 0.0` the+//! recorded breakdown moves neither the scores nor the eviction decisions.+//!+//! The curator is held to the same formula: its `cold_episodic` finding is a+//! prediction of what the sweep will evict, so a page the sweep keeps must not+//! be reported cold.++use ai_memory_consolidate::{CuratorParams, CuratorReport, run_curator_report, run_sweep};+use ai_memory_core::{IdentityKey, NewPage, PageId, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_store::{DecayParams, Store, WriterHandle, retention_score};+use rusqlite::params;+use tempfile::TempDir;++const US_PER_DAY: i64 = 86_400_000_000;+/// Old enough and cold enough that the pair falls just under the default+/// `cold_threshold` — so any breadth bonus is what decides their fate.+const AGE_DAYS: i64 = 100;+const ACCESS_COUNT: u32 = 50;++/// Two otherwise identical episodic pages: `team.md` reinforced by five distinct+/// operators, `solo.md` by one. Same age, same total hit count, same last-access+/// timestamp, so the ONLY thing that can separate them is the breadth term.+async fn seed(store: &Store) -> (WorkspaceId, ProjectId) {+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .expect("ws");+ let proj = store+ .writer+ .get_or_create_project(ws, "breadth".to_string(), None)+ .await+ .expect("proj");++ let team = write_page(&store.writer, ws, proj, "sessions/team.md").await;+ let solo = write_page(&store.writer, ws, proj, "sessions/solo.md").await;++ // Actors are recorded under their qualified identity storage key, the same+ // TEXT `IdentityKey::storage_key()` produces on the read path.+ for actor in ["alice", "bob", "carol", "dave", "erin"] {+ store+ .writer+ .bump_access(+ vec![team],+ Some(IdentityKey::User(actor.into()).storage_key()),+ )+ .await+ .expect("bump team");+ }+ store+ .writer+ .bump_access(+ vec![solo],+ Some(IdentityKey::User("alice".into()).storage_key()),+ )+ .await+ .expect("bump solo");++ // Time-travel afterwards so both pages end up with byte-identical counters:+ // `updated_at == last_accessed_at` also makes `days_since_access` equal to+ // the sweep's reported `age_days`, which is what lets the assertions below+ // recompute the historical score exactly.+ let now_us = jiff::Timestamp::now().as_microsecond();+ let then_us = now_us - AGE_DAYS * US_PER_DAY;+ let conn = rusqlite::Connection::open(store.db_path()).expect("aux conn");+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();+ for id in [team, solo] {+ conn.execute(+ "UPDATE pages \+ SET created_at = ?1, updated_at = ?1, access_count = ?2, last_accessed_at = ?1 \+ WHERE id = ?3",+ params![then_us, i64::from(ACCESS_COUNT), id.as_bytes()],+ )+ .expect("backdate");+ }+ (ws, proj)+}++async fn write_page(writer: &WriterHandle, ws: WorkspaceId, proj: ProjectId, path: &str) -> PageId {+ writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path.to_string()).expect("path"),+ title: path.into(),+ body: "retention fixture".into(),+ tier: Tier::Episodic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ })+ .await+ .expect("upsert")+}++/// The no-break proof: with the shipped defaults the sweep must score a page+/// read by five operators exactly as the pre-breadth formula scored it, and+/// evict it just the same. Recording `page_access` rows must not move a single+/// eviction decision on an existing database.+#[tokio::test]+async fn default_weight_scores_identically_however_many_operators_read_the_page() {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let (ws, proj) = seed(&store).await;++ let params = DecayParams::default();+ assert_eq!(params.breadth_weight, 0.0, "the shipped default");+ let report = run_sweep(&store.reader, &store.writer, None, ws, proj, ¶ms, true)+ .await+ .expect("sweep");++ let mut evicted: Vec<_> = report.evicted.iter().collect();+ evicted.sort_by(|a, b| a.path.cmp(&b.path));+ assert_eq!(+ evicted.iter().map(|e| e.path.as_str()).collect::<Vec<_>>(),+ vec!["sessions/solo.md", "sessions/team.md"],+ "breadth must not save a page at the default weight",+ );+ for e in &evicted {+ assert_eq!(e.access_count, ACCESS_COUNT);+ assert_eq!(+ e.retention,+ retention_score(¶ms, e.age_days, e.access_count, Some(e.age_days), None),+ "{} scored differently from the pre-breadth formula",+ e.path,+ );+ }+ assert_eq!(+ evicted[0].retention, evicted[1].retention,+ "five readers and one reader must be indistinguishable at weight 0.0",+ );+}++/// And once an operator deliberately raises the weight, the breadth actually+/// reaches the score — which is the whole point of recording it.+#[tokio::test]+async fn a_page_many_operators_read_outlives_one_read_as_often_by_a_single_operator() {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let (ws, proj) = seed(&store).await;++ let params = DecayParams {+ breadth_weight: 1.5,+ ..DecayParams::default()+ };+ let report = run_sweep(&store.reader, &store.writer, None, ws, proj, ¶ms, true)+ .await+ .expect("sweep");++ assert_eq!(+ report+ .evicted+ .iter()+ .map(|e| e.path.as_str())+ .collect::<Vec<_>>(),+ vec!["sessions/solo.md"],+ "the team-read page should have been carried over the threshold",+ );+}++/// `(path, score, age_days)` for every `cold_episodic` finding, sorted by path.+fn cold_findings(report: &CuratorReport) -> Vec<(String, f64, f64)> {+ let mut rows: Vec<_> = report+ .findings+ .iter()+ .filter(|f| f.kind == "cold_episodic")+ .map(|f| {+ let detail = f+ .detail+ .as_ref()+ .expect("cold findings carry a detail blob");+ (+ f.pages+ .first()+ .expect("cold finding names its page")+ .clone(),+ detail["score"].as_f64().expect("score"),+ detail["age_days"].as_f64().expect("age_days"),+ )+ })+ .collect();+ rows.sort_by(|a, b| a.0.cmp(&b.0));+ rows+}++async fn curate(+ store: &Store,+ ws: WorkspaceId,+ proj: ProjectId,+ decay: DecayParams,+) -> CuratorReport {+ run_curator_report(+ &store.reader,+ ws,+ proj,+ "default",+ "breadth",+ CuratorParams {+ decay_params: decay,+ ..CuratorParams::default()+ },+ )+ .await+ .expect("curator")+}++/// The no-break proof for the curator: at the shipped default the recorded+/// `page_access` breakdown must not move a single reported score.+///+/// This one does not discriminate the fix — at `breadth_weight = 0.0` the+/// breadth-aware formula is the historical formula by construction — it exists+/// so a later change to the breadth term cannot silently alter default output.+#[tokio::test]+async fn curator_scores_match_the_pre_breadth_formula_at_the_default_weight() {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let (ws, proj) = seed(&store).await;++ let params = DecayParams::default();+ assert_eq!(params.breadth_weight, 0.0, "the shipped default");+ let report = curate(&store, ws, proj, params).await;++ let cold = cold_findings(&report);+ assert_eq!(+ cold.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),+ vec!["sessions/solo.md", "sessions/team.md"],+ "breadth must not spare a page at the default weight",+ );+ for (path, score, age_days) in &cold {+ assert_eq!(+ *score,+ retention_score(¶ms, *age_days, ACCESS_COUNT, Some(*age_days), None),+ "{path} scored differently from the pre-breadth formula",+ );+ }+ assert_eq!(+ cold[0].1, cold[1].1,+ "five readers and one reader must be indistinguishable at weight 0.0",+ );+}++/// The discriminating one. `cold_episodic` is a prediction of an eviction, so a+/// page the sweep carries over the threshold must not be reported cold: a+/// breadth-blind curator hands the operator a page that will never be evicted,+/// on a run of the very same `[decay]` parameters.+#[tokio::test]+async fn the_curator_reports_cold_exactly_when_the_sweep_would_evict() {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let (ws, proj) = seed(&store).await;++ let params = DecayParams {+ breadth_weight: 1.5,+ ..DecayParams::default()+ };+ let sweep = run_sweep(&store.reader, &store.writer, None, ws, proj, ¶ms, true)+ .await+ .expect("sweep");+ let cold = cold_findings(&curate(&store, ws, proj, params).await);++ let mut evicted: Vec<&str> = sweep.evicted.iter().map(|e| e.path.as_str()).collect();+ evicted.sort_unstable();+ assert_eq!(+ evicted,+ vec!["sessions/solo.md"],+ "fixture must have the team page surviving, or there is nothing to disagree about",+ );+ assert_eq!(+ cold.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),+ evicted,+ "the curator flagged a page the sweep will never evict",+ );++ // Same page, same parameters, same score — the two must be reading the same+ // distinct-actor input, not merely reaching the same verdict by luck.+ let swept = &sweep.evicted[0];+ assert!(+ (cold[0].1 - swept.retention).abs() < 1e-6,+ "curator scored {} at {}, sweep at {}",+ cold[0].0,+ cold[0].1,+ swept.retention,+ );+}diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 281240a5..8aeac4e5 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -57,8 +57,8 @@ use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, ProviderHealthSnapshouse ai_memory_store::{ApproveAutoImproveProposalResult, AutoImproveProposalOperation, AutoImproveProposalStatus,DecayParams, NewAutoImproveProposal, ReaderPool, RejectAutoImproveProposal,- ScopeResolutionError, StageAutoImproveRun, StoreError, WriterHandle, create_explicit_scope,- f32_vec_to_bytes, lookup_existing_scope, lookup_existing_workspace,+ ScopeResolutionError, SkippedProposal, StageAutoImproveRun, StoreError, WriterHandle,+ create_explicit_scope, f32_vec_to_bytes, lookup_existing_scope, lookup_existing_workspace,};use ai_memory_wiki::{AdmissionContext, AdmissionOp, Markdown, Wiki, WikiError, WritePageRequest};use axum::Json;@@ -302,6 +302,10 @@ struct AutoImproveStageResponse {warnings: Vec<String>,rejected_candidates_count: usize,proposals: Vec<AutoImproveProposalOutcome>,+ /// Proposals the reviewer produced but the store did not stage, with the+ /// reason. Always present (empty on a clean run) so a consumer can tell+ /// "nothing was dropped" from "this build does not report drops".+ skipped: Vec<SkippedProposal>,}#[derive(Debug, Serialize)]@@ -337,6 +341,9 @@ struct AutoImproveTelemetryReportStageResponse {run_id: String,proposal_ids: Vec<String>,sidecar_paths: Vec<String>,+ /// Same reason as [`AutoImproveStageResponse::skipped`]: a single-proposal+ /// run that collides otherwise returns an empty `proposal_ids` and no clue.+ skipped: Vec<SkippedProposal>,report: AutoImproveTelemetryReport,}@@ -365,6 +372,9 @@ struct CuratorStageResponse {run_id: String,proposal_ids: Vec<String>,sidecar_paths: Vec<String>,+ /// Same reason as [`AutoImproveStageResponse::skipped`]: a single-proposal+ /// run that collides otherwise returns an empty `proposal_ids` and no clue.+ skipped: Vec<SkippedProposal>,report: CuratorReport,}@@ -1456,10 +1466,47 @@ async fn handle_auto_improve(run_auto_improve_review(&state.reader, &*llm, ws, proj, req.session_id, cfg.clone()).await.map_err(auto_improve_error_response)?;+ // Whose suggestion this is. It scopes the one-pending-per-target rule+ // (V42), and is taken from the authenticated actor's qualified identity+ // key rather than a `users` row, because most identified operators on a+ // shared server are named by an authenticating proxy and never get one.+ //+ // Only where operators are actually told apart, though: on a+ // single-operator server this call would otherwise stage into bucket+ // `user:<root_username>` while the scheduler and the report handlers stage+ // into the unattributed one, leaving two proposals pending for the same+ // page — the collision V42 promises cannot happen.+ //+ // Both halves go through the shared accessors — `identity_key` for "which+ // human is this", `owner_stamp` for "does this deployment name them" —+ // rather than re-deriving either here. Its `memory_auto_improve` sibling+ // stages into the same V42 bucket, and a bucket computed two ways is a+ // bucket that eventually disagrees with itself.+ let staged_by_actor_user = ai_memory_core::owner_stamp(+ actor_ext+ .as_ref()+ .and_then(|axum::Extension(actor)| actor.identity_key())+ .as_ref(),+ state+ .reader+ .distinguishes_operators(state.trusted_proxy_identity)+ .await+ .map_err(|e| internal_err(e.to_string()))?,+ );let proposals = auto_improve_new_proposals(&state, ws, proj, &report).await?;- let staged =- stage_auto_improve_report(&state, ws, proj, req.session_id, &cfg, &report, proposals)- .await?;+ let staged = stage_auto_improve_report(+ &state,+ AutoImproveStagingScope {+ ws,+ proj,+ session_id: req.session_id,+ cfg: &cfg,+ staged_by_actor_user,+ },+ &report,+ proposals,+ )+ .await?;let actor = actor_ext.map(|axum::Extension(actor)| actor).unwrap_or_else(ai_memory_core::ActorContext::anonymous);@@ -1498,6 +1545,10 @@ async fn handle_auto_improve(warnings: report.warnings,rejected_candidates_count: report.rejected_candidates.len(),proposals: outcomes,+ // Store-level collisions the reviewer's run never staged.+ // Dropped silently, a run reporting N-1 proposals has nothing+ // saying the Nth ever existed.+ skipped: staged.skipped,}).unwrap_or_else(|_| serde_json::json!({})),),@@ -1628,17 +1679,37 @@ struct StagedAutoImproveData {run_id: ai_memory_core::AutoImproveRunId,proposal_ids: Vec<AutoImproveProposalId>,sidecar_paths: Vec<String>,+ /// Proposals the store refused to stage. Dropping these here would hand the+ /// operator a run reporting N-1 proposals with nothing saying the Nth+ /// existed — the silent drop the per-proposal skip was meant to end.+ skipped: Vec<SkippedProposal>,}-async fn stage_auto_improve_report(- state: &AdminState,+/// Everything `stage_auto_improve_report` needs about WHO and WHERE, bundled so+/// the helper keeps a readable arity.+struct AutoImproveStagingScope<'a> {ws: WorkspaceId,proj: ProjectId,session_id: SessionId,- cfg: &AutoImproveReviewConfig,+ cfg: &'a AutoImproveReviewConfig,+ /// Operator that staged the run, as the qualified identity storage key;+ /// also scopes the one-pending-per-target rule.+ staged_by_actor_user: Option<String>,+}++async fn stage_auto_improve_report(+ state: &AdminState,+ scope: AutoImproveStagingScope<'_>,report: &ai_memory_consolidate::AutoImproveReport,proposals: Vec<NewAutoImproveProposal>,) -> Result<StagedAutoImproveData, (StatusCode, Json<serde_json::Value>)> {+ let AutoImproveStagingScope {+ ws,+ proj,+ session_id,+ cfg,+ staged_by_actor_user,+ } = scope;let staged = state.writer.stage_auto_improve_run(StageAutoImproveRun {@@ -1672,6 +1743,9 @@ async fn stage_auto_improve_report("max_procedure_page_tokens": cfg.max_procedure_page_tokens,"eval": cfg.eval,}),+ // Whose suggestion this is; also scopes the one-pending-per-target+ // rule (V42) so operators stop blocking each other.+ staged_by_actor_user,proposal_actor: ai_memory_core::ActorContext {agent: Some(cfg.proposal_actor.clone()),..ai_memory_core::ActorContext::default()@@ -1685,6 +1759,7 @@ async fn stage_auto_improve_report(run_id: staged.run_id,proposal_ids: staged.proposal_ids,sidecar_paths,+ skipped: staged.skipped,})}@@ -1789,6 +1864,12 @@ async fn handle_auto_improve_report("auto_improve_report": true,"params": params,}),+ // The report describes the project, not the caller, and its+ // target page is a single canonical path. Staging it into the+ // unattributed bucket of the one-pending-per-target rule (V42)+ // keeps "one pending report per project" in both modes, exactly+ // as before the rule learned about authors.+ staged_by_actor_user: None,proposal_actor: ai_memory_core::ActorContext {agent: Some("auto_improve_report".into()),..ai_memory_core::ActorContext::default()@@ -1827,6 +1908,7 @@ async fn handle_auto_improve_report(.map(ToString::to_string).collect(),sidecar_paths,+ skipped: staged.skipped,report,}).unwrap_or_else(|_| serde_json::json!({})),@@ -1909,6 +1991,10 @@ async fn handle_curator("curator": true,"params": params,}),+ // Same reasoning as the telemetry report above: a project-scoped+ // report on one canonical path, so it shares the unattributed+ // bucket of the one-pending-per-target rule (V42).+ staged_by_actor_user: None,proposal_actor: ai_memory_core::ActorContext {agent: Some("curator".into()),..ai_memory_core::ActorContext::default()@@ -1945,6 +2031,7 @@ async fn handle_curator(.map(ToString::to_string).collect(),sidecar_paths,+ skipped: staged.skipped,report,}).unwrap_or_else(|_| serde_json::json!({})),@@ -5436,6 +5523,7 @@ mod tests {warnings_json: serde_json::json!([]),rejected_candidates_json: serde_json::json!([]),config_json: serde_json::json!({"mode":"stage"}),+ staged_by_actor_user: None,proposal_actor: ai_memory_core::ActorContext {agent: Some("auto_improve".into()),..ai_memory_core::ActorContext::default()@@ -5779,6 +5867,384 @@ mod tests {);}+ /// The V42 staging bucket is keyed on+ /// [`ai_memory_core::ActorContext::identity_key`] through+ /// [`ai_memory_core::owner_stamp`], not on `actor.user`, so an operator an+ /// ingress named with the OIDC subject claim alone still lands in their own+ /// bucket (`sub:<subject>`) rather than the unattributed one their+ /// colleagues share.+ ///+ /// # This shape is a floor, not a live rung+ ///+ /// `AuthLevel::Root` beside an actor carrying only `sub` is not something+ /// `require_bearer` produces: the proxy overlay downgrades a caller it names+ /// with a subject alone to `AuthLevel::User` (it can never match+ /// `root_username`), and `require_root_for_multiuser_admin` then turns that+ /// caller away before this handler runs. It is pinned anyway because the+ /// `memory_auto_improve` MCP tool computes the SAME bucket for the same+ /// operator, and the two must not derive it differently — a bucket computed+ /// two ways is one that eventually disagrees with itself, and the V42+ /// one-pending-per-target promise is what breaks when it does.+ #[tokio::test]+ async fn auto_improve_buckets_a_sub_only_operator_by_identity_key() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();++ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("_slots/current-focus.md").unwrap(),+ frontmatter: serde_json::json!({"kind":"slot"}),+ body: "# Current Focus\n\nold focus".into(),+ tier: Tier::Working,+ pinned: false,+ title: Some("Current Focus".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "focus changed and durable lesson".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();++ // A trusted proxy is configured, so the deployment distinguishes its+ // operators even with no `users` rows — which is exactly the case where+ // reaching for `actor.user` sees nobody.+ let mut state =+ admin_state_for_store_with_llm(&tmp, &store, wiki, Some(Arc::new(FakeAutoImproveLlm)));+ state.trusted_proxy_identity = true;+ let router = admin_router(state);++ let mut req = Request::builder()+ .method("POST")+ .uri("/admin/auto-improve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({+ "workspace": "default",+ "project": "scratch",+ "session_id": session_id.to_string(),+ "min_observations": 1,+ "min_session_duration_secs": 0,+ "min_confidence": 0.75,+ "max_proposals_per_run": 5+ }))+ .unwrap(),+ ))+ .unwrap();+ req.extensions_mut().insert(ai_memory_core::ActorContext {+ sub: Some("oidc|subject-only-42".into()),+ ..ai_memory_core::ActorContext::anonymous()+ });+ req.extensions_mut().insert(ai_memory_core::AuthLevel::Root);++ let resp = router.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ // The bucket the contract stamps, built through the API rather than+ // hand-written, so this test follows the encoding if it ever moves.+ let expected_bucket =+ ai_memory_core::IdentityKey::Subject("oidc|subject-only-42".into()).storage_key();+ let staged = store+ .reader+ .list_auto_improve_proposals(ws, proj, None, 10)+ .await+ .unwrap();+ assert!(!staged.is_empty(), "the fake LLM proposes two pages");+ for proposal in &staged {+ let detail = store+ .reader+ .auto_improve_proposal_detail(ws, proj, proposal.id)+ .await+ .unwrap()+ .expect("staged proposal readable in its own scope");+ assert_eq!(+ detail.staged_by_actor_user.as_deref(),+ Some(expected_bucket.as_str()),+ "the subject claim is the operator, not `None`: {}",+ detail.summary.target_path.as_str()+ );+ }+ }++ /// The admin report must name the proposals the store refused to stage.+ /// Returning only the staged ids hands the operator a successful run of+ /// N-1 proposals with no trace of the Nth — the silent drop the+ /// per-proposal skip was introduced to end.+ #[tokio::test]+ async fn auto_improve_report_names_the_proposal_a_collision_skipped() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let (ws, proj, _pending) = stage_pending_write(+ &store,+ "default",+ "scratch",+ "notes/new-auto-improve.md",+ "# New Auto Improve Lesson\n\nstaged earlier",+ )+ .await;++ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("_slots/current-focus.md").unwrap(),+ frontmatter: serde_json::json!({"kind":"slot"}),+ body: "# Current Focus\n\nold focus".into(),+ tier: Tier::Working,+ pinned: false,+ title: Some("Current Focus".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "focus changed and durable lesson".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();++ let router = admin_router(admin_state_for_store_with_llm(+ &tmp,+ &store,+ wiki,+ Some(Arc::new(FakeAutoImproveLlm)),+ ));+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/auto-improve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({+ "workspace": "default",+ "project": "scratch",+ "session_id": session_id.to_string(),+ "min_observations": 1,+ "min_session_duration_secs": 0,+ "min_confidence": 0.75,+ "max_proposals_per_run": 5+ }))+ .unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(+ json["proposals"].as_array().unwrap().len(),+ 1,+ "the sibling proposal still stages",+ );+ let skipped = json["skipped"].as_array().expect("skipped array");+ assert_eq!(skipped.len(), 1, "the collided proposal must be reported");+ assert_eq!(skipped[0]["target_path"], "notes/new-auto-improve.md");+ assert!(+ skipped[0]["reason"]+ .as_str()+ .is_some_and(|r| !r.trim().is_empty()),+ "a skipped proposal must say why: {}",+ skipped[0]+ );+ }++ /// `[auth].root_username` alone does not make a server multi-operator: the+ /// scheduler and the report handlers stage unattributed, so bucketing this+ /// call by its actor would leave TWO pending proposals for one page on a+ /// single-operator server — the collision V42 promises cannot happen.+ #[tokio::test]+ async fn single_operator_admin_auto_improve_shares_the_unattributed_bucket() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let (ws, proj, _pending) = stage_pending_write(+ &store,+ "default",+ "scratch",+ "notes/new-auto-improve.md",+ "# New Auto Improve Lesson\n\nstaged earlier",+ )+ .await;++ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("_slots/current-focus.md").unwrap(),+ frontmatter: serde_json::json!({"kind":"slot"}),+ body: "# Current Focus\n\nold focus".into(),+ tier: Tier::Working,+ pinned: false,+ title: Some("Current Focus".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "focus changed and durable lesson".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();++ // The root actor `[auth].root_username` produces, as the auth+ // middleware would stamp it.+ let router = admin_router(admin_state_for_store_with_llm(+ &tmp,+ &store,+ wiki,+ Some(Arc::new(FakeAutoImproveLlm)),+ ))+ .layer(axum::middleware::from_fn(+ |mut req: Request<Body>, next: axum::middleware::Next| async move {+ req.extensions_mut().insert(ai_memory_core::ActorContext {+ user: Some("the-operator".into()),+ ..ai_memory_core::ActorContext::default()+ });+ next.run(req).await+ },+ ));+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/auto-improve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({+ "workspace": "default",+ "project": "scratch",+ "session_id": session_id.to_string(),+ "min_observations": 1,+ "min_session_duration_secs": 0,+ "min_confidence": 0.75,+ "max_proposals_per_run": 5+ }))+ .unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let skipped = json["skipped"].as_array().expect("skipped array");+ assert_eq!(+ skipped.len(),+ 1,+ "a named root operator must not open a second pending bucket for the same page"+ );+ assert_eq!(skipped[0]["target_path"], "notes/new-auto-improve.md");+ }+#[tokio::test]async fn auto_improve_admin_omitted_eval_inherits_server_defaults() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 0213d99e..f105511d 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -389,7 +389,12 @@ pub struct AiMemoryServer {/// repeated or overlapping queries from flooding the single writer/// actor with redundant reinforcement writes. Shared across `Clone`s/// so every request handler consults the same clock.- access_bump_seen: Arc<Mutex<HashMap<PageId, Instant>>>,+ ///+ /// Keyed by operator as well as page: with a page-only key one operator's+ /// read swallows everyone else's reinforcement for the whole window, so the+ /// counter measures "distinct minutes in which SOMEBODY read this",+ /// undercounting in proportion to team size.+ access_bump_seen: Arc<Mutex<AccessBumpSeen>>,/// True when a trusted authenticating proxy is configured to assert end-user/// identities (`[auth].actor_proxy_secret`).///@@ -1619,7 +1624,11 @@ impl AiMemoryServer {};let hits = hits.map_err(|e| McpError::internal_error(e.to_string(), None))?;let hits = self.rerank_hits(&args.query, hits, limit).await;- self.spawn_access_bump(hits.iter().map(|(h, _)| h.id).collect());+ let bump_actor = Self::bump_actor_from_parts(&parts);+ self.spawn_access_bump(+ hits.iter().map(|(h, _)| h.id).collect(),+ bump_actor.as_deref(),+ );// Raw-observation fallback when compiled-page search misses. Works// for a single resolved project (default / workspace+project) AND// for explicit `scopes` — the recommended scope-bleed mitigation —@@ -1697,7 +1706,10 @@ impl AiMemoryServer {).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;- self.spawn_access_bump(hits.iter().map(|(h, _)| h.id).collect());+ self.spawn_access_bump(+ hits.iter().map(|(h, _)| h.id).collect(),+ bump_actor.as_deref(),+ );hits.into_iter().map(|(hit, score_details)| QueryHit { hit, score_details }).collect()@@ -1776,7 +1788,10 @@ impl AiMemoryServer {.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());+ self.spawn_access_bump(+ hits.iter().map(|h| h.id).collect(),+ Self::bump_actor_from_parts(&parts).as_deref(),+ );ok_json(&MemoryRecentResponse {hits,global_hits: Vec::new(),@@ -2119,6 +2134,26 @@ impl AiMemoryServer {run_auto_improve_review(&self.reader, &**llm, ws, proj, session_id, cfg.clone()).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;+ // Whose suggestion this is; it also scopes the one-pending-per-target+ // rule (V42). Only meaningful where operators are actually told apart:+ // on a single-operator server the caller would otherwise stage into+ // bucket `user:<root_username>` while the scheduler and the report+ // handlers stage into the unattributed one, so two proposals could be+ // pending for the same page — the collision V42 promises cannot+ // happen. The schema stays able to express per-author; this rule+ // decides when that matters.+ //+ // Both halves go through the shared accessors — `identity_key` for+ // "which human is this", `owner_stamp` for "does this deployment name+ // them" — so this tool and its `/admin/auto-improve` sibling compute+ // the SAME bucket for the same operator; a bucket computed two ways+ // eventually disagrees with itself.+ let staged_by_actor_user = ai_memory_core::owner_stamp(+ request_actor.identity_key().as_ref(),+ self.deployment_distinguishes_operators()+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,+ );let mut proposals = Vec::with_capacity(report.proposals.len());for p in &report.proposals {let path = PagePath::new(p.path.clone()).map_err(|e| {@@ -2202,6 +2237,7 @@ impl AiMemoryServer {..ai_memory_core::ActorContext::default()},proposals,+ staged_by_actor_user,}).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;@@ -2268,6 +2304,14 @@ impl AiMemoryServer {"warnings": report.warnings,"rejected_candidates_count": report.rejected_candidates.len(),"proposals": outcomes,+ // Proposals the reviewer produced but the store never staged —+ // one-pending-per-target collisions — with the target path and the+ // reason. Without this the agent sees a successful run of N-1+ // proposals and nothing saying the Nth ever existed, the silent+ // drop the per-proposal skip set out to end. Always present (empty+ // on a clean run), and additive: a consumer that ignores the key+ // reads the response exactly as before.+ "skipped": staged.skipped,}))}@@ -3135,6 +3179,12 @@ fn moonshot_safe_tool_list(tools: Vec<Tool>) -> Vec<Tool> {/// day/week-scale retention scoring.const ACCESS_BUMP_COOLDOWN: Duration = Duration::from_secs(60);+/// Throttle bookkeeping for access-count bumps, keyed by page AND operator.+///+/// The operator half is what stops one person's read from swallowing everyone+/// else's reinforcement for the whole window.+type AccessBumpSeen = HashMap<(PageId, Option<String>), Instant>;+/// Pick the page ids due for an access bump, updating the cooldown clock in/// place: a page is due when it has not been bumped within `cooldown`./// Entries that have aged past `cooldown` are pruned in the same pass, so the@@ -3142,8 +3192,9 @@ const ACCESS_BUMP_COOLDOWN: Duration = Duration::from_secs(60);/// distinct page ever searched. Kept pure and synchronous so the throttle/// policy is unit-testable without a store or async runtime.fn select_bumpable(- seen: &mut HashMap<PageId, Instant>,+ seen: &mut AccessBumpSeen,ids: Vec<PageId>,+ actor: Option<&str>,now: Instant,cooldown: Duration,) -> Vec<PageId> {@@ -3152,23 +3203,41 @@ fn select_bumpable(seen.retain(|_, last| now.duration_since(*last) < cooldown);let mut fresh = Vec::new();for id in ids {+ let id = (id, actor.map(str::to_string));// After the prune, an occupied slot means "still within cooldown" —// skip it, and do not refresh its timestamp: refreshing would starve// a continuously-hot page of its once-per-window bump entirely.- if let Entry::Vacant(slot) = seen.entry(id) {+ if let Entry::Vacant(slot) = seen.entry(id.clone()) {slot.insert(now);- fresh.push(id);+ fresh.push(id.0);}}fresh}impl AiMemoryServer {+ /// The caller's qualified identity storage key+ /// ([`ai_memory_core::IdentityKey::storage_key`]), for keying the bump+ /// throttle and the `page_access` rows it feeds. One derivation for both:+ /// a throttle keyed one way and a table keyed another would throttle one+ /// operator's reads against another's rows.+ fn bump_actor_from_parts(parts: &axum::http::request::Parts) -> Option<String> {+ parts+ .extensions+ .get::<ai_memory_core::ActorContext>()+ .and_then(ai_memory_core::ActorContext::identity_key)+ .map(|key| key.storage_key())+ }+/// Fire-and-forget access-counter bump for the M8 reinforcement term,- /// throttled to at most one bump per page per [`ACCESS_BUMP_COOLDOWN`]- /// (see [`select_bumpable`]). Failures are logged at warn but never- /// surfaced to the caller.- fn spawn_access_bump(&self, ids: Vec<PageId>) {+ /// throttled to at most one bump per page PER OPERATOR per+ /// [`ACCESS_BUMP_COOLDOWN`] (see [`select_bumpable`]). Keyed per operator+ /// on purpose: a throttle keyed on the page alone would let whoever read+ /// it first swallow everybody else's reinforcement inside the window, so+ /// breadth — the signal `[decay] breadth_weight` exists to read — would+ /// under-count exactly on the busy pages it matters for. Failures are+ /// logged at warn but never surfaced to the caller.+ fn spawn_access_bump(&self, ids: Vec<PageId>, actor: Option<&str>) {if ids.is_empty() {return;}@@ -3177,14 +3246,17 @@ impl AiMemoryServer {.access_bump_seen.lock().unwrap_or_else(|poisoned| poisoned.into_inner());- select_bumpable(&mut seen, ids, Instant::now(), ACCESS_BUMP_COOLDOWN)+ select_bumpable(&mut seen, ids, actor, Instant::now(), ACCESS_BUMP_COOLDOWN)};if fresh.is_empty() {return;}let writer = self.writer.clone();+ // Carried into the write so reinforcement is recorded per operator as+ // well as in the shared counter.+ let actor = actor.map(str::to_string);tokio::spawn(async move {- if let Err(e) = writer.bump_access(fresh).await {+ if let Err(e) = writer.bump_access(fresh, actor).await {tracing::warn!(error = %e, "access bump failed");}});@@ -8064,6 +8136,265 @@ mod tests {);}+ /// Reviewer that always proposes the same two pages, so one of them can be+ /// made to collide with an already-pending proposal.+ struct TwoProposalAutoImproveLlm;++ #[async_trait::async_trait]+ impl ai_memory_llm::LlmProvider for TwoProposalAutoImproveLlm {+ fn name(&self) -> &'static str {+ "fake-auto-improve"+ }++ fn model(&self) -> &str {+ "fake-model"+ }++ async fn complete(+ &self,+ _request: ai_memory_llm::ChatRequest,+ ) -> ai_memory_llm::LlmResult<ai_memory_llm::ChatResponse> {+ Ok(ai_memory_llm::ChatResponse {+ text: String::new(),+ usage: None,+ model: self.model().to_string(),+ })+ }++ async fn complete_structured_raw(+ &self,+ _request: ai_memory_llm::ChatRequest,+ _schema: serde_json::Value,+ ) -> ai_memory_llm::LlmResult<serde_json::Value> {+ Ok(serde_json::json!({+ "summary": "two staged proposals",+ "proposals": [+ {+ "operation": "create_or_update",+ "path": "notes/collides.md",+ "title": "Colliding Lesson",+ "kind": "note",+ "confidence": 0.93,+ "rationale": "A proposal for this page is already pending.",+ "evidence": [{"page":"session", "quote":"durable lesson"}],+ "body_markdown": "# Colliding Lesson\n\nsecond proposal"+ },+ {+ "operation": "create_or_update",+ "path": "notes/fresh.md",+ "title": "Fresh Lesson",+ "kind": "note",+ "confidence": 0.91,+ "rationale": "The session contains a durable lesson worth adding.",+ "evidence": [{"page":"session", "quote":"durable lesson"}],+ "body_markdown": "# Fresh Lesson\n\nfirst proposal"+ }+ ],+ "rejected_candidates": []+ }))+ }+ }++ /// Stage one pending proposal for `notes/collides.md` into+ /// `pending_bucket`, then run `memory_auto_improve` as `caller` against the+ /// same page. Returns the tool's JSON so the caller can see whether the+ /// second proposal collided or got its own bucket.+ async fn auto_improve_over_pending_target(+ trusted_proxy_identity: bool,+ pending_bucket: Option<String>,+ caller: Option<&str>,+ ) -> serde_json::Value {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();++ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "durable lesson worth capturing".into(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ store+ .writer+ .stage_auto_improve_run(StageAutoImproveRun {+ workspace_id: ws,+ project_id: proj,+ session_id: None,+ provider: Some("test".into()),+ model: Some("model".into()),+ summary: Some("earlier run".into()),+ warnings_json: serde_json::json!([]),+ rejected_candidates_json: serde_json::json!([]),+ config_json: serde_json::json!({}),+ staged_by_actor_user: pending_bucket,+ proposal_actor: ai_memory_core::ActorContext::default(),+ proposals: vec![NewAutoImproveProposal {+ operation: AutoImproveProposalOperation::Create,+ target_path: PagePath::new("notes/collides.md").unwrap(),+ kind: "note".into(),+ title: "Colliding Lesson".into(),+ confidence: 0.9,+ rationale: "staged earlier".into(),+ evidence_json: serde_json::json!([]),+ body_markdown: "# Colliding Lesson\n\nfirst proposal".into(),+ artifact_sha256: None,+ edit_mode: None,+ patch_json: None,+ expected_base_body_sha256: None,+ }],+ })+ .await+ .unwrap();++ let llm: Arc<dyn LlmProvider> = Arc::new(TwoProposalAutoImproveLlm);+ let consolidator = Arc::new(Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki.clone(),+ llm.clone(),+ ws,+ proj,+ ));+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_consolidator_arc(wiki, llm, consolidator)+ .with_auto_improve_require_approval(true)+ .with_trusted_proxy_identity(trusted_proxy_identity);++ let mut parts = test_parts_default();+ if let Some(user) = caller {+ parts.extensions.insert(ai_memory_core::ActorContext {+ user: Some(user.to_string()),+ ..ai_memory_core::ActorContext::default()+ });+ }++ call_tool_json(+ server+ .memory_auto_improve(+ Parameters(AutoImproveArgs {+ session_id: Some(session_id.to_string()),+ dry_run: None,+ stage: None,+ mode: None,+ project: None,+ workspace: None,+ min_observations: Some(1),+ min_session_duration_secs: Some(0),+ min_confidence: Some(0.75),+ max_input_tokens: None,+ max_proposals: Some(5),+ include_raw_fallback: None,+ }),+ OptionalParts(parts),+ )+ .await+ .expect("a collision must not fail the run"),+ )+ }++ /// A proposal the store refuses to stage must reach the agent. Reporting+ /// only `proposal_ids` shows a successful run of N-1 proposals with nothing+ /// saying the Nth ever existed — the silent drop the per-proposal skip was+ /// introduced to end.+ #[tokio::test]+ async fn memory_auto_improve_reports_a_collided_proposal_instead_of_dropping_it() {+ // The default parts carry no operator, matching the unattributed+ // bucket the pending proposal was staged into.+ let json = auto_improve_over_pending_target(false, None, None).await;++ let proposals = json["proposals"].as_array().expect("proposals array");+ assert_eq!(proposals.len(), 1, "the sibling proposal still stages");+ let skipped = json["skipped"].as_array().expect("skipped array");+ assert_eq!(skipped.len(), 1, "the collided proposal must be reported");+ assert_eq!(skipped[0]["target_path"], "notes/collides.md");+ assert!(+ skipped[0]["reason"]+ .as_str()+ .is_some_and(|r| !r.trim().is_empty()),+ "a skipped proposal must say why: {}",+ skipped[0]+ );+ }++ /// `[auth].root_username` alone does not make a server multi-operator. The+ /// scheduler and the report handlers stage unattributed, so bucketing an+ /// interactive call by its actor would leave TWO pending proposals for one+ /// page on a single-operator server — exactly the collision V42 promises+ /// cannot happen.+ #[tokio::test]+ async fn single_operator_auto_improve_shares_one_pending_bucket_with_the_scheduler() {+ let json = auto_improve_over_pending_target(false, None, Some("the-operator")).await;++ let proposals = json["proposals"].as_array().expect("proposals array");+ assert_eq!(proposals.len(), 1, "the sibling proposal still stages");+ let skipped = json["skipped"].as_array().expect("skipped array");+ assert_eq!(+ skipped.len(),+ 1,+ "a named root operator must not open a second pending bucket for the same page"+ );+ assert_eq!(skipped[0]["target_path"], "notes/collides.md");+ }++ /// The other mode: once a trusted proxy tells operators apart, each one+ /// gets their own pending slot instead of blocking the others — the point+ /// of V42's author-scoped index. The pending bucket is built through the+ /// identity contract, the same encoding `owner_stamp` produces for the+ /// caller.+ #[tokio::test]+ async fn proxied_operators_each_hold_a_pending_proposal_for_the_same_page() {+ let alice = ai_memory_core::IdentityKey::User("alice".into()).storage_key();+ let json = auto_improve_over_pending_target(true, Some(alice), Some("bob")).await;++ let proposals = json["proposals"].as_array().expect("proposals array");+ assert_eq!(+ proposals.len(),+ 2,+ "a second operator must be able to propose for a page someone else has pending"+ );+ let skipped = json["skipped"].as_array().expect("skipped array");+ assert!(+ skipped.is_empty(),+ "nothing should collide across distinct operators: {skipped:?}"+ );+ }+/// `memory_lint` reads the wiki to build its candidate set. With/// no wiki wired, it must error cleanly.#[tokio::test]@@ -8292,28 +8623,67 @@ mod tests {// First sighting of both pages → both due, in input order.assert_eq!(- select_bumpable(&mut seen, vec![a, b], t0, cooldown),+ select_bumpable(&mut seen, vec![a, b], None, t0, cooldown),vec![a, b]);// The same hot pages 30s later (inside the window) → nothing due, so// the writer actor is spared the redundant reinforcement writes.let t30 = t0 + Duration::from_secs(30);- assert!(select_bumpable(&mut seen, vec![a, b], t30, cooldown).is_empty());+ assert!(select_bumpable(&mut seen, vec![a, b], None, t30, cooldown).is_empty());// A fresh page mixed in with the cooling ones → only the fresh one.assert_eq!(- select_bumpable(&mut seen, vec![a, b, c], t30, cooldown),+ select_bumpable(&mut seen, vec![a, b, c], None, t30, cooldown),vec![c]);// Past the window, `a` is due again.let t90 = t0 + Duration::from_secs(90);- assert_eq!(select_bumpable(&mut seen, vec![a], t90, cooldown), vec![a]);+ assert_eq!(+ select_bumpable(&mut seen, vec![a], None, t90, cooldown),+ vec![a]+ );// Aged-out entries are pruned, so the map never grows without bound.let t_far = t0 + Duration::from_secs(1_000);- assert!(select_bumpable(&mut seen, Vec::new(), t_far, cooldown).is_empty());+ assert!(select_bumpable(&mut seen, Vec::new(), None, t_far, cooldown).is_empty());assert!(seen.is_empty(), "aged-out entries must be pruned");}++ /// The throttle is keyed on (page, operator) ON PURPOSE: keyed on the page+ /// alone, whoever read it first would swallow everybody else's+ /// reinforcement inside the cooldown window, under-counting breadth+ /// exactly on the busy pages it matters for.+ #[test]+ fn access_bump_throttle_is_per_operator_not_per_page() {+ let cooldown = Duration::from_secs(60);+ let t0 = Instant::now();+ let page = PageId::new();+ let mut seen = HashMap::new();++ let alice = ai_memory_core::IdentityKey::User("alice".into()).storage_key();+ let bob = ai_memory_core::IdentityKey::User("bob".into()).storage_key();++ // Alice reads first; inside the window Bob's read must still count.+ assert_eq!(+ select_bumpable(&mut seen, vec![page], Some(&alice), t0, cooldown),+ vec![page]+ );+ let t10 = t0 + Duration::from_secs(10);+ assert_eq!(+ select_bumpable(&mut seen, vec![page], Some(&bob), t10, cooldown),+ vec![page],+ "one operator's read must not swallow another's reinforcement"+ );+ // An unattributed read is its own throttle slot, not Alice's.+ assert_eq!(+ select_bumpable(&mut seen, vec![page], None, t10, cooldown),+ vec![page]+ );++ // Each operator is still throttled against THEMSELVES.+ assert!(select_bumpable(&mut seen, vec![page], Some(&alice), t10, cooldown).is_empty());+ assert!(select_bumpable(&mut seen, vec![page], Some(&bob), t10, cooldown).is_empty());+ }}diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rsindex 55577880..3dfee25a 100644--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@ -102,6 +102,7 @@ fn telemetry_stage_input(warnings_json: serde_json::json!([]),rejected_candidates_json: serde_json::json!([]),config_json: serde_json::json!({}),+ staged_by_actor_user: None,proposal_actor: ActorContext::default(),proposals: vec![NewAutoImproveProposal {operation: AutoImproveProposalOperation::Create,diff --git a/crates/ai-memory-store/migrations/V42__auto_improve_proposal_author.sql b/crates/ai-memory-store/migrations/V42__auto_improve_proposal_author.sqlnew file mode 100644index 00000000..d7f75930--- /dev/null+++ b/crates/ai-memory-store/migrations/V42__auto_improve_proposal_author.sql@@ -0,0 +1,45 @@+-- V42: record who staged an auto-improvement proposal, and scope the+-- one-pending-per-target rule to that person.+--+-- `auto_improve_proposals` recorded `decided_by_author_id` (who approved or+-- rejected) but never who STAGED the proposal, so a reviewer could not tell+-- whose suggestion they were looking at.+--+-- The bigger problem is the uniqueness rule. `idx_auto_improve_one_pending_target`+-- allowed exactly one pending proposal per (workspace, project, target_path).+-- That is right for one operator and wrong for several: one person's pending+-- suggestion for `_rules/style.md` blocked everybody else's for the same page.+--+-- Correct in BOTH modes without a runtime switch, by folding the author into+-- the key with a NULL-collapsing expression:+--+-- * Single operator (or any unattributed caller): every row has+-- `staged_by_actor_user IS NULL`, so `COALESCE(...)` maps them all onto one+-- bucket and the existing "one pending per target" invariant holds exactly+-- as before.+-- * Several operators: each one gets their own bucket, so proposals stop+-- blocking each other.+--+-- `staged_by_actor_user` is TEXT rather than a FK to `users(id)` for the same+-- reason `handoffs.owner_user`, `sessions.actor_user` and `page_access.actor`+-- are: the identity that reaches a request is usually a username asserted by an+-- authenticating proxy, with no `users` row behind it. Keying on the row id+-- would make every proxied operator NULL and collapse them all into one bucket,+-- which is precisely the collision this index exists to break.+--+-- The COALESCE matters. A plain `UNIQUE (…, staged_by_actor_user)` would NOT+-- work: SQLite treats NULLs as distinct in unique indexes, so every existing+-- single-operator database would silently lose the guarantee and start+-- accepting unlimited pending proposals per page.+ALTER TABLE auto_improve_proposals ADD COLUMN staged_by_actor_user TEXT;++DROP INDEX IF EXISTS idx_auto_improve_one_pending_target;++CREATE UNIQUE INDEX idx_auto_improve_one_pending_target+ ON auto_improve_proposals(+ workspace_id,+ project_id,+ target_path,+ COALESCE(staged_by_actor_user, '')+ )+ WHERE status = 'pending';diff --git a/crates/ai-memory-store/migrations/V43__page_access_by_actor.sql b/crates/ai-memory-store/migrations/V43__page_access_by_actor.sqlnew file mode 100644index 00000000..6037a424--- /dev/null+++ b/crates/ai-memory-store/migrations/V43__page_access_by_actor.sql@@ -0,0 +1,27 @@+-- V43: record page reinforcement per operator, alongside the existing counter.+--+-- `pages.access_count` is a single number per page. It cannot distinguish+-- "50 reads by one person" from "one read by each of 50 people", yet those mean+-- very different things for whether a page is load-bearing for a team. On a+-- shared server the scalar also mixes everyone's reading into one signal.+--+-- Purely additive, and deliberately NOT a replacement:+-- * `pages.access_count` keeps being bumped exactly as before, so every+-- existing query, the retention formula and the hard-delete predicate are+-- untouched.+-- * Pages that existed before this simply have no rows here, which reads as+-- "breadth unknown" and is scored identically to breadth 1 — so there is no+-- eviction cliff and no backfill to run.+--+-- `actor` is TEXT rather than a FK to `users(id)` on purpose: the identity that+-- reaches a request is often a username asserted by an authenticating proxy,+-- with no `users` row behind it. Same reasoning as `handoffs.owner_user`.+CREATE TABLE page_access (+ page_id BLOB NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ actor TEXT NOT NULL,+ count INTEGER NOT NULL DEFAULT 0,+ last_accessed_at INTEGER,+ PRIMARY KEY (page_id, actor)+) WITHOUT ROWID;++CREATE INDEX idx_page_access_page ON page_access (page_id);diff --git a/crates/ai-memory-store/src/auto_improve.rs b/crates/ai-memory-store/src/auto_improve.rsindex aeea92de..dc1aca97 100644--- a/crates/ai-memory-store/src/auto_improve.rs+++ b/crates/ai-memory-store/src/auto_improve.rs@@ -142,6 +142,16 @@ pub struct StageAutoImproveRun {pub config_json: serde_json::Value,/// Actor attribution recorded on the run and its `staged` events.pub proposal_actor: ActorContext,+ /// Operator that staged this run, as the qualified+ /// [`ai_memory_core::IdentityKey::storage_key`] the caller computed through+ /// [`ai_memory_core::owner_stamp`] (`sub:<subject>` / `user:<name>`).+ ///+ /// A storage key rather than a `users(id)`: the majority of identified+ /// callers on a shared server are asserted by an authenticating proxy and+ /// have no row. `None` for a single-operator server and for any+ /// unattributed caller, which keeps the one-pending-per-target rule+ /// behaving exactly as before (see V42).+ pub staged_by_actor_user: Option<String>,/// Page edits to stage as pending proposals.pub proposals: Vec<NewAutoImproveProposal>,}@@ -183,6 +193,26 @@ pub struct StagedAutoImproveRun {pub run_id: AutoImproveRunId,/// Ids of the staged proposals, in input order.pub proposal_ids: Vec<AutoImproveProposalId>,+ /// Proposals that could not be staged because something is already pending+ /// for the same target, reported instead of silently dropped.+ ///+ /// A colliding proposal used to abort the whole transaction, losing the run+ /// row, the non-colliding proposals beside it, and the (paid) LLM call that+ /// produced them.+ pub skipped: Vec<SkippedProposal>,+}++/// One proposal that was not staged, and why.+///+/// `Deserialize` because the HTTP clients (the CLI) have to read this back off+/// the wire to show it; a report the operator never sees is the silent drop+/// again, one hop further out.+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct SkippedProposal {+ /// Wiki path the proposal targeted.+ pub target_path: String,+ /// Human-readable reason, safe to surface to an operator.+ pub reason: String,}/// List-view projection of a proposal (no bodies or event history).@@ -257,6 +287,14 @@ pub struct AutoImproveProposalDetail {pub expected_base_body_sha256: Option<[u8; 32]>,/// Base body hash the staged `body_markdown` was materialized from.pub materialized_base_body_sha256: Option<[u8; 32]>,+ /// Operator whose session produced this proposal, as the qualified+ /// identity storage key (`sub:<subject>` / `user:<name>`); `None` for an+ /// unattributed run (single-operator server, or the unattended scheduler on+ /// a session nobody was named on).+ ///+ /// Reviewer-facing — V42 added the column so a reviewer could tell whose+ /// suggestion they were looking at.+ pub staged_by_actor_user: Option<String>,/// Status history, oldest first.pub events: Vec<AutoImproveProposalEvent>,}@@ -572,7 +610,21 @@ pub fn stage_run()?;insert_rejected_candidates_in_tx(&tx, input, run_id, now)?;let mut proposal_ids = Vec::with_capacity(input.proposals.len());+ let mut skipped: Vec<SkippedProposal> = Vec::new();+ // Two proposals in ONE run targeting the same path mean the batch itself is+ // malformed — the model emitted contradictory suggestions for one page, and+ // silently keeping an arbitrary one would be worse than refusing. That+ // stays a hard error (see `duplicate_targets_within_one_run_still_fail_the_run`).+ // A collision with a proposal already PENDING from an earlier run is a+ // different situation, handled per-proposal below.+ let mut seen_targets: std::collections::HashSet<&str> = std::collections::HashSet::new();for proposal in &input.proposals {+ if !seen_targets.insert(proposal.target_path.as_str()) {+ return Err(StoreError::InvalidState(format!(+ "two proposals in the same run target {}",+ proposal.target_path+ )));+ }let id = AutoImproveProposalId::new();let artifact_path = artifact_path_for(id);let evidence_json = serde_json::to_string(&proposal.evidence_json)?;@@ -648,15 +700,16 @@ pub fn stage_run(}}}- tx.execute(+ let insert = tx.execute("INSERT INTO auto_improve_proposals \(id, run_id, workspace_id, project_id, status, operation, target_path, kind, title, \confidence, rationale, evidence_json, body_markdown, body_sha256, artifact_path, \artifact_sha256, target_latest_page_id_at_stage, target_body_sha256_at_stage, \target_updated_at_at_stage, staged_at, edit_mode, patch_json, \- expected_base_body_sha256, materialized_base_body_sha256) \+ expected_base_body_sha256, materialized_base_body_sha256, \+ staged_by_actor_user) \VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, \- ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23)",+ ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24)",params![id.as_bytes(),run_id.as_bytes(),@@ -681,8 +734,24 @@ pub fn stage_run(patch_json,proposal.expected_base_body_sha256.map(|h| h.to_vec()),proposal.expected_base_body_sha256.map(|h| h.to_vec()),+ input.staged_by_actor_user.as_deref(),],- )?;+ );+ // A pending proposal already exists for this target. Skip just this+ // one: aborting here would discard the run row and every sibling+ // proposal, which is a strictly worse outcome than not staging one+ // duplicate. Same tolerated-constraint shape as `get_or_create_project`.+ match insert {+ Ok(_) => {}+ Err(rusqlite::Error::SqliteFailure(err, _)) if is_pending_target_collision(&err) => {+ skipped.push(SkippedProposal {+ target_path: proposal.target_path.to_string(),+ reason: "a proposal is already pending review for this path".into(),+ });+ continue;+ }+ Err(e) => return Err(e.into()),+ }insert_event_in_tx(&tx,id,@@ -698,6 +767,7 @@ pub fn stage_run(Ok(StagedAutoImproveRun {run_id,proposal_ids,+ skipped,})}@@ -1220,6 +1290,19 @@ fn hex_sha256(bytes: &[u8]) -> String {out}+/// Is this insert failure the one-pending-proposal-per-target collision that+/// [`stage_run`] is allowed to swallow?+///+/// Only the UNIQUE extended code qualifies. `ErrorCode::ConstraintViolation` is+/// the PRIMARY code shared by NOT NULL, CHECK, FK and `RAISE(ABORT)` failures,+/// and `auto_improve_proposals` has CHECKs on `status`/`operation`, FKs to four+/// tables, and a workspace/project pairing trigger — accepting the primary code+/// would relabel any of those "a proposal is already pending review for this+/// path" and drop the proposal instead of surfacing a schema-contract bug.+fn is_pending_target_collision(err: &rusqlite::ffi::Error) -> bool {+ err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE+}+fn sha256(bytes: &[u8]) -> [u8; 32] {let mut hasher = Sha256::new();hasher.update(bytes);diff --git a/crates/ai-memory-store/src/decay.rs b/crates/ai-memory-store/src/decay.rsindex 4d5481ad..d8806653 100644--- a/crates/ai-memory-store/src/decay.rs+++ b/crates/ai-memory-store/src/decay.rs@@ -30,6 +30,15 @@ pub struct DecayParams {/// Days a soft-deleted (sweep-evicted) page must survive before/// hard-delete, *with* zero subsequent access.pub hard_delete_after_days: i64,+ /// How much a page being reinforced by MANY distinct operators should+ /// count for, beyond the raw hit count.+ ///+ /// `0.0` (the default) makes [`retention_score_with_breadth`] identical to+ /// the historical formula, so existing deployments keep byte-identical+ /// eviction decisions until this is deliberately raised. Only meaningful+ /// once requests carry distinct identities: with one shared credential+ /// every read lands under the same actor.+ pub breadth_weight: f64,}impl Default for DecayParams {@@ -38,6 +47,8 @@ impl Default for DecayParams {lambda: 0.02,sigma: 0.6,mu: 0.04,+ // Off: the score is identical to the pre-breadth formula.+ breadth_weight: 0.0,salience_default: 1.0,cold_threshold: 0.20,hard_delete_after_days: 180,@@ -62,11 +73,48 @@ pub fn retention_score(access_count: u32,days_since_access: Option<f64>,salience: Option<f64>,+) -> f64 {+ retention_score_with_breadth(+ params,+ age_days,+ access_count,+ days_since_access,+ salience,+ 0,+ )+}++/// Retention score that also accounts for HOW MANY distinct operators reinforced+/// the page.+///+/// `access_count` cannot tell "50 reads by one person" from "one read by each of+/// 50 people", although only the second says the page is load-bearing for a+/// team. `distinct_actors` supplies that, weighted by+/// [`DecayParams::breadth_weight`].+///+/// Identity at the default weight of `0.0`, and identity again for+/// `distinct_actors` of 0 (no per-actor rows recorded — every page written+/// before this existed) or 1 (a single reader). So enabling the table changes+/// no score until an operator deliberately turns the weight up, and there is no+/// eviction cliff to migrate around.+///+/// `salience` is the page's own feedback-moved salience; it scales the time+/// term independently of breadth, which scales the access term.+#[must_use]+pub fn retention_score_with_breadth(+ params: &DecayParams,+ age_days: f64,+ access_count: u32,+ days_since_access: Option<f64>,+ salience: Option<f64>,+ distinct_actors: u32,) -> f64 {let salience = salience.unwrap_or(params.salience_default);let time_term = salience * (-params.lambda * age_days).exp();+ // g(0) = g(1) = 1, monotonically non-decreasing afterwards.+ let breadth = 1.0 + params.breadth_weight * (f64::from(distinct_actors.max(1)) - 1.0).ln_1p();let access_term = days_since_access.map_or(0.0, |d| {- params.sigma * (1.0 + f64::from(access_count)).ln() * (-params.mu * d).exp()+ params.sigma * (1.0 + f64::from(access_count)).ln() * (-params.mu * d).exp() * breadth});time_term + access_term}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 3b44e07d..7a1ca571 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -33,11 +33,12 @@ pub use auto_improve::{AutoImproveProposalEvent, AutoImproveProposalOperation, AutoImproveProposalStatus,AutoImproveProposalSummary, AutoImproveRejectionSummary, AutoImproveTelemetryAggregate,AutoImproveTelemetryCount, FailAutoImproveProposal, NewAutoImproveProposal,- RejectAutoImproveProposal, StageAutoImproveRun, StagedAutoImproveRun, artifact_path_for,+ RejectAutoImproveProposal, SkippedProposal, StageAutoImproveRun, StagedAutoImproveRun,+ artifact_path_for,};pub use decay::{DecayParams, SALIENCE_MAX, SALIENCE_MIN, SALIENCE_STEP, retention_score,- salience_after_feedback,+ retention_score_with_breadth, salience_after_feedback,};pub use error::{StoreError, StoreResult};pub use maintenance::MaintenanceJob;@@ -198,6 +199,7 @@ mod tests {warnings_json: serde_json::json!([]),rejected_candidates_json: serde_json::json!([]),config_json: serde_json::json!({"mode":"stage"}),+ staged_by_actor_user: None,proposal_actor: ActorContext {agent: Some("auto_improve".into()),..ActorContext::default()@@ -551,20 +553,39 @@ mod tests {migrations::run_to(&mut conn, 23).unwrap();let ws = ops::get_or_create_workspace(&mut conn, "default").unwrap();let proj = ops::get_or_create_project(&mut conn, &ws, "app", None).unwrap();- let id = auto_improve::stage_run(- &mut conn,- &stage_input(- ws,- proj,- vec![proposal(- "notes/old.md",- AutoImproveProposalOperation::Create,- "old",- )],- ),+ // Era-appropriate raw insert: this fixture stops at V23 on purpose,+ // while `stage_run` writes whatever columns the CURRENT schema has, and+ // every later migration that adds one would break a test about an older+ // era.+ let id = ai_memory_core::AutoImproveProposalId::new();+ let run_id = ai_memory_core::AutoImproveRunId::new();+ let now = jiff::Timestamp::now().as_microsecond();+ conn.execute(+ "INSERT INTO auto_improve_runs \+ (id, workspace_id, project_id, warnings_json, rejected_candidates_json, \+ config_json, proposal_actor_json, created_at) \+ VALUES (?1, ?2, ?3, '[]', '[]', '{}', '{}', ?4)",+ params![run_id.as_bytes(), ws.as_bytes(), proj.as_bytes(), now],)- .unwrap()- .proposal_ids[0];+ .unwrap();+ conn.execute(+ "INSERT INTO auto_improve_proposals \+ (id, run_id, workspace_id, project_id, status, operation, target_path, kind, \+ title, confidence, rationale, evidence_json, body_markdown, body_sha256, \+ artifact_path, staged_at) \+ VALUES (?1, ?2, ?3, ?4, 'pending', 'create', 'notes/old.md', 'note', 'old', \+ 0.9, 'r', '[]', 'body', ?5, ?6, ?7)",+ params![+ id.as_bytes(),+ run_id.as_bytes(),+ ws.as_bytes(),+ proj.as_bytes(),+ &sha256("body")[..],+ auto_improve::artifact_path_for(id),+ now,+ ],+ )+ .unwrap();drop(conn);let store = Store::open(tmp.path()).unwrap();@@ -3172,6 +3193,7 @@ mod tests {warnings_json: serde_json::json!([]),rejected_candidates_json: serde_json::json!([]),config_json: serde_json::json!({ "trigger": "scheduler" }),+ staged_by_actor_user: None,proposal_actor: ActorContext {agent: Some("auto_improve".into()),..ActorContext::default()diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex f652d824..8caebe62 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1098,7 +1098,14 @@ pub fn store_embeddings(conn: &mut Connection, embeddings: &[EmbeddingWrite]) ->/// Bump `access_count` + `last_accessed_at` for the pages whose ids/// appear in `page_ids`. Idempotent for unknown ids (no-op)./// Used by the read path to feed the M8 reinforcement term.-pub fn bump_access_for_pages(conn: &mut Connection, page_ids: &[PageId]) -> StoreResult<()> {+///+/// `actor` is the reading operator's qualified identity storage key+/// (`IdentityKey::storage_key()`), or `None` for an unattributed read.+pub fn bump_access_for_pages(+ conn: &mut Connection,+ page_ids: &[PageId],+ actor: Option<&str>,+) -> StoreResult<()> {if page_ids.is_empty() {return Ok(());}@@ -1113,6 +1120,30 @@ pub fn bump_access_for_pages(conn: &mut Connection, page_ids: &[PageId]) -> Storfor id in page_ids {stmt.execute(params![now, id.as_bytes()])?;}+ // Per-operator reinforcement, recorded in the SAME transaction so the+ // scalar and the breakdown cannot drift. Purely additive: the scalar+ // above is what the retention formula still reads by default.+ if let Some(actor) = actor.filter(|a| !a.trim().is_empty()) {+ // The `WHERE EXISTS` guard is what keeps the documented idempotence+ // for unknown ids: `page_access.page_id` REFERENCES `pages(id)` and+ // the writer connection runs with `foreign_keys` ON, so a bare+ // INSERT for a page deleted between the search and this (detached,+ // post-response) bump would raise a FK violation and roll back the+ // WHOLE batch — costing every other page in the result set its+ // reinforcement. `INSERT OR IGNORE` does not help: it suppresses+ // constraint conflicts, not FK violations. The predicate mirrors the+ // UPDATE above so the scalar and the breakdown cannot drift.+ let mut per_actor = tx.prepare(+ "INSERT INTO page_access (page_id, actor, count, last_accessed_at) \+ SELECT ?1, ?2, 1, ?3 \+ WHERE EXISTS (SELECT 1 FROM pages WHERE id = ?1 AND is_latest = 1) \+ ON CONFLICT(page_id, actor) DO UPDATE \+ SET count = count + 1, last_accessed_at = excluded.last_accessed_at",+ )?;+ for id in page_ids {+ per_actor.execute(params![id.as_bytes(), actor, now])?;+ }+ }}tx.commit()?;Ok(())diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex af1bb5ed..8eebb5f1 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -2198,6 +2198,49 @@ impl ReaderPool {.await}+ /// Return the number of DISTINCT operators that reinforced each+ /// `is_latest = 1` page of a project, for the sweep's breadth term.+ ///+ /// Scoped and grouped exactly like [`decay_candidates`](Self::decay_candidates)+ /// so the sweep pays for one query per run, never one per candidate. Pages+ /// with no per-operator rows (everything read anonymously, and everything+ /// that predates `page_access`) are simply absent from the map, which the+ /// caller reads as breadth 0 — scored identically to breadth 1 by+ /// [`retention_score_with_breadth`](crate::retention_score_with_breadth).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn access_breadth_for_project(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ ) -> StoreResult<std::collections::HashMap<PageId, u32>> {+ self.with_conn(move |conn| {+ let mut stmt = conn.prepare(+ "SELECT pa.page_id, COUNT(DISTINCT pa.actor) \+ FROM page_access pa \+ JOIN pages p ON p.id = pa.page_id \+ WHERE p.workspace_id = ?1 AND p.project_id = ?2 AND p.is_latest = 1 \+ GROUP BY pa.page_id",+ )?;+ let rows = stmt.query_map(+ params![workspace_id.as_bytes(), project_id.as_bytes()],+ |row| {+ let id: Vec<u8> = row.get(0)?;+ let actors: i64 = row.get(1)?;+ Ok((id, u32::try_from(actors).unwrap_or(u32::MAX)))+ },+ )?;+ let mut out = std::collections::HashMap::new();+ for r in rows {+ let (id, actors) = r?;+ out.insert(PageId::from_slice(&id)?, actors);+ }+ Ok(out)+ })+ .await+ }+/// Rank pages by how many of the query's tokens match their indexed/// entities, weighting each match by inverse entity frequency — a/// query token matching an entity that appears on 2 pages is a much@@ -4491,7 +4534,8 @@ impl ReaderPool {target_body_sha256_at_stage, target_updated_at_at_stage, \decision_reason, decided_by_author_id, decided_by_actor_json, \applied_page_id, checkpoint, edit_mode, patch_json, \- expected_base_body_sha256, materialized_base_body_sha256 \+ expected_base_body_sha256, materialized_base_body_sha256, \+ staged_by_actor_user \FROM auto_improve_proposals \WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",params![@@ -4549,6 +4593,7 @@ impl ReaderPool {.map_err(to_sql_err)?,expected_base_body_sha256: opt_bytes32(row.get(28)?).map_err(to_sql_err)?,+ staged_by_actor_user: row.get(30)?,materialized_base_body_sha256: opt_bytes32(row.get(29)?).map_err(to_sql_err)?,events: Vec::new(),@@ -5355,9 +5400,10 @@ impl ReaderPool {/// visible from the store, so the caller passes the second in — a/// proxy-only deployment reports `users_exist() == false` forever.///- /// One notion, several gates: the admin authorization boundaries all key- /// on this, so a single-operator server keeps the exact behaviour it had- /// before either route existed.+ /// One notion, several gates: the admin authorization boundaries and the+ /// per-author bucketing of pending auto-improve proposals all key on this,+ /// so a single-operator server keeps the exact behaviour it had before+ /// either route existed.////// # Errors/// Propagates any SQL or pool error so callers can fail closed.diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 6111c0be..5d6d099a 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -183,6 +183,7 @@ pub(crate) enum WriteCmd {},BumpAccess {page_ids: Vec<PageId>,+ actor: Option<String>,reply: oneshot::Sender<StoreResult<()>>,},RecordPageFeedback {@@ -857,12 +858,20 @@ impl WriterHandle {/// Bump access counters for a set of pages (M8 reinforcement term).///+ /// `actor` is the reading operator's qualified identity storage key+ /// (`IdentityKey::storage_key()`); `None` records only the shared scalar.+ ////// # Errors/// Returns [`StoreError::WriterClosed`] or propagates SQL errors.- pub async fn bump_access(&self, page_ids: Vec<PageId>) -> StoreResult<()> {+ pub async fn bump_access(+ &self,+ page_ids: Vec<PageId>,+ actor: Option<String>,+ ) -> StoreResult<()> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::BumpAccess {page_ids,+ actor,reply: tx,}).await?;@@ -1749,8 +1758,12 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {);send_or_warn(reply, result, "record_page_feedback");}- WriteCmd::BumpAccess { page_ids, reply } => {- let result = ops::bump_access_for_pages(&mut conn, &page_ids);+ WriteCmd::BumpAccess {+ page_ids,+ actor,+ reply,+ } => {+ let result = ops::bump_access_for_pages(&mut conn, &page_ids, actor.as_deref());send_or_warn(reply, result, "bump_access_for_pages");}WriteCmd::SoftDeleteForDecay { page_ids, reply } => {diff --git a/crates/ai-memory-store/tests/access_breadth.rs b/crates/ai-memory-store/tests/access_breadth.rsnew file mode 100644index 00000000..103876b1--- /dev/null+++ b/crates/ai-memory-store/tests/access_breadth.rs@@ -0,0 +1,252 @@+//! Per-operator reinforcement, recorded alongside the shared counter.+//!+//! `pages.access_count` cannot distinguish "50 reads by one person" from "one+//! read by each of 50 people", although only the second says a page is+//! load-bearing for a team. `page_access` records the breakdown WITHOUT+//! replacing the scalar, so the retention formula, the hard-delete predicate+//! and every existing query keep reading exactly what they read before.++use ai_memory_core::{IdentityKey, NewPage, PagePath, Tier};+use ai_memory_store::{DecayParams, Store, retention_score, retention_score_with_breadth};+use rusqlite::{Connection, params};++/// The qualified TEXT the read path records operators under — built through+/// the contract (`IdentityKey::storage_key()`), never hand-written, so these+/// tests break if the storage encoding ever drifts from the API.+fn actor_key(name: &str) -> String {+ IdentityKey::User(name.into()).storage_key()+}++/// Default parameters must reproduce the historical score exactly, whatever the+/// breadth — otherwise adopting the table would silently move every eviction+/// decision on every existing database.+#[test]+fn breadth_is_identity_at_the_default_weight() {+ let params = DecayParams::default();+ assert_eq!(params.breadth_weight, 0.0);++ for actors in [0, 1, 2, 10, 500] {+ for (age, count, since) in [+ (0.0, 0, None),+ (10.0, 3, Some(2.0)),+ (365.0, 100, Some(200.0)),+ ] {+ assert_eq!(+ retention_score_with_breadth(¶ms, age, count, since, None, actors),+ retention_score(¶ms, age, count, since, None),+ "default weight must be identity (actors={actors})"+ );+ }+ }+}++/// Even with the weight turned up, 0 and 1 distinct actors score identically to+/// the old formula: a page nobody has read per-actor rows for (everything+/// written before this existed) and a page one person reads are unchanged. That+/// is what removes the eviction cliff and the need for any backfill.+#[test]+fn zero_and_one_actor_score_identically_even_when_weighted() {+ let params = DecayParams {+ breadth_weight: 1.5,+ ..DecayParams::default()+ };+ let baseline = retention_score(¶ms, 30.0, 5, Some(3.0), None);+ for actors in [0, 1] {+ assert_eq!(+ retention_score_with_breadth(¶ms, 30.0, 5, Some(3.0), None, actors),+ baseline,+ "actors={actors} must not change the score"+ );+ }+ // More readers is worth strictly more, and monotonically so.+ let two = retention_score_with_breadth(¶ms, 30.0, 5, Some(3.0), None, 2);+ let ten = retention_score_with_breadth(¶ms, 30.0, 5, Some(3.0), None, 10);+ assert!(two > baseline);+ assert!(ten > two);+}++/// A page never accessed scores the same regardless of breadth: with no access+/// timestamp there is no access term to weight.+#[test]+fn never_accessed_pages_are_unaffected_by_breadth() {+ let params = DecayParams {+ breadth_weight: 2.0,+ ..DecayParams::default()+ };+ assert_eq!(+ retention_score_with_breadth(¶ms, 10.0, 0, None, None, 9),+ retention_score(¶ms, 10.0, 0, None, None)+ );+}++/// The breakdown is written in the same transaction as the scalar, so the two+/// cannot drift, and an unattributed read still bumps the scalar.+#[tokio::test]+async fn per_actor_rows_accumulate_without_replacing_the_scalar() {+ 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();+ let page = store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/x.md").unwrap(),+ title: "x".into(),+ body: "b".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ })+ .await+ .unwrap();++ store+ .writer+ .bump_access(vec![page], Some(actor_key("alice")))+ .await+ .unwrap();+ store+ .writer+ .bump_access(vec![page], Some(actor_key("alice")))+ .await+ .unwrap();+ store+ .writer+ .bump_access(vec![page], Some(actor_key("bob")))+ .await+ .unwrap();+ // An unattributed read: still counted in the shared scalar.+ store.writer.bump_access(vec![page], None).await.unwrap();++ let conn = Connection::open(store.db_path()).unwrap();+ let scalar: i64 = conn+ .query_row(+ "SELECT access_count FROM pages WHERE id = ?1",+ params![page.as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(scalar, 4, "the historical counter still counts every read");++ let distinct: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM page_access WHERE page_id = ?1",+ params![page.as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(distinct, 2, "two named operators, the anonymous read aside");++ let alice: i64 = conn+ .query_row(+ "SELECT count FROM page_access WHERE page_id = ?1 AND actor = ?2",+ params![page.as_bytes(), actor_key("alice")],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(alice, 2);+}++/// The bump is fired from a detached task AFTER the search responded, so a page+/// can be deleted in the interval. `page_access.page_id` REFERENCES `pages(id)`+/// with foreign keys ON, so an unguarded insert for that id aborts the+/// transaction and every OTHER page in the same result set silently loses its+/// once-per-window reinforcement — which then makes those pages likelier to be+/// evicted by the next sweep.+#[tokio::test]+async fn a_stale_page_id_does_not_cost_the_rest_of_the_batch_its_bump() {+ 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();++ let mut ids = Vec::new();+ for path in ["notes/live-a.md", "notes/doomed.md", "notes/live-b.md"] {+ ids.push(+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: path.into(),+ body: "b".into(),+ tier: Tier::Episodic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ })+ .await+ .unwrap(),+ );+ }++ // The page vanishes between the search and the bump.+ store+ .writer+ .delete_page(ws, proj, PagePath::new("notes/doomed.md").unwrap(), None)+ .await+ .unwrap();++ store+ .writer+ .bump_access(ids.clone(), Some(actor_key("alice")))+ .await+ .unwrap();++ let conn = Connection::open(store.db_path()).unwrap();+ for (label, id) in [("live-a", ids[0]), ("live-b", ids[2])] {+ let scalar: i64 = conn+ .query_row(+ "SELECT access_count FROM pages WHERE id = ?1",+ params![id.as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(scalar, 1, "{label} lost its bump to the stale sibling");++ let per_actor: i64 = conn+ .query_row(+ "SELECT count FROM page_access WHERE page_id = ?1 AND actor = ?2",+ params![id.as_bytes(), actor_key("alice")],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(per_actor, 1, "{label} lost its per-operator row");+ }++ // The unknown id stays a no-op, exactly as it was before per-actor rows.+ let orphaned: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM page_access WHERE page_id = ?1",+ params![ids[1].as_bytes()],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(orphaned, 0);+}diff --git a/crates/ai-memory-store/tests/auto_improve_staging.rs b/crates/ai-memory-store/tests/auto_improve_staging.rsnew file mode 100644index 00000000..8a5a48ec--- /dev/null+++ b/crates/ai-memory-store/tests/auto_improve_staging.rs@@ -0,0 +1,296 @@+//! A colliding proposal must not destroy the run it arrived with.+//!+//! `stage_run` inserted each proposal blind inside one transaction, so the+//! partial UNIQUE index on pending targets aborted the whole thing via `?`:+//! the run row, every non-colliding proposal beside it, and the paid LLM call+//! that produced them were all lost. It fires with a single operator, through+//! the path the prompt itself recommends.++use ai_memory_core::{ActorContext, IdentityKey, PagePath, ProjectId, WorkspaceId};+use ai_memory_store::{+ AutoImproveProposalOperation, NewAutoImproveProposal, StageAutoImproveRun, Store,+};++fn proposal(path: &str, title: &str) -> NewAutoImproveProposal {+ NewAutoImproveProposal {+ operation: AutoImproveProposalOperation::Create,+ target_path: PagePath::new(path).unwrap(),+ kind: "rule".into(),+ title: title.into(),+ confidence: 0.9,+ rationale: "because".into(),+ evidence_json: serde_json::json!([]),+ body_markdown: format!("# {title}\n\nbody"),+ artifact_sha256: None,+ edit_mode: None,+ patch_json: None,+ expected_base_body_sha256: None,+ }+}++fn run(+ ws: WorkspaceId,+ proj: ProjectId,+ proposals: Vec<NewAutoImproveProposal>,+) -> StageAutoImproveRun {+ StageAutoImproveRun {+ workspace_id: ws,+ project_id: proj,+ session_id: None,+ proposals,+ proposal_actor: ActorContext::anonymous(),+ staged_by_actor_user: None,+ warnings_json: serde_json::json!([]),+ rejected_candidates_json: serde_json::json!([]),+ config_json: serde_json::json!({}),+ summary: Some("s".into()),+ provider: None,+ model: None,+ }+}++async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "p".to_string(), None)+ .await+ .unwrap();+ (ws, proj)+}++/// A second run targeting an already-pending path keeps its own run row and its+/// unrelated proposal; only the duplicate is skipped, and it is reported.+#[tokio::test]+async fn a_colliding_proposal_does_not_destroy_the_run() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let first = store+ .writer+ .stage_auto_improve_run(run(+ ws,+ proj,+ vec![proposal("_slots/current-focus.md", "Focus")],+ ))+ .await+ .unwrap();+ assert_eq!(first.proposal_ids.len(), 1);+ assert!(first.skipped.is_empty());++ // Second run: one duplicate target + one perfectly good new proposal.+ let second = store+ .writer+ .stage_auto_improve_run(run(+ ws,+ proj,+ vec![+ proposal("_slots/current-focus.md", "Focus again"),+ proposal("_rules/unrelated.md", "Unrelated"),+ ],+ ))+ .await+ .unwrap();++ assert_eq!(+ second.proposal_ids.len(),+ 1,+ "the non-colliding proposal must still be staged"+ );+ assert_eq!(+ second.skipped.len(),+ 1,+ "the duplicate is reported, not silent"+ );+ assert_eq!(second.skipped[0].target_path, "_slots/current-focus.md");+}++/// A batch that contradicts itself is refused wholesale, and must keep being+/// refused: two proposals for one page mean the model emitted conflicting+/// suggestions, and picking one arbitrarily is worse than failing. This is a+/// different situation from colliding with an EARLIER run's pending proposal,+/// which is skipped per-proposal so the rest of the run survives.+#[tokio::test]+async fn duplicate_targets_within_one_run_still_fail_the_run() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ let result = store+ .writer+ .stage_auto_improve_run(run(+ ws,+ proj,+ vec![+ proposal("_slots/current-focus.md", "First"),+ proposal("_slots/current-focus.md", "Second"),+ ],+ ))+ .await;+ assert!(result.is_err(), "a self-contradicting batch is refused");++ // …and nothing from it is left behind.+ assert!(+ store+ .reader+ .list_auto_improve_proposals(ws, proj, None, 10)+ .await+ .unwrap()+ .is_empty()+ );+}++/// The one-pending-per-target rule must be right in BOTH modes, from one index.+///+/// V42 folds the operator into the unique key through `COALESCE(actor, '')`:+/// unattributed rows (single operator, or any caller the server cannot name)+/// all land in one bucket and keep the original invariant, while distinct+/// operators get their own. A plain `UNIQUE (…, staged_by_actor_user)` would+/// NOT do this — SQLite treats NULLs as distinct, so every existing+/// single-operator database would silently start accepting unlimited pending+/// proposals per page.+///+/// The key is the actor's qualified identity storage key+/// (`IdentityKey::storage_key()`), not a `users(id)`: operators asserted by a+/// trusted proxy have no row, so keying on the id would leave every one of them+/// NULL and collapse them all back into a single bucket — the exact collision+/// this index exists to break.+#[tokio::test]+async fn pending_uniqueness_is_per_operator_without_weakening_single_user() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ // Buckets are the contract's storage keys, built through the API so this+ // test exercises the same encoding the servers stamp.+ let staged_by = |actor: Option<&str>| {+ let mut r = run(ws, proj, vec![proposal("_rules/style.md", "Style")]);+ r.staged_by_actor_user = actor.map(|name| IdentityKey::User(name.into()).storage_key());+ r+ };++ // --- single-operator behaviour is untouched: unattributed rows collapse+ // into one bucket, so the second pending proposal is still refused.+ let first = store+ .writer+ .stage_auto_improve_run(staged_by(None))+ .await+ .unwrap();+ assert_eq!(first.proposal_ids.len(), 1);+ let second = store+ .writer+ .stage_auto_improve_run(staged_by(None))+ .await+ .unwrap();+ assert!(+ second.proposal_ids.is_empty() && second.skipped.len() == 1,+ "an unattributed duplicate must still be refused, as before V42"+ );++ // --- multi-operator: two proxy-asserted humans, neither with a `users`+ // row, must not block each other on the same page.+ let alices = store+ .writer+ .stage_auto_improve_run(staged_by(Some("alice")))+ .await+ .unwrap();+ assert_eq!(+ alices.proposal_ids.len(),+ 1,+ "one operator's pending proposal must not block another's for the same page"+ );+ assert!(alices.skipped.is_empty());++ let bobs = store+ .writer+ .stage_auto_improve_run(staged_by(Some("bob")))+ .await+ .unwrap();+ assert_eq!(bobs.proposal_ids.len(), 1);+ assert!(bobs.skipped.is_empty());++ // …and Alice still cannot stack two of her own.+ let alice_again = store+ .writer+ .stage_auto_improve_run(staged_by(Some("alice")))+ .await+ .unwrap();+ assert_eq!(alice_again.skipped.len(), 1);+}++/// Only the UNIQUE collision may be swallowed.+///+/// `ErrorCode::ConstraintViolation` is the PRIMARY code that NOT NULL, CHECK, FK+/// and `RAISE(ABORT)` failures all share, and `auto_improve_proposals` carries+/// CHECKs on `status`/`operation`, FKs to four tables, and a workspace/project+/// pairing trigger. Accepting the primary code relabels any of those "a proposal+/// is already pending review for this path" and drops the proposal, so a broken+/// schema contract looks like ordinary contention and nothing ever reports it.+#[tokio::test]+async fn a_non_unique_constraint_failure_is_not_reported_as_a_pending_collision() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;++ // Stand-in for the constraints the table already has, reached with a target+ // path the test controls: same primary code as the pending-collision index,+ // different extended one.+ {+ let conn =+ rusqlite::Connection::open(tmp.path().join("db").join(ai_memory_store::DB_FILENAME))+ .unwrap();+ conn.execute_batch(+ "CREATE TRIGGER test_schema_contract \+ BEFORE INSERT ON auto_improve_proposals \+ FOR EACH ROW WHEN NEW.target_path = 'notes/contract.md' \+ BEGIN SELECT RAISE(ABORT, 'schema contract violated'); END;",+ )+ .unwrap();+ }++ let err = store+ .writer+ .stage_auto_improve_run(run(+ ws,+ proj,+ vec![proposal("notes/contract.md", "Contract")],+ ))+ .await+ .expect_err("a schema-contract failure must surface, not be skipped");+ assert!(+ err.to_string().contains("schema contract violated"),+ "the real cause must reach the caller: {err}"+ );+ assert!(+ store+ .reader+ .list_auto_improve_proposals(ws, proj, None, 10)+ .await+ .unwrap()+ .is_empty(),+ "nothing may be staged by an aborted run"+ );++ // The genuine collision is still tolerated per-proposal.+ let first = store+ .writer+ .stage_auto_improve_run(run(ws, proj, vec![proposal("notes/ok.md", "Ok")]))+ .await+ .unwrap();+ assert_eq!(first.proposal_ids.len(), 1);+ let again = store+ .writer+ .stage_auto_improve_run(run(ws, proj, vec![proposal("notes/ok.md", "Ok again")]))+ .await+ .unwrap();+ assert_eq!(again.skipped.len(), 1);+ assert_eq!(+ again.skipped[0].reason,+ "a proposal is already pending review for this path"+ );+}diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 6485bc8e..3e111439 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -2067,6 +2067,7 @@ mod tests {warnings_json: serde_json::json!([]),rejected_candidates_json: serde_json::json!([]),config_json: serde_json::json!({}),+ staged_by_actor_user: None,proposal_actor: ActorContext {agent: Some("auto_improve".into()),..ActorContext::default()diff --git a/docs/users.md b/docs/users.mdindex f49f89bd..df3617c6 100644--- a/docs/users.md+++ b/docs/users.md@@ -121,6 +121,38 @@ derivation is `IdentityKey::path_segment()`: values made only ofelse hex-encodes under a distinct prefix (`sx-…`, `ux-…`) that keeps theencoding injective.+## Other per-operator state++Beyond attribution, some engine state is recorded per operator. "Absent means+shared" is the rule throughout — a row with no recorded operator behaves+exactly as it did before the column existed — so a single-operator server+keeps its historical behaviour:++- **Auto-improvement proposals.** Each records the operator who staged it (the+ qualified identity key — `sub:<subject>` / `user:<name>` — so proxy-asserted+ humans count too, and it shows up on the proposal detail), and the "one+ pending proposal per page" rule applies per operator, so operators stop+ blocking each other. Only where the deployment distinguishes operators,+ though: elsewhere proposals stay unattributed and the original one-per-page+ rule holds unchanged. A scheduled run has no caller and stages unattributed;+ the telemetry report and the curator describe the project rather than a+ person and stay unattributed too, so they neither block nor are blocked by+ any named operator's pending proposal for the same page.++ A proposal that does collide with one already pending is skipped on its own+ — the run's other proposals still stage — and every staging surface reports+ the skip with the target path and the reason (the `skipped` list in the MCP+ and `/admin` responses, the CLI output, and the scheduler's log), so a run+ of N-1 proposals is never silently indistinguishable from a clean run of+ N-1.+- **Page reinforcement.** Reads are counted per operator as well as in the+ shared counter. `[decay] breadth_weight` (default `0.0`) optionally lets a+ page reinforced by many different people outrank one read repeatedly by a+ single person — the forget sweep reads the per-page count of distinct+ operators and feeds it into the retention score. At the default, and for+ pages with fewer than two distinct readers at any weight, retention scores+ are unchanged.+## Implementation contractRequest identity and authorization are separate: