Skip to content

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

Rust

fix: harden proposal ownership and breadth retention

AkitaOnRails0861e4c06f6c
diff --git a/README.md b/README.md
index 642522f1..dd988bec 100644
--- a/README.md
+++ b/README.md
@@ -263,7 +263,10 @@ priors are at the [bottom](#influences-and-prior-art).
auto-improve-report --workspace <w> --project <p>` returns a read-only
telemetry report for recent auto-improvement outcomes without staging or
creating proposals; add `--stage` to create one pending report page for
- audit/approval. See
+ audit/approval. On deployments that distinguish operators, pending learning
+ proposals are isolated by qualified operator identity, so one person's
+ proposal for a page does not block another's; unattributed and single-user
+ deployments retain the shared pending queue. See
[`docs/auto-improve-eval-gates.md`](docs/auto-improve-eval-gates.md) for
example executable eval scorers.
@@ -279,7 +282,9 @@ priors are at the [bottom](#influences-and-prior-art).
episodic pages, stale slots, duplicate exact normalized titles, and dangling
cross-project links. It is report-only unless `--stage` is passed; staging
queues one report page for approval and still performs no maintenance actions
- itself.
+ itself. Shared servers can opt into `[decay] breadth_weight` to give pages
+ reinforced by several identified operators a retention bonus; the default
+ `0.0` leaves existing retention scores unchanged.
- **"Run one ai-memory for the whole household."** Stand the server
up on a homelab box at `0.0.0.0:49374` with a bearer token; every
laptop/desktop talks to it. Per-cwd routing keeps each project's
diff --git a/crates/ai-memory-cli/src/commands/curator.rs b/crates/ai-memory-cli/src/commands/curator.rs
index e7215239..ddee4139 100644
--- a/crates/ai-memory-cli/src/commands/curator.rs
+++ b/crates/ai-memory-cli/src/commands/curator.rs
@@ -1,6 +1,7 @@
//! `ai-memory curator` — rule-based report-only maintenance review.
use ai_memory_consolidate::CuratorReport;
+use ai_memory_store::SkippedProposal;
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
@@ -21,6 +22,8 @@ struct StageResponse {
run_id: String,
proposal_ids: Vec<String>,
sidecar_paths: Vec<String>,
+ #[serde(default)]
+ skipped: Vec<SkippedProposal>,
report: CuratorReport,
}
@@ -49,14 +52,7 @@ pub async fn run(config: &Config, args: CuratorArgs) -> Result<()> {
if args.json {
println!("{}", serde_json::to_string_pretty(&response)?);
} else {
- println!("Staged curator report run {}", response.run_id);
- for (id, path) in response
- .proposal_ids
- .iter()
- .zip(response.sidecar_paths.iter())
- {
- println!(" - {id}: {path}");
- }
+ println!("{}", render_stage_human(&response));
}
} else {
let report: CuratorReport = post_json(&endpoint, "/admin/curator", &request).await?;
@@ -71,6 +67,19 @@ pub async fn run(config: &Config, args: CuratorArgs) -> Result<()> {
Ok(())
}
+fn render_stage_human(response: &StageResponse) -> String {
+ let mut lines = vec![format!("Staged curator report run {}", response.run_id)];
+ lines.extend(
+ response
+ .proposal_ids
+ .iter()
+ .zip(response.sidecar_paths.iter())
+ .map(|(id, path)| format!(" - {id}: {path}")),
+ );
+ lines.extend(super::skipped_proposal_lines(&response.skipped));
+ lines.join("\n")
+}
+
fn print_human_report(report: &CuratorReport, project: &str) {
println!("\nCurator dry-run for {project}\n");
println!("Summary: {}", report.summary);
@@ -85,3 +94,47 @@ fn print_human_report(report: &CuratorReport, project: &str) {
println!(" ... {} more", report.findings.len() - 10);
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn response(skipped: Vec<SkippedProposal>) -> StageResponse {
+ StageResponse {
+ run_id: "run-1".into(),
+ proposal_ids: Vec::new(),
+ sidecar_paths: Vec::new(),
+ skipped,
+ report: CuratorReport {
+ workspace: "default".into(),
+ project: "project".into(),
+ generated_at: "2026-01-01T00:00:00Z".into(),
+ dry_run: false,
+ summary: "summary".into(),
+ params: ai_memory_consolidate::CuratorParams::default(),
+ findings: Vec::new(),
+ },
+ }
+ }
+
+ #[test]
+ fn staged_collision_reaches_human_and_json_output() {
+ let response = response(vec![SkippedProposal {
+ target_path: "_reports/curator.md".into(),
+ reason: "a proposal is already pending review for this path".into(),
+ }]);
+ let human = render_stage_human(&response);
+ assert!(human.contains("_reports/curator.md"), "{human}");
+ assert!(human.contains("already pending review"), "{human}");
+ let json = serde_json::to_value(response).unwrap();
+ assert_eq!(json["skipped"][0]["target_path"], "_reports/curator.md");
+ }
+
+ #[test]
+ fn older_server_response_without_skipped_still_parses() {
+ let mut json = serde_json::to_value(response(Vec::new())).unwrap();
+ json.as_object_mut().unwrap().remove("skipped");
+ let parsed: StageResponse = serde_json::from_value(json).unwrap();
+ assert!(parsed.skipped.is_empty());
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 12dfcf42..b3240c84 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -7,7 +7,7 @@ use std::time::Duration;
use ai_memory_consolidate::{
AutoImproveReviewConfig, Consolidator, EmbedBackfillOptions, ScheduledAutoImproveSettings,
- run_auto_improve_scheduler_tick, run_embedding_backfill, run_lint, run_sweep,
+ run_auto_improve_scheduler_tick, run_embedding_backfill, run_lint, run_sweep_with_breadth,
};
use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};
use ai_memory_hooks::{
@@ -15,7 +15,9 @@ use ai_memory_hooks::{
workstream_router,
};
use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, build_embedder, build_provider};
-use ai_memory_mcp::{AdminState, AiMemoryServer, ScopeInvalidation, admin_router};
+use ai_memory_mcp::{
+ AdminState, AiMemoryServer, ScopeInvalidation, admin_router_with_decay_breadth,
+};
use ai_memory_store::{ReaderPool, Store, WriterHandle};
use ai_memory_web::{WebMountSpec, mount_web_router, normalize_prefix, web_base_href};
use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
@@ -449,9 +451,11 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
max_entries = config.auto_scope.max_entries,
"active-project isolation mode"
);
+ let decay_params = config.decay.decay_params();
let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
.with_wiki(wiki.clone())
- .with_decay_params(config.decay)
+ .with_decay_params(decay_params)
+ .with_decay_breadth_weight(config.decay.breadth_weight)
.with_auto_improve_require_approval(config.auto_improve.require_approval)
.with_auto_improve_review_config(auto_improve_review_config_from_settings(
&config.auto_improve,
@@ -604,33 +608,36 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
sanitizer: sanitizer.clone(),
data_dir: config.data_dir.clone(),
});
- let admin = admin_router(AdminState {
- writer: store.writer.clone(),
- reader: store.reader.clone(),
- wiki: wiki.clone(),
- llm: admin_llm,
- auto_improve_require_approval: config.auto_improve.require_approval,
- auto_improve_review_config: auto_improve_review_config_from_settings(
- &config.auto_improve,
- ),
- embedder: embedder.clone(),
- provider_health: provider_health.clone(),
- decay_params: config.decay,
- data_dir: config.data_dir.clone(),
- db_path: store.db_path().to_path_buf(),
- bind: bind.clone(),
- home_dir: config.home_dir.clone(),
- bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
- token_pepper: config
- .auth
- .token_pepper
- .as_ref()
- .filter(|p| !p.trim().is_empty())
- .map(|p| ai_memory_store::TokenPepper::new(p.clone())),
- active_project: active_project.clone(),
- scope_invalidator: Some(scope_invalidator),
- trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
- });
+ let admin = admin_router_with_decay_breadth(
+ AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki: wiki.clone(),
+ llm: admin_llm,
+ auto_improve_require_approval: config.auto_improve.require_approval,
+ auto_improve_review_config: auto_improve_review_config_from_settings(
+ &config.auto_improve,
+ ),
+ embedder: embedder.clone(),
+ provider_health: provider_health.clone(),
+ decay_params,
+ data_dir: config.data_dir.clone(),
+ db_path: store.db_path().to_path_buf(),
+ bind: bind.clone(),
+ home_dir: config.home_dir.clone(),
+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: config
+ .auth
+ .token_pepper
+ .as_ref()
+ .filter(|p| !p.trim().is_empty())
+ .map(|p| ai_memory_store::TokenPepper::new(p.clone())),
+ active_project: active_project.clone(),
+ scope_invalidator: Some(scope_invalidator),
+ trusted_proxy_identity: trusted_proxy_identity_enabled(&config.auth),
+ },
+ config.decay.breadth_weight,
+ );
// Multi-rung auth assembly:
// - rung 0 (no bearer_token configured) → AuthState::new
// stays as-is, middleware injects anonymous actor.
@@ -814,7 +821,7 @@ async fn start_maintenance_scheduler(
wiki: Wiki,
embedder: Option<Arc<dyn Embedder>>,
llm: Option<Arc<dyn LlmProvider>>,
- decay: ai_memory_store::DecayParams,
+ decay: crate::config::DecaySettings,
) -> Vec<tokio::task::JoinHandle<()>> {
let maintenance_enabled = settings.enabled;
if !maintenance_enabled {
@@ -857,8 +864,14 @@ async fn start_maintenance_scheduler(
let decay = decay;
async move {
let started = std::time::Instant::now();
- let outcome =
- run_scheduled_sweep_tick(&reader, &writer, &wiki, &decay).await?;
+ let outcome = run_scheduled_sweep_tick(
+ &reader,
+ &writer,
+ &wiki,
+ &decay.decay_params(),
+ decay.breadth_weight,
+ )
+ .await?;
if outcome.errors > 0 {
anyhow::bail!(
"scheduled forget sweep had {} scope errors",
@@ -1090,6 +1103,7 @@ async fn run_scheduled_sweep_tick(
writer: &WriterHandle,
wiki: &Wiki,
decay: &ai_memory_store::DecayParams,
+ breadth_weight: f64,
) -> Result<ScheduledSweepTickOutcome> {
let scopes = reader.list_all_scopes().await?;
let mut outcome = ScheduledSweepTickOutcome {
@@ -1098,13 +1112,14 @@ async fn run_scheduled_sweep_tick(
};
for scope in scopes {
- match run_sweep(
+ match run_sweep_with_breadth(
reader,
writer,
Some(wiki),
scope.workspace_id,
scope.project_id,
decay,
+ breadth_weight,
false,
)
.await
@@ -2020,7 +2035,7 @@ mod tests {
wiki,
None,
None,
- ai_memory_store::DecayParams::default(),
+ crate::config::DecaySettings::default(),
)
.await;
assert!(tasks.is_empty());
@@ -2064,7 +2079,7 @@ mod tests {
wiki,
None,
None,
- ai_memory_store::DecayParams::default(),
+ crate::config::DecaySettings::default(),
)
.await;
// One enabled lint/sweep job plus the independent hollow-project job.
@@ -2326,7 +2341,7 @@ mod tests {
cold_threshold: 2.0,
..ai_memory_store::DecayParams::default()
};
- let outcome = run_scheduled_sweep_tick(&store.reader, &store.writer, &wiki, &decay)
+ let outcome = run_scheduled_sweep_tick(&store.reader, &store.writer, &wiki, &decay, 0.0)
.await
.unwrap();
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index a93826d6..93b88290 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -39,6 +39,60 @@ pub const DEFAULT_WORKSPACE: &str = ai_memory_core::DEFAULT_WORKSPACE_NAME;
/// Defensive project fallback used only when no cwd/project is available.
pub const DEFAULT_PROJECT: &str = ai_memory_core::DEFAULT_PROJECT_NAME;
+/// Config-file representation of retention settings.
+///
+/// The breadth coefficient lives here rather than expanding the public
+/// `ai_memory_store::DecayParams` struct, preserving source compatibility for
+/// downstream Rust callers that construct that struct directly.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[serde(default)]
+pub struct DecaySettings {
+ /// Per-day decay rate.
+ pub lambda: f64,
+ /// Access-reinforcement magnitude.
+ pub sigma: f64,
+ /// Per-day decay of access reinforcement.
+ pub mu: f64,
+ /// Default page salience.
+ pub salience_default: f64,
+ /// Soft-delete threshold.
+ pub cold_threshold: f64,
+ /// Delay before hard-deleting an untouched soft-deleted page.
+ pub hard_delete_after_days: i64,
+ /// Optional weight for the number of distinct authenticated readers.
+ pub breadth_weight: f64,
+}
+
+impl Default for DecaySettings {
+ fn default() -> Self {
+ let base = ai_memory_store::DecayParams::default();
+ Self {
+ lambda: base.lambda,
+ sigma: base.sigma,
+ mu: base.mu,
+ salience_default: base.salience_default,
+ cold_threshold: base.cold_threshold,
+ hard_delete_after_days: base.hard_delete_after_days,
+ breadth_weight: 0.0,
+ }
+ }
+}
+
+impl DecaySettings {
+ /// Retention coefficients consumed by existing store/consolidation APIs.
+ #[must_use]
+ pub fn decay_params(self) -> ai_memory_store::DecayParams {
+ ai_memory_store::DecayParams {
+ lambda: self.lambda,
+ sigma: self.sigma,
+ mu: self.mu,
+ salience_default: self.salience_default,
+ cold_threshold: self.cold_threshold,
+ hard_delete_after_days: self.hard_delete_after_days,
+ }
+ }
+}
+
/// Top-level runtime configuration.
///
/// `deny_unknown_fields` is intentionally NOT set: figment's
@@ -124,7 +178,7 @@ pub struct Config {
/// threshold), followed by ~180 days of soft-delete buffer before
/// hard-deletion. Tune `decay.lambda` down to slow decay or
/// `decay.cold_threshold` to evict more / less aggressively.
- pub decay: ai_memory_store::DecayParams,
+ pub decay: DecaySettings,
/// Server-side scheduled maintenance. Jobs run outside hook latency.
pub maintenance: MaintenanceSettings,
/// Memory-slot behaviour.
@@ -446,7 +500,7 @@ impl Default for Config {
embedding_model: None,
embedding_dim: None,
embedding_base_url: None,
- decay: ai_memory_store::DecayParams::default(),
+ decay: DecaySettings::default(),
maintenance: MaintenanceSettings::default(),
slots: SlotSettings::default(),
auto_improve: AutoImproveSettings::default(),
@@ -750,6 +804,12 @@ impl Config {
config.data_dir = canonicalise_or_keep(&config.data_dir);
config.runtime_env = runtime_env;
+ if !config.decay.breadth_weight.is_finite() || config.decay.breadth_weight < 0.0 {
+ anyhow::bail!(
+ "decay.breadth_weight must be a finite number greater than or equal to zero"
+ );
+ }
+
Ok(config)
}
@@ -1110,6 +1170,7 @@ mod tests {
assert_eq!(cfg.maintenance.forget_sweep_interval_secs, 86_400);
assert_eq!(cfg.maintenance.lint_interval_secs, 86_400);
assert_eq!(cfg.maintenance.embedding_backfill_interval_secs, 0);
+ assert_eq!(cfg.decay.breadth_weight, 0.0);
assert!(!cfg.slots.per_user);
assert!(cfg.auto_improve.scheduler.enabled);
assert_eq!(cfg.auto_improve.scheduler.interval_secs, 3_600);
@@ -1163,6 +1224,21 @@ mod tests {
);
}
+ #[test]
+ fn load_rejects_destructive_invalid_breadth_weights() {
+ for value in ["-0.1", "nan", "inf"] {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("config.toml");
+ std::fs::write(&config_path, format!("[decay]\nbreadth_weight = {value}\n")).unwrap();
+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf()))
+ .expect_err("invalid breadth weight must fail closed");
+ assert!(
+ error.to_string().contains("breadth_weight"),
+ "unexpected error for {value}: {error:#}"
+ );
+ }
+ }
+
#[test]
fn load_populates_home_dir_from_env() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.toml
index 49496e19..ec8805d6 100644
--- a/crates/ai-memory-cli/templates/config.default.toml
+++ b/crates/ai-memory-cli/templates/config.default.toml
@@ -48,6 +48,8 @@ log_level = "info"
# Formula:
# retention = salience * exp(-lambda * age_days)
# + sigma * log(1 + access_count) * exp(-mu * days_since_access)
+# * (1 + breadth_weight
+# * ln(1 + max(distinct_actors - 1, 0)))
#
# With the defaults below, an unused episodic page drops below
# `cold_threshold = 0.20` at ~80 days; recent accesses bump it back up.
@@ -57,6 +59,7 @@ log_level = "info"
# - Faster decay (clean up more aggressively): lambda = 0.04 (~40d floor)
# - Bigger access boost (frequently-used stuff lasts longer): sigma = 1.0
# - Bigger time-pressure on access: mu = 0.08
+# - Reward pages used by more identified operators: breadth_weight = 0.2
[decay]
lambda = 0.02
sigma = 0.6
@@ -64,6 +67,7 @@ mu = 0.04
salience_default = 1.0
cold_threshold = 0.20
hard_delete_after_days = 180
+breadth_weight = 0.0
# Privacy strip.
#
diff --git a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs b/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
index 3c95d8b3..96c65312 100644
--- a/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
+++ b/crates/ai-memory-consolidate/src/auto_improve_schedule.rs
@@ -282,56 +282,49 @@ async fn run_scheduled_auto_improve(
.await?;
let staged = ctx
.writer
- .stage_auto_improve_run(StageAutoImproveRun {
- workspace_id: ctx.workspace_id,
- project_id: ctx.project_id,
- session_id: Some(session_id),
- provider: Some(report.provider.clone()),
- model: Some(report.model.clone()),
- summary: Some(report.summary.clone()),
- warnings_json: serde_json::to_value(&report.warnings)
- .unwrap_or_else(|_| serde_json::json!([])),
- rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
- .unwrap_or_else(|_| serde_json::json!([])),
- config_json: serde_json::json!({
- "trigger": "scheduler",
- "min_observations": cfg.min_observations,
- "min_session_duration_secs": cfg.min_session_duration_secs,
- "min_confidence": cfg.min_confidence,
- "max_input_tokens": cfg.max_input_tokens,
- "max_proposals_per_run": cfg.max_proposals_per_run,
- "include_raw_fallback": cfg.include_raw_fallback,
- "max_patchable_pages": cfg.max_patchable_pages,
- "max_patchable_body_chars": cfg.max_patchable_body_chars,
- "max_edits_per_proposal": cfg.max_edits_per_proposal,
- "max_edit_content_chars": cfg.max_edit_content_chars,
- "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
- "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
- "max_rejection_context": cfg.max_rejection_context,
- "rejection_context_days": cfg.rejection_context_days,
- "max_final_body_chars": cfg.max_final_body_chars,
- "max_rule_page_tokens": cfg.max_rule_page_tokens,
- "max_procedure_page_tokens": cfg.max_procedure_page_tokens,
- "eval": cfg.eval,
- "require_approval": ctx.settings.require_approval,
- }),
- proposal_actor: ActorContext {
- agent: Some(cfg.proposal_actor.clone()),
- ..ActorContext::default()
+ .stage_auto_improve_run_for_owner(
+ StageAutoImproveRun {
+ workspace_id: ctx.workspace_id,
+ project_id: ctx.project_id,
+ session_id: Some(session_id),
+ provider: Some(report.provider.clone()),
+ model: Some(report.model.clone()),
+ summary: Some(report.summary.clone()),
+ warnings_json: serde_json::to_value(&report.warnings)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ config_json: serde_json::json!({
+ "trigger": "scheduler",
+ "min_observations": cfg.min_observations,
+ "min_session_duration_secs": cfg.min_session_duration_secs,
+ "min_confidence": cfg.min_confidence,
+ "max_input_tokens": cfg.max_input_tokens,
+ "max_proposals_per_run": cfg.max_proposals_per_run,
+ "include_raw_fallback": cfg.include_raw_fallback,
+ "max_patchable_pages": cfg.max_patchable_pages,
+ "max_patchable_body_chars": cfg.max_patchable_body_chars,
+ "max_edits_per_proposal": cfg.max_edits_per_proposal,
+ "max_edit_content_chars": cfg.max_edit_content_chars,
+ "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
+ "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
+ "max_rejection_context": cfg.max_rejection_context,
+ "rejection_context_days": cfg.rejection_context_days,
+ "max_final_body_chars": cfg.max_final_body_chars,
+ "max_rule_page_tokens": cfg.max_rule_page_tokens,
+ "max_procedure_page_tokens": cfg.max_procedure_page_tokens,
+ "eval": cfg.eval,
+ "require_approval": ctx.settings.require_approval,
+ }),
+ proposal_actor: ActorContext {
+ agent: Some(cfg.proposal_actor.clone()),
+ ..ActorContext::default()
+ },
+ proposals,
},
- 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,
- })
+ None,
+ )
.await?;
-
for id in &staged.proposal_ids {
ctx.wiki
.write_auto_improve_sidecar(ctx.workspace_id, ctx.project_id, *id)
@@ -677,6 +670,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -725,7 +719,6 @@ mod tests {
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(),
diff --git a/crates/ai-memory-consolidate/src/curator.rs b/crates/ai-memory-consolidate/src/curator.rs
index 3c60e4bd..22b1ca9f 100644
--- a/crates/ai-memory-consolidate/src/curator.rs
+++ b/crates/ai-memory-consolidate/src/curator.rs
@@ -83,6 +83,38 @@ pub async fn run_curator_report(
project_name: &str,
params: CuratorParams,
) -> ai_memory_store::StoreResult<CuratorReport> {
+ run_curator_report_with_breadth(
+ reader,
+ workspace_id,
+ project_id,
+ workspace_name,
+ project_name,
+ params,
+ 0.0,
+ )
+ .await
+}
+
+/// Build a curator report using the same optional access-breadth term as the
+/// forget sweep.
+///
+/// # Errors
+/// Propagates store failures and rejects negative or non-finite breadth
+/// coefficients.
+pub async fn run_curator_report_with_breadth(
+ reader: &ReaderPool,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ workspace_name: &str,
+ project_name: &str,
+ params: CuratorParams,
+ breadth_weight: f64,
+) -> ai_memory_store::StoreResult<CuratorReport> {
+ if !breadth_weight.is_finite() || breadth_weight < 0.0 {
+ return Err(ai_memory_store::StoreError::InvalidState(
+ "decay breadth_weight must be a finite number greater than or equal to zero".into(),
+ ));
+ }
let now = Timestamp::now();
let now_us = now.as_microsecond();
let mut findings = Vec::new();
@@ -93,7 +125,7 @@ pub async fn run_curator_report(
// 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, &params.decay_params).await?;
+ access_breadth_for_scoring(reader, workspace_id, project_id, breadth_weight).await?;
let mut cold = Vec::new();
for c in &candidates {
if c.tier != Tier::Episodic || c.pinned || frontmatter_pinned(&c.frontmatter_json) {
@@ -108,6 +140,7 @@ pub async fn run_curator_report(
days_since_access,
c.salience,
breadth.get(&c.id).copied().unwrap_or(0),
+ breadth_weight,
);
if score < params.decay_params.cold_threshold {
cold.push(CuratorFinding {
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 482beef3..85c9946d 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -56,13 +56,13 @@ pub use consolidator::{
};
pub use curator::{
CuratorFinding, CuratorParams, CuratorReport, render_curator_report_markdown,
- run_curator_report,
+ run_curator_report, run_curator_report_with_breadth,
};
pub use embed::{
EmbedBackfillCounts, EmbedBackfillError, EmbedBackfillOptions, run_embedding_backfill,
};
pub use lint::{LintError, LintFinding, LintReport, run_lint};
-pub use sweep::{EvictedPage, SweepError, SweepReport, run_sweep};
+pub use sweep::{EvictedPage, SweepError, SweepReport, run_sweep, run_sweep_with_breadth};
pub use types::{
ConsolidatedBatch, ConsolidatedPage, ConsolidatedPageUpdate, ConsolidationOutcome, PageKind,
SlotKind,
diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rs
index 7e6b6f69..d319c020 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -84,6 +84,9 @@ pub enum SweepError {
/// Underlying store error.
#[error(transparent)]
Store(#[from] ai_memory_store::StoreError),
+ /// The optional access-breadth coefficient was negative or non-finite.
+ #[error("decay breadth_weight must be a finite number greater than or equal to zero")]
+ InvalidBreadthWeight,
}
const US_PER_DAY: f64 = 86_400_000_000.0;
@@ -111,8 +114,41 @@ pub async fn run_sweep(
params: &DecayParams,
dry_run: bool,
) -> Result<SweepReport, SweepError> {
+ run_sweep_with_breadth(
+ reader,
+ writer,
+ wiki,
+ workspace_id,
+ project_id,
+ params,
+ 0.0,
+ dry_run,
+ )
+ .await
+}
+
+/// Run a sweep with an opt-in access-breadth coefficient.
+///
+/// # Errors
+/// Returns [`SweepError::InvalidBreadthWeight`] for negative or non-finite
+/// coefficients, in addition to the errors documented by [`run_sweep`].
+#[allow(clippy::too_many_arguments)]
+pub async fn run_sweep_with_breadth(
+ reader: &ReaderPool,
+ writer: &WriterHandle,
+ wiki: Option<&Wiki>,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ params: &DecayParams,
+ breadth_weight: f64,
+ dry_run: bool,
+) -> Result<SweepReport, SweepError> {
+ if !breadth_weight.is_finite() || breadth_weight < 0.0 {
+ return Err(SweepError::InvalidBreadthWeight);
+ }
let candidates = reader.decay_candidates(workspace_id, project_id).await?;
- let breadth = access_breadth_for_scoring(reader, workspace_id, project_id, params).await?;
+ let breadth =
+ access_breadth_for_scoring(reader, workspace_id, project_id, breadth_weight).await?;
let now_us = Timestamp::now().as_microsecond();
let mut evicted = Vec::new();
@@ -145,6 +181,7 @@ pub async fn run_sweep(
days_since_access,
c.salience,
breadth.get(&c.id).copied().unwrap_or(0),
+ breadth_weight,
);
if score < params.cold_threshold {
evicted.push(EvictedPage {
@@ -223,9 +260,9 @@ pub(crate) async fn access_breadth_for_scoring(
reader: &ReaderPool,
workspace_id: WorkspaceId,
project_id: ProjectId,
- params: &DecayParams,
+ breadth_weight: f64,
) -> ai_memory_store::StoreResult<HashMap<PageId, u32>> {
- if params.breadth_weight == 0.0 {
+ if breadth_weight == 0.0 {
return Ok(HashMap::new());
}
reader
diff --git a/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs b/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs
index dbf8cd55..59db0a8c 100644
--- a/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs
+++ b/crates/ai-memory-consolidate/tests/access_breadth_sweep.rs
@@ -10,7 +10,10 @@
//! 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_consolidate::{
+ CuratorParams, CuratorReport, run_curator_report_with_breadth, run_sweep,
+ run_sweep_with_breadth,
+};
use ai_memory_core::{IdentityKey, NewPage, PageId, PagePath, ProjectId, Tier, WorkspaceId};
use ai_memory_store::{DecayParams, Store, WriterHandle, retention_score};
use rusqlite::params;
@@ -45,19 +48,13 @@ async fn seed(store: &Store) -> (WorkspaceId, ProjectId) {
for actor in ["alice", "bob", "carol", "dave", "erin"] {
store
.writer
- .bump_access(
- vec![team],
- Some(IdentityKey::User(actor.into()).storage_key()),
- )
+ .bump_access_for_actor(vec![team], Some(IdentityKey::User(actor.into())))
.await
.expect("bump team");
}
store
.writer
- .bump_access(
- vec![solo],
- Some(IdentityKey::User("alice".into()).storage_key()),
- )
+ .bump_access_for_actor(vec![solo], Some(IdentityKey::User("alice".into())))
.await
.expect("bump solo");
@@ -112,7 +109,6 @@ async fn default_weight_scores_identically_however_many_operators_read_the_page(
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, &params, true)
.await
.expect("sweep");
@@ -147,13 +143,19 @@ async fn a_page_many_operators_read_outlives_one_read_as_often_by_a_single_opera
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, &params, true)
- .await
- .expect("sweep");
+ let params = DecayParams::default();
+ let report = run_sweep_with_breadth(
+ &store.reader,
+ &store.writer,
+ None,
+ ws,
+ proj,
+ &params,
+ 1.5,
+ true,
+ )
+ .await
+ .expect("sweep");
assert_eq!(
report
@@ -166,6 +168,46 @@ async fn a_page_many_operators_read_outlives_one_read_as_often_by_a_single_opera
);
}
+#[tokio::test]
+async fn destructive_readers_reject_invalid_breadth_coefficients() {
+ let tmp = TempDir::new().expect("tempdir");
+ let store = Store::open(tmp.path()).expect("store");
+ let (ws, proj) = seed(&store).await;
+ let params = DecayParams::default();
+
+ for weight in [-1.0, f64::NAN, f64::INFINITY] {
+ let sweep_error = run_sweep_with_breadth(
+ &store.reader,
+ &store.writer,
+ None,
+ ws,
+ proj,
+ &params,
+ weight,
+ false,
+ )
+ .await
+ .expect_err("an invalid coefficient must stop the sweep before mutation");
+ assert!(sweep_error.to_string().contains("breadth_weight"));
+
+ let curator_error = run_curator_report_with_breadth(
+ &store.reader,
+ ws,
+ proj,
+ "default",
+ "breadth",
+ CuratorParams {
+ decay_params: params,
+ ..CuratorParams::default()
+ },
+ weight,
+ )
+ .await
+ .expect_err("the curator must reject the same invalid coefficient");
+ assert!(curator_error.to_string().contains("breadth_weight"));
+ }
+}
+
/// `(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
@@ -196,8 +238,9 @@ async fn curate(
ws: WorkspaceId,
proj: ProjectId,
decay: DecayParams,
+ breadth_weight: f64,
) -> CuratorReport {
- run_curator_report(
+ run_curator_report_with_breadth(
&store.reader,
ws,
proj,
@@ -207,6 +250,7 @@ async fn curate(
decay_params: decay,
..CuratorParams::default()
},
+ breadth_weight,
)
.await
.expect("curator")
@@ -225,8 +269,7 @@ async fn curator_scores_match_the_pre_breadth_formula_at_the_default_weight() {
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 report = curate(&store, ws, proj, params, 0.0).await;
let cold = cold_findings(&report);
assert_eq!(
@@ -257,14 +300,20 @@ async fn the_curator_reports_cold_exactly_when_the_sweep_would_evict() {
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, &params, true)
- .await
- .expect("sweep");
- let cold = cold_findings(&curate(&store, ws, proj, params).await);
+ let params = DecayParams::default();
+ let sweep = run_sweep_with_breadth(
+ &store.reader,
+ &store.writer,
+ None,
+ ws,
+ proj,
+ &params,
+ 1.5,
+ true,
+ )
+ .await
+ .expect("sweep");
+ let cold = cold_findings(&curate(&store, ws, proj, params, 1.5).await);
let mut evicted: Vec<&str> = sweep.evicted.iter().map(|e| e.path.as_str()).collect();
evicted.sort_unstable();
diff --git a/crates/ai-memory-core/src/actor.rs b/crates/ai-memory-core/src/actor.rs
index 24e89262..ecc1a678 100644
--- a/crates/ai-memory-core/src/actor.rs
+++ b/crates/ai-memory-core/src/actor.rs
@@ -343,6 +343,16 @@ pub enum IdentityKey {
}
impl IdentityKey {
+ /// Whether this value satisfies the same non-blank, trimmed invariants as
+ /// [`ActorContext::identity_key`].
+ ///
+ /// The enum is public, so storage boundaries use this check before
+ /// accepting a directly constructed value.
+ #[must_use]
+ pub fn is_valid(&self) -> bool {
+ self.to_actor_context().identity_key().as_ref() == Some(self)
+ }
+
/// The TEXT form used for in-memory routing and future owner columns:
/// `oidc:<issuer-byte-length>:<issuer><subject>` or `user:<name>`.
///
@@ -414,7 +424,7 @@ impl IdentityKey {
// trims and rejects blanks. Enforce the same invariant on persisted
// data so a corrupt `user:` / partial OIDC key cannot become a new
// ownership bucket when a session is finalized.
- (parsed.to_actor_context().identity_key().as_ref() == Some(&parsed)).then_some(parsed)
+ parsed.is_valid().then_some(parsed)
}
/// Build an actor that round-trips through [`ActorContext::identity_key`].
@@ -474,15 +484,25 @@ impl OwnerFilter {
/// A single-operator server leaves rows shared even when its HTTP root has a
/// username, because the same operator's stdio transport carries no actor.
#[must_use]
-pub fn owner_stamp(
+pub fn owner_identity(
identity: Option<&IdentityKey>,
distinguishes_operators: bool,
-) -> Option<String> {
+) -> Option<IdentityKey> {
distinguishes_operators
- .then(|| identity.map(IdentityKey::storage_key))
+ .then(|| identity.filter(|identity| identity.is_valid()).cloned())
.flatten()
}
+/// Derive the qualified owner string stored by an operator-distinguishing
+/// deployment.
+#[must_use]
+pub fn owner_stamp(
+ identity: Option<&IdentityKey>,
+ distinguishes_operators: bool,
+) -> Option<String> {
+ owner_identity(identity, distinguishes_operators).map(|identity| identity.storage_key())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -738,6 +758,13 @@ mod tests {
issuer: "https://idp.example".into(),
subject: "oidc-subject-123".into(),
};
+ assert_eq!(owner_identity(Some(&key), false), None);
+ assert_eq!(owner_identity(None, true), None);
+ assert_eq!(owner_identity(Some(&key), true), Some(key.clone()));
+ assert_eq!(
+ owner_identity(Some(&IdentityKey::User(" ".into())), true),
+ None
+ );
assert_eq!(owner_stamp(Some(&key), false), None);
assert_eq!(owner_stamp(None, true), None);
assert_eq!(owner_stamp(Some(&key), true), Some(key.storage_key()));
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index ca5a2402..088c9548 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -40,7 +40,8 @@ pub use active_project::{
};
pub use actor::{
ActorContext, AuthLevel, AuthzError, Capability, IdentityKey, OwnerFilter,
- SKIP_ADMISSION_CHAIN_HEADER, owner_stamp, parse_skip_admission_chain, skip_admission_chain_for,
+ SKIP_ADMISSION_CHAIN_HEADER, owner_identity, owner_stamp, parse_skip_admission_chain,
+ skip_admission_chain_for,
};
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffAcceptance, HandoffState, NewHandoff};
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 1434d918..8c3924d4 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -46,8 +46,8 @@ use ai_memory_consolidate::{
BootstrapConfig, BootstrapOutcome, BootstrapSource, CuratorParams, CuratorReport,
EmbedBackfillCounts, EmbedBackfillOptions, SourceCounts, prune_sources_to_budget,
render_auto_improve_telemetry_report_markdown, render_curator_report_markdown,
- run_auto_improve_review, run_auto_improve_telemetry_report, run_curator_report,
- run_embedding_backfill, run_lint, run_sweep,
+ run_auto_improve_review, run_auto_improve_telemetry_report, run_curator_report_with_breadth,
+ run_embedding_backfill, run_lint, run_sweep_with_breadth,
};
use ai_memory_core::{
ActiveProject, AgentKind, AutoImproveProposalId, Capability, DEFAULT_PROJECT_NAME,
@@ -77,6 +77,9 @@ use tracing::{info, warn};
const CONTRIBUTORS_WEBHOOK_NAME: &str = "contributors";
+#[derive(Clone, Copy)]
+struct DecayBreadthWeight(f64);
+
/// Shared state for the admin router.
#[derive(Clone)]
pub struct AdminState {
@@ -521,6 +524,11 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {
/// - `POST /admin/delete-page`
/// - user-management routes under `/admin/users*`
pub fn admin_router(state: AdminState) -> Router {
+ admin_router_with_decay_breadth(state, 0.0)
+}
+
+/// Build the admin router with the optional distinct-reader retention weight.
+pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -> Router {
let state = Arc::new(state);
let operational = Router::new()
.route("/admin/backup", post(handle_backup))
@@ -590,6 +598,7 @@ pub fn admin_router(state: AdminState) -> Router {
require_root_for_multiuser_admin,
))
.with_state(state)
+ .layer(axum::Extension(DecayBreadthWeight(breadth_weight)))
}
async fn require_root_for_multiuser_admin(
@@ -1497,11 +1506,11 @@ async fn handle_auto_improve(
// 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" —
+ // human is this", `owner_identity` 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(
+ let staging_owner = ai_memory_core::owner_identity(
actor_ext
.as_ref()
.and_then(|axum::Extension(actor)| actor.identity_key())
@@ -1520,7 +1529,7 @@ async fn handle_auto_improve(
proj,
session_id: req.session_id,
cfg: &cfg,
- staged_by_actor_user,
+ staging_owner,
},
&report,
proposals,
@@ -1711,9 +1720,9 @@ struct AutoImproveStagingScope<'a> {
proj: ProjectId,
session_id: SessionId,
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>,
+ /// Typed operator that staged the run; also scopes the
+ /// one-pending-per-target rule.
+ staging_owner: Option<ai_memory_core::IdentityKey>,
}
async fn stage_auto_improve_report(
@@ -1727,50 +1736,50 @@ async fn stage_auto_improve_report(
proj,
session_id,
cfg,
- staged_by_actor_user,
+ staging_owner,
} = scope;
let staged = state
.writer
- .stage_auto_improve_run(StageAutoImproveRun {
- workspace_id: ws,
- project_id: proj,
- session_id: Some(session_id),
- provider: Some(report.provider.clone()),
- model: Some(report.model.clone()),
- summary: Some(report.summary.clone()),
- warnings_json: serde_json::to_value(&report.warnings)
- .unwrap_or_else(|_| serde_json::json!([])),
- rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
- .unwrap_or_else(|_| serde_json::json!([])),
- config_json: serde_json::json!({
- "min_observations": cfg.min_observations,
- "min_session_duration_secs": cfg.min_session_duration_secs,
- "min_confidence": cfg.min_confidence,
- "max_input_tokens": cfg.max_input_tokens,
- "max_proposals_per_run": cfg.max_proposals_per_run,
- "include_raw_fallback": cfg.include_raw_fallback,
- "max_patchable_pages": cfg.max_patchable_pages,
- "max_patchable_body_chars": cfg.max_patchable_body_chars,
- "max_edits_per_proposal": cfg.max_edits_per_proposal,
- "max_edit_content_chars": cfg.max_edit_content_chars,
- "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
- "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
- "max_rejection_context": cfg.max_rejection_context,
- "rejection_context_days": cfg.rejection_context_days,
- "max_final_body_chars": cfg.max_final_body_chars,
- "max_rule_page_tokens": cfg.max_rule_page_tokens,
- "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()
+ .stage_auto_improve_run_for_owner(
+ StageAutoImproveRun {
+ workspace_id: ws,
+ project_id: proj,
+ session_id: Some(session_id),
+ provider: Some(report.provider.clone()),
+ model: Some(report.model.clone()),
+ summary: Some(report.summary.clone()),
+ warnings_json: serde_json::to_value(&report.warnings)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ config_json: serde_json::json!({
+ "min_observations": cfg.min_observations,
+ "min_session_duration_secs": cfg.min_session_duration_secs,
+ "min_confidence": cfg.min_confidence,
+ "max_input_tokens": cfg.max_input_tokens,
+ "max_proposals_per_run": cfg.max_proposals_per_run,
+ "include_raw_fallback": cfg.include_raw_fallback,
+ "max_patchable_pages": cfg.max_patchable_pages,
+ "max_patchable_body_chars": cfg.max_patchable_body_chars,
+ "max_edits_per_proposal": cfg.max_edits_per_proposal,
+ "max_edit_content_chars": cfg.max_edit_content_chars,
+ "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
+ "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
+ "max_rejection_context": cfg.max_rejection_context,
+ "rejection_context_days": cfg.rejection_context_days,
+ "max_final_body_chars": cfg.max_final_body_chars,
+ "max_rule_page_tokens": cfg.max_rule_page_tokens,
+ "max_procedure_page_tokens": cfg.max_procedure_page_tokens,
+ "eval": cfg.eval,
+ }),
+ proposal_actor: ai_memory_core::ActorContext {
+ agent: Some(cfg.proposal_actor.clone()),
+ ..ai_memory_core::ActorContext::default()
+ },
+ proposals,
},
- proposals,
- })
+ staging_owner,
+ )
.await
.map_err(|e| internal_err(e.to_string()))?;
let sidecar_paths = write_auto_improve_sidecars(state, ws, proj, &staged.proposal_ids).await?;
@@ -1869,7 +1878,8 @@ async fn handle_auto_improve_report(
let operation = target_operation_for_page(&state, ws, proj, &target).await?;
let staged = state
.writer
- .stage_auto_improve_run(StageAutoImproveRun {
+ .stage_auto_improve_run_for_owner(
+ StageAutoImproveRun {
workspace_id: ws,
project_id: proj,
session_id: None,
@@ -1883,12 +1893,6 @@ 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()
@@ -1911,7 +1915,9 @@ async fn handle_auto_improve_report(
patch_json: None,
expected_base_body_sha256: None,
}],
- })
+ },
+ None,
+ )
.await
.map_err(|e| internal_err(e.to_string()))?;
let sidecar_paths =
@@ -1942,6 +1948,7 @@ async fn handle_auto_improve_report(
async fn handle_curator(
State(state): State<Arc<AdminState>>,
+ axum::Extension(breadth): axum::Extension<DecayBreadthWeight>,
Json(req): Json<CuratorRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let mode = req.mode.as_deref().map(str::trim).filter(|s| !s.is_empty());
@@ -1965,13 +1972,14 @@ async fn handle_curator(
let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
let params = CuratorParams::default();
- let mut report = run_curator_report(
+ let mut report = run_curator_report_with_breadth(
&state.reader,
ws,
proj,
&req.workspace,
&req.project,
params.clone(),
+ breadth.0,
)
.await
.map_err(|e| internal_err(e.to_string()))?;
@@ -1995,47 +2003,46 @@ async fn handle_curator(
let operation = target_operation_for_page(&state, ws, proj, &target).await?;
let staged = state
- .writer
- .stage_auto_improve_run(StageAutoImproveRun {
- workspace_id: ws,
- project_id: proj,
- session_id: None,
- provider: None,
- model: None,
- summary: Some(report.summary.clone()),
- warnings_json: serde_json::json!([]),
- rejected_candidates_json: serde_json::json!([]),
- config_json: serde_json::json!({
- "mode": "stage",
- "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()
- },
- proposals: vec![NewAutoImproveProposal {
- operation,
- target_path: target,
- kind: "curator_report".into(),
- title: "Curator Report".into(),
- confidence: 1.0,
- rationale: "Rule-based curator report only; approval writes the report page and performs no maintenance actions.".into(),
- evidence_json: serde_json::json!({
- "summary": report.summary.clone(),
- "findings": report.findings.clone(),
- }),
- body_markdown,
- artifact_sha256: None,
- edit_mode: None,
- patch_json: None,
- expected_base_body_sha256: None,
- }],
- })
+ .writer
+ .stage_auto_improve_run_for_owner(
+ StageAutoImproveRun {
+ workspace_id: ws,
+ project_id: proj,
+ session_id: None,
+ provider: None,
+ model: None,
+ summary: Some(report.summary.clone()),
+ warnings_json: serde_json::json!([]),
+ rejected_candidates_json: serde_json::json!([]),
+ config_json: serde_json::json!({
+ "mode": "stage",
+ "curator": true,
+ "params": params,
+ }),
+ proposal_actor: ai_memory_core::ActorContext {
+ agent: Some("curator".into()),
+ ..ai_memory_core::ActorContext::default()
+ },
+ proposals: vec![NewAutoImproveProposal {
+ operation,
+ target_path: target,
+ kind: "curator_report".into(),
+ title: "Curator Report".into(),
+ confidence: 1.0,
+ rationale: "Rule-based curator report only; approval writes the report page and performs no maintenance actions.".into(),
+ evidence_json: serde_json::json!({
+ "summary": report.summary.clone(),
+ "findings": report.findings.clone(),
+ }),
+ body_markdown,
+ artifact_sha256: None,
+ edit_mode: None,
+ patch_json: None,
+ expected_base_body_sha256: None,
+ }],
+ },
+ None,
+ )
.await
.map_err(|e| internal_err(e.to_string()))?;
let sidecar_paths = write_auto_improve_sidecars(&state, ws, proj, &staged.proposal_ids).await?;
@@ -2116,7 +2123,7 @@ async fn pending_detail(
(
WorkspaceId,
ProjectId,
- ai_memory_store::AutoImproveProposalDetail,
+ ai_memory_store::OwnedAutoImproveProposalDetail,
),
(StatusCode, Json<serde_json::Value>),
> {
@@ -2129,7 +2136,7 @@ async fn pending_detail(
let (ws, proj) = lookup_ws_proj_no_create(state, &query.workspace, &query.project).await?;
let detail = state
.reader
- .auto_improve_proposal_detail(ws, proj, id)
+ .auto_improve_proposal_detail_with_owner(ws, proj, id)
.await
.map_err(|e| internal_err(e.to_string()))?
.ok_or_else(|| {
@@ -2161,7 +2168,8 @@ async fn handle_pending_write_diff(
Query(query): Query<PendingWriteScopeQuery>,
) -> impl IntoResponse {
match pending_detail(&state, &id, &query).await {
- Ok((ws, proj, detail)) => {
+ Ok((ws, proj, owned)) => {
+ let detail = &owned.detail;
let before = state
.reader
.page_body_by_ids(ws, proj, detail.summary.target_path.as_str())
@@ -2598,17 +2606,19 @@ struct ForgetSweepRequest {
async fn handle_forget_sweep(
State(state): State<Arc<AdminState>>,
+ axum::Extension(breadth): axum::Extension<DecayBreadthWeight>,
Json(req): Json<ForgetSweepRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
- run_sweep(
+ run_sweep_with_breadth(
&state.reader,
&state.writer,
Some(&state.wiki),
ws,
proj,
&state.decay_params,
+ breadth.0,
req.dry_run,
)
.await
@@ -5592,7 +5602,6 @@ 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()
@@ -5939,24 +5948,13 @@ 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
+ /// [`ai_memory_core::owner_identity`], not on `actor.user`, so an operator
+ /// identified by a complete OIDC issuer/subject pair lands in an
+ /// issuer-qualified bucket rather than the unattributed one. The
+ /// `memory_auto_improve` MCP tool computes the same bucket, 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() {
+ async fn auto_improve_buckets_an_oidc_operator_by_qualified_identity() {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
let wiki = Wiki::new(tmp.path(), store.writer.clone())
@@ -5998,6 +5996,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -6046,7 +6045,8 @@ mod tests {
))
.unwrap();
req.extensions_mut().insert(ai_memory_core::ActorContext {
- sub: Some("oidc|subject-only-42".into()),
+ issuer: Some("https://issuer.example".into()),
+ sub: Some("subject-42".into()),
..ai_memory_core::ActorContext::anonymous()
});
req.extensions_mut().insert(ai_memory_core::AuthLevel::Root);
@@ -6056,8 +6056,11 @@ mod tests {
// 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 expected_bucket = ai_memory_core::IdentityKey::Subject {
+ issuer: "https://issuer.example".into(),
+ subject: "subject-42".into(),
+ }
+ .storage_key();
let staged = store
.reader
.list_auto_improve_proposals(ws, proj, None, 10)
@@ -6067,7 +6070,7 @@ mod tests {
for proposal in &staged {
let detail = store
.reader
- .auto_improve_proposal_detail(ws, proj, proposal.id)
+ .auto_improve_proposal_detail_with_owner(ws, proj, proposal.id)
.await
.unwrap()
.expect("staged proposal readable in its own scope");
@@ -6075,7 +6078,14 @@ mod tests {
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()
+ detail.detail.summary.target_path.as_str()
+ );
+ let json = serde_json::to_value(&detail).unwrap();
+ assert_eq!(json["staged_by_actor_user"], expected_bucket);
+ assert!(json.get("summary").is_some(), "detail fields stay flat");
+ assert!(
+ json.get("detail").is_none(),
+ "no nested compatibility wrapper"
);
}
}
@@ -6125,6 +6135,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -6241,6 +6252,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
diff --git a/crates/ai-memory-mcp/src/lib.rs b/crates/ai-memory-mcp/src/lib.rs
index c59a9ba2..9176704e 100644
--- a/crates/ai-memory-mcp/src/lib.rs
+++ b/crates/ai-memory-mcp/src/lib.rs
@@ -14,5 +14,7 @@ pub mod auth;
mod server;
pub use actor::actor_from_headers;
-pub use admin::{AdminState, ScopeInvalidation, ScopeInvalidator, admin_router};
+pub use admin::{
+ AdminState, ScopeInvalidation, ScopeInvalidator, admin_router, admin_router_with_decay_breadth,
+};
pub use server::{AiMemoryServer, MEMORY_INSTRUCTIONS};
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 157ff9b3..a9ce99c2 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
use ai_memory_consolidate::{
AutoImproveReviewConfig, Consolidator, projection::cap_text_with_marker,
- run_auto_improve_review, run_lint, run_sweep,
+ run_auto_improve_review, run_lint, run_sweep_with_breadth,
};
use ai_memory_core::{
ActiveProject, AgentKind, FeedbackKind, HandoffId, HandoffState, NewHandoff, PageId, PagePath,
@@ -366,6 +366,8 @@ pub struct AiMemoryServer {
/// M8 retention parameters. Defaults if not overridden by the
/// caller (typically from the user's config.toml `[decay]` block).
decay_params: DecayParams,
+ /// Optional distinct-reader reinforcement coefficient.
+ decay_breadth_weight: f64,
/// M9 embedder for hybrid query. When `None`, `memory_query`
/// still fuses FTS5 with entity matches and graph-neighbour expansion.
embedder: Option<Arc<dyn Embedder>>,
@@ -1000,6 +1002,7 @@ impl AiMemoryServer {
llm: None,
wiki: None,
decay_params: DecayParams::default(),
+ decay_breadth_weight: 0.0,
embedder: None,
reranker: None,
rerank_gate: Arc::new(tokio::sync::Semaphore::new(RERANK_MAX_IN_FLIGHT)),
@@ -1476,6 +1479,13 @@ impl AiMemoryServer {
self
}
+ /// Set the optional distinct-reader reinforcement coefficient.
+ #[must_use]
+ pub fn with_decay_breadth_weight(mut self, breadth_weight: f64) -> Self {
+ self.decay_breadth_weight = breadth_weight;
+ self
+ }
+
/// Attach the wiki handle. Without this, `memory_forget_sweep`
/// and `memory_lint` cannot write their report pages.
#[must_use]
@@ -1674,7 +1684,7 @@ impl AiMemoryServer {
let bump_actor = Self::bump_actor_from_parts(&parts);
self.spawn_access_bump(
hits.iter().map(|(h, _)| h.id).collect(),
- bump_actor.as_deref(),
+ bump_actor.as_ref(),
);
// Raw-observation fallback when compiled-page search misses. Works
// for a single resolved project (default / workspace+project) AND
@@ -1755,7 +1765,7 @@ impl AiMemoryServer {
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
self.spawn_access_bump(
hits.iter().map(|(h, _)| h.id).collect(),
- bump_actor.as_deref(),
+ bump_actor.as_ref(),
);
hits.into_iter()
.map(|(hit, score_details)| QueryHit { hit, score_details })
@@ -1837,7 +1847,7 @@ impl AiMemoryServer {
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
self.spawn_access_bump(
hits.iter().map(|h| h.id).collect(),
- Self::bump_actor_from_parts(&parts).as_deref(),
+ Self::bump_actor_from_parts(&parts).as_ref(),
);
ok_json(&MemoryRecentResponse {
hits,
@@ -2104,13 +2114,14 @@ impl AiMemoryServer {
&aps_actor,
)
.await?;
- let report = run_sweep(
+ let report = run_sweep_with_breadth(
&self.reader,
&self.writer,
self.wiki.as_ref(),
ws,
proj,
&self.decay_params,
+ self.decay_breadth_weight,
args.dry_run.unwrap_or(false),
)
.await
@@ -2315,11 +2326,11 @@ impl AiMemoryServer {
// 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
+ // "which human is this", `owner_identity` 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(
+ let staging_owner = ai_memory_core::owner_identity(
request_actor.identity_key().as_ref(),
self.deployment_distinguishes_operators()
.await
@@ -2372,44 +2383,46 @@ impl AiMemoryServer {
}
let staged = self
.writer
- .stage_auto_improve_run(StageAutoImproveRun {
- workspace_id: ws,
- project_id: proj,
- session_id: Some(session_id),
- provider: Some(report.provider.clone()),
- model: Some(report.model.clone()),
- summary: Some(report.summary.clone()),
- warnings_json: serde_json::to_value(&report.warnings)
- .unwrap_or_else(|_| serde_json::json!([])),
- rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
- .unwrap_or_else(|_| serde_json::json!([])),
- config_json: serde_json::json!({
- "min_observations": cfg.min_observations,
- "min_session_duration_secs": cfg.min_session_duration_secs,
- "min_confidence": cfg.min_confidence,
- "max_input_tokens": cfg.max_input_tokens,
- "max_proposals_per_run": cfg.max_proposals_per_run,
- "include_raw_fallback": cfg.include_raw_fallback,
- "max_patchable_pages": cfg.max_patchable_pages,
- "max_patchable_body_chars": cfg.max_patchable_body_chars,
- "max_edits_per_proposal": cfg.max_edits_per_proposal,
- "max_edit_content_chars": cfg.max_edit_content_chars,
- "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
- "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
- "max_rejection_context": cfg.max_rejection_context,
- "rejection_context_days": cfg.rejection_context_days,
- "max_final_body_chars": cfg.max_final_body_chars,
- "max_rule_page_tokens": cfg.max_rule_page_tokens,
- "max_procedure_page_tokens": cfg.max_procedure_page_tokens,
- "eval": cfg.eval,
- }),
- proposal_actor: ai_memory_core::ActorContext {
- agent: Some(cfg.proposal_actor.clone()),
- ..ai_memory_core::ActorContext::default()
+ .stage_auto_improve_run_for_owner(
+ StageAutoImproveRun {
+ workspace_id: ws,
+ project_id: proj,
+ session_id: Some(session_id),
+ provider: Some(report.provider.clone()),
+ model: Some(report.model.clone()),
+ summary: Some(report.summary.clone()),
+ warnings_json: serde_json::to_value(&report.warnings)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)
+ .unwrap_or_else(|_| serde_json::json!([])),
+ config_json: serde_json::json!({
+ "min_observations": cfg.min_observations,
+ "min_session_duration_secs": cfg.min_session_duration_secs,
+ "min_confidence": cfg.min_confidence,
+ "max_input_tokens": cfg.max_input_tokens,
+ "max_proposals_per_run": cfg.max_proposals_per_run,
+ "include_raw_fallback": cfg.include_raw_fallback,
+ "max_patchable_pages": cfg.max_patchable_pages,
+ "max_patchable_body_chars": cfg.max_patchable_body_chars,
+ "max_edits_per_proposal": cfg.max_edits_per_proposal,
+ "max_edit_content_chars": cfg.max_edit_content_chars,
+ "max_changed_chars_per_proposal": cfg.max_changed_chars_per_proposal,
+ "max_patch_edits_per_run": cfg.max_patch_edits_per_run,
+ "max_rejection_context": cfg.max_rejection_context,
+ "rejection_context_days": cfg.rejection_context_days,
+ "max_final_body_chars": cfg.max_final_body_chars,
+ "max_rule_page_tokens": cfg.max_rule_page_tokens,
+ "max_procedure_page_tokens": cfg.max_procedure_page_tokens,
+ "eval": cfg.eval,
+ }),
+ proposal_actor: ai_memory_core::ActorContext {
+ agent: Some(cfg.proposal_actor.clone()),
+ ..ai_memory_core::ActorContext::default()
+ },
+ proposals,
},
- proposals,
- staged_by_actor_user,
- })
+ staging_owner,
+ )
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let mut sidecar_paths = Vec::with_capacity(staged.proposal_ids.len());
@@ -3468,7 +3481,7 @@ const ACCESS_BUMP_COOLDOWN: Duration = Duration::from_secs(60);
///
/// 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>;
+type AccessBumpSeen = HashMap<(PageId, Option<ai_memory_core::IdentityKey>), 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`.
@@ -3479,7 +3492,7 @@ type AccessBumpSeen = HashMap<(PageId, Option<String>), Instant>;
fn select_bumpable(
seen: &mut AccessBumpSeen,
ids: Vec<PageId>,
- actor: Option<&str>,
+ actor: Option<&ai_memory_core::IdentityKey>,
now: Instant,
cooldown: Duration,
) -> Vec<PageId> {
@@ -3488,7 +3501,7 @@ 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));
+ let id = (id, actor.cloned());
// 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.
@@ -3501,17 +3514,17 @@ fn select_bumpable(
}
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:
+ /// The caller's typed identity 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> {
+ fn bump_actor_from_parts(
+ parts: &axum::http::request::Parts,
+ ) -> Option<ai_memory_core::IdentityKey> {
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,
@@ -3522,7 +3535,7 @@ impl AiMemoryServer {
/// 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>) {
+ fn spawn_access_bump(&self, ids: Vec<PageId>, actor: Option<&ai_memory_core::IdentityKey>) {
if ids.is_empty() {
return;
}
@@ -3539,9 +3552,9 @@ impl AiMemoryServer {
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);
+ let actor = actor.cloned();
tokio::spawn(async move {
- if let Err(e) = writer.bump_access(fresh, actor).await {
+ if let Err(e) = writer.bump_access_for_actor(fresh, actor).await {
tracing::warn!(error = %e, "access bump failed");
}
});
@@ -8867,7 +8880,7 @@ mod tests {
/// second proposal collided or got its own bucket.
async fn auto_improve_over_pending_target(
trusted_proxy_identity: bool,
- pending_bucket: Option<String>,
+ pending_owner: Option<ai_memory_core::IdentityKey>,
caller: Option<&str>,
) -> serde_json::Value {
let tmp = TempDir::new().unwrap();
@@ -8895,6 +8908,7 @@ mod tests {
project_id: proj,
agent_kind: AgentKind::Other,
cwd: None,
+ actor_user: None,
})
.await
.unwrap();
@@ -8918,33 +8932,35 @@ mod tests {
.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,
- }],
- })
+ .stage_auto_improve_run_for_owner(
+ 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!({}),
+ 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,
+ }],
+ },
+ pending_owner,
+ )
.await
.unwrap();
@@ -9041,11 +9057,11 @@ mod tests {
/// 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
+ /// identity contract, the same encoding `owner_identity` 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 alice = ai_memory_core::IdentityKey::User("alice".into());
let json = auto_improve_over_pending_target(true, Some(alice), Some("bob")).await;
let proposals = json["proposals"].as_array().expect("proposals array");
@@ -9357,8 +9373,8 @@ mod tests {
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();
+ let alice = ai_memory_core::IdentityKey::User("alice".into());
+ let bob = ai_memory_core::IdentityKey::User("bob".into());
// Alice reads first; inside the window Bob's read must still count.
assert_eq!(
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index ec36ee76..ae34fb93 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -102,7 +102,6 @@ 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.sql
index d7f75930..d2cd2e08 100644
--- a/crates/ai-memory-store/migrations/V42__auto_improve_proposal_author.sql
+++ b/crates/ai-memory-store/migrations/V42__auto_improve_proposal_author.sql
@@ -22,10 +22,10 @@
--
-- `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.
+-- are: the identity may be a proxy username or an issuer-qualified OIDC
+-- subject 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
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.sql
index 6037a424..ab1f2737 100644
--- a/crates/ai-memory-store/migrations/V43__page_access_by_actor.sql
+++ b/crates/ai-memory-store/migrations/V43__page_access_by_actor.sql
@@ -13,15 +13,11 @@
-- "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`.
+-- `actor` is TEXT rather than a FK to `users(id)` on purpose: an authenticated
+-- identity may be a proxy username or an issuer-qualified OIDC subject 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.rs
index dc1aca97..905c2fdf 100644
--- a/crates/ai-memory-store/src/auto_improve.rs
+++ b/crates/ai-memory-store/src/auto_improve.rs
@@ -25,8 +25,8 @@
use std::str::FromStr;
use ai_memory_core::{
- ActorContext, AutoImproveProposalId, AutoImproveRunId, NewPage, PageId, PagePath, ProjectId,
- SessionId, UserId, WorkspaceId,
+ ActorContext, AutoImproveProposalId, AutoImproveRunId, IdentityKey, NewPage, PageId, PagePath,
+ ProjectId, SessionId, UserId, WorkspaceId,
};
use jiff::Timestamp;
use rusqlite::{Connection, OptionalExtension, Row, params};
@@ -142,16 +142,6 @@ 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>,
}
@@ -193,6 +183,16 @@ pub struct StagedAutoImproveRun {
pub run_id: AutoImproveRunId,
/// Ids of the staged proposals, in input order.
pub proposal_ids: Vec<AutoImproveProposalId>,
+}
+
+/// Result of operator-scoped staging, including proposals skipped because the
+/// same operator already has a pending proposal for the target.
+#[derive(Debug, Clone, Serialize)]
+pub struct StagedAutoImproveRunReport {
+ /// Id of the recorded run row.
+ pub run_id: AutoImproveRunId,
+ /// Ids of proposals that were staged, 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.
///
@@ -202,6 +202,15 @@ pub struct StagedAutoImproveRun {
pub skipped: Vec<SkippedProposal>,
}
+impl StagedAutoImproveRunReport {
+ fn into_staged(self) -> StagedAutoImproveRun {
+ StagedAutoImproveRun {
+ run_id: self.run_id,
+ proposal_ids: self.proposal_ids,
+ }
+ }
+}
+
/// One proposal that was not staged, and why.
///
/// `Deserialize` because the HTTP clients (the CLI) have to read this back off
@@ -287,18 +296,23 @@ 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>,
}
+/// Proposal detail plus the operator identity that staged it.
+///
+/// Kept as an additive wrapper so [`AutoImproveProposalDetail`] remains source
+/// compatible for downstream Rust callers that construct or destructure it.
+#[derive(Debug, Clone, Serialize)]
+pub struct OwnedAutoImproveProposalDetail {
+ /// Existing detail fields, flattened on HTTP serialization.
+ #[serde(flatten)]
+ pub detail: AutoImproveProposalDetail,
+ /// Qualified identity storage key, or `None` for shared/unattributed work.
+ pub staged_by_actor_user: Option<String>,
+}
+
/// One append-only status-history entry for a proposal.
#[derive(Debug, Clone, Serialize)]
pub struct AutoImproveProposalEvent {
@@ -566,8 +580,40 @@ pub fn stage_run(
conn: &mut Connection,
input: &StageAutoImproveRun,
) -> StoreResult<StagedAutoImproveRun> {
+ stage_run_impl(conn, input, None, false).map(StagedAutoImproveRunReport::into_staged)
+}
+
+/// Stage a run in an optional operator bucket and report target collisions
+/// without discarding non-colliding sibling proposals.
+///
+/// The owner is typed so callers cannot manufacture malformed or ambiguous
+/// persisted identity keys. `None` retains the shared legacy bucket.
+///
+/// # Errors
+/// Returns [`StoreError::InvalidState`] when a precondition fails, or an
+/// SQLite error when a statement fails; either way nothing is committed.
+pub fn stage_run_for_owner(
+ conn: &mut Connection,
+ input: &StageAutoImproveRun,
+ owner: Option<&IdentityKey>,
+) -> StoreResult<StagedAutoImproveRunReport> {
+ stage_run_impl(conn, input, owner, true)
+}
+
+fn stage_run_impl(
+ conn: &mut Connection,
+ input: &StageAutoImproveRun,
+ owner: Option<&IdentityKey>,
+ skip_pending_collisions: bool,
+) -> StoreResult<StagedAutoImproveRunReport> {
let now = Timestamp::now().as_microsecond();
let run_id = AutoImproveRunId::new();
+ if owner.is_some_and(|identity| !identity.is_valid()) {
+ return Err(StoreError::InvalidState(
+ "auto-improve proposal owner is not a normalized identity".into(),
+ ));
+ }
+ let staged_by_actor_user = owner.map(IdentityKey::storage_key);
let actor_json = serde_json::to_string(&input.proposal_actor)?;
let warnings_json = serde_json::to_string(&input.warnings_json)?;
let rejected_json = serde_json::to_string(&input.rejected_candidates_json)?;
@@ -734,16 +780,27 @@ 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(),
+ 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`.
+ // duplicate. Confirm the exact pending target below before treating a
+ // UNIQUE failure as a skippable collision.
match insert {
Ok(_) => {}
- Err(rusqlite::Error::SqliteFailure(err, _)) if is_pending_target_collision(&err) => {
+ Err(rusqlite::Error::SqliteFailure(err, _))
+ if skip_pending_collisions
+ && err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE
+ && pending_target_exists(
+ &tx,
+ input.workspace_id,
+ input.project_id,
+ proposal.target_path.as_str(),
+ staged_by_actor_user.as_deref(),
+ )? =>
+ {
skipped.push(SkippedProposal {
target_path: proposal.target_path.to_string(),
reason: "a proposal is already pending review for this path".into(),
@@ -764,7 +821,7 @@ pub fn stage_run(
proposal_ids.push(id);
}
tx.commit()?;
- Ok(StagedAutoImproveRun {
+ Ok(StagedAutoImproveRunReport {
run_id,
proposal_ids,
skipped,
@@ -1290,17 +1347,29 @@ 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 pending_target_exists(
+ tx: &rusqlite::Transaction<'_>,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ target_path: &str,
+ owner: Option<&str>,
+) -> StoreResult<bool> {
+ tx.query_row(
+ "SELECT EXISTS( \
+ SELECT 1 FROM auto_improve_proposals \
+ WHERE workspace_id = ?1 AND project_id = ?2 \
+ AND target_path = ?3 AND status = 'pending' \
+ AND staged_by_actor_user IS ?4 \
+ )",
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ target_path,
+ owner,
+ ],
+ |row| row.get(0),
+ )
+ .map_err(Into::into)
}
fn sha256(bytes: &[u8]) -> [u8; 32] {
diff --git a/crates/ai-memory-store/src/decay.rs b/crates/ai-memory-store/src/decay.rs
index d8806653..842cf3a8 100644
--- a/crates/ai-memory-store/src/decay.rs
+++ b/crates/ai-memory-store/src/decay.rs
@@ -30,15 +30,6 @@ 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 {
@@ -47,8 +38,6 @@ 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,
@@ -81,6 +70,7 @@ pub fn retention_score(
days_since_access,
salience,
0,
+ 0.0,
)
}
@@ -90,7 +80,7 @@ pub fn retention_score(
/// `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`].
+/// `breadth_weight`. A weight of `0.0` preserves the historical formula.
///
/// Identity at the default weight of `0.0`, and identity again for
/// `distinct_actors` of 0 (no per-actor rows recorded — every page written
@@ -108,11 +98,21 @@ pub fn retention_score_with_breadth(
days_since_access: Option<f64>,
salience: Option<f64>,
distinct_actors: u32,
+ breadth_weight: f64,
) -> f64 {
let salience = salience.unwrap_or(params.salience_default);
+ // Destructive callers validate and reject invalid config. The pure helper
+ // also fails closed for direct library callers: an invalid coefficient
+ // disables the optional bonus instead of producing NaN or reducing a
+ // page's historical retention score.
+ let breadth_weight = if breadth_weight.is_finite() && breadth_weight >= 0.0 {
+ breadth_weight
+ } else {
+ 0.0
+ };
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 breadth = 1.0 + 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() * breadth
});
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 92adb5e6..cdfe6b1d 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -33,8 +33,8 @@ pub use auto_improve::{
AutoImproveProposalEvent, AutoImproveProposalOperation, AutoImproveProposalStatus,
AutoImproveProposalSummary, AutoImproveRejectionSummary, AutoImproveTelemetryAggregate,
AutoImproveTelemetryCount, FailAutoImproveProposal, NewAutoImproveProposal,
- RejectAutoImproveProposal, SkippedProposal, StageAutoImproveRun, StagedAutoImproveRun,
- artifact_path_for,
+ OwnedAutoImproveProposalDetail, RejectAutoImproveProposal, SkippedProposal,
+ StageAutoImproveRun, StagedAutoImproveRun, StagedAutoImproveRunReport, artifact_path_for,
};
pub use decay::{
DecayParams, SALIENCE_MAX, SALIENCE_MIN, SALIENCE_STEP, retention_score,
@@ -199,7 +199,6 @@ 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()
@@ -3228,7 +3227,6 @@ 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.rs
index d33dd8d9..58373a36 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -1103,16 +1103,21 @@ pub fn store_embeddings(conn: &mut Connection, embeddings: &[EmbeddingWrite]) ->
/// appear in `page_ids`. Idempotent for unknown ids (no-op).
/// Used by the read path to feed the M8 reinforcement term.
///
-/// `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(
+/// Bump shared access counters and record an optional typed operator as a
+/// distinct reader. Both mutations commit in the same transaction.
+pub fn bump_access_for_pages_for_actor(
conn: &mut Connection,
page_ids: &[PageId],
- actor: Option<&str>,
+ actor: Option<&IdentityKey>,
) -> StoreResult<()> {
if page_ids.is_empty() {
return Ok(());
}
+ if actor.is_some_and(|identity| !identity.is_valid()) {
+ return Err(StoreError::InvalidState(
+ "page access actor is not a normalized identity".into(),
+ ));
+ }
let now = Timestamp::now().as_microsecond();
let tx = conn.transaction()?;
{
@@ -1127,7 +1132,8 @@ pub fn bump_access_for_pages(
// 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()) {
+ if let Some(actor) = actor {
+ let actor = actor.storage_key();
// 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
@@ -1138,14 +1144,13 @@ pub fn bump_access_for_pages(
// 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 \
+ "INSERT INTO page_access (page_id, actor) \
+ SELECT ?1, ?2 \
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",
+ ON CONFLICT(page_id, actor) DO NOTHING",
)?;
for id in page_ids {
- per_actor.execute(params![id.as_bytes(), actor, now])?;
+ per_actor.execute(params![id.as_bytes(), actor])?;
}
}
}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index cbf911ac..b656ff34 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -28,7 +28,8 @@ use uuid::Uuid;
use crate::auto_improve::{
AutoImproveProposalDetail, AutoImproveProposalEvent, AutoImproveProposalStatus,
AutoImproveProposalSummary, AutoImproveRejectionSummary, AutoImproveTelemetryAggregate,
- AutoImproveTelemetryCount, bytes32, opt_bytes32, summary_from_row, to_sql_err,
+ AutoImproveTelemetryCount, OwnedAutoImproveProposalDetail, bytes32, opt_bytes32,
+ summary_from_row, to_sql_err,
};
use crate::error::{StoreError, StoreResult};
use crate::fts_query::prepare_fts5_query;
@@ -2259,7 +2260,7 @@ impl ReaderPool {
) -> StoreResult<std::collections::HashMap<PageId, u32>> {
self.with_conn(move |conn| {
let mut stmt = conn.prepare(
- "SELECT pa.page_id, COUNT(DISTINCT pa.actor) \
+ "SELECT pa.page_id, COUNT(*) \
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 \
@@ -4859,6 +4860,19 @@ impl ReaderPool {
project_id: ProjectId,
proposal_id: AutoImproveProposalId,
) -> StoreResult<Option<AutoImproveProposalDetail>> {
+ self.auto_improve_proposal_detail_with_owner(workspace_id, project_id, proposal_id)
+ .await
+ .map(|detail| detail.map(|owned| owned.detail))
+ }
+
+ /// Read one proposal plus the operator that staged it, failing closed when
+ /// the scope does not match.
+ pub async fn auto_improve_proposal_detail_with_owner(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ proposal_id: AutoImproveProposalId,
+ ) -> StoreResult<Option<OwnedAutoImproveProposalDetail>> {
self.with_conn(move |conn| {
let row = conn
.query_row(
@@ -4901,37 +4915,39 @@ impl ReaderPool {
.transpose()
.map_err(to_sql_err)?;
let patch_raw: Option<String> = row.get(27)?;
- Ok(AutoImproveProposalDetail {
- summary,
- rationale: row.get(12)?,
- evidence_json: serde_json::from_str(&evidence_raw)
- .map_err(to_sql_err)?,
- body_markdown: row.get(14)?,
- body_sha256: body_hash,
- artifact_path: row.get(16)?,
- artifact_sha256: artifact_hash,
- target_latest_page_id_at_stage: staged_page_id,
- target_body_sha256_at_stage: staged_body_hash,
- target_updated_at_at_stage: row.get(20)?,
- decision_reason: row.get(21)?,
- decided_by_author_id: decided_author,
- decided_by_actor_json: decided_actor_raw
- .map(|raw| serde_json::from_str(&raw))
- .transpose()
- .map_err(to_sql_err)?,
- applied_page_id,
- checkpoint: row.get(25)?,
- edit_mode: row.get(26)?,
- patch_json: patch_raw
- .map(|raw| serde_json::from_str(&raw))
- .transpose()
- .map_err(to_sql_err)?,
- expected_base_body_sha256: opt_bytes32(row.get(28)?)
- .map_err(to_sql_err)?,
+ Ok(OwnedAutoImproveProposalDetail {
+ detail: AutoImproveProposalDetail {
+ summary,
+ rationale: row.get(12)?,
+ evidence_json: serde_json::from_str(&evidence_raw)
+ .map_err(to_sql_err)?,
+ body_markdown: row.get(14)?,
+ body_sha256: body_hash,
+ artifact_path: row.get(16)?,
+ artifact_sha256: artifact_hash,
+ target_latest_page_id_at_stage: staged_page_id,
+ target_body_sha256_at_stage: staged_body_hash,
+ target_updated_at_at_stage: row.get(20)?,
+ decision_reason: row.get(21)?,
+ decided_by_author_id: decided_author,
+ decided_by_actor_json: decided_actor_raw
+ .map(|raw| serde_json::from_str(&raw))
+ .transpose()
+ .map_err(to_sql_err)?,
+ applied_page_id,
+ checkpoint: row.get(25)?,
+ edit_mode: row.get(26)?,
+ patch_json: patch_raw
+ .map(|raw| serde_json::from_str(&raw))
+ .transpose()
+ .map_err(to_sql_err)?,
+ expected_base_body_sha256: opt_bytes32(row.get(28)?)
+ .map_err(to_sql_err)?,
+ materialized_base_body_sha256: opt_bytes32(row.get(29)?)
+ .map_err(to_sql_err)?,
+ events: Vec::new(),
+ },
staged_by_actor_user: row.get(30)?,
- materialized_base_body_sha256: opt_bytes32(row.get(29)?)
- .map_err(to_sql_err)?,
- events: Vec::new(),
})
},
)
@@ -4965,7 +4981,7 @@ impl ReaderPool {
})
})?;
for row in rows {
- detail.events.push(row?);
+ detail.detail.events.push(row?);
}
Ok(Some(detail))
})
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 04db0a4f..8005de7b 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -11,9 +11,9 @@ use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use ai_memory_core::{
- AgentKind, HandoffAcceptance, HandoffId, ManagedRunId, NewHandoff, NewObservation, NewPage,
- NewSession, NewUser, ObservationId, OwnerFilter, PageId, PagePath, ProjectId, Sanitized,
- SessionId, UserId, WorkspaceId,
+ AgentKind, HandoffAcceptance, HandoffId, IdentityKey, ManagedRunId, NewHandoff, NewObservation,
+ NewPage, NewSession, NewUser, ObservationId, OwnerFilter, PageId, PagePath, ProjectId,
+ Sanitized, SessionId, UserId, WorkspaceId,
};
use rusqlite::Connection;
use tokio::sync::{mpsc, oneshot};
@@ -21,6 +21,7 @@ use tokio::sync::{mpsc, oneshot};
use crate::auto_improve::{
ApproveAutoImproveProposal, ApproveAutoImproveProposalResult, FailAutoImproveProposal,
RejectAutoImproveProposal, StageAutoImproveRun, StagedAutoImproveRun,
+ StagedAutoImproveRunReport,
};
use crate::error::{StoreError, StoreResult};
use crate::ops::{
@@ -184,7 +185,7 @@ pub(crate) enum WriteCmd {
},
BumpAccess {
page_ids: Vec<PageId>,
- actor: Option<String>,
+ actor: Option<IdentityKey>,
reply: oneshot::Sender<StoreResult<()>>,
},
RecordPageFeedback {
@@ -314,6 +315,11 @@ pub(crate) enum WriteCmd {
input: StageAutoImproveRun,
reply: oneshot::Sender<StoreResult<StagedAutoImproveRun>>,
},
+ StageAutoImproveRunForOwner {
+ input: StageAutoImproveRun,
+ owner: Option<IdentityKey>,
+ reply: oneshot::Sender<StoreResult<StagedAutoImproveRunReport>>,
+ },
RejectAutoImproveProposal {
input: RejectAutoImproveProposal,
reply: oneshot::Sender<StoreResult<()>>,
@@ -863,15 +869,21 @@ 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<()> {
+ self.bump_access_for_actor(page_ids, None).await
+ }
+
+ /// Bump shared access counters and record each identified operator once per
+ /// page for the optional access-breadth retention term.
///
/// # Errors
/// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
- pub async fn bump_access(
+ pub async fn bump_access_for_actor(
&self,
page_ids: Vec<PageId>,
- actor: Option<String>,
+ actor: Option<IdentityKey>,
) -> StoreResult<()> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::BumpAccess {
@@ -1313,6 +1325,23 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Stage an auto-improvement run in an optional typed operator bucket,
+ /// reporting target collisions without discarding sibling proposals.
+ pub async fn stage_auto_improve_run_for_owner(
+ &self,
+ input: StageAutoImproveRun,
+ owner: Option<IdentityKey>,
+ ) -> StoreResult<StagedAutoImproveRunReport> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::StageAutoImproveRunForOwner {
+ input,
+ owner,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Reject a pending auto-improvement proposal and append an event.
pub async fn reject_auto_improve_proposal(
&self,
@@ -1762,7 +1791,8 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
actor,
reply,
} => {
- let result = ops::bump_access_for_pages(&mut conn, &page_ids, actor.as_deref());
+ let result =
+ ops::bump_access_for_pages_for_actor(&mut conn, &page_ids, actor.as_ref());
send_or_warn(reply, result, "bump_access_for_pages");
}
WriteCmd::SoftDeleteForDecay { page_ids, reply } => {
@@ -1931,6 +1961,15 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = crate::auto_improve::stage_run(&mut conn, &input);
send_or_warn(reply, result, "stage_auto_improve_run");
}
+ WriteCmd::StageAutoImproveRunForOwner {
+ input,
+ owner,
+ reply,
+ } => {
+ let result =
+ crate::auto_improve::stage_run_for_owner(&mut conn, &input, owner.as_ref());
+ send_or_warn(reply, result, "stage_auto_improve_run_for_owner");
+ }
WriteCmd::RejectAutoImproveProposal { input, reply } => {
let result = crate::auto_improve::reject_proposal(&mut conn, &input);
send_or_warn(reply, result, "reject_auto_improve_proposal");
diff --git a/crates/ai-memory-store/tests/access_breadth.rs b/crates/ai-memory-store/tests/access_breadth.rs
index 103876b1..89486823 100644
--- a/crates/ai-memory-store/tests/access_breadth.rs
+++ b/crates/ai-memory-store/tests/access_breadth.rs
@@ -13,8 +13,8 @@ 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()
+fn actor(name: &str) -> IdentityKey {
+ IdentityKey::User(name.into())
}
/// Default parameters must reproduce the historical score exactly, whatever the
@@ -23,7 +23,7 @@ fn actor_key(name: &str) -> String {
#[test]
fn breadth_is_identity_at_the_default_weight() {
let params = DecayParams::default();
- assert_eq!(params.breadth_weight, 0.0);
+ let breadth_weight = 0.0;
for actors in [0, 1, 2, 10, 500] {
for (age, count, since) in [
@@ -32,7 +32,15 @@ fn breadth_is_identity_at_the_default_weight() {
(365.0, 100, Some(200.0)),
] {
assert_eq!(
- retention_score_with_breadth(&params, age, count, since, None, actors),
+ retention_score_with_breadth(
+ &params,
+ age,
+ count,
+ since,
+ None,
+ actors,
+ breadth_weight,
+ ),
retention_score(&params, age, count, since, None),
"default weight must be identity (actors={actors})"
);
@@ -46,21 +54,19 @@ fn breadth_is_identity_at_the_default_weight() {
/// 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 params = DecayParams::default();
+ let breadth_weight = 1.5;
let baseline = retention_score(&params, 30.0, 5, Some(3.0), None);
for actors in [0, 1] {
assert_eq!(
- retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, actors),
+ retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, actors, breadth_weight,),
baseline,
"actors={actors} must not change the score"
);
}
// More readers is worth strictly more, and monotonically so.
- let two = retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 2);
- let ten = retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 10);
+ let two = retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 2, breadth_weight);
+ let ten = retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 10, breadth_weight);
assert!(two > baseline);
assert!(ten > two);
}
@@ -69,16 +75,25 @@ fn zero_and_one_actor_score_identically_even_when_weighted() {
/// 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()
- };
+ let params = DecayParams::default();
assert_eq!(
- retention_score_with_breadth(&params, 10.0, 0, None, None, 9),
+ retention_score_with_breadth(&params, 10.0, 0, None, None, 9, 2.0),
retention_score(&params, 10.0, 0, None, None)
);
}
+#[test]
+fn invalid_breadth_weights_fail_closed_to_the_historical_score() {
+ let params = DecayParams::default();
+ let baseline = retention_score(&params, 30.0, 5, Some(3.0), None);
+ for weight in [-1.0, f64::NAN, f64::INFINITY] {
+ assert_eq!(
+ retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 50, weight),
+ baseline,
+ );
+ }
+}
+
/// 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]
@@ -116,21 +131,27 @@ async fn per_actor_rows_accumulate_without_replacing_the_scalar() {
store
.writer
- .bump_access(vec![page], Some(actor_key("alice")))
+ .bump_access_for_actor(vec![page], Some(actor("alice")))
.await
.unwrap();
store
.writer
- .bump_access(vec![page], Some(actor_key("alice")))
+ .bump_access_for_actor(vec![page], Some(actor("alice")))
.await
.unwrap();
store
.writer
- .bump_access(vec![page], Some(actor_key("bob")))
+ .bump_access_for_actor(vec![page], Some(actor("bob")))
.await
.unwrap();
// An unattributed read: still counted in the shared scalar.
- store.writer.bump_access(vec![page], None).await.unwrap();
+ store.writer.bump_access(vec![page]).await.unwrap();
+ let error = store
+ .writer
+ .bump_access_for_actor(vec![page], Some(IdentityKey::User(" ".into())))
+ .await
+ .expect_err("a directly constructed blank identity must be rejected");
+ assert!(error.to_string().contains("normalized identity"));
let conn = Connection::open(store.db_path()).unwrap();
let scalar: i64 = conn
@@ -140,7 +161,10 @@ async fn per_actor_rows_accumulate_without_replacing_the_scalar() {
|r| r.get(0),
)
.unwrap();
- assert_eq!(scalar, 4, "the historical counter still counts every read");
+ assert_eq!(
+ scalar, 4,
+ "the historical counter counts valid reads, not rejected identities"
+ );
let distinct: i64 = conn
.query_row(
@@ -151,14 +175,14 @@ async fn per_actor_rows_accumulate_without_replacing_the_scalar() {
.unwrap();
assert_eq!(distinct, 2, "two named operators, the anonymous read aside");
- let alice: i64 = conn
+ let alice_exists: bool = conn
.query_row(
- "SELECT count FROM page_access WHERE page_id = ?1 AND actor = ?2",
- params![page.as_bytes(), actor_key("alice")],
+ "SELECT EXISTS(SELECT 1 FROM page_access WHERE page_id = ?1 AND actor = ?2)",
+ params![page.as_bytes(), actor("alice").storage_key()],
|r| r.get(0),
)
.unwrap();
- assert_eq!(alice, 2);
+ assert!(alice_exists);
}
/// The bump is fired from a detached task AFTER the search responded, so a page
@@ -215,7 +239,7 @@ async fn a_stale_page_id_does_not_cost_the_rest_of_the_batch_its_bump() {
store
.writer
- .bump_access(ids.clone(), Some(actor_key("alice")))
+ .bump_access_for_actor(ids.clone(), Some(actor("alice")))
.await
.unwrap();
@@ -230,14 +254,14 @@ async fn a_stale_page_id_does_not_cost_the_rest_of_the_batch_its_bump() {
.unwrap();
assert_eq!(scalar, 1, "{label} lost its bump to the stale sibling");
- let per_actor: i64 = conn
+ let per_actor: bool = conn
.query_row(
- "SELECT count FROM page_access WHERE page_id = ?1 AND actor = ?2",
- params![id.as_bytes(), actor_key("alice")],
+ "SELECT EXISTS(SELECT 1 FROM page_access WHERE page_id = ?1 AND actor = ?2)",
+ params![id.as_bytes(), actor("alice").storage_key()],
|r| r.get(0),
)
.unwrap();
- assert_eq!(per_actor, 1, "{label} lost its per-operator row");
+ assert!(per_actor, "{label} lost its per-operator row");
}
// The unknown id stays a no-op, exactly as it was before per-actor rows.
diff --git a/crates/ai-memory-store/tests/auto_improve_staging.rs b/crates/ai-memory-store/tests/auto_improve_staging.rs
index 8a5a48ec..a336921c 100644
--- a/crates/ai-memory-store/tests/auto_improve_staging.rs
+++ b/crates/ai-memory-store/tests/auto_improve_staging.rs
@@ -39,7 +39,6 @@ fn run(
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!({}),
@@ -63,6 +62,32 @@ async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {
(ws, proj)
}
+#[tokio::test]
+async fn malformed_direct_owner_keys_cannot_create_hidden_pending_buckets() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ let error = store
+ .writer
+ .stage_auto_improve_run_for_owner(
+ run(ws, proj, vec![proposal("_rules/hidden.md", "Hidden")]),
+ Some(IdentityKey::User(" ".into())),
+ )
+ .await
+ .expect_err("a directly constructed blank owner must be rejected");
+ assert!(error.to_string().contains("normalized identity"));
+ assert!(
+ store
+ .reader
+ .list_auto_improve_proposals(ws, proj, None, 10)
+ .await
+ .unwrap()
+ .is_empty(),
+ "validation must happen before the run transaction is committed"
+ );
+}
+
/// 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]
@@ -73,11 +98,10 @@ async fn a_colliding_proposal_does_not_destroy_the_run() {
let first = store
.writer
- .stage_auto_improve_run(run(
- ws,
- proj,
- vec![proposal("_slots/current-focus.md", "Focus")],
- ))
+ .stage_auto_improve_run_for_owner(
+ run(ws, proj, vec![proposal("_slots/current-focus.md", "Focus")]),
+ None,
+ )
.await
.unwrap();
assert_eq!(first.proposal_ids.len(), 1);
@@ -86,14 +110,17 @@ async fn a_colliding_proposal_does_not_destroy_the_run() {
// 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"),
- ],
- ))
+ .stage_auto_improve_run_for_owner(
+ run(
+ ws,
+ proj,
+ vec![
+ proposal("_slots/current-focus.md", "Focus again"),
+ proposal("_rules/unrelated.md", "Unrelated"),
+ ],
+ ),
+ None,
+ )
.await
.unwrap();
@@ -123,14 +150,17 @@ async fn duplicate_targets_within_one_run_still_fail_the_run() {
let result = store
.writer
- .stage_auto_improve_run(run(
- ws,
- proj,
- vec![
- proposal("_slots/current-focus.md", "First"),
- proposal("_slots/current-focus.md", "Second"),
- ],
- ))
+ .stage_auto_improve_run_for_owner(
+ run(
+ ws,
+ proj,
+ vec![
+ proposal("_slots/current-focus.md", "First"),
+ proposal("_slots/current-focus.md", "Second"),
+ ],
+ ),
+ None,
+ )
.await;
assert!(result.is_err(), "a self-contradicting batch is refused");
@@ -169,22 +199,25 @@ async fn pending_uniqueness_is_per_operator_without_weakening_single_user() {
// 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
+ (
+ run(ws, proj, vec![proposal("_rules/style.md", "Style")]),
+ actor.map(|name| IdentityKey::User(name.into())),
+ )
};
// --- single-operator behaviour is untouched: unattributed rows collapse
// into one bucket, so the second pending proposal is still refused.
+ let (input, owner) = staged_by(None);
let first = store
.writer
- .stage_auto_improve_run(staged_by(None))
+ .stage_auto_improve_run_for_owner(input, owner)
.await
.unwrap();
assert_eq!(first.proposal_ids.len(), 1);
+ let (input, owner) = staged_by(None);
let second = store
.writer
- .stage_auto_improve_run(staged_by(None))
+ .stage_auto_improve_run_for_owner(input, owner)
.await
.unwrap();
assert!(
@@ -194,9 +227,10 @@ async fn pending_uniqueness_is_per_operator_without_weakening_single_user() {
// --- multi-operator: two proxy-asserted humans, neither with a `users`
// row, must not block each other on the same page.
+ let (input, owner) = staged_by(Some("alice"));
let alices = store
.writer
- .stage_auto_improve_run(staged_by(Some("alice")))
+ .stage_auto_improve_run_for_owner(input, owner)
.await
.unwrap();
assert_eq!(
@@ -206,18 +240,20 @@ async fn pending_uniqueness_is_per_operator_without_weakening_single_user() {
);
assert!(alices.skipped.is_empty());
+ let (input, owner) = staged_by(Some("bob"));
let bobs = store
.writer
- .stage_auto_improve_run(staged_by(Some("bob")))
+ .stage_auto_improve_run_for_owner(input, owner)
.await
.unwrap();
assert_eq!(bobs.proposal_ids.len(), 1);
assert!(bobs.skipped.is_empty());
// …and Alice still cannot stack two of her own.
+ let (input, owner) = staged_by(Some("alice"));
let alice_again = store
.writer
- .stage_auto_improve_run(staged_by(Some("alice")))
+ .stage_auto_improve_run_for_owner(input, owner)
.await
.unwrap();
assert_eq!(alice_again.skipped.len(), 1);
@@ -255,11 +291,10 @@ async fn a_non_unique_constraint_failure_is_not_reported_as_a_pending_collision(
let err = store
.writer
- .stage_auto_improve_run(run(
- ws,
- proj,
- vec![proposal("notes/contract.md", "Contract")],
- ))
+ .stage_auto_improve_run_for_owner(
+ run(ws, proj, vec![proposal("notes/contract.md", "Contract")]),
+ None,
+ )
.await
.expect_err("a schema-contract failure must surface, not be skipped");
assert!(
@@ -279,13 +314,16 @@ async fn a_non_unique_constraint_failure_is_not_reported_as_a_pending_collision(
// 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")]))
+ .stage_auto_improve_run_for_owner(run(ws, proj, vec![proposal("notes/ok.md", "Ok")]), None)
.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")]))
+ .stage_auto_improve_run_for_owner(
+ run(ws, proj, vec![proposal("notes/ok.md", "Ok again")]),
+ None,
+ )
.await
.unwrap();
assert_eq!(again.skipped.len(), 1);
@@ -294,3 +332,49 @@ async fn a_non_unique_constraint_failure_is_not_reported_as_a_pending_collision(
"a proposal is already pending review for this path"
);
}
+
+/// A UNIQUE failure is not necessarily the pending-target index. Confirm the
+/// actual target/owner row before swallowing it so future schema constraints
+/// cannot silently discard proposals.
+#[tokio::test]
+async fn an_unrelated_unique_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;
+
+ store
+ .writer
+ .stage_auto_improve_run_for_owner(
+ run(ws, proj, vec![proposal("notes/first.md", "Repeated title")]),
+ None,
+ )
+ .await
+ .unwrap();
+ {
+ let conn =
+ rusqlite::Connection::open(tmp.path().join("db").join(ai_memory_store::DB_FILENAME))
+ .unwrap();
+ conn.execute_batch(
+ "CREATE UNIQUE INDEX test_unique_proposal_title \
+ ON auto_improve_proposals(title)",
+ )
+ .unwrap();
+ }
+
+ let error = store
+ .writer
+ .stage_auto_improve_run_for_owner(
+ run(
+ ws,
+ proj,
+ vec![proposal("notes/second.md", "Repeated title")],
+ ),
+ None,
+ )
+ .await
+ .expect_err("an unrelated UNIQUE constraint must surface");
+ assert!(
+ error.to_string().contains("UNIQUE constraint failed"),
+ "the real constraint must reach the caller: {error}"
+ );
+}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 48314e50..eff52db0 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -2135,7 +2135,6 @@ 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/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 3d2f5367..507f25ec 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -128,10 +128,12 @@ from hook paths.
`scopes` mode, bounded raw observation FTS returns fallback `raw_hits`;
`global=true` searches compiled wiki pages across projects only. Page hits
bump `access_count` + `last_accessed_at` - the M8 reinforcement term, which
- `memory_feedback` complements with explicit per-page salience. That bump is
- throttled to at most once per page per minute, so a burst of overlapping
- searches does not flood the writer actor with redundant reinforcement
- writes.
+ `memory_feedback` complements with explicit per-page salience. Identified
+ operators also add one `page_access` row per page; an opt-in
+ `[decay] breadth_weight` can reward pages reinforced by several distinct
+ operators. That bump is throttled to at most once per page per minute, so a
+ burst of overlapping searches does not flood the writer actor with
+ redundant reinforcement writes.
7. The forget sweep runs on demand and on the server's `[maintenance]`
schedule: pages past their frontmatter `expires_at:` TTL are
hard-deleted through the wiki layer (file + rows, pin or not);
@@ -260,6 +262,8 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| `handoffs` | Typed cross-agent handoff records (open / accepted / expired). |
| `page_embeddings` | Optional vector rows for latest pages, with `(provider, model, dim)` denormalised so hybrid search can ignore stale vectors after an embedding config change and report missing-embedding diagnostics. |
| `page_feedback` | Append-only `memory_feedback` signals (`helpful` / `not_helpful` / `stale` / `wrong`) keyed by page *version*, with an optional sanitized reason and `salience_after`. Source of truth for the derived `pages.salience`; the lint pass reads unresolved stale/wrong rows joined against `is_latest = 1`, so a rewrite retires the finding. |
+| `page_access` | One row per latest page and qualified operator identity. Supplies the optional access-breadth retention term without changing the existing shared access counter. |
+| `auto_improve_proposals` | Staged learning and maintenance edits with immutable target snapshots and append-only decision events. Pending-target uniqueness is scoped by the qualified staging identity; unattributed proposals retain the historical shared bucket. |
| `entities`, `entity_page_links` | V38 noun index derived from canonical frontmatter. Names are normalized and unique per project; links target immutable page versions while retrieval filters to the latest version. Scope-pairing triggers prevent cross-project links. Powers the fourth RRF retrieval stream. |
| `audit_log` | Every mutation, addressable by `at DESC`. |
@@ -268,7 +272,7 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| Tier | Lifetime | Decay |
|---|---|---|
| Working | Current session only | Hard-drop on session end (kept in `observations` for forensics) |
-| Episodic | 30d hot → 180d cold → evict | `salience · exp(−λΔt) + σ · log(1+access_count) · exp(−μ · days_since_access)` |
+| Episodic | 30d hot → 180d cold → evict | `salience · exp(−λΔt) + σ · log(1+access_count) · exp(−μ · days_since_access) · (1 + breadth_weight · ln(1 + max(distinct_actors−1, 0)))` |
| Semantic | Indefinite | None - only supersedeable via M7 LLM rewrite |
| Procedural | Indefinite | Frequency-decay if not re-observed |
@@ -484,6 +488,7 @@ sigma = 0.6 # ↑ to reward query-hits more
mu = 0.04 # ↑ if recent hits should count more
cold_threshold = 0.20 # below this → soft-delete
hard_delete_after_days = 180
+breadth_weight = 0.0 # opt-in reward for distinct operators
[slots] # optional shared-server injection boundary
per_user = false # shared + own slots in agent context
diff --git a/docs/auto-improvement-loop.md b/docs/auto-improvement-loop.md
index 793b9967..6c1ec6a2 100644
--- a/docs/auto-improvement-loop.md
+++ b/docs/auto-improvement-loop.md
@@ -398,6 +398,13 @@ proposal state, approval status, evidence metadata, and audit rows, but the
review artifact itself should be inspectable and versioned like the rest of the
wiki.
+On deployments that distinguish operators, manually staged proposals record
+the qualified operator identity and enforce one pending proposal per target
+*per operator*. Unattributed scheduler, curator, and telemetry proposals stay
+in the shared bucket. A collision skips only that proposal, preserves its
+siblings, and appears in the command or API response with the target and
+reason; it must not become a silent partial run.
+
Because this is now an MCP tool surface, the standard prompt snippets, managed
Agent Skills, and regression tests assert `memory_auto_improve` appears in the
combined prompt-routing surface. Existing installed `CLAUDE.md`/`AGENTS.md`
diff --git a/docs/users.md b/docs/users.md
index c25d6587..3abbdceb 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -222,8 +222,9 @@ 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
+ qualified identity key — username or complete OIDC issuer/subject pair — 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
@@ -238,8 +239,9 @@ keeps its historical behaviour:
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 reinforcement.** The first reinforced read by each identified
+ operator is recorded per page alongside the existing shared access 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