Files
shared-memory/apps/web/lib/db/schema.ts
T
shadowdaoandClaude Opus 4.7 fcc8708dd5 feat(snippets): named reusable artifacts with scope mirroring memories
Snippets are exact-name-keyed templates (PR formats, checklists, style
rules) — prescriptive artifacts the user wants applied consistently.
Distinct from memories, which are searched descriptive prose.

- Migration 0002 adds scope/project_id/deleted_at to snippets, partial
  unique indexes per scope, and a scope/project CHECK constraint
  mirroring memories_scope_project_chk.
- New @shared-memory/schemas: SnippetName/Put/Get/List/Delete inputs
  with shared scope-project refinement.
- lib/snippets.ts: get/put/list/softDelete helpers used by both the
  Web Server Actions and the MCP tool handlers.
- Four new MCP tools (snippet.put/get/list/delete) with directive
  descriptions contrasting against memory.* (exact-name lookup vs
  search; templates vs facts).
- /snippets pages: list, new, [name] with edit + delete and a
  scope-picker when a name lives in multiple scopes.
- Nav: Snippets link between Memories and Projects.

Design note: when a name exists in both user and project scope,
snippet.get without an explicit scope prefers project (if project key
given) then falls back to user. The detail page shows a picker when
the name is ambiguous and no scope query param was supplied.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 06:48:00 -07:00

191 lines
6.8 KiB
TypeScript

import {
pgTable,
pgEnum,
uuid,
text,
timestamp,
jsonb,
uniqueIndex,
index,
customType,
vector,
varchar,
} from "drizzle-orm/pg-core";
import { sql } from "drizzle-orm";
// ---------- custom column types ----------
// Postgres tsvector — generated server-side from `content`, not written by app.
const tsvector = customType<{ data: string; driverData: string }>({
dataType() {
return "tsvector";
},
});
// Text array helper (Drizzle's `.array()` works, but this keeps intent explicit).
const textArray = customType<{ data: string[]; driverData: string }>({
dataType() {
return "text[]";
},
toDriver(value) {
return `{${value.map((v) => `"${v.replace(/"/g, '\\"')}"`).join(",")}}`;
},
});
// ---------- enums ----------
export const memoryScope = pgEnum("memory_scope", ["project", "user"]);
export const memoryVisibility = pgEnum("memory_visibility", ["private", "shared", "team"]);
export const auditActor = pgEnum("audit_actor", ["mcp", "web", "system"]);
// ---------- tables ----------
export const users = pgTable(
"users",
{
id: uuid("id").primaryKey().defaultRandom(),
// OIDC `sub` claim from Authentik — stable identifier for this user.
oidcSub: text("oidc_sub").notNull(),
// OIDC `iss` so we can disambiguate if we ever federate.
oidcIss: text("oidc_iss").notNull(),
email: text("email"),
name: text("name"),
picture: text("picture"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => ({
uniqueIss: uniqueIndex("users_iss_sub_uq").on(t.oidcIss, t.oidcSub),
}),
);
export const projects = pgTable(
"projects",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
// Caller-supplied stable identifier (e.g. repo name or any string).
key: varchar("key", { length: 200 }).notNull(),
displayName: text("display_name"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => ({
uniqueUserKey: uniqueIndex("projects_user_key_uq").on(t.userId, t.key),
}),
);
export const memories = pgTable(
"memories",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
// NULL when scope = 'user' (global to the user across all projects).
projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
scope: memoryScope("scope").notNull().default("project"),
visibility: memoryVisibility("visibility").notNull().default("private"),
content: text("content").notNull(),
tags: textArray("tags").notNull().default([]),
// Populated by Phase 2 once the embedder sidecar is online; NULL in Phase 1.
embedding: vector("embedding", { dimensions: 384 }),
// Generated column — see migration SQL for definition.
contentTsv: tsvector("content_tsv"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
deletedAt: timestamp("deleted_at", { withTimezone: true }),
},
(t) => ({
userIdx: index("memories_user_idx").on(t.userId),
projectIdx: index("memories_project_idx").on(t.projectId),
createdIdx: index("memories_created_idx").on(t.createdAt),
// Vector index, tsvector index, and trigram index for tags are declared
// in the SQL migration since drizzle-kit doesn't model them.
}),
);
export const snippets = pgTable(
"snippets",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
// NULL when scope = 'user' (global to the user). Mirrors `memories`.
projectId: uuid("project_id").references(() => projects.id, { onDelete: "set null" }),
scope: memoryScope("scope").notNull().default("user"),
name: varchar("name", { length: 200 }).notNull(),
body: text("body").notNull(),
description: text("description"),
tags: textArray("tags").notNull().default([]),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
deletedAt: timestamp("deleted_at", { withTimezone: true }),
},
(t) => ({
userIdx: index("snippets_user_idx").on(t.userId),
projectIdx: index("snippets_project_idx").on(t.projectId),
// Partial unique indexes (one per scope, live rows only) are declared
// in the SQL migration since drizzle-kit doesn't model partial indexes.
}),
);
export const cliTokens = pgTable(
"cli_tokens",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
jti: text("jti").notNull().unique(),
name: text("name").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
lastUsedAt: timestamp("last_used_at", { withTimezone: true }),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
revokedAt: timestamp("revoked_at", { withTimezone: true }),
},
(t) => ({
userIdx: index("cli_tokens_user_idx").on(t.userId),
}),
);
export const auditLog = pgTable(
"audit_log",
{
id: uuid("id").primaryKey().defaultRandom(),
userId: uuid("user_id").references(() => users.id, { onDelete: "set null" }),
actor: auditActor("actor").notNull(),
action: text("action").notNull(),
entityType: text("entity_type"),
entityId: uuid("entity_id"),
payload: jsonb("payload"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(t) => ({
userIdx: index("audit_user_idx").on(t.userId),
createdIdx: index("audit_created_idx").on(t.createdAt),
}),
);
// Re-export sql helper so callers can compose raw fragments without a
// second drizzle import.
export { sql };
// ---------- inferred types ----------
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Project = typeof projects.$inferSelect;
export type NewProject = typeof projects.$inferInsert;
export type Memory = typeof memories.$inferSelect;
export type NewMemory = typeof memories.$inferInsert;
export type Snippet = typeof snippets.$inferSelect;
export type NewSnippet = typeof snippets.$inferInsert;
export type CliToken = typeof cliTokens.$inferSelect;
export type NewCliToken = typeof cliTokens.$inferInsert;
export type AuditEntry = typeof auditLog.$inferSelect;
export type NewAuditEntry = typeof auditLog.$inferInsert;