Skip to content

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

Rust

M20: rule-vs-fact disambiguation in consolidation + lint

AkitaOnRails93a0492f1e67
diff --git a/README.md b/README.md
index 3e64caf7..bd39f5b1 100644
--- a/README.md
+++ b/README.md
@@ -152,6 +152,28 @@ docker cp ai-memory:/data/wiki ./my-ai-memory-wiki
docker exec ai-memory git -C /data/wiki log --oneline
```
+### Rules vs facts — ai-memory tells you when something belongs in CLAUDE.md
+
+When you type something like "don't forget to never add a function
+without a unit test", that's a **durable project rule**, not a
+session-level observation. Rules need to fire on every relevant
+action — that's what your project's `CLAUDE.md` / `AGENTS.md` is for
+(it's loaded into the agent's system prompt every turn), while
+ai-memory queries only fire when the agent thinks to call them.
+
+The consolidator now classifies each compiled observation as
+`decision | fact | rule | gotcha`. Rule-tagged pages are auto-routed
+to `wiki/_rules/<slug>.md`, and the next time you run `memory_lint`
+the agent sees a suggestion:
+
+> **rule_suggestion**: Page `_rules/never-ship-code-without-test.md`
+> looks like a durable project rule. Consider copying it into your
+> project's CLAUDE.md / AGENTS.md so the agent sees it on every
+> turn, not just when it remembers to call memory_query.
+
+ai-memory never edits your `CLAUDE.md` itself — the suggestion is
+the whole UX. You copy what's useful, ignore what isn't.
+
### Nudge the agent to *use* memory proactively
Lifecycle hooks handle *capture* and *handoff resume* without you
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index d2faf73b..de2b2250 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -212,7 +212,19 @@ impl Consolidator {
let mut requests = Vec::with_capacity(batch.updates.len());
let mut outcomes_preview = Vec::with_capacity(batch.updates.len());
for upd in &batch.updates {
- let path = PagePath::new(upd.path.clone())?;
+ // When the LLM classifies an update as a rule, ALWAYS
+ // route it to `_rules/<slug>.md` regardless of what
+ // path it suggested — this is the M20 contract that
+ // lets the lint pass find every rule-shaped page in a
+ // single sweep without scanning frontmatter across the
+ // whole wiki.
+ let final_path = if upd.kind == crate::types::PageKind::Rule {
+ let slug = slugify_for_rule(&upd.title);
+ format!("_rules/{slug}.md")
+ } else {
+ upd.path.clone()
+ };
+ let path = PagePath::new(final_path)?;
let tier = upd.tier.parse::<Tier>().unwrap_or(Tier::Semantic);
let mut fm = serde_json::Map::new();
fm.insert("title".into(), serde_json::Value::String(upd.title.clone()));
@@ -220,6 +232,13 @@ impl Consolidator {
"tier".into(),
serde_json::Value::String(tier_as_str(tier).into()),
);
+ // M20: surface the semantic classification into
+ // frontmatter so the lint pass + downstream tooling
+ // can branch on it without re-classifying.
+ fm.insert(
+ "kind".into(),
+ serde_json::Value::String(upd.kind.as_str().into()),
+ );
if !upd.tags.is_empty() {
fm.insert(
"tags".into(),
@@ -308,7 +327,18 @@ fn build_batch_request(session_id: SessionId, observations: &[Observation]) -> C
- concepts/<slug>.md (semantic, evergreen concept pages)\n\
- decisions/<short>.md (semantic, ADR-style records)\n\
- gotchas/<slug>.md (semantic, failure modes / surprises)\n\
- \nEach update must include a title, markdown body, tier, and tags.\n",
+ \nClassify each update with one of these `kind` values:\n\
+ - `decision` (the project chose X over Y)\n\
+ - `gotcha` (a failure mode or surprise worth remembering)\n\
+ - `rule` (durable project convention: \"always X\", \"never Y\")\n\
+ - `fact` (everything else; the default)\n\
+ \nWhen you mark an update as `rule`, write the body as a clear \
+ standalone instruction the agent could follow on every relevant \
+ action. The path you suggest for a rule will be overridden — the \
+ system routes rules to `_rules/<slug>.md` automatically and the \
+ lint pass surfaces a hint to copy it into the project's CLAUDE.md.\
+ \n\nEach update must include a title, markdown body, tier, kind, \
+ and tags.\n",
);
ChatRequest {
system: Some(BATCH_SYSTEM_PROMPT.into()),
@@ -396,6 +426,40 @@ fn one_line(s: &str) -> String {
.collect()
}
+/// ASCII-slug a rule title for the `_rules/<slug>.md` path.
+///
+/// Lower-cases, replaces runs of non-`[a-z0-9]` with `-`, trims
+/// leading/trailing hyphens, and caps at 60 chars. Falls back to
+/// `rule` when the input has no alphanumerics (e.g. a non-Latin
+/// title) so we always produce a valid PagePath.
+fn slugify_for_rule(title: &str) -> String {
+ let mut out = String::with_capacity(title.len());
+ let mut prev_dash = true; // leading dashes get folded
+ for c in title.chars() {
+ let lower = c.to_ascii_lowercase();
+ if lower.is_ascii_alphanumeric() {
+ out.push(lower);
+ prev_dash = false;
+ } else if !prev_dash {
+ out.push('-');
+ prev_dash = true;
+ }
+ }
+ while out.ends_with('-') {
+ out.pop();
+ }
+ if out.is_empty() {
+ return "rule".into();
+ }
+ if out.len() > 60 {
+ out.truncate(60);
+ while out.ends_with('-') {
+ out.pop();
+ }
+ }
+ out
+}
+
fn short_id(s: &str) -> String {
s.chars().take(8).collect()
}
@@ -415,3 +479,46 @@ that future agents and the user can read to recover context.\n\nRules:\n\
4. Do NOT include redundant per-tool-call detail. Aggregate.\n\
5. Do NOT echo timestamps or session ids (frontmatter already has them).\n\
6. Tags: 0-5 short kebab-case tags surfaced to frontmatter.\n";
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Slugifier produces a clean ASCII path for typical English titles.
+ #[test]
+ fn slugify_handles_typical_rule_title() {
+ assert_eq!(
+ slugify_for_rule("Never ship code without a unit test"),
+ "never-ship-code-without-a-unit-test"
+ );
+ }
+
+ /// Punctuation + apostrophes collapse into single hyphens; no
+ /// trailing hyphen lingers from a final non-alphanumeric.
+ #[test]
+ fn slugify_collapses_punctuation_and_trims() {
+ assert_eq!(
+ slugify_for_rule("Don't merge before lint!"),
+ "don-t-merge-before-lint"
+ );
+ assert_eq!(slugify_for_rule("---hyphenated---"), "hyphenated");
+ }
+
+ /// Non-Latin / empty-after-cleanup titles fall back to a static
+ /// slug instead of producing an invalid PagePath.
+ #[test]
+ fn slugify_falls_back_for_unprintable_titles() {
+ assert_eq!(slugify_for_rule(""), "rule");
+ assert_eq!(slugify_for_rule("!!!"), "rule");
+ assert_eq!(slugify_for_rule("中文"), "rule");
+ }
+
+ /// Very long titles get capped at 60 chars with no trailing dash.
+ #[test]
+ fn slugify_caps_length() {
+ let long = "a".repeat(200);
+ let slug = slugify_for_rule(&long);
+ assert!(slug.len() <= 60);
+ assert!(!slug.ends_with('-'));
+ }
+}
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index 6fab0fdd..0aeb9c45 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -19,5 +19,5 @@ pub use consolidator::{Consolidator, ConsolidatorError, ConsolidatorResult};
pub use lint::{LintError, LintFinding, LintReport, run_lint};
pub use sweep::{EvictedPage, SweepError, SweepReport, run_sweep};
pub use types::{
- ConsolidatedBatch, ConsolidatedPage, ConsolidatedPageUpdate, ConsolidationOutcome,
+ ConsolidatedBatch, ConsolidatedPage, ConsolidatedPageUpdate, ConsolidationOutcome, PageKind,
};
diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rs
index 5278105b..05084ff7 100644
--- a/crates/ai-memory-consolidate/src/lint.rs
+++ b/crates/ai-memory-consolidate/src/lint.rs
@@ -125,8 +125,35 @@ fn rule_based_findings(candidates: &[DecayCandidate]) -> Vec<LintFinding> {
pages: vec![c.path.as_str().to_string()],
});
}
+ // M20: rule-shaped pages get a "consider adding to
+ // CLAUDE.md" suggestion. Two signals are checked:
+ // 1. Frontmatter `kind: rule` — set by the consolidator
+ // when it classifies an observation as a rule.
+ // 2. Page path starts with `_rules/` — same routing
+ // target. Either signal suffices.
+ let frontmatter: Option<serde_json::Value> = serde_json::from_str(&c.frontmatter_json).ok();
+ let kind_is_rule = frontmatter
+ .as_ref()
+ .and_then(|fm| fm.get("kind"))
+ .and_then(serde_json::Value::as_str)
+ == Some("rule");
+ let path_str = c.path.as_str();
+ let path_is_rule = path_str.starts_with("_rules/");
+ if kind_is_rule || path_is_rule {
+ out.push(LintFinding {
+ kind: "rule_suggestion".into(),
+ severity: "info".into(),
+ message: format!(
+ "Page {path_str} looks like a durable project rule. \
+ Consider copying it into your project's CLAUDE.md / \
+ AGENTS.md so the agent sees it on every turn, not \
+ just when it remembers to call memory_query."
+ ),
+ pages: vec![path_str.to_string()],
+ });
+ }
// Duplicate-title tracking: peek the frontmatter for a `title` field.
- if let Ok(fm) = serde_json::from_str::<serde_json::Value>(&c.frontmatter_json)
+ if let Some(fm) = frontmatter.as_ref()
&& let Some(t) = fm.get("title").and_then(serde_json::Value::as_str)
{
titles
@@ -297,4 +324,72 @@ mod tests {
assert_eq!(dupes.len(), 1);
assert_eq!(dupes[0].pages.len(), 2);
}
+
+ /// M20: a page tagged `kind: rule` in its frontmatter triggers
+ /// a rule_suggestion finding pointing the user at CLAUDE.md.
+ #[test]
+ fn rule_pass_flags_rule_kind_frontmatter() {
+ let candidate = DecayCandidate {
+ id: ai_memory_core::PageId::new(),
+ path: ai_memory_core::PagePath::new("concepts/no-impl-without-test.md").unwrap(),
+ tier: Tier::Semantic,
+ pinned: false,
+ updated_at_us: Timestamp::now().as_microsecond(),
+ access_count: 0,
+ last_accessed_at_us: None,
+ frontmatter_json: r#"{"title": "Never ship code without a test", "kind": "rule"}"#
+ .into(),
+ };
+ let findings = rule_based_findings(&[candidate]);
+ let rules: Vec<_> = findings
+ .iter()
+ .filter(|f| f.kind == "rule_suggestion")
+ .collect();
+ assert_eq!(rules.len(), 1, "expected one rule_suggestion finding");
+ assert!(rules[0].message.contains("CLAUDE.md"));
+ }
+
+ /// M20: a page under `_rules/` also triggers the suggestion
+ /// even when the frontmatter is missing/empty — the path
+ /// itself is enough signal.
+ #[test]
+ fn rule_pass_flags_rules_path() {
+ let candidate = DecayCandidate {
+ id: ai_memory_core::PageId::new(),
+ path: ai_memory_core::PagePath::new("_rules/no-impl-without-test.md").unwrap(),
+ tier: Tier::Semantic,
+ pinned: false,
+ updated_at_us: Timestamp::now().as_microsecond(),
+ access_count: 0,
+ last_accessed_at_us: None,
+ frontmatter_json: "{}".into(),
+ };
+ let findings = rule_based_findings(&[candidate]);
+ assert!(
+ findings.iter().any(|f| f.kind == "rule_suggestion"),
+ "expected a rule_suggestion finding for _rules/ page",
+ );
+ }
+
+ /// Defensive: a normal concept page (no rule signal) does NOT
+ /// emit the suggestion. Without this guard, every fact-tagged
+ /// page would noise up the lint report.
+ #[test]
+ fn rule_pass_skips_non_rule_pages() {
+ let candidate = DecayCandidate {
+ id: ai_memory_core::PageId::new(),
+ path: ai_memory_core::PagePath::new("concepts/karpathy-wiki.md").unwrap(),
+ tier: Tier::Semantic,
+ pinned: false,
+ updated_at_us: Timestamp::now().as_microsecond(),
+ access_count: 5,
+ last_accessed_at_us: None,
+ frontmatter_json: r#"{"title": "Karpathy Wiki", "kind": "fact"}"#.into(),
+ };
+ let findings = rule_based_findings(&[candidate]);
+ assert!(
+ findings.iter().all(|f| f.kind != "rule_suggestion"),
+ "non-rule page must not produce a rule_suggestion finding",
+ );
+ }
}
diff --git a/crates/ai-memory-consolidate/src/types.rs b/crates/ai-memory-consolidate/src/types.rs
index fa0bf00b..09a0e8d9 100644
--- a/crates/ai-memory-consolidate/src/types.rs
+++ b/crates/ai-memory-consolidate/src/types.rs
@@ -18,13 +18,65 @@ pub struct ConsolidatedPage {
pub tags: Vec<String>,
}
+/// Semantic classification of one consolidated page. Surfaced into
+/// the page's frontmatter (`kind: rule`, etc.) so the lint pass can
+/// differentiate "decisions the project has made" from "durable
+/// rules the team enforces" from raw "facts that emerged today".
+///
+/// The `rule` variant is special: rule-tagged pages are auto-routed
+/// to `_rules/<slug>.md` and the lint pass suggests adding them to
+/// the project's CLAUDE.md / AGENTS.md so they fire on every turn,
+/// not just on memory_query.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum PageKind {
+ /// Project-wide constraint or convention. Examples: "never
+ /// commit without a test", "always run lint before merging".
+ /// Gets routed to `_rules/<slug>.md` + a lint suggestion to
+ /// migrate into CLAUDE.md.
+ Rule,
+ /// Decision the project made (ADR-shaped). Examples: "chose
+ /// session cookies over JWT for auth", "rejected vector RAG
+ /// in favour of Karpathy wiki".
+ Decision,
+ /// A failure mode or surprise worth remembering. Examples:
+ /// "Claude Code's session-end fires twice when /exit is typed
+ /// during a tool call".
+ Gotcha,
+ /// Anything that doesn't fit a stronger category. The default —
+ /// keeps existing call sites that don't classify explicitly
+ /// working unchanged.
+ #[default]
+ Fact,
+}
+
+impl PageKind {
+ /// Wire string for serialisation + frontmatter.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Rule => "rule",
+ Self::Decision => "decision",
+ Self::Gotcha => "gotcha",
+ Self::Fact => "fact",
+ }
+ }
+}
+
/// One update inside a multi-page consolidation batch (M7b).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ConsolidatedPageUpdate {
/// Relative wiki path (`concepts/foo.md`, `decisions/0001.md`, …).
+ /// When `kind` is `Rule` the consolidator overrides this to
+ /// `_rules/<slug>.md` regardless — see `PageKind::Rule`.
pub path: String,
/// Tier (`semantic`, `episodic`, `procedural`, `working`).
pub tier: String,
+ /// Semantic classification. Defaults to `fact` if the LLM
+ /// doesn't supply one — existing consolidations without this
+ /// field still deserialise.
+ #[serde(default)]
+ pub kind: PageKind,
/// New page title.
pub title: String,
/// New markdown body.