Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/use/execute.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,22 @@ To run persisted user code by name, use **`meta_run_skill`** with **`name`** and
optional **`params`**. To inspect source, use **`meta_get_skill`**. You can also
inline saved skill code into **execute** when that fits the workflow.

## Long-term memory

Kody can surface a small number of relevant long-term memories when you pass a
short **`memoryContext`** with **`conversationId`** on normal MCP tool calls.

For memory mutations, the workflow is explicit and strict:

- **Always run `meta_memory_verify` before writing or deleting memory**
- then decide whether to call **`meta_memory_upsert`**,
**`meta_memory_delete`**, both, or neither
- **`meta_memory_upsert`** creates a new memory when **`memory_id`** is omitted
and updates an existing memory when **`memory_id`** is provided

Kody retrieves related memories, but the **consuming agent** remains responsible
for deciding what action to take.

## MCP server instructions

Users can read or replace their own MCP server instruction overlay with
Expand Down
8 changes: 8 additions & 0 deletions docs/use/first-steps.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,24 @@ skill).

- **Pass `conversationId` back** on follow-up calls when the tool response
includes one. That keeps related calls grouped and can reduce response size.
- **Pass `memoryContext`** when durable user memory may matter. Kody uses it to
surface a small set of relevant long-term memories that have not already been
shown in the same conversation.
- **Ask for natural-language goals**, for example: “Search Kody for GitHub pull
request automation” or “Find Cloudflare DNS helpers.”
- **Do not paste secrets in chat.** Use saved secrets, generated UI, or the
flows described in
[Secrets, values, and host approval](./secrets-and-values.md).
- **Confirm destructive work** before mutating GitHub, Cloudflare, or Cursor
Cloud Agents. See [Mutating actions and confirmations](./mutating-actions.md).
- **Verify before changing memory.** If you think something should become
durable memory, call `meta_memory_verify` first, review related memories, and
only then choose `meta_memory_upsert` or `meta_memory_delete`.

## Where to go next

