Skip to content

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

Rust

feat(decay): per-tier retention half-life curves (A1)

AkitaOnRails6f664e86aea8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e5dc57e8..de76e71b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Per-tier retention half-life curves (design-memory-aging.md bucket A1): the
+ forget-sweep's decay rate can now be tuned per memory tier via an opt-in
+ `[decay.half_life_days]` config table, replacing the single global λ. Each
+ key (`working` / `episodic` / `semantic` / `procedural`) is a half-life in
+ *days*, converted internally to `λ = ln(2) / days`, so an operator can keep
+ episodic session history longer and working-tier scratch shorter (the
+ mcp-memory-service 365/180/90/30 shape). An omitted key falls back to the
+ scalar `[decay] lambda`, so the default (no table) is byte-identical to the
+ previous single-λ behaviour — an upgrade changes no score and mass-evicts
+ nothing on the first post-upgrade sweep. Pure math + config: no new column,
+ no migration, and no new MCP tool (still 23) (#799).
- Access reinforcement on the remaining read paths (design-memory-aging.md
bucket C1): `memory_read_page` (a direct by-path/by-query read), its
`include_related` link-graph walk (the walked neighbours, not just the seed),
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 5145cc1b..49e1624c 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -46,6 +46,27 @@ 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;
+/// Optional per-tier retention half-lives, expressed in **days**.
+///
+/// This is the operator-facing `[decay.half_life_days]` sub-table. Half-life in
+/// days is the intuitive knob ("episodic pages: a 180-day half-life"); it is
+/// converted to the internal per-day decay rate λ (`λ = ln(2) / days`) in
+/// [`DecaySettings::decay_params`]. Every key is optional: an omitted key falls
+/// back to the scalar `lambda`, so the default (all keys unset) reproduces
+/// today's single-λ behaviour byte-for-byte and no upgrade changes a score.
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
+#[serde(default)]
+pub struct DecayHalfLifeDays {
+ /// Half-life in days for `working`-tier pages; unset uses the scalar λ.
+ pub working: Option<f64>,
+ /// Half-life in days for `episodic`-tier pages; unset uses the scalar λ.
+ pub episodic: Option<f64>,
+ /// Half-life in days for `semantic`-tier pages; unset uses the scalar λ.
+ pub semantic: Option<f64>,
+ /// Half-life in days for `procedural`-tier pages; unset uses the scalar λ.
+ pub procedural: Option<f64>,
+}
+
/// Config-file representation of retention settings.
///
/// The breadth coefficient lives here rather than expanding the public
@@ -73,6 +94,10 @@ pub struct DecaySettings {
pub observation_retention_days: i64,
/// Observation rows deleted per prune transaction.
pub observation_prune_batch: usize,
+ /// Optional per-tier half-life overrides (`[decay.half_life_days]`). All
+ /// keys default to unset ⇒ the scalar `lambda` applies to every tier, which
+ /// is byte-identical to the historical single-λ behaviour.
+ pub half_life_days: DecayHalfLifeDays,
}
impl Default for DecaySettings {
@@ -88,6 +113,7 @@ impl Default for DecaySettings {
breadth_weight: 0.0,
observation_retention_days: 0,
observation_prune_batch: ai_memory_consolidate::DEFAULT_OBSERVATION_PRUNE_BATCH,
+ half_life_days: DecayHalfLifeDays::default(),
}
}
}
@@ -103,6 +129,28 @@ impl DecaySettings {
salience_default: self.salience_default,
cold_threshold: self.cold_threshold,
hard_delete_after_days: self.hard_delete_after_days,
+ // Half-life-in-days is the user surface; λ is the math. Convert here
+ // once. An unset key stays `None`, so `lambda_for` falls back to the
+ // scalar `lambda` unchanged — the identity default, no days↔λ
+ // round-trip that could perturb an unconfigured store's scores.
+ tier_lambda: ai_memory_store::TierLambdas {
+ working: self
+ .half_life_days
+ .working
+ .map(ai_memory_store::lambda_from_half_life_days),
+ episodic: self
+ .half_life_days
+ .episodic
+ .map(ai_memory_store::lambda_from_half_life_days),
+ semantic: self
+ .half_life_days
+ .semantic
+ .map(ai_memory_store::lambda_from_half_life_days),
+ procedural: self
+ .half_life_days
+ .procedural
+ .map(ai_memory_store::lambda_from_half_life_days),
+ },
}
}
@@ -1151,6 +1199,27 @@ impl Config {
);
}
+ // A per-tier half-life must be a real, positive number of days: `0` (or
+ // negative/NaN) would convert to a nonsensical λ (+inf / negative /
+ // NaN) and silently mass-evict or never decay that tier. Reject it at
+ // load rather than at 3am inside the sweep. An unset key is fine — it
+ // falls back to the scalar `lambda`.
+ for (tier, value) in [
+ ("working", config.decay.half_life_days.working),
+ ("episodic", config.decay.half_life_days.episodic),
+ ("semantic", config.decay.half_life_days.semantic),
+ ("procedural", config.decay.half_life_days.procedural),
+ ] {
+ if let Some(days) = value
+ && (!days.is_finite() || days <= 0.0)
+ {
+ anyhow::bail!(
+ "decay.half_life_days.{tier} must be a finite number greater than zero \
+ (got {days}); omit the key to use the default decay rate"
+ );
+ }
+ }
+
// Fail closed at load rather than at 3am inside a destructive pass: a
// negative age would be a nonsensical cutoff, and a zero batch would
// spin the prune loop forever without deleting anything.
@@ -2246,6 +2315,97 @@ mod tests {
}
}
+ /// `[decay.half_life_days]` parses per-tier half-lives (in days) and
+ /// converts each to the internal λ; an omitted key falls back to the scalar
+ /// `lambda`, so the resulting `DecayParams` is a pure identity for every
+ /// unset tier.
+ #[test]
+ fn load_parses_per_tier_half_lives_and_falls_back_for_omitted_keys() {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("config.toml");
+ std::fs::write(
+ &config_path,
+ "[decay.half_life_days]\nepisodic = 365.0\nworking = 7.0\n",
+ )
+ .unwrap();
+ let cfg = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();
+ let params = cfg.decay.decay_params();
+
+ // Configured tiers convert days -> λ = ln(2) / days.
+ let expect = |days: f64| std::f64::consts::LN_2 / days;
+ assert_eq!(
+ params.lambda_for(ai_memory_core::Tier::Episodic).to_bits(),
+ expect(365.0).to_bits(),
+ );
+ assert_eq!(
+ params.lambda_for(ai_memory_core::Tier::Working).to_bits(),
+ expect(7.0).to_bits(),
+ );
+ // Omitted tiers fall back to the scalar λ, byte-for-byte.
+ assert_eq!(
+ params.lambda_for(ai_memory_core::Tier::Semantic).to_bits(),
+ params.lambda.to_bits(),
+ );
+ assert_eq!(
+ params
+ .lambda_for(ai_memory_core::Tier::Procedural)
+ .to_bits(),
+ params.lambda.to_bits(),
+ );
+ }
+
+ /// With no `[decay.half_life_days]` table the resolved `DecayParams` is the
+ /// store default: every tier's λ is the scalar `lambda` (the identity
+ /// upgrade guarantee at the config layer).
+ #[test]
+ fn load_without_half_lives_is_identity_to_the_default_params() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = Config::load(None, Some(tmp.path().to_path_buf())).unwrap();
+ let params = cfg.decay.decay_params();
+ let default = ai_memory_store::DecayParams::default();
+ for tier in [
+ ai_memory_core::Tier::Working,
+ ai_memory_core::Tier::Episodic,
+ ai_memory_core::Tier::Semantic,
+ ai_memory_core::Tier::Procedural,
+ ] {
+ assert_eq!(
+ params.lambda_for(tier).to_bits(),
+ default.lambda_for(tier).to_bits(),
+ "tier {tier:?} must decay at the default scalar λ",
+ );
+ }
+ }
+
+ /// A zero, negative, or non-finite half-life converts to a nonsensical λ,
+ /// so it is rejected at load rather than silently mass-evicting (or never
+ /// decaying) that tier.
+ #[test]
+ fn load_rejects_invalid_per_tier_half_lives() {
+ for (tier, value) in [
+ ("episodic", "0.0"),
+ ("working", "-5.0"),
+ ("semantic", "nan"),
+ ("procedural", "inf"),
+ ] {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("config.toml");
+ std::fs::write(
+ &config_path,
+ format!("[decay.half_life_days]\n{tier} = {value}\n"),
+ )
+ .unwrap();
+ let error = Config::load(Some(&config_path), Some(tmp.path().to_path_buf()))
+ .expect_err("an invalid per-tier half-life must fail closed");
+ assert!(
+ error
+ .to_string()
+ .contains(&format!("decay.half_life_days.{tier}")),
+ "unexpected error for {tier} = {value}: {error:#}"
+ );
+ }
+ }
+
/// A negative retention age or a zero batch is rejected at load, beside
/// the breadth-weight guard, so a destructive pass can never be configured
/// into a nonsensical shape.
diff --git a/crates/ai-memory-consolidate/src/curator.rs b/crates/ai-memory-consolidate/src/curator.rs
index 424ff031..8d469a27 100644
--- a/crates/ai-memory-consolidate/src/curator.rs
+++ b/crates/ai-memory-consolidate/src/curator.rs
@@ -135,6 +135,7 @@ pub async fn run_curator_report_with_breadth(
let days_since_access = c.last_accessed_at_us.map(|us| age_days(now_us, us));
let score = retention_score_with_breadth(
&params.decay_params,
+ c.tier,
page_age_days,
c.access_count,
days_since_access,
diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rs
index b7dcfc19..8ab8bade 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -275,6 +275,7 @@ pub async fn run_sweep_with_options(
let days_since_access = c.last_accessed_at_us.map(|us| elapsed_days(now_us, us));
let score = retention_score_with_breadth(
params,
+ c.tier,
age_days,
c.access_count,
days_since_access,
diff --git a/crates/ai-memory-consolidate/tests/suite/access_breadth_sweep.rs b/crates/ai-memory-consolidate/tests/suite/access_breadth_sweep.rs
index 483e1c87..298483e5 100644
--- a/crates/ai-memory-consolidate/tests/suite/access_breadth_sweep.rs
+++ b/crates/ai-memory-consolidate/tests/suite/access_breadth_sweep.rs
@@ -125,7 +125,14 @@ async fn default_weight_scores_identically_however_many_operators_read_the_page(
assert_eq!(e.access_count, ACCESS_COUNT);
assert_eq!(
e.retention,
- retention_score(&params, e.age_days, e.access_count, Some(e.age_days), None),
+ retention_score(
+ &params,
+ Tier::Episodic,
+ e.age_days,
+ e.access_count,
+ Some(e.age_days),
+ None,
+ ),
"{} scored differently from the pre-breadth formula",
e.path,
);
@@ -281,7 +288,14 @@ async fn curator_scores_match_the_pre_breadth_formula_at_the_default_weight() {
for (path, score, age_days) in &cold {
assert_eq!(
*score,
- retention_score(&params, *age_days, ACCESS_COUNT, Some(*age_days), None),
+ retention_score(
+ &params,
+ Tier::Episodic,
+ *age_days,
+ ACCESS_COUNT,
+ Some(*age_days),
+ None,
+ ),
"{path} scored differently from the pre-breadth formula",
);
}
diff --git a/crates/ai-memory-store/src/decay.rs b/crates/ai-memory-store/src/decay.rs
index 35ce5d44..16fd0bb9 100644
--- a/crates/ai-memory-store/src/decay.rs
+++ b/crates/ai-memory-store/src/decay.rs
@@ -10,13 +10,65 @@
//! The forget-sweep job computes it from store rows; the property tests
//! pin the math without touching the database.
+use ai_memory_core::Tier;
use serde::{Deserialize, Serialize};
+/// Convert a half-life expressed in **days** to the per-day exponential decay
+/// rate λ the retention formula uses: `λ = ln(2) / half_life_days`.
+///
+/// The config surface talks in half-lives ("episodic pages: 180-day
+/// half-life") because that is the intuitive knob; the math needs λ. This is
+/// the single conversion both live and reused by the config layer. Callers are
+/// responsible for rejecting a non-positive `half_life_days` (config validation
+/// does): passing `0.0` yields `+inf` and a negative value a negative λ, either
+/// of which would be a nonsensical curve rather than a silent fallback.
+#[must_use]
+pub fn lambda_from_half_life_days(half_life_days: f64) -> f64 {
+ std::f64::consts::LN_2 / half_life_days
+}
+
+/// Per-`Tier` decay-rate (λ) overrides.
+///
+/// A closed, `Copy` struct — one `Option<f64>` per tier — rather than a
+/// `HashMap<Tier, f64>`: the four tiers are a closed enum, so a fixed struct
+/// keeps [`DecayParams`] `Copy` (a map would not) and needs no allocation on
+/// the sweep's hot batch path. `None` for a tier means "fall back to the scalar
+/// [`DecayParams::lambda`]", so the default (every tier `None`) reproduces the
+/// single-λ behaviour byte-for-byte — there is no eviction cliff to migrate
+/// around. Each `Some` value is a λ (already converted from the operator's
+/// half-life-in-days via [`lambda_from_half_life_days`]).
+#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
+pub struct TierLambdas {
+ /// λ override for [`Tier::Working`]; `None` uses the scalar λ.
+ pub working: Option<f64>,
+ /// λ override for [`Tier::Episodic`]; `None` uses the scalar λ.
+ pub episodic: Option<f64>,
+ /// λ override for [`Tier::Semantic`]; `None` uses the scalar λ.
+ pub semantic: Option<f64>,
+ /// λ override for [`Tier::Procedural`]; `None` uses the scalar λ.
+ pub procedural: Option<f64>,
+}
+
+impl TierLambdas {
+ /// The λ override recorded for `tier`, if any.
+ #[must_use]
+ pub fn get(&self, tier: Tier) -> Option<f64> {
+ match tier {
+ Tier::Working => self.working,
+ Tier::Episodic => self.episodic,
+ Tier::Semantic => self.semantic,
+ Tier::Procedural => self.procedural,
+ }
+ }
+}
+
/// Tunable retention coefficients.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct DecayParams {
/// Per-day exponential decay rate applied to "age since updated_at".
- /// `0.02` ≈ 35-day half-life.
+ /// `0.02` ≈ 35-day half-life. Used for any tier without a
+ /// [`DecayParams::tier_lambda`] override, so it stays the single knob a
+ /// zero-config store decays by.
pub lambda: f64,
/// Magnitude of the access-reinforcement boost.
pub sigma: f64,
@@ -30,6 +82,11 @@ pub struct DecayParams {
/// Days an evicted page's tombstone and version ancestry survive before
/// permanent deletion.
pub hard_delete_after_days: i64,
+ /// Optional per-tier λ overrides. Default (all `None`) falls back to the
+ /// scalar [`DecayParams::lambda`] for every tier — byte-identical to the
+ /// pre-per-tier behaviour. An operator sets these to keep, e.g., episodic
+ /// history longer and working-tier scratch shorter.
+ pub tier_lambda: TierLambdas,
}
impl Default for DecayParams {
@@ -41,10 +98,24 @@ impl Default for DecayParams {
salience_default: 1.0,
cold_threshold: 0.20,
hard_delete_after_days: 180,
+ tier_lambda: TierLambdas::default(),
}
}
}
+impl DecayParams {
+ /// The decay rate λ for a page in `tier`: its per-tier override when one is
+ /// set, otherwise the scalar [`DecayParams::lambda`].
+ ///
+ /// The fallback returns `self.lambda` *unchanged* (not a days↔λ round-trip
+ /// of it), so a store with no per-tier config scores exactly as it did
+ /// before this existed.
+ #[must_use]
+ pub fn lambda_for(&self, tier: Tier) -> f64 {
+ self.tier_lambda.get(tier).unwrap_or(self.lambda)
+ }
+}
+
/// Compute the retention score. Higher = "keep this page".
///
/// * `age_days` — days since the page's `updated_at`.
@@ -58,6 +129,7 @@ impl Default for DecayParams {
#[must_use]
pub fn retention_score(
params: &DecayParams,
+ tier: Tier,
age_days: f64,
access_count: u32,
days_since_access: Option<f64>,
@@ -65,6 +137,7 @@ pub fn retention_score(
) -> f64 {
retention_score_with_breadth(
params,
+ tier,
age_days,
access_count,
days_since_access,
@@ -90,9 +163,19 @@ pub fn retention_score(
///
/// `salience` is the page's own feedback-moved salience; it scales the time
/// term independently of breadth, which scales the access term.
+///
+/// `tier` selects the decay rate λ via [`DecayParams::lambda_for`]: with the
+/// default (empty) per-tier map every tier resolves to the scalar
+/// [`DecayParams::lambda`], so the score is identical for every tier until an
+/// operator configures a per-tier curve.
+// Each argument is an independent, orthogonal input to the pure formula
+// (page state and tuning coefficients); bundling them into a struct would only
+// move the same fields behind a name and obscure the call sites in the sweep.
+#[allow(clippy::too_many_arguments)]
#[must_use]
pub fn retention_score_with_breadth(
params: &DecayParams,
+ tier: Tier,
age_days: f64,
access_count: u32,
days_since_access: Option<f64>,
@@ -110,7 +193,7 @@ pub fn retention_score_with_breadth(
} else {
0.0
};
- let time_term = salience * (-params.lambda * age_days).exp();
+ let time_term = salience * (-params.lambda_for(tier) * age_days).exp();
// g(0) = g(1) = 1, monotonically non-decreasing afterwards.
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| {
@@ -156,27 +239,27 @@ pub fn salience_after_feedback(
#[cfg(test)]
mod tests {
use super::*;
- use ai_memory_core::FeedbackKind;
+ use ai_memory_core::{FeedbackKind, Tier};
#[test]
fn fresh_unused_page_starts_near_salience() {
let p = DecayParams::default();
- let score = retention_score(&p, 0.0, 0, None, None);
+ let score = retention_score(&p, Tier::Episodic, 0.0, 0, None, None);
assert!((score - p.salience_default).abs() < 1e-9);
}
#[test]
fn ancient_page_with_no_access_decays_below_threshold() {
let p = DecayParams::default();
- let score = retention_score(&p, 365.0, 0, None, None);
+ let score = retention_score(&p, Tier::Episodic, 365.0, 0, None, None);
assert!(score < p.cold_threshold, "got {score}");
}
#[test]
fn frequently_accessed_page_stays_above_threshold_even_old() {
let p = DecayParams::default();
- let aged_unused = retention_score(&p, 200.0, 0, None, None);
- let aged_hot = retention_score(&p, 200.0, 50, Some(2.0), None);
+ let aged_unused = retention_score(&p, Tier::Episodic, 200.0, 0, None, None);
+ let aged_hot = retention_score(&p, Tier::Episodic, 200.0, 50, Some(2.0), None);
assert!(aged_unused < p.cold_threshold);
assert!(
aged_hot > p.cold_threshold,
@@ -187,24 +270,24 @@ mod tests {
#[test]
fn recent_access_boosts_more_than_old_access() {
let p = DecayParams::default();
- let recent = retention_score(&p, 100.0, 10, Some(2.0), None);
- let stale = retention_score(&p, 100.0, 10, Some(120.0), None);
+ let recent = retention_score(&p, Tier::Episodic, 100.0, 10, Some(2.0), None);
+ let stale = retention_score(&p, Tier::Episodic, 100.0, 10, Some(120.0), None);
assert!(recent > stale, "recent {recent} vs stale {stale}");
}
#[test]
fn score_decreases_as_age_increases_without_access() {
let p = DecayParams::default();
- let young = retention_score(&p, 10.0, 0, None, None);
- let old = retention_score(&p, 20.0, 0, None, None);
+ let young = retention_score(&p, Tier::Episodic, 10.0, 0, None, None);
+ let old = retention_score(&p, Tier::Episodic, 20.0, 0, None, None);
assert!(young > old, "young {young} vs old {old}");
}
#[test]
fn score_increases_with_access_count_when_access_age_matches() {
let p = DecayParams::default();
- let low = retention_score(&p, 100.0, 1, Some(5.0), None);
- let high = retention_score(&p, 100.0, 20, Some(5.0), None);
+ let low = retention_score(&p, Tier::Episodic, 100.0, 1, Some(5.0), None);
+ let high = retention_score(&p, Tier::Episodic, 100.0, 20, Some(5.0), None);
assert!(high > low, "high {high} vs low {low}");
}
@@ -212,15 +295,16 @@ mod tests {
fn explicit_salience_scales_the_time_term_only() {
let p = DecayParams::default();
// No access term: the score is purely salience · exp(−λt).
- let default = retention_score(&p, 30.0, 0, None, None);
- let boosted = retention_score(&p, 30.0, 0, None, Some(2.0));
- let dropped = retention_score(&p, 30.0, 0, None, Some(SALIENCE_MIN));
+ let default = retention_score(&p, Tier::Episodic, 30.0, 0, None, None);
+ let boosted = retention_score(&p, Tier::Episodic, 30.0, 0, None, Some(2.0));
+ let dropped = retention_score(&p, Tier::Episodic, 30.0, 0, None, Some(SALIENCE_MIN));
assert!((boosted - 2.0 * default).abs() < 1e-9);
assert!(dropped < default, "floor salience must score below default");
// With an access term, only the time half scales.
- let with_access_default = retention_score(&p, 30.0, 10, Some(1.0), None);
- let with_access_boosted = retention_score(&p, 30.0, 10, Some(1.0), Some(2.0));
+ let with_access_default = retention_score(&p, Tier::Episodic, 30.0, 10, Some(1.0), None);
+ let with_access_boosted =
+ retention_score(&p, Tier::Episodic, 30.0, 10, Some(1.0), Some(2.0));
assert!((with_access_boosted - with_access_default - default).abs() < 1e-9);
}
@@ -228,8 +312,15 @@ mod tests {
fn salience_none_matches_explicit_default() {
let p = DecayParams::default();
assert!(
- (retention_score(&p, 42.0, 3, Some(7.0), None)
- - retention_score(&p, 42.0, 3, Some(7.0), Some(p.salience_default)))
+ (retention_score(&p, Tier::Episodic, 42.0, 3, Some(7.0), None)
+ - retention_score(
+ &p,
+ Tier::Episodic,
+ 42.0,
+ 3,
+ Some(7.0),
+ Some(p.salience_default)
+ ))
.abs()
< 1e-12,
"NULL salience must read exactly as salience_default",
@@ -267,10 +358,88 @@ mod tests {
// The floor must not make an actively-used page sweep-eligible:
// feedback lowers confidence, the sweep decides eviction.
let p = DecayParams::default();
- let fresh_floored = retention_score(&p, 0.0, 0, None, Some(SALIENCE_MIN));
+ let fresh_floored = retention_score(&p, Tier::Episodic, 0.0, 0, None, Some(SALIENCE_MIN));
assert!(
fresh_floored > p.cold_threshold,
"fresh floored page should survive: {fresh_floored}",
);
}
+
+ /// Load-bearing upgrade guarantee: with the DEFAULT (empty) per-tier map,
+ /// every tier scores byte-for-byte identically to the historical scalar-λ
+ /// formula. This is what proves an upgrade never changes a score or
+ /// mass-evicts on the first post-upgrade forget-sweep.
+ #[test]
+ fn default_params_are_byte_identical_to_the_scalar_lambda_formula_for_every_tier() {
+ let p = DecayParams::default();
+ // The pre-per-tier formula, written out against the scalar lambda.
+ let reference =
+ |age_days: f64, access_count: u32, since: Option<f64>, salience: Option<f64>| {
+ let salience = salience.unwrap_or(p.salience_default);
+ let time_term = salience * (-p.lambda * age_days).exp();
+ let access_term = since.map_or(0.0, |d| {
+ p.sigma * (1.0 + f64::from(access_count)).ln() * (-p.mu * d).exp()
+ });
+ time_term + access_term
+ };
+ for tier in [
+ Tier::Working,
+ Tier::Episodic,
+ Tier::Semantic,
+ Tier::Procedural,
+ ] {
+ for age in [0.0, 1.0, 35.0, 200.0, 365.0, 1000.0] {
+ for count in [0u32, 1, 7, 50] {
+ for since in [None, Some(0.0), Some(3.0), Some(90.0)] {
+ for salience in [None, Some(SALIENCE_MIN), Some(1.0), Some(2.0)] {
+ let got = retention_score(&p, tier, age, count, since, salience);
+ let want = reference(age, count, since, salience);
+ assert_eq!(
+ got.to_bits(),
+ want.to_bits(),
+ "tier {tier:?} age {age} count {count} since {since:?} \
+ salience {salience:?} must match the scalar-λ formula exactly",
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /// A non-default map lets tiers age at different rates: an old episodic page
+ /// on a long half-life survives while an equally-old working page on a short
+ /// one falls below the cold threshold. Tiers left unset still decay at the
+ /// scalar rate (identity).
+ #[test]
+ fn per_tier_half_lives_evict_by_tier() {
+ let p = DecayParams {
+ tier_lambda: TierLambdas {
+ working: Some(lambda_from_half_life_days(7.0)),
+ episodic: Some(lambda_from_half_life_days(365.0)),
+ ..TierLambdas::default()
+ },
+ ..DecayParams::default()
+ };
+ // 90 days: many working half-lives, a fraction of an episodic one.
+ let age = 90.0;
+ // Unused, feedback-free pages: only the time term (per-tier λ) matters.
+ let working = retention_score(&p, Tier::Working, age, 0, None, None);
+ let episodic = retention_score(&p, Tier::Episodic, age, 0, None, None);
+ assert!(
+ working < p.cold_threshold,
+ "short-half-life working page should be cold: {working}",
+ );
+ assert!(
+ episodic > p.cold_threshold,
+ "long-half-life episodic page should survive: {episodic}",
+ );
+ // A tier with no override is byte-identical to the default params.
+ let semantic = retention_score(&p, Tier::Semantic, age, 0, None, None);
+ assert_eq!(
+ semantic.to_bits(),
+ retention_score(&DecayParams::default(), Tier::Semantic, age, 0, None, None).to_bits(),
+ "an un-overridden tier must be unchanged from the default",
+ );
+ }
}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 2dedfc2d..8566d38a 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -44,8 +44,9 @@ pub use auto_improve::{
StageAutoImproveRun, StagedAutoImproveRun, StagedAutoImproveRunReport, artifact_path_for,
};
pub use decay::{
- DecayParams, SALIENCE_MAX, SALIENCE_MIN, SALIENCE_STEP, retention_score,
- retention_score_with_breadth, salience_after_feedback,
+ DecayParams, SALIENCE_MAX, SALIENCE_MIN, SALIENCE_STEP, TierLambdas,
+ lambda_from_half_life_days, retention_score, retention_score_with_breadth,
+ salience_after_feedback,
};
pub use error::{StoreError, StoreResult};
pub use maintenance::MaintenanceJob;
diff --git a/crates/ai-memory-store/tests/suite/access_breadth.rs b/crates/ai-memory-store/tests/suite/access_breadth.rs
index 30322eee..40ae7674 100644
--- a/crates/ai-memory-store/tests/suite/access_breadth.rs
+++ b/crates/ai-memory-store/tests/suite/access_breadth.rs
@@ -34,6 +34,7 @@ fn breadth_is_identity_at_the_default_weight() {
assert_eq!(
retention_score_with_breadth(
&params,
+ Tier::Episodic,
age,
count,
since,
@@ -41,7 +42,7 @@ fn breadth_is_identity_at_the_default_weight() {
actors,
breadth_weight,
),
- retention_score(&params, age, count, since, None),
+ retention_score(&params, Tier::Episodic, age, count, since, None),
"default weight must be identity (actors={actors})"
);
}
@@ -56,17 +57,44 @@ fn breadth_is_identity_at_the_default_weight() {
fn zero_and_one_actor_score_identically_even_when_weighted() {
let params = DecayParams::default();
let breadth_weight = 1.5;
- let baseline = retention_score(&params, 30.0, 5, Some(3.0), None);
+ let baseline = retention_score(&params, Tier::Episodic, 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, breadth_weight,),
+ retention_score_with_breadth(
+ &params,
+ Tier::Episodic,
+ 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, breadth_weight);
- let ten = retention_score_with_breadth(&params, 30.0, 5, Some(3.0), None, 10, breadth_weight);
+ let two = retention_score_with_breadth(
+ &params,
+ Tier::Episodic,
+ 30.0,
+ 5,
+ Some(3.0),
+ None,
+ 2,
+ breadth_weight,
+ );
+ let ten = retention_score_with_breadth(
+ &params,
+ Tier::Episodic,
+ 30.0,
+ 5,
+ Some(3.0),
+ None,
+ 10,
+ breadth_weight,
+ );
assert!(two > baseline);
assert!(ten > two);
}
@@ -77,18 +105,27 @@ fn zero_and_one_actor_score_identically_even_when_weighted() {
fn never_accessed_pages_are_unaffected_by_breadth() {
let params = DecayParams::default();
assert_eq!(
- retention_score_with_breadth(&params, 10.0, 0, None, None, 9, 2.0),
- retention_score(&params, 10.0, 0, None, None)
+ retention_score_with_breadth(&params, Tier::Episodic, 10.0, 0, None, None, 9, 2.0),
+ retention_score(&params, Tier::Episodic, 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);
+ let baseline = retention_score(&params, Tier::Episodic, 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),
+ retention_score_with_breadth(
+ &params,
+ Tier::Episodic,
+ 30.0,
+ 5,
+ Some(3.0),
+ None,
+ 50,
+ weight
+ ),
baseline,
);
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 238a504b..bb6c0cdd 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -307,6 +307,11 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| Semantic | Indefinite | None - only supersedeable via M7 LLM rewrite |
| Procedural | Indefinite | Frequency-decay if not re-observed |
+`λ` is the scalar `[decay] lambda` by default, but can be set per tier via
+`[decay.half_life_days]` (a half-life in days per tier, converted to
+`λ = ln(2)/days`); an unset tier uses the scalar, so the default reproduces
+today's single-λ scores exactly.
+
Pinned pages (`pinned: true` in frontmatter) are exempt from all
decay paths. Pages under `_slots/` are pinned automatically and surfaced
in briefing/explore snapshots as tiny editable memory slots. Slot pages
@@ -572,7 +577,7 @@ run_autowire = true # `ai-memory run <harness>` auto-installs tha
# one-time per harness+version). Also `--no-autowire`.
[decay] # M8 retention params
-lambda = 0.02 # ↓ to forget less aggressively
+lambda = 0.02 # ↓ to forget less aggressively (fallback λ)
sigma = 0.6 # ↑ to reward query-hits more
mu = 0.04 # ↑ if recent hits should count more
cold_threshold = 0.20 # below this → remove file + retain tombstone
@@ -581,6 +586,17 @@ breadth_weight = 0.0 # opt-in reward for distinct operators
observation_retention_days = 0 # 0 = never prune raw observations
observation_prune_batch = 5000 # rows per prune transaction
+[decay.half_life_days] # opt-in per-tier retention curves (all keys
+ # optional). Half-life in DAYS; converted to
+ # λ = ln(2)/days. An omitted key falls back to
+ # the scalar `lambda` above, so the default
+ # (no keys) is byte-identical to today — no
+ # score change or mass-eviction on upgrade.
+# working = 7 # e.g. keep scratch short…
+# episodic = 365 # …and session history long
+# semantic = 180
+# procedural = 90
+
[slots] # optional shared-server injection boundary
per_user = false # shared + own slots in agent context