Skip to content

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

fix: address 12 code review findings across validation, safety, and correctness

Rohit Ghumare0e9d5ac76f3b
diff --git a/plugin/scripts/post-tool-failure.mjs b/plugin/scripts/post-tool-failure.mjs
index e062106b..c3d4c2df 100755
--- a/plugin/scripts/post-tool-failure.mjs
+++ b/plugin/scripts/post-tool-failure.mjs
@@ -30,8 +30,8 @@ async function main() {
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
data: {
tool_name: data.tool_name,
- tool_input: data.tool_input,
- error: data.error
+ tool_input: typeof data.tool_input === "string" ? data.tool_input.slice(0, 4e3) : JSON.stringify(data.tool_input ?? "").slice(0, 4e3),
+ error: typeof data.error === "string" ? data.error.slice(0, 4e3) : JSON.stringify(data.error ?? "").slice(0, 4e3)
}
}),
signal: AbortSignal.timeout(3e3)
diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs
index 2a957472..5cd84f9a 100755
--- a/plugin/scripts/pre-tool-use.mjs
+++ b/plugin/scripts/pre-tool-use.mjs
@@ -27,12 +27,13 @@ async function main() {
].includes(toolName)) return;
const toolInput = data.tool_input || {};
const files = [];
- for (const key of [
+ const fileKeys = toolName === "Grep" ? ["path", "file"] : [
"file_path",
"path",
"file",
"pattern"
- ]) {
+ ];
+ for (const key of fileKeys) {
const val = toolInput[key];
if (typeof val === "string" && val.length > 0) files.push(val);
}
diff --git a/plugin/scripts/subagent-stop.mjs b/plugin/scripts/subagent-stop.mjs
index 9a08e5c0..ad78b4f2 100755
--- a/plugin/scripts/subagent-stop.mjs
+++ b/plugin/scripts/subagent-stop.mjs
@@ -34,7 +34,7 @@ async function main() {
last_message: lastMsg
}
}),
- signal: AbortSignal.timeout(3e3)
+ signal: AbortSignal.timeout(2e3)
});
} catch {}
}
diff --git a/plugin/skills/recall/SKILL.md b/plugin/skills/recall/SKILL.md
index b8afdd67..3d5824d9 100644
--- a/plugin/skills/recall/SKILL.md
+++ b/plugin/skills/recall/SKILL.md
@@ -7,7 +7,7 @@ user-invocable: true
Search agentmemory for observations matching: $ARGUMENTS
-!`curl -s -H "Content-Type: application/json" -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" -X POST http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/search -d "{\"query\": \"$ARGUMENTS\", \"limit\": 10}" 2>/dev/null || echo '{"results":[]}'`
+!`QUERY=$(echo "$ARGUMENTS" | sed 's/\\/\\\\/g; s/"/\\"/g') && curl -s -H "Content-Type: application/json" -H "Authorization: Bearer ${AGENTMEMORY_SECRET:-}" -X POST http://${AGENTMEMORY_URL:-localhost:3111}/agentmemory/search -d "{\"query\": \"${QUERY}\", \"limit\": 10}" 2>/dev/null || echo '{"results":[]}'`
Present the search results to the user in a readable format:
- Group by session
diff --git a/src/functions/consolidate.ts b/src/functions/consolidate.ts
index 71f509ac..9e433273 100644
--- a/src/functions/consolidate.ts
+++ b/src/functions/consolidate.ts
@@ -68,7 +68,7 @@ export function registerConsolidateFunction(
{ id: "mem::consolidate" },
async (data: { project?: string; minObservations?: number }) => {
const ctx = getContext();
- const minObs = data.minObservations || 10;
+ const minObs = data.minObservations ?? 10;
const sessions = await kv.list<Session>(KV.sessions);
const filtered = data.project
@@ -122,10 +122,15 @@ export function registerConsolidateFunction(
.join("\n\n");
try {
- const response = await provider.compress(
- CONSOLIDATION_SYSTEM,
- `Concept: "${concept}"\n\nObservations:\n${prompt}`,
- );
+ const response = await Promise.race([
+ provider.compress(
+ CONSOLIDATION_SYSTEM,
+ `Concept: "${concept}"\n\nObservations:\n${prompt}`,
+ ),
+ new Promise<never>((_, reject) =>
+ setTimeout(() => reject(new Error("compress timeout")), 30_000),
+ ),
+ ]);
const parsed = parseMemoryXml(response, sessionIds);
if (!parsed) continue;
diff --git a/src/functions/file-index.ts b/src/functions/file-index.ts
index 751e30da..00509406 100644
--- a/src/functions/file-index.ts
+++ b/src/functions/file-index.ts
@@ -20,27 +20,36 @@ interface FileHistory {
export function registerFileIndexFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
{ id: "mem::file-context" },
- async (data: { sessionId: string; files: string[] }) => {
+ async (data: { sessionId: string; files: string[]; project?: string }) => {
const ctx = getContext();
const results: FileHistory[] = [];
const sessions = await kv.list<Session>(KV.sessions);
- const otherSessions = sessions
- .filter((s) => s.id !== data.sessionId)
+ let otherSessions = sessions.filter((s) => s.id !== data.sessionId);
+ if (data.project) {
+ otherSessions = otherSessions.filter((s) => s.project === data.project);
+ }
+ otherSessions = otherSessions
.sort(
(a, b) =>
new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime(),
)
.slice(0, 15);
+ const obsCache = new Map<string, CompressedObservation[]>();
+ for (const session of otherSessions) {
+ obsCache.set(
+ session.id,
+ await kv.list<CompressedObservation>(KV.observations(session.id)),
+ );
+ }
+
for (const file of data.files) {
const history: FileHistory = { file, observations: [] };
const normalizedFile = file.replace(/^\.\//, "");
for (const session of otherSessions) {
- const observations = await kv.list<CompressedObservation>(
- KV.observations(session.id),
- );
+ const observations = obsCache.get(session.id) || [];
for (const obs of observations) {
if (!obs.files || !obs.title) continue;
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index db8e50ba..edb9481e 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -31,8 +31,8 @@ export function registerObserveFunction(sdk: ISdk, kv: StateKV): void {
raw: sanitizedRaw,
};
- if (typeof payload.data === "object" && payload.data !== null) {
- const d = payload.data as Record<string, unknown>;
+ if (typeof sanitizedRaw === "object" && sanitizedRaw !== null) {
+ const d = sanitizedRaw as Record<string, unknown>;
if (
payload.hookType === "post_tool_use" ||
payload.hookType === "post_tool_failure"
diff --git a/src/functions/patterns.ts b/src/functions/patterns.ts
index 4e23ce14..97ef4345 100644
--- a/src/functions/patterns.ts
+++ b/src/functions/patterns.ts
@@ -47,7 +47,7 @@ export function registerPatternsFunction(sdk: ISdk, kv: StateKV): void {
}
if (obs.type === "error" && obs.title) {
- const key = obs.title.toLowerCase().slice(0, 80);
+ const key = obs.title.toLowerCase();
if (!errorPatterns.has(key)) {
errorPatterns.set(key, { count: 0, sessions: new Set() });
}
diff --git a/src/functions/remember.ts b/src/functions/remember.ts
index be3839e1..7f5588a3 100644
--- a/src/functions/remember.ts
+++ b/src/functions/remember.ts
@@ -14,6 +14,9 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
files?: string[];
}) => {
const ctx = getContext();
+ if (!data.content || !data.content.trim()) {
+ return { success: false, error: "content is required" };
+ }
const validTypes = new Set([
"pattern",
"preference",
@@ -65,7 +68,7 @@ export function registerRememberFunction(sdk: ISdk, kv: StateKV): void {
deleted++;
}
- if (data.observationIds && data.sessionId) {
+ if (data.observationIds?.length && data.sessionId) {
for (const obsId of data.observationIds) {
await kv.delete(KV.observations(data.sessionId), obsId);
deleted++;
diff --git a/src/hooks/post-tool-failure.ts b/src/hooks/post-tool-failure.ts
index 97646720..7bf9668b 100644
--- a/src/hooks/post-tool-failure.ts
+++ b/src/hooks/post-tool-failure.ts
@@ -38,8 +38,14 @@ async function main() {
timestamp: new Date().toISOString(),
data: {
tool_name: data.tool_name,
- tool_input: data.tool_input,
- error: data.error,
+ tool_input:
+ typeof data.tool_input === "string"
+ ? data.tool_input.slice(0, 4000)
+ : JSON.stringify(data.tool_input ?? "").slice(0, 4000),
+ error:
+ typeof data.error === "string"
+ ? data.error.slice(0, 4000)
+ : JSON.stringify(data.error ?? "").slice(0, 4000),
},
}),
signal: AbortSignal.timeout(3000),
diff --git a/src/hooks/pre-tool-use.ts b/src/hooks/pre-tool-use.ts
index e74c1099..dbc4a9c0 100644
--- a/src/hooks/pre-tool-use.ts
+++ b/src/hooks/pre-tool-use.ts
@@ -30,7 +30,11 @@ async function main() {
const toolInput = (data.tool_input || {}) as Record<string, unknown>;
const files: string[] = [];
- for (const key of ["file_path", "path", "file", "pattern"]) {
+ const fileKeys =
+ toolName === "Grep"
+ ? ["path", "file"]
+ : ["file_path", "path", "file", "pattern"];
+ for (const key of fileKeys) {
const val = toolInput[key];
if (typeof val === "string" && val.length > 0) files.push(val);
}
diff --git a/src/hooks/subagent-stop.ts b/src/hooks/subagent-stop.ts
index f2756ac1..5b96947a 100644
--- a/src/hooks/subagent-stop.ts
+++ b/src/hooks/subagent-stop.ts
@@ -23,9 +23,10 @@ async function main() {
}
const sessionId = (data.session_id as string) || "unknown";
- const lastMsg = typeof data.last_assistant_message === "string"
- ? data.last_assistant_message.slice(0, 4000)
- : "";
+ const lastMsg =
+ typeof data.last_assistant_message === "string"
+ ? data.last_assistant_message.slice(0, 4000)
+ : "";
try {
await fetch(`${REST_URL}/agentmemory/observe`, {
@@ -43,7 +44,7 @@ async function main() {
last_message: lastMsg,
},
}),
- signal: AbortSignal.timeout(3000),
+ signal: AbortSignal.timeout(2000),
});
} catch {
// fire and forget
diff --git a/src/index.ts b/src/index.ts
index c5f175e1..0ba06f60 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -67,7 +67,9 @@ async function main() {
console.log(` POST /agentmemory/context - Generate context`);
console.log(` POST /agentmemory/search - Search observations`);
console.log(` POST /agentmemory/summarize - Summarize session`);
- console.log(` POST /agentmemory/remember - Save to long-term memory`);
+ console.log(
+ ` POST /agentmemory/remember - Save to long-term memory`,
+ );
console.log(` POST /agentmemory/forget - Delete memory data`);
console.log(` POST /agentmemory/file-context - File history context`);
console.log(` POST /agentmemory/consolidate - Consolidate memories`);
@@ -78,6 +80,9 @@ async function main() {
);
console.log(` GET /agentmemory/health - Health check`);
console.log(` GET /agentmemory/viewer - Web viewer`);
+ console.log(
+ ` POST /agentmemory/generate-rules - Generate rules from patterns`,
+ );
console.log(` POST /agentmemory/migrate - Import from SQLite`);
console.log(` GET /agentmemory/mcp/tools - MCP tool listing`);
console.log(` POST /agentmemory/mcp/call - MCP tool execution`);
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index d53b586e..e4a19b0e 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -94,7 +94,8 @@ const MCP_TOOLS: McpTool[] = [
properties: {
project: {
type: "string",
- description: "Project path to analyze (optional, analyzes all if omitted)",
+ description:
+ "Project path to analyze (optional, analyzes all if omitted)",
},
},
},
@@ -149,64 +150,134 @@ export function registerMcpEndpoints(
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const { name, arguments: args } = req.body;
+ if (!req.body || typeof req.body.name !== "string") {
+ return { status_code: 400, body: { error: "name is required" } };
+ }
- switch (name) {
- case "memory_recall": {
- const result = await sdk.trigger("mem::search", {
- query: args.query as string,
- limit: (args.limit as number) || 10,
- });
- return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
- }
+ const { name, arguments: args = {} } = req.body;
- case "memory_save": {
- const content = args.content as string;
- const type = (args.type as string) || "fact";
- const concepts = args.concepts
- ? (args.concepts as string).split(",").map((c: string) => c.trim())
- : [];
- const files = args.files
- ? (args.files as string).split(",").map((f: string) => f.trim())
- : [];
+ try {
+ switch (name) {
+ case "memory_recall": {
+ if (typeof args.query !== "string" || !args.query.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "query is required for memory_recall" },
+ };
+ }
+ const result = await sdk.trigger("mem::search", {
+ query: args.query,
+ limit: (args.limit as number) || 10,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(result, null, 2) },
+ ],
+ },
+ };
+ }
- const result = await sdk.trigger("mem::remember", {
- content,
- type,
- concepts,
- files,
- });
- return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result) }] } };
- }
+ case "memory_save": {
+ if (typeof args.content !== "string" || !args.content.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "content is required for memory_save" },
+ };
+ }
+ const type = (args.type as string) || "fact";
+ const concepts = args.concepts
+ ? (args.concepts as string)
+ .split(",")
+ .map((c: string) => c.trim())
+ : [];
+ const files = args.files
+ ? (args.files as string).split(",").map((f: string) => f.trim())
+ : [];
- case "memory_file_history": {
- const fileList = (args.files as string)
- .split(",")
- .map((f: string) => f.trim());
- const result = await sdk.trigger("mem::file-context", {
- sessionId: (args.sessionId as string) || "",
- files: fileList,
- });
- return { status_code: 200, body: { content: [{ type: "text", text: (result as { context: string }).context || "No history found." }] } };
- }
+ const result = await sdk.trigger("mem::remember", {
+ content: args.content,
+ type,
+ concepts,
+ files,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [{ type: "text", text: JSON.stringify(result) }],
+ },
+ };
+ }
- case "memory_patterns": {
- const result = await sdk.trigger("mem::patterns", {
- project: args.project as string,
- });
- return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] } };
- }
+ case "memory_file_history": {
+ if (typeof args.files !== "string" || !args.files.trim()) {
+ return {
+ status_code: 400,
+ body: { error: "files is required for memory_file_history" },
+ };
+ }
+ const fileList = (args.files as string)
+ .split(",")
+ .map((f: string) => f.trim());
+ const result = await sdk.trigger("mem::file-context", {
+ sessionId: (args.sessionId as string) || "",
+ files: fileList,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ {
+ type: "text",
+ text:
+ (result as { context: string }).context ||
+ "No history found.",
+ },
+ ],
+ },
+ };
+ }
- case "memory_sessions": {
- const sessions = await kv.list(KV.sessions);
- return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify({ sessions }, null, 2) }] } };
- }
+ case "memory_patterns": {
+ const result = await sdk.trigger("mem::patterns", {
+ project: args.project as string,
+ });
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify(result, null, 2) },
+ ],
+ },
+ };
+ }
- default:
- return {
- status_code: 400,
- body: { error: `Unknown tool: ${name}` },
- };
+ case "memory_sessions": {
+ const sessions = await kv.list(KV.sessions);
+ return {
+ status_code: 200,
+ body: {
+ content: [
+ { type: "text", text: JSON.stringify({ sessions }, null, 2) },
+ ],
+ },
+ };
+ }
+
+ default:
+ return {
+ status_code: 400,
+ body: { error: `Unknown tool: ${name}` },
+ };
+ }
+ } catch (err) {
+ return {
+ status_code: 500,
+ body: {
+ error: err instanceof Error ? err.message : "Internal error",
+ },
+ };
}
},
);
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 4534eca4..8cc9dba9 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -221,6 +221,13 @@ export function registerApiTriggers(
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
+ if (
+ !req.body?.content ||
+ typeof req.body.content !== "string" ||
+ !req.body.content.trim()
+ ) {
+ return { status_code: 400, body: { error: "content is required" } };
+ }
const result = await sdk.trigger("mem::remember", req.body);
return { status_code: 201, body: result };
},
@@ -242,6 +249,12 @@ export function registerApiTriggers(
): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
+ if (!req.body?.sessionId && !req.body?.memoryId) {
+ return {
+ status_code: 400,
+ body: { error: "sessionId or memoryId is required" },
+ };
+ }
const result = await sdk.trigger("mem::forget", req.body);
return { status_code: 200, body: result };
},
@@ -304,6 +317,9 @@ export function registerApiTriggers(
async (req: ApiRequest<{ dbPath: string }>): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
+ if (!req.body?.dbPath || typeof req.body.dbPath !== "string") {
+ return { status_code: 400, body: { error: "dbPath is required" } };
+ }
const result = await sdk.trigger("mem::migrate", req.body);
return { status_code: 200, body: result };
},