feat: Phase 4 - Notes + Graph + Wikilinks

- Wikilink parser: [[Title]], [[Title|Display]], [[entity_type:Title]] patterns
- Notes REST API: CRUD under /api/domains/[domainId]/notes/ with wikilink sync
- Note link service: idempotent wikilink resolution, backlinks, outgoing links
- Notes list page: search, filter (all/pinned/archived), domain selector
- Note editor: TipTap with backlinks panel and outgoing links display
- Graph data API: /api/domains/[domainId]/graph and /api/graph
- Graph view page: D3 force-directed graph with entity type filters, search, zoom
- Keyboard shortcuts: g g → graph, c n → new note
- 18 passing wikilink parser tests
- All API routes follow AGENTS.md contract (activity + pg_notify)
This commit is contained in:
2026-07-29 06:56:23 -04:00
parent 064a46f97d
commit 40a26d2672
14 changed files with 1827 additions and 135 deletions
@@ -0,0 +1,24 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, requireWorkspaceAccess } from '@/lib/auth';
import { getGraphData } from '@/lib/graph-service';
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/graph — Get graph data for one domain
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const graphData = await getGraphData(domainId);
return NextResponse.json(graphData, {
headers: {
'Cache-Control': 'private, max-age=30, stale-while-revalidate=120',
},
});
});
@@ -0,0 +1,23 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, requireWorkspaceAccess, createErrorResponse } from '@/lib/auth';
import { getBacklinks } from '@/lib/note-link-service';
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
// GET /api/domains/[domainId]/notes/[id]/backlinks — List notes that link to this one
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
const backlinks = await getBacklinks(id);
return NextResponse.json({
items: backlinks,
totalItems: backlinks.length,
});
});
@@ -0,0 +1,147 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
import { recordActivity } from '@/lib/activity';
import { db, notes, noteTags, tags as tagsTable } from '@project-e/db';
import { and, eq, inArray, isNull } from 'drizzle-orm';
import { z } from 'zod';
import { syncNoteLinks, getBacklinks, getOutgoingLinks } from '@/lib/note-link-service';
const updateNoteSchema = z.object({
title: z.string().min(1).optional(),
content: z.string().optional().nullable(),
isPinned: z.boolean().optional(),
isArchived: z.boolean().optional(),
});
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
// GET /api/domains/[domainId]/notes/[id] — Get a single note with computed links
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
const [note] = await db.select()
.from(notes)
.where(and(eq(notes.id, id), eq(notes.domainId, domainId), isNull(notes.deletedAt)))
.limit(1);
if (!note) {
return createErrorResponse('NOT_FOUND', 'Note not found', 404);
}
// Fetch tags
const tagRows = await db.select({
id: tagsTable.id,
name: tagsTable.name,
color: tagsTable.color,
})
.from(noteTags)
.innerJoin(tagsTable, eq(noteTags.tagId, tagsTable.id))
.where(eq(noteTags.noteId, id));
// Fetch backlinks and outgoing links
const [backlinks, outgoingLinks] = await Promise.all([
getBacklinks(id),
getOutgoingLinks(id),
]);
return NextResponse.json({
...note,
tags: tagRows,
backlinks,
outgoingLinks,
});
});
// PATCH /api/domains/[domainId]/notes/[id] — Update a note, re-parse wikilinks
export const PATCH = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = updateNoteSchema.parse(body);
const [existing] = await db.select()
.from(notes)
.where(and(eq(notes.id, id), eq(notes.domainId, domainId), isNull(notes.deletedAt)))
.limit(1);
if (!existing) {
return createErrorResponse('NOT_FOUND', 'Note not found', 404);
}
const updateValues: Record<string, unknown> = {};
if (data.title !== undefined) updateValues.title = data.title;
if (data.content !== undefined) updateValues.content = data.content;
if (data.isPinned !== undefined) updateValues.isPinned = data.isPinned;
if (data.isArchived !== undefined) updateValues.isArchived = data.isArchived;
updateValues.updatedAt = new Date();
const [updated] = await db.update(notes)
.set(updateValues)
.where(eq(notes.id, id))
.returning();
// Re-sync wikilinks if content changed
const content = data.content ?? existing.content;
if (content) {
await syncNoteLinks(id, content);
}
await recordActivity({
actor: user.name,
action: 'updated',
entityType: 'note',
entityId: id,
changes: { ...data, previousTitle: existing.title },
workspaceId: domainId,
});
return NextResponse.json(updated);
} catch (error) {
if (error instanceof z.ZodError) {
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
}
if (error instanceof ApiError) {
return createErrorResponse(error.code, error.message, error.status);
}
console.error('[notes PATCH] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to update note', 500);
}
});
// DELETE /api/domains/[domainId]/notes/[id] — Soft delete a note
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
const [existing] = await db.select()
.from(notes)
.where(and(eq(notes.id, id), eq(notes.domainId, domainId), isNull(notes.deletedAt)))
.limit(1);
if (!existing) {
return createErrorResponse('NOT_FOUND', 'Note not found', 404);
}
await db.update(notes)
.set({ deletedAt: new Date(), updatedAt: new Date() })
.where(eq(notes.id, id));
await recordActivity({
actor: user.name,
action: 'deleted',
entityType: 'note',
entityId: id,
changes: { title: existing.title },
workspaceId: domainId,
});
return new NextResponse(null, { status: 204 });
});
@@ -0,0 +1,123 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
import { recordActivity } from '@/lib/activity';
import { db, notes, noteTags, tags as tagsTable } from '@project-e/db';
import { and, eq, isNull } from 'drizzle-orm';
import { z } from 'zod';
const tagActionSchema = z.object({
tagId: z.string().uuid(),
});
type RouteContext = { params: Promise<{ domainId: string; id: string }> };
// POST /api/domains/[domainId]/notes/[id]/tags — Add a tag to a note
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = tagActionSchema.parse(body);
// Verify note exists
const [note] = await db.select()
.from(notes)
.where(and(eq(notes.id, id), eq(notes.domainId, domainId), isNull(notes.deletedAt)))
.limit(1);
if (!note) {
return createErrorResponse('NOT_FOUND', 'Note not found', 404);
}
// Verify tag exists
const [tag] = await db.select()
.from(tagsTable)
.where(eq(tagsTable.id, data.tagId))
.limit(1);
if (!tag) {
return createErrorResponse('NOT_FOUND', 'Tag not found', 404);
}
// Check if already tagged
const [existing] = await db.select()
.from(noteTags)
.where(and(eq(noteTags.noteId, id), eq(noteTags.tagId, data.tagId)))
.limit(1);
if (existing) {
return createErrorResponse('CONFLICT', 'Tag already added to this note', 409);
}
await db.insert(noteTags).values({ noteId: id, tagId: data.tagId });
await recordActivity({
actor: user.name,
action: 'tag_added',
entityType: 'note',
entityId: id,
changes: { tagId: data.tagId, tagName: tag.name },
workspaceId: domainId,
});
return NextResponse.json({ success: true }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
}
if (error instanceof ApiError) {
return createErrorResponse(error.code, error.message, error.status);
}
console.error('[note tags POST] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to add tag', 500);
}
});
// DELETE /api/domains/[domainId]/notes/[id]/tags — Remove a tag from a note
export const DELETE = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId, id } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = tagActionSchema.parse(body);
const [existing] = await db.select()
.from(noteTags)
.where(and(eq(noteTags.noteId, id), eq(noteTags.tagId, data.tagId)))
.limit(1);
if (!existing) {
return createErrorResponse('NOT_FOUND', 'Tag not found on this note', 404);
}
await db.delete(noteTags)
.where(and(eq(noteTags.noteId, id), eq(noteTags.tagId, data.tagId)));
await recordActivity({
actor: user.name,
action: 'tag_removed',
entityType: 'note',
entityId: id,
changes: { tagId: data.tagId },
workspaceId: domainId,
});
return NextResponse.json({ success: true });
} catch (error) {
if (error instanceof z.ZodError) {
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
}
if (error instanceof ApiError) {
return createErrorResponse(error.code, error.message, error.status);
}
console.error('[note tags DELETE] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to remove tag', 500);
}
});
@@ -0,0 +1,154 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth, requireWorkspaceAccess, createErrorResponse, ApiError } from '@/lib/auth';
import { recordActivity } from '@/lib/activity';
import { db, notes, noteTags, tags as tagsTable } from '@project-e/db';
import { and, asc, desc, eq, ilike, inArray, isNull, or, sql } from 'drizzle-orm';
import { z } from 'zod';
import { syncNoteLinks } from '@/lib/note-link-service';
const createNoteSchema = z.object({
title: z.string().min(1, 'Title is required'),
content: z.string().optional().nullable(),
isPinned: z.boolean().optional().default(false),
isArchived: z.boolean().optional().default(false),
tagIds: z.array(z.string().uuid()).optional(),
});
type RouteContext = { params: Promise<{ domainId: string }> };
// GET /api/domains/[domainId]/notes — List notes with filtering
export const GET = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
const { searchParams } = new URL(request.url);
const pinned = searchParams.get('pinned');
const archived = searchParams.get('archived');
const search = searchParams.get('search');
const limit = Math.min(parseInt(searchParams.get('limit') || '50'), 200);
const offset = parseInt(searchParams.get('offset') || '0');
const sort = searchParams.get('sort') || 'updated_at';
const order = searchParams.get('order') || 'desc';
const conditions: any[] = [
eq(notes.domainId, domainId),
isNull(notes.deletedAt),
];
if (pinned === 'true') conditions.push(eq(notes.isPinned, true));
if (archived === 'true') conditions.push(eq(notes.isArchived, true));
else if (archived !== 'all') conditions.push(eq(notes.isArchived, false));
if (search) conditions.push(ilike(notes.title, `%${search}%`));
const orderFn = order === 'desc' ? desc : asc;
let orderColumn;
switch (sort) {
case 'title': orderColumn = orderFn(notes.title); break;
case 'created_at': orderColumn = orderFn(notes.createdAt); break;
case 'is_pinned': orderColumn = orderFn(notes.isPinned); break;
default: orderColumn = orderFn(notes.updatedAt); break;
}
const [items, countResult] = await Promise.all([
db.select()
.from(notes)
.where(and(...conditions))
.orderBy(orderColumn)
.limit(limit)
.offset(offset),
db.select({ count: sql<number>`count(*)` })
.from(notes)
.where(and(...conditions)),
]);
const totalItems = Number(countResult[0]?.count || 0);
// Fetch tags for all notes
let noteTagMap = new Map<string, { id: string; name: string; color: string | null }[]>();
if (items.length > 0) {
const noteIds = items.map(n => n.id);
const tagRows = await db.select({
noteId: noteTags.noteId,
id: tagsTable.id,
name: tagsTable.name,
color: tagsTable.color,
})
.from(noteTags)
.innerJoin(tagsTable, eq(noteTags.tagId, tagsTable.id))
.where(inArray(noteTags.noteId, noteIds));
for (const row of tagRows) {
if (!noteTagMap.has(row.noteId)) noteTagMap.set(row.noteId, []);
noteTagMap.get(row.noteId)!.push({ id: row.id, name: row.name, color: row.color });
}
}
const itemsWithTags = items.map(n => ({
...n,
tags: noteTagMap.get(n.id) || [],
}));
return NextResponse.json({
items: itemsWithTags,
totalItems,
limit,
offset,
});
});
// POST /api/domains/[domainId]/notes — Create a note
export const POST = withAuth<RouteContext>(async (request: NextRequest, user, context) => {
const { domainId } = await context!.params;
await requireWorkspaceAccess(domainId);
try {
const body = await request.json();
const data = createNoteSchema.parse(body);
const [note] = await db.insert(notes).values({
title: data.title,
content: data.content ?? null,
domainId,
isPinned: data.isPinned,
isArchived: data.isArchived,
}).returning();
// Insert tags if provided
if (data.tagIds && data.tagIds.length > 0) {
await db.insert(noteTags).values(
data.tagIds.map(tagId => ({ noteId: note.id, tagId }))
);
}
// Sync wikilinks from content
if (data.content) {
await syncNoteLinks(note.id, data.content);
}
// Record activity
await recordActivity({
actor: user.name,
action: 'created',
entityType: 'note',
entityId: note.id,
changes: { title: note.title },
workspaceId: domainId,
});
return NextResponse.json(note, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return createErrorResponse('VALIDATION_ERROR', 'Invalid input', 400, error.issues);
}
if (error instanceof ApiError) {
return createErrorResponse(error.code, error.message, error.status);
}
console.error('[notes POST] error:', error);
return createErrorResponse('INTERNAL_ERROR', 'Failed to create note', 500);
}
});
+19
View File
@@ -0,0 +1,19 @@
// AGENT INSTRUCTION: After every write (INSERT/UPDATE/DELETE), you MUST:
// 1. Insert activity feed entry
// 2. Call pg.notify('project_e_events', JSON.stringify({ type, action, id, workspace_id }))
// See AGENTS.md for full rules.
import { NextRequest, NextResponse } from 'next/server';
import { withAuth } from '@/lib/auth';
import { getGlobalGraphData } from '@/lib/graph-service';
// GET /api/graph — Get global graph data (all domains the user has access to)
export const GET = withAuth(async (request: NextRequest, user) => {
const graphData = await getGlobalGraphData();
return NextResponse.json(graphData, {
headers: {
'Cache-Control': 'private, max-age=30, stale-while-revalidate=120',
},
});
});