Skip to content

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

Rust

feat(mcp): memory_feedback records page quality signals (V37)

Samir Hanna Verzaf5edc99de8c9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 150c60d3..13d0493d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- New MCP tool `memory_feedback` (17th tool) — the "finer-grained
+ reinforcement beyond access counts" P2 item. Record how useful a
+ recalled page actually was by exact path: `helpful` / `not_helpful`
+ step the page's new `pages.salience` column (V37, bounded to
+ `[0.25, 2.0]` in 0.25 steps), which now scales the retention formula's
+ time term instead of a single global `salience_default`; `stale` /
+ `wrong` floor the salience AND surface the page as a
+ `feedback_flagged` finding in the next `memory_lint` report. Signals
+ land in a new append-only `page_feedback` table with an optional
+ sanitized reason and full audit-log entry. Nothing is ever deleted by
+ feedback. Signals attach to the page *version* that was read, so
+ rewriting a flagged page retires both its salience and its lint
+ findings — there is no separate dismissal state. Pages without
+ feedback keep `salience = NULL`, which reads as exactly the previous
+ behaviour.
- `memory_query` gained an optional `explain: true` mode for project and
explicit-scope searches. Each compiled-page hit then includes its 1-based
FTS5, vector, and graph ranks; raw BM25/cosine values; graph seed and link
diff --git a/README.md b/README.md
index 2887188f..87942dc8 100644
--- a/README.md
+++ b/README.md
@@ -208,6 +208,15 @@ priors are at the [bottom](#influences-and-prior-art).
auto-synthesised session page (rewritten on consolidation), a
write-page note is yours: it shows up in `memory_query`, renders in
`/web`, and stays until you change it.
+- **"That page you found is out of date."** The agent calls
+ `memory_feedback` with the page's path and a signal: `helpful` /
+ `not_helpful` tune how strongly retention keeps the page (they move its
+ salience, which scales the decay formula's time term), while `stale` /
+ `wrong` floor the salience *and* make the page show up as a
+ `feedback_flagged` finding in the next `memory_lint` report. Feedback
+ never deletes anything — it lowers confidence and flags for review —
+ and it attaches to the page version you read, so rewriting the page
+ clears the flag.
- **"Remember this, but only until the sprint ends."** Pass
`expires_at` to `memory_write_page` (RFC3339 or `YYYY-MM-DD` = end of
that day, UTC) — or put `expires_at:` in a page's frontmatter by
diff --git a/crates/ai-memory-consolidate/src/curator.rs b/crates/ai-memory-consolidate/src/curator.rs
index d605320e..250567ba 100644
--- a/crates/ai-memory-consolidate/src/curator.rs
+++ b/crates/ai-memory-consolidate/src/curator.rs
@@ -98,6 +98,7 @@ pub async fn run_curator_report(
page_age_days,
c.access_count,
days_since_access,
+ c.salience,
);
if score < params.decay_params.cold_threshold {
cold.push(CuratorFinding {
diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rs
index 947533b4..957a2a05 100644
--- a/crates/ai-memory-consolidate/src/lint.rs
+++ b/crates/ai-memory-consolidate/src/lint.rs
@@ -139,6 +139,36 @@ pub async fn run_lint(
});
}
+ // Explicit `stale` / `wrong` feedback (memory_feedback). An agent or
+ // user asserting a page is outdated or incorrect is the highest-signal
+ // finding the zero-LLM path can produce — it came from a human/agent
+ // judgement, not a heuristic. Findings repeat until the page is
+ // rewritten, which is the point: an unfixed stale page is still stale.
+ let feedback_flagged = reader
+ .open_feedback_findings(workspace_id, project_id)
+ .await?;
+ for flagged in &feedback_flagged {
+ let plural = if flagged.signal_count == 1 {
+ "signal"
+ } else {
+ "signals"
+ };
+ let mut message = format!(
+ "Page {} was flagged `{}` ({} {}, latest {})",
+ flagged.path, flagged.kind, flagged.signal_count, plural, flagged.latest_at,
+ );
+ if let Some(reason) = &flagged.reason {
+ message.push_str(&format!(": {reason}"));
+ }
+ findings.push(LintFinding {
+ kind: "feedback_flagged".into(),
+ severity: "warning".into(),
+ message,
+ pages: vec![flagged.path.clone()],
+ detail: None,
+ });
+ }
+
if use_llm && let Some(provider) = llm {
match contradiction_pass(
provider.clone(),
@@ -396,6 +426,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: None,
}];
let findings = rule_based_findings(&candidates);
assert_eq!(findings.len(), 1);
@@ -414,6 +445,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: r#"{"title": "Karpathy Wiki"}"#.into(),
expires_at_us: None,
+ salience: None,
};
let b = DecayCandidate {
path: ai_memory_core::PagePath::new("concepts/b.md").unwrap(),
@@ -440,6 +472,7 @@ mod tests {
frontmatter_json: r#"{"title": "Never ship code without a test", "kind": "rule"}"#
.into(),
expires_at_us: None,
+ salience: None,
};
let findings = rule_based_findings(&[candidate]);
let rules: Vec<_> = findings
@@ -465,6 +498,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: None,
};
let findings = rule_based_findings(&[candidate]);
assert!(
@@ -488,6 +522,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: r#"{"title": "Karpathy Wiki", "kind": "fact"}"#.into(),
expires_at_us: None,
+ salience: None,
};
let findings = rule_based_findings(&[candidate]);
assert!(
@@ -543,6 +578,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: 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 a9a1a0fc..c3cbfa53 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -133,7 +133,13 @@ pub async fn run_sweep(
}
let age_days = elapsed_days(now_us, c.updated_at_us);
let days_since_access = c.last_accessed_at_us.map(|us| elapsed_days(now_us, us));
- let score = retention_score(params, age_days, c.access_count, days_since_access);
+ let score = retention_score(
+ params,
+ age_days,
+ c.access_count,
+ days_since_access,
+ c.salience,
+ );
if score < params.cold_threshold {
evicted.push(EvictedPage {
id: c.id,
@@ -232,6 +238,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: None,
};
assert!(!is_decayable(&c));
}
@@ -248,6 +255,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: None,
};
assert!(!is_decayable(&c));
}
@@ -264,6 +272,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: r#"{"pinned": true}"#.into(),
expires_at_us: None,
+ salience: None,
};
assert!(!is_decayable(&c));
}
@@ -280,6 +289,7 @@ mod tests {
last_accessed_at_us: None,
frontmatter_json: "{}".into(),
expires_at_us: None,
+ salience: None,
};
assert!(is_decayable(&c));
}
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index cb8dbff7..6ee31723 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -88,6 +88,7 @@ id_newtype!(pub ManagedRunId, "Identifier for one `ai-memory run` invocation.");
id_newtype!(pub UserId, "Identifier for a registered user (multi-user attribution; see [`crate::actor`]).");
id_newtype!(pub AutoImproveRunId, "Identifier for one auto-improvement review run.");
id_newtype!(pub AutoImproveProposalId, "Identifier for one staged auto-improvement proposal.");
+id_newtype!(pub PageFeedbackId, "Identifier for one page-feedback signal (`memory_feedback`).");
/// Relative path of a page within the wiki tree.
///
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index 96f51356..2ec9aaef 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -42,10 +42,10 @@ pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
pub use ids::{
AgentKind, AutoImproveProposalId, AutoImproveRunId, HandoffId, ManagedRunId, ObservationId,
- PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId, WorkstreamId,
+ PageFeedbackId, PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId, WorkstreamId,
};
pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
-pub use page::{LinkTarget, NewPage, Page, Tier};
+pub use page::{FeedbackKind, LinkTarget, NewPage, Page, Tier};
pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_line, full_block};
pub use sanitize::{
OBSERVATION_BODY_MAX_BYTES, SanitizeConfig, Sanitized, Sanitizer, truncate_utf8_bytes,
diff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rs
index a5617f26..d93df0a6 100644
--- a/crates/ai-memory-core/src/page.rs
+++ b/crates/ai-memory-core/src/page.rs
@@ -166,6 +166,65 @@ impl Tier {
}
}
+/// An explicit judgement on how useful a recalled page was.
+///
+/// The M8 decay formula's only reinforcement signal is the access
+/// counter every search hit bumps, which cannot distinguish "this page
+/// answered the question" from "this page surfaced and wasted a read".
+/// These four signals close that gap: `Helpful` / `NotHelpful` nudge the
+/// page's salience (bounded, see the store's feedback op), while `Stale`
+/// / `Wrong` additionally route the page into the next `memory_lint`
+/// report rather than deleting anything — an agent's judgement lowers
+/// confidence, it does not destroy memory.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum FeedbackKind {
+ /// The page answered the question it surfaced for.
+ Helpful,
+ /// The page surfaced but did not help.
+ NotHelpful,
+ /// The content is outdated — the page needs a refresh.
+ Stale,
+ /// The content is factually wrong, not merely dated.
+ Wrong,
+}
+
+impl FeedbackKind {
+ /// Canonical short string for storage and serialisation. Matches the
+ /// `page_feedback.kind` CHECK constraint (V37).
+ #[must_use]
+ pub const fn as_str(&self) -> &'static str {
+ match self {
+ Self::Helpful => "helpful",
+ Self::NotHelpful => "not_helpful",
+ Self::Stale => "stale",
+ Self::Wrong => "wrong",
+ }
+ }
+
+ /// Whether this signal should surface as a `memory_lint` finding.
+ #[must_use]
+ pub const fn routes_to_lint(&self) -> bool {
+ matches!(self, Self::Stale | Self::Wrong)
+ }
+}
+
+impl FromStr for FeedbackKind {
+ type Err = crate::MemoryError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "helpful" => Ok(Self::Helpful),
+ "not_helpful" => Ok(Self::NotHelpful),
+ "stale" => Ok(Self::Stale),
+ "wrong" => Ok(Self::Wrong),
+ other => Err(crate::MemoryError::MalformedRecord(format!(
+ "unknown feedback kind: {other} (want helpful|not_helpful|stale|wrong)"
+ ))),
+ }
+ }
+}
+
impl FromStr for Tier {
type Err = crate::MemoryError;
@@ -210,4 +269,20 @@ mod tests {
"\"procedural\""
);
}
+ #[test]
+ fn feedback_kind_round_trips_and_flags_lint_routing() {
+ for k in [
+ FeedbackKind::Helpful,
+ FeedbackKind::NotHelpful,
+ FeedbackKind::Stale,
+ FeedbackKind::Wrong,
+ ] {
+ assert_eq!(k.as_str().parse::<FeedbackKind>().unwrap(), k);
+ }
+ assert!("nope".parse::<FeedbackKind>().is_err());
+ assert!(!FeedbackKind::Helpful.routes_to_lint());
+ assert!(!FeedbackKind::NotHelpful.routes_to_lint());
+ assert!(FeedbackKind::Stale.routes_to_lint());
+ assert!(FeedbackKind::Wrong.routes_to_lint());
+ }
}
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
index 0d967528..638f6cf5 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-learning-maintenance/SKILL.md
@@ -14,6 +14,11 @@ Use this skill for compilation, learning review, wiki linting, and cleanup of ai
- `memory_auto_improve` reviews a completed session for durable lessons and project-rule proposals.
- `memory_lint` audits the wiki for contradictions, stale guidance, and candidate rule placement.
- `memory_forget_sweep` prunes cold pages and deletes TTL-expired pages when the user asks for memory cleanup.
+- `memory_feedback` records that a specific page is stale or wrong, which lowers its retention weight and makes the audit report it.
+
+## Flagged pages
+
+Pages the user or an agent flagged through feedback show up in the audit as `feedback_flagged` findings, with the reason that was given. They are the highest-signal cleanup targets: someone read the page and said it was outdated or incorrect. Fix the page content rather than deleting it, unless the user asks for removal — rewriting it also clears the flag.
## Consolidation and learning review
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
index e8f239e9..ca6bb7bf 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
@@ -65,3 +65,12 @@ Treat matching pages under `_rules/`, `gotchas/`, `procedures/`, and `decisions/
- Check gotchas before editing the same subsystem.
- Follow procedures as checklists for releases, PR review, deploys, migrations, and other repeatable workflows.
- Treat decisions as prior architecture unless the user asks to revisit them.
+
+## Rate what you retrieved
+
+`memory_feedback` closes the loop on a lookup. Call it with the exact path from the hit and one signal:
+
+- `helpful` when the page answered the question, `not_helpful` when it surfaced but wasted the read. These tune how strongly retention keeps the page.
+- `stale` when the content is outdated and `wrong` when it is incorrect. Both also flag the page for the next wiki audit. Add a short `reason` whenever the user said what was wrong.
+
+Feedback never deletes anything, so it is safe to send. It applies to the page version you read, so a later rewrite clears it.
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 2b913ff8..a1e54ec7 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -266,6 +266,14 @@ should be proposed from a completed session, or at explicit wrap-up \
admission chain so mirrors/backups stay consistent. Pass `workspace` \
+ `project` together only when the page lives in a sibling \
workspace/project; missing explicit scopes fail closed instead of falling back.\n\
+- `memory_feedback` — right after a `memory_query` / `memory_read_page` \
+ hit proves useful or misleading, and whenever the user says a recalled \
+ page is out of date or wrong. Pass the exact `path` from the hit plus \
+ `signal`: `helpful` / `not_helpful` tune how strongly retention keeps \
+ the page; `stale` / `wrong` additionally surface it in the next \
+ `memory_lint` report. Nothing is ever deleted by feedback — it lowers \
+ confidence and flags the page for review. Add a short `reason` when the \
+ user said what was wrong.\n\
- `memory_lint` — when the user asks to audit the wiki for stale \
pages, contradictions, or rule suggestions.\n\
- `memory_forget_sweep` — when the user wants to prune old / cold \
@@ -527,6 +535,32 @@ struct StatusResponse {
counts: ai_memory_store::StatusCounts,
}
+/// Cap on the free-text `reason` stored with a feedback signal.
+const MAX_FEEDBACK_REASON_CHARS: usize = 500;
+
+#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
+struct FeedbackArgs {
+ /// Exact wiki path of the page you are rating — copy it from the
+ /// `memory_query` / `memory_read_page` hit.
+ path: String,
+ /// One of `helpful`, `not_helpful`, `stale`, `wrong`.
+ signal: String,
+ /// Optional short note on *why*, especially for `stale` / `wrong`
+ /// (e.g. "we moved off Postgres in March"). Shows up in the lint
+ /// report. Capped at 500 characters and sanitized.
+ #[serde(default)]
+ reason: Option<String>,
+ /// Project the page lives in. Omit to target the project you're
+ /// currently working in. **Omit unless the user explicitly names a
+ /// *different* project.**
+ #[serde(default)]
+ project: Option<String>,
+ /// Workspace to use together with `project`. Omit for the current
+ /// workspace.
+ #[serde(default)]
+ workspace: Option<String>,
+}
+
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
struct SweepArgs {
/// If true, preview only. Default false.
@@ -1534,6 +1568,86 @@ impl AiMemoryServer {
})
}
+ /// Record an explicit quality signal for one recalled page.
+ #[tool(description = "Record how useful a recalled page actually was, \
+ by its exact path. `helpful` / `not_helpful` nudge the page's \
+ salience, which scales the retention formula's time term — a \
+ helpful page survives decay longer, an unhelpful one less. \
+ `stale` (outdated) and `wrong` (incorrect) drop salience to the \
+ floor AND surface the page as a `feedback_flagged` finding in the \
+ next memory_lint report. Nothing is deleted: feedback lowers \
+ confidence and flags for review. The signal attaches to the page \
+ version you read, so rewriting the page clears it. Call this right \
+ after a memory_query / memory_read_page hit proved useful or \
+ misleading, or when the user says a recalled page is out of date.")]
+ async fn memory_feedback(
+ &self,
+ Parameters(args): Parameters<FeedbackArgs>,
+ OptionalParts(parts): OptionalParts,
+ ) -> Result<CallToolResult, McpError> {
+ let aps_actor = Self::actor_key_from_parts(Some(&parts));
+ let path = PagePath::new(args.path.clone())
+ .map_err(|e| McpError::invalid_params(format!("invalid path: {e}"), None))?;
+ let kind: ai_memory_core::FeedbackKind =
+ args.signal
+ .parse()
+ .map_err(|e: ai_memory_core::MemoryError| {
+ McpError::invalid_params(e.to_string(), None)
+ })?;
+ let (ws, proj) = self
+ .effective_ids_for_read_args_with_actor(
+ args.workspace.as_deref(),
+ args.project.as_deref(),
+ &aps_actor,
+ )
+ .await?;
+ // The reason is free-text from the model; scrub it on the way in
+ // like any other caller-supplied body.
+ let reason = args
+ .reason
+ .as_deref()
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(|s| {
+ self.sanitizer.scrub(
+ &s.chars()
+ .take(MAX_FEEDBACK_REASON_CHARS)
+ .collect::<String>(),
+ )
+ });
+ let author_id = crate::actor::author_id_from_parts(&parts);
+ let recorded = self
+ .writer
+ .record_page_feedback(
+ ws,
+ proj,
+ path.clone(),
+ kind,
+ reason,
+ author_id,
+ self.decay_params,
+ )
+ .await
+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ match recorded {
+ Some((page_id, salience)) => ok_json(&serde_json::json!({
+ "recorded": true,
+ "path": path.as_str(),
+ "page_id": page_id.to_string(),
+ "signal": kind.as_str(),
+ "salience": salience,
+ "routed_to_lint": kind.routes_to_lint(),
+ })),
+ None => Err(McpError::internal_error(
+ format!(
+ "no current page at path {} in the resolved project",
+ path.as_str()
+ ),
+ None,
+ )),
+ }
+ }
+
/// Run the M8 forget sweep over episodic pages.
#[tool(description = "Run the retention sweep: walk is_latest=1 \
episodic pages, score them with the agentmemory-style retention \
@@ -3233,6 +3347,7 @@ mod tests {
"memory_write_page",
"memory_read_page",
"memory_delete_page",
+ "memory_feedback",
"memory_lint",
"memory_forget_sweep",
"memory_install_self_routing",
@@ -3252,6 +3367,7 @@ mod tests {
"memory_write_page",
"memory_read_page",
"memory_delete_page",
+ "memory_feedback",
"memory_lint",
"memory_forget_sweep",
];
diff --git a/crates/ai-memory-store/migrations/V37__page_feedback.sql b/crates/ai-memory-store/migrations/V37__page_feedback.sql
new file mode 100644
index 00000000..10a95670
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V37__page_feedback.sql
@@ -0,0 +1,32 @@
+-- Explicit feedback on retrieval quality, and the per-page salience it
+-- drives. Until now the only reinforcement signal was the coarse
+-- `access_count` / `last_accessed_at` bump every search hit produced;
+-- the retention formula multiplied a single global `salience_default`.
+--
+-- `pages.salience` is NULL for every existing page, which the decay
+-- math reads as "use salience_default" — so behaviour is unchanged
+-- until a page actually receives feedback. It is a derived value:
+-- `page_feedback` is the append-only source of truth.
+--
+-- Feedback attaches to a page *version* (`page_id`), so rewriting a
+-- flagged page retires both its salience and its lint findings: the
+-- rows stay for audit but point at an `is_latest = 0` version, which
+-- the lint query's `is_latest = 1` join filters out. That is the
+-- resolution path — there is no separate "dismiss" state.
+ALTER TABLE pages ADD COLUMN salience REAL;
+
+CREATE TABLE page_feedback (
+ id BLOB PRIMARY KEY,
+ page_id BLOB NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ -- helpful / not_helpful move salience; stale / wrong additionally
+ -- surface the page in memory_lint reports.
+ kind TEXT NOT NULL CHECK (kind IN ('helpful', 'not_helpful', 'stale', 'wrong')),
+ reason TEXT,
+ author_id BLOB REFERENCES users(id) ON DELETE SET NULL,
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX idx_page_feedback_page ON page_feedback(page_id, created_at DESC);
+CREATE INDEX idx_page_feedback_scope ON page_feedback(workspace_id, project_id, created_at DESC);
diff --git a/crates/ai-memory-store/src/decay.rs b/crates/ai-memory-store/src/decay.rs
index e81c1f77..4d5481ad 100644
--- a/crates/ai-memory-store/src/decay.rs
+++ b/crates/ai-memory-store/src/decay.rs
@@ -51,43 +51,84 @@ impl Default for DecayParams {
/// * `access_count` — total number of search hits.
/// * `days_since_access` — `Some(N)` if the page has ever been
/// accessed; `None` if it never has.
+/// * `salience` — the page's own salience when explicit feedback has
+/// moved it (`pages.salience`, V37); `None` falls back to
+/// [`DecayParams::salience_default`], which is what every page
+/// without feedback uses.
#[must_use]
pub fn retention_score(
params: &DecayParams,
age_days: f64,
access_count: u32,
days_since_access: Option<f64>,
+ salience: Option<f64>,
) -> f64 {
- let time_term = params.salience_default * (-params.lambda * age_days).exp();
+ let salience = salience.unwrap_or(params.salience_default);
+ let time_term = salience * (-params.lambda * age_days).exp();
let access_term = days_since_access.map_or(0.0, |d| {
params.sigma * (1.0 + f64::from(access_count)).ln() * (-params.mu * d).exp()
});
time_term + access_term
}
+/// Salience bounds and step for explicit feedback. Deliberately narrow:
+/// feedback should tilt retention, not let one agent judgement pin a
+/// page forever (`SALIENCE_MAX`) or evict it on the next sweep
+/// (`SALIENCE_MIN` keeps a fresh page above `cold_threshold`).
+pub const SALIENCE_MIN: f64 = 0.25;
+/// Upper salience bound; see [`SALIENCE_MIN`].
+pub const SALIENCE_MAX: f64 = 2.0;
+/// Per-signal salience step; see [`SALIENCE_MIN`].
+pub const SALIENCE_STEP: f64 = 0.25;
+
+/// Apply one feedback signal to a page's salience, clamped to
+/// `[SALIENCE_MIN, SALIENCE_MAX]`. `current` is `None` for a page that
+/// has never received feedback, which starts from
+/// [`DecayParams::salience_default`].
+///
+/// `Stale` / `Wrong` drop straight to the floor rather than stepping:
+/// they assert the content is no longer trustworthy, so retention
+/// should stop propping it up while it waits for a lint pass.
+#[must_use]
+pub fn salience_after_feedback(
+ params: &DecayParams,
+ current: Option<f64>,
+ kind: ai_memory_core::FeedbackKind,
+) -> f64 {
+ use ai_memory_core::FeedbackKind as K;
+ let current = current.unwrap_or(params.salience_default);
+ let next = match kind {
+ K::Helpful => current + SALIENCE_STEP,
+ K::NotHelpful => current - SALIENCE_STEP,
+ K::Stale | K::Wrong => SALIENCE_MIN,
+ };
+ next.clamp(SALIENCE_MIN, SALIENCE_MAX)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ use ai_memory_core::FeedbackKind;
#[test]
fn fresh_unused_page_starts_near_salience() {
let p = DecayParams::default();
- let score = retention_score(&p, 0.0, 0, None);
+ let score = retention_score(&p, 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);
+ let score = retention_score(&p, 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);
- let aged_hot = retention_score(&p, 200.0, 50, Some(2.0));
+ let aged_unused = retention_score(&p, 200.0, 0, None, None);
+ let aged_hot = retention_score(&p, 200.0, 50, Some(2.0), None);
assert!(aged_unused < p.cold_threshold);
assert!(
aged_hot > p.cold_threshold,
@@ -98,24 +139,90 @@ 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));
- let stale = retention_score(&p, 100.0, 10, Some(120.0));
+ let recent = retention_score(&p, 100.0, 10, Some(2.0), None);
+ let stale = retention_score(&p, 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);
- let old = retention_score(&p, 20.0, 0, None);
+ let young = retention_score(&p, 10.0, 0, None, None);
+ let old = retention_score(&p, 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));
- let high = retention_score(&p, 100.0, 20, Some(5.0));
+ let low = retention_score(&p, 100.0, 1, Some(5.0), None);
+ let high = retention_score(&p, 100.0, 20, Some(5.0), None);
assert!(high > low, "high {high} vs low {low}");
}
+
+ #[test]
+ 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));
+ 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));
+ assert!((with_access_boosted - with_access_default - default).abs() < 1e-9);
+ }
+
+ #[test]
+ 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)))
+ .abs()
+ < 1e-12,
+ "NULL salience must read exactly as salience_default",
+ );
+ }
+
+ #[test]
+ fn feedback_steps_salience_within_bounds() {
+ let p = DecayParams::default();
+ // Helpful steps up and saturates at the ceiling.
+ let mut s = salience_after_feedback(&p, None, FeedbackKind::Helpful);
+ assert!((s - (p.salience_default + SALIENCE_STEP)).abs() < 1e-9);
+ for _ in 0..20 {
+ s = salience_after_feedback(&p, Some(s), FeedbackKind::Helpful);
+ }
+ assert!((s - SALIENCE_MAX).abs() < 1e-9, "got {s}");
+
+ // Not-helpful steps down and saturates at the floor.
+ let mut s = salience_after_feedback(&p, None, FeedbackKind::NotHelpful);
+ assert!((s - (p.salience_default - SALIENCE_STEP)).abs() < 1e-9);
+ for _ in 0..20 {
+ s = salience_after_feedback(&p, Some(s), FeedbackKind::NotHelpful);
+ }
+ assert!((s - SALIENCE_MIN).abs() < 1e-9, "got {s}");
+
+ // Stale/wrong drop straight to the floor from anywhere.
+ for kind in [FeedbackKind::Stale, FeedbackKind::Wrong] {
+ let s = salience_after_feedback(&p, Some(SALIENCE_MAX), kind);
+ assert!((s - SALIENCE_MIN).abs() < 1e-9, "{kind:?} → {s}");
+ }
+ }
+
+ #[test]
+ fn floored_salience_keeps_a_fresh_page_above_the_cold_threshold() {
+ // 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));
+ assert!(
+ fresh_floored > p.cold_threshold,
+ "fresh floored page should survive: {fresh_floored}",
+ );
+ }
}
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 5e751e82..f220dd06 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -45,10 +45,10 @@ pub use ops::{
pub use reader::{
ActivityWindow, AutoImproveCandidateSession, BriefPageBody, BriefingPage, BriefingSnapshot,
ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,
- DerivedIndexStatus, EmbeddingTripleCount, GraphVia, HealthDetail, HealthPage, ObservationHit,
- OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary,
- ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow,
- SearchExplain, SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody,
+ DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia, HealthDetail, HealthPage,
+ ObservationHit, OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta,
+ PageSummary, ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions,
+ ScopeRow, SearchExplain, SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody,
WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
pub use scope::{
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 8bbbb8c5..7ced4d17 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -1078,6 +1078,79 @@ pub fn bump_access_for_pages(conn: &mut Connection, page_ids: &[PageId]) -> Stor
Ok(())
}
+/// Record one explicit feedback signal against the latest version of a
+/// page and update its derived salience, in a single transaction.
+///
+/// `page_feedback` is the append-only source of truth; `pages.salience`
+/// is the derived value the decay formula reads. Returns the page id and
+/// the salience after the update, or `None` when the path has no latest
+/// version in that scope (idempotent no-op for a deleted page).
+#[allow(clippy::too_many_arguments)]
+pub fn record_page_feedback(
+ conn: &mut Connection,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: &PagePath,
+ kind: ai_memory_core::FeedbackKind,
+ reason: Option<&str>,
+ author_id: Option<ai_memory_core::UserId>,
+ params: &crate::decay::DecayParams,
+) -> StoreResult<Option<(PageId, f64)>> {
+ let now = Timestamp::now().as_microsecond();
+ let tx = conn.transaction()?;
+ let existing: Option<(Vec<u8>, Option<f64>)> = tx
+ .query_row(
+ "SELECT id, salience FROM pages \
+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ path.as_str()
+ ],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ let Some((page_id_bytes, current_salience)) = existing else {
+ return Ok(None);
+ };
+ let page_id = PageId::from_slice(&page_id_bytes)?;
+ let next_salience = crate::decay::salience_after_feedback(params, current_salience, kind);
+
+ tx.execute(
+ "INSERT INTO page_feedback \
+ (id, page_id, workspace_id, project_id, kind, reason, author_id, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
+ params![
+ ai_memory_core::PageFeedbackId::new().as_bytes(),
+ page_id.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ kind.as_str(),
+ reason,
+ author_id.map(|id| id.as_bytes().to_vec()),
+ now,
+ ],
+ )?;
+ // Salience rides on the page *version*: a later supersession starts
+ // from salience_default again, which is intentional — feedback is a
+ // judgement on the content that was read, not on the path forever.
+ tx.execute(
+ "UPDATE pages SET salience = ?1 WHERE id = ?2",
+ params![next_salience, page_id.as_bytes()],
+ )?;
+ audit(
+ &tx,
+ "page_feedback",
+ Some(workspace_id.as_bytes()),
+ Some(project_id.as_bytes()),
+ Some(page_id.as_bytes()),
+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
+ now,
+ )?;
+ tx.commit()?;
+ Ok(Some((page_id, next_salience)))
+}
+
/// Mark a set of `is_latest=1` pages as soft-deleted by the forget
/// sweep. Distinguished from M7 supersession by `supersedes IS NULL`.
pub fn soft_delete_for_decay(conn: &mut Connection, page_ids: &[PageId]) -> StoreResult<usize> {
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 02e1a33b..55a32802 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -220,6 +220,22 @@ fn rerank_page_hits_with_meta(
hits
}
+/// One page flagged by `stale`/`wrong` feedback on its current version,
+/// aggregated per (page, kind) for the lint pass.
+#[derive(Debug, Clone, Serialize)]
+pub struct FeedbackFinding {
+ /// Wiki path of the flagged page.
+ pub path: String,
+ /// `stale` or `wrong`.
+ pub kind: String,
+ /// How many signals of this kind the current version has.
+ pub signal_count: u32,
+ /// ISO-8601 timestamp of the most recent signal.
+ pub latest_at: String,
+ /// Most recent caller-supplied reason for this kind, if any.
+ pub reason: Option<String>,
+}
+
/// A graph-expansion neighbour with provenance (which seed and which
/// link direction produced it). Internal to hybrid search + explain.
struct GraphNeighbor {
@@ -2079,7 +2095,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 \
+ frontmatter_json, expires_at, salience \
FROM pages \
WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1",
)?;
@@ -2096,6 +2112,63 @@ impl ReaderPool {
.await
}
+ /// Return `stale` / `wrong` feedback still attached to a *current*
+ /// page version in one project, grouped by (page, kind) — the input
+ /// for the lint pass's `feedback_flagged` findings. Rewriting a
+ /// flagged page supersedes the version the feedback points at, so
+ /// the finding drops out here without any explicit dismissal.
+ /// Most-recent signal first.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn open_feedback_findings(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> StoreResult<Vec<FeedbackFinding>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare_cached(
+ "SELECT pg.path, f.kind, COUNT(*) AS signal_count, MAX(f.created_at) AS latest, \
+ (SELECT reason FROM page_feedback r \
+ WHERE r.page_id = f.page_id AND r.kind = f.kind \
+ AND r.reason IS NOT NULL \
+ ORDER BY r.created_at DESC LIMIT 1) AS reason \
+ FROM page_feedback f \
+ JOIN pages pg ON pg.id = f.page_id AND pg.is_latest = 1 \
+ WHERE f.workspace_id = ?1 AND f.project_id = ?2 \
+ AND f.kind IN ('stale', 'wrong') \
+ GROUP BY pg.path, f.kind \
+ ORDER BY latest DESC",
+ )?;
+ let rows = stmt.query_map(
+ params![workspace_id.as_bytes(), project_id.as_bytes()],
+ |row| {
+ let path: String = row.get(0)?;
+ let kind: String = row.get(1)?;
+ let signal_count: i64 = row.get(2)?;
+ let latest_us: i64 = row.get(3)?;
+ let reason: Option<String> = row.get(4)?;
+ Ok((path, kind, signal_count, latest_us, reason))
+ },
+ )?;
+ let mut out = Vec::new();
+ for row in rows {
+ let (path, kind, signal_count, latest_us, reason) = row?;
+ out.push(FeedbackFinding {
+ path,
+ kind,
+ signal_count: u32::try_from(signal_count.max(0)).unwrap_or(u32::MAX),
+ latest_at: jiff::Timestamp::from_microsecond(latest_us)
+ .map(|ts| ts.to_string())
+ .unwrap_or_default(),
+ reason,
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// `expiry_cutoff_us`: see [`Self::search_pages_for_project`].
///
/// # Errors
@@ -5261,6 +5334,9 @@ pub struct DecayCandidate {
/// TTL instant in microseconds since epoch. The sweep hard-deletes
/// pages past this regardless of tier or pin.
pub expires_at_us: Option<i64>,
+ /// Per-page salience once explicit feedback has moved it (V37);
+ /// `None` means "use `DecayParams::salience_default`".
+ pub salience: Option<f64>,
}
fn row_to_decay_candidate(
@@ -5275,6 +5351,7 @@ fn row_to_decay_candidate(
let last_accessed_at_us: Option<i64> = row.get(6)?;
let frontmatter_json: String = row.get(7)?;
let expires_at_us: Option<i64> = row.get(8)?;
+ let salience: Option<f64> = row.get(9)?;
Ok(materialise_decay_candidate(
id_bytes,
path,
@@ -5285,6 +5362,7 @@ fn row_to_decay_candidate(
last_accessed_at_us,
frontmatter_json,
expires_at_us,
+ salience,
))
}
@@ -5299,6 +5377,7 @@ fn materialise_decay_candidate(
last_accessed_at_us: Option<i64>,
frontmatter_json: String,
expires_at_us: Option<i64>,
+ salience: Option<f64>,
) -> StoreResult<DecayCandidate> {
Ok(DecayCandidate {
id: PageId::from_slice(&id_bytes)?,
@@ -5312,6 +5391,7 @@ fn materialise_decay_candidate(
last_accessed_at_us,
frontmatter_json,
expires_at_us,
+ salience,
})
}
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 76cf75d3..e62f7415 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -185,6 +185,16 @@ pub(crate) enum WriteCmd {
page_ids: Vec<PageId>,
reply: oneshot::Sender<StoreResult<()>>,
},
+ RecordPageFeedback {
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: PagePath,
+ kind: ai_memory_core::FeedbackKind,
+ reason: Option<String>,
+ author_id: Option<ai_memory_core::UserId>,
+ params: crate::decay::DecayParams,
+ reply: oneshot::Sender<StoreResult<Option<(PageId, f64)>>>,
+ },
SoftDeleteForDecay {
page_ids: Vec<PageId>,
reply: oneshot::Sender<StoreResult<usize>>,
@@ -857,6 +867,38 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Record one explicit feedback signal for a page and update its
+ /// derived salience. Returns `None` when the path has no latest
+ /// version in that scope.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ #[allow(clippy::too_many_arguments)]
+ pub async fn record_page_feedback(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: PagePath,
+ kind: ai_memory_core::FeedbackKind,
+ reason: Option<String>,
+ author_id: Option<ai_memory_core::UserId>,
+ params: crate::decay::DecayParams,
+ ) -> StoreResult<Option<(PageId, f64)>> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RecordPageFeedback {
+ workspace_id,
+ project_id,
+ path,
+ kind,
+ reason,
+ author_id,
+ params,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Soft-delete pages identified by the M8 forget sweep.
///
/// # Errors
@@ -1676,6 +1718,28 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::reorg_sessions(&mut conn, &workspace_id, &plan);
send_or_warn(reply, result, "reorg_sessions");
}
+ WriteCmd::RecordPageFeedback {
+ workspace_id,
+ project_id,
+ path,
+ kind,
+ reason,
+ author_id,
+ params,
+ reply,
+ } => {
+ let result = ops::record_page_feedback(
+ &mut conn,
+ workspace_id,
+ project_id,
+ &path,
+ kind,
+ reason.as_deref(),
+ author_id,
+ &params,
+ );
+ send_or_warn(reply, result, "record_page_feedback");
+ }
WriteCmd::BumpAccess { page_ids, reply } => {
let result = ops::bump_access_for_pages(&mut conn, &page_ids);
send_or_warn(reply, result, "bump_access_for_pages");
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index e9f12300..bbdee147 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -239,7 +239,7 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| Table | What |
|---|---|
| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. |
-| `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. V36: `expires_at` (frontmatter TTL). |
+| `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. V36: `expires_at` (frontmatter TTL). V37: `salience` (NULL = `salience_default`; derived from `page_feedback`). |
| `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. |
| `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. `sessions.ended_observation_count` is the stable generation watermark for resumed-session re-end eligibility; wall clocks are not used for that decision. They are an operational audit trail, not a complete native transcript. |
| `session_consolidation_jobs` | Durable, observation-generation-idempotent queue for opt-in SessionEnd LLM consolidation. One bounded server worker leases jobs, retries provider failures with backoff, and recovers expired leases after restart. |
@@ -249,6 +249,7 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| `links` | Wikilink / markdown cross-references. `to_page_id` (a global PageId) is nullable for unresolved forward links. `to_workspace` / `to_project` carry a cross-project scope (NULL = the source page's own project). |
| `handoffs` | Typed cross-agent handoff records (open / accepted / expired). |
| `page_embeddings` | Optional vector rows for latest pages, with `(provider, model, dim)` denormalised so hybrid search can ignore stale vectors after an embedding config change and report missing-embedding diagnostics. |
+| `page_feedback` | Append-only `memory_feedback` signals (`helpful` / `not_helpful` / `stale` / `wrong`) keyed by page *version*, with an optional reason. Source of truth for the derived `pages.salience`; the lint pass reads unresolved stale/wrong rows joined against `is_latest = 1`, so a rewrite retires the finding. |
| `audit_log` | Every mutation, addressable by `at DESC`. |
**Memory tiers (M8 policy):**
@@ -316,7 +317,7 @@ Each crate has a single responsibility and exposes a typed API. No
circular deps. Inter-crate boundaries enforce the cross-cutting
invariants below.
-## MCP tool surface (16 tools)
+## MCP tool surface (17 tools)
| Tool | Hint | Purpose |
|---|---|---|
@@ -330,6 +331,7 @@ invariants below.
| `memory_handoff_accept` | destructive | Fetch + ack the latest open handoff (auto-cwd-matched by default). Optional `workspace` + `project` targets a named sibling workspace/project. |
| `memory_handoff_cancel` | destructive | Mark an exact open handoff id expired when it was created by mistake. |
| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. |
+| `memory_feedback` | write | Record a quality signal for one page by exact `path`: `helpful`/`not_helpful` step its `pages.salience` (which scales the retention formula's time term), `stale`/`wrong` floor salience AND surface the page as a `feedback_flagged` lint finding. Never deletes; attaches to the page *version*, so a rewrite clears it. |
| `memory_auto_improve` | write | Manually review a completed session and apply or stage validated wiki edits through the auto-improvement approval path. Defaults to the latest completed session in the resolved current project; the server also schedules review for new sessions; `[auto_improve] require_approval = true` leaves proposals pending for manual review. |
| `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate it. `scope: "global"` writes into the reserved `_global` preferences scope; optional `expires_at` sets an RFC3339 or date-only TTL. |
| `memory_delete_page` | destructive | Delete a single page by exact `path`. Fires the admission chain (op=delete); idempotent. |
@@ -339,7 +341,7 @@ invariants below.
`memory_briefing`, `memory_explore`, `memory_write_page`,
`memory_install_self_routing`, `memory_read_page`, `memory_delete_page`,
-`memory_handoff_cancel`, and `memory_auto_improve`
+`memory_handoff_cancel`, `memory_auto_improve`, and `memory_feedback`
post-date the original "narrow on purpose" cut (§10 of
`design-decisions.md`): briefing/explore separate the structured vs.
prose halves of "what's going on", `memory_write_page` covers explicit
@@ -354,7 +356,13 @@ safe default-on learning review through the same approval/write path as
pending writes, and `memory_delete_page` is the exact-path destructive pair
needed by admission-aware mirrors. `memory_handoff_cancel` is the safety valve
for mistaken handoff creation. The narrow-surface discipline still holds —
-every new tool has to earn its slot — but the v1 count is 16, not 10.
+every new tool has to earn its slot — but the v1 count is 16, not 10. `memory_feedback` implements the
+"finer-grained reinforcement beyond access counts" P2 item from
+`prior-art-implementation-findings.md`: it cannot ride on a read tool
+without conflating read and write semantics, and the access counter it
+supplements cannot tell "this page answered the question" from "this page
+wasted a read". The narrow-surface discipline still holds —
+every new tool has to earn its slot — but the count is 17, not 10.
The managed Agent Skills are a narrow prompt-packaging exception to the
otherwise wiki-centered architecture. They are static `SKILL.md` files that