#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
feat(slots): add editable pinned memory slots + idle reflection + global scope
Rohit Ghumarec70b60211a88
diff --git a/README.md b/README.mdindex ed600d87..849a1638 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@<p align="center"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-recall.svg"><img src="assets/tags/stat-recall.svg" alt="95.2% retrieval R@5" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tokens.svg"><img src="assets/tags/stat-tokens.svg" alt="92% fewer tokens" height="38" /></picture>- <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="45 MCP tools" height="38" /></picture>+ <picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tools.svg"><img src="assets/tags/stat-tools.svg" alt="51 MCP tools" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-hooks.svg"><img src="assets/tags/stat-hooks.svg" alt="12 auto hooks" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-deps.svg"><img src="assets/tags/stat-deps.svg" alt="0 external DBs" height="38" /></picture><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/stat-tests.svg"><img src="assets/tags/stat-tests.svg" alt="654 tests passing" height="38" /></picture>@@ -334,7 +334,7 @@ Implementation details live in `src/cli.ts` (see `runUpgrade` around the `src/cl### Claude Code (one block, paste it)```-Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 45 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113.+Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server. Then run `/plugin marketplace add rohitg00/agentmemory` and `/plugin install agentmemory` — the plugin registers all 12 hooks, 4 skills, AND auto-wires the `@agentmemory/mcp` stdio server via its `.mcp.json`, so you get 51 MCP tools (memory_smart_search, memory_save, memory_sessions, memory_governance_delete, etc.) without any extra config step. Verify with `curl http://localhost:3111/agentmemory/health`. The real-time viewer is at http://localhost:3113.```<details>@@ -593,7 +593,7 @@ npm install @xenova/transformers<h2 id="mcp-server"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/tags/light/section-mcp.svg"><img src="assets/tags/section-mcp.svg" alt="MCP Server" height="32" /></picture></h2>-45 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent.+50 tools, 6 resources, 3 prompts, and 4 skills — the most comprehensive MCP memory toolkit for any agent.### 44 Tools@@ -816,17 +816,23 @@ Create `~/.agentmemory/.env`:# LLM provider to compress the# observation — expect significant# token spend on active sessions.-# AGENTMEMORY_IMAGE_EMBEDDINGS=false # OFF by default. When on, loads- # CLIP ViT-B/32 (512d) via- # @xenova/transformers and embeds- # every captured screenshot into- # mem:image-embeddings. Enables- # memory_vision_search (cross-modal:- # text→image or image→image cosine).- # Model downloads (~350 MB) on first- # use — lazy. Observe pipeline fires- # mem::vision-embed via triggerVoid,- # so capture latency is unchanged.+# AGENTMEMORY_SLOTS=false # OFF by default. Editable pinned+ # memory slots — persona,+ # user_preferences, tool_guidelines,+ # project_context, guidance,+ # pending_items, session_patterns,+ # self_notes. Size-limited; agent+ # edits via memory_slot_* tools.+ # Pinned slots addressable for+ # SessionStart injection.+# AGENTMEMORY_REFLECT=false # OFF by default. Requires SLOTS=on.+ # Stop hook fires mem::slot-reflect:+ # scans recent observations, auto-+ # appends TODOs to pending_items,+ # counts patterns in+ # session_patterns, records touched+ # files in project_context. Fire-+ # and-forget; does not block.# AGENTMEMORY_INJECT_CONTEXT=false # OFF by default (#143). When on:# - SessionStart may inject ~1-2K# chars of project context into@@ -854,7 +860,7 @@ Create `~/.agentmemory/.env`:# USER_ID=# TEAM_MODE=private-# Tool visibility: "core" (8 tools) or "all" (45 tools)+# Tool visibility: "core" (8 tools) or "all" (51 tools)# AGENTMEMORY_TOOLS=core```diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.jsonindex 059edc94..3ae465d5 100644--- a/plugin/.claude-plugin/plugin.json+++ b/plugin/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "agentmemory","version": "0.9.1",- "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 45 MCP tools, 4 skills, real-time viewer.",+ "description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 51 MCP tools, 4 skills, real-time viewer.","author": {"name": "Rohit Ghumare","url": "https://github.com/rohitg00"diff --git a/src/functions/slots.ts b/src/functions/slots.tsnew file mode 100644index 00000000..d18382d4--- /dev/null+++ b/src/functions/slots.ts@@ -0,0 +1,451 @@+import type { ISdk } from "iii-sdk";+import type { MemorySlot, CompressedObservation } from "../types.js";+import { KV } from "../state/schema.js";+import { StateKV } from "../state/kv.js";+import { withKeyedLock } from "../state/keyed-mutex.js";+import { recordAudit } from "./audit.js";+import { logger } from "../logger.js";++type SlotScope = "project" | "global";++const DEFAULT_SIZE_LIMIT = 2000;++export const DEFAULT_SLOTS: ReadonlyArray<+ Omit<MemorySlot, "createdAt" | "updatedAt">+> = [+ {+ label: "persona",+ content: "",+ sizeLimit: 1000,+ description:+ "How the agent should see itself: role, tone, behavioural guidelines.",+ pinned: true,+ readOnly: false,+ scope: "global",+ },+ {+ label: "user_preferences",+ content: "",+ sizeLimit: 2000,+ description:+ "Coding style, tool preferences, naming conventions, and other habits the user wants preserved across sessions.",+ pinned: true,+ readOnly: false,+ scope: "global",+ },+ {+ label: "tool_guidelines",+ content: "",+ sizeLimit: 1500,+ description:+ "Rules the agent should follow when picking or sequencing tools (e.g. prefer X over Y, never run Z without confirmation).",+ pinned: true,+ readOnly: false,+ scope: "global",+ },+ {+ label: "project_context",+ content: "",+ sizeLimit: 3000,+ description:+ "Architecture decisions, codebase conventions, build/test commands, and cross-cutting constraints for the current project.",+ pinned: true,+ readOnly: false,+ scope: "project",+ },+ {+ label: "guidance",+ content: "",+ sizeLimit: 1500,+ description:+ "Active advice for the next session: what to focus on, what to avoid, open risks.",+ pinned: true,+ readOnly: false,+ scope: "project",+ },+ {+ label: "pending_items",+ content: "",+ sizeLimit: 2000,+ description:+ "Unfinished work, explicit TODOs, and promises made but not yet delivered.",+ pinned: true,+ readOnly: false,+ scope: "project",+ },+ {+ label: "session_patterns",+ content: "",+ sizeLimit: 1500,+ description:+ "Recurring behaviours and common struggles observed across recent sessions.",+ pinned: false,+ readOnly: false,+ scope: "project",+ },+ {+ label: "self_notes",+ content: "",+ sizeLimit: 1500,+ description:+ "Free-form notes the agent keeps for itself: hypotheses, dead ends, things to revisit.",+ pinned: false,+ readOnly: false,+ scope: "project",+ },+];++export function isSlotsEnabled(): boolean {+ return process.env["AGENTMEMORY_SLOTS"] === "true";+}++export function isReflectEnabled(): boolean {+ return process.env["AGENTMEMORY_REFLECT"] === "true";+}++function scopeKv(scope: SlotScope): string {+ return scope === "global" ? KV.globalSlots : KV.slots;+}++function nowIso(): string {+ return new Date().toISOString();+}++function validateLabel(label: unknown): string | null {+ if (typeof label !== "string") return null;+ const trimmed = label.trim();+ if (!trimmed || trimmed.length > 64) return null;+ if (!/^[a-z][a-z0-9_]*$/.test(trimmed)) return null;+ return trimmed;+}++async function readSlot(+ kv: StateKV,+ label: string,+): Promise<{ slot: MemorySlot | null; scope: SlotScope }> {+ const project = await kv.get<MemorySlot>(KV.slots, label);+ if (project) return { slot: project, scope: "project" };+ const global = await kv.get<MemorySlot>(KV.globalSlots, label);+ if (global) return { slot: global, scope: "global" };+ return { slot: null, scope: "project" };+}++async function seedDefaults(kv: StateKV): Promise<void> {+ 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(),+ };+ await kv.set(target, tmpl.label, slot);+ }+}++export async function listPinnedSlots(kv: StateKV): Promise<MemorySlot[]> {+ const [project, global] = await Promise.all([+ kv.list<MemorySlot>(KV.slots),+ kv.list<MemorySlot>(KV.globalSlots),+ ]);+ const merged = new Map<string, MemorySlot>();+ for (const s of global) merged.set(s.label, s);+ for (const s of project) merged.set(s.label, s);+ return Array.from(merged.values())+ .filter((s) => s.pinned && s.content.trim().length > 0)+ .sort((a, b) => a.label.localeCompare(b.label));+}++export function renderPinnedContext(slots: MemorySlot[]): string {+ if (slots.length === 0) return "";+ const lines: string[] = ["# agentmemory pinned slots", ""];+ for (const slot of slots) {+ lines.push(`## ${slot.label}`);+ lines.push(slot.content.trim());+ lines.push("");+ }+ return lines.join("\n");+}++export function registerSlotsFunctions(sdk: ISdk, kv: StateKV): void {+ void seedDefaults(kv).catch((err) => {+ logger.warn("slot defaults seed failed", {+ error: err instanceof Error ? err.message : String(err),+ });+ });++ sdk.registerFunction("mem::slot-list", async () => {+ const [project, global] = await Promise.all([+ kv.list<MemorySlot>(KV.slots),+ kv.list<MemorySlot>(KV.globalSlots),+ ]);+ const merged = new Map<string, MemorySlot>();+ for (const s of global) merged.set(s.label, s);+ for (const s of project) merged.set(s.label, s);+ const slots = Array.from(merged.values()).sort((a, b) =>+ a.label.localeCompare(b.label),+ );+ return { success: true, slots };+ });++ sdk.registerFunction(+ "mem::slot-get",+ async (data: { label?: string }) => {+ const label = validateLabel(data?.label);+ if (!label) return { success: false, error: "label required (lowercase, starts with letter, [a-z0-9_])" };+ const { slot, scope } = await readSlot(kv, label);+ if (!slot) return { success: false, error: "slot not found" };+ return { success: true, slot, scope };+ },+ );++ sdk.registerFunction(+ "mem::slot-create",+ async (data: {+ label?: string;+ content?: string;+ sizeLimit?: number;+ description?: string;+ pinned?: boolean;+ scope?: SlotScope;+ }) => {+ 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 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,+ });+ return { success: true, slot };+ },+ );++ sdk.registerFunction(+ "mem::slot-append",+ async (data: { label?: string; text?: string }) => {+ const label = validateLabel(data?.label);+ if (!label) return { success: false, error: "label required" };+ const text = typeof data?.text === "string" ? data.text : "";+ if (!text) return { success: false, error: "text required" };+ return withKeyedLock(`slot:${label}`, async () => {+ const { slot, scope } = await readSlot(kv, label);+ if (!slot) return { success: false, error: "slot not found (use mem::slot-create first)" };+ if (slot.readOnly) return { success: false, error: "slot is read-only" };+ const sep = slot.content && !slot.content.endsWith("\n") ? "\n" : "";+ const next = `${slot.content}${sep}${text}`;+ if (next.length > slot.sizeLimit) {+ return {+ success: false,+ error: `append would exceed sizeLimit (${next.length} > ${slot.sizeLimit}). Use mem::slot-replace to compact first.`,+ currentSize: slot.content.length,+ sizeLimit: slot.sizeLimit,+ };+ }+ const updated: MemorySlot = { ...slot, content: next, updatedAt: nowIso() };+ await kv.set(scopeKv(scope), label, updated);+ await recordAudit(kv, "slot_append", "mem::slot-append", [label], {+ scope,+ added: text.length,+ total: next.length,+ });+ return { success: true, slot: updated, size: next.length };+ });+ },+ );++ sdk.registerFunction(+ "mem::slot-replace",+ async (data: { label?: string; content?: string }) => {+ const label = validateLabel(data?.label);+ if (!label) return { success: false, error: "label required" };+ if (typeof data?.content !== "string") return { success: false, error: "content required (string)" };+ return withKeyedLock(`slot:${label}`, async () => {+ const { slot, scope } = await readSlot(kv, label);+ if (!slot) return { success: false, error: "slot not found (use mem::slot-create first)" };+ if (slot.readOnly) return { success: false, error: "slot is read-only" };+ if (data.content.length > slot.sizeLimit) {+ return {+ success: false,+ error: `content exceeds sizeLimit (${data.content.length} > ${slot.sizeLimit})`,+ sizeLimit: slot.sizeLimit,+ };+ }+ const updated: MemorySlot = { ...slot, content: data.content, updatedAt: nowIso() };+ await kv.set(scopeKv(scope), label, updated);+ await recordAudit(kv, "slot_replace", "mem::slot-replace", [label], {+ scope,+ before: slot.content.length,+ after: data.content.length,+ });+ return { success: true, slot: updated, size: data.content.length };+ });+ },+ );++ sdk.registerFunction(+ "mem::slot-delete",+ 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 { success: true };+ },+ );++ sdk.registerFunction(+ "mem::slot-reflect",+ async (data: { sessionId?: string; maxObservations?: number }) => {+ if (!data?.sessionId || typeof data.sessionId !== "string") {+ return { success: false, error: "sessionId required" };+ }+ const max =+ typeof data.maxObservations === "number" &&+ Number.isInteger(data.maxObservations) &&+ data.maxObservations > 0+ ? Math.min(200, data.maxObservations)+ : 50;+ const observations = await kv.list<CompressedObservation>(+ KV.observations(data.sessionId),+ );+ if (observations.length === 0) {+ return { success: true, applied: 0, reason: "no observations for session" };+ }+ const recent = observations+ .slice()+ .sort((a, b) => (b.timestamp || "").localeCompare(a.timestamp || ""))+ .slice(0, max);++ const pendingLines: string[] = [];+ const patternCounts = new Map<string, number>();+ const files = new Set<string>();+ for (const obs of recent) {+ const title = (obs.title || "").toLowerCase();+ const narrative = (obs.narrative || "").toLowerCase();+ if (narrative.includes("todo") || title.includes("todo")) {+ pendingLines.push(`- ${obs.title || obs.id}`);+ }+ if (obs.type === "error") {+ patternCounts.set("errors", (patternCounts.get("errors") ?? 0) + 1);+ }+ if (obs.type === "command_run") {+ patternCounts.set("commands", (patternCounts.get("commands") ?? 0) + 1);+ }+ if (obs.files) for (const f of obs.files) files.add(f);+ }++ 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++;+ });+ }+ }++ if (patternCounts.size > 0) {+ const { slot, scope } = await readSlot(kv, "session_patterns");+ if (slot) {+ const summary = [+ `last reflection: ${nowIso()}`,+ ...Array.from(patternCounts.entries()).map(+ ([kind, count]) => `- ${kind}: ${count} in last ${recent.length} observations`,+ ),+ ].join("\n");+ const next =+ summary.length > slot.sizeLimit ? summary.slice(0, slot.sizeLimit) : summary;+ await kv.set(scopeKv(scope), "session_patterns", {+ ...slot,+ content: next,+ updatedAt: nowIso(),+ });+ 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++;+ });+ }+ }++ if (applied > 0) {+ await recordAudit(kv, "slot_reflect", "mem::slot-reflect", [data.sessionId], {+ observationCount: recent.length,+ slotsUpdated: applied,+ });+ }++ return { success: true, applied, observationsReviewed: recent.length };+ },+ );+}diff --git a/src/index.ts b/src/index.tsindex 580ee547..1d7cacd7 100644--- a/src/index.ts+++ b/src/index.ts@@ -26,6 +26,7 @@ import { registerPrivacyFunction } from "./functions/privacy.js";import { registerObserveFunction } from "./functions/observe.js";import { registerImageQuotaCleanup } from "./functions/image-quota-cleanup.js";import { registerVisionSearchFunctions } from "./functions/vision-search.js";+import { registerSlotsFunctions, isSlotsEnabled, isReflectEnabled } from "./functions/slots.js";import { registerDiskSizeManager } from "./functions/disk-size-manager.js";import { registerCompressFunction } from "./functions/compress.js";import {@@ -163,6 +164,9 @@ async function main() {registerObserveFunction(sdk, kv, dedupMap, config.maxObservationsPerSession);registerImageQuotaCleanup(sdk, kv);registerVisionSearchFunctions(sdk, kv, imageEmbeddingProvider);+ if (isSlotsEnabled()) {+ registerSlotsFunctions(sdk, kv);+ }registerDiskSizeManager(sdk, kv);registerCompressFunction(sdk, kv, provider, metricsStore);registerSearchFunction(sdk, kv);@@ -262,6 +266,11 @@ async function main() {console.log(`[agentmemory] Orchestration layer: actions, frontier, leases, routines, signals, checkpoints, flow-compress, mesh, branch-aware, sentinels, sketches, crystallize, diagnostics, facets`,);+ if (isSlotsEnabled()) {+ console.log(+ `[agentmemory] Slots: enabled (pinned editable memory). Reflect on Stop hook: ${isReflectEnabled() ? "on" : "off"}`,+ );+ }const snapshotConfig = loadSnapshotConfig();if (snapshotConfig.enabled) {diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 69539a2f..a8fc45e8 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -1134,6 +1134,73 @@ export function registerMcpEndpoints(return { status_code: 200, body: { content: [{ type: "text", text: JSON.stringify(obsidianResult, null, 2) }] } };}+ case "memory_slot_list": {+ const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }++ case "memory_slot_get": {+ const label = asNonEmptyString(args.label);+ if (!label) return { status_code: 400, body: { error: "label required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }++ case "memory_slot_create": {+ const label = asNonEmptyString(args.label);+ if (!label) return { status_code: 400, body: { error: "label required" } };+ const payload: Record<string, unknown> = { label };+ 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";+ const result = await sdk.trigger({ function_id: "mem::slot-create", payload });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }++ case "memory_slot_append": {+ const label = asNonEmptyString(args.label);+ const text = typeof args.text === "string" ? args.text : null;+ if (!label || !text) return { status_code: 400, body: { error: "label and text required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }++ case "memory_slot_replace": {+ const label = asNonEmptyString(args.label);+ if (!label || typeof args.content !== "string") {+ return { status_code: 400, body: { error: "label and content (string) required" } };+ }+ const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content: args.content } });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }++ case "memory_slot_delete": {+ const label = asNonEmptyString(args.label);+ if (!label) return { status_code: 400, body: { error: "label required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } });+ return {+ status_code: 200,+ body: { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] },+ };+ }+default:return {status_code: 400,diff --git a/src/mcp/tools-registry.ts b/src/mcp/tools-registry.tsindex 679e5288..82d7e7ce 100644--- a/src/mcp/tools-registry.ts+++ b/src/mcp/tools-registry.ts@@ -820,6 +820,78 @@ export const V073_TOOLS: McpToolDef[] = [},];+export const V010_SLOTS_TOOLS: McpToolDef[] = [+ {+ name: "memory_slot_list",+ description:+ "List all memory slots (pinned + project + global). Slots are editable, size-limited memory units the agent can read and modify across sessions.",+ inputSchema: { type: "object", properties: {} },+ },+ {+ name: "memory_slot_get",+ description: "Read a single slot by label.",+ inputSchema: {+ type: "object",+ properties: {+ label: { type: "string", description: "Slot label (e.g. 'persona', 'pending_items')" },+ },+ required: ["label"],+ },+ },+ {+ name: "memory_slot_create",+ description: "Create a new slot. Reject if a slot with the same label already exists.",+ inputSchema: {+ type: "object",+ properties: {+ label: { type: "string", description: "Slot label — lowercase, starts with letter, [a-z0-9_]" },+ content: { type: "string", description: "Initial content (default empty)" },+ sizeLimit: { type: "number", description: "Max chars (default 2000, hard cap 20000)" },+ description: { type: "string", description: "What this slot is for" },+ pinned: { type: "string", description: "'false' to exclude from context injection; default true" },+ scope: { type: "string", description: "'project' (default) or 'global' (shared across projects)" },+ },+ required: ["label"],+ },+ },+ {+ name: "memory_slot_append",+ description:+ "Append text to an existing slot. Fails with 413 if the append would exceed the slot's sizeLimit — agent must compact via memory_slot_replace first.",+ inputSchema: {+ type: "object",+ properties: {+ label: { type: "string", description: "Slot label" },+ text: { type: "string", description: "Text to append" },+ },+ required: ["label", "text"],+ },+ },+ {+ name: "memory_slot_replace",+ description: "Replace slot content in place. Fails if content exceeds sizeLimit.",+ inputSchema: {+ type: "object",+ properties: {+ label: { type: "string", description: "Slot label" },+ content: { type: "string", description: "New full content" },+ },+ required: ["label", "content"],+ },+ },+ {+ name: "memory_slot_delete",+ description: "Delete a slot. Seeded default slots can be deleted unless marked readOnly.",+ inputSchema: {+ type: "object",+ properties: {+ label: { type: "string", description: "Slot label" },+ },+ required: ["label"],+ },+ },+];+const ESSENTIAL_TOOLS = new Set(["memory_save","memory_recall",@@ -832,7 +904,16 @@ const ESSENTIAL_TOOLS = new Set([]);export function getAllTools(): McpToolDef[] {- return [...CORE_TOOLS, ...V040_TOOLS, ...V050_TOOLS, ...V051_TOOLS, ...V061_TOOLS, ...V070_TOOLS, ...V073_TOOLS];+ return [+ ...CORE_TOOLS,+ ...V040_TOOLS,+ ...V050_TOOLS,+ ...V051_TOOLS,+ ...V061_TOOLS,+ ...V070_TOOLS,+ ...V073_TOOLS,+ ...V010_SLOTS_TOOLS,+ ];}export function getVisibleTools(): McpToolDef[] {diff --git a/src/state/schema.ts b/src/state/schema.tsindex b3c8bac5..33d2ccfe 100644--- a/src/state/schema.ts+++ b/src/state/schema.ts@@ -43,6 +43,8 @@ export const KV = {accessLog: "mem:access",imageRefs: "mem:image-refs",imageEmbeddings: "mem:image-embeddings",+ slots: "mem:slots",+ globalSlots: "mem:slots:global",} as const;export const STREAM = {diff --git a/src/triggers/api.ts b/src/triggers/api.tsindex a47f4996..8a8f20c2 100644--- a/src/triggers/api.ts+++ b/src/triggers/api.ts@@ -1344,6 +1344,148 @@ export function registerApiTriggers(type: "http",function_id: "api::vision-embed",config: { api_path: "/agentmemory/vision-embed", http_method: "POST" },+=======+ sdk.registerFunction("api::slot-list", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const result = await sdk.trigger({ function_id: "mem::slot-list", payload: {} });+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-list",+ config: { api_path: "/agentmemory/slots", http_method: "GET" },+ });++ sdk.registerFunction("api::slot-get", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const label = asNonEmptyString(req.query_params?.["label"]);+ if (!label) return { status_code: 400, body: { error: "label query param required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-get", payload: { label } });+ const resp = result as { success?: boolean; error?: string };+ if (resp?.success === false) {+ return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp };+ }+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-get",+ config: { api_path: "/agentmemory/slot", http_method: "GET" },+ });++ sdk.registerFunction("api::slot-create", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ 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;+ const sizeLimit = parseOptionalPositiveInt(body["sizeLimit"]);+ if (sizeLimit === null) return { status_code: 400, body: { error: "sizeLimit must be a positive integer" } };+ 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;+ const result = await sdk.trigger({ function_id: "mem::slot-create", payload });+ const resp = result as { success?: boolean; error?: string };+ if (resp?.success === false) {+ return { status_code: resp.error?.includes("exists") ? 409 : 400, body: resp };+ }+ return { status_code: 201, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-create",+ config: { api_path: "/agentmemory/slot", http_method: "POST" },+ });++ sdk.registerFunction("api::slot-append", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const body = (req.body ?? {}) as Record<string, unknown>;+ const label = asNonEmptyString(body["label"]);+ const text = typeof body["text"] === "string" ? body["text"] : null;+ if (!label || !text) return { status_code: 400, body: { error: "label and text required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-append", payload: { label, text } });+ const resp = result as { success?: boolean; error?: string };+ if (resp?.success === false) {+ const notFound = resp.error?.includes("not found");+ const overLimit = resp.error?.includes("exceed");+ return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp };+ }+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-append",+ config: { api_path: "/agentmemory/slot/append", http_method: "POST" },+ });++ sdk.registerFunction("api::slot-replace", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const body = (req.body ?? {}) as Record<string, unknown>;+ const label = asNonEmptyString(body["label"]);+ const content = body["content"];+ if (!label || typeof content !== "string") {+ return { status_code: 400, body: { error: "label and content (string) required" } };+ }+ const result = await sdk.trigger({ function_id: "mem::slot-replace", payload: { label, content } });+ const resp = result as { success?: boolean; error?: string };+ if (resp?.success === false) {+ const notFound = resp.error?.includes("not found");+ const overLimit = resp.error?.includes("exceed");+ return { status_code: notFound ? 404 : overLimit ? 413 : 400, body: resp };+ }+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-replace",+ config: { api_path: "/agentmemory/slot/replace", http_method: "POST" },+ });++ sdk.registerFunction("api::slot-delete", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const label = asNonEmptyString(req.query_params?.["label"]);+ if (!label) return { status_code: 400, body: { error: "label query param required" } };+ const result = await sdk.trigger({ function_id: "mem::slot-delete", payload: { label } });+ const resp = result as { success?: boolean; error?: string };+ if (resp?.success === false) {+ return { status_code: resp.error?.includes("not found") ? 404 : 400, body: resp };+ }+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-delete",+ config: { api_path: "/agentmemory/slot", http_method: "DELETE" },+ });++ sdk.registerFunction("api::slot-reflect", async (req: ApiRequest): Promise<Response> => {+ const authErr = checkAuth(req, secret);+ if (authErr) return authErr;+ const body = (req.body ?? {}) as Record<string, unknown>;+ const sessionId = asNonEmptyString(body["sessionId"]);+ if (!sessionId) return { status_code: 400, body: { error: "sessionId required" } };+ const maxObservations = parseOptionalPositiveInt(body["maxObservations"]);+ if (maxObservations === null) return { status_code: 400, body: { error: "maxObservations must be a positive integer" } };+ const payload: Record<string, unknown> = { sessionId };+ if (maxObservations !== undefined) payload["maxObservations"] = maxObservations;+ const result = await sdk.trigger({ function_id: "mem::slot-reflect", payload });+ return { status_code: 200, body: result };+ });+ sdk.registerTrigger({+ type: "http",+ function_id: "api::slot-reflect",+ config: { api_path: "/agentmemory/slot/reflect", http_method: "POST" },});sdk.registerFunction("api::action-create",diff --git a/src/triggers/events.ts b/src/triggers/events.tsindex 6deb470e..637f2027 100644--- a/src/triggers/events.ts+++ b/src/triggers/events.ts@@ -41,9 +41,13 @@ export function registerEventTriggers(sdk: ISdk, kv: StateKV): void {config: { topic: "agentmemory.observation" },});- sdk.registerFunction("event::session::stopped", async (data: { sessionId: string }) =>- sdk.trigger({ function_id: "mem::summarize", payload: data }),- );+ 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 });+ }+ return summary;+ });sdk.registerTrigger({type: "durable:subscriber",function_id: "event::session::stopped",diff --git a/src/types.ts b/src/types.tsindex 434778af..5a450b9b 100644--- a/src/types.ts+++ b/src/types.ts@@ -203,6 +203,18 @@ export interface CircuitBreakerState {openedAt: number | null;}+export interface MemorySlot {+ label: string;+ content: string;+ sizeLimit: number;+ description: string;+ pinned: boolean;+ readOnly: boolean;+ scope: "project" | "global";+ createdAt: string;+ updatedAt: string;+}+export interface EmbeddingProvider {name: string;dimensions: number;@@ -503,7 +515,12 @@ export interface AuditEntry {| "core_add"| "core_remove"| "auto_page"- | "vision_embed";+ | "vision_embed"+ | "slot_append"+ | "slot_replace"+ | "slot_create"+ | "slot_delete"+ | "slot_reflect";userId?: string;functionId: string;targetIds: string[];diff --git a/test/slots.test.ts b/test/slots.test.tsnew file mode 100644index 00000000..b003fcd9--- /dev/null+++ b/test/slots.test.ts@@ -0,0 +1,237 @@+import { describe, it, expect, beforeEach, vi } from "vitest";+import { registerSlotsFunctions, DEFAULT_SLOTS, listPinnedSlots, renderPinnedContext } from "../src/functions/slots.js";+import { KV } from "../src/state/schema.js";++function mockKV() {+ const store = new Map<string, Map<string, unknown>>();+ return {+ get: async <T>(scope: string, key: string): Promise<T | null> => {+ return (store.get(scope)?.get(key) as T) ?? null;+ },+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {+ if (!store.has(scope)) store.set(scope, new Map());+ store.get(scope)!.set(key, data);+ return data;+ },+ delete: async (scope: string, key: string): Promise<void> => {+ store.get(scope)?.delete(key);+ },+ list: async <T>(scope: string): Promise<T[]> => {+ if (!store.has(scope)) return [];+ return Array.from(store.get(scope)!.values()) as T[];+ },+ };+}++function wire() {+ const kv = mockKV();+ const handlers: Record<string, (data: Record<string, unknown>) => Promise<Record<string, unknown>>> = {};+ const sdk = {+ registerFunction: vi.fn((id: string, cb) => {+ handlers[id] = cb;+ }),+ } as unknown as import("iii-sdk").ISdk;+ registerSlotsFunctions(sdk, kv as never);+ return { kv, handlers };+}++async function waitForSeed(kv: ReturnType<typeof mockKV>) {+ for (let i = 0; i < 20; i++) {+ const p = await kv.list(KV.slots);+ const g = await kv.list(KV.globalSlots);+ if (p.length + g.length >= DEFAULT_SLOTS.length) return;+ await new Promise((r) => setTimeout(r, 5));+ }+}++describe("slots — primitive", () => {+ let kv: ReturnType<typeof mockKV>;+ let handlers: Record<string, (d: Record<string, unknown>) => Promise<Record<string, unknown>>>;++ beforeEach(async () => {+ ({ kv, handlers } = wire());+ await waitForSeed(kv);+ });++ it("seeds default slots into the right scopes on first run", async () => {+ const global = (await kv.list(KV.globalSlots)) as Array<{ label: string }>;+ const project = (await kv.list(KV.slots)) as Array<{ label: string }>;+ expect(global.map((s) => s.label).sort()).toEqual(+ ["persona", "tool_guidelines", "user_preferences"].sort(),+ );+ expect(project.map((s) => s.label).sort().length).toBeGreaterThanOrEqual(5);+ });++ it("rejects labels with bad shape", async () => {+ const res = (await handlers["mem::slot-create"]({ label: "Bad Label!" })) as { success: boolean; error: string };+ expect(res.success).toBe(false);+ expect(res.error).toMatch(/label required/);+ });++ it("create then get round-trips a new slot", async () => {+ const created = (await handlers["mem::slot-create"]({+ label: "notes_todo",+ content: "hello",+ description: "scratchpad",+ })) as { success: boolean; slot: { label: string; content: string } };+ expect(created.success).toBe(true);+ expect(created.slot.content).toBe("hello");++ const fetched = (await handlers["mem::slot-get"]({ label: "notes_todo" })) as {+ success: boolean;+ slot: { content: string };+ };+ expect(fetched.success).toBe(true);+ expect(fetched.slot.content).toBe("hello");+ });++ it("rejects duplicate create", async () => {+ await handlers["mem::slot-create"]({ label: "scratch", content: "a" });+ const dup = (await handlers["mem::slot-create"]({ label: "scratch", content: "b" })) as {+ success: boolean;+ error: string;+ };+ expect(dup.success).toBe(false);+ expect(dup.error).toMatch(/already exists/);+ });++ it("append refuses writes that would blow the sizeLimit", async () => {+ await handlers["mem::slot-create"]({ label: "tight", content: "", sizeLimit: 10 });+ const ok = (await handlers["mem::slot-append"]({ label: "tight", text: "short" })) as { success: boolean };+ expect(ok.success).toBe(true);+ const tooBig = (await handlers["mem::slot-append"]({ label: "tight", text: "way too long for this slot" })) as {+ success: boolean;+ error: string;+ };+ expect(tooBig.success).toBe(false);+ expect(tooBig.error).toMatch(/exceed sizeLimit/);+ });++ it("replace refuses content above sizeLimit", async () => {+ await handlers["mem::slot-create"]({ label: "tiny", content: "", sizeLimit: 5 });+ const res = (await handlers["mem::slot-replace"]({ label: "tiny", content: "exceeds" })) as {+ success: boolean;+ error: string;+ };+ expect(res.success).toBe(false);+ expect(res.error).toMatch(/exceeds/);+ });++ it("delete removes the slot", async () => {+ await handlers["mem::slot-create"]({ label: "throwaway", content: "bye" });+ const del = (await handlers["mem::slot-delete"]({ label: "throwaway" })) as { success: boolean };+ expect(del.success).toBe(true);+ const get = (await handlers["mem::slot-get"]({ label: "throwaway" })) as { success: boolean };+ expect(get.success).toBe(false);+ });++ 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", {+ label: "persona",+ content: "project-override",+ sizeLimit: 1000,+ description: "",+ pinned: true,+ readOnly: false,+ scope: "project",+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ });+ const res = (await handlers["mem::slot-get"]({ label: "persona" })) as {+ slot: { content: string };+ scope: string;+ };+ expect(res.slot.content).toBe("project-override");+ expect(res.scope).toBe("project");+ });++ 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);+ expect(pinned.some((s) => s.label === "persona")).toBe(true);+ expect(pinned.every((s) => s.pinned && s.content.trim().length > 0)).toBe(true);+ });++ it("renderPinnedContext serialises slots into markdown", async () => {+ await handlers["mem::slot-append"]({ label: "persona", text: "senior eng" });+ const pinned = await listPinnedSlots(kv as never);+ const rendered = renderPinnedContext(pinned);+ expect(rendered).toContain("## persona");+ expect(rendered).toContain("senior eng");+ });+});++describe("slots — reflect", () => {+ let kv: ReturnType<typeof mockKV>;+ let handlers: Record<string, (d: Record<string, unknown>) => Promise<Record<string, unknown>>>;++ beforeEach(async () => {+ ({ kv, handlers } = wire());+ await waitForSeed(kv);+ });++ it("no-ops when the session has no observations", async () => {+ const res = (await handlers["mem::slot-reflect"]({ sessionId: "empty-session" })) as {+ success: boolean;+ applied: number;+ };+ expect(res.success).toBe(true);+ expect(res.applied).toBe(0);+ });++ it("moves TODO-flavoured observations into pending_items and counts patterns", async () => {+ const sessionId = "sess_reflect";+ const obsKey = KV.observations(sessionId);+ const base = {+ id: "obs1",+ sessionId,+ timestamp: new Date().toISOString(),+ type: "error" as const,+ title: "TODO: wire up retries",+ subtitle: "",+ facts: [],+ narrative: "agent left a TODO for retries",+ concepts: [],+ files: ["src/retry.ts"],+ importance: 5,+ };+ await kv.set(obsKey, "obs1", base);+ await kv.set(obsKey, "obs2", {+ ...base,+ id: "obs2",+ title: "compile error",+ narrative: "tsc failed",+ files: ["src/other.ts"],+ type: "error",+ });+ const res = (await handlers["mem::slot-reflect"]({ sessionId })) as {+ success: boolean;+ applied: number;+ observationsReviewed: number;+ };+ expect(res.success).toBe(true);+ expect(res.observationsReviewed).toBe(2);+ expect(res.applied).toBeGreaterThan(0);++ const pending = (await handlers["mem::slot-get"]({ label: "pending_items" })) as {+ slot: { content: string };+ };+ expect(pending.slot.content).toContain("TODO: wire up retries");++ const patterns = (await handlers["mem::slot-get"]({ label: "session_patterns" })) as {+ slot: { content: string };+ };+ expect(patterns.slot.content).toMatch(/errors: 2/);+ });+});