feat(memory): allow editing scope and project on memory.update

Extends both the Web UI edit form and the memory.update MCP tool so
existing memories can be reclassified between user-global and
project-attached scopes without delete+rewrite. Schema refines enforce
the user/project consistency invariants; audit log captures from/to
scope and projectKey on transitions.
This commit is contained in:
2026-05-17 06:43:19 -07:00
parent af5e7c4680
commit d65e1cb351
4 changed files with 199 additions and 17 deletions
+44 -1
View File
@@ -1,6 +1,6 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, eq, isNull } from "drizzle-orm";
import { and, desc, eq, isNull } from "drizzle-orm";
import { auth } from "@/auth";
import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema";
@@ -48,6 +48,15 @@ export default async function MemoryDetailPage({
const isEditing = edit === "1";
const projectList = isEditing
? await db
.select({ key: projects.key, displayName: projects.displayName })
.from(projects)
.where(eq(projects.userId, userId))
.orderBy(desc(projects.updatedAt))
.limit(50)
: [];
return (
<Container className="pt-6 max-w-3xl">
<PageHeader
@@ -81,6 +90,40 @@ export default async function MemoryDetailPage({
<CardBody>
<form action={updateMemoryAction} className="space-y-4">
<input type="hidden" name="id" value={m.id} />
<div>
<Label htmlFor="scope">Scope</Label>
<select
id="scope"
name="scope"
defaultValue={m.scope}
className="mt-1 h-9 px-2 rounded-md bg-surface-1 border border-border text-fg text-sm w-full"
>
<option value="project">Project attached to a project</option>
<option value="user">User global across all projects</option>
</select>
</div>
<div>
<Label htmlFor="project" hint="Required for project scope">
Project key
</Label>
<Input
id="project"
name="project"
defaultValue={m.projectKey ?? ""}
placeholder="repo name, slug, or any stable string"
list="project-list"
className="mt-1"
/>
{projectList.length > 0 ? (
<datalist id="project-list">
{projectList.map((p) => (
<option key={p.key} value={p.key}>
{p.displayName ?? p.key}
</option>
))}
</datalist>
) : null}
</div>
<div>
<Label htmlFor="content">Content</Label>
<Textarea
+72 -8
View File
@@ -311,13 +311,24 @@ const memoryDelete: ToolDef = {
const memoryUpdate: ToolDef = {
name: "memory.update",
description:
"Edit an existing memory in place — for correcting a stored fact, expanding it with new detail, or adjusting tags. Preserves the memory's id (so callers referencing it don't break) and re-embeds automatically when content changes. Use this — not delete + write — whenever you're refining what's already there.",
"Edit an existing memory in place — for correcting a stored fact, expanding it with new detail, adjusting tags, or moving it to a different scope/project. Preserves the memory's id (so callers referencing it don't break) and re-embeds automatically when content changes. Pass `scope` and/or `project` to reclassify a memory between user-global and project-attached without recreating it. Use this — not delete + write — whenever you're refining what's already there.",
inputSchema: {
type: "object",
properties: {
id: { type: "string", format: "uuid" },
content: { type: "string", description: "Replacement content (164,000 chars)." },
tags: { type: "array", items: { type: "string" }, description: "Replacement tag list." },
scope: {
type: "string",
enum: ["project", "user"],
description:
"New scope. When 'project', `project` must be set. When 'user', `project` must be omitted.",
},
project: {
type: "string",
description:
"Project key the memory should attach to (required and only valid when scope='project'). Project is upserted if it doesn't exist.",
},
},
required: ["id"],
},
@@ -325,9 +336,16 @@ const memoryUpdate: ToolDef = {
const parsed = MemoryUpdateInput.safeParse(args);
if (!parsed.success) return err(parsed.error.message);
const existing = await db
.select({ id: memories.id, content: memories.content })
const existingRows = await db
.select({
id: memories.id,
content: memories.content,
scope: memories.scope,
projectId: memories.projectId,
projectKey: projects.key,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(
and(
eq(memories.id, parsed.data.id),
@@ -336,30 +354,76 @@ const memoryUpdate: ToolDef = {
),
)
.limit(1);
if (!existing[0]) return err("not found");
const existing = existingRows[0];
if (!existing) return err("not found");
const update: Record<string, unknown> = { updatedAt: new Date() };
if (parsed.data.tags !== undefined) update.tags = parsed.data.tags;
if (parsed.data.content !== undefined && parsed.data.content !== existing[0].content) {
if (parsed.data.content !== undefined && parsed.data.content !== existing.content) {
update.content = parsed.data.content;
update.embedding = await embedText(parsed.data.content);
}
let scopeChanged = false;
let projectChanged = false;
let newProjectKey: string | null = existing.projectKey ?? null;
if (parsed.data.scope !== undefined) {
if (parsed.data.scope === "user") {
if (existing.scope !== "user") {
update.scope = "user";
scopeChanged = true;
}
if (existing.projectId !== null) {
update.projectId = null;
projectChanged = true;
newProjectKey = null;
}
} else {
// scope === 'project' — schema refine guarantees `project` is set
const projectKey = parsed.data.project!;
const projectId = await resolveProjectId(ctx, projectKey);
if (!projectId) {
return err(`unknown project '${projectKey}'; call project.identify first`);
}
if (existing.scope !== "project") {
update.scope = "project";
scopeChanged = true;
}
if (existing.projectId !== projectId) {
update.projectId = projectId;
projectChanged = true;
newProjectKey = projectKey;
}
}
}
const updated = await db
.update(memories)
.set(update)
.where(eq(memories.id, parsed.data.id))
.returning({ id: memories.id, updatedAt: memories.updatedAt });
const auditFields = Object.keys(update).filter((k) => k !== "updatedAt");
const auditPayload: Record<string, unknown> = { fields: auditFields };
if (scopeChanged || projectChanged) {
auditPayload.scope = {
from: existing.scope,
to: update.scope ?? existing.scope,
};
auditPayload.projectKey = {
from: existing.projectKey ?? null,
to: newProjectKey,
};
}
await db.insert(auditLog).values({
userId: ctx.userId,
actor: "mcp",
action: "memory.update",
entityType: "memory",
entityId: updated[0]!.id,
payload: {
fields: Object.keys(update).filter((k) => k !== "updatedAt"),
},
payload: auditPayload,
});
return ok(updated[0]!, `updated memory ${updated[0]!.id}`);
+64 -5
View File
@@ -113,41 +113,100 @@ export async function updateMemoryAction(formData: FormData) {
const userId = await requireUserId();
const id = String(formData.get("id") ?? "");
const rawScope = formData.get("scope");
const rawProject = (formData.get("project") as string | null)?.trim() || undefined;
const payload = {
id,
content: ((formData.get("content") as string | null) ?? "").trim() || undefined,
tags: parseTags(formData.get("tags")),
scope:
rawScope === "project" || rawScope === "user"
? (rawScope as "project" | "user")
: undefined,
project: rawProject,
};
const parsed = MemoryUpdateInput.safeParse(payload);
if (!parsed.success) {
throw new Error(parsed.error.issues.map((i) => i.message).join("; "));
}
const existing = await db
.select({ id: memories.id, content: memories.content })
const existingRows = await db
.select({
id: memories.id,
content: memories.content,
scope: memories.scope,
projectId: memories.projectId,
projectKey: projects.key,
})
.from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where(
and(eq(memories.id, parsed.data.id), eq(memories.userId, userId), isNull(memories.deletedAt)),
)
.limit(1);
if (!existing[0]) throw new Error("not found");
const existing = existingRows[0];
if (!existing) throw new Error("not found");
const update: Record<string, unknown> = { updatedAt: new Date() };
if (parsed.data.tags !== undefined) update.tags = parsed.data.tags;
if (parsed.data.content !== undefined && parsed.data.content !== existing[0].content) {
if (parsed.data.content !== undefined && parsed.data.content !== existing.content) {
update.content = parsed.data.content;
update.embedding = await embedText(parsed.data.content);
}
let scopeChanged = false;
let projectChanged = false;
let newProjectKey: string | null = existing.projectKey ?? null;
if (parsed.data.scope !== undefined) {
if (parsed.data.scope === "user") {
if (existing.scope !== "user") {
update.scope = "user";
scopeChanged = true;
}
if (existing.projectId !== null) {
update.projectId = null;
projectChanged = true;
newProjectKey = null;
}
} else {
// scope === 'project' — schema refine guarantees project is set
const projectKey = parsed.data.project!;
const projectId = await upsertProject(userId, projectKey);
if (existing.scope !== "project") {
update.scope = "project";
scopeChanged = true;
}
if (existing.projectId !== projectId) {
update.projectId = projectId;
projectChanged = true;
newProjectKey = projectKey;
}
}
}
await db.update(memories).set(update).where(eq(memories.id, parsed.data.id));
const auditFields = Object.keys(update).filter((k) => k !== "updatedAt");
const auditPayload: Record<string, unknown> = { fields: auditFields };
if (scopeChanged || projectChanged) {
auditPayload.scope = {
from: existing.scope,
to: update.scope ?? existing.scope,
};
auditPayload.projectKey = {
from: existing.projectKey ?? null,
to: newProjectKey,
};
}
await db.insert(auditLog).values({
userId,
actor: "web",
action: "memory.update",
entityType: "memory",
entityId: parsed.data.id,
payload: { fields: Object.keys(update).filter((k) => k !== "updatedAt") },
payload: auditPayload,
});
revalidatePath(`/memories/${parsed.data.id}`);