Skip to content
Open
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
60 changes: 0 additions & 60 deletions .claude/settings.local.json

This file was deleted.

1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ coverage/

# MCP configs (contain API keys)
.claude/mcp.json
.claude/settings.local.json
.codex/mcp.json
.gemini/

Expand Down
24 changes: 21 additions & 3 deletions packages/server/src/__tests__/test-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,21 @@ export const TEST_API_KEY_HASH = _apiKeyHash;
export const TEST_AGENT_TOKEN = _agentToken;
export const TEST_AGENT_TOKEN_HASH = _agentTokenHash;

export const FAKE_ORGANIZATION = {
id: 'org_123',
name: 'test-org',
plan: 'free',
orgApiKeyHash: null,
createdAt: new Date(),
};

export const FAKE_WORKSPACE = {
id: 'ws_123',
name: 'test-workspace',
apiKeyHash: TEST_API_KEY_HASH,
systemPrompt: null,
plan: 'free' as const,
organizationId: 'org_123',
createdAt: new Date(),
metadata: {},
};
Expand Down Expand Up @@ -72,10 +81,16 @@ export function createMockKV(): KVNamespace {
* Create a mock DB that returns the fake workspace for workspace-key auth.
*/
export function mockDbForWorkspaceAuth() {
let callCount = 0;
return {
select: () => ({
from: () => ({
where: vi.fn().mockResolvedValue([FAKE_WORKSPACE]),
where: vi.fn().mockImplementation(() => {
callCount++;
// Auth middleware queries: 1=workspace, 2=organization
if (callCount % 2 === 1) return Promise.resolve([FAKE_WORKSPACE]);
return Promise.resolve([FAKE_ORGANIZATION]);
}),
}),
}),
insert: () => ({
Expand Down Expand Up @@ -110,8 +125,11 @@ export function mockDbForAgentAuth() {
from: () => ({
where: vi.fn().mockImplementation(() => {
callCount++;
if (callCount % 2 === 1) return Promise.resolve([FAKE_AGENT]);
return Promise.resolve([FAKE_WORKSPACE]);
// Auth middleware queries: 1=agent, 2=workspace, 3=organization, then repeats
const phase = ((callCount - 1) % 3) + 1;
if (phase === 1) return Promise.resolve([FAKE_AGENT]);
if (phase === 2) return Promise.resolve([FAKE_WORKSPACE]);
return Promise.resolve([FAKE_ORGANIZATION]);
}),
}),
}),
Expand Down
63 changes: 63 additions & 0 deletions packages/server/src/db/migrations/0002_organizations.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
-- Create users table
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
email_verified INTEGER NOT NULL DEFAULT 0,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

-- Create organizations table
CREATE TABLE IF NOT EXISTS organizations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
plan TEXT NOT NULL DEFAULT 'free',
org_api_key_hash TEXT UNIQUE,
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

-- Create org_memberships table
CREATE TABLE IF NOT EXISTS org_memberships (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
organization_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'member',
created_at INTEGER NOT NULL DEFAULT (unixepoch()),
PRIMARY KEY (user_id, organization_id)
);
CREATE INDEX IF NOT EXISTS idx_org_memberships_org ON org_memberships(organization_id);
CREATE INDEX IF NOT EXISTS idx_org_memberships_user ON org_memberships(user_id);

-- Create sessions table
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
active_org_id TEXT REFERENCES organizations(id),
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);

-- Create email_verifications table
CREATE TABLE IF NOT EXISTS email_verifications (
id TEXT PRIMARY KEY,
email TEXT NOT NULL,
code TEXT NOT NULL,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL DEFAULT (unixepoch())
);
CREATE INDEX IF NOT EXISTS idx_email_verifications_user ON email_verifications(user_id);

-- Add new columns to workspaces
ALTER TABLE workspaces ADD COLUMN organization_id TEXT REFERENCES organizations(id) ON DELETE CASCADE;
ALTER TABLE workspaces ADD COLUMN last_activity_at INTEGER;
ALTER TABLE workspaces ADD COLUMN deleted_at INTEGER;

-- Backfill: create a shadow org for each existing workspace and link them.
-- Uses the workspace id as the org id for simplicity in a one-time migration.
INSERT INTO organizations (id, name, created_at)
SELECT id, 'shadow-' || name, created_at FROM workspaces WHERE organization_id IS NULL;

UPDATE workspaces SET organization_id = id WHERE organization_id IS NULL;
93 changes: 92 additions & 1 deletion packages/server/src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,106 @@ import {
import { sql } from 'drizzle-orm';
import type { AnySQLiteColumn } from 'drizzle-orm/sqlite-core';

// ============================================
// Users
// ============================================
export const users = sqliteTable('users', {
id: text('id').primaryKey(),
email: text('email').notNull().unique(),
emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),
passwordHash: text('password_hash').notNull(),
name: text('name').notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
});

// ============================================
// Organizations
// ============================================
export const organizations = sqliteTable('organizations', {
id: text('id').primaryKey(),
name: text('name').notNull(),
plan: text('plan').notNull().default('free'),
orgApiKeyHash: text('org_api_key_hash').unique(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
});

// ============================================
// Org Memberships
// ============================================
export const orgMemberships = sqliteTable(
'org_memberships',
{
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
organizationId: text('organization_id')
.notNull()
.references(() => organizations.id, { onDelete: 'cascade' }),
role: text('role').notNull().default('member'), // 'owner' | 'admin' | 'member'
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
},
(table) => [
primaryKey({ columns: [table.userId, table.organizationId] }),
index('idx_org_memberships_org').on(table.organizationId),
index('idx_org_memberships_user').on(table.userId),
],
);

// ============================================
// Sessions (user auth)
// ============================================
export const sessions = sqliteTable(
'sessions',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
activeOrgId: text('active_org_id')
.references(() => organizations.id),
expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
},
(table) => [
index('idx_sessions_user').on(table.userId),
index('idx_sessions_expires').on(table.expiresAt),
],
);

// ============================================
// Email Verifications
// ============================================
export const emailVerifications = sqliteTable(
'email_verifications',
{
id: text('id').primaryKey(),
email: text('email').notNull(),
code: text('code').notNull(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
},
(table) => [
index('idx_email_verifications_user').on(table.userId),
],
);

// ============================================
// Workspaces
// ============================================
export const workspaces = sqliteTable('workspaces', {
id: text('id').primaryKey(),
organizationId: text('organization_id')
.notNull()
.references(() => organizations.id, { onDelete: 'cascade' }),
name: text('name').notNull().unique(),
apiKeyHash: text('api_key_hash').notNull().unique(),
systemPrompt: text('system_prompt'),
plan: text('plan').notNull().default('free'),
plan: text('plan').notNull().default('free'), // deprecated: read from org
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

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

The workspace schema still has a plan field (line 112) marked as deprecated with a comment "deprecated: read from org". However, the migration doesn't drop this column. This creates technical debt and potential confusion.

Either remove the field entirely from the schema (and update all code that references it), or document clearly that it's kept for backwards compatibility but should not be written to. Currently it's still being set with a default value which is wasteful.

Suggested change
plan: text('plan').notNull().default('free'), // deprecated: read from org
plan: text('plan').notNull(), // deprecated: read from org; kept for backwards compatibility, do not write to explicitly

Copilot uses AI. Check for mistakes.
lastActivityAt: integer('last_activity_at', { mode: 'timestamp' }),
deletedAt: integer('deleted_at', { mode: 'timestamp' }),
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`),
metadata: text('metadata', { mode: 'json' }).default('{}'),
});
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/engine/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { eq, and, ne, sql } from 'drizzle-orm';
import { files, agents } from '../db/schema.js';
import { generateId } from './snowflake.js';
import type { getDb } from '../db/index.js';
import { touchLastActivity } from './workspace.js';

type Db = ReturnType<typeof getDb>;

Expand Down Expand Up @@ -54,6 +55,8 @@ export async function createUpload(
});
const uploadUrl = await getSignedUrl(s3, command, { expiresIn: 3600 });

await touchLastActivity(db, workspaceId);

return {
id,
upload_url: uploadUrl,
Expand Down
4 changes: 3 additions & 1 deletion packages/server/src/engine/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { eq, and, sql, isNull, lt, gt, inArray } from 'drizzle-orm';
import type { getDb } from '../db/index.js';
import { messages, channels, agents, reactions, readReceipts, messageAttachments, files } from '../db/schema.js';
import { generateId } from './snowflake.js';
import { touchLastActivity } from './workspace.js';

type Db = ReturnType<typeof getDb>;

Expand Down Expand Up @@ -75,10 +76,11 @@ export async function postMessage(
await db.insert(messageAttachments).values(attachmentValues);
}

// Fetch attachment details and agent name
// Fetch attachment details and agent name; track activity
const [attachmentMap, [agent]] = await Promise.all([
hasAttachments ? fetchAttachmentsBatch(db, [messageId]) : Promise.resolve(new Map<string, AttachmentRow[]>()),
db.select({ name: agents.name }).from(agents).where(eq(agents.id, agentId)),
touchLastActivity(db, workspaceId),
]);
const attachments = attachmentMap.get(messageId) || [];

Expand Down
Loading
Loading