- [Search](./search.md) — discovery, ranked results, and `entity` lookups
- [Execute and workflows](./execute.md) — chaining capability calls in one run
- [Memory and conversation context](./memory.md) — surfaced memories and the
verify-first write workflow
- [Troubleshooting](./troubleshooting.md) — empty results, auth, and approvals
84 changes: 77 additions & 7 deletions docs/use/memory.md
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`
6 changes: 6 additions & 0 deletions docs/use/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ values).
Pass a **`query`** string that describes what you want to do. Results are
ranked; order in the response matters.

When a tool call also includes **`memoryContext`**, Kody may attach a small
number of relevant long-term memories that have not already been surfaced for
that **`conversationId`**.

Optional **`limit`** caps how many ranked hits return. Optional
**`maxResponseSize`** trims low-ranked matches when the response must stay
small.
Expand Down Expand Up @@ -42,3 +46,5 @@ for an empty ranked list.

Saved **skills** and **apps** require a signed-in MCP user. Capabilities and
builtin behavior still work without user-scoped data.

Long-term memory retrieval also requires a signed-in MCP user.
38 changes: 38 additions & 0 deletions packages/worker/migrations/0016-mcp-memories.sql
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);
5 changes: 5 additions & 0 deletions packages/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
} from './mcp/generated-ui-api.ts'
import { withCors } from './utils.ts'
import { handleCapabilityReindexRequest } from './capability-maintenance.ts'
import { handleMemoryReindexRequest } from './memory-maintenance.ts'
import { handleSkillReindexRequest } from './skill-maintenance.ts'
import { handleUiArtifactReindexRequest } from './ui-artifact-maintenance.ts'
import { CodemodeFetchGateway } from '#mcp/fetch-gateway.ts'
Expand Down Expand Up @@ -86,6 +87,10 @@ const appHandler = withCors({
return handleSkillReindexRequest(request, env)
}

if (url.pathname === '/__maintenance/reindex-memories') {
return handleMemoryReindexRequest(request, env)
}

if (url.pathname === '/__maintenance/reindex-apps') {
return handleUiArtifactReindexRequest(request, env)
}
Expand Down
23 changes: 21 additions & 2 deletions packages/worker/src/mcp/capabilities/meta/domain.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { defineDomain } from '../define-domain.ts'
import { capabilityDomainNames } from '../domain-metadata.ts'
import { metaDeleteSkillCapability } from './meta-delete-skill.ts'
import { metaMemoryDeleteCapability } from './meta-memory-delete.ts'
import { metaMemoryGetCapability } from './meta-memory-get.ts'
import { metaMemorySearchCapability } from './meta-memory-search.ts'
import { metaMemoryUpsertCapability } from './meta-memory-upsert.ts'
import { metaMemoryVerifyCapability } from './meta-memory-verify.ts'
import { metaGetHomeConnectorStatusCapability } from './meta-get-home-connector-status.ts'
import { metaGetMcpServerInstructionsCapability } from './meta-get-mcp-server-instructions.ts'
import { metaGetSkillCapability } from './meta-get-skill.ts'
Expand All @@ -13,13 +18,27 @@ import { metaSetMcpServerInstructionsCapability } from './meta-set-mcp-server-in
export const metaDomain = defineDomain({
name: capabilityDomainNames.meta,
description:
'Save, list via search, load, run, and delete user-scoped codemode skills; read or update per-user MCP server instruction overlays. Skill saves upsert by unique name per user. Inspect the current runtime capability registry when search results seem incomplete. Save skills only for reasonably repeatable workflows (reusable patterns), not one-off or highly bespoke tasks.',
keywords: ['skill', 'meta', 'save', 'recipe', 'codemode', 'capabilities'],
'Save, list via search, load, run, and delete user-scoped codemode skills; read or update per-user MCP server instruction overlays; verify, search, fetch, upsert, and delete long-term user memories. Skill saves upsert by unique name per user. Memory writes and deletes require a verify-first workflow: inspect related memories with meta_memory_verify before changing stored memory. Inspect the current runtime capability registry when search results seem incomplete. Save skills only for reasonably repeatable workflows (reusable patterns), not one-off or highly bespoke tasks.',
keywords: [
'skill',
'meta',
'save',
'recipe',
'codemode',
'capabilities',
'memory',
'verify',
],
capabilities: [
metaListCapabilitiesCapability,
metaGetMcpServerInstructionsCapability,
metaSetMcpServerInstructionsCapability,
metaGetHomeConnectorStatusCapability,
metaMemorySearchCapability,
metaMemoryGetCapability,
metaMemoryVerifyCapability,
metaMemoryUpsertCapability,
metaMemoryDeleteCapability,
metaListSkillCollectionsCapability,
metaSaveSkillCapability,
metaDeleteSkillCapability,
Expand Down
106 changes: 106 additions & 0 deletions packages/worker/src/mcp/capabilities/meta/meta-memory-delete.ts
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.`,
Comment on lines +70 to +80

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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.`,
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),
guidance: `${verifyFirstGuidance} Use soft delete by default; reserve force=true for records that should be removed permanently.`,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/worker/src/mcp/capabilities/meta/meta-memory-delete.ts` around lines
70 - 80, The response currently returns ok: true even when deleteMemory(...)
returns null; change the logic in meta-memory-delete handler to check the
returned memory value from deleteMemory and treat null as a failure: if memory
is null, return ok: false (include force: args.force ?? false) and a guidance
message asking the caller to re-verify/retry (use/extend verifyFirstGuidance),
otherwise proceed to return ok: true with memory: formatMemoryRecord(memory).
Ensure you reference deleteMemory, formatMemoryRecord, memory, args.force and
verifyFirstGuidance when making the check and constructing the two different
responses.

}
},
},
)

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,
}
}
Loading
Loading