Skip to content

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

Rust

fix(hooks): bound lifecycle observation bodies

AkitaOnRailse851837d8a00
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 34ad1866..f5798945 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,6 +46,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`access_count` a coarser retention signal. (#239)
### Fixed
+- Lifecycle `user-prompt` and `post-compaction` bodies are now truncated
+ UTF-8-safely at 16 KiB, while notification and tool excerpts remain capped at
+ 2 KB. Native hook commands apply the event cap before local spooling or
+ transport, the server repeats it for direct and older clients, and the
+ sanitized observation boundary independently caps every durable body at
+ 16 KiB so neither SQLite nor observation FTS can grow to the 10 MiB HTTP
+ transport limit. (#249)
- `ai-memory run <harness>` now verifies an ai-memory-injected native resume
target still exists in that harness's read-only session store. A confirmed
orphan starts a fresh native session and repoints the same workstream instead
diff --git a/README.md b/README.md
index e65b4cd7..79e3ec38 100644
--- a/README.md
+++ b/README.md
@@ -63,6 +63,9 @@ priors are at the [bottom](#influences-and-prior-art).
- **Zero-friction lifecycle capture.** Hooks fire-and-forget bounded,
sanitized prompt, tool-lifecycle, and session-boundary observations. Direct
launches keep this lightweight path; it is not a complete native transcript.
+ User prompts and post-compaction summaries retain up to 16 KiB;
+ notifications and tool excerpts retain up to 2 KB, with a 16 KiB durable
+ backstop for every observation body.
- **Opt-in managed workstreams.** `ai-memory run claude`, then `ai-memory run
codex --yolo`, then `ai-memory run kimi`, transparently resumes one logical
workstream with native per-harness sessions, a portable visible-event ledger,
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 86e925ec..8b80bfbe 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -426,6 +426,12 @@ where
}
false
};
+ if ai_memory_hooks::cap_lifecycle_body_for_client(
+ &mut json,
+ ai_memory_hooks::HookEvent::parse(&args.event),
+ ) {
+ payload = serde_json::to_string(&json)?;
+ }
let (policy_cwd, canonical_session_id) = hook_context(&args.agent, &json);
let policy = policy_cwd.as_deref().map(capture_policy);
let tool_event = is_tool_event(&args.event);
diff --git a/crates/ai-memory-cli/tests/hook_payload.rs b/crates/ai-memory-cli/tests/hook_payload.rs
index 820fe5f0..6acccc85 100644
--- a/crates/ai-memory-cli/tests/hook_payload.rs
+++ b/crates/ai-memory-cli/tests/hook_payload.rs
@@ -234,6 +234,50 @@ fn opted_in_non_stop_event_is_inert() {
);
}
+#[test]
+fn oversized_core_bodies_are_capped_before_the_local_spool() {
+ for (event, field, cap) in [
+ (
+ "user-prompt-submit",
+ "prompt",
+ ai_memory_hooks::USER_PROMPT_EXCERPT_MAX_BYTES,
+ ),
+ (
+ "notification",
+ "message",
+ ai_memory_hooks::NOTIFICATION_EXCERPT_MAX_BYTES,
+ ),
+ (
+ "post-compaction",
+ "summary",
+ ai_memory_hooks::POST_COMPACTION_EXCERPT_MAX_BYTES,
+ ),
+ ] {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ let payload = serde_json::json!({
+ "session_id": "bounded-spool",
+ (field): format!("{}TAIL_SENTINEL", "x".repeat(cap + 8))
+ })
+ .to_string();
+ let output = run_hook_event(tmp.path(), event, payload.as_bytes());
+ assert!(
+ output.status.success(),
+ "{event}: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let body = spooled_body(tmp.path());
+ assert!(
+ !body.contains("TAIL_SENTINEL"),
+ "{event} spool was not capped"
+ );
+ let json: serde_json::Value =
+ serde_json::from_str(&body).expect("spooled body remains JSON");
+ let excerpt = json[field].as_str().expect("body field is text");
+ assert!(excerpt.len() <= cap, "{event} exceeded {cap} bytes");
+ assert!(excerpt.ends_with('…'));
+ }
+}
+
#[test]
fn every_spooled_event_carries_a_persistent_ingest_key() {
// The idempotency key is minted ONCE at spool time and baked into the
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index c2dd141d..0c5c5d96 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -47,7 +47,9 @@ pub use ids::{
pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
pub use page::{LinkTarget, NewPage, Page, Tier};
pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_line, full_block};
-pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};
+pub use sanitize::{
+ OBSERVATION_BODY_MAX_BYTES, SanitizeConfig, Sanitized, Sanitizer, truncate_utf8_bytes,
+};
pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};
pub use workstream::{
FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest,
diff --git a/crates/ai-memory-core/src/sanitize.rs b/crates/ai-memory-core/src/sanitize.rs
index fc2c21a4..06385569 100644
--- a/crates/ai-memory-core/src/sanitize.rs
+++ b/crates/ai-memory-core/src/sanitize.rs
@@ -37,6 +37,11 @@ use tracing::debug;
use crate::NewObservation;
+/// Universal durable-body ceiling for lifecycle observations. Event adapters
+/// may impose smaller limits, but no sanitized observation can cross the store
+/// boundary above 16 KiB.
+pub const OBSERVATION_BODY_MAX_BYTES: usize = 16 * 1024;
+
/// Compile-time list of redaction patterns. Order is intentional:
/// more-specific patterns first. False positives are acceptable —
/// better to redact a stray hash than to leak a credential.
@@ -189,15 +194,41 @@ impl<T> Sanitized<T> {
}
impl Sanitized<NewObservation> {
- /// Apply the privacy strip to an observation's title + body.
+ /// Apply the privacy strip to an observation's title + body, then enforce
+ /// the universal durable-body ceiling after redaction.
#[must_use]
pub fn new(mut obs: NewObservation, sanitizer: &Sanitizer) -> Self {
obs.title = sanitizer.scrub(&obs.title);
- obs.body = sanitizer.scrub(&obs.body);
+ obs.body = truncate_utf8_bytes(&sanitizer.scrub(&obs.body), OBSERVATION_BODY_MAX_BYTES);
Self(obs)
}
}
+/// Truncate text to at most `max` UTF-8 bytes, reserving the ellipsis inside
+/// the requested cap and never splitting a code point.
+#[must_use]
+pub fn truncate_utf8_bytes(input: &str, max: usize) -> String {
+ if input.len() <= max {
+ return input.to_string();
+ }
+ if max < '…'.len_utf8() {
+ return String::new();
+ }
+ let limit = max - '…'.len_utf8();
+ let mut end = 0;
+ for (index, character) in input.char_indices() {
+ let next = index + character.len_utf8();
+ if next > limit {
+ break;
+ }
+ end = next;
+ }
+ let mut output = String::with_capacity(max);
+ output.push_str(&input[..end]);
+ output.push('…');
+ output
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -293,6 +324,39 @@ mod tests {
assert!(scrubbed.body.contains("[REDACTED]"));
}
+ #[test]
+ fn observation_boundary_caps_after_sanitizing_without_splitting_utf8() {
+ let raw = NewObservation {
+ session_id: SessionId::new(),
+ workspace_id: WorkspaceId::new(),
+ project_id: ProjectId::new(),
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "large prompt".into(),
+ body: format!(
+ "OPENAI_API_KEY=sk-{} {} TAIL_SENTINEL",
+ "a".repeat(40),
+ "é".repeat(OBSERVATION_BODY_MAX_BYTES)
+ ),
+ importance: 8,
+ };
+ let scrubbed = Sanitized::new(raw, &s()).into_inner();
+ assert!(scrubbed.body.len() <= OBSERVATION_BODY_MAX_BYTES);
+ assert!(scrubbed.body.contains("[REDACTED]"));
+ assert!(!scrubbed.body.contains("TAIL_SENTINEL"));
+ assert!(scrubbed.body.ends_with('…'));
+ }
+
+ #[test]
+ fn utf8_truncation_reserves_the_ellipsis_inside_the_cap() {
+ let truncated = truncate_utf8_bytes("abcééé", 7);
+ assert_eq!(truncated, "abc…");
+ assert_eq!(truncated.len(), 6);
+ assert_eq!(truncate_utf8_bytes("unchanged", 9), "unchanged");
+ assert!(truncate_utf8_bytes("large", 2).is_empty());
+ }
+
#[test]
fn extra_patterns_compile_and_apply() {
let cfg = SanitizeConfig {
diff --git a/crates/ai-memory-hooks/src/assistant_capture.rs b/crates/ai-memory-hooks/src/assistant_capture.rs
index a52ed98a..c0cb1a37 100644
--- a/crates/ai-memory-hooks/src/assistant_capture.rs
+++ b/crates/ai-memory-hooks/src/assistant_capture.rs
@@ -13,10 +13,10 @@
//! opt-in path that re-introduces a sanitized, capped excerpt: the client-side
//! [`transform_for_client`] and the server-side [`apply_assistant_backstop`].
-use ai_memory_core::{AgentKind, Sanitizer};
+use ai_memory_core::{AgentKind, Sanitizer, truncate_utf8_bytes};
use serde::{Deserialize, Serialize};
-use crate::payload::{HookEnvelope, HookEvent, truncate_utf8_bytes};
+use crate::payload::{HookEnvelope, HookEvent};
/// Synthetic body key carrying the opt-in, sanitized assistant excerpt from the
/// client to the server. Distinct from the raw `last_assistant_message` field,
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 0326818f..2afe17c8 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -42,7 +42,10 @@ pub use capture_policy::{
CaptureConfig, CaptureDecision, CaptureDisposition, CapturePolicy, CaptureProtocol,
CaptureSource, ExtractionState, PolicyState, ToolFamily,
};
-pub use payload::{HookEnvelope, HookEvent};
+pub use payload::{
+ HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,
+ USER_PROMPT_EXCERPT_MAX_BYTES, cap_lifecycle_body_for_client,
+};
pub use router::{
DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, DEFAULT_INGEST_GATE_MAX_ENTRIES,
DEFAULT_PROJECT_CACHE_MAX_ENTRIES, HookState, IngestGates, IngestRateLimiter, ProjectCache,
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 54d0d3be..27eb2ebf 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -1,12 +1,24 @@
//! Wire envelope received on `POST /hook`.
-use ai_memory_core::{AgentKind, ObservationKind};
+use ai_memory_core::{AgentKind, OBSERVATION_BODY_MAX_BYTES, ObservationKind, truncate_utf8_bytes};
use serde::{Deserialize, Serialize};
use crate::capture_policy::{
ToolObservationMetadata, tool_observation_metadata, tool_observation_outcome,
};
+/// Durable excerpt ceiling for user prompts. Prompts retain more working
+/// context than tool/notification summaries while remaining bounded.
+pub const USER_PROMPT_EXCERPT_MAX_BYTES: usize = OBSERVATION_BODY_MAX_BYTES;
+
+/// Durable excerpt ceiling for post-compaction summaries.
+pub const POST_COMPACTION_EXCERPT_MAX_BYTES: usize = OBSERVATION_BODY_MAX_BYTES;
+
+/// Durable excerpt ceiling for notifications.
+pub const NOTIFICATION_EXCERPT_MAX_BYTES: usize = 2_000;
+
+const TOOL_EXCERPT_MAX_BYTES: usize = 2_000;
+
/// Query-string parameters on `POST /hook`.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct HookQuery {
@@ -744,7 +756,8 @@ fn value_to_text(value: &serde_json::Value) -> Option<String> {
fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<String> {
match event {
- HookEvent::UserPrompt => extract_content(raw, &["prompt", "message", "text"]),
+ HookEvent::UserPrompt => extract_content(raw, &["prompt", "message", "text"])
+ .map(|body| truncate_utf8_bytes(&body, USER_PROMPT_EXCERPT_MAX_BYTES)),
HookEvent::PostToolUse => {
let tool = extract_string(raw, &["tool", "tool_name", "name"])
.or_else(|| extract_string_path(raw, &[&["toolCall", "name"]]))
@@ -757,8 +770,10 @@ fn best_body_excerpt(event: HookEvent, raw: &serde_json::Value) -> Option<String
.unwrap_or_else(|| "(no output captured)".into());
Some(format!("tool: {tool}\n---\n{}", truncate_excerpt(&result)))
}
- HookEvent::Notification => extract_content(raw, &["message", "text"]),
- HookEvent::PostCompaction => extract_content(raw, &["summary"]),
+ HookEvent::Notification => extract_content(raw, &["message", "text"])
+ .map(|body| truncate_utf8_bytes(&body, NOTIFICATION_EXCERPT_MAX_BYTES)),
+ HookEvent::PostCompaction => extract_content(raw, &["summary"])
+ .map(|body| truncate_utf8_bytes(&body, POST_COMPACTION_EXCERPT_MAX_BYTES)),
_ => None,
}
}
@@ -776,31 +791,72 @@ fn truncate_for_title(s: &str) -> String {
}
fn truncate_excerpt(s: &str) -> String {
- truncate_utf8_bytes(s, 2_000)
+ truncate_utf8_bytes(s, TOOL_EXCERPT_MAX_BYTES)
+}
+
+/// Cap core lifecycle body fields before the native hook writes its local
+/// spool entry. The server independently reapplies the same per-event limits
+/// while constructing [`HookEnvelope`], and the typed persistence boundary has
+/// a universal backstop.
+pub fn cap_lifecycle_body_for_client(raw: &mut serde_json::Value, event: HookEvent) -> bool {
+ let Some((keys, max_bytes)) = core_body_cap(event) else {
+ return false;
+ };
+ let mut changed = cap_candidate_group(raw, keys, max_bytes);
+ for container in ["payload", "event"] {
+ if let Some(nested) = raw.get_mut(container) {
+ changed |= cap_candidate_group(nested, keys, max_bytes);
+ }
+ }
+ changed
}
-/// Truncate `s` to at most `max` bytes on a UTF-8 char boundary, reserving the
-/// ellipsis within the cap (never beyond it). Shared by the tool-excerpt cap
-/// and the opt-in assistant excerpt cap (#196) so there is one UTF-8-safe
-/// truncation, two named caps.
-pub(crate) fn truncate_utf8_bytes(s: &str, max: usize) -> String {
- if s.len() <= max {
- return s.to_string();
- }
- // Reserve the ellipsis within the byte cap, not beyond it.
- let limit = max.saturating_sub('…'.len_utf8());
- let mut buf = String::with_capacity(max);
- let mut end = 0;
- for (idx, ch) in s.char_indices() {
- let next = idx + ch.len_utf8();
- if next > limit {
- break;
+fn core_body_cap(event: HookEvent) -> Option<(&'static [&'static str], usize)> {
+ match event {
+ HookEvent::UserPrompt => Some((
+ &["prompt", "message", "text"],
+ USER_PROMPT_EXCERPT_MAX_BYTES,
+ )),
+ HookEvent::Notification => Some((&["message", "text"], NOTIFICATION_EXCERPT_MAX_BYTES)),
+ HookEvent::PostCompaction => Some((&["summary"], POST_COMPACTION_EXCERPT_MAX_BYTES)),
+ _ => None,
+ }
+}
+
+fn cap_candidate_group(value: &mut serde_json::Value, keys: &[&str], max_bytes: usize) -> bool {
+ let mut changed = cap_object_fields(value, keys, max_bytes);
+ if let Some(properties) = value.get_mut("properties") {
+ changed |= cap_object_fields(properties, keys, max_bytes);
+ if let Some(info) = properties.get_mut("info") {
+ changed |= cap_object_fields(info, keys, max_bytes);
+ }
+ }
+ for container in ["info", "path"] {
+ if let Some(nested) = value.get_mut(container) {
+ changed |= cap_object_fields(nested, keys, max_bytes);
}
- end = next;
}
- buf.push_str(&s[..end]);
- buf.push('…');
- buf
+ changed
+}
+
+fn cap_object_fields(value: &mut serde_json::Value, keys: &[&str], max_bytes: usize) -> bool {
+ let Some(object) = value.as_object_mut() else {
+ return false;
+ };
+ let mut changed = false;
+ for key in keys {
+ let Some(field) = object.get_mut(*key) else {
+ continue;
+ };
+ let Some(text) = value_to_text(field) else {
+ continue;
+ };
+ if text.len() > max_bytes {
+ *field = serde_json::Value::String(truncate_utf8_bytes(&text, max_bytes));
+ changed = true;
+ }
+ }
+ changed
}
fn normalize_extension_name(value: Option<&str>) -> Option<String> {
@@ -1443,6 +1499,76 @@ mod tests {
assert!(title.ends_with('…'));
}
+ #[test]
+ fn core_lifecycle_bodies_use_named_utf8_safe_caps() {
+ for (event, field, cap) in [
+ ("user-prompt", "prompt", USER_PROMPT_EXCERPT_MAX_BYTES),
+ ("notification", "message", NOTIFICATION_EXCERPT_MAX_BYTES),
+ (
+ "post-compaction",
+ "summary",
+ POST_COMPACTION_EXCERPT_MAX_BYTES,
+ ),
+ ] {
+ let body = format!("{}éTAIL_SENTINEL", "x".repeat(cap - 1));
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: event.into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({(field): body}),
+ );
+ let excerpt = env.body_excerpt.expect("bounded body excerpt");
+ assert!(excerpt.len() <= cap, "{event} exceeded {cap} bytes");
+ assert!(excerpt.ends_with('…'), "{event} omitted truncation marker");
+ assert!(
+ !excerpt.contains("TAIL_SENTINEL"),
+ "{event} retained content after the cap"
+ );
+ }
+ }
+
+ #[test]
+ fn client_body_cap_covers_supported_nested_candidate_shapes() {
+ let mut raw = serde_json::json!({
+ "prompt": "x".repeat(USER_PROMPT_EXCERPT_MAX_BYTES + 1),
+ "payload": {
+ "properties": {
+ "info": {
+ "message": [{"type": "text", "text": "y".repeat(USER_PROMPT_EXCERPT_MAX_BYTES + 1)}]
+ }
+ }
+ },
+ "event": {
+ "info": {
+ "text": "z".repeat(USER_PROMPT_EXCERPT_MAX_BYTES + 1)
+ }
+ }
+ });
+ assert!(cap_lifecycle_body_for_client(
+ &mut raw,
+ HookEvent::UserPrompt
+ ));
+ for value in [
+ &raw["prompt"],
+ &raw["payload"]["properties"]["info"]["message"],
+ &raw["event"]["info"]["text"],
+ ] {
+ let text = value.as_str().expect("oversized value flattened to text");
+ assert!(text.len() <= USER_PROMPT_EXCERPT_MAX_BYTES);
+ assert!(text.ends_with('…'));
+ }
+ assert!(!cap_lifecycle_body_for_client(
+ &mut raw,
+ HookEvent::UserPrompt
+ ));
+ assert!(!cap_lifecycle_body_for_client(
+ &mut raw,
+ HookEvent::SessionStart
+ ));
+ }
+
/// Kimi Code's content-block `prompt` must flatten into the title
/// exactly like the body excerpt does.
#[test]
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 0ecf8ddc..140282b3 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -7378,6 +7378,79 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn oversized_prompt_is_bounded_in_storage_and_fts() {
+ const TAIL_SENTINEL: &str = "PROMPT_TAIL_MUST_NOT_BE_INDEXED_249";
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let session_id = "bounded-prompt";
+ process(
+ &state,
+ HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": session_id,
+ "cwd": "/repo",
+ "prompt": format!(
+ "PROMPT_HEAD_IS_INDEXED {} {TAIL_SENTINEL}",
+ "x".repeat(crate::payload::USER_PROMPT_EXCERPT_MAX_BYTES)
+ )
+ }),
+ ),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let sid = resolve_session_id(&HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "session-start".into(),
+ ..Default::default()
+ },
+ serde_json::json!({ "session_id": session_id }),
+ ))
+ .unwrap();
+ let observations = state.reader.observations_for_session(sid).await.unwrap();
+ let prompt = observations
+ .iter()
+ .find(|observation| observation.kind == ObservationKind::UserPrompt)
+ .expect("prompt observation");
+ assert!(prompt.body.len() <= ai_memory_core::OBSERVATION_BODY_MAX_BYTES);
+ assert!(prompt.body.ends_with('…'));
+ assert!(!prompt.body.contains(TAIL_SENTINEL));
+ assert!(
+ state
+ .reader
+ .search_observations_for_project(
+ prompt.workspace_id,
+ prompt.project_id,
+ TAIL_SENTINEL.into(),
+ 10,
+ )
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ state
+ .reader
+ .search_observations_for_project(
+ prompt.workspace_id,
+ prompt.project_id,
+ "PROMPT_HEAD_IS_INDEXED".into(),
+ 10,
+ )
+ .await
+ .unwrap()
+ .len(),
+ 1
+ );
+ }
+
#[test]
fn unknown_capture_protocol_version_protects_recognized_file_tool() {
let env = HookEnvelope::from_query_and_body(
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ef50c65c..f975ce59 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -151,6 +151,7 @@ normalises them to exactly one of these `ObservationKind` values:
| `pre-tool-use` | Agent is about to call a tool. |
| `post-tool-use` | Agent finished a tool call. |
| `pre-compact` | Agent is about to compact or compress its context. |
+| `post-compaction` | Agent compacted context and supplied a post-facto summary or checkpoint. |
| `notification` | Agent emitted a notification-style event. |
| `stop` | Agent finished an interactive turn or stopped naturally. |
| `session-end` | Agent session ended; summary/handoff path may run. |
@@ -167,6 +168,15 @@ extension seam, not a runtime plugin system: external processors must use
the existing HTTP/MCP APIs and cannot bypass the sanitizer, hook
backpressure, or single-writer SQLite actor.
+Lifecycle bodies have content limits independent of the 10 MiB HTTP request
+limit. User prompts and post-compaction summaries are capped UTF-8-safely at
+16 KiB; notification and tool excerpts are capped at 2 KB. Native
+`ai-memory hook` commands apply the event-specific cap before local spooling
+and transport, and the server repeats it when parsing every request so direct
+and older clients cannot bypass it. The typed sanitizer boundary then applies a
+16 KiB backstop to every durable observation body after redaction. The
+separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
+
## Storage architecture
**Two layers, one source of truth.**
diff --git a/docs/design-decisions.md b/docs/design-decisions.md
index eed8323b..983eb916 100644
--- a/docs/design-decisions.md
+++ b/docs/design-decisions.md
@@ -11,7 +11,7 @@
A self-contained Rust binary that:
1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw, OpenCode, OMP, and MCP-capable clients).
-2. Captures sanitized, bounded lifecycle observations **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that agent CLIs invoke. Optional `ai-memory run` workstreams additionally read visible native transcript tails through host-side, read-only adapters.
+2. Captures sanitized, bounded lifecycle observations **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that agent CLIs invoke. User prompts and post-compaction summaries retain at most 16 KiB; notifications and tool excerpts retain at most 2 KB; every sanitized durable body has a 16 KiB backstop. Optional `ai-memory run` workstreams additionally read visible native transcript tails through host-side, read-only adapters.
3. Maintains a **Karpathy-style wiki**: incrementally-compiled markdown pages with cross-links, supersession, an `index.md` and a `log.md`.
4. Serves retrieval via the MCP `tools/list` to coding agents: a handful of *narrow* tools, not 50.
5. Ships a **Docker image** (`docker run -v ai-memory-data:/data -p 49374:49374 ai-memory`) so it can move between desktop and homelab.
@@ -139,7 +139,7 @@ Adopt agentmemory's tier model **but** keep the surface narrow:
| **Semantic** | Distilled facts/preferences/architecture notes - the wiki pages themselves | Indefinite, supersedeable | Versioned in place: old `is_latest=false`, new `supersedes=old_id` |
| **Procedural** | Repeated patterns extracted from episodic clusters (`pattern` type with frequency ≥ 2) | Indefinite | Frequency-decay if not re-observed in N days |
-**Implementation note:** the four tiers map to one `pages` table with a `tier` enum column + an `observations` table for raw working/episodic, not four separate tables. Keeps schema migrations sane.
+**Implementation note:** the four tiers map to one `pages` table with a `tier` enum column + an `observations` table for bounded working/episodic projections, not four separate tables. Keeps schema migrations sane.
## 8. Consolidation (the Karpathy bit)
diff --git a/docs/install.md b/docs/install.md
index 979f50ce..286e0fc7 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -392,6 +392,16 @@ Docker script bundles do not enforce it. Re-run `install-hooks --agent <agent>
capability output reflects the selected integration. See the canonical
[capture exclusions reference](marker-file.md#capture-exclusions).
+Lifecycle observation bodies are bounded separately from the 10 MiB HTTP
+request limit. User prompts and post-compaction summaries retain up to 16 KiB;
+notifications and tool excerpts retain up to 2 KB. Native `ai-memory hook`
+commands truncate those fields UTF-8-safely before they enter the local spool
+or wire. The server repeats the event-specific caps for every integration,
+including script and generated clients, then applies a 16 KiB backstop after
+sanitization before any observation reaches SQLite or FTS. Native hook commands
+invoke the installed binary directly, so upgrading that binary is enough to
+receive the client-side cap.
+
Some agent harnesses attach the assistant's final turn to their `Stop` event —
Claude Code sends it as a raw `last_assistant_message`. By default that text is
never persisted: the native hook binary strips the raw field before it can reach