Repository navigation
Kody memory subsystem #133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
95a1f78
Add MCP memory subsystem
cursoragent df8d095
Fix search memory rendering
cursoragent cc6f99a
Align memory schemas and simplify context
cursoragent 7c9b15d
Fix memory upsert and search ranks
cursoragent 83fd972
Tighten memory retrieval behavior
cursoragent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,15 +1,85 @@ | ||
| # Memory and conversation context | ||
|
|
||
| **Work in progress.** Kody’s MCP tools accept optional **`conversationId`** and | ||
| **`memoryContext`** fields. | ||
| Kody supports two related memory features: | ||
|
|
||
| - **conversation-scoped suppression** via **`conversationId`** | ||
| - **long-term memory retrieval and persistence** via **`memoryContext`** and | ||
| memory capabilities | ||
|
|
||
| ## `conversationId` | ||
|
|
||
| **`conversationId`** ties related tool calls together. Omit it on the first call | ||
| to receive a server-generated id, then pass the returned id on follow-up calls | ||
| in the same conversation. | ||
|
|
||
| **`memoryContext`** is reserved for **future memory-aware behavior**. It is | ||
| **not** persisted or used for retrieval yet. Keep it short and task-focused when | ||
| you set it so future versions can build on consistent patterns. | ||
| Kody uses this id to avoid surfacing the same long-term memory repeatedly in one | ||
| conversation. | ||
|
|
||
| ## `memoryContext` | ||
|
|
||
| **`memoryContext`** is a short, task-focused hint the agent sends with normal | ||
| tool calls. Kody uses it to retrieve a small number of relevant long-term | ||
| memories for the current task. | ||
|
|
||
| Keep it brief and factual. Good fields include: | ||
|
|
||
| - current task | ||
| - current query | ||
| - important entities | ||
| - important constraints | ||
|
|
||
| ## Automatic memory surfacing | ||
|
|
||
| When a signed-in agent includes **`memoryContext`**, Kody may return a small | ||
| number of relevant previously-unsurfaced memories alongside the normal tool | ||
| result. | ||
|
|
||
| That retrieval is: | ||
|
|
||
| - **conservative** — only a few memories | ||
| - **task-based** — driven by `memoryContext` | ||
| - **conversation-aware** — repeated memories are suppressed within the same | ||
| `conversationId` | ||
|
|
||
| ## Verify-first rule for memory writes | ||
|
|
||
| Agents must treat long-term memory writes as an explicit workflow. | ||
|
|
||
| If the agent believes durable memory should be created, updated, or deleted, it | ||
| should: | ||
|
|
||
| 1. call **`meta_memory_verify`** first | ||
| 2. review the related memories returned by verify | ||
| 3. decide whether to: | ||
| - upsert a memory | ||
| - delete a memory | ||
| - do both | ||
| - do nothing | ||
|
|
||
| Kody helps retrieve related memories, but the **consuming agent** is responsible | ||
| for deciding what those related memories mean. | ||
|
|
||
| ## Memory capabilities | ||
|
|
||
| Use these through **`execute`**: | ||
|
|
||
| - **`meta_memory_verify`** — required first step before mutating memory | ||
| - **`meta_memory_upsert`** — create a new memory when `memory_id` is omitted, or | ||
| update an existing memory when `memory_id` is provided | ||
| - **`meta_memory_delete`** — soft-delete by default; pass `force: true` for | ||
| permanent deletion | ||
| - **`meta_memory_get`** — load one stored memory by id | ||
| - **`meta_memory_search`** — browse/search stored memories directly | ||
|
|
||
| ## Categories | ||
|
|
||
| Memory categories are freeform strings. Kody does not force a closed list. | ||
|
|
||
| Suggested examples: | ||
|
|
||
| This page expands when memory features ship. See [First steps](./first-steps.md) | ||
| for current behavior that already helps (reusing **`conversationId`**). | ||
| - `preference` | ||
| - `identifier` | ||
| - `relationship` | ||
| - `workflow` | ||
| - `project` | ||
| - `profile` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| CREATE TABLE IF NOT EXISTS mcp_memories ( | ||
| id TEXT PRIMARY KEY NOT NULL, | ||
| user_id TEXT NOT NULL, | ||
| category TEXT, | ||
| status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'deleted', 'archived')), | ||
| subject TEXT NOT NULL, | ||
| summary TEXT NOT NULL, | ||
| details TEXT NOT NULL DEFAULT '', | ||
| tags_json TEXT NOT NULL DEFAULT '[]', | ||
| dedupe_key TEXT, | ||
| created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP), | ||
| updated_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP), | ||
| last_accessed_at TEXT, | ||
| deleted_at TEXT | ||
| ); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_mcp_memories_user_status_updated | ||
| ON mcp_memories(user_id, status, updated_at); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_mcp_memories_user_category_status | ||
| ON mcp_memories(user_id, category, status); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_mcp_memories_user_dedupe_key | ||
| ON mcp_memories(user_id, dedupe_key); | ||
|
|
||
| CREATE TABLE IF NOT EXISTS mcp_memory_conversation_suppressions ( | ||
| user_id TEXT NOT NULL, | ||
| conversation_id TEXT NOT NULL, | ||
| memory_id TEXT NOT NULL, | ||
| created_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP), | ||
| last_seen_at TEXT NOT NULL DEFAULT (CURRENT_TIMESTAMP), | ||
| expires_at TEXT NOT NULL, | ||
| PRIMARY KEY (user_id, conversation_id, memory_id), | ||
| FOREIGN KEY (memory_id) REFERENCES mcp_memories(id) ON DELETE CASCADE | ||
| ); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_mcp_memory_suppressions_expires_at | ||
| ON mcp_memory_conversation_suppressions(expires_at); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
packages/worker/src/mcp/capabilities/meta/meta-memory-delete.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { z } from 'zod' | ||
| import { defineDomainCapability } from '#mcp/capabilities/define-domain-capability.ts' | ||
| import { capabilityDomainNames } from '#mcp/capabilities/domain-metadata.ts' | ||
| import { type CapabilityContext } from '#mcp/capabilities/types.ts' | ||
| import { deleteMemory, getMemory } from '#mcp/memory/service.ts' | ||
| import { memoryRecordSchema, verifyFirstGuidance } from './meta-memory-shared.ts' | ||
| import { requireMcpUser } from './require-user.ts' | ||
|
|
||
| const outputSchema = z.object({ | ||
| ok: z.boolean(), | ||
| force: z.boolean(), | ||
| memory: memoryRecordSchema.nullable(), | ||
| guidance: z.string(), | ||
| }) | ||
|
|
||
| export const metaMemoryDeleteCapability = defineDomainCapability( | ||
| capabilityDomainNames.meta, | ||
| { | ||
| name: 'meta_memory_delete', | ||
| description: | ||
| 'Soft-delete a stored memory by default, or hard-delete it when `force` is true. Always run `meta_memory_verify` before deleting memory. Do not delete memory blindly. Review related memories first, decide the correct action, then delete.', | ||
| keywords: [ | ||
| 'memory', | ||
| 'delete', | ||
| 'archive', | ||
| 'verify first', | ||
| 'soft delete', | ||
| 'hard delete', | ||
| ], | ||
| readOnly: false, | ||
| idempotent: false, | ||
| destructive: true, | ||
| inputSchema: z.object({ | ||
| memory_id: z.string().min(1).describe('Target memory id to delete.'), | ||
| force: z | ||
| .boolean() | ||
| .optional() | ||
| .describe( | ||
| 'When true, permanently delete the record. Otherwise soft-delete it by setting status to deleted.', | ||
| ), | ||
| verified_by_agent: z | ||
| .boolean() | ||
| .describe( | ||
| 'Agent assertion that `meta_memory_verify` was run before deletion.', | ||
| ), | ||
| verification_reference: z | ||
| .string() | ||
| .min(1) | ||
| .optional() | ||
| .describe( | ||
| 'Optional agent-supplied note or reference to the verification step that justified this deletion.', | ||
| ), | ||
| }), | ||
| outputSchema, | ||
| async handler(args, ctx: CapabilityContext) { | ||
| const user = requireMcpUser(ctx.callerContext) | ||
| if (!args.verified_by_agent) { | ||
| throw new Error( | ||
| 'Agents must run meta_memory_verify before calling meta_memory_delete. Set verified_by_agent=true only after review.', | ||
| ) | ||
| } | ||
| const existing = await getMemory({ | ||
| env: ctx.env, | ||
| userId: user.userId, | ||
| memoryId: args.memory_id, | ||
| }) | ||
| if (!existing) { | ||
| throw new Error('Memory not found for this user.') | ||
| } | ||
| const memory = await deleteMemory({ | ||
| env: ctx.env, | ||
| userId: user.userId, | ||
| memoryId: args.memory_id, | ||
| force: args.force ?? false, | ||
| }) | ||
| return { | ||
| ok: true, | ||
| force: args.force ?? false, | ||
| memory: formatMemoryRecord(memory), | ||
| guidance: `${verifyFirstGuidance} Use soft delete by default; reserve force=true for records that should be removed permanently.`, | ||
| } | ||
| }, | ||
| }, | ||
| ) | ||
|
|
||
| function formatMemoryRecord( | ||
| memory: | ||
| | Awaited<ReturnType<typeof deleteMemory>> | ||
| | Awaited<ReturnType<typeof getMemory>>, | ||
| ) { | ||
| if (!memory) return null | ||
| return { | ||
| id: memory.id, | ||
| category: memory.category, | ||
| status: memory.status, | ||
| subject: memory.subject, | ||
| summary: memory.summary, | ||
| details: memory.details, | ||
| tags: memory.tags, | ||
| dedupe_key: memory.dedupeKey, | ||
| created_at: memory.createdAt, | ||
| updated_at: memory.updatedAt, | ||
| last_accessed_at: memory.lastAccessedAt, | ||
| deleted_at: memory.deletedAt, | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't acknowledge a delete that didn't actually happen.
deleteMemory()is nullable, so a concurrent delete or failed hard-delete can currently return{ ok: true, memory: null }. Treat a null result as a failure and ask the caller to re-verify/retry instead of reporting success.Suggested fix
const memory = await deleteMemory({ env: ctx.env, userId: user.userId, memoryId: args.memory_id, force: args.force ?? false, }) + if (!memory) { + throw new Error( + 'Memory changed or was already removed before deletion completed. Re-run meta_memory_verify and retry.', + ) + } return { ok: true, force: args.force ?? false, memory: formatMemoryRecord(memory),📝 Committable suggestion
🤖 Prompt for AI Agents