Skip to content

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

Rust

feat(mcp): cap memory_read_page bodies and shrink session-observation defaults

Aldo Junior0e9c0f75616c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e65cba04..7c274647 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,24 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Added
+
+- `memory_read_page` now accepts an optional `max_chars` (default 12000,
+ minimum 500, maximum 64000). It caps the returned body with the same visible
+ truncation marker that `memory_read_session_observations` already uses. The
+ response always carries `truncated` and `total_chars`, so a caller knows the
+ real size even when the body was not cut (#NNN).
+
+### Changed
+
+- `memory_read_session_observations` returns less by default: `limit` drops
+ from 50 to 20 and `body_max_chars` from 4000 to 1000. A caller that needs
+ more can still raise either one, up to the unchanged ceilings of 200 and
+ 16384. A routine "what did this session do" lookup is much cheaper this way.
+ The retrieval skill now documents a narrow `order="desc"` recipe, with a small
+ `kinds`, `limit` and `body_max_chars`, for that question instead of reading
+ the whole session (#NNN).
+
### Fixed
- Refused empty and whitespace-only `--workspace` and `--project` flags at the
diff --git a/companions/ai-memory-ts/CHANGELOG.md b/companions/ai-memory-ts/CHANGELOG.md
index 246da631..f504151a 100644
--- a/companions/ai-memory-ts/CHANGELOG.md
+++ b/companions/ai-memory-ts/CHANGELOG.md
@@ -13,6 +13,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `query` takes the server's `memory_query` page filters: `kind`, `tier`,
`pathPrefix` and `tag`, in every search mode.
+- `pages.read` takes `maxChars`, and `Page` carries `truncated` and
+ `totalChars`, matching the server's new `memory_read_page` size cap. Both are
+ `undefined` against a server that predates it. The documented `observations`
+ defaults are now 20 rows of 1000 characters.
+
## [0.1.0]
### Added
diff --git a/companions/ai-memory-ts/docs/arguments.md b/companions/ai-memory-ts/docs/arguments.md
index 4c764020..584aed5b 100644
--- a/companions/ai-memory-ts/docs/arguments.md
+++ b/companions/ai-memory-ts/docs/arguments.md
@@ -40,6 +40,7 @@ Methods: `pages.read`, `pages.update`
| `query` | `query` |
| `include_related` | `includeRelated` |
| `related_depth` | `relatedDepth` |
+| `max_chars` | `maxChars` |
## `memory_delete_page`
diff --git a/companions/ai-memory-ts/schema/tools.json b/companions/ai-memory-ts/schema/tools.json
index 5146a071..b914f9f8 100644
--- a/companions/ai-memory-ts/schema/tools.json
+++ b/companions/ai-memory-ts/schema/tools.json
@@ -678,6 +678,12 @@
"include_related": {
"type": "boolean"
},
+ "max_chars": {
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
"path": {
"type": [
"null",
diff --git a/companions/ai-memory-ts/src/client.ts b/companions/ai-memory-ts/src/client.ts
index 65bea6ce..1838c66e 100644
--- a/companions/ai-memory-ts/src/client.ts
+++ b/companions/ai-memory-ts/src/client.ts
@@ -244,6 +244,7 @@ export class PagesNamespace {
query: a.query,
include_related: a.includeRelated === true ? true : undefined,
related_depth: a.relatedDepth,
+ max_chars: a.maxChars,
}),
false,
options,
@@ -255,6 +256,8 @@ export class PagesNamespace {
path: str(o, "path", "memory_read_page"),
title: untrusted(str(o, "title", "memory_read_page")),
body: untrusted(str(o, "body", "memory_read_page")),
+ truncated: typeof o["truncated"] === "boolean" ? o["truncated"] : undefined,
+ totalChars: typeof o["total_chars"] === "number" ? o["total_chars"] : undefined,
frontmatter:
frontmatter !== null && typeof frontmatter === "object" && !Array.isArray(frontmatter)
? (frontmatter as Raw)
diff --git a/companions/ai-memory-ts/src/coverage.ts b/companions/ai-memory-ts/src/coverage.ts
index 944ef109..5ee0e3ed 100644
--- a/companions/ai-memory-ts/src/coverage.ts
+++ b/companions/ai-memory-ts/src/coverage.ts
@@ -61,7 +61,7 @@ export const TOOL_COVERAGE: Readonly<Record<string, ToolClassification>> = {
status: "wrapped",
methods: ["pages.read", "pages.update"],
phase: 1,
- sends: [...SCOPE, "path", "query", "include_related", "related_depth"],
+ sends: [...SCOPE, "path", "query", "include_related", "related_depth", "max_chars"],
},
memory_delete_page: {
status: "wrapped",
diff --git a/companions/ai-memory-ts/src/types.ts b/companions/ai-memory-ts/src/types.ts
index 5394f6a2..d38ce65b 100644
--- a/companions/ai-memory-ts/src/types.ts
+++ b/companions/ai-memory-ts/src/types.ts
@@ -108,6 +108,8 @@ export interface ReadPageBase extends ScopedArgs {
includeRelated?: boolean;
/** Hops to walk with `includeRelated` (default 1, capped at 3 by the server). */
relatedDepth?: number;
+ /** Cap the returned body at this many characters (default 12000, 500 to 64000). */
+ maxChars?: number;
}
/** Arguments of {@link PagesNamespace.read}: exactly one of `path` or `query`. */
@@ -153,8 +155,12 @@ export interface Page {
readonly path: string;
/** Page title. */
readonly title: UntrustedText;
- /** Markdown body. */
+ /** Markdown body, cut at `maxChars` with a visible marker when `truncated`. */
readonly body: UntrustedText;
+ /** Whether the server cut the body at `maxChars`. */
+ readonly truncated: boolean | undefined;
+ /** Length in characters of the untruncated body. */
+ readonly totalChars: number | undefined;
/** Parsed frontmatter (tags, tier, pinned and other metadata). Untrusted. */
readonly frontmatter: Readonly<Record<string, unknown>>;
/** Pages reachable through links, present only with `includeRelated`. */
@@ -515,7 +521,7 @@ export interface ObservationsArgs extends ScopedArgs {
* completed one when nothing worked in the last 30 days.
*/
sessionId?: string;
- /** Maximum observations (server default 50, clamped to 200). */
+ /** Maximum observations (server default 20, clamped to 200). */
limit?: number;
/** Observations to skip. */
offset?: number;
@@ -525,7 +531,7 @@ export interface ObservationsArgs extends ScopedArgs {
kinds?: ObservationKind[];
/** Full-text query restricted to the session. */
query?: string;
- /** Cap each body at this many characters (200 to 16384, default 4000). */
+ /** Cap each body at this many characters (200 to 16384, default 1000). */
bodyMaxChars?: number;
}
diff --git a/companions/ai-memory-ts/test/unit/client.test.ts b/companions/ai-memory-ts/test/unit/client.test.ts
index 185f4eed..326dd252 100644
--- a/companions/ai-memory-ts/test/unit/client.test.ts
+++ b/companions/ai-memory-ts/test/unit/client.test.ts
@@ -110,6 +110,24 @@ describe("pages", () => {
include_related: true,
related_depth: 2,
});
+ server.tools.set("memory_read_page", () => ({
+ ...payloads.read,
+ truncated: true,
+ total_chars: 40_000,
+ }));
+ const capped = await memory.pages.read({ path: "notes/retries.md", maxChars: 500 });
+ assert.deepEqual(server.lastArgs(), {
+ workspace: "demo",
+ project: "app",
+ path: "notes/retries.md",
+ max_chars: 500,
+ });
+ assert.equal(capped.truncated, true);
+ assert.equal(capped.totalChars, 40_000);
+ server.tools.set("memory_read_page", () => payloads.read);
+ const older = await memory.pages.read({ path: "notes/retries.md" });
+ assert.equal(older.truncated, undefined);
+ assert.equal(older.totalChars, undefined);
const before = server.requests.length;
await assert.rejects(
memory.pages.read({ path: "a", query: "b" } as never),
@@ -527,7 +545,7 @@ describe("wire names", () => {
expectedPageId: "v",
}),
memory.pages.write({ path: "p", body: "b", createOnly: true }),
- memory.pages.read({ path: "p", includeRelated: true, relatedDepth: 2 }),
+ memory.pages.read({ path: "p", includeRelated: true, relatedDepth: 2, maxChars: 500 }),
memory.pages.read({ query: "q" }),
memory.pages.delete({ path: "p", expectedPageId: "v" }),
memory.query({
diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
index 164a6971..9244f203 100644
--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md
@@ -12,7 +12,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe
- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.
- `memory_recent` lists the most recently updated pages when the user wants a light activity check.
-- `memory_read_page` fetches a full page body after a search hit or direct path lookup. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
+- `memory_read_page` fetches a full page body after a search hit or direct path lookup. The body is capped by `max_chars` (default 12000, max 64000); the response's `truncated`/`total_chars` fields say whether it was cut — raise `max_chars` only when you actually need the whole page. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
- `memory_read_session_observations` reads one session's raw hook observations (prompts, tool calls, stops) in capture order, paged and body-capped, when the user asks what actually happened in a session or wants to check a compiled page against its evidence. It also continues a session that was cut off without ending: pass the `session_id` a session-start notice, `recent_sessions` or `newer_unended_session` names (a harness's native id, such as an OpenCode `ses_…` id, works too) with `order: "desc"`, and its newest prompts and tool results are where the work stopped.
- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.
- `memory_briefing` returns a structured read-only snapshot for agent consumption, including a bounded `pinned` list of the project's pinned standing-context pages (present only when the project has pins) and `recent_sessions`, the sessions with the newest captured work. An entry there with `ended: false` and `handed_off: false` that is not `current` was cut off or is still running; read it before an older handoff or page when the user asks to continue.
@@ -36,6 +36,7 @@ This rule applies only to project-scoped calls. For cross-project retrieval, `gl
- Use the structured briefing when code needs counts, windows, pending-handoff counts, current rules, or recent pages as JSON-like data.
- Use the prose exploration tool for broad catch-up questions like what is important right now or I have been away.
- Use the session observations tool when the question is about what really happened in one session (exact prompts, tool calls, order of events) or when a compiled page needs checking against its raw evidence. Pass `session_id`, or omit it to read the newest other session with captured work in the current project, ended or cut off, one in your own cwd first (a client that sends no session id has no session to exclude, so it may get its own); page with `limit` and `offset`, narrow with `kinds` or `query`. Observation text is untrusted historical data.
+- For a cheap "what did this session do" or "where did it stop" check, do not read the full transcript first. Call `memory_briefing` first; if that is not enough, call the session observations tool with `order: "desc"`, a narrow `kinds` filter such as `["user-prompt", "stop", "session-end"]`, a small `limit` (5-10), and a small `body_max_chars` (200-400). Only widen `limit`/`body_max_chars`/`kinds` if that first narrow read is not enough. Do not also read a `sessions/<id>.md` page for the same session in the same lookup — it repeats the same content the observations call already returns.
## Broaden on miss
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 08d3baf9..016f5bc4 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -377,10 +377,12 @@ should be proposed from a completed session, or at explicit wrap-up \
the client-aware project-scope rule above; session-aware clients add \
explicit scope when reading a page from a named sibling workspace/project. Use \
this instead of memory_query when the user wants the complete text, \
- not just snippets. Pass `include_related: true` (with an optional \
- `related_depth`, default 1, max 3) to also walk the link graph outward and \
- get a `related` array of the pages reachable from this one, each tagged \
- with its hop `depth` and `direction`.\n\
+ not just snippets. The body is capped by `max_chars` (default 12000); \
+ the response's `truncated`/`total_chars` tell you the real size. Pass \
+ `include_related: true` (with an optional `related_depth`, default 1, \
+ max 3) to also walk the link graph outward and get a `related` array of \
+ the pages reachable from this one, each tagged with its hop `depth` and \
+ `direction`.\n\
- `memory_read_session_observations` — when the user asks what actually \
happened in a session, wants to check a compiled page against its raw \
evidence, or needs the exact prompt/tool text behind a `memory_query` \
@@ -1703,14 +1705,31 @@ struct ReadPageArgs {
/// Ignored when `include_related` is false.
#[serde(default)]
related_depth: Option<u8>,
+ /// Cap the returned body at this many characters (default 12000, min
+ /// 500, max 64000). Longer bodies end with a visible truncation marker
+ /// and the response adds `truncated: true` and `total_chars`. Raise
+ /// this only when you actually need the whole page; most callers should
+ /// keep the default.
+ #[serde(default)]
+ max_chars: Option<usize>,
}
+/// Bounds for `memory_read_page`'s `max_chars`. The default keeps a typical
+/// page read well under a context window while staying large enough that
+/// most pages never truncate; the ceiling still lets a caller read a long
+/// page whole by raising it explicitly.
+const READ_PAGE_DEFAULT_MAX_CHARS: usize = 12_000;
+const READ_PAGE_MIN_MAX_CHARS: usize = 500;
+const READ_PAGE_MAX_MAX_CHARS: usize = 64_000;
+
/// Bounds for `memory_read_session_observations`. The defaults keep one call
-/// well under a context window; the ceilings match what the store keeps per
-/// body (16 KiB) so a caller can always read a whole observation in one go.
-const SESSION_OBSERVATIONS_DEFAULT_LIMIT: usize = 50;
+/// cheap — a "what did this session do" lookup should cost low thousands of
+/// tokens, not tens of thousands — while the ceilings still match what the
+/// store keeps per body (16 KiB) so a caller can always read a whole
+/// observation in one go by raising `limit`/`body_max_chars` explicitly.
+const SESSION_OBSERVATIONS_DEFAULT_LIMIT: usize = 20;
const SESSION_OBSERVATIONS_MAX_LIMIT: usize = 200;
-const SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS: usize = 4_000;
+const SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS: usize = 1_000;
const SESSION_OBSERVATIONS_MIN_BODY_CHARS: usize = 200;
const SESSION_OBSERVATIONS_MAX_BODY_CHARS: usize = 16_384;
/// Sessions with recent work the default read scans for one in the caller's
@@ -1729,7 +1748,7 @@ struct ReadSessionObservationsArgs {
/// completed session.
#[serde(default)]
session_id: Option<String>,
- /// Maximum observations per call (default 50, max 200).
+ /// Maximum observations per call (default 20, max 200).
#[serde(default)]
limit: Option<usize>,
/// Observations to skip before the first returned one (default 0).
@@ -1749,7 +1768,7 @@ struct ReadSessionObservationsArgs {
/// restricted to this session. Omit to list the session in order.
#[serde(default)]
query: Option<String>,
- /// Cap each returned body at this many characters (default 4000, min
+ /// Cap each returned body at this many characters (default 1000, min
/// 200, max 16384). Longer bodies end with a visible truncation marker.
#[serde(default)]
body_max_chars: Option<usize>,
@@ -4881,6 +4900,12 @@ impl AiMemoryServer {
served from the DB fallback, and `expired: true` when the page's \
`expires_at` TTL has passed: an exact-path read still returns such a \
page, which `memory_query` and `memory_recent` no longer surface). \
+ The body is capped at `max_chars` \
+ (default 12000, max 64000) with a visible truncation marker when it \
+ is cut; the response always also carries `truncated` (bool) and \
+ `total_chars` (the untruncated length) so you know the real size \
+ even when it wasn't cut. Raise `max_chars` only when you need the \
+ whole page. \
\
Set `include_related: true` to also walk the link graph outward from \
this page and get a `related` array of the reachable pages, each with \
@@ -4922,6 +4947,10 @@ impl AiMemoryServer {
.as_deref()
.is_none_or(|s| s.trim().is_empty())
&& args.project.as_deref().is_none_or(|s| s.trim().is_empty());
+ let max_chars = args
+ .max_chars
+ .unwrap_or(READ_PAGE_DEFAULT_MAX_CHARS)
+ .clamp(READ_PAGE_MIN_MAX_CHARS, READ_PAGE_MAX_MAX_CHARS);
// A blank fill is not a supplied argument: an empty/whitespace `path`
// would otherwise fail as "invalid path: empty path" with `query` never
@@ -5053,12 +5082,17 @@ impl AiMemoryServer {
// frontmatter title was never filled otherwise read back
// titleless despite a proper `# Heading` (#599).
let title = ai_memory_wiki::derive_title(&md.frontmatter, &md.body, &page_path);
+ let total_chars = md.body.chars().count();
+ let truncated = total_chars > max_chars;
+ let body = cap_text_with_marker(&md.body, max_chars, "body");
ok_json(&annotate(serde_json::json!({
"path": page_path.to_string(),
"page_id": page_id.map(|id| id.to_string()),
"title": title,
- "body": md.body,
+ "body": body,
"frontmatter": md.frontmatter,
+ "truncated": truncated,
+ "total_chars": total_chars,
})))
}
Err(disk_err) if is_missing_wiki_file(&disk_err) => {
@@ -5077,13 +5111,18 @@ impl AiMemoryServer {
.and_then(|v| v.as_str())
.map(str::to_string)
.or(Some(stored.title));
+ let total_chars = stored.body.chars().count();
+ let truncated = total_chars > max_chars;
+ let body = cap_text_with_marker(&stored.body, max_chars, "body");
ok_json(&annotate(serde_json::json!({
"path": page_path.to_string(),
"page_id": page_id.map(|id| id.to_string()),
"title": title,
- "body": stored.body,
+ "body": body,
"frontmatter": frontmatter,
"served_from": "db-fallback",
+ "truncated": truncated,
+ "total_chars": total_chars,
})))
}
None => {
@@ -5146,9 +5185,9 @@ impl AiMemoryServer {
work visible to you in the resolved project, other than your own \
(one in your own cwd first; ended or not), or the latest completed \
one when nothing worked in the last 30 days. Pages with \
- `limit`/`offset` (default 50, max 200) and returns `total`, so loop on \
+ `limit`/`offset` (default 20, max 200) and returns `total`, so loop on \
`offset` to read more. `order` is `asc` (capture order) or `desc`; \
- `kinds` and `query` narrow the rows; `body_max_chars` (default 4000) \
+ `kinds` and `query` narrow the rows; `body_max_chars` (default 1000) \
caps each body with a visible truncation marker. Only rows that landed \
in the resolved project are returned; `elided_other_scope` counts rows \
the same session left in another project. Follow the client-aware \
@@ -13789,6 +13828,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -13832,6 +13872,7 @@ mod tests {
let err = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: Some(" ".into()),
path: None,
project: None,
@@ -13853,6 +13894,7 @@ mod tests {
let result = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: Some("zonkolite".into()),
path: Some(String::new()),
project: None,
@@ -13880,6 +13922,7 @@ mod tests {
let result = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: Some("no-such-term-anywhere".into()),
path: Some("notes/blankfill.md".into()),
project: None,
@@ -13944,6 +13987,7 @@ mod tests {
workspace: Some("practice".into()),
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -13999,6 +14043,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -14020,6 +14065,110 @@ mod tests {
);
}
+ /// A body under `max_chars` is returned whole, and `truncated`/
+ /// `total_chars` still report the real (untruncated) size — the caller
+ /// should not have to guess whether a short page was cut.
+ #[tokio::test]
+ async fn memory_read_page_reports_size_without_truncating_a_short_body() {
+ let (tmp, store, server, ws, proj) = setup_server().await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/short.md").unwrap(),
+ frontmatter: serde_json::json!({"title": "Short"}),
+ body: "a short body".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Short".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let page = call_tool_json(
+ server
+ .with_wiki(wiki)
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/short.md".into()),
+ project: None,
+ workspace: None,
+ include_related: false,
+ related_depth: None,
+ max_chars: None,
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap(),
+ );
+ assert_eq!(page["body"], "a short body");
+ assert_eq!(page["truncated"], false);
+ assert_eq!(page["total_chars"], "a short body".chars().count() as u64);
+ }
+
+ /// A body over `max_chars` is cut with a visible marker (default cap
+ /// 12000; this test passes an explicit small `max_chars` so it does not
+ /// depend on the exact default), and `truncated`/`total_chars` report
+ /// the real size so a caller knows to raise `max_chars` if it needs more.
+ #[tokio::test]
+ async fn memory_read_page_truncates_a_long_body_with_marker() {
+ let (tmp, store, server, ws, proj) = setup_server().await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let long_body = "x".repeat(2_000);
+ wiki.write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new("notes/long.md").unwrap(),
+ frontmatter: serde_json::json!({"title": "Long"}),
+ body: long_body.clone(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Long".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+
+ let page = call_tool_json(
+ server
+ .with_wiki(wiki)
+ .memory_read_page(
+ Parameters(ReadPageArgs {
+ query: None,
+ path: Some("notes/long.md".into()),
+ project: None,
+ workspace: None,
+ include_related: false,
+ related_depth: None,
+ max_chars: Some(500),
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .unwrap(),
+ );
+ let body = page["body"].as_str().unwrap();
+ assert!(
+ body.starts_with(&"x".repeat(500)),
+ "must keep the first max_chars characters; got {body}"
+ );
+ assert!(
+ body.contains("[body truncated; 1500 chars omitted]"),
+ "body must end with a visible marker; got {body}"
+ );
+ assert_eq!(page["truncated"], true);
+ assert_eq!(page["total_chars"], 2_000);
+ }
+
#[tokio::test]
async fn memory_read_page_marks_an_expired_page() {
let (tmp, store, server, ws, proj) = setup_server().await;
@@ -14077,6 +14226,7 @@ mod tests {
let result = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some(path.into()),
project: None,
@@ -14123,6 +14273,7 @@ mod tests {
let err = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some("notes/does-not-exist.md".into()),
project: Some("scratch".into()),
@@ -14143,6 +14294,7 @@ mod tests {
let err = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: Some("zzzz-no-such-term".into()),
path: None,
project: Some("scratch".into()),
@@ -14174,6 +14326,7 @@ mod tests {
let err = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some("blocked.md".into()),
project: Some("scratch".into()),
@@ -14209,6 +14362,7 @@ mod tests {
workspace: Some("default".into()),
include_related: false,
related_depth: None,
+ max_chars: None,
}),
test_optional_parts(),
)
@@ -14234,6 +14388,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
test_optional_parts(),
)
@@ -17137,6 +17292,7 @@ mod tests {
let err = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some("../x.md".into()),
project: None,
@@ -17411,6 +17567,7 @@ mod tests {
server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("notes/keep.md".into()),
@@ -17459,6 +17616,7 @@ mod tests {
let seeded = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("notes/keep.md".into()),
@@ -17525,6 +17683,7 @@ mod tests {
&server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("notes/keep.md".into()),
@@ -17567,6 +17726,7 @@ mod tests {
server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("notes/keep.md".into()),
@@ -17822,6 +17982,7 @@ mod tests {
server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("preferences.md".into()),
@@ -18085,6 +18246,7 @@ mod tests {
server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("profile/tools/pnpm.md".into()),
@@ -18554,6 +18716,7 @@ mod tests {
server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: false,
related_depth: None,
path: Some("secrets/rates.md".into()),
@@ -18684,6 +18847,7 @@ mod tests {
let result = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
include_related: true,
related_depth: Some(3),
path: Some("notes/a.md".into()),
@@ -19378,6 +19542,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -19463,6 +19628,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -19605,6 +19771,7 @@ mod tests {
&server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some("notes/retries.md".into()),
project: None,
@@ -19842,6 +20009,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -19963,6 +20131,7 @@ mod tests {
workspace: Some("alpha".into()),
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -19982,6 +20151,7 @@ mod tests {
workspace: Some("beta".into()),
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(test_parts_default()),
)
@@ -20806,6 +20976,7 @@ mod tests {
workspace: None,
include_related: false,
related_depth: None,
+ max_chars: None,
}),
OptionalParts(alice_parts),
)
@@ -23075,6 +23246,7 @@ mod tests {
let result = server
.memory_read_page(
Parameters(ReadPageArgs {
+ max_chars: None,
query: None,
path: Some(path.into()),
project: Some("scratch".into()),
diff --git a/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs b/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
index 645220dd..57ed5ab0 100644
--- a/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
+++ b/crates/ai-memory-mcp/tests/suite/access_reinforcement.rs
@@ -285,7 +285,15 @@ async fn read_page_response_payload_unchanged() {
keys.sort_unstable();
assert_eq!(
keys,
- vec!["body", "frontmatter", "page_id", "path", "title"],
+ vec![
+ "body",
+ "frontmatter",
+ "page_id",
+ "path",
+ "title",
+ "total_chars",
+ "truncated"
+ ],
"reinforcement must not add fields to the read_page payload: {resp}"
);
}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 05437ef1..3e865c30 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -736,7 +736,7 @@ does not need to ride on the public protocol change.
|---|---|---|
| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF + observation-evidence stream (on by default) search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; single-project calls (project implicit or named with `workspace`+`project`) also union the reserved `_global` preferences scope as `global_scope_hits`, and only an explicit multi-`scopes` set opts out (#930); `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, the matched observation ids when the observation stream voted, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list and a `timings` object with each stream's wall time in milliseconds (`fts_ms`, `entity_ms`, `vector_ms` for the stored-vector scans, `graph_ms`, `observation_ms`, `rerank_ms`; a stream that did not run is left out, and `scopes` searches sum per stream). Timings are read only on an explained query; the normal path takes no clock reading for them. The global FTS-only ranker reports its active stream and `fts_ms` without per-hit details; `as_of` reports no timings. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`. Citation paths must identify exactly one supplied page version, including supplemental preferences. Repeated citations are deduplicated in model order. An unknown path or a path shared by distinct page IDs withholds the whole answer and returns `answer_unavailable` with the unchanged retrieval hits; this includes same-path historical versions. Empty citations remain valid for abstention. This validates source identity, not the truth of generated claims. With no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Answer quality is not yet eval-validated. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). Optional `kind`, `tag`, `tier` and `path_prefix` filters narrow candidates before ranking, on every stream including the CJK substring search. |
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
-| `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). The response carries the page's current version as `page_id`, the value compare-and-write calls pass back. A page whose `expires_at` TTL has passed is still returned and carries `expired: true`; a live page's response has no such field. |
+| `memory_read_page` | read-only | Fetch the body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. The body is capped by `max_chars` (default 12000, max 64000); responses include `truncated` and `total_chars`. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). The response carries the page's current version as `page_id`, the value compare-and-write calls pass back. A page whose `expires_at` TTL has passed is still returned and carries `expired: true`; a live page's response has no such field. |
| `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the visible session with the newest captured work other than the caller's own, ended or cut off (`ReaderPool::recent_session_activity` over 30 days, preferring the caller session's cwd), else the latest completed visible session. |
| `memory_status` | read-only | Counts, paths, version, plus the `scope` that answered: `workspace`, `project`, and `resolved_by` (`explicit`, `session`, `shared_slot`, `startup_seed`, `default`, `default_after_mismatch`). Unscoped reads resolved by `startup_seed` or `default_after_mismatch` also log a server warning. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Project-scoped snapshots also carry a bounded `pinned` list (up to 10) of the project's pinned latest pages (`pinned = 1`, newest first) as standing SessionStart hot-context, distinct from `slots`, which is keyed by the `_slots/` path prefix; empty and omitted from JSON when the project has no pins, so the default shape is unchanged. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. `scope` names the workspace/project briefed and `resolved_by` how it was chosen. |
diff --git a/docs/usage.md b/docs/usage.md
index a0de1c9e..5c1d2bae 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -249,6 +249,21 @@ a page: a query aimed at a session-specific term can still return that session.
`pinned` remains primarily a retention and automation-mutation control, not an
unconditional search override.
+### Keep a lookup cheap
+
+`memory_read_session_observations` defaults to 20 rows of up to 1000 characters
+each, and `memory_read_page` defaults to a 12,000-character cap. Both are
+read-only, and both accept a bigger `limit`, `body_max_chars` or `max_chars`
+when you need the full transcript or page. For a question like "what did this
+session do" or "where did it stop", a narrow `order: "desc"` read with a `kinds`
+filter such as `["user-prompt", "stop", "session-end"]` is usually enough.
+
+The other lever is the asking session, not ai-memory. A question sent into a
+long-idle agent session re-caches that session's entire context before the first
+tool call runs, and every later tool call re-reads it. A quick lookup like this
+costs far less in a fresh session or a subagent than appended to one that has
+been idle for hours.
+
## Search from the terminal
`ai-memory search` runs an FTS5 query against the wiki from a shell. It skips
diff --git a/plugins/claude-code/skills/ai-memory-retrieval/SKILL.md b/plugins/claude-code/skills/ai-memory-retrieval/SKILL.md
index 164a6971..9244f203 100644
--- a/plugins/claude-code/skills/ai-memory-retrieval/SKILL.md
+++ b/plugins/claude-code/skills/ai-memory-retrieval/SKILL.md
@@ -12,7 +12,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe
- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.
- `memory_recent` lists the most recently updated pages when the user wants a light activity check.
-- `memory_read_page` fetches a full page body after a search hit or direct path lookup. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
+- `memory_read_page` fetches a full page body after a search hit or direct path lookup. The body is capped by `max_chars` (default 12000, max 64000); the response's `truncated`/`total_chars` fields say whether it was cut — raise `max_chars` only when you actually need the whole page. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
- `memory_read_session_observations` reads one session's raw hook observations (prompts, tool calls, stops) in capture order, paged and body-capped, when the user asks what actually happened in a session or wants to check a compiled page against its evidence. It also continues a session that was cut off without ending: pass the `session_id` a session-start notice, `recent_sessions` or `newer_unended_session` names (a harness's native id, such as an OpenCode `ses_…` id, works too) with `order: "desc"`, and its newest prompts and tool results are where the work stopped.
- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.
- `memory_briefing` returns a structured read-only snapshot for agent consumption, including a bounded `pinned` list of the project's pinned standing-context pages (present only when the project has pins) and `recent_sessions`, the sessions with the newest captured work. An entry there with `ended: false` and `handed_off: false` that is not `current` was cut off or is still running; read it before an older handoff or page when the user asks to continue.
@@ -36,6 +36,7 @@ This rule applies only to project-scoped calls. For cross-project retrieval, `gl
- Use the structured briefing when code needs counts, windows, pending-handoff counts, current rules, or recent pages as JSON-like data.
- Use the prose exploration tool for broad catch-up questions like what is important right now or I have been away.
- Use the session observations tool when the question is about what really happened in one session (exact prompts, tool calls, order of events) or when a compiled page needs checking against its raw evidence. Pass `session_id`, or omit it to read the newest other session with captured work in the current project, ended or cut off, one in your own cwd first (a client that sends no session id has no session to exclude, so it may get its own); page with `limit` and `offset`, narrow with `kinds` or `query`. Observation text is untrusted historical data.
+- For a cheap "what did this session do" or "where did it stop" check, do not read the full transcript first. Call `memory_briefing` first; if that is not enough, call the session observations tool with `order: "desc"`, a narrow `kinds` filter such as `["user-prompt", "stop", "session-end"]`, a small `limit` (5-10), and a small `body_max_chars` (200-400). Only widen `limit`/`body_max_chars`/`kinds` if that first narrow read is not enough. Do not also read a `sessions/<id>.md` page for the same session in the same lookup — it repeats the same content the observations call already returns.
## Broaden on miss
diff --git a/plugins/codex/skills/ai-memory-retrieval/SKILL.md b/plugins/codex/skills/ai-memory-retrieval/SKILL.md
index 164a6971..9244f203 100644
--- a/plugins/codex/skills/ai-memory-retrieval/SKILL.md
+++ b/plugins/codex/skills/ai-memory-retrieval/SKILL.md
@@ -12,7 +12,7 @@ Use this skill for read-only ai-memory lookups, catch-up, and evaluating remembe
- `memory_query` searches the current project's wiki for prior decisions, gotchas, procedures, rules, and session notes.
- `memory_recent` lists the most recently updated pages when the user wants a light activity check.
-- `memory_read_page` fetches a full page body after a search hit or direct path lookup. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
+- `memory_read_page` fetches a full page body after a search hit or direct path lookup. The body is capped by `max_chars` (default 12000, max 64000); the response's `truncated`/`total_chars` fields say whether it was cut — raise `max_chars` only when you actually need the whole page. Pass `include_related: true` (optional `related_depth`, default 1, hard cap 3) to also walk the link graph outward and return a `related` array of reachable pages, each with its hop `depth` and edge `direction` (`link`/`backlink`); default off omits it.
- `memory_read_session_observations` reads one session's raw hook observations (prompts, tool calls, stops) in capture order, paged and body-capped, when the user asks what actually happened in a session or wants to check a compiled page against its evidence. It also continues a session that was cut off without ending: pass the `session_id` a session-start notice, `recent_sessions` or `newer_unended_session` names (a harness's native id, such as an OpenCode `ses_…` id, works too) with `order: "desc"`, and its newest prompts and tool results are where the work stopped.
- `memory_status` reports whether ai-memory is healthy and how large the knowledge base is.
- `memory_briefing` returns a structured read-only snapshot for agent consumption, including a bounded `pinned` list of the project's pinned standing-context pages (present only when the project has pins) and `recent_sessions`, the sessions with the newest captured work. An entry there with `ended: false` and `handed_off: false` that is not `current` was cut off or is still running; read it before an older handoff or page when the user asks to continue.
@@ -36,6 +36,7 @@ This rule applies only to project-scoped calls. For cross-project retrieval, `gl
- Use the structured briefing when code needs counts, windows, pending-handoff counts, current rules, or recent pages as JSON-like data.
- Use the prose exploration tool for broad catch-up questions like what is important right now or I have been away.
- Use the session observations tool when the question is about what really happened in one session (exact prompts, tool calls, order of events) or when a compiled page needs checking against its raw evidence. Pass `session_id`, or omit it to read the newest other session with captured work in the current project, ended or cut off, one in your own cwd first (a client that sends no session id has no session to exclude, so it may get its own); page with `limit` and `offset`, narrow with `kinds` or `query`. Observation text is untrusted historical data.
+- For a cheap "what did this session do" or "where did it stop" check, do not read the full transcript first. Call `memory_briefing` first; if that is not enough, call the session observations tool with `order: "desc"`, a narrow `kinds` filter such as `["user-prompt", "stop", "session-end"]`, a small `limit` (5-10), and a small `body_max_chars` (200-400). Only widen `limit`/`body_max_chars`/`kinds` if that first narrow read is not enough. Do not also read a `sessions/<id>.md` page for the same session in the same lookup — it repeats the same content the observations call already returns.
## Broaden on miss