Skip to content

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

Rust

refactor: post-audit health sweep — dedupe, CI gate, docs, log cap

AkitaOnRails44b3ad26f60f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8799f8ce..f025049a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -47,6 +47,26 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo test --workspace --all-targets
+ # The companion importer is deliberately outside the root workspace
+ # (its own [workspace] in companions/ai-memory-importer/Cargo.toml), so
+ # none of the jobs above compile it. Gate it here with the same
+ # fmt/clippy/test trio docs/companion-crates.md prescribes, or a
+ # toolchain bump / convention change rots it silently.
+ companions:
+ name: companions (ai-memory-importer)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: rustfmt, clippy
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: companions/ai-memory-importer
+ - run: cargo fmt --check --manifest-path companions/ai-memory-importer/Cargo.toml
+ - run: cargo clippy --manifest-path companions/ai-memory-importer/Cargo.toml --all-targets -- -D warnings
+ - run: cargo test --manifest-path companions/ai-memory-importer/Cargo.toml
+
# Build the release binary on its own so a release-only failure
# (LTO crash, codegen issue, dead-code-with-debug-assertions) doesn't
# ship to Docker Hub silently.
diff --git a/AGENTS.md b/AGENTS.md
index 8dadbde9..812fb12c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -178,20 +178,15 @@ durable retrieval follows the Karpathy-style LLM Wiki pattern.
document it in docs/design notes rather than shipping unreachable stubs.
- Document constraints and incidents, not line-by-line mechanics.
- Add focused regression tests for bug fixes and behavior changes.
-- MCP tool surface changes must update `MEMORY_INSTRUCTIONS`,
- `ai_memory_core::SNIPPET_BODY`, README/docs tool references, and regression
- tests that assert every tool appears in both prompt surfaces.
-- Any change affecting user-visible behavior, installation, supported agents,
- providers, deployment, env/config, or public tool/admin surfaces must update
- `CHANGELOG.md` and relevant docs in the same change.
## Project Maintenance Rules
- Keep `CLAUDE.md` as a pointer to `AGENTS.md`; this avoids split-brain
instructions between Claude Code and AGENTS-aware harnesses.
-- When a change affects user-visible behavior, installation, supported
- platforms, supported agents, providers, or deployment, update
- `CHANGELOG.md` and the README/docs support references in the same commit.
+- Any change affecting user-visible behavior, installation, supported
+ platforms, supported agents, providers, deployment, env/config, or public
+ tool/admin surfaces must update `CHANGELOG.md` and the relevant README/docs
+ references in the same commit.
- Do not bump crate/package versions, minor versions, or cut release tags
automatically. Ask the user before any version bump or release tag; prefer no
version change unless the user explicitly approves it.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e395928..74a7d05d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+- The detached drainer's `logs/hook-drain.log` now rotates once it exceeds
+ 1 MiB (previous contents move to `hook-drain.log.old`), so an agent
+ pointed at a chronically unreachable server can no longer grow the log
+ without bound.
+
+### Changed
+- Post-audit cleanup, no behavior change: the `AI_MEMORY_HOOK_PLATFORM`
+ override is parsed in one place instead of three copies, the CLI
+ `AgentChoice` → domain `AgentKind` mapping is a single `kind()` method
+ instead of three per-command match blocks, the companion importer crate
+ is now gated in CI (fmt/clippy/test), and
+ `crates/ai-memory-store/src/auto_improve.rs` is fully documented (its
+ file-wide `missing_docs` allowance is gone). `AI_MEMORY_HOOKS_HOST_ROOT`
+ is now documented in `docs/install.md`.
+
## [1.7.1] - 2026-07-02
### Fixed
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 10e0babd..724bde6f 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -820,6 +820,42 @@ pub enum AgentChoice {
Grok,
}
+impl AgentChoice {
+ /// The core [`AgentKind`] this CLI choice selects — the single mapping
+ /// point between the clap surface and the domain enum. Wire strings,
+ /// hook-bundle directory names, and session attribution all derive from
+ /// the returned kind's `as_str()`; adding an agent means extending this
+ /// match once instead of hunting per-command copies.
+ #[must_use]
+ pub const fn kind(self) -> ai_memory_core::AgentKind {
+ use ai_memory_core::AgentKind;
+ match self {
+ Self::ClaudeCode => AgentKind::ClaudeCode,
+ Self::Codex => AgentKind::Codex,
+ Self::Cursor => AgentKind::Cursor,
+ Self::GeminiCli => AgentKind::GeminiCli,
+ Self::OpenCode => AgentKind::OpenCode,
+ Self::Pi => AgentKind::Pi,
+ Self::Omp => AgentKind::Omp,
+ Self::Openclaw => AgentKind::OpenClaw,
+ Self::AntigravityCli => AgentKind::AntigravityCli,
+ Self::Grok => AgentKind::Grok,
+ }
+ }
+
+ /// `hooks/<subdir>` bundle name for agents that install script hooks.
+ /// `None` for agents wired through a generated integration (plugin /
+ /// extension) instead of a script directory. The subdir equals the
+ /// kind's wire string for every script agent.
+ #[must_use]
+ pub const fn script_hook_subdir(self) -> Option<&'static str> {
+ match self {
+ Self::OpenCode | Self::Pi | Self::Omp | Self::Openclaw => None,
+ _ => Some(self.kind().as_str()),
+ }
+ }
+}
+
/// Arguments for `finalize-session`.
#[derive(Debug, Args)]
pub struct FinalizeSessionArgs {
diff --git a/crates/ai-memory-cli/src/commands/finalize_session.rs b/crates/ai-memory-cli/src/commands/finalize_session.rs
index 36ca67c7..8ce9f675 100644
--- a/crates/ai-memory-cli/src/commands/finalize_session.rs
+++ b/crates/ai-memory-cli/src/commands/finalize_session.rs
@@ -5,7 +5,7 @@ use ai_memory_store::{DB_FILENAME, OpenSession, ReaderPool};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
-use crate::cli::{AgentChoice, FinalizeSessionArgs};
+use crate::cli::FinalizeSessionArgs;
use crate::config::Config;
use crate::http_client::ServerEndpoint;
@@ -40,7 +40,7 @@ struct FinalizeSessionReport {
/// Returns an error if the local store cannot be read or the configured server
/// rejects a synthetic `session-end` hook.
pub async fn run(config: &Config, args: FinalizeSessionArgs) -> Result<()> {
- let agent = agent_choice_to_kind(args.agent);
+ let agent = args.agent.kind();
let project = super::resolve_project_name(config, args.project.as_deref())?;
let db_path = config.data_dir.join("db").join(DB_FILENAME);
if !db_path.exists() {
@@ -192,21 +192,6 @@ fn effective_cwd(config: &Config) -> Result<String> {
.into_owned())
}
-fn agent_choice_to_kind(choice: AgentChoice) -> AgentKind {
- match choice {
- AgentChoice::ClaudeCode => AgentKind::ClaudeCode,
- AgentChoice::Codex => AgentKind::Codex,
- AgentChoice::OpenCode => AgentKind::OpenCode,
- AgentChoice::Cursor => AgentKind::Cursor,
- AgentChoice::GeminiCli => AgentKind::GeminiCli,
- AgentChoice::Openclaw => AgentKind::OpenClaw,
- AgentChoice::AntigravityCli => AgentKind::AntigravityCli,
- AgentChoice::Omp => AgentKind::Omp,
- AgentChoice::Pi => AgentKind::Pi,
- AgentChoice::Grok => AgentKind::Grok,
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-cli/src/commands/hook_drain_process.rs b/crates/ai-memory-cli/src/commands/hook_drain_process.rs
index 17f2e457..1c7fa8e0 100644
--- a/crates/ai-memory-cli/src/commands/hook_drain_process.rs
+++ b/crates/ai-memory-cli/src/commands/hook_drain_process.rs
@@ -6,6 +6,27 @@ use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
+/// Rotate `hook-drain.log` once it grows past this. The log only receives
+/// drainer warnings, but a chronically unreachable server emits one on every
+/// session boundary forever — without a cap the append-only file grows
+/// unbounded. One rotation generation (`.old`) keeps the recent history.
+const MAX_DRAIN_LOG_BYTES: u64 = 1024 * 1024;
+
+/// Rename an oversized log to `<name>.old` (replacing any previous `.old`)
+/// so the next append starts a fresh file. Best-effort: a failed rotation
+/// must never block spawning the drainer.
+fn rotate_oversized_log(log: &Path, max_bytes: u64) {
+ let Ok(meta) = std::fs::metadata(log) else {
+ return;
+ };
+ if meta.len() <= max_bytes {
+ return;
+ }
+ let mut old = log.as_os_str().to_os_string();
+ old.push(".old");
+ let _ = std::fs::rename(log, PathBuf::from(old));
+}
+
/// Unit-testable description of the hidden drainer command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DrainCommandSpec {
@@ -79,6 +100,7 @@ fn spawn_spec(spec: &DrainCommandSpec) -> io::Result<()> {
if let Some(parent) = spec.stderr_log.parent() {
std::fs::create_dir_all(parent)?;
}
+ rotate_oversized_log(&spec.stderr_log, MAX_DRAIN_LOG_BYTES);
let config = spawn_config(spec, true);
let stderr = OpenOptions::new()
.create(true)
@@ -229,6 +251,33 @@ mod tests {
);
}
+ #[test]
+ fn rotate_oversized_log_rotates_once_over_cap_and_keeps_small_logs() {
+ let tmp = tempfile::tempdir().unwrap();
+ let log = tmp.path().join("hook-drain.log");
+ let old = tmp.path().join("hook-drain.log.old");
+
+ // Under the cap: untouched.
+ std::fs::write(&log, b"small").unwrap();
+ rotate_oversized_log(&log, 16);
+ assert!(log.exists());
+ assert!(!old.exists());
+
+ // Over the cap: current becomes .old, next append starts fresh.
+ std::fs::write(&log, vec![b'x'; 32]).unwrap();
+ rotate_oversized_log(&log, 16);
+ assert!(!log.exists());
+ assert_eq!(std::fs::metadata(&old).unwrap().len(), 32);
+
+ // A second rotation replaces the previous .old rather than failing.
+ std::fs::write(&log, vec![b'y'; 32]).unwrap();
+ rotate_oversized_log(&log, 16);
+ assert_eq!(std::fs::read(&old).unwrap(), vec![b'y'; 32]);
+
+ // Missing file: no-op, no panic.
+ rotate_oversized_log(&log, 16);
+ }
+
#[test]
fn spawn_config_redirects_stdio_and_logs_under_data_dir_logs() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index ed34d999..daa53a09 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -2283,16 +2283,8 @@ fn is_hook_script_file(path: &Path) -> bool {
}
fn resolve_hooks_dir(explicit: Option<&Path>, agent: AgentChoice) -> Result<PathBuf> {
- let sub = match agent {
- AgentChoice::ClaudeCode => "claude-code",
- AgentChoice::Codex => "codex",
- AgentChoice::Cursor => "cursor",
- AgentChoice::GeminiCli => "gemini-cli",
- AgentChoice::AntigravityCli => "antigravity-cli",
- AgentChoice::Grok => "grok",
- AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw => {
- anyhow::bail!("{agent:?} uses a generated integration, not a hook script directory")
- }
+ let Some(sub) = agent.script_hook_subdir() else {
+ anyhow::bail!("{agent:?} uses a generated integration, not a hook script directory")
};
if let Some(p) = explicit {
let path = p.join(sub);
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 05c48b34..6f5e36d1 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -493,55 +493,55 @@ impl<'a> HookCommandContext<'a> {
}
impl HookCommandPlatform {
- fn current() -> Self {
- match std::env::var("AI_MEMORY_HOOK_PLATFORM") {
- Ok(v) if v.eq_ignore_ascii_case("windows") => Self::Windows,
- Ok(v) if v.eq_ignore_ascii_case("posix") || v.eq_ignore_ascii_case("unix") => {
- Self::Posix
+ /// Parse an explicit `AI_MEMORY_HOOK_PLATFORM` override. `None` when the
+ /// var is unset or names no known platform — callers then apply their own
+ /// per-render-path default. One parser so a new platform value can't be
+ /// recognised by one render path and silently ignored by another.
+ fn from_env_override() -> Option<Self> {
+ let v = std::env::var("AI_MEMORY_HOOK_PLATFORM").ok()?;
+ match v {
+ v if v.eq_ignore_ascii_case("windows") => Some(Self::Windows),
+ v if v.eq_ignore_ascii_case("posix") || v.eq_ignore_ascii_case("unix") => {
+ Some(Self::Posix)
}
- Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
- Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
- Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
- _ if cfg!(windows) => Self::Windows,
- _ => Self::Posix,
+ v if v.eq_ignore_ascii_case("windows-bash") => Some(Self::WindowsBash),
+ v if v.eq_ignore_ascii_case("windows-native") => Some(Self::WindowsNative),
+ v if v.eq_ignore_ascii_case("posix-native") => Some(Self::PosixNative),
+ _ => None,
}
}
+ fn current() -> Self {
+ Self::from_env_override().unwrap_or(if cfg!(windows) {
+ Self::Windows
+ } else {
+ Self::Posix
+ })
+ }
+
/// Platform for agents known to use bash as their hook runner on
- /// Windows (currently Claude Code). Returns `WindowsBash` on
+ /// Windows (currently Claude Code). Returns `WindowsNative` on
/// Windows unless overridden by `AI_MEMORY_HOOK_PLATFORM`.
fn for_bash_runner() -> Self {
- match std::env::var("AI_MEMORY_HOOK_PLATFORM") {
- Ok(v) if v.eq_ignore_ascii_case("windows") => Self::Windows,
- Ok(v) if v.eq_ignore_ascii_case("posix") || v.eq_ignore_ascii_case("unix") => {
- Self::Posix
- }
- Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
- Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
- Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
- _ if cfg!(windows) => Self::WindowsNative,
- // Native macOS / Linux defaults to the binary hook command (spool +
- // OIDC), same as Windows. The Docker wrapper forces `posix` so its
- // host-rendered config keeps using the `.sh` scripts.
- _ => Self::PosixNative,
- }
+ // Native macOS / Linux defaults to the binary hook command (spool +
+ // OIDC), same as Windows. The Docker wrapper forces `posix` so its
+ // host-rendered config keeps using the `.sh` scripts.
+ Self::from_env_override().unwrap_or(if cfg!(windows) {
+ Self::WindowsNative
+ } else {
+ Self::PosixNative
+ })
}
/// Script fallback for setup-agent / docker-host snippets. Respects an
/// explicit override, but defaults to the shell command because setup-agent
/// copies scripts, not a host-local native binary.
fn for_bash_script_runner() -> Self {
- match std::env::var("AI_MEMORY_HOOK_PLATFORM") {
- Ok(v) if v.eq_ignore_ascii_case("windows") => Self::Windows,
- Ok(v) if v.eq_ignore_ascii_case("posix") || v.eq_ignore_ascii_case("unix") => {
- Self::Posix
- }
- Ok(v) if v.eq_ignore_ascii_case("windows-bash") => Self::WindowsBash,
- Ok(v) if v.eq_ignore_ascii_case("windows-native") => Self::WindowsNative,
- Ok(v) if v.eq_ignore_ascii_case("posix-native") => Self::PosixNative,
- _ if cfg!(windows) => Self::WindowsBash,
- _ => Self::Posix,
- }
+ Self::from_env_override().unwrap_or(if cfg!(windows) {
+ Self::WindowsBash
+ } else {
+ Self::Posix
+ })
}
}
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 95b3a1e8..3507d169 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -66,16 +66,8 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
emit_extension_setup_hint(&args)?;
return Ok(());
}
- let agent_sub = match args.agent {
- AgentChoice::ClaudeCode => "claude-code",
- AgentChoice::Codex => "codex",
- AgentChoice::Cursor => "cursor",
- AgentChoice::GeminiCli => "gemini-cli",
- AgentChoice::AntigravityCli => "antigravity-cli",
- AgentChoice::Grok => "grok",
- AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw => {
- bail!("internal: generated integration should have returned before staging hooks")
- }
+ let Some(agent_sub) = args.agent.script_hook_subdir() else {
+ bail!("internal: generated integration should have returned before staging hooks")
};
let source = resolve_source(args.source.as_deref(), agent_sub)?;
diff --git a/crates/ai-memory-store/src/auto_improve.rs b/crates/ai-memory-store/src/auto_improve.rs
index 883e4b42..72e3887c 100644
--- a/crates/ai-memory-store/src/auto_improve.rs
+++ b/crates/ai-memory-store/src/auto_improve.rs
@@ -1,4 +1,26 @@
-#![allow(missing_docs)]
+//! SQLite persistence for the auto-improvement loop.
+//!
+//! The consolidate crate reviews a finished session and produces *proposals*
+//! (create/update a wiki page). This module stores those proposals with a
+//! full audit trail so an operator can approve, reject, or fail them later:
+//!
+//! - `auto_improve_runs` — one row per review pass, with provider/model,
+//! warnings, and the rejected-candidate list for telemetry.
+//! - `auto_improve_proposals` — staged page edits plus a snapshot of the
+//! target page at stage time (`*_at_stage` columns). Approval re-checks
+//! that snapshot and returns [`ApproveAutoImproveProposalResult::Conflict`]
+//! instead of clobbering a page that changed since staging.
+//! - `auto_improve_proposal_events` — append-only status history per
+//! proposal (`staged` / `approved` / `rejected` / `failed` / `conflict`).
+//! - `auto_improve_rejections` — normalized rejection records with a
+//! whitespace/case-insensitive fingerprint so the telemetry report can
+//! spot the same proposal being re-staged and re-rejected.
+//! - `auto_improve_scheduler_state` / `_claims` — the session-end scheduler
+//! watermark and per-session claims that make the background reviewer
+//! idempotent across restarts.
+//!
+//! All mutations run inside a transaction on the caller's connection; the
+//! writer actor owns that connection, so the single-writer invariant holds.
use std::str::FromStr;
@@ -15,17 +37,25 @@ use uuid::Uuid;
use crate::error::{StoreError, StoreResult};
use crate::ops;
+/// Lifecycle status of a staged proposal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoImproveProposalStatus {
+ /// Staged and awaiting an operator decision.
Pending,
+ /// Approved and applied — `applied_page_id` points at the written page.
Approved,
+ /// Rejected by an operator with a reason.
Rejected,
+ /// Approval was attempted but the target page changed since staging.
Conflict,
+ /// Application failed after approval (e.g. the page write errored).
Failed,
}
impl AutoImproveProposalStatus {
+ /// Snake-case string stored in the `status` column.
+ #[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Pending => "pending",
@@ -53,14 +83,19 @@ impl FromStr for AutoImproveProposalStatus {
}
}
+/// What a proposal wants to do to its target page.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutoImproveProposalOperation {
+ /// Create a page that must not exist yet at stage time.
Create,
+ /// Rewrite a page that must already exist at stage time.
Update,
}
impl AutoImproveProposalOperation {
+ /// Snake-case string stored in the `operation` column.
+ #[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Create => "create",
@@ -82,109 +117,201 @@ impl FromStr for AutoImproveProposalOperation {
}
}
+/// One review pass to persist: run metadata plus its staged proposals.
#[derive(Debug, Clone)]
pub struct StageAutoImproveRun {
+ /// Owning workspace.
pub workspace_id: WorkspaceId,
+ /// Owning project.
pub project_id: ProjectId,
+ /// Session the review covered, when session-scoped. Must belong to the
+ /// same workspace/project or staging fails.
pub session_id: Option<SessionId>,
+ /// LLM provider name used for the review, for telemetry.
pub provider: Option<String>,
+ /// LLM model id used for the review, for telemetry.
pub model: Option<String>,
+ /// Reviewer's one-paragraph run summary.
pub summary: Option<String>,
+ /// Reviewer warnings (JSON array) surfaced in reports.
pub warnings_json: serde_json::Value,
+ /// Candidates the reviewer itself rejected (JSON array); each entry with
+ /// a non-empty `reason` also lands in `auto_improve_rejections`.
pub rejected_candidates_json: serde_json::Value,
+ /// Effective review config snapshot for reproducibility.
pub config_json: serde_json::Value,
+ /// Actor attribution recorded on the run and its `staged` events.
pub proposal_actor: ActorContext,
+ /// Page edits to stage as pending proposals.
pub proposals: Vec<NewAutoImproveProposal>,
}
+/// One page edit to stage, before it gets an id or a status.
#[derive(Debug, Clone)]
pub struct NewAutoImproveProposal {
+ /// Create a new page or update an existing one.
pub operation: AutoImproveProposalOperation,
+ /// Wiki path of the page this proposal targets.
pub target_path: PagePath,
+ /// Proposal category (e.g. `learning`, maintenance kinds) for telemetry.
pub kind: String,
+ /// Human-readable proposal title.
pub title: String,
+ /// Reviewer confidence in `0.0..=1.0`.
pub confidence: f64,
+ /// Why the reviewer proposes this edit.
pub rationale: String,
+ /// Supporting evidence (JSON) shown to the deciding operator.
pub evidence_json: serde_json::Value,
+ /// Full proposed page body (also the materialized result for patches).
pub body_markdown: String,
+ /// SHA-256 of the staged `_pending/` artifact file, when one was written.
pub artifact_sha256: Option<[u8; 32]>,
+ /// `full_page` (default when `None`) or `patch`.
pub edit_mode: Option<String>,
+ /// Patch operations (JSON) — required when `edit_mode == "patch"`.
pub patch_json: Option<serde_json::Value>,
+ /// SHA-256 of the base body the patch was materialized against —
+ /// required for patches; staging fails if the live target differs.
pub expected_base_body_sha256: Option<[u8; 32]>,
}
+/// Ids assigned by [`stage_run`].
#[derive(Debug, Clone, Serialize)]
pub struct StagedAutoImproveRun {
+ /// Id of the recorded run row.
pub run_id: AutoImproveRunId,
+ /// Ids of the staged proposals, in input order.
pub proposal_ids: Vec<AutoImproveProposalId>,
}
+/// List-view projection of a proposal (no bodies or event history).
#[derive(Debug, Clone, Serialize)]
pub struct AutoImproveProposalSummary {
+ /// Proposal id.
pub id: AutoImproveProposalId,
+ /// Run that staged the proposal.
pub run_id: AutoImproveRunId,
+ /// Owning workspace.
pub workspace_id: WorkspaceId,
+ /// Owning project.
pub project_id: ProjectId,
+ /// Current lifecycle status.
pub status: AutoImproveProposalStatus,
+ /// Create vs update.
pub operation: AutoImproveProposalOperation,
+ /// Wiki path of the targeted page.
pub target_path: PagePath,
+ /// Proposal category for telemetry.
pub kind: String,
+ /// Human-readable proposal title.
pub title: String,
+ /// Reviewer confidence in `0.0..=1.0`.
pub confidence: f64,
+ /// Stage time (Unix microseconds).
pub staged_at: i64,
+ /// Decision time (Unix microseconds), once decided.
pub decided_at: Option<i64>,
}
+/// Full proposal record: summary plus bodies, stage-time target snapshot,
+/// decision attribution, and the append-only event history.
#[derive(Debug, Clone, Serialize)]
pub struct AutoImproveProposalDetail {
+ /// The list-view fields.
pub summary: AutoImproveProposalSummary,
+ /// Why the reviewer proposed this edit.
pub rationale: String,
+ /// Supporting evidence (JSON) shown to the deciding operator.
pub evidence_json: serde_json::Value,
+ /// Full proposed page body.
pub body_markdown: String,
+ /// SHA-256 of `body_markdown`, computed at stage time.
pub body_sha256: [u8; 32],
+ /// `_pending/auto-improve/<id>.md` artifact path for this proposal.
pub artifact_path: String,
+ /// SHA-256 of the staged artifact file, when one was written.
pub artifact_sha256: Option<[u8; 32]>,
+ /// Latest page id of the target at stage time (`None` for creates).
pub target_latest_page_id_at_stage: Option<PageId>,
+ /// Target body hash at stage time — approval compares against this to
+ /// detect a page that changed after staging.
pub target_body_sha256_at_stage: Option<[u8; 32]>,
+ /// Target `updated_at` at stage time (Unix microseconds).
pub target_updated_at_at_stage: Option<i64>,
+ /// Operator-supplied reason for a reject/fail/conflict decision.
pub decision_reason: Option<String>,
+ /// Deciding user, when the decision came from an identified account.
pub decided_by_author_id: Option<UserId>,
+ /// Full actor context (JSON) recorded at decision time.
pub decided_by_actor_json: Option<serde_json::Value>,
+ /// Page written by an approval.
pub applied_page_id: Option<PageId>,
+ /// Wiki git checkpoint recorded alongside an approval, when available.
pub checkpoint: Option<String>,
+ /// `full_page` or `patch`.
pub edit_mode: String,
+ /// Patch operations (JSON) for `patch` proposals.
pub patch_json: Option<serde_json::Value>,
+ /// Base body hash the patch was generated against.
pub expected_base_body_sha256: Option<[u8; 32]>,
+ /// Base body hash the staged `body_markdown` was materialized from.
pub materialized_base_body_sha256: Option<[u8; 32]>,
+ /// Status history, oldest first.
pub events: Vec<AutoImproveProposalEvent>,
}
+/// One append-only status-history entry for a proposal.
#[derive(Debug, Clone, Serialize)]
pub struct AutoImproveProposalEvent {
+ /// Autoincrement row id (orders events).
pub id: i64,
+ /// Proposal this event belongs to.
pub proposal_id: AutoImproveProposalId,
+ /// Event name: `staged`, `approved`, `rejected`, `failed`, or `conflict`.
pub event: String,
+ /// Actor context (JSON) that caused the event.
pub actor_json: serde_json::Value,
+ /// Acting user, when identified.
pub author_id: Option<UserId>,
+ /// Event-specific payload (e.g. `reason`, `applied_page_id`).
pub detail_json: serde_json::Value,
+ /// Event time (Unix microseconds).
pub at: i64,
}
+/// Normalized rejection record used by the telemetry report to spot the
+/// same proposal being re-staged and re-rejected.
#[derive(Debug, Clone, Serialize)]
pub struct AutoImproveRejectionSummary {
+ /// Rejection row id (UUID string).
pub id: String,
+ /// Owning workspace.
pub workspace_id: WorkspaceId,
+ /// Owning project.
pub project_id: ProjectId,
+ /// Targeted wiki path, when the rejected candidate named one.
pub target_path: Option<String>,
+ /// Proposal category, when known.
pub kind: Option<String>,
+ /// Create vs update, when known.
pub operation: Option<String>,
+ /// `full_page` / `patch`, when known.
pub edit_mode: Option<String>,
+ /// Why the candidate/proposal was rejected.
pub reason: String,
+ /// Whitespace/case-insensitive SHA-256 over the identifying fields —
+ /// equal fingerprints mean "the same rejection happened again".
pub normalized_fingerprint: String,
+ /// One-line description (title, summary, or the reason itself).
pub summary: String,
+ /// Original candidate/evidence payload (JSON).
pub evidence_json: serde_json::Value,
+ /// Run the rejection came from, when known.
pub source_run_id: Option<AutoImproveRunId>,
+ /// Proposal the rejection came from (`None` for reviewer-side rejects).
pub source_proposal_id: Option<AutoImproveProposalId>,
+ /// Record time (Unix microseconds).
pub created_at: i64,
}
@@ -224,47 +351,86 @@ pub struct AutoImproveTelemetryCount {
pub count: usize,
}
+/// Reject a pending proposal with a reason.
#[derive(Debug, Clone)]
pub struct RejectAutoImproveProposal {
+ /// Owning workspace (scope check).
pub workspace_id: WorkspaceId,
+ /// Owning project (scope check).
pub project_id: ProjectId,
+ /// Proposal to reject; must currently be pending.
pub proposal_id: AutoImproveProposalId,
+ /// Operator-supplied rejection reason.
pub reason: String,
+ /// Actor attribution for the decision event.
pub actor: ActorContext,
+ /// Deciding user, when identified.
pub author_id: Option<UserId>,
}
+/// Mark a pending proposal failed (its application errored).
#[derive(Debug, Clone)]
pub struct FailAutoImproveProposal {
+ /// Owning workspace (scope check).
pub workspace_id: WorkspaceId,
+ /// Owning project (scope check).
pub project_id: ProjectId,
+ /// Proposal to fail; must currently be pending.
pub proposal_id: AutoImproveProposalId,
+ /// What went wrong.
pub reason: String,
+ /// Actor attribution for the decision event.
pub actor: ActorContext,
+ /// Deciding user, when identified.
pub author_id: Option<UserId>,
}
+/// Approve a pending proposal and apply its page in the same transaction.
#[derive(Debug, Clone)]
pub struct ApproveAutoImproveProposal {
+ /// Owning workspace (scope check).
pub workspace_id: WorkspaceId,
+ /// Owning project (scope check).
pub project_id: ProjectId,
+ /// Proposal to approve; must currently be pending.
pub proposal_id: AutoImproveProposalId,
+ /// Page to write on approval. Its scope, author, and path must match the
+ /// proposal or approval fails before touching anything.
pub page: NewPage,
+ /// Actor attribution for the decision event.
pub actor: ActorContext,
+ /// Deciding user, when identified.
pub author_id: Option<UserId>,
+ /// Wiki git checkpoint to record alongside the approval.
pub checkpoint: Option<String>,
}
+/// Outcome of [`approve_proposal`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApproveAutoImproveProposalResult {
- Approved { page_id: PageId },
+ /// The page was written and the proposal marked approved.
+ Approved {
+ /// Id of the written page version.
+ page_id: PageId,
+ },
+ /// The target changed since staging; the proposal was marked `conflict`
+ /// and nothing was written.
Conflict,
}
+/// `_pending/auto-improve/<id>.md` — where a staged proposal's body artifact
+/// lives in the wiki tree.
+#[must_use]
pub fn artifact_path_for(proposal_id: AutoImproveProposalId) -> String {
format!("_pending/auto-improve/{proposal_id}.md")
}
+/// Ensure a scheduler-state row exists for the scope, seeding the watermark
+/// at the newest already-ended session so pre-existing history is not
+/// retroactively reviewed.
+///
+/// # Errors
+/// Returns an error when the underlying SQLite statements fail.
pub fn ensure_scheduler_state(
conn: &mut Connection,
workspace_id: WorkspaceId,
@@ -292,6 +458,13 @@ pub fn ensure_scheduler_state(
Ok(())
}
+/// Atomically claim one ended session for background review. Returns `true`
+/// only for the first claimer: the insert requires the session to be past
+/// the scope's watermark and not already covered by a run, so concurrent
+/// schedulers and restarts cannot double-review a session.
+///
+/// # Errors
+/// Returns an error when the underlying SQLite statements fail.
pub fn claim_scheduler_session(
conn: &mut Connection,
workspace_id: WorkspaceId,
@@ -342,6 +515,15 @@ pub fn claim_scheduler_session(
Ok(inserted == 1)
}
+/// Persist one review run and stage its proposals as `pending`, all in one
+/// transaction. Validates per-proposal preconditions (create targets must
+/// not exist, update/patch targets must exist and — for patches — still
+/// match the expected base hash) and snapshots the target page so approval
+/// can detect later drift.
+///
+/// # Errors
+/// Returns [`StoreError::InvalidState`] when a precondition fails, or an
+/// SQLite error when a statement fails; either way nothing is committed.
pub fn stage_run(
conn: &mut Connection,
input: &StageAutoImproveRun,
@@ -517,6 +699,12 @@ pub fn stage_run(
})
}
+/// Mark a pending proposal `failed`, record the rejection fingerprint, and
+/// append a `failed` event.
+///
+/// # Errors
+/// Returns [`StoreError::InvalidState`] when the proposal is not pending in
+/// the given scope, or an SQLite error when a statement fails.
pub fn fail_proposal(conn: &mut Connection, input: &FailAutoImproveProposal) -> StoreResult<()> {
let now = Timestamp::now().as_microsecond();
let actor_json = serde_json::to_string(&input.actor)?;
@@ -555,6 +743,12 @@ pub fn fail_proposal(conn: &mut Connection, input: &FailAutoImproveProposal) ->
Ok(())
}
+/// Mark a pending proposal `rejected`, record the rejection fingerprint, and
+/// append a `rejected` event.
+///
+/// # Errors
+/// Returns [`StoreError::InvalidState`] when the proposal is not pending in
+/// the given scope, or an SQLite error when a statement fails.
pub fn reject_proposal(
conn: &mut Connection,
input: &RejectAutoImproveProposal,
@@ -596,6 +790,15 @@ pub fn reject_proposal(
Ok(())
}
+/// Approve a pending proposal: re-check the stage-time target snapshot and,
+/// when it still matches, write the page and mark the proposal `approved`
+/// in the same transaction. A drifted target marks the proposal `conflict`
+/// instead and writes nothing.
+///
+/// # Errors
+/// Returns [`StoreError::InvalidState`] when the approval page's scope,
+/// author, or path disagrees with the proposal, or when the proposal is not
+/// pending in the given scope; or an SQLite error when a statement fails.
pub fn approve_proposal(
conn: &mut Connection,
input: &ApproveAutoImproveProposal,
diff --git a/docs/install.md b/docs/install.md
index 5ae11d87..adfbbdb3 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -708,6 +708,18 @@ This path is friction-free when:
- You don't need to run a local ai-memory server (you're a client of
a homelab/remote ai-memory)
+### Hook command paths across a container boundary
+
+`install-hooks --apply` stages the hook scripts into the data dir and
+writes their absolute paths into the agent's config. When the CLI runs
+inside a container but the agent runs on the host, those staged paths
+would be container paths the host can't see. Set
+`AI_MEMORY_HOOKS_HOST_ROOT` to the *host* directory that the staged
+`hooks/` tree is mounted from and the rendered config uses
+`<host-root>/<agent>/…` command paths instead. The bundled docker
+wrappers (`bin/ai-memory`, `bin/ai-memory.ps1`) forward this variable
+automatically; you only set it by hand for custom container setups.
+
---
## Running ai-memory without docker