Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: auto-approve memory improvements
AkitaOnRails2cf85d675e63
diff --git a/AGENTS.md b/AGENTS.mdindex 258655e3..b7349e89 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -42,7 +42,7 @@ match the intent to the tool. They do not need to name the tool.| "save context for the next session" / wrapping up / ending this session | `memory_handoff_begin` (session-end only; do **not** use for status/briefing; single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets; pass `workspace` + `project` together only for a named sibling workspace/project) || "discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` (requires exact `handoff_id` from `memory_handoff_begin`; marks it expired before the next session sees it) || "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` |-| "what did we learn from this session?" / "what memory should we add?" / explicit wrap-up learning review | `memory_auto_improve` (dry-run only; omit `session_id` for latest completed session; show proposals and evidence; do **not** apply/write them unless the user explicitly approves) |+| "what did we learn from this session?" / "what memory should we add?" / explicit wrap-up learning review | `memory_auto_improve` (reviews a completed session and applies validated wiki edits through the auto-improvement approval path; omit `session_id` for latest completed session) || "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes; put the title as a `# H1` on the first line of `body` and omit the `title` arg — ai-memory derives it from the H1) || "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup; pass `workspace` + `project` together only for a named sibling workspace/project) || "delete the page X" / "remove that note" | `memory_delete_page` (by exact `path`; idempotent; pass `workspace` + `project` together only for a named sibling workspace/project) |@@ -96,12 +96,12 @@ query specific error/subsystem terms before designing a fix.### Learning Review-`memory_auto_improve` is a dry-run learning reviewer. Use it when the-user asks what durable lessons this session suggests, or at explicit-wrap-up when reviewing proposed memory would be useful. It returns-proposed wiki edits with evidence and never writes pages or pending-proposals. Do not apply proposals with `memory_write_page` unless the-user explicitly approves.+`memory_auto_improve` is a learning reviewer that applies validated wiki edits+through the auto-improvement approval path. Use it when the user asks what+durable lessons this session suggests, or at explicit wrap-up when reviewing+proposed memory would be useful. Admins can opt into manual review with+`[auto_improve] require_approval = true`, in which case proposals stay in+pending-writes until approved.### When you write a project rule, write it herediff --git a/CHANGELOG.md b/CHANGELOG.mdindex cd6a25d6..b76e973e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,22 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed+- `ai-memory auto-improve --session-id <uuid>` and `POST /admin/auto-improve`+ now record validated proposals in the pending-writes audit trail and approve+ them immediately through the normal wiki write path. Set+ `[auto_improve] require_approval = true` to keep proposals pending for manual+ review. The MCP `memory_auto_improve` tool uses the same behavior.+- Existing project wikis need no migration. Existing server configs that+ contain the old `[auto_improve] mode = ...` key keep working; the key is now+ ignored and can be removed when convenient.+## [1.0.9] - 2026-06-15### Fixed- Clarified architecture and auto-improvement design docs so CLI/admin- auto-improvement is described as dry-run by default with explicit staging and- pending-writes approval, while only the MCP tool remains dry-run-only.+ auto-improvement is described with pending-writes storage and approval+ boundaries.## [1.0.8] - 2026-06-15### Added-- Added staged auto-improvement review: `ai-memory auto-improve --stage` and- `POST /admin/auto-improve` stage mode store validated proposals in durable- SQLite-backed pending-write rows with non-indexed `_pending/auto-improve/`- sidecars. The new `ai-memory pending-writes list|show|diff|approve|reject`- commands and `/admin/pending-writes*` routes let operators review, apply, or- reject those stored proposal bodies through the normal wiki mutation path.+- Added auto-improvement proposal storage: `ai-memory auto-improve` and+ `POST /admin/auto-improve` store validated proposals in durable SQLite-backed+ pending-write rows with non-indexed `_pending/auto-improve/` sidecars. The new+ `ai-memory pending-writes list|show|diff|approve|reject` commands and+ `/admin/pending-writes*` routes let operators review, apply, or reject stored+ proposal bodies through the normal wiki mutation path.- Added first-release curator support: `ai-memory curator` and`POST /admin/curator` run a rule-based, no-LLM, report-only maintenancereview for an existing workspace/project. Dry-run is the default and writes@@ -33,21 +43,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [1.0.7] - 2026-06-15### Added-- Added a dry-run-only auto-improvement reviewer: `ai-memory auto-improve- --dry-run --session-id <uuid>` calls `POST /admin/auto-improve`, reads one- completed session, applies preflight noise filters, samples large sessions via- the consolidated session page plus high-signal observations, asks the- configured LLM for structured durable wiki edit proposals, validates- path/evidence/confidence and duplicate existing path/title constraints, and- returns a report without writing wiki files or pending proposals. New- `[auto_improve]` config defaults are enabled in safe `dry_run` mode, with no- session-end trigger or writes unless a future staged/apply mode is explicitly- enabled. Thresholds remain configurable: confidence, input budget, proposal- cap, `auto_improve` attribution, and `_pending/auto-improve` staging path.-- Added read-only MCP tool `memory_auto_improve` so agents can dry-run learning- review for the latest completed session (or a named session) without shelling- out. The canonical MCP instructions and installed CLAUDE.md/AGENTS.md routing- snippet now teach agents to treat `_rules/`, `gotchas/`, `procedures/`, and+- Added the initial auto-improvement reviewer: `ai-memory auto-improve+ --session-id <uuid>` calls `POST /admin/auto-improve`, reads one completed+ session, applies preflight noise filters, samples large sessions via the+ consolidated session page plus high-signal observations, asks the configured+ LLM for structured durable wiki edit proposals, and validates+ path/evidence/confidence plus duplicate existing path/title constraints.+ Thresholds remain configurable: confidence, input budget, proposal cap,+ `auto_improve` attribution, and `_pending/auto-improve` proposal path.+- Added MCP tool `memory_auto_improve` so agents can run learning review for the+ latest completed session (or a named session) without shelling out. The+ canonical MCP instructions and installed CLAUDE.md/AGENTS.md routing snippet+ now teach agents to treat `_rules/`, `gotchas/`, `procedures/`, and`decisions/` as actionable guidance for proactive retrieval.### Changed@@ -65,7 +72,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`create_or_update` operation, markdown bodies can arrive as `body`,`markdown`, or `content`, plural/folder-style kind names are normalized beforepath validation, and proposals still missing required target data are rejected- by validation instead of turning the whole dry-run review into a 502 response.+ by validation instead of turning the whole review into a 502 response.- Admin destructive ops (`/admin/purge-project`, `/admin/move-project`) nowpropagate the authenticated actor (from the auth middleware's`Extension<ActorContext>`) into the admission context, so a `scope-guard`diff --git a/README.md b/README.mdindex 2bced181..2fc7d898 100644--- a/README.md+++ b/README.md@@ -89,14 +89,14 @@ priors are at the [bottom](#influences-and-prior-art).session-aware current-project routing.- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,`restore-page`, `purge-project`, `rename-project`, `move-project`, `lint`,- `curator`, `auto-improve --dry-run`, `embed`, `forget-sweep`, `backup` are+ `curator`, `auto-improve`, `pending-writes`, `embed`, `forget-sweep`, `backup` areall HTTP clients of the running server - never touch SQLite orwiki files directly. `status` also reports passive LLM/embeddingprovider health from the last real provider call. Server is thesingle source of truth.- **LLM is opt-in.** Zero-LLM mode still gives you FTS5 search +rule-based summarisation. Add a provider when you want consolidated- pages, lint contradictions, or dry-run auto-improvement proposals.+ pages, lint contradictions, or staged auto-improvement proposals.## Use cases@@ -129,18 +129,23 @@ priors are at the [bottom](#influences-and-prior-art).one-shot-summarises them into seed wiki pages. Future sessionsbuild on top.- **"What durable lesson did that session teach?"**- `ai-memory auto-improve --dry-run --session-id <uuid>` reviews one completed- session with the configured LLM and returns validated proposed wiki edits. It- writes nothing by default; `ai-memory auto-improve --stage --session-id <uuid>`- stores validated proposals in the pending-writes queue for later- `list`/`show`/`diff`/`approve`/`reject`. Agents can also call- `memory_auto_improve` to dry-run review the latest completed session in the- current project without knowing the session id.+ `ai-memory auto-improve --session-id <uuid>` reviews one completed session+ with the configured LLM, records proposed wiki edits in the pending-writes+ audit trail, and approves them immediately through the normal wiki write path.+ Agents can also call `memory_auto_improve` to review the latest completed+ session in the current project without knowing the session id. If you want a+ human review queue instead, set `[auto_improve] require_approval = true` and+ use `pending-writes list`/`show`/`diff`/`approve`/`reject`.++ Existing installs do not need per-project migration. Older configs may still+ contain an `[auto_improve] mode = ...` line; current ai-memory ignores that+ legacy key, so you can remove it when convenient.- **"What housekeeping should I consider?"**`ai-memory curator` runs a no-LLM, rule-based maintenance report over coldepisodic pages, stale slots, duplicate exact normalized titles, and dangling- cross-project links. It defaults to dry-run; `--stage` queues one report page- for approval and still performs no maintenance actions itself.+ cross-project links. It is report-only unless `--stage` is passed; staging+ queues one report page for approval and still performs no maintenance actions+ itself.- **"Run one ai-memory for the whole household."** Stand the serverup on a homelab box at `0.0.0.0:49374` with a bearer token; everylaptop/desktop talks to it. Per-cwd routing keeps each project's@@ -551,7 +556,7 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. || [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS (multi-user, non-loopback) and when you don't (loopback / stdio). Copy-paste docker compose templates for Caddy + Let's Encrypt, Caddy + internal CA (LAN-only), Cloudflare Tunnel (no open ports), and external cert files; plus native-Caddy + nginx recipes. The "thinking you're secure when you're not" failure modes explicitly called out. || [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset / reindex / restore-page.** Safety matrix for state-touching commands, per-project disk layout (how isolation actually works), checkpoint-based page recovery, and operator workflows for "fresh start", "snapshot before risky op", "drop one project", and rebuilding SQLite from wiki files. |-| [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: Hermes-inspired post-session review, dry-run defaults, approval boundaries, pending proposal storage, and future curator work. |+| [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: Hermes-inspired post-session review, auto-approval default, manual review opt-in, pending proposal storage, and curator work. || [`docs/llm-provider-comparison.md`](docs/llm-provider-comparison.md) | Empirical notes behind the recommended LLM defaults. || [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. || [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec. |diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex d8851dc9..8f42da08 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -81,7 +81,7 @@ pub enum Command {Lint(LintArgs),/// Run the rule-based curator report.Curator(CuratorArgs),- /// Dry-run an optional auto-improvement review for one completed session.+ /// Run auto-improvement for one completed session.AutoImprove(AutoImproveArgs),/// Review, approve, or reject staged auto-improvement proposals.PendingWrites(PendingWritesArgs),@@ -882,12 +882,6 @@ pub struct CuratorArgs {/// Arguments for `auto-improve`.#[derive(Debug, Args)]pub struct AutoImproveArgs {- /// Run reviewer without staging proposals.- #[arg(long)]- pub dry_run: bool,- /// Stage validated proposals for review.- #[arg(long)]- pub stage: bool,/// Completed session UUID to review.#[arg(long)]pub session_id: String,@@ -1275,25 +1269,25 @@ mod tests {}#[test]- fn auto_improve_dry_run_parses_required_session() {+ fn auto_improve_parses_required_session() {let cli = Cli::try_parse_from(["ai-memory","auto-improve",- "--dry-run","--session-id","00000000-0000-0000-0000-000000000000",+ "--project",+ "scratch","--max-proposals","2",])- .expect("auto-improve dry-run parses");+ .expect("auto-improve parses");let Command::AutoImprove(args) = cli.command else {panic!("expected auto-improve command");};- assert!(args.dry_run);assert_eq!(args.session_id, "00000000-0000-0000-0000-000000000000");assert_eq!(args.max_proposals, Some(2));- assert_eq!(args.project, None);+ assert_eq!(args.project.as_deref(), Some("scratch"));}#[test]@@ -1330,27 +1324,6 @@ mod tests {assert!(!args.dry_run);}- #[test]- fn auto_improve_stage_parses_required_session() {- let cli = Cli::try_parse_from([- "ai-memory",- "auto-improve",- "--stage",- "--session-id",- "00000000-0000-0000-0000-000000000000",- "--project",- "scratch",- ])- .expect("auto-improve stage parses");-- let Command::AutoImprove(args) = cli.command else {- panic!("expected auto-improve command");- };- assert!(args.stage);- assert!(!args.dry_run);- assert_eq!(args.project.as_deref(), Some("scratch"));- }-#[test]fn pending_writes_subcommands_parse() {let id = "00000000-0000-0000-0000-000000000000";diff --git a/crates/ai-memory-cli/src/commands/auto_improve.rs b/crates/ai-memory-cli/src/commands/auto_improve.rsindex c9eaf5ac..e4ffb714 100644--- a/crates/ai-memory-cli/src/commands/auto_improve.rs+++ b/crates/ai-memory-cli/src/commands/auto_improve.rs@@ -1,7 +1,6 @@-//! `ai-memory auto-improve` — dry-run durable wiki edit proposals.+//! `ai-memory auto-improve` — review one session and apply durable wiki edits through the auto-improvement approval path.-use ai_memory_consolidate::AutoImproveReport;-use anyhow::{Result, bail};+use anyhow::Result;use serde::{Deserialize, Serialize};use crate::cli::AutoImproveArgs;@@ -14,8 +13,6 @@ struct AutoImproveRequest {workspace: String,project: String,session_id: String,- dry_run: bool,- stage: bool,min_observations: usize,min_session_duration_secs: u64,min_confidence: f32,@@ -29,21 +26,28 @@ struct AutoImproveRequest {#[derive(Debug, Deserialize, Serialize)]struct StageResponse {run_id: String,- proposal_ids: Vec<String>,- sidecar_paths: Vec<String>,- report: AutoImproveReport,+ approval_required: bool,+ approval_policy: String,+ session_id: String,+ summary: String,+ warnings: Vec<String>,+ rejected_candidates_count: usize,+ proposals: Vec<ProposalOutcome>,+}++#[derive(Debug, Deserialize, Serialize)]+struct ProposalOutcome {+ id: String,+ sidecar_path: String,+ status: String,+ page_id: Option<String>,}/// Run the `auto-improve` subcommand.////// # Errors-/// Returns an error if the command is not explicitly dry-run, if the server is-/// unreachable, or if the server rejects the review request.+/// Returns an error if the server is unreachable or rejects the review request.pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {- if args.dry_run == args.stage {- bail!("choose exactly one of --dry-run or --stage");- }-let endpoint = ServerEndpoint::from_config(config);let project = super::resolve_project_name(config, args.project.as_deref())?;let settings = &config.auto_improve;@@ -51,8 +55,6 @@ pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {workspace: args.workspace,project: project.clone(),session_id: args.session_id,- dry_run: args.dry_run,- stage: args.stage,min_observations: args.min_observations.unwrap_or(settings.min_observations),min_session_duration_secs: args.min_session_duration_secs@@ -65,76 +67,32 @@ pub async fn run(config: &Config, args: AutoImproveArgs) -> Result<()> {pending_path: settings.pending_path.clone(),};- if args.stage {- let response: StageResponse = post_json(&endpoint, "/admin/auto-improve", &request).await?;- if args.json {- println!("{}", serde_json::to_string_pretty(&response)?);- } else {- println!("Staged auto-improve run {}", response.run_id);- for (id, path) in response- .proposal_ids- .iter()- .zip(response.sidecar_paths.iter())- {- println!(" - {id}: {path}");- }- }+ let response: StageResponse = post_json(&endpoint, "/admin/auto-improve", &request).await?;+ if args.json {+ println!("{}", serde_json::to_string_pretty(&response)?);} else {- let report: AutoImproveReport =- post_json(&endpoint, "/admin/auto-improve", &request).await?;- if args.json {- println!("{}", serde_json::to_string_pretty(&report)?);- } else {- print_human_report(&report, &project);- println!("\n--- machine-readable ---");- println!("{}", serde_json::to_string_pretty(&report)?);- }- }- Ok(())-}--fn print_human_report(report: &AutoImproveReport, project: &str) {- println!(- "\nAuto-improve dry-run for {project} session {}\n",- report.session_id- );- println!("Summary: {}", report.summary);- println!(- "Input: {} observations, {}s span, ~{} tokens",- report.observations_considered, report.session_duration_secs, report.estimated_input_tokens- );- println!(- "Reviewer: {}/{}; min confidence {}",- report.provider, report.model, report.min_confidence- );- println!(- "Future staging: actor `{}`, path `{}`",- report.proposal_actor, report.pending_path- );-- if report.proposals.is_empty() {- println!("\nValidated proposals: none");- } else {- println!("\nValidated proposals:");- for proposal in &report.proposals {+ if response.approval_required {println!(- " - {} [{}] confidence {:.2}: {}",- proposal.path, proposal.kind, proposal.confidence, proposal.title+ "Staged auto-improve run {} for manual approval",+ response.run_id);+ } else {+ println!("Auto-approved auto-improve run {}", response.run_id);}- }-- if !report.rejected_candidates.is_empty() {- println!("\nRejected candidates:");- for rejected in &report.rejected_candidates {- println!(" - {}: {}", rejected.reason, rejected.evidence);- }- }-- if !report.warnings.is_empty() {- println!("\nWarnings:");- for warning in &report.warnings {- println!(" - {warning}");+ println!("Approval policy: {}", response.approval_policy);+ for proposal in &response.proposals {+ if let Some(page_id) = &proposal.page_id {+ println!(+ " - {} [{}] page {} ({})",+ proposal.id, proposal.status, page_id, proposal.sidecar_path+ );+ } else {+ println!(+ " - {} [{}] ({})",+ proposal.id, proposal.status, proposal.sidecar_path+ );+ }}}+ Ok(())}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex ef544517..ccef7891 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -164,6 +164,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj).with_wiki(wiki.clone()).with_decay_params(config.decay)+ .with_auto_improve_require_approval(config.auto_improve.require_approval).with_active_project(active_project.clone()).with_sanitizer(sanitizer.clone());if let Some(e) = embedder.clone() {@@ -262,6 +263,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {reader: store.reader.clone(),wiki: wiki.clone(),llm: admin_llm,+ auto_improve_require_approval: config.auto_improve.require_approval,embedder: embedder.clone(),provider_health: provider_health.clone(),decay_params: config.decay,diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex d07b857c..19093855 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -105,7 +105,9 @@ pub struct Config {pub decay: ai_memory_store::DecayParams,/// Server-side scheduled maintenance. Jobs run outside hook latency.pub maintenance: MaintenanceSettings,- /// Optional post-session auto-improvement reviewer. Off by default.+ /// Optional auto-improvement reviewer. Manual CLI/admin runs approve+ /// validated proposals by default unless `require_approval` is set; the+ /// SessionEnd trigger stays off by default.pub auto_improve: AutoImproveSettings,/// Privacy-strip tuning. Built-in patterns always run; this section/// lets the operator extend or punch holes in them.@@ -360,28 +362,14 @@ impl Default for Config {}}-/// Write mode for the optional auto-improvement loop.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]-#[serde(rename_all = "snake_case")]-pub enum AutoImproveMode {- /// Report-only preview; no wiki or pending-proposal writes.- #[default]- DryRun,- /// Store proposals for human approval. Intended default once storage ships.- Stage,- /// Future mode only: apply narrow high-confidence proposals automatically.- AutoApply,-}-/// `[auto_improve]` optional post-session reviewer settings.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(default)]pub struct AutoImproveSettings {- /// Master switch. Defaults to false; manual dry-runs can still pass- /// explicit CLI flags without enabling the session-end trigger.- pub enabled: bool,- /// Configured write mode. The first shipped command supports dry-run only.- pub mode: AutoImproveMode,+ /// Require manual pending-writes approval. Defaults false so validated+ /// proposals are staged for audit and immediately approved through the+ /// normal wiki write path.+ pub require_approval: bool,/// Whether SessionEnd should schedule a reviewer run. Defaults off so hooks/// stay cheap and fire-and-forget.pub on_session_end: bool,@@ -399,15 +387,14 @@ pub struct AutoImproveSettings {pub include_raw_fallback: bool,/// Synthetic actor used for autonomous proposal provenance.pub proposal_actor: String,- /// Wiki-relative pending proposal folder once staging ships.+ /// Wiki-relative folder for non-indexed pending proposal sidecars.pub pending_path: String,}impl Default for AutoImproveSettings {fn default() -> Self {Self {- enabled: true,- mode: AutoImproveMode::DryRun,+ require_approval: false,on_session_end: false,min_observations: ai_memory_consolidate::DEFAULT_AUTO_IMPROVE_MIN_OBSERVATIONS,min_session_duration_secs:@@ -804,9 +791,8 @@ mod tests {assert_eq!(cfg.maintenance.forget_sweep_interval_secs, 86_400);assert_eq!(cfg.maintenance.lint_interval_secs, 86_400);assert_eq!(cfg.maintenance.embedding_backfill_interval_secs, 0);- assert!(cfg.auto_improve.enabled);- assert_eq!(cfg.auto_improve.mode, AutoImproveMode::DryRun);assert!(!cfg.auto_improve.on_session_end);+ assert!(!cfg.auto_improve.require_approval);assert_eq!(cfg.auto_improve.min_observations, 8);assert_eq!(cfg.auto_improve.min_session_duration_secs, 120);assert_eq!(@@ -852,8 +838,8 @@ mod tests {lint_interval_secs = 3600[auto_improve]- enabled = truemode = "dry_run"+ require_approval = trueon_session_end = truemin_observations = 3min_session_duration_secs = 45@@ -874,9 +860,8 @@ mod tests {assert_eq!(cfg.log_level, "debug");assert!(!cfg.maintenance.enabled);assert_eq!(cfg.maintenance.lint_interval_secs, 3600);- assert!(cfg.auto_improve.enabled);- assert_eq!(cfg.auto_improve.mode, AutoImproveMode::DryRun);assert!(cfg.auto_improve.on_session_end);+ assert!(cfg.auto_improve.require_approval);assert_eq!(cfg.auto_improve.min_observations, 3);assert_eq!(cfg.auto_improve.min_session_duration_secs, 45);assert_eq!(cfg.auto_improve.min_confidence, 0.9);diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.tomlindex b53f7cfa..6ec21e83 100644--- a/crates/ai-memory-cli/templates/config.default.toml+++ b/crates/ai-memory-cli/templates/config.default.toml@@ -74,3 +74,23 @@ hard_delete_after_days = 180[sanitize]extra_patterns = []allowlist = []++# Auto-improvement reviewer.+#+# Manual CLI/admin/MCP runs stage validated proposals in the pending-writes queue+# for audit, then approve them immediately by default through the normal wiki+# write path. Set `require_approval = true` to keep proposals pending until an+# admin runs `ai-memory pending-writes approve <id>`.+#+# Older configs may still contain an `[auto_improve] mode = ...` line. That key+# is ignored by current ai-memory and can be removed when convenient.+[auto_improve]+require_approval = false+min_observations = 8+min_session_duration_secs = 120+min_confidence = 0.75+max_input_tokens = 24000+max_proposals_per_run = 5+include_raw_fallback = false+proposal_actor = "auto_improve"+pending_path = "_pending/auto-improve"diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex 7811b5a4..db0132bf 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -1,8 +1,9 @@-//! Dry-run reviewer for optional auto-improvement proposals.+//! Reviewer for optional auto-improvement proposals.//!//! This module is intentionally read-only. It inspects one completed session,//! asks the configured LLM for structured wiki edit proposals, validates those-//! proposals, and returns a report. Staging and approval live in a later phase.+//! proposals, and returns a report. CLI/admin code may stage the validated+//! proposals after this read-only review returns.use std::collections::BTreeSet;@@ -36,10 +37,10 @@ pub const DEFAULT_AUTO_IMPROVE_MAX_INPUT_TOKENS: usize = 24_000;pub const DEFAULT_AUTO_IMPROVE_MAX_PROPOSALS: usize = 5;/// Default synthetic actor name for autonomous proposal provenance.pub const DEFAULT_AUTO_IMPROVE_PROPOSAL_ACTOR: &str = "auto_improve";-/// Default wiki-relative folder for future pending proposal markdown.+/// Default wiki-relative folder for pending proposal sidecar markdown.pub const DEFAULT_AUTO_IMPROVE_PENDING_PATH: &str = "_pending/auto-improve";-/// Configuration for one dry-run auto-improvement review.+/// Configuration for one auto-improvement review.#[derive(Debug, Clone)]pub struct AutoImproveReviewConfig {/// Minimum observations before a session is worth reviewing.@@ -52,16 +53,15 @@ pub struct AutoImproveReviewConfig {pub max_input_tokens: usize,/// Maximum validated proposals returned from one run.pub max_proposals_per_run: usize,- /// Whether raw fallback content may be considered. Reserved for prompt- /// visibility in this dry-run slice; hooks still provide raw observations.+ /// Whether raw fallback content may be considered. Hooks still provide raw observations.pub include_raw_fallback: bool,- /// Synthetic actor name used for future proposal provenance.+ /// Synthetic actor name used for staged proposal provenance.pub proposal_actor: String,- /// Wiki-relative pending proposal folder once staging ships.+ /// Wiki-relative pending proposal sidecar folder.pub pending_path: String,}-/// Errors raised by the dry-run reviewer.+/// Errors raised by the reviewer.#[derive(Debug, Error)]pub enum AutoImproveError {/// Underlying store error.@@ -188,11 +188,9 @@ pub struct AutoImproveLlmResponse {pub rejected_candidates: Vec<AutoImproveRejectedCandidate>,}-/// Report returned by the dry-run reviewer.+/// Report returned by the reviewer.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct AutoImproveReport {- /// Always true for this first implementation slice.- pub dry_run: bool,/// Reviewed session id.pub session_id: String,/// Number of observations read from the session.@@ -207,13 +205,13 @@ pub struct AutoImproveReport {pub model: String,/// Configured confidence floor used by validation.pub min_confidence: f32,- /// Actor name reserved for future staged proposal provenance.+ /// Actor name used for staged proposal provenance.pub proposal_actor: String,- /// Wiki-relative pending path reserved for future staged proposal markdown.+ /// Wiki-relative pending proposal sidecar path.pub pending_path: String,/// Review summary.pub summary: String,- /// Validated proposals. No wiki writes have occurred.+ /// Validated proposals. Target wiki pages have not been written.pub proposals: Vec<AutoImproveProposal>,/// Model and validator rejections.pub rejected_candidates: Vec<AutoImproveRejectedCandidate>,@@ -221,7 +219,7 @@ pub struct AutoImproveReport {pub warnings: Vec<String>,}-/// Run a dry-run auto-improvement review for one session.+/// Run a read-only auto-improvement review for one session.////// # Errors/// Returns store, scope, or LLM errors. This function never writes wiki files or@@ -245,7 +243,6 @@ pub async fn run_auto_improve_review(let duration = session_duration_secs(&observations);if let Some(rejection) = preflight_rejection(&observations, duration, &cfg) {return Ok(AutoImproveReport {- dry_run: true,session_id: session_id.to_string(),observations_considered: observations.len(),session_duration_secs: duration,@@ -295,7 +292,6 @@ pub async fn run_auto_improve_review(warnings.extend(prompt_input.warnings);Ok(AutoImproveReport {- dry_run: true,session_id: session_id.to_string(),observations_considered: observations.len(),session_duration_secs: duration,@@ -410,7 +406,7 @@ fn build_prompt_input(Minimum confidence: {}\n\Max proposals: {}\n\Include raw fallback: {}\n\- Pending path for future staging: {}\n\n\+ Pending proposal sidecar path: {}\n\n\Existing project pages, for duplicate avoidance. Do not target these existing paths or titles; diff-based update proposals are a later phase:\n{recent}\n\n\Consolidated session page, primary source when present:\n{session_page_section}\n\n\Selected observations, sampled for scale and supporting evidence:\n{rendered_observations}\n\n\@@ -871,7 +867,7 @@ fn estimate_tokens(text: &str) -> usize {text.len().div_ceil(CHARS_PER_TOKEN)}-const AUTO_IMPROVE_SYSTEM_PROMPT: &str = r#"You are ai-memory's dry-run auto-improvement reviewer.+const AUTO_IMPROVE_SYSTEM_PROMPT: &str = r#"You are ai-memory's review-gated auto-improvement reviewer.Return structured JSON matching the schema. You are proposing wiki edits, not applying them.@@ -1052,7 +1048,6 @@ mod tests {.await.unwrap();- assert!(report.dry_run);assert_eq!(report.provider, "fake");assert_eq!(report.model, "fake-model");assert_eq!(report.proposals.len(), 1);diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex e47b0df4..8238b51a 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -70,7 +70,7 @@ match the intent to the tool. They do not need to name the tool.| "save context for the next session" / wrapping up / ending this session | `memory_handoff_begin` (session-end only; do **not** use for status/briefing; single-use handoff; terse summary; put detail in `open_questions` + `next_steps` bullets; pass `workspace` + `project` together only for a named sibling workspace/project) || "discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` (requires exact `handoff_id` from `memory_handoff_begin`; marks it expired before the next session sees it) || "consolidate this session" / "compile what we learned" (also runs on PreCompact; at session end only if `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set) | `memory_consolidate` |-| "what did we learn from this session?" / "what memory should we add?" / explicit wrap-up learning review | `memory_auto_improve` (dry-run only; omit `session_id` for latest completed session; show proposals and evidence; do **not** apply/write them unless the user explicitly approves) |+| "what did we learn from this session?" / "what memory should we add?" / explicit wrap-up learning review | `memory_auto_improve` (reviews a completed session and applies validated wiki edits through the auto-improvement approval path; omit `session_id` for latest completed session) || "remember this permanently" / "save a note" / "add an annotation" / durable project knowledge | `memory_write_page` (write a wiki page; do **not** use handoff for permanent notes; put the title as a `# H1` on the first line of `body` and omit the `title` arg — ai-memory derives it from the H1) || "read the page about X" / "show me the full content of Y" / "open the page on Z" | `memory_read_page` (full body; pass a query to search or `path` for a direct lookup; pass `workspace` + `project` together only for a named sibling workspace/project) || "delete the page X" / "remove that note" | `memory_delete_page` (by exact `path`; idempotent; pass `workspace` + `project` together only for a named sibling workspace/project) |@@ -124,12 +124,12 @@ query specific error/subsystem terms before designing a fix.### Learning Review-`memory_auto_improve` is a dry-run learning reviewer. Use it when the-user asks what durable lessons this session suggests, or at explicit-wrap-up when reviewing proposed memory would be useful. It returns-proposed wiki edits with evidence and never writes pages or pending-proposals. Do not apply proposals with `memory_write_page` unless the-user explicitly approves.+`memory_auto_improve` is a learning reviewer that applies validated wiki edits+through the auto-improvement approval path. Use it when the user asks what+durable lessons this session suggests, or at explicit wrap-up when reviewing+proposed memory would be useful. Admins can opt into manual review with+`[auto_improve] require_approval = true`, in which case proposals stay in+pending-writes until approved.### When you write a project rule, write it herediff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex b8fff9bd..da1930f1 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -4,7 +4,7 @@//! - `POST /admin/backup` — snapshot db + wiki into a gzip tarball (binary response).//! - `POST /admin/bootstrap` — ingest a pre-collected source bundle//! into seed wiki pages via the configured LLM provider.-//! - `POST /admin/auto-improve` — dry-run durable wiki edit proposals for one session.+//! - `POST /admin/auto-improve` — review one session and stage proposals.//! - `POST /admin/curator` — dry-run or stage a rule-based curator report.//! - `GET /admin/status` — lifetime counts + server data-dir info.//! - `GET /admin/search?q=` — FTS5 hits against the wiki index.@@ -77,6 +77,10 @@ pub struct AdminState {pub wiki: Wiki,/// Optional LLM provider. When `None`, bootstrap returns 503.pub llm: Option<Arc<dyn LlmProvider>>,+ /// If true, auto-improve leaves staged proposals pending for manual+ /// approval; otherwise it approves them immediately through the normal wiki+ /// write path.+ pub auto_improve_require_approval: bool,/// Optional embedder. When `None`, `/admin/embed` returns 503.pub embedder: Option<Arc<dyn Embedder>>,/// Passive process-scoped health recorder for configured providers.@@ -166,16 +170,6 @@ struct AutoImproveRequest {project: String,/// Completed session to review.session_id: SessionId,- /// Required for the first implementation slice. Live staging/apply is not- /// available until pending proposal storage ships.- #[serde(default)]- dry_run: bool,- /// Stage validated proposals into the pending-review queue.- #[serde(default)]- stage: bool,- /// Optional mode alias (`dry_run` or `stage`).- #[serde(default)]- mode: Option<String>,/// Minimum observations before the LLM review runs.#[serde(default = "default_auto_improve_min_observations")]min_observations: usize,@@ -194,20 +188,42 @@ struct AutoImproveRequest {/// Whether future raw fallback details may be considered.#[serde(default)]include_raw_fallback: bool,- /// Synthetic actor reserved for future staged proposal provenance.+ /// Synthetic actor used for staged proposal provenance.#[serde(default = "default_auto_improve_proposal_actor")]proposal_actor: String,- /// Pending proposal folder reserved for future staging.+ /// Pending proposal sidecar folder.#[serde(default = "default_auto_improve_pending_path")]pending_path: String,+ /// Removed compatibility field. Requests that still send it fail closed so+ /// old preview callers cannot accidentally write pages.+ #[serde(default)]+ dry_run: Option<bool>,+ /// Removed compatibility field.+ #[serde(default)]+ stage: Option<bool>,+ /// Removed compatibility field.+ #[serde(default)]+ mode: Option<String>,}#[derive(Debug, Serialize)]struct AutoImproveStageResponse {run_id: String,- proposal_ids: Vec<String>,- sidecar_paths: Vec<String>,- report: ai_memory_consolidate::AutoImproveReport,+ approval_required: bool,+ approval_policy: String,+ session_id: String,+ summary: String,+ warnings: Vec<String>,+ rejected_candidates_count: usize,+ proposals: Vec<AutoImproveProposalOutcome>,+}++#[derive(Debug, Serialize)]+struct AutoImproveProposalOutcome {+ id: String,+ sidecar_path: String,+ status: String,+ page_id: Option<String>,}/// JSON request body for `POST /admin/curator`.@@ -1000,39 +1016,25 @@ fn dry_run_outcome(}// ----------------------------------------------------------------------// auto-improve dry-run reviewer+// auto-improve reviewer/stager// ---------------------------------------------------------------------async fn handle_auto_improve(State(state): State<Arc<AdminState>>,+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,+ level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,+ headers: HeaderMap,Json(req): Json<AutoImproveRequest>,) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {- let mode = req.mode.as_deref().map(str::trim).filter(|s| !s.is_empty());- let wants_stage = req.stage || matches!(mode, Some("stage"));- let wants_dry_run = req.dry_run || matches!(mode, Some("dry_run" | "dry-run"));- if wants_stage && wants_dry_run {- return Err((- StatusCode::UNPROCESSABLE_ENTITY,- Json(serde_json::json!({ "error": "choose either dry_run or stage, not both" })),- ));- }- if let Some(other) = mode- && !matches!(other, "stage" | "dry_run" | "dry-run")- {+ if req.dry_run.is_some() || req.stage.is_some() || req.mode.is_some() {return Err((StatusCode::UNPROCESSABLE_ENTITY,- Json(serde_json::json!({ "error": format!("unknown auto-improve mode '{other}'") })),- ));- }- if !wants_dry_run && !wants_stage {- return Err((- StatusCode::UNPROCESSABLE_ENTITY,- Json(- serde_json::json!({ "error": "auto-improve requires dry_run=true or stage=true" }),- ),+ Json(serde_json::json!({+ "error": "auto-improve dry_run/stage/mode request fields were removed; set [auto_improve].require_approval = true for manual review"+ })),));}-let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;let Some(llm) = state.llm.as_ref().cloned() else {return Err((@@ -1057,13 +1059,128 @@ async fn handle_auto_improve(let report = run_auto_improve_review(&state.reader, &*llm, ws, proj, req.session_id, cfg).await.map_err(auto_improve_error_response)?;- if wants_dry_run {- return Ok((- StatusCode::OK,- Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),- ));+ let proposals = auto_improve_new_proposals(&state, ws, proj, &report).await?;+ let staged =+ stage_auto_improve_report(&state, ws, proj, req.session_id, &req, &report, proposals)+ .await?;+ let actor = actor_ext+ .map(|axum::Extension(actor)| actor)+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);+ let author_id = author_ext.map(|axum::Extension(author_id)| author_id);+ let skip_webhooks = skip_webhooks_for_admin_request(level_ext, &headers);+ let outcomes = finalize_auto_improve_proposals(+ &state,+ &staged,+ AutoImproveFinalizeContext {+ workspace_id: ws,+ project_id: proj,+ require_approval: state.auto_improve_require_approval,+ actor,+ author_id,+ admission_ctx: Some(AdmissionContext {+ op: AdmissionOp::WritePage,+ skip_webhooks,+ ..AdmissionContext::default()+ }),+ },+ )+ .await?;+ Ok((+ StatusCode::OK,+ Json(+ serde_json::to_value(AutoImproveStageResponse {+ run_id: staged.run_id.to_string(),+ approval_required: state.auto_improve_require_approval,+ approval_policy: if state.auto_improve_require_approval {+ "manual".into()+ } else {+ "auto_approve".into()+ },+ session_id: req.session_id.to_string(),+ summary: report.summary,+ warnings: report.warnings,+ rejected_candidates_count: report.rejected_candidates.len(),+ proposals: outcomes,+ })+ .unwrap_or_else(|_| serde_json::json!({})),+ ),+ ))+}++fn auto_improve_auto_approve_actor(+ mut actor: ai_memory_core::ActorContext,+) -> ai_memory_core::ActorContext {+ actor.agent = Some("auto_improve_auto_approve".into());+ actor+}++struct AutoImproveFinalizeContext {+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ require_approval: bool,+ actor: ai_memory_core::ActorContext,+ author_id: Option<ai_memory_core::UserId>,+ admission_ctx: Option<AdmissionContext>,+}++async fn finalize_auto_improve_proposals(+ state: &AdminState,+ staged: &StagedAutoImproveData,+ ctx: AutoImproveFinalizeContext,+) -> Result<Vec<AutoImproveProposalOutcome>, (StatusCode, Json<serde_json::Value>)> {+ let mut outcomes = Vec::with_capacity(staged.proposal_ids.len());+ for (proposal_id, sidecar_path) in staged.proposal_ids.iter().zip(staged.sidecar_paths.iter()) {+ if ctx.require_approval {+ outcomes.push(AutoImproveProposalOutcome {+ id: proposal_id.to_string(),+ sidecar_path: sidecar_path.clone(),+ status: "pending".into(),+ page_id: None,+ });+ continue;+ }++ let approval_actor = auto_improve_auto_approve_actor(ctx.actor.clone());+ match state+ .wiki+ .approve_auto_improve_proposal(+ ctx.workspace_id,+ ctx.project_id,+ *proposal_id,+ approval_actor,+ ctx.author_id,+ ctx.admission_ctx.clone(),+ )+ .await+ {+ Ok(ApproveAutoImproveProposalResult::Approved { page_id }) => {+ outcomes.push(AutoImproveProposalOutcome {+ id: proposal_id.to_string(),+ sidecar_path: sidecar_path.clone(),+ status: "approved".into(),+ page_id: Some(page_id.to_string()),+ });+ }+ Ok(ApproveAutoImproveProposalResult::Conflict) => {+ outcomes.push(AutoImproveProposalOutcome {+ id: proposal_id.to_string(),+ sidecar_path: sidecar_path.clone(),+ status: "conflict".into(),+ page_id: None,+ });+ }+ Err(e) => return Err(internal_err(e.to_string())),+ }}+ Ok(outcomes)+}+async fn auto_improve_new_proposals(+ state: &AdminState,+ ws: WorkspaceId,+ proj: ProjectId,+ report: &ai_memory_consolidate::AutoImproveReport,+) -> Result<Vec<NewAutoImproveProposal>, (StatusCode, Json<serde_json::Value>)> {let mut proposals = Vec::with_capacity(report.proposals.len());for p in &report.proposals {let path = PagePath::new(p.path.clone()).map_err(|e| {@@ -1096,12 +1213,30 @@ async fn handle_auto_improve(artifact_sha256: None,});}+ Ok(proposals)+}++struct StagedAutoImproveData {+ run_id: ai_memory_core::AutoImproveRunId,+ proposal_ids: Vec<AutoImproveProposalId>,+ sidecar_paths: Vec<String>,+}++async fn stage_auto_improve_report(+ state: &AdminState,+ ws: WorkspaceId,+ proj: ProjectId,+ session_id: SessionId,+ req: &AutoImproveRequest,+ report: &ai_memory_consolidate::AutoImproveReport,+ proposals: Vec<NewAutoImproveProposal>,+) -> Result<StagedAutoImproveData, (StatusCode, Json<serde_json::Value>)> {let staged = state.writer.stage_auto_improve_run(StageAutoImproveRun {workspace_id: ws,project_id: proj,- session_id: Some(req.session_id),+ session_id: Some(session_id),provider: Some(report.provider.clone()),model: Some(report.model.clone()),summary: Some(report.summary.clone()),@@ -1134,22 +1269,11 @@ async fn handle_auto_improve(.map_err(|e| internal_err(e.to_string()))?;sidecar_paths.push(path.display().to_string());}- Ok((- StatusCode::OK,- Json(- serde_json::to_value(AutoImproveStageResponse {- run_id: staged.run_id.to_string(),- proposal_ids: staged- .proposal_ids- .iter()- .map(ToString::to_string)- .collect(),- sidecar_paths,- report,- })- .unwrap_or_else(|_| serde_json::json!({})),- ),- ))+ Ok(StagedAutoImproveData {+ run_id: staged.run_id,+ proposal_ids: staged.proposal_ids,+ sidecar_paths,+ })}fn auto_improve_error_response(@@ -4067,6 +4191,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -4107,6 +4232,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -4136,6 +4262,7 @@ mod tests {reader: store.reader.clone(),wiki,llm,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -4273,8 +4400,21 @@ mod tests {}#[tokio::test]- async fn auto_improve_rejects_missing_mode() {- let (_tmp, router) = read_page_test_router();+ async fn auto_improve_requires_llm_provider() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "audit", None)+ .await+ .unwrap();+ let router = admin_router(admin_state_for_store(&tmp, &store, wiki));let resp = router.oneshot(@@ -4286,8 +4426,7 @@ mod tests {serde_json::to_vec(&serde_json::json!({"workspace": "default","project": "audit",- "session_id": "00000000-0000-0000-0000-000000000000",- "dry_run": false+ "session_id": "00000000-0000-0000-0000-000000000000"})).unwrap(),))@@ -4296,14 +4435,14 @@ mod tests {.await.unwrap();- assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();let json: serde_json::Value = serde_json::from_slice(&body).unwrap();assert!(json["error"].as_str().unwrap_or_default()- .contains("dry_run=true or stage=true")+ .contains("LLM provider not configured"));}@@ -4321,8 +4460,7 @@ mod tests {serde_json::to_vec(&serde_json::json!({"workspace": "missing","project": "missing",- "session_id": "00000000-0000-0000-0000-000000000000",- "dry_run": true+ "session_id": "00000000-0000-0000-0000-000000000000"})).unwrap(),))@@ -4335,7 +4473,7 @@ mod tests {}#[tokio::test]- async fn auto_improve_stage_stages_rows_sidecars_and_concrete_operations() {+ async fn auto_improve_auto_approves_by_default_and_uses_concrete_operations() {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let wiki = Wiki::new(tmp.path(), store.writer.clone())@@ -4413,7 +4551,6 @@ mod tests {"workspace": "default","project": "scratch","session_id": session_id.to_string(),- "stage": true,"min_observations": 1,"min_session_duration_secs": 0,"min_confidence": 0.75,@@ -4429,12 +4566,14 @@ mod tests {assert_eq!(resp.status(), StatusCode::OK);let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();let json: serde_json::Value = serde_json::from_slice(&body).unwrap();- let proposal_ids = json["proposal_ids"].as_array().unwrap();- assert_eq!(proposal_ids.len(), 2);- let sidecar_paths = json["sidecar_paths"].as_array().unwrap();- assert_eq!(sidecar_paths.len(), 2);- for path in sidecar_paths {- let path = path.as_str().unwrap();+ assert_eq!(json["approval_required"], false);+ assert_eq!(json["approval_policy"], "auto_approve");+ let proposals = json["proposals"].as_array().unwrap();+ assert_eq!(proposals.len(), 2);+ for proposal in proposals {+ assert_eq!(proposal["status"], "approved");+ assert!(proposal["page_id"].as_str().is_some());+ let path = proposal["sidecar_path"].as_str().unwrap();assert!(std::path::Path::new(path).exists(),"sidecar file must be written: {path}"@@ -4443,10 +4582,10 @@ mod tests {let staged = store.reader- .list_auto_improve_proposals(ws, proj, Some(AutoImproveProposalStatus::Pending), 10)+ .list_auto_improve_proposals(ws, proj, Some(AutoImproveProposalStatus::Approved), 10).await.unwrap();- assert_eq!(staged.len(), 2, "DB proposal rows must be staged");+ assert_eq!(staged.len(), 2, "DB proposal rows must be approved");let slot = staged.iter().find(|p| p.target_path.as_str() == "_slots/current-focus.md")@@ -4464,7 +4603,106 @@ mod tests {.await.unwrap().expect("existing target remains present");- assert_eq!(existing.body, "# Current Focus\n\nold focus");+ assert_eq!(existing.body, "# Current Focus\n\nupdated focus proposal");+ let note_page = store+ .reader+ .page_body_by_ids(ws, proj, "notes/new-auto-improve.md")+ .await+ .unwrap()+ .expect("auto-approve writes absent target page");+ assert_eq!(+ note_page.body,+ "# New Auto Improve Lesson\n\nnew page proposal"+ );+ }++ #[tokio::test]+ async fn auto_improve_require_approval_keeps_proposals_pending() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::Other,+ cwd: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "durable lesson".into(),+ importance: 5,+ })+ .await+ .unwrap();+ let mut state =+ admin_state_for_store_with_llm(&tmp, &store, wiki, Some(Arc::new(FakeAutoImproveLlm)));+ state.auto_improve_require_approval = true;+ let router = admin_router(state);++ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/auto-improve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({+ "workspace": "default",+ "project": "scratch",+ "session_id": session_id.to_string(),+ "min_observations": 1,+ "min_session_duration_secs": 0,+ "min_confidence": 0.75,+ "max_proposals_per_run": 5+ }))+ .unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(json["approval_required"], true);+ assert_eq!(json["approval_policy"], "manual");+ let proposals = json["proposals"].as_array().unwrap();+ assert_eq!(proposals.len(), 2);+ assert!(proposals.iter().all(|p| p["status"] == "pending"));++ let pending = store+ .reader+ .list_auto_improve_proposals(ws, proj, Some(AutoImproveProposalStatus::Pending), 10)+ .await+ .unwrap();+ assert_eq!(pending.len(), 2);assert!(store.reader@@ -4472,7 +4710,41 @@ mod tests {.await.unwrap().is_none(),- "stage mode must not write absent target page"+ "manual approval mode must not write target pages"+ );+ }++ #[tokio::test]+ async fn auto_improve_removed_mode_fields_fail_closed() {+ let (_tmp, router) = read_page_test_router();+ let resp = router+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/admin/auto-improve")+ .header("content-type", "application/json")+ .body(Body::from(+ serde_json::to_vec(&serde_json::json!({+ "workspace": "default",+ "project": "scratch",+ "session_id": "00000000-0000-0000-0000-000000000000",+ "dry_run": true+ }))+ .unwrap(),+ ))+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(+ json["error"]+ .as_str()+ .unwrap_or_default()+ .contains("removed"));}@@ -4913,6 +5185,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -5018,6 +5291,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -5116,6 +5390,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -5220,6 +5495,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -5303,6 +5579,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),@@ -5804,6 +6081,7 @@ mod tests {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 5dd4bd51..55b37066 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -12,6 +12,7 @@ use ai_memory_core::{SessionId, Tier, WorkspaceId,};use ai_memory_llm::{Embedder, LlmProvider};+use ai_memory_store::{AutoImproveProposalOperation, NewAutoImproveProposal, StageAutoImproveRun};use ai_memory_store::{DecayParams, PageHit, ReaderPool, ScopeName, ScopeResolver, WriterHandle};use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};use rmcp::handler::server::router::tool::ToolRouter;@@ -92,10 +93,10 @@ the conversation calls for them:\n\session end only when AI_MEMORY_CONSOLIDATE_ON_SESSION_END is set.\n\- `memory_auto_improve` — when the user asks what durable lessons \should be proposed from a completed session, or at explicit wrap-up \- when learning review is useful. Dry-run only for now: it reads the \- latest completed session by default, returns proposed wiki edits with \- evidence, and never writes pages or pending proposals. Do NOT apply \- proposals with memory_write_page unless the user explicitly approves.\n\+ when learning review is useful. It reads the latest completed session \+ by default and applies validated edits through the auto-improvement \+ approval path. Admins can set `[auto_improve] require_approval = true` \+ to leave proposals in pending-writes for manual review.\n\- `memory_write_page` — when the user explicitly asks to remember, \save, or annotate durable project knowledge. This writes a wiki page; \do NOT use `memory_handoff_begin` for permanent annotations. \@@ -194,6 +195,10 @@ pub struct AiMemoryServer {/// `memory_handoff_begin` (handoffs bypass `Wiki::write_page` so/// the wiki-level scrub doesn't cover them).sanitizer: ai_memory_core::Sanitizer,+ /// If true, `memory_auto_improve` stages proposals for manual approval;+ /// otherwise it immediately approves validated proposals through the normal+ /// wiki write path.+ auto_improve_require_approval: bool,// Read by the `#[tool_handler]` macro expansion; rustc's dead-code// analysis can't see that, so the lint must be allowed explicitly.#[allow(dead_code)]@@ -342,10 +347,20 @@ struct AutoImproveArgs {/// session in the resolved current project.#[serde(default)]session_id: Option<String>,- /// Must be true or omitted. The MCP surface is dry-run only until pending- /// proposal storage and approval tools exist.+ /// Removed compatibility field. Hidden from the tool schema; if an old+ /// caller still sends it, fail closed instead of turning an old preview+ /// request into an applying request.#[serde(default)]+ #[schemars(skip)]dry_run: Option<bool>,+ /// Removed compatibility field; hidden from schema and rejected if present.+ #[serde(default)]+ #[schemars(skip)]+ stage: Option<bool>,+ /// Removed compatibility field; hidden from schema and rejected if present.+ #[serde(default)]+ #[schemars(skip)]+ mode: Option<String>,/// Project to review. Omit to target the project you're currently working/// in (resolved from recent hook activity). **Omit unless the user/// explicitly names a different project.**@@ -592,10 +607,18 @@ impl AiMemoryServer {decay_params: DecayParams::default(),embedder: None,sanitizer: ai_memory_core::Sanitizer::builtin(),+ auto_improve_require_approval: false,tool_router: Self::tool_router(),}}+ /// Configure whether auto-improvement requires manual pending-writes approval.+ #[must_use]+ pub fn with_auto_improve_require_approval(mut self, require_approval: bool) -> Self {+ self.auto_improve_require_approval = require_approval;+ self+ }+/// Replace the default built-in-only sanitizer with one carrying/// the operator's `[sanitize]` extras + allowlist.#[must_use]@@ -1138,22 +1161,28 @@ impl AiMemoryServer {}}- /// Dry-run durable wiki edit proposals for a completed session.+ /// Stage durable wiki edit proposals for a completed session.#[tool(- description = "Run a DRY-RUN auto-improvement review for one completed session. Use when the user asks what durable lessons should be proposed, what memory pages this session suggests, or at explicit wrap-up when a learning review is useful. Omit `session_id` to review the latest completed session in the current project. This is read-only: it never writes wiki files, pending proposals, or handoffs. Do NOT apply proposals with memory_write_page unless the user explicitly approves."+ description = "Run auto-improvement for one completed session and apply validated wiki edit proposals through the auto-improvement approval path. Use when the user asks what durable lessons should be captured, what memory pages this session suggests, or at explicit wrap-up when a learning review is useful. Omit `session_id` to review the latest completed session in the current project. Admins can set `[auto_improve] require_approval = true` to leave proposals pending for manual review.")]async fn memory_auto_improve(&self,Parameters(args): Parameters<AutoImproveArgs>,Extension(parts): Extension<axum::http::request::Parts>,) -> Result<CallToolResult, McpError> {- if args.dry_run == Some(false) {+ if args.dry_run.is_some() || args.stage.is_some() || args.mode.is_some() {return Err(McpError::invalid_params(- "memory_auto_improve currently supports dry-run only",+ "auto-improve dry_run/stage/mode arguments were removed; set [auto_improve].require_approval = true for manual review",None,));}let aps_actor = Self::actor_key_from_parts(Some(&parts));+ let request_actor = parts+ .extensions+ .get::<ai_memory_core::ActorContext>()+ .cloned()+ .unwrap_or_else(ai_memory_core::ActorContext::anonymous);+ let author_id = parts.extensions.get::<ai_memory_core::UserId>().copied();let (ws, proj) = self.effective_ids_for_read_args_with_actor(args.workspace.as_deref(),@@ -1167,6 +1196,12 @@ impl AiMemoryServer {None,));};+ let Some(wiki) = self.wiki.as_ref() else {+ return Err(McpError::internal_error(+ "memory_auto_improve requires the server to be built with a wiki handle",+ None,+ ));+ };let session_id = match args.session_id.as_deref() {Some(raw) => SessionId::from_str(raw).map_err(|e| McpError::invalid_params(e.to_string(), None))?,@@ -1203,10 +1238,132 @@ impl AiMemoryServer {pending_path: ai_memory_consolidate::DEFAULT_AUTO_IMPROVE_PENDING_PATH.into(),};- let report = run_auto_improve_review(&self.reader, &**llm, ws, proj, session_id, cfg)+ let report =+ run_auto_improve_review(&self.reader, &**llm, ws, proj, session_id, cfg.clone())+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ let mut proposals = Vec::with_capacity(report.proposals.len());+ for p in &report.proposals {+ let path = PagePath::new(p.path.clone()).map_err(|e| {+ McpError::invalid_params(format!("invalid proposal path: {e}"), None)+ })?;+ let operation = if self+ .reader+ .page_body_by_ids(ws, proj, path.as_str())+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ .is_some()+ {+ AutoImproveProposalOperation::Update+ } else {+ AutoImproveProposalOperation::Create+ };+ proposals.push(NewAutoImproveProposal {+ operation,+ target_path: path,+ kind: p.kind.clone(),+ title: p.title.clone(),+ confidence: f64::from(p.confidence),+ rationale: p.rationale.clone(),+ evidence_json: serde_json::to_value(&p.evidence)+ .map_err(|e| McpError::internal_error(e.to_string(), None))?,+ body_markdown: p.body_markdown.clone(),+ artifact_sha256: None,+ });+ }+ let staged = self+ .writer+ .stage_auto_improve_run(StageAutoImproveRun {+ workspace_id: ws,+ project_id: proj,+ session_id: Some(session_id),+ provider: Some(report.provider.clone()),+ model: Some(report.model.clone()),+ summary: Some(report.summary.clone()),+ warnings_json: serde_json::to_value(&report.warnings)+ .unwrap_or_else(|_| serde_json::json!([])),+ rejected_candidates_json: serde_json::to_value(&report.rejected_candidates)+ .unwrap_or_else(|_| serde_json::json!([])),+ config_json: serde_json::json!({+ "min_observations": cfg.min_observations,+ "min_session_duration_secs": cfg.min_session_duration_secs,+ "min_confidence": cfg.min_confidence,+ "max_input_tokens": cfg.max_input_tokens,+ "max_proposals_per_run": cfg.max_proposals_per_run,+ "include_raw_fallback": cfg.include_raw_fallback,+ }),+ proposal_actor: ai_memory_core::ActorContext {+ agent: Some(cfg.proposal_actor.clone()),+ ..ai_memory_core::ActorContext::default()+ },+ proposals,+ }).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;- ok_json(&report)+ let mut sidecar_paths = Vec::with_capacity(staged.proposal_ids.len());+ for id in &staged.proposal_ids {+ let path = wiki+ .write_auto_improve_sidecar(ws, proj, *id)+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?;+ sidecar_paths.push(path.display().to_string());+ }+ let mut outcomes = Vec::with_capacity(staged.proposal_ids.len());+ for (proposal_id, sidecar_path) in staged.proposal_ids.iter().zip(sidecar_paths.iter()) {+ if self.auto_improve_require_approval {+ outcomes.push(serde_json::json!({+ "id": proposal_id.to_string(),+ "sidecar_path": sidecar_path,+ "status": "pending",+ "page_id": null,+ }));+ continue;+ }+ let mut approval_actor = request_actor.clone();+ approval_actor.agent = Some("auto_improve_auto_approve".into());+ match wiki+ .approve_auto_improve_proposal(+ ws,+ proj,+ *proposal_id,+ approval_actor,+ author_id,+ Some(ai_memory_wiki::AdmissionContext {+ op: ai_memory_wiki::AdmissionOp::WritePage,+ ..ai_memory_wiki::AdmissionContext::default()+ }),+ )+ .await+ .map_err(|e| McpError::internal_error(e.to_string(), None))?+ {+ ai_memory_store::ApproveAutoImproveProposalResult::Approved { page_id } => {+ outcomes.push(serde_json::json!({+ "id": proposal_id.to_string(),+ "sidecar_path": sidecar_path,+ "status": "approved",+ "page_id": page_id.to_string(),+ }));+ }+ ai_memory_store::ApproveAutoImproveProposalResult::Conflict => {+ outcomes.push(serde_json::json!({+ "id": proposal_id.to_string(),+ "sidecar_path": sidecar_path,+ "status": "conflict",+ "page_id": null,+ }));+ }+ }+ }+ ok_json(&serde_json::json!({+ "run_id": staged.run_id.to_string(),+ "approval_required": self.auto_improve_require_approval,+ "approval_policy": if self.auto_improve_require_approval { "manual" } else { "auto_approve" },+ "session_id": session_id.to_string(),+ "summary": report.summary,+ "warnings": report.warnings,+ "rejected_candidates_count": report.rejected_candidates.len(),+ "proposals": outcomes,+ }))}/// Write or update a durable wiki page.@@ -2256,18 +2413,17 @@ mod tests {}#[tokio::test]- async fn prompts_expose_auto_improve_as_dry_run_only() {+ async fn prompts_expose_auto_improve_as_auto_approval_with_manual_opt_in() {for prompt in [MEMORY_INSTRUCTIONS, ai_memory_core::SNIPPET_BODY] {let lower = prompt.to_ascii_lowercase();assert!(prompt.contains("memory_auto_improve"));- assert!(lower.contains("dry-run") || lower.contains("dry run"));assert!(- lower.contains("never writes") || lower.contains("never write"),- "prompt must state auto-improve review is non-mutating"+ lower.contains("applies validated") || lower.contains("approval path"),+ "prompt must state auto-improve applies through the approval path");assert!(- lower.contains("explicitly approves") || lower.contains("explicitly approve"),- "prompt must require explicit approval before applying proposals"+ lower.contains("require_approval") && lower.contains("pending-writes"),+ "prompt must describe the manual review opt-in");}@@ -2281,8 +2437,8 @@ mod tests {.description.as_deref().expect("memory_auto_improve must carry a description");- assert!(desc.contains("DRY-RUN") || desc.contains("dry-run"));- assert!(desc.contains("never writes"));+ assert!(desc.contains("apply validated"));+ assert!(desc.contains("approval"));}#[test]@@ -4162,13 +4318,15 @@ mod tests {}#[tokio::test]- async fn memory_auto_improve_rejects_non_dry_run() {+ async fn memory_auto_improve_removed_dry_run_arg_fails_closed() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;let err = server.memory_auto_improve(Parameters(AutoImproveArgs {- session_id: None,- dry_run: Some(false),+ session_id: Some("00000000-0000-0000-0000-000000000000".into()),+ dry_run: Some(true),+ stage: None,+ mode: None,project: None,workspace: None,min_observations: None,@@ -4181,11 +4339,11 @@ mod tests {rmcp::handler::server::tool::Extension(test_parts_default()),).await- .expect_err("auto-improve MCP tool must be dry-run only");+ .expect_err("removed dry_run argument must fail closed");let msg = format!("{err:?}");assert!(- msg.contains("dry-run"),- "error should mention dry-run: {msg}"+ msg.contains("removed"),+ "error should mention removal: {msg}");}@@ -4196,7 +4354,9 @@ mod tests {.memory_auto_improve(Parameters(AutoImproveArgs {session_id: Some("00000000-0000-0000-0000-000000000000".into()),- dry_run: Some(true),+ dry_run: None,+ stage: None,+ mode: None,project: None,workspace: None,min_observations: None,diff --git a/crates/ai-memory-mcp/tests/admin_backup.rs b/crates/ai-memory-mcp/tests/admin_backup.rsindex 04c80e54..284b1601 100644--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@ -28,6 +28,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_bootstrap.rs b/crates/ai-memory-mcp/tests/admin_bootstrap.rsindex 0b1b05c3..8c092b07 100644--- a/crates/ai-memory-mcp/tests/admin_bootstrap.rs+++ b/crates/ai-memory-mcp/tests/admin_bootstrap.rs@@ -24,7 +24,8 @@ async fn make_admin_state(tmp: &TempDir) -> AdminState {writer: store.writer.clone(),reader: store.reader.clone(),wiki,- llm: None, // no LLM — dry-run path only+ llm: None, // no LLM — bootstrap report path only+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_move.rs b/crates/ai-memory-mcp/tests/admin_move.rsindex 2c8b9752..20457e98 100644--- a/crates/ai-memory-mcp/tests/admin_move.rs+++ b/crates/ai-memory-mcp/tests/admin_move.rs@@ -41,6 +41,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -393,6 +394,7 @@ async fn move_project_carries_source_embedding() {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: Some(embedder),provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -674,6 +676,7 @@ async fn true_move_notifies_admission_with_destination_names() {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -725,6 +728,7 @@ async fn make_state_with_embedder(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: Some(embedder),provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -875,6 +879,7 @@ fn build_state(store: &Store, tmp: &TempDir) -> AdminState {reader: store.reader.clone(),wiki: Wiki::new(tmp.path(), store.writer.clone()).unwrap(),llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -1368,6 +1373,7 @@ async fn true_move_aborts_when_admission_rejects() {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -1460,6 +1466,7 @@ async fn copy_purge_purge_admission_runs_before_db_destruction() {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rsindex 402e22b4..96440026 100644--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@ -36,6 +36,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_purge.rs b/crates/ai-memory-mcp/tests/admin_purge.rsindex b772e793..d90ab052 100644--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@ -34,6 +34,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -338,6 +339,7 @@ async fn purge_project_rejecting_admission_leaves_source_intact() {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -436,6 +438,7 @@ async fn purge_project_idempotent_second_call_is_404() {reader: store.reader.clone(),wiki: state_a.wiki.clone(),llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_read_page.rs b/crates/ai-memory-mcp/tests/admin_read_page.rsindex 6118d1ab..d57f1e3b 100644--- a/crates/ai-memory-mcp/tests/admin_read_page.rs+++ b/crates/ai-memory-mcp/tests/admin_read_page.rs@@ -21,6 +21,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rsindex ed8e67e6..3e89e903 100644--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@ -27,6 +27,7 @@ async fn make_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -312,6 +313,7 @@ async fn rename_project_pages_still_searchable() {reader: store.reader.clone(),wiki: state.wiki.clone(),llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),@@ -381,6 +383,7 @@ async fn rename_project_after_purge_returns_404_not_silent_200() {reader: state.reader.clone(),wiki: state.wiki.clone(),llm: state.llm.clone(),+ auto_improve_require_approval: false,embedder: state.embedder.clone(),provider_health: state.provider_health.clone(),decay_params: state.decay_params,diff --git a/crates/ai-memory-mcp/tests/admin_status_search.rs b/crates/ai-memory-mcp/tests/admin_status_search.rsindex 8e443340..9007e679 100644--- a/crates/ai-memory-mcp/tests/admin_status_search.rs+++ b/crates/ai-memory-mcp/tests/admin_status_search.rs@@ -22,6 +22,7 @@ async fn make_admin_state(tmp: &TempDir) -> (AdminState, Store) {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/crates/ai-memory-mcp/tests/admin_write_page.rs b/crates/ai-memory-mcp/tests/admin_write_page.rsindex eb3591c3..1b976660 100644--- a/crates/ai-memory-mcp/tests/admin_write_page.rs+++ b/crates/ai-memory-mcp/tests/admin_write_page.rs@@ -22,6 +22,7 @@ async fn make_state(tmp: &TempDir) -> AdminState {reader: store.reader.clone(),wiki,llm: None,+ auto_improve_require_approval: false,embedder: None,provider_health: ai_memory_llm::ProviderHealth::default(),decay_params: DecayParams::default(),diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d88bdb6d..c2419d17 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -29,9 +29,10 @@ background reconciliation or provider-backed maintenance. The core invariant isunchanged: the markdown wiki is the source of truth, and SQLite is the derivedindex for search, sessions, observations, handoffs, audit, and embeddings.Auto-improvement sits on the provider-backed maintenance side: it reviews a-completed session and returns validated proposals. CLI/admin dry-run writes-nothing; CLI/admin stage mode stores pending proposal rows plus non-indexed-sidecars for later approval. MCP remains dry-run-only.+completed session, records validated proposals in the pending-writes audit trail,+and auto-approves them through the normal wiki write path by default. Admins can+set `[auto_improve] require_approval = true` to leave proposals pending for+manual review.**Steady-state loop:**@@ -55,13 +56,13 @@ sidecars for later approval. MCP remains dry-run-only.4. When `AI_MEMORY_LLM_PROVIDER` is set, `memory_consolidate` rewritesthat summary into a richer durable page or fans out into amulti-page batch under `concepts/`, `decisions/`, `gotchas/`.-5. On explicit CLI/admin request, `auto-improve --dry-run` previews one- completed session with the configured LLM, while `auto-improve --stage`- stores validated `concepts/`, `decisions/`, `gotchas/`, `procedures/`, and- `_rules/` proposals in the pending-writes queue. The MCP- `memory_auto_improve` tool remains dry-run-only. Auto-improvement does not- run on SessionEnd by default and staged proposals do not become durable wiki- pages until an explicit pending-writes approval.+5. On explicit CLI/admin/MCP request, auto-improvement reviews one completed+ session with the configured LLM, records validated `concepts/`, `decisions/`,+ `gotchas/`, `procedures/`, and `_rules/` proposals in the pending-writes+ audit trail, then approves them through the wiki mutation path by default.+ Auto-improvement does not run on SessionEnd by default. With+ `[auto_improve] require_approval = true`, proposals remain pending until an+ explicit pending-writes approval.6. `memory_query` answers via FTS5 + link-neighbour RRF; when anembedder is configured, vector cosine over `page_embeddings` joinsthe same RRF. If compiled wiki pages miss entirely, bounded raw@@ -213,7 +214,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. |-| `memory_auto_improve` | read-only | Dry-run durable wiki edit proposals for a completed session. Defaults to the latest completed session in the resolved current project and never writes pages or pending proposals. |+| `memory_auto_improve` | write | Review a completed session and apply validated wiki edits through the auto-improvement approval path. Defaults to the latest completed session in the resolved current project; `[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 something permanent. || `memory_delete_page` | destructive | Delete a single page by exact `path`. Fires the admission chain (op=delete); idempotent. || `memory_forget_sweep` | destructive | M8 retention pass. `dry_run=true` for preview. |@@ -232,7 +233,7 @@ must re-write its own routing rules into a project's `CLAUDE.md` /`AGENTS.md`, `memory_read_page` complements `memory_query` for the"I need the full page, not a snippet" case (e.g. opening a decision pageend-to-end), `memory_auto_improve` exposes a safe default-on learning review-without mutation, and `memory_delete_page` is the exact-path destructive pair+through the same approval/write path as pending writes, and `memory_delete_page` is the exact-path destructive pairneeded by admission-aware mirrors. `memory_handoff_cancel` is the safety valvefor 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.@@ -319,10 +320,8 @@ mu = 0.04 # ↑ if recent hits should count morecold_threshold = 0.20 # below this → soft-deletehard_delete_after_days = 180-[auto_improve] # default-available, review-gated proposals-enabled = true-mode = "dry_run" # CLI/admin stage is explicit; no auto-apply-on_session_end = false # hooks never gain LLM latency on upgrade+[auto_improve] # default-available learning reviewer+require_approval = false # true leaves proposals pending for reviewmin_observations = 8min_session_duration_secs = 120min_confidence = 0.75diff --git a/docs/architecture-overview.svg b/docs/architecture-overview.svgindex d449ad60..39b6031d 100644--- a/docs/architecture-overview.svg+++ b/docs/architecture-overview.svg@@ -61,7 +61,7 @@<rect class="external" x="1050" y="130" width="290" height="118" /><text class="box-title" x="1075" y="164">Optional providers</text><text class="box-text" x="1075" y="190">LLM consolidation and lint</text>- <text class="box-text" x="1075" y="211">dry-run auto-improvement</text>+ <text class="box-text" x="1075" y="211">auto-improvement review/approval</text><text class="box-text" x="1075" y="232">embedding vector backfill</text><rect class="server" x="60" y="300" width="1280" height="390" />diff --git a/docs/auto-improvement-loop.md b/docs/auto-improvement-loop.mdindex cdbfb0ca..506c2371 100644--- a/docs/auto-improvement-loop.md+++ b/docs/auto-improvement-loop.md@@ -1,26 +1,27 @@# Optional Auto-Improvement Loop Research-> Status: research plus phased implementation notes. The dry-run reviewer is-> implemented for CLI/admin/MCP use and is safe to expose by default because it-> does not mutate wiki files or pending proposals. Pending proposal storage,-> approval, session-end triggers, and auto-apply remain proposed future work.+> Status: research plus implemented production notes. CLI/admin/MCP+> auto-improvement records validated proposals in the pending-writes audit trail+> and auto-approves them through the normal wiki write path by default. Admins+> can set `[auto_improve] require_approval = true` for manual review.+> Session-end triggers remain future work.## Executive SummaryAn ai-memory equivalent of Hermes Agent's self-improvement loop is worth-building as a default-available dry-run review path, with staged review required-before any write behavior. The current wiki already-captures useful durable knowledge: decisions, gotchas, concepts, rules, notes,-and session summaries. The missing piece is not more capture. It is a careful-post-session reviewer that can identify durable lessons and propose small wiki-patches without mutating the active agent context or silently promoting weak-session residue into rules.+shipping as a default-available, review-gated staging path. The current wiki+already captures useful durable knowledge: decisions, gotchas, concepts, rules,+notes, and session summaries. The missing piece is not more capture. It is a+careful reviewer that can identify durable lessons and apply small wiki patches+through the existing review/audit path without mutating the active agent context+or silently promoting weak session residue into rules.The safe product shape is:1. Keep automatic observation capture and session consolidation as they are.2. Add an optional background review pass that creates pending wiki edits.-3. Require approval by default before applying those edits.+3. Record proposals and apply them through the approval/audit path by default,+ with manual approval available as an admin opt-in.4. Keep a separate slow maintenance pass for deduplication, stale-page review,and lifecycle cleanup.@@ -95,7 +96,7 @@ docs:First-run behavior is deliberately conservative. A fresh install seeds`last_run_at` and defers the first real pass by a full interval. Users can run a-manual dry-run first.+manual report first.Important curator properties:@@ -106,7 +107,7 @@ Important curator properties:| Pinned objects | Pinned skills bypass automatic transitions. | Pinned pages and invariant slots must be protected. || Reports | Writes machine-readable `run.json` and human `REPORT.md`. | Every maintenance run should leave an audit artifact. || Backups | Takes snapshots before mutating runs and supports rollback. | Wiki git commits help, but approval reports should still be explicit. |-| Dry run | Produces report-only preview. | Dry-run should be first-class. |+| Report mode | Produces report-only output. | Non-destructive reports should be first-class for maintenance. || Consolidation | Merges narrow skills into umbrellas with structured summary. | ai-memory should consolidate duplicate/narrow pages separately from fresh lesson capture. |## Live ai-memory Wiki Findings@@ -155,15 +156,15 @@ new memory substrate.## Recommendation-Build auto-improvement as a default-available review path, but keep the default-mode read-only. Do not let it write directly to the wiki without review at-first.+Build auto-improvement as a default-available review path that records proposal+provenance before writing target wiki pages. Manual CLI/admin/MCP runs apply+validated proposals through the same approval path used by pending-writes;+manual approval remains an admin opt-in.-The initial feature should be a stage-only learning reviewer:+The shipped feature is an audit-first learning reviewer:-1. Dry-run review is enabled by default when an LLM provider is configured;- CLI/admin/MCP dry-runs still require that provider and can be invoked without- enabling any session-end trigger.+1. CLI/admin/MCP auto-improvement is enabled when an LLM provider is configured.+ Manual runs do not enable any session-end trigger.2. Reads a completed session, recent pages, and relevant existing wiki pages.3. Produces a structured proposal containing small page creates or updates.4. Stores the proposal in a pending-review queue with evidence and diffs.@@ -171,7 +172,8 @@ The initial feature should be a stage-only learning reviewer:auth capabilities, audit logging, and the single writer actor.Auto-apply can be considered later for narrow, high-confidence updates, but the-first version should earn trust through dry-runs and pending approvals.+current version earns trust by recording staged proposals and applying them+through the same approval path, while allowing admins to require manual review.## Proposed Page Targets@@ -208,8 +210,8 @@ The review prompt should explicitly reject these as durable learning:Any implementation should preserve these invariants:-1. Off by default.-2. Stage by default.+1. Manual CLI/admin/MCP runs record proposals and auto-approve by default.+2. Automatic SessionEnd triggering is off by default.3. Never mutate the active session prompt or already-prepended handoff context.4. Never run inside hook latency. Hooks remain fire-and-forget and bounded.5. Never bypass workspace/project isolation. Use `ScopeResolver` or its explicit@@ -234,20 +236,19 @@ Any implementation should preserve these invariants:Default-available auto-improvement must not surprise existing installs:-1. Dry-run review may be exposed by default, but it must not write wiki files,- pending proposals, handoffs, or audit rows. Staging must remain an explicit- operator action.-2. Session-end triggering stays off until a bounded background scheduler and- proposal storage exist; hooks must not gain LLM latency as a side effect of- upgrade.+1. Existing project wiki folders need no migration. Older configs may still+ contain an `[auto_improve] mode = ...` key; current ai-memory ignores that+ legacy key. Operators can remove the line when convenient.+2. Session-end triggering stays off until a bounded background scheduler exists;+ hooks must not gain LLM latency as a side effect of upgrade.3. Pending proposal storage must use additive, idempotent migrations thatpreserve all existing wiki files and session/observation rows.4. Existing installed `CLAUDE.md`/`AGENTS.md` blocks remain valid. Operators pickup newer proactive retrieval guidance by running `ai-memory install-instructions`or asking an agent to refresh the ai-memory routing block. The marker-basedreplacement must remain idempotent.-5. Staged/apply modes must default to reviewable staging before any mutation- and must keep approval attribution separate from the autonomous+5. Target-page mutations must pass through proposal staging first and must keep+ approval attribution separate from the autonomous`auto_improve` proposal actor.## Configuration Sketch@@ -256,30 +257,26 @@ The exact names can change, but the shape should be explicit and conservative:```toml[auto_improve]-enabled = true-mode = "dry_run" # dry_run | stage | auto_apply, auto_apply future only-on_session_end = false # opt in separately from manual runs+require_approval = false # true leaves proposals pending for manual reviewmin_observations = 8min_session_duration_secs = 120-min_confidence = 0.75 # tune from dry-runs before any auto_apply mode+min_confidence = 0.75 # tune before any future unattended trigger designmax_input_tokens = 24000max_proposals_per_run = 5include_raw_fallback = falseproposal_actor = "auto_improve"pending_path = "_pending/auto-improve"--[auto_improve.maintenance]-enabled = false-interval_hours = 168-min_idle_hours = 2-dry_run_first = true```-`mode = "auto_apply"` should not ship until staged proposals have enough real-usage to calibrate prompt quality and false-positive rates. The confidence-threshold should remain configurable because real projects vary; initial values-should be chosen from dry-runs against existing deployed wikis, not from prompt-intuition alone.+Future scheduled maintenance settings should live in a separate config section+once that scheduler exists; do not copy unsupported `auto_improve.maintenance`+keys into current configs.++A future unattended session-end loop must not ship until manually-triggered+auto-improvement has enough real usage to calibrate prompt quality and+false-positive rates. The confidence threshold should remain configurable+because real projects vary; initial values should be chosen from applied+proposals against existing deployed wikis, not from prompt intuition alone.## Proposal Format@@ -317,18 +314,16 @@ or confidence below the configured threshold.## Pending Review UX-The first production UX is explicit and review-gated. The CLI/admin dry-run-path previews proposals, `--stage` stores validated pending proposals, and-`pending-writes` applies or rejects them later. The MCP tool remains dry-run-only so agents can ask for a learning review without gaining an approval/apply-surface.+The first production UX is explicit and audit-gated. CLI/admin/MCP+auto-improvement records validated pending proposals, then auto-approves them by+default through the wiki mutation path. With `require_approval = true`,+`pending-writes` applies or rejects them later.| Command or route | Purpose ||---|---|-| `ai-memory auto-improve --dry-run` | Preview proposals for a project/session. |-| `memory_auto_improve` | MCP dry-run preview for the latest completed session or a named session. |-| `ai-memory auto-improve --stage` | Store pending proposals without applying. |-| `ai-memory curator` | Rule-based, report-only maintenance review. Defaults to dry-run. |+| `ai-memory auto-improve --session-id <id>` | Review one session and apply validated proposals through the auto-improvement approval path. |+| `memory_auto_improve` | Review the latest completed session or a named session and apply validated proposals through the same path. |+| `ai-memory curator` | Rule-based, report-only maintenance review. || `ai-memory curator --stage` | Stage exactly one curator report page for pending-writes approval. || `ai-memory pending-writes list` | Show staged wiki changes. || `ai-memory pending-writes diff <id>` | Show markdown diff. |@@ -347,6 +342,15 @@ Existing installed `CLAUDE.md`/`AGENTS.md` snippets update idempotently when theoperator runs `ai-memory install-instructions` or asks an agent to refresh theai-memory routing block.+### Upgrade note for existing installs++Existing project wiki folders need no migration. Pending proposal storage is a+server-side database migration and sidecar directory.++Older server configs may contain a now-ignored `[auto_improve] mode = ...` key.+No data migration is required; remove the legacy line when convenient to avoid+confusion.+## Maintenance Loop ShapeKeep the curator analogue separate from the post-session learning reviewer.@@ -370,13 +374,12 @@ pages.### Phase 1: Dry-Run Reviewer-Status: implemented for explicit CLI/admin/MCP dry-runs; CLI/admin can also-stage validated proposals for pending-writes review.+Status: implemented for CLI/admin/MCP proposal staging plus default auto-approval.Add a library-level reviewer that consumes one completed session plus existing-wiki context and returns validated proposals. Dry-run writes nothing. Stage mode-requires an explicit `--session-id`, stores pending proposal rows plus sidecars,-and still does not write durable wiki target pages until pending-writes approval.+wiki context and returns validated proposals. The runtime stores pending+proposal rows plus sidecars first, then approves them through the wiki mutation+path unless `require_approval = true` is configured.The implemented reviewer is designed for existing projects with large histories:it treats the consolidated `sessions/<id>.md` page as the primary source when it@@ -397,10 +400,12 @@ Tests:### Phase 2: Pending Wiki Writes-Add durable pending proposal storage under `_pending/auto-improve/`,-list/diff/approve/reject commands, and audit rows. Approval applies through-`Wiki::apply_batch` and existing admission hooks with the `auto_improve` actor-preserved in proposal provenance.+Status: implemented for CLI/admin staging, list/show/diff, approve, and reject.++Durable pending proposal storage lives under `_pending/auto-improve/` as+non-indexed sidecars plus SQLite rows, with list/diff/approve/reject commands+and audit rows. Approval applies through the existing wiki mutation boundaries+with the `auto_improve` actor preserved in proposal provenance.Tests:@@ -433,7 +438,7 @@ retention scoring, links, and page metadata to propose merges/supersessions.Tests:-1. First run defers or dry-runs before mutating behavior is possible.+1. First run defers or reports before mutating behavior is possible.2. Pinned pages and invariant slots are skipped.3. Semantic pages are never hard-deleted.4. Proposed merges identify source and destination pages with evidence.@@ -447,11 +452,11 @@ Tests:3. Autonomous proposals should be attributed to a distinct `auto_improve` actor,with approval attribution tracked separately.4. The minimum confidence threshold should be configurable and calibrated with- dry-runs on real projects before any future auto-apply mode is considered.+ applied proposals on real projects before any future unattended trigger is considered.## Remaining Open Question-Should approval be CLI/admin-only at first, or exposed to agents through MCP?+Should unattended SessionEnd auto-improvement ever be enabled by default?## Current Conclusion@@ -460,7 +465,7 @@ part is not that the agent can write memory by itself. The useful part is abounded, observable, reviewable loop that turns repeated work into durableknowledge while keeping active task execution isolated.-For ai-memory, the next correct step after the dry-run reviewer is pending-proposal storage under `_pending/auto-improve/` plus approval/rejection commands.-Direct autonomous wiki mutation should remain out of scope until staged proposals-prove high signal in real deployments.+For ai-memory, the current correct boundary is pending proposal storage under+`_pending/auto-improve/` plus approval/rejection commands. Unattended+SessionEnd mutation should remain out of scope until manually-triggered applied+proposals prove high signal in real deployments.diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex f1f85bc8..cf9ad552 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -138,12 +138,13 @@ Three scheduled MCP operations:Decay/forget runs as a separate `memory_forget_sweep` job: applies the retention formula; soft-deletes via `is_latest=false` + `superseded_at`; hard-deletes only after 180 days *and* zero accesses. Never silently destroys anything user-pinned.Auto-improvement work stays separate from normal session consolidation. The-dry-run reviewer notes and proposed staged design are in+reviewer notes and staged design are in[`docs/auto-improvement-loop.md`](auto-improvement-loop.md). The short version:-learning review is default-available when an LLM provider is configured, but the-default mode is read-only and reviewable; staged/apply behavior must remain-explicit, scoped through the shared resolver/auth paths, and must not mutate the-active agent context mid-turn.+learning review is default-available when an LLM provider is configured, and+manual CLI/admin/MCP runs apply validated proposals through the auto-improvement+approval path by default. Admins can opt into manual review with+`[auto_improve] require_approval = true`. All writes remain scoped through the+shared resolver/auth paths and must not mutate the active agent context mid-turn.## 9. Cross-agent handoff@@ -183,7 +184,7 @@ basic-memory has ~25 tools, agentmemory has 53. Both have user confusion as a re| `memory_handoff_accept` | Fetch + ack the latest open handoff | destructive || `memory_handoff_cancel` | Mark an exact mistakenly-created open handoff expired | destructive || `memory_consolidate` | LLM-driven page rewrite (`multi_page=true` for atomic fan-out) | destructive |-| `memory_auto_improve` | Dry-run learning review that proposes durable wiki edits with evidence; no writes | read-only |+| `memory_auto_improve` | Learning review that applies validated wiki edits through the auto-improvement approval path; manual-review opt-in keeps proposals pending | write || `memory_write_page` | Write durable wiki knowledge on explicit user request | destructive || `memory_read_page` | Read a full page body by exact path or top search hit | read-only || `memory_delete_page` | Delete a single exact-path page with admission hooks | destructive |diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex a5937d7c..dc4008bd 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -36,7 +36,7 @@ endpoint. The trade-off:| | What you get | What you don't get ||---|---|---|-| **MCP only** | LLM can query the wiki, accept handoffs, run memory_consolidate, and dry-run `memory_auto_improve` learning reviews | No automatic session-end summaries; no auto-handoff at session boundaries |+| **MCP only** | LLM can query the wiki, accept handoffs, run memory_consolidate, and run `memory_auto_improve` learning reviews | No automatic session-end summaries; no auto-handoff at session boundaries || **MCP + hooks** | All of the above *plus* every prompt/tool-call captured automatically; handoffs surface at SessionStart with no human prompting | - |For MCP-only use, you can still cover the session-boundary gap by askingdiff --git a/docs/usage.md b/docs/usage.mdindex 7f37bd1e..0b9a3ec1 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -54,7 +54,7 @@ the wiki without you naming tools explicitly.| "Save context for the next session" | `memory_handoff_begin` | Writes a terse session-end handoff with open questions and next steps. Do not use for status or briefing requests. || "Discard that handoff" / "I created a handoff by mistake" | `memory_handoff_cancel` | Marks an exact open handoff id expired before the next session can consume it. || "Consolidate this session" | `memory_consolidate` | Manually runs LLM consolidation. Also runs on PreCompact, and at session end only when `AI_MEMORY_CONSOLIDATE_ON_SESSION_END` is set (off by default; session end otherwise writes a rule-based summary page). |-| "What did we learn from this session?" / "what memory should we add?" | `memory_auto_improve` | Dry-run learning review. Reviews the latest completed session by default, returns proposed wiki edits with evidence, and writes nothing. |+| "What did we learn from this session?" / "what memory should we add?" | `memory_auto_improve` | Reviews the latest completed session by default and applies validated edits through the auto-improvement approval path. Admins can set `[auto_improve] require_approval = true` to leave proposals in pending-writes for manual review. || "Remember this permanently" / "add an annotation" | `memory_write_page` | Writes durable wiki knowledge; not a single-use handoff. || "Delete this page" / "remove the note about X" | `memory_delete_page` | Removes a page by exact path. Pass `workspace` + `project` together when the page lives in a sibling workspace, so a project name shared between workspaces never silently routes the delete to the wrong slot. || "Audit the wiki" / "any contradictions?" | `memory_lint` | Runs stale-page, contradiction, and rule-suggestion checks. |