Merge: memory edit scope/project change (Agent A)

This commit is contained in:
2026-05-17 06:48:48 -07:00
4 changed files with 199 additions and 17 deletions
+44 -1
View File
@@ -1,6 +1,6 @@
import Link from "next/link"; import Link from "next/link";
import { notFound } from "next/navigation"; 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 { auth } from "@/auth";
import { db } from "@/lib/db/client"; import { db } from "@/lib/db/client";
import { memories, projects } from "@/lib/db/schema"; import { memories, projects } from "@/lib/db/schema";
@@ -48,6 +48,15 @@ export default async function MemoryDetailPage({
const isEditing = edit === "1"; 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 ( return (
<Container className="pt-6 max-w-3xl"> <Container className="pt-6 max-w-3xl">
<PageHeader <PageHeader
@@ -81,6 +90,40 @@ export default async function MemoryDetailPage({
<CardBody> <CardBody>
<form action={updateMemoryAction} className="space-y-4"> <form action={updateMemoryAction} className="space-y-4">
<input type="hidden" name="id" value={m.id} /> <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> <div>
<Label htmlFor="content">Content</Label> <Label htmlFor="content">Content</Label>
<Textarea <Textarea
+72 -8
View File
@@ -311,13 +311,24 @@ const memoryDelete: ToolDef = {
const memoryUpdate: ToolDef = { const memoryUpdate: ToolDef = {
name: "memory.update", name: "memory.update",
description: 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: { inputSchema: {
type: "object", type: "object",
properties: { properties: {
id: { type: "string", format: "uuid" }, id: { type: "string", format: "uuid" },
content: { type: "string", description: "Replacement content (164,000 chars)." }, content: { type: "string", description: "Replacement content (164,000 chars)." },
tags: { type: "array", items: { type: "string" }, description: "Replacement tag list." }, 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"], required: ["id"],
}, },
@@ -325,9 +336,16 @@ const memoryUpdate: ToolDef = {
const parsed = MemoryUpdateInput.safeParse(args); const parsed = MemoryUpdateInput.safeParse(args);
if (!parsed.success) return err(parsed.error.message); if (!parsed.success) return err(parsed.error.message);
const existing = await db const existingRows = await db
.select({ id: memories.id, content: memories.content }) .select({
id: memories.id,
content: memories.content,
scope: memories.scope,
projectId: memories.projectId,
projectKey: projects.key,
})
.from(memories) .from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where( .where(
and( and(
eq(memories.id, parsed.data.id), eq(memories.id, parsed.data.id),
@@ -336,30 +354,76 @@ const memoryUpdate: ToolDef = {
), ),
) )
.limit(1); .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() }; const update: Record<string, unknown> = { updatedAt: new Date() };
if (parsed.data.tags !== undefined) update.tags = parsed.data.tags; 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.content = parsed.data.content;
update.embedding = await embedText(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 const updated = await db
.update(memories) .update(memories)
.set(update) .set(update)
.where(eq(memories.id, parsed.data.id)) .where(eq(memories.id, parsed.data.id))
.returning({ id: memories.id, updatedAt: memories.updatedAt }); .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({ await db.insert(auditLog).values({
userId: ctx.userId, userId: ctx.userId,
actor: "mcp", actor: "mcp",
action: "memory.update", action: "memory.update",
entityType: "memory", entityType: "memory",
entityId: updated[0]!.id, entityId: updated[0]!.id,
payload: { payload: auditPayload,
fields: Object.keys(update).filter((k) => k !== "updatedAt"),
},
}); });
return ok(updated[0]!, `updated memory ${updated[0]!.id}`); 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 userId = await requireUserId();
const id = String(formData.get("id") ?? ""); const id = String(formData.get("id") ?? "");
const rawScope = formData.get("scope");
const rawProject = (formData.get("project") as string | null)?.trim() || undefined;
const payload = { const payload = {
id, id,
content: ((formData.get("content") as string | null) ?? "").trim() || undefined, content: ((formData.get("content") as string | null) ?? "").trim() || undefined,
tags: parseTags(formData.get("tags")), tags: parseTags(formData.get("tags")),
scope:
rawScope === "project" || rawScope === "user"
? (rawScope as "project" | "user")
: undefined,
project: rawProject,
}; };
const parsed = MemoryUpdateInput.safeParse(payload); const parsed = MemoryUpdateInput.safeParse(payload);
if (!parsed.success) { if (!parsed.success) {
throw new Error(parsed.error.issues.map((i) => i.message).join("; ")); throw new Error(parsed.error.issues.map((i) => i.message).join("; "));
} }
const existing = await db const existingRows = await db
.select({ id: memories.id, content: memories.content }) .select({
id: memories.id,
content: memories.content,
scope: memories.scope,
projectId: memories.projectId,
projectKey: projects.key,
})
.from(memories) .from(memories)
.leftJoin(projects, eq(memories.projectId, projects.id))
.where( .where(
and(eq(memories.id, parsed.data.id), eq(memories.userId, userId), isNull(memories.deletedAt)), and(eq(memories.id, parsed.data.id), eq(memories.userId, userId), isNull(memories.deletedAt)),
) )
.limit(1); .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() }; const update: Record<string, unknown> = { updatedAt: new Date() };
if (parsed.data.tags !== undefined) update.tags = parsed.data.tags; 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.content = parsed.data.content;
update.embedding = await embedText(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)); 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({ await db.insert(auditLog).values({
userId, userId,
actor: "web", actor: "web",
action: "memory.update", action: "memory.update",
entityType: "memory", entityType: "memory",
entityId: parsed.data.id, entityId: parsed.data.id,
payload: { fields: Object.keys(update).filter((k) => k !== "updatedAt") }, payload: auditPayload,
}); });
revalidatePath(`/memories/${parsed.data.id}`); revalidatePath(`/memories/${parsed.data.id}`);
+19 -3
View File
@@ -46,9 +46,25 @@ export const MemoryUpdateInput = z.object({
id: z.string().uuid(), id: z.string().uuid(),
content: MemoryContent.optional(), content: MemoryContent.optional(),
tags: Tags.optional(), tags: Tags.optional(),
}).refine((v) => v.content !== undefined || v.tags !== undefined, { scope: MemoryScope.optional(),
message: "memory.update requires content or tags", project: ProjectKey.optional(),
}); })
.refine(
(v) =>
v.content !== undefined ||
v.tags !== undefined ||
v.scope !== undefined ||
v.project !== undefined,
{ message: "memory.update requires content, tags, scope, or project" },
)
.refine(
(v) => v.scope !== "project" || (v.project !== undefined && v.project !== ""),
{ message: "scope='project' requires a non-empty project key" },
)
.refine(
(v) => v.scope !== "user" || v.project === undefined || v.project === "",
{ message: "scope='user' cannot have a project key" },
);
export type MemoryUpdateInput = z.infer<typeof MemoryUpdateInput>; export type MemoryUpdateInput = z.infer<typeof MemoryUpdateInput>;
export const MemorySearchInput = z.object({ export const MemorySearchInput = z.object({