Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(lint): derive the stale threshold from [decay] lambda
AkitaOnRails4700ef892fd1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ba00381..7e12df84 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- The lint `stale` threshold is now derived from the operator's `[decay]+ lambda` instead of a hard-coded 30 days (#426). The rule only fires on+ episodic pages with zero accesses, and for those the decay score reduces+ exactly to `salience * exp(-lambda * age)` — the reinforcement term carries+ `ln(1 + access_count)`, which is zero — so the lint was already measuring+ decay, just against a constant rather than against `lambda`. Slowing decay+ made the two diverge: at `lambda = 0.008` real eviction lands near day 201+ while the lint still called a page stale on day 31, and because a report+ page is written whenever any finding exists, one page nobody intended to+ read produced a new `_lint/<date>.md` every day, forever. The threshold is+ now `0.6 / lambda`, which is **exactly 30 days at the default+ `lambda = 0.02`** — unchanged for anyone who never tuned decay — and 75+ days at `0.008`. An invalid or non-positive lambda falls back to the+ historical constant rather than silencing the rule.- `bin/deploy` now refuses to push a single-architecture build over a tag thatalready resolves to a multi-architecture manifest (#427). It builds for thearchitecture of the machine it runs on, so deploying a homelab from an x86diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex f31956ce..c1bf70b6 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1052,9 +1052,12 @@ async fn start_maintenance_scheduler(let reader = reader.clone();let wiki = wiki.clone();let llm = llm.clone();+ let decay_lambda = decay.decay_params().lambda;async move {let started = std::time::Instant::now();- let outcome = run_scheduled_lint_tick(&reader, &wiki, llm.as_ref()).await?;+ let outcome =+ run_scheduled_lint_tick(&reader, &wiki, llm.as_ref(), decay_lambda)+ .await?;if outcome.errors > 0 {anyhow::bail!("scheduled rule-based lint had {} scope errors",@@ -1246,6 +1249,7 @@ async fn run_scheduled_lint_tick(reader: &ReaderPool,wiki: &Wiki,llm: Option<&Arc<dyn LlmProvider>>,+ decay_lambda: f64,) -> Result<ScheduledLintTickOutcome> {let scopes = reader.list_all_scopes().await?;let mut outcome = ScheduledLintTickOutcome {@@ -1262,6 +1266,7 @@ async fn run_scheduled_lint_tick(scope.project_id,false,false,+ decay_lambda,).await{@@ -2553,9 +2558,14 @@ mod tests {}let panic_llm: Arc<dyn LlmProvider> = Arc::new(PanicLlm);- let outcome = run_scheduled_lint_tick(&store.reader, &wiki, Some(&panic_llm))- .await- .unwrap();+ let outcome = run_scheduled_lint_tick(+ &store.reader,+ &wiki,+ Some(&panic_llm),+ ai_memory_store::DecayParams::default().lambda,+ )+ .await+ .unwrap();assert_eq!(outcome.scopes, 2);assert_eq!(outcome.errors, 0);diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rsindex 957a2a05..df88dc48 100644--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@ -81,13 +81,53 @@ pub enum LintError {const US_PER_DAY: f64 = 86_400_000_000.0;/// Cap on pages fed to the LLM contradiction pass (token budget).pub const LLM_CLUSTER_CAP: usize = 20;-/// Stale threshold: an unused page this many days old is flagged.+/// Stale threshold at the default `[decay] lambda`, in days.+///+/// Kept for callers that want the historical constant; the live threshold+/// comes from [`stale_days_for`].pub const STALE_DAYS: f64 = 30.0;+/// Decay score at which an unread episodic page is called stale:+/// `exp(-0.02 * 30)`, the score the old fixed 30-day threshold implied at+/// the default lambda. Stored as its negative log so the day count is a+/// plain division.+const STALE_SCORE_LN: f64 = 0.6;++/// Days after which an unread episodic page is flagged stale, derived from+/// the operator's `[decay] lambda`.+///+/// The rule only fires on pages with `access_count == 0`, and for those the+/// decay score reduces exactly to `salience * exp(-lambda * age)` — the M8+/// reinforcement term carries `ln(1 + access_count)`, which is zero. So the+/// lint was already measuring decay; it just measured it against a constant+/// instead of against the operator's lambda, and the two diverged by a+/// growing factor as lambda moved.+///+/// Concretely, at `lambda = 0.008` real eviction lands near day 201 while a+/// fixed threshold still called the page stale on day 31 — and because the+/// lint writes `_lint/<date>.md` whenever any finding exists, one page+/// nobody intends to read produced a new page every day, forever (#426).+///+/// `lambda = 0.02` (the default) yields exactly 30 days, so an operator who+/// never touched decay sees no change.+#[must_use]+pub fn stale_days_for(lambda: f64) -> f64 {+ if lambda.is_finite() && lambda > 0.0 {+ STALE_SCORE_LN / lambda+ } else {+ // Fail back to the historical constant rather than emitting+ // infinity (which would silence the rule) or NaN (which would make+ // every comparison false).+ STALE_DAYS+ }+}+/// Run the lint pass.////// * `llm` — when `Some`, the contradiction pass runs; otherwise the/// report contains only rule-based findings.+/// * `decay_lambda` — the operator's `[decay] lambda`; the stale+/// threshold is derived from it (see [`stale_days_for`])./// * `dry_run` — when `true`, no file is written./// * `use_llm` — when `false`, the contradiction pass is skipped even/// if a provider is present. Lets operators run rule-based-only lint@@ -103,9 +143,10 @@ pub async fn run_lint(project_id: ProjectId,dry_run: bool,use_llm: bool,+ decay_lambda: f64,) -> Result<LintReport, LintError> {let candidates = reader.decay_candidates(workspace_id, project_id).await?;- let mut findings = rule_based_findings(&candidates);+ let mut findings = rule_based_findings(&candidates, stale_days_for(decay_lambda));// Dangling cross-project links: a `[[project:path]]` dependency that does// not resolve. A broken inter-project edge is high-signal — surface it@@ -193,17 +234,17 @@ pub async fn run_lint(Ok(report)}-fn rule_based_findings(candidates: &[DecayCandidate]) -> Vec<LintFinding> {+fn rule_based_findings(candidates: &[DecayCandidate], stale_days: f64) -> Vec<LintFinding> {let now_us = Timestamp::now().as_microsecond();let mut out = Vec::new();let mut titles: std::collections::HashMap<String, Vec<String>> =std::collections::HashMap::new();for c in candidates {- // Stale: episodic, >30d, zero accesses.+ // Stale: episodic, older than the lambda-derived threshold, zero accesses.#[allow(clippy::cast_precision_loss)]let age_days = (now_us - c.updated_at_us) as f64 / US_PER_DAY;- if c.tier == Tier::Episodic && age_days > STALE_DAYS && c.access_count == 0 {+ if c.tier == Tier::Episodic && age_days > stale_days && c.access_count == 0 {out.push(LintFinding {kind: "stale".into(),severity: "info".into(),@@ -406,6 +447,81 @@ fn render_markdown(report: &LintReport) -> String {mod tests {use super::*;+ /// The whole point of #426: an operator who never touched `[decay]`+ /// must see byte-identical behaviour. `0.6 / 0.02` is exactly 30.+ #[test]+ fn default_lambda_reproduces_the_historical_thirty_day_threshold() {+ assert!(+ (stale_days_for(0.02) - STALE_DAYS).abs() < f64::EPSILON,+ "default lambda must reproduce {STALE_DAYS} days, got {}",+ stale_days_for(0.02)+ );+ }++ /// Slower decay must push the lint out with it, not keep flagging on+ /// day 31 while real eviction is 200 days away.+ #[test]+ fn stale_threshold_tracks_lambda() {+ assert!(+ (stale_days_for(0.008) - 75.0).abs() < 1e-9,+ "{}",+ stale_days_for(0.008)+ );+ assert!(+ (stale_days_for(0.04) - 15.0).abs() < 1e-9,+ "{}",+ stale_days_for(0.04)+ );+ // Monotonic: slower decay (smaller lambda) => later staleness.+ assert!(stale_days_for(0.008) > stale_days_for(0.02));+ assert!(stale_days_for(0.04) < stale_days_for(0.02));+ }++ /// A nonsensical lambda must not silence the rule (infinity) or make+ /// every comparison false (NaN); it falls back to the constant.+ #[test]+ fn stale_threshold_fails_back_on_invalid_lambda() {+ for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {+ let days = stale_days_for(bad);+ assert!(+ (days - STALE_DAYS).abs() < f64::EPSILON,+ "lambda {bad} must fall back to {STALE_DAYS}, got {days}"+ );+ }+ }++ /// End-to-end through the rule: a 60-day unread episodic page is stale+ /// at the default lambda but NOT at the slower one the reporter runs.+ #[test]+ fn slower_decay_stops_flagging_a_sixty_day_page() {+ let now_us = jiff::Timestamp::now().as_microsecond();+ let sixty_days_ago = now_us - (60.0 * US_PER_DAY) as i64;+ let candidate = DecayCandidate {+ id: ai_memory_core::PageId::new(),+ path: ai_memory_core::PagePath::new("sessions/2026-06-20.md").unwrap(),+ tier: Tier::Episodic,+ pinned: false,+ updated_at_us: sixty_days_ago,+ access_count: 0,+ last_accessed_at_us: None,+ frontmatter_json: r#"{"title": "A session nobody reopened"}"#.into(),+ expires_at_us: None,+ salience: None,+ };++ let default_lambda = rule_based_findings(&[candidate.clone()], stale_days_for(0.02));+ assert!(+ default_lambda.iter().any(|f| f.kind == "stale"),+ "60d page must be stale at the default lambda"+ );++ let slow_lambda = rule_based_findings(&[candidate], stale_days_for(0.008));+ assert!(+ !slow_lambda.iter().any(|f| f.kind == "stale"),+ "at lambda=0.008 the threshold is 75d, so a 60d page is not stale yet"+ );+ }+#[test]fn lint_prompt_rejects_embedded_wiki_instructions() {assert!(LINT_SYSTEM_PROMPT.contains("## SECURITY BOUNDARY"));@@ -428,7 +544,7 @@ mod tests {expires_at_us: None,salience: None,}];- let findings = rule_based_findings(&candidates);+ let findings = rule_based_findings(&candidates, STALE_DAYS);assert_eq!(findings.len(), 1);assert_eq!(findings[0].kind, "stale");}@@ -451,7 +567,7 @@ mod tests {path: ai_memory_core::PagePath::new("concepts/b.md").unwrap(),..a.clone()};- let findings = rule_based_findings(&[a, b]);+ let findings = rule_based_findings(&[a, b], STALE_DAYS);let dupes: Vec<_> = findings.iter().filter(|f| f.kind == "duplicate").collect();assert_eq!(dupes.len(), 1);assert_eq!(dupes[0].pages.len(), 2);@@ -474,7 +590,7 @@ mod tests {expires_at_us: None,salience: None,};- let findings = rule_based_findings(&[candidate]);+ let findings = rule_based_findings(&[candidate], STALE_DAYS);let rules: Vec<_> = findings.iter().filter(|f| f.kind == "rule_suggestion")@@ -500,7 +616,7 @@ mod tests {expires_at_us: None,salience: None,};- let findings = rule_based_findings(&[candidate]);+ let findings = rule_based_findings(&[candidate], STALE_DAYS);assert!(findings.iter().any(|f| f.kind == "rule_suggestion"),"expected a rule_suggestion finding for _rules/ page",@@ -524,7 +640,7 @@ mod tests {expires_at_us: None,salience: None,};- let findings = rule_based_findings(&[candidate]);+ let findings = rule_based_findings(&[candidate], STALE_DAYS);assert!(findings.iter().all(|f| f.kind != "rule_suggestion"),"non-rule page must not produce a rule_suggestion finding",@@ -582,7 +698,7 @@ mod tests {}];// rule_based_findings is the exact code path that `use_llm=false`// keeps active. Confirm it still fires.- let findings = rule_based_findings(&candidates);+ let findings = rule_based_findings(&candidates, STALE_DAYS);assert!(findings.iter().any(|f| f.kind == "stale"),"rule-based stale finding must be present regardless of use_llm flag",diff --git a/crates/ai-memory-consolidate/tests/lifecycle.rs b/crates/ai-memory-consolidate/tests/lifecycle.rsindex 5fb65163..805e716e 100644--- a/crates/ai-memory-consolidate/tests/lifecycle.rs+++ b/crates/ai-memory-consolidate/tests/lifecycle.rs@@ -426,6 +426,7 @@ async fn m8_retention_lifecycle_end_to_end() {proj,/* dry_run */ true,/* use_llm */ true,+ /* decay_lambda */ ai_memory_store::DecayParams::default().lambda,).await.expect("lint dry-run");diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 8ab19790..c024d53d 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -2716,6 +2716,7 @@ async fn handle_lint(proj,req.dry_run,!req.no_llm,+ state.decay_params.lambda,).await.map(|report| {diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 1018f556..addc1616 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2424,6 +2424,7 @@ impl AiMemoryServer {proj,args.dry_run.unwrap_or(false),!args.no_llm.unwrap_or(false),+ self.decay_params.lambda,).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;