Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(slots): address CodeRabbit review on #182

Rohit Ghumareb03e9702f2ee
diff --git a/README.md b/README.md
index 849a1638..8bdabde8 100644
--- a/README.md
+++ b/README.md
@@ -341,7 +341,7 @@ Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal t
<summary><b>OpenClaw (paste this prompt)</b></summary>
```
-Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 43 memory tools:
+Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 50 memory tools:
{
"mcpServers": {
@@ -363,7 +363,7 @@ Full guide: [`integrations/openclaw/`](integrations/openclaw/)
<summary><b>Hermes Agent (paste this prompt)</b></summary>
```
-Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 43 memory tools:
+Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 50 memory tools:
mcp_servers:
agentmemory:
@@ -595,7 +595,7 @@ npm install @xenova/transformers
50 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent.
-### 44 Tools
+### 50 Tools
<details>
<summary>Core tools (always available)</summary>
@@ -617,7 +617,7 @@ npm install @xenova/transformers
</details>
<details>
-<summary>Extended tools (44 total — set AGENTMEMORY_TOOLS=all)</summary>
+<summary>Extended tools (50 total — set AGENTMEMORY_TOOLS=all)</summary>
| Tool | Description |
|------|-------------|
@@ -901,7 +901,7 @@ Full endpoint list: [`src/triggers/api.ts`](src/triggers/api.ts)
Built on [iii-engine](https://iii.dev)'s three primitives — no Express, no Postgres, no Redis.
-**118 source files · ~21,800 LOC · 646 tests · 123 functions · 34 KV scopes**
+**118 source files · ~21,800 LOC · 800 tests · 123 functions · 34 KV scopes**
<details>
<summary>What iii-engine replaces</summary>
@@ -921,7 +921,7 @@ Built on [iii-engine](https://iii.dev)'s three primitives — no Express, no Pos
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 646 tests (~1.7s)
+npm test # 800 tests (~1.7s)
npm run test:integration # API tests (requires running services)
```
diff --git a/src/functions/slots.ts b/src/functions/slots.ts
index d18382d4..a6f61753 100644
--- a/src/functions/slots.ts
+++ b/src/functions/slots.ts
@@ -130,15 +130,37 @@ async function readSlot(
return { slot: null, scope: "project" };
}
+async function readSlotInScope(
+ kv: StateKV,
+ label: string,
+ scope: SlotScope,
+): Promise<MemorySlot | null> {
+ return kv.get<MemorySlot>(scopeKv(scope), label);
+}
+
+function validateScope(raw: unknown): SlotScope | null {
+ if (raw === undefined || raw === null) return "project";
+ if (raw === "project" || raw === "global") return raw;
+ return null;
+}
+
+function validateSizeLimit(raw: unknown): number | null | undefined {
+ if (raw === undefined || raw === null) return DEFAULT_SIZE_LIMIT;
+ if (typeof raw !== "number") return null;
+ if (!Number.isInteger(raw) || raw < 1 || raw > 20000) return null;
+ return raw;
+}
+
async function seedDefaults(kv: StateKV): Promise<void> {
+ const ts = nowIso();
for (const tmpl of DEFAULT_SLOTS) {
const target = scopeKv(tmpl.scope);
const existing = await kv.get<MemorySlot>(target, tmpl.label);
if (existing) continue;
const slot: MemorySlot = {
...tmpl,
- createdAt: nowIso(),
- updatedAt: nowIso(),
+ createdAt: ts,
+ updatedAt: ts,
};
await kv.set(target, tmpl.label, slot);
}
@@ -212,36 +234,43 @@ export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void {
}) => {
const label = validateLabel(data?.label);
if (!label) return { success: false, error: "label required (lowercase, starts with letter, [a-z0-9_])" };
- const { slot: existing } = await readSlot(kv, label);
- if (existing) return { success: false, error: "slot already exists" };
- const scope: SlotScope = data?.scope === "global" ? "global" : "project";
- const sizeLimit =
- typeof data?.sizeLimit === "number" && Number.isInteger(data.sizeLimit) && data.sizeLimit > 0 && data.sizeLimit <= 20000
- ? data.sizeLimit
- : DEFAULT_SIZE_LIMIT;
+ const scope = validateScope(data?.scope);
+ if (!scope) return { success: false, error: "scope must be 'project' or 'global'" };
+ const sizeLimit = validateSizeLimit(data?.sizeLimit);
+ if (sizeLimit === null) {
+ return { success: false, error: "sizeLimit must be an integer between 1 and 20000" };
+ }
const content = typeof data?.content === "string" ? data.content : "";
if (content.length > sizeLimit) {
return { success: false, error: `content exceeds sizeLimit (${content.length} > ${sizeLimit})` };
}
const description = typeof data?.description === "string" ? data.description : "";
- const slot: MemorySlot = {
- label,
- content,
- sizeLimit,
- description,
- pinned: data?.pinned !== false,
- readOnly: false,
- scope,
- createdAt: nowIso(),
- updatedAt: nowIso(),
- };
- await kv.set(scopeKv(scope), label, slot);
- await recordAudit(kv, "slot_create", "mem::slot-create", [label], {
- scope,
- sizeLimit,
- pinned: slot.pinned,
+ const pinned = typeof data?.pinned === "boolean" ? data.pinned : true;
+ return withKeyedLock(`slot:${label}`, async () => {
+ // Duplicate check is scope-local so a project slot can shadow a
+ // global slot with the same label — matches the read precedence.
+ const existing = await readSlotInScope(kv, label, scope);
+ if (existing) return { success: false, error: `slot already exists in ${scope} scope` };
+ const ts = nowIso();
+ const slot: MemorySlot = {
+ label,
+ content,
+ sizeLimit: sizeLimit as number,
+ description,
+ pinned,
+ readOnly: false,
+ scope,
+ createdAt: ts,
+ updatedAt: ts,
+ };
+ await kv.set(scopeKv(scope), label, slot);
+ await recordAudit(kv, "slot_create", "mem::slot-create", [label], {
+ scope,
+ sizeLimit: slot.sizeLimit,
+ pinned: slot.pinned,
+ });
+ return { success: true, slot };
});
- return { success: true, slot };
},
);
@@ -312,15 +341,17 @@ export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void {
async (data: { label?: string }) => {
const label = validateLabel(data?.label);
if (!label) return { success: false, error: "label required" };
- const { slot, scope } = await readSlot(kv, label);
- if (!slot) return { success: false, error: "slot not found" };
- if (slot.readOnly) return { success: false, error: "slot is read-only" };
- await kv.delete(scopeKv(scope), label);
- await recordAudit(kv, "slot_delete", "mem::slot-delete", [label], {
- scope,
- size: slot.content.length,
+ return withKeyedLock(`slot:${label}`, async () => {
+ const { slot, scope } = await readSlot(kv, label);
+ if (!slot) return { success: false, error: "slot not found" };
+ if (slot.readOnly) return { success: false, error: "slot is read-only" };
+ await kv.delete(scopeKv(scope), label);
+ await recordAudit(kv, "slot_delete", "mem::slot-delete", [label], {
+ scope,
+ size: slot.content.length,
+ });
+ return { success: true };
});
- return { success: true };
},
);
@@ -368,30 +399,31 @@ export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void {
let applied = 0;
if (pendingLines.length > 0) {
- const { slot, scope } = await readSlot(kv, "pending_items");
- if (slot) {
- await withKeyedLock(`slot:pending_items`, async () => {
- const already = new Set(slot.content.split("\n"));
- const fresh = pendingLines.filter((line) => !already.has(line));
- if (fresh.length === 0) return;
- const sep = slot.content && !slot.content.endsWith("\n") ? "\n" : "";
- const next = `${slot.content}${sep}${fresh.join("\n")}`;
- const truncated = next.length > slot.sizeLimit
- ? next.slice(next.length - slot.sizeLimit)
- : next;
- await kv.set(scopeKv(scope), "pending_items", {
- ...slot,
- content: truncated,
- updatedAt: nowIso(),
- });
- applied++;
+ const pendingApplied = await withKeyedLock(`slot:pending_items`, async () => {
+ const { slot, scope } = await readSlot(kv, "pending_items");
+ if (!slot) return false;
+ const already = new Set(slot.content.split("\n"));
+ const fresh = pendingLines.filter((line) => !already.has(line));
+ if (fresh.length === 0) return false;
+ const sep = slot.content && !slot.content.endsWith("\n") ? "\n" : "";
+ const next = `${slot.content}${sep}${fresh.join("\n")}`;
+ const truncated = next.length > slot.sizeLimit
+ ? next.slice(next.length - slot.sizeLimit)
+ : next;
+ await kv.set(scopeKv(scope), "pending_items", {
+ ...slot,
+ content: truncated,
+ updatedAt: nowIso(),
});
- }
+ return true;
+ });
+ if (pendingApplied) applied++;
}
if (patternCounts.size > 0) {
- const { slot, scope } = await readSlot(kv, "session_patterns");
- if (slot) {
+ const patternsApplied = await withKeyedLock(`slot:session_patterns`, async () => {
+ const { slot, scope } = await readSlot(kv, "session_patterns");
+ if (!slot) return false;
const summary = [
`last reflection: ${nowIso()}`,
...Array.from(patternCounts.entries()).map(
@@ -405,37 +437,38 @@ export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void {
content: next,
updatedAt: nowIso(),
});
- applied++;
- }
+ return true;
+ });
+ if (patternsApplied) applied++;
}
if (files.size > 0) {
- const { slot, scope } = await readSlot(kv, "project_context");
- if (slot) {
- await withKeyedLock(`slot:project_context`, async () => {
- const already = slot.content;
- const fresh = Array.from(files)
- .filter((f) => !already.includes(f))
- .slice(0, 20);
- if (fresh.length === 0) return;
- const header =
- already.length === 0 ? "Files touched in recent sessions:" : "";
- const sep = already && !already.endsWith("\n") ? "\n" : "";
- const nextRaw = `${already}${sep}${header ? header + "\n" : ""}${fresh
- .map((f) => `- ${f}`)
- .join("\n")}`;
- const next =
- nextRaw.length > slot.sizeLimit
- ? nextRaw.slice(nextRaw.length - slot.sizeLimit)
- : nextRaw;
- await kv.set(scopeKv(scope), "project_context", {
- ...slot,
- content: next,
- updatedAt: nowIso(),
- });
- applied++;
+ const ctxApplied = await withKeyedLock(`slot:project_context`, async () => {
+ const { slot, scope } = await readSlot(kv, "project_context");
+ if (!slot) return false;
+ const already = slot.content;
+ const fresh = Array.from(files)
+ .filter((f) => !already.includes(f))
+ .slice(0, 20);
+ if (fresh.length === 0) return false;
+ const header =
+ already.length === 0 ? "Files touched in recent sessions:" : "";
+ const sep = already && !already.endsWith("\n") ? "\n" : "";
+ const nextRaw = `${already}${sep}${header ? header + "\n" : ""}${fresh
+ .map((f) => `- ${f}`)
+ .join("\n")}`;
+ const next =
+ nextRaw.length > slot.sizeLimit
+ ? nextRaw.slice(nextRaw.length - slot.sizeLimit)
+ : nextRaw;
+ await kv.set(scopeKv(scope), "project_context", {
+ ...slot,
+ content: next,
+ updatedAt: nowIso(),
});
- }
+ return true;
+ });
+ if (ctxApplied) applied++;
}
if (applied > 0) {
diff --git a/src/index.ts b/src/index.ts
index 1d7cacd7..b21a5116 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -85,6 +85,7 @@ import { registerReplayFunctions } from "./functions/replay.js";
import { registerApiTriggers } from "./triggers/api.js";
import { registerEventTriggers } from "./triggers/events.js";
import { registerMcpEndpoints } from "./mcp/server.js";
+import { getAllTools } from "./mcp/tools-registry.js";
import { startViewerServer } from "./viewer/server.js";
import { MetricsStore } from "./eval/metrics-store.js";
import { DedupMap } from "./functions/dedup.js";
@@ -340,7 +341,7 @@ async function main() {
`[agentmemory] Ready. ${embeddingProvider ? "Triple-stream (BM25+Vector+Graph)" : "BM25+Graph"} search active.`,
);
console.log(
- `[agentmemory] Endpoints: 107 REST + 44 MCP tools + 6 MCP resources + 3 MCP prompts`,
+ `[agentmemory] Endpoints: 107 REST + ${getAllTools().length} MCP tools + 6 MCP resources + 3 MCP prompts`,
);
const viewerPort = config.restPort + 2;
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index a8fc45e8..21c2069a 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -1159,8 +1159,11 @@ export function registerMcpEndpoints(
if (typeof args.content === "string") payload.content = args.content;
if (typeof args.description === "string") payload.description = args.description;
if (typeof args.sizeLimit === "number") payload.sizeLimit = args.sizeLimit;
- if (args.pinned === "false") payload.pinned = false;
- if (args.scope === "global") payload.scope = "global";
+ // Accept boolean and string-boolean forms; MCP clients bind either
+ // depending on their JSON schema wrapper.
+ if (args.pinned === false || args.pinned === "false") payload.pinned = false;
+ else if (args.pinned === true || args.pinned === "true") payload.pinned = true;
+ if (args.scope === "global" || args.scope === "project") payload.scope = args.scope;
const result = await sdk.trigger({ function_id: "mem::slot-create", payload });
return {
status_code: 200,
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 8a8f20c2..ee9e643f 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1381,17 +1381,36 @@ export function registerApiTriggers(
const body = (req.body ?? {}) as Record<string, unknown>;
const label = asNonEmptyString(body["label"]);
if (!label) return { status_code: 400, body: { error: "label required" } };
- const payload: Record<string, unknown> = { label };
- const content = body["content"];
- if (typeof content === "string") payload["content"] = content;
- const description = asNonEmptyString(body["description"]);
- if (description) payload["description"] = description;
+ // Reject malformed inputs instead of silently dropping them.
+ if (body["content"] !== undefined && typeof body["content"] !== "string") {
+ return { status_code: 400, body: { error: "content must be a string" } };
+ }
+ if (body["description"] !== undefined && typeof body["description"] !== "string") {
+ return { status_code: 400, body: { error: "description must be a string" } };
+ }
+ if (body["pinned"] !== undefined && typeof body["pinned"] !== "boolean") {
+ return { status_code: 400, body: { error: "pinned must be a boolean" } };
+ }
+ if (
+ body["scope"] !== undefined &&
+ body["scope"] !== "project" &&
+ body["scope"] !== "global"
+ ) {
+ return { status_code: 400, body: { error: "scope must be 'project' or 'global'" } };
+ }
const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]);
- if (sizeLimit === null) return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } };
+ if (sizeLimit === null) {
+ return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } };
+ }
+ if (sizeLimit !== undefined && sizeLimit > 20000) {
+ return { status_code: 400, body: { error: "sizeLimit must be <= 20000" } };
+ }
+ const payload: Record<string, unknown> = { label };
+ if (typeof body["content"] === "string") payload["content"] = body["content"];
+ if (typeof body["description"] === "string") payload["description"] = body["description"];
if (sizeLimit !== undefined) payload["sizeLimit"] = sizeLimit;
if (typeof body["pinned"] === "boolean") payload["pinned"] = body["pinned"];
- const scope = body["scope"];
- if (scope === "project" || scope === "global") payload["scope"] = scope;
+ if (body["scope"] === "project" || body["scope"] === "global") payload["scope"] = body["scope"];
const result = await sdk.trigger({ function_id: "mem::slot-create", payload });
const resp = result as { success?: boolean; error?: string };
if (resp?.success === false) {
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 637f2027..418ccc88 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -2,6 +2,8 @@ import { TriggerAction, type ISdk } from "iii-sdk";
import type { HookPayload, Session } from "../types.js";
import { KV, STREAM } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
+import { isReflectEnabled } from "../functions/slots.js";
+import { logger } from "../logger.js";
export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
@@ -43,8 +45,15 @@ export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction("event::session::stopped", async (data: { sessionId: string }) => {
const summary = await sdk.trigger({ function_id: "mem::summarize", payload: data });
- if (process.env["AGENTMEMORY_REFLECT"] === "true") {
- sdk.triggerVoid("mem::slot-reflect", { sessionId: data.sessionId });
+ if (isReflectEnabled()) {
+ try {
+ sdk.triggerVoid("mem::slot-reflect", { sessionId: data.sessionId });
+ } catch (err) {
+ logger.warn("slot-reflect triggerVoid failed", {
+ sessionId: data.sessionId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
}
return summary;
});
diff --git a/test/slots.test.ts b/test/slots.test.ts
index b003fcd9..70da2aed 100644
--- a/test/slots.test.ts
+++ b/test/slots.test.ts
@@ -126,28 +126,18 @@ describe("slots — primitive", () => {
});
it("project slot shadows global slot of the same label", async () => {
- await kv.set(KV.globalSlots, "persona", {
- label: "persona",
- content: "global-persona",
- sizeLimit: 1000,
- description: "",
- pinned: true,
- readOnly: false,
- scope: "global",
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- });
- await kv.set(KV.slots, "persona", {
+ // Default seed already created a global `persona`. Populate it through
+ // the public handler, then create a project-scoped override through the
+ // same handler so scope validation + shadowing logic is exercised end
+ // to end (no direct kv.set).
+ await handlers["mem::slot-replace"]({ label: "persona", content: "global-persona" });
+ const createRes = (await handlers["mem::slot-create"]({
label: "persona",
content: "project-override",
- sizeLimit: 1000,
- description: "",
- pinned: true,
- readOnly: false,
scope: "project",
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- });
+ })) as { success: boolean };
+ expect(createRes.success).toBe(true);
+
const res = (await handlers["mem::slot-get"]({ label: "persona" })) as {
slot: { content: string };
scope: string;
@@ -156,6 +146,36 @@ describe("slots — primitive", () => {
expect(res.scope).toBe("project");
});
+ it("rejects invalid sizeLimit instead of silently defaulting", async () => {
+ const tooBig = (await handlers["mem::slot-create"]({
+ label: "oversize",
+ sizeLimit: 99999,
+ })) as { success: boolean; error: string };
+ expect(tooBig.success).toBe(false);
+ expect(tooBig.error).toMatch(/sizeLimit must be/);
+
+ const negative = (await handlers["mem::slot-create"]({
+ label: "negative",
+ sizeLimit: -1,
+ })) as { success: boolean; error: string };
+ expect(negative.success).toBe(false);
+
+ const nonInteger = (await handlers["mem::slot-create"]({
+ label: "fractional",
+ sizeLimit: 1.5,
+ })) as { success: boolean; error: string };
+ expect(nonInteger.success).toBe(false);
+ });
+
+ it("rejects unknown scope values", async () => {
+ const res = (await handlers["mem::slot-create"]({
+ label: "bad_scope",
+ scope: "wrong" as unknown as "project",
+ })) as { success: boolean; error: string };
+ expect(res.success).toBe(false);
+ expect(res.error).toMatch(/scope must be/);
+ });
+
it("listPinnedSlots returns only pinned slots with content", async () => {
await handlers["mem::slot-append"]({ label: "persona", text: "helpful senior engineer" });
const pinned = await listPinnedSlots(kv as never);