Skip to content

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

Rust

feat(decay): extractive tier-down of cold episodic pages (A2)

AkitaOnRailsec18487a5f3a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26e52e96..eb570a6d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Extractive tier-down of cold episodic pages (design-memory-aging.md bucket
+ A2): instead of evicting a cold episodic page, the forget-sweep can now
+ *compact* it — keeping the L0 frontmatter `abstract:`, an L1 first-paragraph
+ summary, and an L2 regex-mined keep-token set (file paths, URLs, inline-code
+ spans, error codes, `UPPER_SNAKE` constants and long identifiers), and
+ dropping the prose body. Tier-down beats eviction because the durable facts
+ survive while the expensive, low-signal prose does not. It is **opt-in and
+ off by default** via `[decay] compact_cold_episodic` (a `false` default, so an
+ upgrade changes nothing until an operator opts in), fully zero-LLM (regex
+ only), and **reversible and non-destructive**: the rewrite goes through the
+ wiki layer, so the full pre-compaction body stays reachable in git history and
+ the supersession chain and is recoverable with `restore-page`. A new `V65`
+ migration adds a nullable `pages.compacted_at` marker (additive `ADD COLUMN`,
+ no backfill; populated lazily by the sweep from a `compacted: true` frontmatter
+ mirror) so the sweep and the curator tell a deliberately-short compacted page
+ from a cold one — a compacted page is never re-compacted, re-evicted, or
+ re-reported as cold. Only unpinned episodic pages compact; pinned/semantic/
+ procedural pages are never touched. Every run reports what it compacted in the
+ `SweepReport`. Ships opt-in/off; the R2 recall no-regression proof is the gate
+ before any future default-on. No new MCP tool (still 23) (#808).
- 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
diff --git a/Cargo.lock b/Cargo.lock
index 8a04b7fb..55fe520a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -92,6 +92,7 @@ dependencies = [
"async-trait",
"git2",
"jiff",
+ "regex",
"rusqlite",
"schemars",
"serde",
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 08d6f669..32a529bf 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -9,7 +9,7 @@ use std::time::Duration;
use ai_memory_consolidate::{
AutoImproveReviewConfig, Consolidator, EmbedBackfillOptions, ObservationRetention,
ScheduledAutoImproveSettings, run_auto_improve_scheduler_tick, run_embedding_backfill,
- run_lint, run_sweep_with_options,
+ run_lint, run_sweep_with_compaction,
};
use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};
use ai_memory_hooks::{
@@ -1027,6 +1027,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
.with_decay_params(decay_params)
.with_decay_breadth_weight(config.decay.breadth_weight)
.with_observation_retention(config.decay.observation_retention())
+ .with_compact_cold_episodic(config.decay.compact_cold_episodic)
.with_auto_improve_require_approval(config.auto_improve.require_approval)
.with_auto_improve_review_config(auto_improve_review_config_from_settings(
&config.auto_improve,
@@ -1263,6 +1264,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
},
config.decay.breadth_weight,
config.decay.observation_retention(),
+ config.decay.compact_cold_episodic,
);
// Multi-rung auth assembly:
// - rung 0 (no bearer_token configured) → AuthState::new
@@ -1601,6 +1603,7 @@ async fn start_maintenance_scheduler(
&decay.decay_params(),
decay.breadth_weight,
decay.observation_retention(),
+ decay.compact_cold_episodic,
)
.await?;
if outcome.errors > 0 {
@@ -1613,6 +1616,7 @@ async fn start_maintenance_scheduler(
scopes = outcome.scopes,
candidates_evaluated = outcome.candidates_evaluated,
evicted = outcome.evicted,
+ compacted = outcome.compacted,
expired = outcome.expired,
hard_deleted = outcome.hard_deleted,
observations_pruned = outcome.observations_pruned,
@@ -1867,6 +1871,7 @@ struct ScheduledSweepTickOutcome {
scopes: usize,
candidates_evaluated: usize,
evicted: usize,
+ compacted: usize,
expired: usize,
hard_deleted: usize,
observations_pruned: usize,
@@ -1880,6 +1885,7 @@ async fn run_scheduled_sweep_tick(
decay: &ai_memory_store::DecayParams,
breadth_weight: f64,
retention: ObservationRetention,
+ compact_cold_episodic: bool,
) -> Result<ScheduledSweepTickOutcome> {
let scopes = reader.list_all_scopes().await?;
let mut outcome = ScheduledSweepTickOutcome {
@@ -1888,7 +1894,7 @@ async fn run_scheduled_sweep_tick(
};
for scope in scopes {
- match run_sweep_with_options(
+ match run_sweep_with_compaction(
reader,
writer,
Some(wiki),
@@ -1897,6 +1903,7 @@ async fn run_scheduled_sweep_tick(
decay,
breadth_weight,
retention,
+ compact_cold_episodic,
false,
)
.await
@@ -1904,6 +1911,11 @@ async fn run_scheduled_sweep_tick(
Ok(report) => {
outcome.candidates_evaluated += report.candidates_evaluated;
outcome.evicted += report.evicted.iter().filter(|page| page.deleted).count();
+ outcome.compacted += report
+ .compacted
+ .iter()
+ .filter(|page| page.compacted)
+ .count();
outcome.expired += report.expired.len();
outcome.hard_deleted += report.hard_deleted;
outcome.observations_pruned += report.observations_pruned;
@@ -3652,6 +3664,7 @@ mod tests {
&decay,
0.0,
ObservationRetention::default(),
+ false,
)
.await
.unwrap();
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 49e1624c..0fe483a9 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -94,6 +94,13 @@ pub struct DecaySettings {
pub observation_retention_days: i64,
/// Observation rows deleted per prune transaction.
pub observation_prune_batch: usize,
+ /// A2 extractive tier-down (`[decay] compact_cold_episodic`). When `true`,
+ /// the forget sweep COMPACTS a cold episodic page — keeping its L0 abstract,
+ /// an L1 summary and the L2 keep-token set, dropping the prose — instead of
+ /// evicting it. Reversible (the full body stays in git + the supersession
+ /// chain) and non-destructive. Defaults to `false`, so an upgrade changes
+ /// nothing until an operator opts in.
+ pub compact_cold_episodic: bool,
/// 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.
@@ -113,6 +120,7 @@ impl Default for DecaySettings {
breadth_weight: 0.0,
observation_retention_days: 0,
observation_prune_batch: ai_memory_consolidate::DEFAULT_OBSERVATION_PRUNE_BATCH,
+ compact_cold_episodic: false,
half_life_days: DecayHalfLifeDays::default(),
}
}
diff --git a/crates/ai-memory-consolidate/Cargo.toml b/crates/ai-memory-consolidate/Cargo.toml
index b1879557..188c37e6 100644
--- a/crates/ai-memory-consolidate/Cargo.toml
+++ b/crates/ai-memory-consolidate/Cargo.toml
@@ -22,6 +22,9 @@ thiserror.workspace = true
serde.workspace = true
serde_json.workspace = true
schemars.workspace = true
+# A2 keep-token miner: file paths / URLs / code spans / error codes, compiled
+# once via `LazyLock`. Same crate + version the core sanitizer already uses.
+regex.workspace = true
sha2.workspace = true
tokio.workspace = true
tracing.workspace = true
diff --git a/crates/ai-memory-consolidate/src/compaction.rs b/crates/ai-memory-consolidate/src/compaction.rs
new file mode 100644
index 00000000..ccbef050
--- /dev/null
+++ b/crates/ai-memory-consolidate/src/compaction.rs
@@ -0,0 +1,163 @@
+//! Extractive tier-down body rewrite for A2 (docs/design-memory-aging.md §A2).
+//!
+//! Given a cold episodic page's frontmatter and body, build the *compacted*
+//! replacement: keep the L0 abstract (it already lives in the frontmatter, so
+//! it survives untouched), an L1 first-paragraph/frontmatter summary, and the
+//! L2 regex-mined keep-token set; drop the prose body. The frontmatter gains a
+//! `compacted: true` mirror of the V65 `pages.compacted_at` column.
+//!
+//! Pure and zero-LLM (invariant #13): the whole rewrite is regex + string
+//! assembly, no provider. The original full body is never destroyed — the
+//! caller writes this through the wiki layer, which supersedes the prior
+//! version (invariant #16), keeping it reachable in git history and the
+//! supersession chain.
+
+use crate::keep_tokens::mine_keep_tokens;
+
+/// The footer stamped on every compacted body so a reader (human or agent) sees
+/// at a glance that prose was dropped and where the full version lives.
+pub(crate) const COMPACTION_FOOTER: &str = "_Extractively compacted from a cold episodic page (A2 tier-down). The full \
+ pre-compaction body is retained in git history and the supersession chain, \
+ and can be recovered with `restore-page`._";
+
+/// Longest L1 summary carried into a compacted body. A summary is a pointer,
+/// not the page.
+const MAX_SUMMARY_LEN: usize = 500;
+
+/// Build the compacted frontmatter + body for a page.
+///
+/// Returns `(frontmatter, body)` where the frontmatter is the original with a
+/// `compacted: true` marker added (and its L0 `abstract:` preserved) and the
+/// body is the L1 summary + L2 keep-tokens + footer, with the prose dropped.
+#[must_use]
+pub fn build_compacted_markdown(
+ frontmatter: &serde_json::Value,
+ body: &str,
+) -> (serde_json::Value, String) {
+ let mut fm = match frontmatter {
+ serde_json::Value::Object(m) => m.clone(),
+ _ => serde_json::Map::new(),
+ };
+ fm.insert("compacted".to_string(), serde_json::Value::Bool(true));
+
+ let summary = summary_line(&fm, body);
+ let tokens = mine_keep_tokens(body);
+
+ let mut out = String::new();
+ if let Some(summary) = &summary {
+ out.push_str(summary);
+ out.push_str("\n\n");
+ }
+ if !tokens.is_empty() {
+ out.push_str("## Retained facts\n\n");
+ for token in &tokens {
+ // Wrap in backticks so identifiers/paths render verbatim and stay
+ // single FTS tokens on re-index.
+ out.push_str("- `");
+ out.push_str(token);
+ out.push_str("`\n");
+ }
+ out.push('\n');
+ }
+ out.push_str(COMPACTION_FOOTER);
+ out.push('\n');
+
+ (serde_json::Value::Object(fm), out)
+}
+
+/// The L1 summary: prefer an explicit frontmatter `summary:` / `abstract:`
+/// line, else the first non-empty, non-heading paragraph of the body. Bounded.
+fn summary_line(fm: &serde_json::Map<String, serde_json::Value>, body: &str) -> Option<String> {
+ for key in ["summary", "abstract"] {
+ if let Some(text) = fm.get(key).and_then(serde_json::Value::as_str) {
+ let trimmed = text.trim();
+ if !trimmed.is_empty() {
+ return Some(truncate(trimmed));
+ }
+ }
+ }
+ for paragraph in body.split("\n\n") {
+ let trimmed = paragraph.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ // Collapse internal newlines so a wrapped first paragraph stays one line.
+ let collapsed = trimmed.split_whitespace().collect::<Vec<_>>().join(" ");
+ if !collapsed.is_empty() {
+ return Some(truncate(&collapsed));
+ }
+ }
+ None
+}
+
+/// Truncate on a char boundary, appending an ellipsis when it actually cut.
+fn truncate(text: &str) -> String {
+ if text.len() <= MAX_SUMMARY_LEN {
+ return text.to_string();
+ }
+ let mut end = MAX_SUMMARY_LEN;
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ format!("{}…", &text[..end])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn marks_frontmatter_and_preserves_abstract() {
+ let fm = serde_json::json!({"title": "Fix", "abstract": "One-line summary."});
+ let (out_fm, _body) = build_compacted_markdown(&fm, "prose body here");
+ assert_eq!(
+ out_fm.get("compacted"),
+ Some(&serde_json::Value::Bool(true))
+ );
+ assert_eq!(
+ out_fm.get("abstract").and_then(|v| v.as_str()),
+ Some("One-line summary."),
+ "L0 abstract survives"
+ );
+ assert_eq!(out_fm.get("title").and_then(|v| v.as_str()), Some("Fix"));
+ }
+
+ #[test]
+ fn keeps_tokens_and_drops_prose() {
+ let fm = serde_json::json!({"title": "Fix"});
+ // First paragraph is the L1 summary; the prose tail (a later paragraph)
+ // is dropped, though its keep-tokens are still mined from the full body.
+ let body = "Fixed the flaky sweep test.\n\n\
+ The root cause was in crates/ai-memory-store/src/ops.rs and produced \
+ E0433. Everyone agreed it was subtle and worth writing down carefully.";
+ let (_fm, out) = build_compacted_markdown(&fm, body);
+ assert!(
+ out.contains("crates/ai-memory-store/src/ops.rs"),
+ "keep-token survives: {out}"
+ );
+ assert!(out.contains("E0433"), "error code survives: {out}");
+ assert!(
+ !out.contains("worth writing down carefully"),
+ "trailing prose dropped: {out}"
+ );
+ assert!(out.contains("A2 tier-down"), "footer present: {out}");
+ }
+
+ #[test]
+ fn prefers_frontmatter_summary_for_l1() {
+ let fm = serde_json::json!({"summary": "The gist."});
+ let (_fm, out) = build_compacted_markdown(&fm, "some other first paragraph");
+ assert!(out.starts_with("The gist."), "{out}");
+ assert!(!out.contains("some other first paragraph"), "{out}");
+ }
+
+ #[test]
+ fn pure_prose_still_produces_a_valid_compacted_body() {
+ let fm = serde_json::json!({"title": "Chat"});
+ let (_fm, out) = build_compacted_markdown(&fm, "we talked and agreed to revisit");
+ // First paragraph becomes the L1 summary; no keep-tokens section.
+ assert!(out.contains("we talked and agreed to revisit"), "{out}");
+ assert!(!out.contains("## Retained facts"), "{out}");
+ assert!(out.contains("A2 tier-down"), "{out}");
+ }
+}
diff --git a/crates/ai-memory-consolidate/src/curator.rs b/crates/ai-memory-consolidate/src/curator.rs
index 8d469a27..6d649fb8 100644
--- a/crates/ai-memory-consolidate/src/curator.rs
+++ b/crates/ai-memory-consolidate/src/curator.rs
@@ -131,6 +131,13 @@ pub async fn run_curator_report_with_breadth(
if c.tier != Tier::Episodic || c.pinned || frontmatter_pinned(&c.frontmatter_json) {
continue;
}
+ // A2: a page already tiered down (its V65 marker set) is a deliberately
+ // short compacted residue, not a fresh cold candidate. The sweep will
+ // never touch it again, so the curator must not report it as cold —
+ // `cold_episodic` is a prediction of what the sweep would evict.
+ if c.compacted_at_us.is_some() {
+ continue;
+ }
let page_age_days = age_days(now_us, c.updated_at_us);
let days_since_access = c.last_accessed_at_us.map(|us| age_days(now_us, us));
let score = retention_score_with_breadth(
diff --git a/crates/ai-memory-consolidate/src/keep_tokens.rs b/crates/ai-memory-consolidate/src/keep_tokens.rs
new file mode 100644
index 00000000..a11d7af5
--- /dev/null
+++ b/crates/ai-memory-consolidate/src/keep_tokens.rs
@@ -0,0 +1,199 @@
+//! Pure, zero-LLM keep-token miner for A2 extractive tier-down
+//! (docs/design-memory-aging.md §A2).
+//!
+//! When the forget sweep tiers a cold episodic page DOWN instead of evicting
+//! it, the prose body is dropped but the *durable facts* must survive. This
+//! module mines those facts with regexes only — no provider, no network
+//! (invariant #13, zero-LLM). The hypothesis A2 tests is that the identifiers,
+//! file paths, URLs, code spans and error codes in a session note are what a
+//! later search actually needs; the surrounding prose is the expensive,
+//! low-signal part.
+//!
+//! The patterns are compiled once via [`std::sync::LazyLock`] and reused, the
+//! same shape the core sanitizer uses for its built-in patterns. The function
+//! is pure and bounded (deduped, capped count and length) so a pathological
+//! body cannot blow up the compacted page.
+
+use std::collections::HashSet;
+use std::sync::LazyLock;
+
+use regex::Regex;
+
+/// Maximum distinct keep-tokens mined from one body. A compacted page is a
+/// terse residue, not a second copy of the body; the cap keeps it that way.
+const MAX_TOKENS: usize = 48;
+/// Tokens longer than this are almost certainly a run-on match, not a fact.
+const MAX_TOKEN_LEN: usize = 128;
+/// Below this a token carries no signal (single characters, stray punctuation).
+const MIN_TOKEN_LEN: usize = 2;
+
+/// One ordered set of pattern + capture-group, evaluated over the whole body.
+struct Pattern {
+ re: Regex,
+ /// Capture group whose text is the token (0 = the whole match).
+ group: usize,
+}
+
+/// The mined token classes, in the order they are appended (higher-signal
+/// classes first, so the cap keeps the most useful tokens when a body overflows
+/// it).
+static PATTERNS: LazyLock<Vec<Pattern>> = LazyLock::new(|| {
+ let raw: &[(&str, usize)] = &[
+ // URLs (http/https). Trailing sentence punctuation is trimmed below.
+ (r#"https?://[^\s<>()\[\]"'`]+"#, 0),
+ // File paths: a slash-separated path ending in an extension …
+ (r"\b(?:[A-Za-z0-9_.-]+/)+[A-Za-z0-9_.-]+\.[A-Za-z0-9]+\b", 0),
+ // … or a bare filename with a recognised source/config extension.
+ (
+ r"\b[A-Za-z0-9_.-]+\.(?:rs|md|toml|sql|json|ya?ml|sh|py|js|ts|tsx|jsx|rb|go|c|h|cc|cpp|hpp|txt|lock|cfg|ini|env|xml|html|css|proto)\b",
+ 0,
+ ),
+ // Rust-style error codes (E0433) and HTTP status codes (HTTP 500).
+ (r"\bE\d{2,4}\b", 0),
+ (r"\bHTTP\s?\d{3}\b", 0),
+ // Inline code spans: keep the inner text, not the backticks.
+ (r"`([^`\n]{1,120})`", 1),
+ // UPPER_SNAKE_CASE constants and env-var names.
+ (r"\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b", 0),
+ // Long identifiers: snake_case (has `_`) or camelCase (lower→Upper).
+ (
+ r"\b(?:[a-z][a-z0-9]*_[a-z0-9_]+|[a-z][a-z0-9]*[A-Z][A-Za-z0-9]*)\b",
+ 0,
+ ),
+ ];
+ raw.iter()
+ .map(|(p, group)| Pattern {
+ re: Regex::new(p).expect("keep-token pattern must compile"),
+ group: *group,
+ })
+ .collect()
+});
+
+/// Extract the durable keep-token set from a page body.
+///
+/// Deterministic, order-preserving (first occurrence wins), deduped, and
+/// bounded in both count and per-token length. Returns an empty vector for pure
+/// prose with no identifiers — which is exactly the signal that such a body was
+/// safe to drop.
+#[must_use]
+pub fn mine_keep_tokens(body: &str) -> Vec<String> {
+ let mut seen: HashSet<String> = HashSet::new();
+ let mut out: Vec<String> = Vec::new();
+ for pattern in PATTERNS.iter() {
+ for caps in pattern.re.captures_iter(body) {
+ let Some(m) = caps.get(pattern.group) else {
+ continue;
+ };
+ let token = trim_token(m.as_str());
+ if token.len() < MIN_TOKEN_LEN || token.len() > MAX_TOKEN_LEN {
+ continue;
+ }
+ if seen.insert(token.to_string()) {
+ out.push(token.to_string());
+ if out.len() >= MAX_TOKENS {
+ return out;
+ }
+ }
+ }
+ }
+ out
+}
+
+/// Trim wrapping punctuation a regex greedily swallowed at a token's edges — a
+/// URL at the end of a sentence, a path inside parentheses — without touching
+/// the token's interior.
+fn trim_token(raw: &str) -> &str {
+ raw.trim().trim_matches(|c: char| {
+ matches!(
+ c,
+ '.' | ',' | ';' | ':' | ')' | '(' | '"' | '\'' | '<' | '>' | '`'
+ )
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn fix_note_keeps_paths_error_codes_and_urls() {
+ let body = "We fixed the panic in crates/ai-memory-store/src/ops.rs by \
+ guarding the upsert. The compiler reported E0433 and the server \
+ returned HTTP 500. See https://github.com/akitaonrails/ai-memory/issues/776 \
+ for the write-up. The env var AI_MEMORY_AUTH_TOKEN was unset.";
+ let tokens = mine_keep_tokens(body);
+ assert!(
+ tokens.contains(&"crates/ai-memory-store/src/ops.rs".to_string()),
+ "file path survives: {tokens:?}"
+ );
+ assert!(
+ tokens.contains(&"E0433".to_string()),
+ "error code: {tokens:?}"
+ );
+ assert!(
+ tokens.iter().any(|t| t == "HTTP 500" || t == "HTTP500"),
+ "HTTP status survives: {tokens:?}"
+ );
+ assert!(
+ tokens
+ .iter()
+ .any(|t| t.contains("github.com/akitaonrails/ai-memory")),
+ "URL survives: {tokens:?}"
+ );
+ assert!(
+ tokens.contains(&"AI_MEMORY_AUTH_TOKEN".to_string()),
+ "UPPER_SNAKE constant: {tokens:?}"
+ );
+ }
+
+ #[test]
+ fn inline_code_span_keeps_inner_text_without_backticks() {
+ let tokens = mine_keep_tokens("call `run_sweep_with_compaction` from serve");
+ assert!(
+ tokens.contains(&"run_sweep_with_compaction".to_string()),
+ "{tokens:?}"
+ );
+ assert!(
+ !tokens.iter().any(|t| t.contains('`')),
+ "backticks are stripped: {tokens:?}"
+ );
+ }
+
+ #[test]
+ fn pure_prose_yields_little_or_nothing() {
+ // No identifiers, paths, URLs, or codes — the case where dropping the
+ // body loses nothing a search would want.
+ let tokens = mine_keep_tokens(
+ "We talked for a while about the plan and agreed to revisit it later \
+ once everyone had time to think it over more carefully.",
+ );
+ assert!(
+ tokens.is_empty(),
+ "prose with no durable facts mines nothing: {tokens:?}"
+ );
+ }
+
+ #[test]
+ fn output_is_deduped_and_order_preserving() {
+ let body = "ops.rs then ops.rs again, and ops.rs a third time; then lib.rs.";
+ let tokens = mine_keep_tokens(body);
+ assert_eq!(
+ tokens.iter().filter(|t| *t == "ops.rs").count(),
+ 1,
+ "deduped: {tokens:?}"
+ );
+ let ops = tokens.iter().position(|t| t == "ops.rs");
+ let lib = tokens.iter().position(|t| t == "lib.rs");
+ assert!(ops < lib, "first occurrence order preserved: {tokens:?}");
+ }
+
+ #[test]
+ fn token_count_is_bounded() {
+ let mut body = String::new();
+ for i in 0..500 {
+ body.push_str(&format!("file_number_{i}.rs "));
+ }
+ let tokens = mine_keep_tokens(&body);
+ assert!(tokens.len() <= MAX_TOKENS, "count capped: {}", tokens.len());
+ }
+}
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 2c6f8689..872612ed 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -12,10 +12,12 @@ pub mod auto_improve;
pub mod auto_improve_schedule;
pub mod auto_improve_telemetry;
pub mod bootstrap;
+pub mod compaction;
pub mod consolidator;
pub mod curator;
pub mod embed;
pub mod experience;
+pub mod keep_tokens;
pub mod lint;
pub mod projection;
pub mod sweep;
@@ -52,6 +54,7 @@ pub use bootstrap::{
derive_project_name, discover_main_repo_root, discover_repo_root, effective_chunk_budget,
plan_bootstrap_chunks, prune_sources_to_budget,
};
+pub use compaction::build_compacted_markdown;
pub use consolidator::{
BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult,
DEFAULT_CONSOLIDATION_MAX_INPUT_TOKENS, DEFAULT_CONSOLIDATION_MAX_OUTPUT_TOKENS,
@@ -65,10 +68,12 @@ pub use embed::{
EmbedBackfillCounts, EmbedBackfillError, EmbedBackfillOptions, run_embedding_backfill,
};
pub use experience::{EXPERIENCE_SYSTEM_PROMPT, ExperienceConfig, run_experience_review};
+pub use keep_tokens::mine_keep_tokens;
pub use lint::{LintError, LintFinding, LintOptions, LintReport, run_lint, stale_days_for};
pub use sweep::{
- DEFAULT_OBSERVATION_PRUNE_BATCH, EvictedPage, ObservationRetention, SweepError, SweepReport,
- run_sweep, run_sweep_with_breadth, run_sweep_with_options,
+ CompactedPage, DEFAULT_OBSERVATION_PRUNE_BATCH, EvictedPage, ObservationRetention, SweepError,
+ SweepReport, run_sweep, run_sweep_with_breadth, run_sweep_with_compaction,
+ run_sweep_with_options,
};
pub use types::{
ConsolidatedBatch, ConsolidatedPage, ConsolidatedPageUpdate, ConsolidationOutcome, PageKind,
diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rs
index fd8fdc02..76815245 100644
--- a/crates/ai-memory-consolidate/src/lint.rs
+++ b/crates/ai-memory-consolidate/src/lint.rs
@@ -670,6 +670,7 @@ mod tests {
frontmatter_json: r#"{"title": "A session nobody reopened"}"#.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let default_lambda =
@@ -707,6 +708,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
}];
let findings = rule_based_findings(&candidates, STALE_DAYS);
assert_eq!(findings.len(), 1);
@@ -726,6 +728,7 @@ mod tests {
frontmatter_json: r#"{"title": "Karpathy Wiki"}"#.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let b = DecayCandidate {
path: ai_memory_core::PagePath::new("concepts/b.md").unwrap(),
@@ -752,6 +755,7 @@ mod tests {
frontmatter_json: r#"{"title": ""}"#.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let blank = DecayCandidate {
path: ai_memory_core::PagePath::new("concepts/b.md").unwrap(),
@@ -781,6 +785,7 @@ mod tests {
.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let findings = rule_based_findings(&[candidate], STALE_DAYS);
let rules: Vec<_> = findings
@@ -807,6 +812,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let findings = rule_based_findings(&[candidate], STALE_DAYS);
assert!(
@@ -831,6 +837,7 @@ mod tests {
frontmatter_json: r#"{"title": "Karpathy Wiki", "kind": "fact"}"#.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
let findings = rule_based_findings(&[candidate], STALE_DAYS);
assert!(
@@ -887,6 +894,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
}];
// rule_based_findings is the exact code path that `use_llm=false`
// keeps active. Confirm it still fires.
diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rs
index 8ab8bade..e4313899 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -29,15 +29,17 @@
use std::collections::{HashMap, HashSet};
-use ai_memory_core::{PageId, ProjectId, Tier, WorkspaceId};
+use ai_memory_core::{ActorContext, PageId, PagePath, ProjectId, Tier, WorkspaceId};
use ai_memory_store::{
DecayCandidate, DecayParams, ReaderPool, WriterHandle, retention_score_with_breadth,
};
-use ai_memory_wiki::Wiki;
+use ai_memory_wiki::{Wiki, WritePageRequest};
use jiff::Timestamp;
use serde::Serialize;
use thiserror::Error;
+use crate::compaction::build_compacted_markdown;
+
/// One evicted page surfaced in the [`SweepReport`].
#[derive(Debug, Clone, Serialize)]
pub struct EvictedPage {
@@ -56,6 +58,30 @@ pub struct EvictedPage {
pub deleted: bool,
}
+/// One cold episodic page tiered DOWN (extractively compacted) instead of
+/// evicted, surfaced in the [`SweepReport`] (A2, docs/design-memory-aging.md).
+#[derive(Debug, Clone, Serialize)]
+pub struct CompactedPage {
+ /// Identifier of the pre-compaction page version selected for tier-down.
+ pub id: PageId,
+ /// Relative wiki path.
+ pub path: String,
+ /// Retention score at the time of the sweep (below the cold threshold).
+ pub retention: f64,
+ /// Days since the page's last update.
+ pub age_days: f64,
+ /// Total access count.
+ pub access_count: u32,
+ /// `true` when the compacting rewrite landed through the wiki layer.
+ /// Always `false` on `dry_run`; a failed rewrite is retried next sweep.
+ pub compacted: bool,
+ /// Identifier of the new compacted latest version, once the rewrite lands.
+ /// The prior full-body version stays reachable via the supersession chain
+ /// and git history, so tier-down is reversible.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub new_id: Option<PageId>,
+}
+
/// One TTL-expired page surfaced in the [`SweepReport`].
#[derive(Debug, Clone, Serialize)]
pub struct ExpiredPage {
@@ -82,6 +108,11 @@ pub struct SweepReport {
/// Pages that fell below the cold threshold (evicted through the wiki
/// layer unless `dry_run`).
pub evicted: Vec<EvictedPage>,
+ /// Cold episodic pages tiered DOWN (extractively compacted) instead of
+ /// evicted, when `compact_cold_episodic` is enabled (A2). Empty — and the
+ /// sweep behaves exactly as before — while the flag is off, which is the
+ /// default. Reported in both modes so every run is observable.
+ pub compacted: Vec<CompactedPage>,
/// Pages past their frontmatter `expires_at:` TTL (hard-deleted
/// through the wiki layer unless `dry_run`).
pub expired: Vec<ExpiredPage>,
@@ -223,7 +254,10 @@ pub async fn run_sweep_with_breadth(
/// Run a sweep with the breadth coefficient and the opt-in observation prune.
///
/// The prune is the only pass that can delete raw capture, and it is off unless
-/// `retention.days` is positive.
+/// `retention.days` is positive. Extractive tier-down (A2) is left OFF, so this
+/// behaves exactly as it did before A2 existed — cold episodic pages are
+/// evicted (tombstoned). Callers that want tier-down use
+/// [`run_sweep_with_compaction`].
///
/// # Errors
/// Returns [`SweepError::InvalidObservationRetention`] for a negative age, in
@@ -239,6 +273,50 @@ pub async fn run_sweep_with_options(
breadth_weight: f64,
retention: ObservationRetention,
dry_run: bool,
+) -> Result<SweepReport, SweepError> {
+ run_sweep_with_compaction(
+ reader,
+ writer,
+ wiki,
+ workspace_id,
+ project_id,
+ params,
+ breadth_weight,
+ retention,
+ false,
+ dry_run,
+ )
+ .await
+}
+
+/// Run a sweep with the breadth coefficient, the observation prune, and the
+/// opt-in A2 extractive tier-down (`compact_cold_episodic`).
+///
+/// With `compact_cold_episodic = false` (the default everywhere) this is
+/// byte-for-byte the historical sweep: a cold episodic page is evicted
+/// (tombstoned). With it `true`, a cold episodic page that has NOT already been
+/// compacted is tiered DOWN instead — rewritten through the wiki layer to keep
+/// its L0 abstract, an L1 summary and the L2 keep-token set, dropping the prose
+/// — and reported under [`SweepReport::compacted`] rather than `evicted`. The
+/// original full body stays reachable via supersession + git (reversible,
+/// invariant #16). An already-compacted cold page (its V65 marker set) is
+/// terminal for the decay pass: it is neither re-compacted nor evicted, so the
+/// durable residue survives.
+///
+/// # Errors
+/// Same as [`run_sweep_with_options`].
+#[allow(clippy::too_many_arguments)]
+pub async fn run_sweep_with_compaction(
+ reader: &ReaderPool,
+ writer: &WriterHandle,
+ wiki: Option<&Wiki>,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ params: &DecayParams,
+ breadth_weight: f64,
+ retention: ObservationRetention,
+ compact_cold_episodic: bool,
+ dry_run: bool,
) -> Result<SweepReport, SweepError> {
if !breadth_weight.is_finite() || breadth_weight < 0.0 {
return Err(SweepError::InvalidBreadthWeight);
@@ -252,6 +330,7 @@ pub async fn run_sweep_with_options(
let now_us = Timestamp::now().as_microsecond();
let mut evicted = Vec::new();
+ let mut compacted: Vec<CompactedPage> = Vec::new();
let mut expired: Vec<ExpiredPage> = Vec::new();
for c in &candidates {
@@ -284,14 +363,34 @@ pub async fn run_sweep_with_options(
breadth_weight,
);
if score < params.cold_threshold {
- evicted.push(EvictedPage {
- id: c.id,
- path: c.path.as_str().to_string(),
- retention: score,
- age_days,
- access_count: c.access_count,
- deleted: false,
- });
+ if compact_cold_episodic {
+ // A2 tier-down replaces eviction for cold episodic pages. An
+ // already-compacted page (its V65 marker set) is terminal — the
+ // durable residue is what we chose to keep, so re-evicting it
+ // would destroy exactly what tier-down preserved, and
+ // re-compacting it is a no-op loop. Skip it entirely.
+ if c.compacted_at_us.is_some() {
+ continue;
+ }
+ compacted.push(CompactedPage {
+ id: c.id,
+ path: c.path.as_str().to_string(),
+ retention: score,
+ age_days,
+ access_count: c.access_count,
+ compacted: false,
+ new_id: None,
+ });
+ } else {
+ evicted.push(EvictedPage {
+ id: c.id,
+ path: c.path.as_str().to_string(),
+ retention: score,
+ age_days,
+ access_count: c.access_count,
+ deleted: false,
+ });
+ }
}
}
@@ -339,6 +438,74 @@ pub async fn run_sweep_with_options(
}
}
}
+ // A2 compaction runs BEFORE the decay-eviction pass. When
+ // `compact_cold_episodic` is on, `evicted` is empty and this pass owns
+ // the cold episodic pages; when it is off, `compacted` is empty and this
+ // pass is a no-op, so the historical eviction path below is unchanged.
+ //
+ // One batched wiki write for the whole cold set (invariant #2): the
+ // rewrite supersedes each page's prior version, keeping the full body
+ // reachable (invariant #16) through git + the supersession chain.
+ if !compacted.is_empty() {
+ match wiki {
+ Some(wiki) => {
+ let mut requests: Vec<WritePageRequest> = Vec::new();
+ let mut request_index: Vec<usize> = Vec::new();
+ for (i, page) in compacted.iter().enumerate() {
+ let path = match PagePath::new(page.path.clone()) {
+ Ok(path) => path,
+ Err(_) => continue,
+ };
+ let markdown = match wiki.read_page(workspace_id, project_id, &path) {
+ Ok(md) => md,
+ Err(error) => {
+ tracing::warn!(
+ path = %page.path,
+ %error,
+ "forget sweep: could not read page for compaction; retrying next sweep"
+ );
+ continue;
+ }
+ };
+ let (frontmatter, body) =
+ build_compacted_markdown(&markdown.frontmatter, &markdown.body);
+ requests.push(WritePageRequest {
+ workspace_id,
+ project_id,
+ path,
+ frontmatter,
+ body,
+ tier: Tier::Episodic,
+ pinned: false,
+ title: None,
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ evidence: Vec::new(),
+ });
+ request_index.push(i);
+ }
+ if !requests.is_empty() {
+ match wiki.apply_batch(requests).await {
+ Ok(new_ids) => {
+ for (slot, new_id) in request_index.into_iter().zip(new_ids) {
+ compacted[slot].compacted = true;
+ compacted[slot].new_id = Some(new_id);
+ }
+ }
+ Err(error) => tracing::warn!(
+ %error,
+ "forget sweep: compaction batch failed; retrying on next sweep"
+ ),
+ }
+ }
+ }
+ None => {
+ tracing::warn!("forget sweep: wiki unavailable; refusing store-only compaction")
+ }
+ }
+ }
+
for page in &mut evicted {
let path = match ai_memory_core::PagePath::new(page.path.clone()) {
Ok(path) => path,
@@ -430,6 +597,7 @@ pub async fn run_sweep_with_options(
dry_run,
candidates_evaluated: candidates.len(),
evicted,
+ compacted,
expired,
hard_deleted,
observations_prunable,
@@ -503,6 +671,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
assert!(!is_decayable(&c));
}
@@ -520,6 +689,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
assert!(!is_decayable(&c));
}
@@ -537,6 +707,7 @@ mod tests {
frontmatter_json: r#"{"pinned": true}"#.into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
assert!(!is_decayable(&c));
}
@@ -554,6 +725,7 @@ mod tests {
frontmatter_json: "{}".into(),
expires_at_us: None,
salience: None,
+ compacted_at_us: None,
};
assert!(is_decayable(&c));
}
diff --git a/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs b/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs
new file mode 100644
index 00000000..883c90d6
--- /dev/null
+++ b/crates/ai-memory-consolidate/tests/suite/compaction_sweep.rs
@@ -0,0 +1,491 @@
+//! A2 extractive tier-down, end to end through a real Store + Wiki.
+//!
+//! The invariants this file guards (docs/design-memory-aging.md §A2):
+//!
+//! 1. **Flag OFF = today's behaviour.** A cold episodic page is EVICTED
+//! (tombstoned), not compacted — an upgrade surprises no one.
+//! 2. **Flag ON = compaction.** The same page is tiered down: the new latest
+//! version keeps its L0 abstract, an L1 summary and the L2 keep-tokens, drops
+//! the prose, sets the V65 `compacted_at` marker and the `compacted: true`
+//! frontmatter mirror, and is reported under `SweepReport.compacted`, not
+//! `evicted`.
+//! 3. **Keep-tokens survive.** A file path + error code + URL seeded in the body
+//! are present in the compacted body.
+//! 4. **Reversible.** The pre-compaction full body stays reachable via the
+//! supersession chain and is recoverable with `restore_page_from_checkpoint`.
+//! 5. **No re-compaction.** A second sweep does not re-compact an
+//! already-compacted page, and the curator does not re-report it as cold.
+//! 6. **Only episodic.** Pinned / semantic / procedural pages never compact.
+
+use ai_memory_consolidate::ObservationRetention;
+use ai_memory_consolidate::{
+ CuratorParams, run_curator_report, run_sweep_with_compaction, run_sweep_with_options,
+};
+use ai_memory_core::{ActorContext, PageId, PagePath, ProjectId, Tier, WorkspaceId};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::{Wiki, WritePageRequest};
+use rusqlite::params;
+use tempfile::TempDir;
+
+const DAY_US: i64 = 86_400_000_000;
+
+struct Fixture {
+ tmp: TempDir,
+ store: Store,
+ wiki: Wiki,
+ ws: WorkspaceId,
+ proj: ProjectId,
+}
+
+async fn seed_fixture() -> Fixture {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ // The reader is required by the sweep's `evict_page_if_latest` guard; the
+ // compaction path also reads the page body back through the wiki.
+ let wiki = Wiki::new(tmp.path(), store.writer.clone())
+ .unwrap()
+ .with_store_reader(store.reader.clone());
+ Fixture {
+ tmp,
+ store,
+ wiki,
+ ws,
+ proj,
+ }
+}
+
+async fn write(
+ fx: &Fixture,
+ path: &str,
+ title: &str,
+ tier: Tier,
+ pinned: bool,
+ body: &str,
+) -> PageId {
+ fx.wiki
+ .write_page(WritePageRequest {
+ workspace_id: fx.ws,
+ project_id: fx.proj,
+ path: PagePath::new(path).unwrap(),
+ frontmatter: serde_json::json!({"title": title}),
+ body: body.to_string(),
+ tier,
+ pinned,
+ title: Some(title.to_string()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap()
+}
+
+/// Push the current `is_latest` version of `path` back in time so it scores as
+/// cold. Mirrors the aux-connection trick the other sweep/curator tests use.
+fn backdate_latest(fx: &Fixture, path: &str, days: i64) {
+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();
+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();
+ let updated_at = jiff::Timestamp::now().as_microsecond() - days * DAY_US;
+ conn.execute(
+ "UPDATE pages SET created_at = ?1, updated_at = ?1 \
+ WHERE workspace_id = ?2 AND project_id = ?3 AND path = ?4 AND is_latest = 1",
+ params![updated_at, fx.ws.as_bytes(), fx.proj.as_bytes(), path,],
+ )
+ .unwrap();
+}
+
+/// The `compacted_at` marker on the current latest version of `path`, and its
+/// body, straight from SQLite.
+fn latest_marker_and_body(fx: &Fixture, path: &str) -> (Option<i64>, String) {
+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();
+ conn.query_row(
+ "SELECT compacted_at, body FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",
+ params![fx.ws.as_bytes(), fx.proj.as_bytes(), path],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap()
+}
+
+/// Every historical (superseded) body for `path`, oldest first — the
+/// supersession chain the reversibility guarantee rests on.
+fn superseded_bodies(fx: &Fixture, path: &str) -> Vec<String> {
+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();
+ let mut stmt = conn
+ .prepare(
+ "SELECT body FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 0 \
+ ORDER BY created_at",
+ )
+ .unwrap();
+ let rows = stmt
+ .query_map(params![fx.ws.as_bytes(), fx.proj.as_bytes(), path], |row| {
+ row.get::<_, String>(0)
+ })
+ .unwrap();
+ rows.map(Result::unwrap).collect()
+}
+
+const COLD_DAYS: i64 = 400;
+
+/// Test 1: with the flag OFF the sweep evicts a cold episodic page exactly as it
+/// always has — no compaction, no upgrade surprise.
+#[tokio::test]
+async fn flag_off_evicts_cold_episodic_page_unchanged() {
+ let fx = seed_fixture().await;
+ let id = write(
+ &fx,
+ "sessions/old.md",
+ "Old Session",
+ Tier::Episodic,
+ false,
+ "a long prose body about a debugging session that nobody reopened",
+ )
+ .await;
+ backdate_latest(&fx, "sessions/old.md", COLD_DAYS);
+
+ let report = run_sweep_with_options(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ report
+ .evicted
+ .iter()
+ .map(|e| e.path.as_str())
+ .collect::<Vec<_>>(),
+ vec!["sessions/old.md"],
+ "flag off must evict the cold page"
+ );
+ assert!(report.evicted[0].deleted, "eviction must have landed");
+ assert!(
+ report.compacted.is_empty(),
+ "nothing is compacted with the flag off"
+ );
+ // The evicted page is a decay tombstone (not is_latest) — same as before A2.
+ let _ = id;
+ assert!(
+ fx.store
+ .reader
+ .decay_candidates(fx.ws, fx.proj)
+ .await
+ .unwrap()
+ .is_empty(),
+ "the evicted page is gone from the live set"
+ );
+}
+
+/// Test 2 + 3: with the flag ON the same page is compacted, not evicted; the
+/// marker and frontmatter mirror are set; keep-tokens survive and prose drops.
+#[tokio::test]
+async fn flag_on_compacts_cold_episodic_and_keeps_durable_facts() {
+ let fx = seed_fixture().await;
+ // First paragraph → L1 summary; the second paragraph is droppable prose,
+ // but its file path / error code / URL are mined as keep-tokens from the
+ // full body and survive.
+ let body = "Fixed the flaky sweep test after an afternoon of chasing it.\n\n\
+ The root cause lived in crates/ai-memory-store/src/ops.rs and surfaced as \
+ E0433 during the build; the server also returned HTTP 500. Details at \
+ https://github.com/akitaonrails/ai-memory/issues/776 which everyone agreed \
+ was worth writing down in careful, unnecessary, easily-forgotten prose.";
+ write(
+ &fx,
+ "sessions/fix.md",
+ "The Fix",
+ Tier::Episodic,
+ false,
+ body,
+ )
+ .await;
+ backdate_latest(&fx, "sessions/fix.md", COLD_DAYS);
+
+ let report = run_sweep_with_compaction(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ true,
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ report.evicted.is_empty(),
+ "the flag redirects the cold page from eviction to compaction: {:?}",
+ report.evicted
+ );
+ assert_eq!(
+ report
+ .compacted
+ .iter()
+ .map(|c| c.path.as_str())
+ .collect::<Vec<_>>(),
+ vec!["sessions/fix.md"],
+ "the cold page is reported as compacted"
+ );
+ assert!(
+ report.compacted[0].compacted,
+ "the rewrite must have landed"
+ );
+ assert!(
+ report.compacted[0].new_id.is_some(),
+ "new version id reported"
+ );
+
+ let (marker, compacted_body) = latest_marker_and_body(&fx, "sessions/fix.md");
+ assert!(marker.is_some(), "V65 compacted_at marker is set");
+
+ // Keep-tokens (L2) survive.
+ assert!(
+ compacted_body.contains("crates/ai-memory-store/src/ops.rs"),
+ "file path survives: {compacted_body}"
+ );
+ assert!(compacted_body.contains("E0433"), "error code survives");
+ assert!(
+ compacted_body.contains("github.com/akitaonrails/ai-memory"),
+ "URL survives"
+ );
+ // Prose (the low-signal tail) is dropped.
+ assert!(
+ !compacted_body.contains("easily-forgotten prose"),
+ "prose body dropped: {compacted_body}"
+ );
+
+ // Frontmatter mirror on disk.
+ let md = fx
+ .wiki
+ .read_page(fx.ws, fx.proj, &PagePath::new("sessions/fix.md").unwrap())
+ .unwrap();
+ assert_eq!(
+ md.frontmatter.get("compacted").and_then(|v| v.as_bool()),
+ Some(true),
+ "frontmatter carries the compacted: true mirror"
+ );
+}
+
+/// Test 4: the pre-compaction full body stays reachable via the supersession
+/// chain and is recoverable through `restore_page_from_checkpoint`.
+#[tokio::test]
+async fn compaction_is_reversible() {
+ let fx = seed_fixture().await;
+ let original_body = "The original full prose body with a keeper path lib.rs and \
+ plenty of easily-forgotten narrative that compaction is meant to drop.";
+ write(
+ &fx,
+ "sessions/reversible.md",
+ "Reversible",
+ Tier::Episodic,
+ false,
+ original_body,
+ )
+ .await;
+ // Snapshot the original in git before compaction rewrites the working file.
+ let rev = fx.wiki.commit_all("seed").unwrap().unwrap().to_string();
+ backdate_latest(&fx, "sessions/reversible.md", COLD_DAYS);
+
+ run_sweep_with_compaction(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ true,
+ false,
+ )
+ .await
+ .unwrap();
+
+ // (a) The prior full body is still in the store's supersession chain.
+ let prior = superseded_bodies(&fx, "sessions/reversible.md");
+ assert!(
+ prior
+ .iter()
+ .any(|b| b.contains("easily-forgotten narrative")),
+ "the pre-compaction body stays reachable via supersession: {prior:?}"
+ );
+
+ // (b) And it is recoverable through the git checkpoint restore path.
+ fx.wiki
+ .restore_page_from_checkpoint(
+ fx.ws,
+ fx.proj,
+ PagePath::new("sessions/reversible.md").unwrap(),
+ &rev,
+ )
+ .await
+ .unwrap();
+ let (_marker, restored) = latest_marker_and_body(&fx, "sessions/reversible.md");
+ assert!(
+ restored.contains("easily-forgotten narrative"),
+ "restore-page brings the original body back: {restored}"
+ );
+}
+
+/// Test 5: a compacted page is terminal for the decay pass — a second sweep does
+/// not re-compact it, and the curator does not re-report it as cold.
+#[tokio::test]
+async fn no_recompaction_and_curator_skips_compacted_pages() {
+ let fx = seed_fixture().await;
+ write(
+ &fx,
+ "sessions/twice.md",
+ "Twice",
+ Tier::Episodic,
+ false,
+ "a body mentioning ops.rs and E0001 among some throwaway prose",
+ )
+ .await;
+ backdate_latest(&fx, "sessions/twice.md", COLD_DAYS);
+
+ let first = run_sweep_with_compaction(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ true,
+ false,
+ )
+ .await
+ .unwrap();
+ assert_eq!(first.compacted.len(), 1, "first sweep compacts once");
+
+ // Age the compacted version so it would be cold again if the marker did not
+ // block it.
+ backdate_latest(&fx, "sessions/twice.md", COLD_DAYS);
+ let second = run_sweep_with_compaction(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ true,
+ false,
+ )
+ .await
+ .unwrap();
+ assert!(
+ second.compacted.is_empty(),
+ "the marker blocks re-compaction: {:?}",
+ second.compacted
+ );
+ assert!(
+ second.evicted.is_empty(),
+ "a compacted page is terminal: it is neither re-compacted nor evicted"
+ );
+
+ // The curator (which predicts what the sweep would evict) must not report a
+ // compacted page as cold.
+ let report = run_curator_report(
+ &fx.store.reader,
+ fx.ws,
+ fx.proj,
+ "default",
+ "scratch",
+ CuratorParams::default(),
+ )
+ .await
+ .unwrap();
+ assert!(
+ report.findings.iter().all(|f| f.kind != "cold_episodic"),
+ "curator must skip compacted pages: {:?}",
+ report.findings
+ );
+}
+
+/// Test 6: only episodic pages compact. Pinned episodic, semantic and
+/// procedural pages are never touched, even when cold, with the flag ON.
+#[tokio::test]
+async fn only_unpinned_episodic_pages_compact() {
+ let fx = seed_fixture().await;
+ write(
+ &fx,
+ "sessions/pinned.md",
+ "Pinned",
+ Tier::Episodic,
+ true,
+ "path a.rs prose",
+ )
+ .await;
+ write(
+ &fx,
+ "concepts/sem.md",
+ "Semantic",
+ Tier::Semantic,
+ false,
+ "path b.rs prose",
+ )
+ .await;
+ write(
+ &fx,
+ "runbooks/proc.md",
+ "Procedural",
+ Tier::Procedural,
+ false,
+ "path c.rs prose",
+ )
+ .await;
+ for path in ["sessions/pinned.md", "concepts/sem.md", "runbooks/proc.md"] {
+ backdate_latest(&fx, path, COLD_DAYS);
+ }
+
+ let report = run_sweep_with_compaction(
+ &fx.store.reader,
+ &fx.store.writer,
+ Some(&fx.wiki),
+ fx.ws,
+ fx.proj,
+ &DecayParams::default(),
+ 0.0,
+ ObservationRetention::default(),
+ true,
+ false,
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ report.compacted.is_empty(),
+ "pinned/semantic/procedural pages must never compact: {:?}",
+ report.compacted
+ );
+ for path in ["sessions/pinned.md", "concepts/sem.md", "runbooks/proc.md"] {
+ let (marker, _body) = latest_marker_and_body(&fx, path);
+ assert!(marker.is_none(), "{path} must not be marked compacted");
+ }
+}
diff --git a/crates/ai-memory-consolidate/tests/suite/mod.rs b/crates/ai-memory-consolidate/tests/suite/mod.rs
index eceef9ad..187fcd7a 100644
--- a/crates/ai-memory-consolidate/tests/suite/mod.rs
+++ b/crates/ai-memory-consolidate/tests/suite/mod.rs
@@ -4,6 +4,7 @@
mod abstract_backfill;
mod access_breadth_sweep;
+mod compaction_sweep;
mod embed_backfill;
mod embeddings;
mod lifecycle;
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 77b513a0..5e7b1d2a 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -54,7 +54,7 @@ use ai_memory_consolidate::{
EmbedBackfillCounts, EmbedBackfillOptions, ObservationRetention, 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_with_breadth, run_embedding_backfill, run_lint, run_sweep_with_options,
+ run_curator_report_with_breadth, run_embedding_backfill, run_lint, run_sweep_with_compaction,
};
use ai_memory_core::{
ActiveProject, AgentKind, AutoImproveProposalId, Capability, DEFAULT_PROJECT_NAME,
@@ -93,6 +93,8 @@ const CONTRIBUTORS_WEBHOOK_NAME: &str = "contributors";
struct SweepTuning {
breadth_weight: f64,
retention: ObservationRetention,
+ /// A2 opt-in: compact cold episodic pages instead of evicting them.
+ compact_cold_episodic: bool,
}
/// Shared state for the admin router.
@@ -596,15 +598,22 @@ pub fn admin_router(state: AdminState) -> Router {
/// Build the admin router with the optional distinct-reader retention weight.
pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -> Router {
- admin_router_with_sweep_tuning(state, breadth_weight, ObservationRetention::default())
+ admin_router_with_sweep_tuning(
+ state,
+ breadth_weight,
+ ObservationRetention::default(),
+ false,
+ )
}
/// Build the admin router with every sweep knob that lives outside
-/// `DecayParams`, including the opt-in observation prune (disabled by default).
+/// `DecayParams`, including the opt-in observation prune (disabled by default)
+/// and A2 extractive tier-down (`compact_cold_episodic`, off by default).
pub fn admin_router_with_sweep_tuning(
state: AdminState,
breadth_weight: f64,
retention: ObservationRetention,
+ compact_cold_episodic: bool,
) -> Router {
let state = Arc::new(state);
let operational = Router::new()
@@ -711,6 +720,7 @@ pub fn admin_router_with_sweep_tuning(
.layer(axum::Extension(SweepTuning {
breadth_weight,
retention,
+ compact_cold_episodic,
}))
}
@@ -3469,7 +3479,7 @@ async fn handle_forget_sweep(
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
- run_sweep_with_options(
+ run_sweep_with_compaction(
&state.reader,
&state.writer,
Some(&state.wiki),
@@ -3478,6 +3488,7 @@ async fn handle_forget_sweep(
&state.decay_params,
tuning.breadth_weight,
tuning.retention,
+ tuning.compact_cold_episodic,
req.dry_run,
)
.await
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 1e2157ce..b89384e5 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, ObservationRetention, projection::cap_text_with_marker,
- run_auto_improve_review, run_lint, run_sweep_with_options,
+ run_auto_improve_review, run_lint, run_sweep_with_compaction,
};
use ai_memory_core::{
ActiveProject, AgentKind, FeedbackKind, HandoffId, HandoffState, NewHandoff, PageId, PagePath,
@@ -452,6 +452,9 @@ pub struct AiMemoryServer {
/// Opt-in bound on how long raw observations outlive their consolidation.
/// Default is disabled, so `memory_forget_sweep` deletes no raw capture.
observation_retention: ObservationRetention,
+ /// A2 opt-in: compact cold episodic pages (tier-down) instead of evicting
+ /// them. Default `false`, so the sweep evicts exactly as before.
+ compact_cold_episodic: bool,
/// M9 embedder for hybrid query. When `None`, `memory_query`
/// still fuses FTS5 with entity matches and graph-neighbour expansion.
embedder: Option<Arc<dyn Embedder>>,
@@ -1626,6 +1629,7 @@ impl AiMemoryServer {
decay_params: DecayParams::default(),
decay_breadth_weight: 0.0,
observation_retention: ObservationRetention::default(),
+ compact_cold_episodic: false,
embedder: None,
reranker: None,
client_activity: Arc::new(std::sync::Mutex::new(ClientActivityBuffer::new())),
@@ -2195,6 +2199,14 @@ impl AiMemoryServer {
self
}
+ /// Enable A2 extractive tier-down: the sweep compacts cold episodic pages
+ /// instead of evicting them. Off by default.
+ #[must_use]
+ pub fn with_compact_cold_episodic(mut self, compact: bool) -> Self {
+ self.compact_cold_episodic = compact;
+ self
+ }
+
/// Set the opt-in observation prune bound used by `memory_forget_sweep`.
/// Unset, the sweep never deletes a raw observation.
#[must_use]
@@ -2995,7 +3007,7 @@ impl AiMemoryServer {
&aps_actor,
)
.await?;
- let report = run_sweep_with_options(
+ let report = run_sweep_with_compaction(
&self.reader,
&self.writer,
self.wiki.as_ref(),
@@ -3004,6 +3016,7 @@ impl AiMemoryServer {
&self.decay_params,
self.decay_breadth_weight,
self.observation_retention,
+ self.compact_cold_episodic,
args.dry_run.unwrap_or(false),
)
.await
diff --git a/crates/ai-memory-store/migrations/V65__page_compacted_marker.sql b/crates/ai-memory-store/migrations/V65__page_compacted_marker.sql
new file mode 100644
index 00000000..6ccd05b5
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V65__page_compacted_marker.sql
@@ -0,0 +1,23 @@
+-- A2 extractive tier-down marker (docs/design-memory-aging.md §A2).
+--
+-- When the forget sweep tiers a cold episodic page DOWN — keeping its L0
+-- abstract, an L1 summary, and an L2 regex-mined keep-token set, dropping the
+-- prose body — instead of evicting it, it stamps this column on the rewritten
+-- latest version. The marker lets the sweep and `curator.rs` tell a
+-- deliberately-short *compacted* page from a *cold* one, so a compacted page is
+-- never re-compacted and never re-reported as a fresh cold candidate.
+--
+-- Purely ADDITIVE DDL: a single nullable `ADD COLUMN` is instant on SQLite
+-- (no table rewrite, no lock on a large store). Existing rows read back NULL
+-- ("not compacted"), which is exactly today's behaviour, so an upgrade changes
+-- nothing until an operator opts in to `[decay] compact_cold_episodic`. There
+-- is NO body backfill: the marker is populated LAZILY by the sweep as it
+-- compacts, not in a boot migration (contrast the V62 window backfill).
+--
+-- The frontmatter carries a `compacted: true` mirror of this column; the column
+-- is derived from that mirror at the single store write choke point
+-- (`ops::upsert_page_in_tx`), so both land in the same transaction as the page
+-- body (invariant: indexes commit with the data). The full pre-compaction body
+-- stays reachable through the supersession chain and git history, so tier-down
+-- is reversible (invariant #16: the loser stays reachable).
+ALTER TABLE pages ADD COLUMN compacted_at INTEGER;
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index cef85c04..7af28525 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -411,7 +411,7 @@ mod tests {
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 64, "update the pin when adding a migration");
+ assert_eq!(version, 65, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index f30a8867..837e637d 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -973,6 +973,17 @@ pub(crate) fn upsert_page_in_tx(
let mut conformed = page.frontmatter_json.clone();
ai_memory_core::okf::conform_frontmatter(page.path.as_str(), &mut conformed);
let tier_str = page.tier.as_str();
+ // A2 tier-down marker (V65). The `compacted: true` frontmatter mirror is
+ // the single source of truth an A2 compaction rewrite carries in through
+ // the wiki layer; the `compacted_at` column is derived from it here, at the
+ // one write choke point, so the marker and the compacted body always land
+ // in the same transaction (invariant: indexes commit with the data). A
+ // normal write has no `compacted` key, so the column stays NULL and every
+ // pre-A2 code path behaves exactly as before.
+ let compacted_at: Option<i64> = conformed
+ .get("compacted")
+ .and_then(serde_json::Value::as_bool)
+ .and_then(|flag| flag.then_some(now));
let existing: Option<ExistingPageVersion> = tx
.query_row(
@@ -1033,8 +1044,8 @@ pub(crate) fn upsert_page_in_tx(
"INSERT INTO pages \
(id, workspace_id, project_id, path, path_search, title, tier, body, body_sha256, \
frontmatter_json, is_latest, supersedes, pinned, author_id, \
- created_at, updated_at, expires_at, valid_from) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1, ?11, ?12, ?13, ?14, ?14, ?15, ?14)",
+ created_at, updated_at, expires_at, valid_from, compacted_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1, ?11, ?12, ?13, ?14, ?14, ?15, ?14, ?16)",
params![
new_id.as_bytes(),
page.workspace_id.as_bytes(),
@@ -1051,6 +1062,7 @@ pub(crate) fn upsert_page_in_tx(
page.author_id.map(|id| id.as_bytes().to_vec()),
now,
page.expires_at.map(|ts| ts.as_microsecond()),
+ compacted_at,
],
)?;
replace_links_in_tx(tx, &new_id, page)?;
@@ -1075,8 +1087,8 @@ pub(crate) fn upsert_page_in_tx(
tx.execute(
"INSERT INTO pages \
(id, workspace_id, project_id, path, path_search, title, tier, body, body_sha256, \
- frontmatter_json, is_latest, pinned, author_id, created_at, updated_at, expires_at, valid_from) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1, ?11, ?12, ?13, ?13, ?14, ?13)",
+ frontmatter_json, is_latest, pinned, author_id, created_at, updated_at, expires_at, valid_from, compacted_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1, ?11, ?12, ?13, ?13, ?14, ?13, ?15)",
params![
new_id.as_bytes(),
page.workspace_id.as_bytes(),
@@ -1092,6 +1104,7 @@ pub(crate) fn upsert_page_in_tx(
page.author_id.map(|id| id.as_bytes().to_vec()),
now,
page.expires_at.map(|ts| ts.as_microsecond()),
+ compacted_at,
],
)?;
replace_links_in_tx(tx, &new_id, page)?;
@@ -6730,6 +6743,38 @@ pub(crate) mod tests {
}
}
+ /// The V65 A2 marker is derived from the `compacted: true` frontmatter
+ /// mirror at the single write choke point, in the same transaction as the
+ /// body — a normal write leaves it NULL, so every pre-A2 path is unchanged.
+ #[test]
+ fn upsert_derives_compacted_at_from_frontmatter_mirror() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+
+ // A normal write has no `compacted` key → marker stays NULL.
+ let plain = upsert_page(&mut conn, &page(ws, proj, "notes/plain.md", "body")).unwrap();
+ let plain_marker: Option<i64> = conn
+ .query_row(
+ "SELECT compacted_at FROM pages WHERE id = ?1",
+ rusqlite::params![plain.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(plain_marker, None, "an ordinary write is never marked");
+
+ // A write carrying the frontmatter mirror sets the marker.
+ let mut compacted = page(ws, proj, "notes/compacted.md", "residue");
+ compacted.frontmatter_json = serde_json::json!({"compacted": true});
+ let compacted_id = upsert_page(&mut conn, &compacted).unwrap();
+ let marker: Option<i64> = conn
+ .query_row(
+ "SELECT compacted_at FROM pages WHERE id = ?1",
+ rusqlite::params![compacted_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert!(marker.is_some(), "the frontmatter mirror sets compacted_at");
+ }
+
/// A page written before entity extraction — tags in frontmatter but
/// no entity links — is backfilled from those tags, with the link's
/// window opening at the page version's creation. A page written with
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 0d223001..258b8528 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -3979,7 +3979,7 @@ impl ReaderPool {
self.with_conn(move |conn| {
let mut stmt = conn.prepare(
"SELECT id, path, tier, pinned, updated_at, access_count, last_accessed_at, \
- frontmatter_json, expires_at, salience \
+ frontmatter_json, expires_at, salience, compacted_at \
FROM pages \
WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1",
)?;
@@ -9060,6 +9060,12 @@ pub struct DecayCandidate {
/// Per-page salience once explicit feedback has moved it (V37);
/// `None` means "use `DecayParams::salience_default`".
pub salience: Option<f64>,
+ /// A2 tier-down marker (V65): microseconds since epoch when this page was
+ /// extractively compacted, or `None` if it has never been compacted. The
+ /// forget sweep and the curator both skip a page whose marker is set so a
+ /// deliberately-short compacted page is never re-compacted or re-classified
+ /// as a fresh cold candidate.
+ pub compacted_at_us: Option<i64>,
}
/// One forget-sweep tombstone eligible for permanent cleanup.
@@ -9084,6 +9090,7 @@ fn row_to_decay_candidate(
let frontmatter_json: String = row.get(7)?;
let expires_at_us: Option<i64> = row.get(8)?;
let salience: Option<f64> = row.get(9)?;
+ let compacted_at_us: Option<i64> = row.get(10)?;
Ok(materialise_decay_candidate(
id_bytes,
path,
@@ -9095,6 +9102,7 @@ fn row_to_decay_candidate(
frontmatter_json,
expires_at_us,
salience,
+ compacted_at_us,
))
}
@@ -9110,6 +9118,7 @@ fn materialise_decay_candidate(
frontmatter_json: String,
expires_at_us: Option<i64>,
salience: Option<f64>,
+ compacted_at_us: Option<i64>,
) -> StoreResult<DecayCandidate> {
Ok(DecayCandidate {
id: PageId::from_slice(&id_bytes)?,
@@ -9124,6 +9133,7 @@ fn materialise_decay_candidate(
frontmatter_json,
expires_at_us,
salience,
+ compacted_at_us,
})
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index bb6c0cdd..f77466a8 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -293,6 +293,7 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| `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. |
| `page_evidence` | V63 append-only record of what produced or reaffirmed each page version — consolidation cites the `session` it ran on, written in the page-upsert transaction and cascaded on purge. Surfaced as `evidence_count` in `memory_query(explain=true)` and used to order the opt-in `settled_first` briefing. Ranking-inert: the confidence→authority factor is deferred behind the eval harness (`docs/design-hindsight-borrowings.md` P2). |
| `agent_messages` | V64 cross-project message inbox/queue (`docs/agent-messaging.md`). Directed, claim-once mail from a sender coordinate to a recipient coordinate; `pending`→`claimed` (popped exactly once, the handoff compare-and-set) or `pending`→`cancelled` (sender retracts). The one table that crosses per-project isolation, so reads are keyed by the recipient coordinate (inbox) or sender coordinate (outbox); `from_owner_user`/`claimed_by_user` are attribution only, never a read filter. Recipient inbox depth is capped. `ON DELETE CASCADE` on both coordinate pairs. |
+| `pages.compacted_at` | V65 nullable A2 tier-down marker (`docs/design-memory-aging.md` §A2). Set when the forget-sweep extractively compacts a cold episodic page (opt-in `[decay] compact_cold_episodic`) instead of evicting it; derived at the single page-upsert choke point from a `compacted: true` frontmatter mirror, so the marker and compacted body land in one transaction. Additive `ADD COLUMN`, no backfill — populated lazily by the sweep. The sweep and curator skip a marked page so it is never re-compacted, re-evicted, or re-reported as cold. Reversible: the full pre-compaction body stays in git + the supersession chain. |
| `client_activity` | Server-wide MCP tool-call counters split into reads/writes and bucketed by UTC day. The MCP request choke point flushes buffered calls on a one-minute background interval; failed batches retry from bounded memory. Each day stores at most 128 sanitized client labels plus `other`, so an untrusted `clientInfo.name` cannot create traffic-proportional rows. |
| `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. |
@@ -303,7 +304,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) · (1 + breadth_weight · ln(1 + max(distinct_actors−1, 0)))` |
+| Episodic | 30d hot → 180d cold → evict (or tier-down, opt-in A2) | `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 |
@@ -312,6 +313,18 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
`λ = ln(2)/days`); an unset tier uses the scalar, so the default reproduces
today's single-λ scores exactly.
+**Extractive tier-down (A2, opt-in).** With `[decay] compact_cold_episodic =
+true`, the sweep runs a compaction pass *before* the decay-eviction pass: a cold
+episodic page that is not already compacted is rewritten through the wiki layer
+to keep its L0 `abstract:`, an L1 first-paragraph summary, and an L2 regex-mined
+keep-token set (paths, URLs, code spans, error codes, identifiers), dropping the
+prose — instead of being tombstoned. The rewrite supersedes the prior version,
+so the full body stays reachable (git + supersession chain; `restore-page`
+recovers it). The `V65` `pages.compacted_at` marker makes a compacted page
+terminal for the decay pass (never re-compacted, never re-evicted, never
+re-reported as cold). Zero-LLM, off by default; the R2 recall no-regression
+proof gates any future default-on.
+
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
@@ -585,6 +598,11 @@ hard_delete_after_days = 180
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
+compact_cold_episodic = false # A2 opt-in: tier-down (compact) a cold
+ # episodic page instead of evicting it —
+ # keep abstract+summary+keep-tokens, drop
+ # prose. Reversible (git + supersession),
+ # zero-LLM. false = today's evict behaviour.
[decay.half_life_days] # opt-in per-tier retention curves (all keys
# optional). Half-life in DAYS; converted to