moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
/**
* Agent Group Executor — converts agent group definitions into
* SubagentOrchestrator workflow templates and executes them.
*
* Strategies:
* - sequential: Execute members in executionOrder, each waits for previous
* - parallel: Execute all members simultaneously
* - coordinator: First member coordinates, others are workers
*/
import type { WorkflowTemplate, WorkflowStep } from '@waggle/agent';
interface AgentGroupMember {
agentId: string;
roleInGroup: string;
executionOrder: number;
// Joined from agents table:
name?: string;
role?: string;
systemPrompt?: string;
model?: string;
tools?: string[];
}
interface AgentGroupData {
id: string;
name: string;
description?: string;
strategy: string;
members: AgentGroupMember[];
}
/**
* Convert an agent group with its members into a WorkflowTemplate
* that the SubagentOrchestrator can execute.
*/
export function buildWorkflowFromGroup(group: AgentGroupData, task: string): WorkflowTemplate {
const strategy = group.strategy || 'sequential';
const steps: WorkflowStep[] = [...group.members]
.sort((a, b) => (a.executionOrder ?? 0) - (b.executionOrder ?? 0))
.map((member, index, arr) => {
const personaInstructions = member.systemPrompt?.trim()
? `\n\n## Agent Instructions\n${member.systemPrompt.trim()}`
: '';
const step: WorkflowStep = {
name: member.name ?? `agent-${member.agentId}`,
role: member.roleInGroup ?? member.role ?? 'worker',
task: `${task}${personaInstructions}`,
tools: member.tools,
maxTurns: 10,
model: member.model,
};
switch (strategy) {
case 'sequential':
// Each step depends on the previous one
if (index > 0) {
const prevName = arr[index - 1].name ?? `agent-${arr[index - 1].agentId}`;
step.dependsOn = [prevName];
step.contextFrom = [prevName];
}
break;
case 'parallel':
// No dependencies — all run simultaneously
break;
case 'coordinator':
// First member is coordinator, others depend on coordinator's output
if (index === 0) {
step.role = 'coordinator';
step.task = `You are the coordinator. Break down this task and delegate to your team:\n\n${step.task}`;
} else {
const coordinatorName = arr[0].name ?? `agent-${arr[0].agentId}`;
step.dependsOn = [coordinatorName];
step.contextFrom = [coordinatorName];
}
break;
}
return step;
});
// Choose aggregation based on strategy
const aggregation: WorkflowTemplate['aggregation'] =
strategy === 'coordinator' ? 'synthesize' :
strategy === 'parallel' ? 'concatenate' :
'last';
return {
name: group.name,
description: group.description ?? `Agent group: ${group.name}`,
steps,
aggregation,
};
}

View File

@@ -0,0 +1,212 @@
import { eq, and } from 'drizzle-orm';
import { agents, agentGroups, agentGroupMembers, agentJobs } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class AgentService {
constructor(private db: Db) {}
async create(userId: string, data: {
name: string;
role?: string;
systemPrompt?: string;
model?: string;
tools?: string[];
config?: Record<string, unknown>;
teamId?: string;
}) {
const [agent] = await this.db.insert(agents).values({
userId,
name: data.name,
role: data.role,
systemPrompt: data.systemPrompt,
model: data.model ?? 'claude-haiku-4-5',
tools: data.tools ?? [],
config: data.config ?? {},
teamId: data.teamId,
}).returning();
return agent;
}
async list(userId: string) {
return this.db
.select()
.from(agents)
.where(eq(agents.userId, userId));
}
async getById(id: string) {
const [agent] = await this.db
.select()
.from(agents)
.where(eq(agents.id, id))
.limit(1);
return agent ?? null;
}
async update(id: string, userId: string, data: {
name?: string;
role?: string;
systemPrompt?: string;
model?: string;
tools?: string[];
config?: Record<string, unknown>;
}) {
const setData: Record<string, unknown> = {};
if (data.name !== undefined) setData.name = data.name;
if (data.role !== undefined) setData.role = data.role;
if (data.systemPrompt !== undefined) setData.systemPrompt = data.systemPrompt;
if (data.model !== undefined) setData.model = data.model;
if (data.tools !== undefined) setData.tools = data.tools;
if (data.config !== undefined) setData.config = data.config;
if (Object.keys(setData).length === 0) return null;
const [updated] = await this.db
.update(agents)
.set(setData)
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
.returning();
return updated ?? null;
}
async delete(id: string, userId: string) {
// First remove agent from any groups
await this.db
.delete(agentGroupMembers)
.where(eq(agentGroupMembers.agentId, id));
const result = await this.db
.delete(agents)
.where(and(eq(agents.id, id), eq(agents.userId, userId)))
.returning();
return result.length > 0;
}
async createGroup(userId: string, data: {
name: string;
description?: string;
strategy: string;
members: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
}) {
return this.db.transaction(async (tx) => {
const [group] = await tx.insert(agentGroups).values({
userId,
name: data.name,
description: data.description,
strategy: data.strategy,
}).returning();
if (data.members.length > 0) {
await tx.insert(agentGroupMembers).values(
data.members.map((m) => ({
groupId: group.id,
agentId: m.agentId,
roleInGroup: m.roleInGroup ?? 'worker',
executionOrder: m.executionOrder ?? 0,
})),
);
}
const members = await tx
.select()
.from(agentGroupMembers)
.where(eq(agentGroupMembers.groupId, group.id));
return { ...group, members };
});
}
async listGroups(userId: string) {
return this.db
.select()
.from(agentGroups)
.where(eq(agentGroups.userId, userId));
}
async getGroup(groupId: string, userId: string) {
const [group] = await this.db
.select()
.from(agentGroups)
.where(and(eq(agentGroups.id, groupId), eq(agentGroups.userId, userId)))
.limit(1);
if (!group) return null;
const members = await this.db
.select()
.from(agentGroupMembers)
.where(eq(agentGroupMembers.groupId, groupId));
return { ...group, members };
}
async updateGroup(groupId: string, userId: string, data: {
name?: string;
description?: string;
strategy?: string;
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
}) {
// Verify ownership
const existing = await this.getGroup(groupId, userId);
if (!existing) return null;
return this.db.transaction(async (tx) => {
// Update group fields if any provided
const updates: Record<string, unknown> = {};
if (data.name != null) updates.name = data.name;
if (data.description != null) updates.description = data.description;
if (data.strategy != null) updates.strategy = data.strategy;
if (Object.keys(updates).length > 0) {
updates.updatedAt = new Date();
await tx.update(agentGroups).set(updates).where(eq(agentGroups.id, groupId));
}
// Replace members if provided
if (data.members) {
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
if (data.members.length > 0) {
await tx.insert(agentGroupMembers).values(
data.members.map(m => ({
groupId,
agentId: m.agentId,
roleInGroup: m.roleInGroup ?? 'worker',
executionOrder: m.executionOrder ?? 0,
})),
);
}
}
// Return updated group with members
const [group] = await tx.select().from(agentGroups).where(eq(agentGroups.id, groupId));
const members = await tx.select().from(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
return { ...group, members };
});
}
async deleteGroup(groupId: string, userId: string): Promise<boolean> {
const existing = await this.getGroup(groupId, userId);
if (!existing) return false;
await this.db.transaction(async (tx) => {
await tx.delete(agentGroupMembers).where(eq(agentGroupMembers.groupId, groupId));
await tx.delete(agentGroups).where(eq(agentGroups.id, groupId));
});
return true;
}
async createJob(userId: string, data: {
teamId: string;
jobType: string;
input: Record<string, unknown>;
}) {
const [job] = await this.db.insert(agentJobs).values({
userId,
teamId: data.teamId,
jobType: data.jobType,
status: 'queued',
input: data.input,
}).returning();
return job;
}
}

View File

@@ -0,0 +1,291 @@
import { eq, and, sql, count, desc, gte, lt } from 'drizzle-orm';
import {
teamMembers, users, tasks, agentAuditLog, agentJobs,
teamCapabilityRequests, messages,
} from '../db/schema.js';
import type { Db } from '../db/connection.js';
export interface AnalyticsResponse {
activeUsers: { daily: number; weekly: number; monthly: number };
tokenUsage: {
total: number;
byUser: Array<{ userId: string; name: string; tokens: number; cost: number }>;
};
topTools: Array<{ name: string; invocations: number }>;
topCommands: Array<{ name: string; count: number }>;
capabilityGaps: Array<{ tool: string; requestCount: number; suggestion: string }>;
performanceTrends: {
correctionRate: number;
correctionTrend: number;
avgResponseTime: number;
};
}
export class AnalyticsService {
constructor(private db: Db) {}
async getAnalytics(teamId: string): Promise<AnalyticsResponse> {
const [activeUsers, tokenUsage, topTools, topCommands, capabilityGaps, performanceTrends] =
await Promise.all([
this.getActiveUsers(teamId),
this.getTokenUsage(teamId),
this.getTopTools(teamId),
this.getTopCommands(teamId),
this.getCapabilityGaps(teamId),
this.getPerformanceTrends(teamId),
]);
return {
activeUsers,
tokenUsage,
topTools,
topCommands,
capabilityGaps,
performanceTrends,
};
}
/**
* Count active users based on audit log activity within time windows.
* Falls back to member count if no activity found.
*/
private async getActiveUsers(teamId: string) {
const now = new Date();
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const oneMonthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
const [dailyResult] = await this.db
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, oneDayAgo),
));
const [weeklyResult] = await this.db
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, oneWeekAgo),
));
const [monthlyResult] = await this.db
.select({ count: sql<number>`count(distinct ${agentAuditLog.userId})` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, oneMonthAgo),
));
return {
daily: Number(dailyResult?.count ?? 0),
weekly: Number(weeklyResult?.count ?? 0),
monthly: Number(monthlyResult?.count ?? 0),
};
}
/**
* Compute token usage from completed jobs.
* Since we don't have a dedicated token tracking table, we estimate from
* job outputs that may contain token counts, or fall back to job counts as proxy.
*/
private async getTokenUsage(teamId: string) {
// Get all members for this team
const members = await this.db
.select({
userId: teamMembers.userId,
displayName: users.displayName,
})
.from(teamMembers)
.innerJoin(users, eq(teamMembers.userId, users.id))
.where(eq(teamMembers.teamId, teamId));
// Count completed jobs per user as a proxy for usage
const jobCounts = await this.db
.select({
userId: agentJobs.userId,
jobCount: sql<number>`count(*)`,
})
.from(agentJobs)
.where(and(
eq(agentJobs.teamId, teamId),
eq(agentJobs.status, 'completed'),
))
.groupBy(agentJobs.userId);
const jobCountMap = new Map(jobCounts.map((j) => [j.userId, Number(j.jobCount)]));
// Estimate tokens: ~1000 tokens per completed job (rough proxy)
const TOKENS_PER_JOB = 1000;
const COST_PER_1K_TOKENS = 0.005;
const byUser = members.map((m) => {
const jobs = jobCountMap.get(m.userId) ?? 0;
const tokens = jobs * TOKENS_PER_JOB;
return {
userId: m.userId,
name: m.displayName,
tokens,
cost: Math.round((tokens / 1000) * COST_PER_1K_TOKENS * 100) / 100,
};
});
const total = byUser.reduce((sum, u) => sum + u.tokens, 0);
return { total, byUser };
}
/**
* Get top tools from audit log action types (tool invocations are logged as actions).
*/
private async getTopTools(teamId: string) {
const results = await this.db
.select({
name: agentAuditLog.actionType,
invocations: sql<number>`count(*)`,
})
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
))
.groupBy(agentAuditLog.actionType)
.orderBy(desc(sql`count(*)`))
.limit(10);
return results.map((r) => ({
name: r.name,
invocations: Number(r.invocations),
}));
}
/**
* Get top commands from audit log entries where actionType starts with 'command:'.
* Falls back to all action types containing 'command' or starting with '/'.
*/
private async getTopCommands(teamId: string) {
const results = await this.db
.select({
name: agentAuditLog.actionType,
count: sql<number>`count(*)`,
})
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
sql`${agentAuditLog.actionType} LIKE 'command:%'`,
))
.groupBy(agentAuditLog.actionType)
.orderBy(desc(sql`count(*)`))
.limit(10);
return results.map((r) => {
const stripped = r.name.replace(/^command:/, '');
return {
name: stripped.startsWith('/') ? stripped : `/${stripped}`,
count: Number(r.count),
};
});
}
/**
* Identify capability gaps from denied/pending capability requests.
*/
private async getCapabilityGaps(teamId: string) {
const results = await this.db
.select({
tool: teamCapabilityRequests.capabilityName,
requestCount: sql<number>`count(*)`,
})
.from(teamCapabilityRequests)
.where(and(
eq(teamCapabilityRequests.teamId, teamId),
sql`${teamCapabilityRequests.status} IN ('pending', 'rejected')`,
))
.groupBy(teamCapabilityRequests.capabilityName)
.orderBy(desc(sql`count(*)`))
.limit(10);
return results.map((r) => ({
tool: r.tool,
requestCount: Number(r.requestCount),
suggestion: `Install ${r.tool} connector or add to allowed tools`,
}));
}
/**
* Compute performance trends from audit log.
* - correctionRate: fraction of actions that were corrections/rejections
* - correctionTrend: difference between this week and last week correction rates
* - avgResponseTime: average time between job creation and completion (seconds)
*/
private async getPerformanceTrends(teamId: string) {
const now = new Date();
const oneWeekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
const twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);
// This week's correction rate
const [thisWeekTotal] = await this.db
.select({ count: sql<number>`count(*)` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, oneWeekAgo),
));
const [thisWeekRejected] = await this.db
.select({ count: sql<number>`count(*)` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, oneWeekAgo),
eq(agentAuditLog.approved, false),
));
// Last week's correction rate
const [lastWeekTotal] = await this.db
.select({ count: sql<number>`count(*)` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, twoWeeksAgo),
lt(agentAuditLog.createdAt, oneWeekAgo),
));
const [lastWeekRejected] = await this.db
.select({ count: sql<number>`count(*)` })
.from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
gte(agentAuditLog.createdAt, twoWeeksAgo),
lt(agentAuditLog.createdAt, oneWeekAgo),
eq(agentAuditLog.approved, false),
));
const thisWeekRate = Number(thisWeekTotal?.count) > 0
? Number(thisWeekRejected?.count ?? 0) / Number(thisWeekTotal.count)
: 0;
const lastWeekRate = Number(lastWeekTotal?.count) > 0
? Number(lastWeekRejected?.count ?? 0) / Number(lastWeekTotal.count)
: 0;
// Average response time from completed jobs
const [avgTime] = await this.db
.select({
avgSeconds: sql<number>`coalesce(avg(extract(epoch from (${agentJobs.completedAt} - ${agentJobs.createdAt}))), 0)`,
})
.from(agentJobs)
.where(and(
eq(agentJobs.teamId, teamId),
eq(agentJobs.status, 'completed'),
sql`${agentJobs.completedAt} IS NOT NULL`,
));
return {
correctionRate: Math.round(thisWeekRate * 100) / 100,
correctionTrend: Math.round((thisWeekRate - lastWeekRate) * 100) / 100,
avgResponseTime: Math.round(Number(avgTime?.avgSeconds ?? 0) * 10) / 10,
};
}
}

View File

@@ -0,0 +1,74 @@
import { eq, and, desc, isNull } from 'drizzle-orm';
import { agentAuditLog } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class AuditService {
constructor(private db: Db) {}
async log(entry: {
userId: string;
teamId?: string;
agentName: string;
actionType: string;
description: string;
beforeState?: Record<string, unknown>;
afterState?: Record<string, unknown>;
requiresApproval?: boolean;
}) {
const [created] = await this.db.insert(agentAuditLog).values({
userId: entry.userId,
teamId: entry.teamId ?? null,
agentName: entry.agentName,
actionType: entry.actionType,
description: entry.description,
beforeState: entry.beforeState ?? null,
afterState: entry.afterState ?? null,
requiresApproval: entry.requiresApproval ?? false,
}).returning();
return created;
}
async list(teamId: string, filters?: { actionType?: string; agentName?: string }) {
const conditions = [eq(agentAuditLog.teamId, teamId)];
if (filters?.actionType) conditions.push(eq(agentAuditLog.actionType, filters.actionType));
if (filters?.agentName) conditions.push(eq(agentAuditLog.agentName, filters.agentName));
return this.db.select().from(agentAuditLog)
.where(and(...conditions))
.orderBy(desc(agentAuditLog.createdAt))
.limit(100);
}
async getById(id: string) {
const [entry] = await this.db.select().from(agentAuditLog)
.where(eq(agentAuditLog.id, id))
.limit(1);
return entry ?? null;
}
async approve(entryId: string, approvedBy: string) {
const [updated] = await this.db.update(agentAuditLog)
.set({ approved: true, approvedBy })
.where(eq(agentAuditLog.id, entryId))
.returning();
return updated ?? null;
}
async reject(entryId: string, approvedBy: string) {
const [updated] = await this.db.update(agentAuditLog)
.set({ approved: false, approvedBy })
.where(eq(agentAuditLog.id, entryId))
.returning();
return updated ?? null;
}
async getPendingApprovals(teamId: string) {
return this.db.select().from(agentAuditLog)
.where(and(
eq(agentAuditLog.teamId, teamId),
eq(agentAuditLog.requiresApproval, true),
isNull(agentAuditLog.approved),
))
.orderBy(desc(agentAuditLog.createdAt));
}
}

View File

@@ -0,0 +1,82 @@
import { eq, and } from 'drizzle-orm';
import cronParser from 'cron-parser';
const { parseExpression } = cronParser;
import { cronSchedules } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export function getNextRunAt(cronExpr: string): Date {
const interval = parseExpression(cronExpr);
return interval.next().toDate();
}
export class CronService {
constructor(private db: Db) {}
async create(
teamId: string,
userId: string,
data: { name: string; cronExpr: string; jobType: string; jobConfig?: Record<string, unknown> },
) {
// Validate cron expression by parsing it
const nextRunAt = getNextRunAt(data.cronExpr);
const [schedule] = await this.db.insert(cronSchedules).values({
teamId,
createdBy: userId,
name: data.name,
cronExpr: data.cronExpr,
jobType: data.jobType,
jobConfig: data.jobConfig ?? {},
enabled: true,
nextRunAt,
}).returning();
return schedule;
}
async list(teamId: string) {
return this.db.select().from(cronSchedules)
.where(eq(cronSchedules.teamId, teamId));
}
async getById(id: string) {
const [schedule] = await this.db.select().from(cronSchedules)
.where(eq(cronSchedules.id, id));
return schedule ?? null;
}
async update(id: string, data: { name?: string; cronExpr?: string; enabled?: boolean; jobConfig?: Record<string, unknown> }) {
const updates: Record<string, unknown> = {};
if (data.name !== undefined) updates.name = data.name;
if (data.enabled !== undefined) updates.enabled = data.enabled;
if (data.jobConfig !== undefined) updates.jobConfig = data.jobConfig;
if (data.cronExpr !== undefined) {
updates.cronExpr = data.cronExpr;
updates.nextRunAt = getNextRunAt(data.cronExpr);
}
if (Object.keys(updates).length === 0) return null;
const [updated] = await this.db.update(cronSchedules)
.set(updates)
.where(eq(cronSchedules.id, id))
.returning();
return updated ?? null;
}
async markRun(id: string) {
const schedule = await this.getById(id);
if (!schedule) return null;
const now = new Date();
const nextRunAt = getNextRunAt(schedule.cronExpr);
const [updated] = await this.db.update(cronSchedules)
.set({ lastRunAt: now, nextRunAt })
.where(eq(cronSchedules.id, id))
.returning();
return updated ?? null;
}
}

View File

@@ -0,0 +1,90 @@
import { Queue } from 'bullmq';
import { eq, desc } from 'drizzle-orm';
import { agentJobs } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class JobService {
private queue: Queue;
constructor(private db: Db, redisUrl: string, queueName = 'waggle-jobs') {
const url = new URL(redisUrl);
this.queue = new Queue(queueName, {
connection: {
host: url.hostname,
port: parseInt(url.port || '6379'),
},
});
}
async createJob(teamId: string, userId: string, jobType: string, input: Record<string, unknown>) {
const [job] = await this.db.insert(agentJobs).values({
teamId,
userId,
jobType,
status: 'queued',
input,
}).returning();
await this.queue.add(jobType, {
jobId: job.id,
teamId,
userId,
jobType,
input,
}, { jobId: job.id });
return job;
}
async getJob(jobId: string) {
const [job] = await this.db.select().from(agentJobs).where(eq(agentJobs.id, jobId));
return job ?? null;
}
async listByTeam(teamId: string, limit = 50) {
return this.db.select().from(agentJobs)
.where(eq(agentJobs.teamId, teamId))
.orderBy(desc(agentJobs.createdAt))
.limit(Math.min(limit, 100));
}
async updateJobStatus(jobId: string, status: string, output?: Record<string, unknown>) {
const updates: Record<string, unknown> = { status };
if (status === 'running') updates.startedAt = new Date();
if (status === 'completed' || status === 'failed') {
updates.completedAt = new Date();
if (output) updates.output = output;
}
const [updated] = await this.db.update(agentJobs)
.set(updates)
.where(eq(agentJobs.id, jobId))
.returning();
return updated;
}
async cancelJob(jobId: string) {
// Update DB status
const updated = await this.updateJobStatus(jobId, 'cancelled');
// Try to remove from BullMQ queue
try {
const bullJob = await this.queue.getJob(jobId);
if (bullJob) {
const state = await bullJob.getState();
if (state === 'waiting' || state === 'delayed') {
await bullJob.remove();
} else if (state === 'active') {
await bullJob.moveToFailed(new Error('Cancelled by user'), 'cancelled', true);
}
}
} catch {
// Queue removal failed — DB status is still updated
}
return updated;
}
async close() {
await this.queue.close();
}
}

View File

@@ -0,0 +1,154 @@
import { eq, and, or, ilike, inArray } from 'drizzle-orm';
import { teamEntities, teamRelations } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export interface EntityFilters {
entityType?: string;
search?: string;
}
export class KnowledgeService {
constructor(private db: Db) {}
async createEntity(
teamId: string,
userId: string,
data: {
entityType: string;
name: string;
properties?: Record<string, unknown>;
validFrom?: string;
validTo?: string;
},
) {
const values: typeof teamEntities.$inferInsert = {
teamId,
entityType: data.entityType,
name: data.name,
properties: data.properties ?? {},
sharedBy: userId,
};
if (data.validFrom) values.validFrom = new Date(data.validFrom);
if (data.validTo) values.validTo = new Date(data.validTo);
const [entity] = await this.db.insert(teamEntities).values(values).returning();
return entity;
}
async listEntities(teamId: string, filters?: EntityFilters) {
const conditions = [eq(teamEntities.teamId, teamId)];
if (filters?.entityType) {
conditions.push(eq(teamEntities.entityType, filters.entityType));
}
if (filters?.search) {
conditions.push(ilike(teamEntities.name, `%${filters.search}%`));
}
return this.db
.select()
.from(teamEntities)
.where(and(...conditions));
}
async getEntity(entityId: string) {
const [entity] = await this.db
.select()
.from(teamEntities)
.where(eq(teamEntities.id, entityId))
.limit(1);
return entity ?? null;
}
async createRelation(
teamId: string,
data: {
sourceId: string;
targetId: string;
relationType: string;
confidence?: number;
properties?: Record<string, unknown>;
},
) {
const [relation] = await this.db.insert(teamRelations).values({
teamId,
sourceId: data.sourceId,
targetId: data.targetId,
relationType: data.relationType,
confidence: data.confidence ?? 1.0,
properties: data.properties ?? {},
}).returning();
return relation;
}
async queryGraph(
teamId: string,
startEntityId: string,
depth: number = 2,
relationTypes?: string[],
) {
const visited = new Set<string>([startEntityId]);
const resultEntities: Array<typeof teamEntities.$inferSelect> = [];
const resultRelations: Array<typeof teamRelations.$inferSelect> = [];
let frontier = [startEntityId];
for (let d = 0; d < depth && frontier.length > 0; d++) {
// Find relations connected to frontier entities
const rels = await this.db
.select()
.from(teamRelations)
.where(
and(
eq(teamRelations.teamId, teamId),
or(
inArray(teamRelations.sourceId, frontier),
inArray(teamRelations.targetId, frontier),
),
),
);
// Apply relationTypes filter if provided
const filteredRels = relationTypes
? rels.filter((r) => relationTypes.includes(r.relationType))
: rels;
const nextFrontier: string[] = [];
for (const rel of filteredRels) {
resultRelations.push(rel);
for (const id of [rel.sourceId, rel.targetId]) {
if (!visited.has(id)) {
visited.add(id);
nextFrontier.push(id);
}
}
}
if (nextFrontier.length > 0) {
const entities = await this.db
.select()
.from(teamEntities)
.where(
and(
eq(teamEntities.teamId, teamId),
inArray(teamEntities.id, nextFrontier),
),
);
resultEntities.push(...entities);
}
frontier = nextFrontier;
}
// Fetch the start entity
const [startEntity] = await this.db
.select()
.from(teamEntities)
.where(eq(teamEntities.id, startEntityId));
return {
entities: [startEntity, ...resultEntities].filter(Boolean),
relations: resultRelations,
};
}
}

View File

@@ -0,0 +1,119 @@
import { eq, and, desc, sql } from 'drizzle-orm';
import { messages, teamEntities, tasks } from '../db/schema.js';
import type { Db } from '../db/connection.js';
import type { HiveQuery, HiveQueryResult } from '@waggle/waggle-dance';
import type Redis from 'ioredis';
export interface MessageFilters {
type?: string;
subtype?: string;
}
export class MessageService {
constructor(private db: Db) {}
async send(
teamId: string,
senderId: string,
data: {
type: string;
subtype: string;
content: Record<string, unknown>;
referenceId?: string;
routing?: Array<{ userId: string; reason: string }>;
},
redis?: Redis,
) {
const [message] = await this.db.insert(messages).values({
teamId,
senderId,
type: data.type,
subtype: data.subtype,
content: data.content,
referenceId: data.referenceId ?? null,
routing: data.routing ?? null,
}).returning();
// Publish to Redis for real-time delivery
if (redis) {
await redis.publish(`team:${teamId}:waggle`, JSON.stringify(message));
}
return message;
}
async list(teamId: string, filters?: MessageFilters) {
const conditions = [eq(messages.teamId, teamId)];
if (filters?.type) {
conditions.push(eq(messages.type, filters.type));
}
if (filters?.subtype) {
conditions.push(eq(messages.subtype, filters.subtype));
}
return this.db
.select()
.from(messages)
.where(and(...conditions))
.orderBy(desc(messages.createdAt));
}
async checkHive(teamId: string, query: HiveQuery): Promise<HiveQueryResult> {
const searchTerm = `%${query.topic}%`;
// Search team_entities by name or entityType matching the topic
const entities = await this.db
.select({
id: teamEntities.id,
name: teamEntities.name,
entityType: teamEntities.entityType,
properties: teamEntities.properties,
})
.from(teamEntities)
.where(
and(
eq(teamEntities.teamId, teamId),
sql`(${teamEntities.name} ILIKE ${searchTerm} OR ${teamEntities.entityType} ILIKE ${searchTerm})`,
),
)
.limit(10);
// Search tasks by title or description matching the topic
const relatedTasks = await this.db
.select({
id: tasks.id,
title: tasks.title,
status: tasks.status,
createdBy: tasks.createdBy,
})
.from(tasks)
.where(
and(
eq(tasks.teamId, teamId),
sql`(${tasks.title} ILIKE ${searchTerm} OR ${tasks.description} ILIKE ${searchTerm})`,
),
)
.limit(10);
// Search recent broadcast messages
const relatedMessages = await this.db
.select({
id: messages.id,
type: messages.type,
subtype: messages.subtype,
content: messages.content,
})
.from(messages)
.where(
and(
eq(messages.teamId, teamId),
eq(messages.type, 'broadcast'),
),
)
.orderBy(desc(messages.createdAt))
.limit(10);
return { entities, relatedTasks, relatedMessages };
}
}

View File

@@ -0,0 +1,95 @@
import { eq, and, desc } from 'drizzle-orm';
import { proactivePatterns, suggestionsLog } from '../db/schema.js';
import type { Db } from '../db/connection.js';
import { MAX_SUGGESTIONS_PER_INTERACTION } from '@waggle/shared';
import { BUILT_IN_PATTERNS } from '../proactive/patterns.js';
export class ProactiveService {
constructor(private db: Db) {}
async ensurePatternsSeeded() {
const existing = await this.db.select().from(proactivePatterns);
if (existing.length === 0) {
for (const p of BUILT_IN_PATTERNS) {
await this.db.insert(proactivePatterns).values({
name: p.name,
trigger: { condition: p.triggerCondition },
suggestionType: p.suggestionType,
template: p.template,
});
}
}
}
async evaluate(userId: string, jobContext: Record<string, unknown>) {
// Check if user already has max pending suggestions
const pending = await this.db.select().from(suggestionsLog)
.where(and(
eq(suggestionsLog.userId, userId),
eq(suggestionsLog.status, 'pending'),
));
if (pending.length >= MAX_SUGGESTIONS_PER_INTERACTION) return null;
// Get active patterns
const patterns = await this.db.select().from(proactivePatterns)
.where(eq(proactivePatterns.enabled, true));
for (const pattern of patterns) {
const shouldTrigger = this.matchPattern(pattern, jobContext);
if (!shouldTrigger) continue;
// Check if already dismissed for this pattern
const dismissed = await this.db.select().from(suggestionsLog)
.where(and(
eq(suggestionsLog.userId, userId),
eq(suggestionsLog.patternId, pattern.id),
eq(suggestionsLog.status, 'dismissed'),
));
if (dismissed.length > 0) continue;
// Create suggestion
const [suggestion] = await this.db.insert(suggestionsLog).values({
userId,
patternId: pattern.id,
context: jobContext,
status: 'pending',
}).returning();
return { ...suggestion, pattern };
}
return null;
}
private matchPattern(
pattern: { suggestionType: string },
context: Record<string, unknown>,
): boolean {
const triggerType = pattern.suggestionType;
if (triggerType === 'cron' && context.repeatCount && (context.repeatCount as number) >= 3) return true;
if (triggerType === 'dashboard' && context.hasData) return true;
if (triggerType === 'share' && context.relevantUsers) return true;
if (triggerType === 'upgrade' && context.expensiveModel) return true;
if (triggerType === 'skill' && context.manualSteps) return true;
return false;
}
async listPending(userId: string) {
return this.db.select().from(suggestionsLog)
.where(and(
eq(suggestionsLog.userId, userId),
eq(suggestionsLog.status, 'pending'),
))
.orderBy(desc(suggestionsLog.createdAt));
}
async updateStatus(suggestionId: string, status: 'accepted' | 'dismissed' | 'snoozed') {
const [updated] = await this.db.update(suggestionsLog)
.set({ status })
.where(eq(suggestionsLog.id, suggestionId))
.returning();
return updated ?? null;
}
}

View File

@@ -0,0 +1,77 @@
import { eq, and } from 'drizzle-orm';
import { teamResources } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class ResourceService {
constructor(private db: Db) {}
async share(
teamId: string,
userId: string,
data: {
resourceType: string;
name: string;
description?: string;
config: Record<string, unknown>;
},
) {
const [resource] = await this.db.insert(teamResources).values({
teamId,
resourceType: data.resourceType,
name: data.name,
description: data.description ?? null,
config: data.config,
sharedBy: userId,
rating: 0,
useCount: 0,
}).returning();
return resource;
}
async list(teamId: string, resourceType?: string) {
const conditions = [eq(teamResources.teamId, teamId)];
if (resourceType) {
conditions.push(eq(teamResources.resourceType, resourceType));
}
return this.db
.select()
.from(teamResources)
.where(and(...conditions));
}
async rate(resourceId: string, rating: number) {
const [resource] = await this.db
.select()
.from(teamResources)
.where(eq(teamResources.id, resourceId))
.limit(1);
if (!resource) return null;
const newRating = resource.useCount > 0
? (resource.rating * resource.useCount + rating) / (resource.useCount + 1)
: rating;
const [updated] = await this.db.update(teamResources)
.set({ rating: newRating })
.where(eq(teamResources.id, resourceId))
.returning();
return updated;
}
async incrementUseCount(resourceId: string) {
const [resource] = await this.db
.select()
.from(teamResources)
.where(eq(teamResources.id, resourceId))
.limit(1);
if (!resource) return null;
const [updated] = await this.db.update(teamResources)
.set({ useCount: resource.useCount + 1 })
.where(eq(teamResources.id, resourceId))
.returning();
return updated;
}
}

View File

@@ -0,0 +1,91 @@
import { eq, and } from 'drizzle-orm';
import { tasks } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export interface TaskFilters {
status?: string;
assignee?: string;
priority?: string;
}
export class TaskService {
constructor(private db: Db) {}
async create(
teamId: string,
userId: string,
data: { title: string; description?: string; priority?: string; parentTaskId?: string },
) {
const [task] = await this.db.insert(tasks).values({
teamId,
title: data.title,
description: data.description,
priority: data.priority ?? 'normal',
createdBy: userId,
parentTaskId: data.parentTaskId,
}).returning();
return task;
}
async list(teamId: string, filters?: TaskFilters) {
const conditions = [eq(tasks.teamId, teamId)];
if (filters?.status) {
conditions.push(eq(tasks.status, filters.status));
}
if (filters?.assignee) {
conditions.push(eq(tasks.assignedTo, filters.assignee));
}
if (filters?.priority) {
conditions.push(eq(tasks.priority, filters.priority));
}
return this.db
.select()
.from(tasks)
.where(and(...conditions));
}
async get(taskId: string) {
const [task] = await this.db
.select()
.from(tasks)
.where(eq(tasks.id, taskId))
.limit(1);
return task ?? null;
}
async update(
taskId: string,
data: {
title?: string;
description?: string;
status?: string;
priority?: string;
assignedTo?: string | null;
},
) {
const setData: Record<string, unknown> = { updatedAt: new Date() };
if (data.title !== undefined) setData.title = data.title;
if (data.description !== undefined) setData.description = data.description;
if (data.status !== undefined) setData.status = data.status;
if (data.priority !== undefined) setData.priority = data.priority;
if (data.assignedTo !== undefined) setData.assignedTo = data.assignedTo;
const [updated] = await this.db
.update(tasks)
.set(setData)
.where(eq(tasks.id, taskId))
.returning();
return updated ?? null;
}
async claim(taskId: string, userId: string) {
const [updated] = await this.db
.update(tasks)
.set({ assignedTo: userId, status: 'claimed', updatedAt: new Date() })
.where(eq(tasks.id, taskId))
.returning();
return updated ?? null;
}
}

View File

@@ -0,0 +1,369 @@
import { eq, and, desc } from 'drizzle-orm';
import { RISK_LEVELS, riskRank, type RiskLevel } from '@waggle/shared';
import {
teamCapabilityPolicies,
teamCapabilityOverrides,
teamCapabilityRequests,
} from '../db/schema.js';
import type { DbExecutor } from '../db/connection.js';
export interface EffectivePermissions {
role: string;
allowedSources: string[];
blockedTools: string[];
approvalThreshold: string;
overrides: Map<string, 'approved' | 'blocked'>;
}
export type PermissionResult =
| 'allowed'
| 'blocked'
| 'needs_approval'
| 'source_not_allowed';
/**
* Rank a governance risk string on the canonical scale (P7/D15 A2b). The
* governance domain adds a 'none' tier (below 'low') that the canonical set
* doesn't have. Anything else falls back to canonical riskRank, so 'critical'
* (rank 3) correctly outranks 'low' (0) — the previous local map omitted
* 'critical', so `?? 0` sorted a critical risk BELOW low (a silent RBAC defect).
*/
function governanceRiskRank(level: string): number {
if (level === 'none') return -1;
return (RISK_LEVELS as readonly string[]).includes(level)
? riskRank(level as RiskLevel)
: -1;
}
/**
* Check if a given risk level exceeds the threshold.
* Threshold 'none' means nothing triggers approval.
*/
export function riskExceedsThreshold(risk: string, threshold: string): boolean {
if (threshold === 'none') return false;
return governanceRiskRank(risk) > governanceRiskRank(threshold);
}
/**
* Resolve permission for a single capability against effective permissions.
*
* Resolution order:
* 1. Check overrides — if override exists, return its decision immediately
* 2. Check role policy (source allowed? tool blocked?)
* 3. If policy allows but risk exceeds threshold → needs_approval
* 4. Otherwise → allowed
*/
export function resolvePermission(
perms: EffectivePermissions,
capabilityName: string,
capabilityType: string,
risk: string = 'low',
): PermissionResult {
// 1. Override wins
const override = perms.overrides.get(capabilityName);
if (override === 'approved') return 'allowed';
if (override === 'blocked') return 'blocked';
// 2. Blocked tool check
if (perms.blockedTools.includes(capabilityName)) return 'blocked';
// 3. Source allowed check
if (!perms.allowedSources.includes(capabilityType)) return 'source_not_allowed';
// 4. Risk threshold check
if (riskExceedsThreshold(risk, perms.approvalThreshold)) return 'needs_approval';
return 'allowed';
}
/**
* Filter a list of capabilities by permissions, returning only those allowed or needing approval.
*/
export function filterByPermissions(
perms: EffectivePermissions,
capabilities: Array<{ name: string; type: string; risk?: string }>,
): Array<{ name: string; type: string; risk?: string; result: PermissionResult }> {
return capabilities.map((cap) => ({
...cap,
result: resolvePermission(perms, cap.name, cap.type, cap.risk ?? 'low'),
}));
}
export interface DefaultPolicy {
role: string;
allowedSources: string[];
blockedTools: string[];
approvalThreshold: string;
}
/**
* Returns the 3 default role policies for a new team.
*/
export function getDefaultPolicies(): DefaultPolicy[] {
return [
{
role: 'owner',
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
blockedTools: [],
approvalThreshold: 'none',
},
{
role: 'admin',
allowedSources: ['native', 'skill', 'plugin', 'mcp'],
blockedTools: [],
approvalThreshold: 'none',
},
{
role: 'member',
allowedSources: ['native', 'skill'],
blockedTools: ['bash', 'delete_skill'],
approvalThreshold: 'medium',
},
];
}
export class TeamCapabilityGovernance {
constructor(private db: DbExecutor) {}
/**
* Get effective permissions for a role in a team, including overrides.
*/
async getEffectivePermissions(teamId: string, role: string): Promise<EffectivePermissions> {
// Get role policy
const [policy] = await this.db
.select()
.from(teamCapabilityPolicies)
.where(and(
eq(teamCapabilityPolicies.teamId, teamId),
eq(teamCapabilityPolicies.role, role),
))
.limit(1);
// Get overrides for this team
const overrideRows = await this.db
.select()
.from(teamCapabilityOverrides)
.where(eq(teamCapabilityOverrides.teamId, teamId));
const overrides = new Map<string, 'approved' | 'blocked'>();
for (const row of overrideRows) {
overrides.set(row.capabilityName, row.decision as 'approved' | 'blocked');
}
if (!policy) {
// Fallback: no policy found, restrictive defaults
return {
role,
allowedSources: [],
blockedTools: [],
approvalThreshold: 'none',
overrides,
};
}
return {
role,
allowedSources: policy.allowedSources as string[],
blockedTools: policy.blockedTools as string[],
approvalThreshold: policy.approvalThreshold,
overrides,
};
}
async listPolicies(teamId: string) {
return this.db
.select()
.from(teamCapabilityPolicies)
.where(eq(teamCapabilityPolicies.teamId, teamId));
}
async upsertPolicy(
teamId: string,
role: string,
data: {
allowedSources?: string[];
blockedTools?: string[];
approvalThreshold?: string;
},
updatedBy: string,
) {
const [existing] = await this.db
.select()
.from(teamCapabilityPolicies)
.where(and(
eq(teamCapabilityPolicies.teamId, teamId),
eq(teamCapabilityPolicies.role, role),
))
.limit(1);
if (existing) {
const [updated] = await this.db
.update(teamCapabilityPolicies)
.set({
...(data.allowedSources !== undefined && { allowedSources: data.allowedSources }),
...(data.blockedTools !== undefined && { blockedTools: data.blockedTools }),
...(data.approvalThreshold !== undefined && { approvalThreshold: data.approvalThreshold }),
updatedBy,
updatedAt: new Date(),
})
.where(eq(teamCapabilityPolicies.id, existing.id))
.returning();
return updated;
}
const defaults = getDefaultPolicies().find((p) => p.role === role);
const [created] = await this.db
.insert(teamCapabilityPolicies)
.values({
teamId,
role,
allowedSources: data.allowedSources ?? defaults?.allowedSources ?? [],
blockedTools: data.blockedTools ?? defaults?.blockedTools ?? [],
approvalThreshold: data.approvalThreshold ?? defaults?.approvalThreshold ?? 'none',
updatedBy,
})
.returning();
return created;
}
async seedDefaultPolicies(teamId: string, seedBy: string) {
const defaults = getDefaultPolicies();
const results = [];
for (const policy of defaults) {
const [row] = await this.db
.insert(teamCapabilityPolicies)
.values({
teamId,
role: policy.role,
allowedSources: policy.allowedSources,
blockedTools: policy.blockedTools,
approvalThreshold: policy.approvalThreshold,
updatedBy: seedBy,
})
.returning();
results.push(row);
}
return results;
}
// --- Overrides ---
async listOverrides(teamId: string) {
return this.db
.select()
.from(teamCapabilityOverrides)
.where(eq(teamCapabilityOverrides.teamId, teamId))
.orderBy(desc(teamCapabilityOverrides.createdAt));
}
async createOverride(
teamId: string,
data: {
capabilityName: string;
capabilityType: string;
decision: 'approved' | 'blocked';
reason?: string;
},
decidedBy: string,
) {
const [row] = await this.db
.insert(teamCapabilityOverrides)
.values({
teamId,
capabilityName: data.capabilityName,
capabilityType: data.capabilityType,
decision: data.decision,
reason: data.reason ?? '',
decidedBy,
})
.returning();
return row;
}
async deleteOverride(overrideId: string) {
const [deleted] = await this.db
.delete(teamCapabilityOverrides)
.where(eq(teamCapabilityOverrides.id, overrideId))
.returning();
return deleted ?? null;
}
// --- Requests ---
async listRequests(teamId: string, status?: string) {
const conditions = [eq(teamCapabilityRequests.teamId, teamId)];
if (status) {
conditions.push(eq(teamCapabilityRequests.status, status));
}
return this.db
.select()
.from(teamCapabilityRequests)
.where(and(...conditions))
.orderBy(desc(teamCapabilityRequests.createdAt));
}
async submitRequest(
teamId: string,
requestedBy: string,
data: {
capabilityName: string;
capabilityType: string;
justification: string;
},
): Promise<{ duplicate: true } | { duplicate: false; request: typeof teamCapabilityRequests.$inferSelect }> {
// Duplicate check: pending request for same capability by same user
const [existing] = await this.db
.select()
.from(teamCapabilityRequests)
.where(and(
eq(teamCapabilityRequests.teamId, teamId),
eq(teamCapabilityRequests.requestedBy, requestedBy),
eq(teamCapabilityRequests.capabilityName, data.capabilityName),
eq(teamCapabilityRequests.status, 'pending'),
))
.limit(1);
if (existing) return { duplicate: true };
const [request] = await this.db
.insert(teamCapabilityRequests)
.values({
teamId,
requestedBy,
capabilityName: data.capabilityName,
capabilityType: data.capabilityType,
justification: data.justification,
})
.returning();
return { duplicate: false, request };
}
async getRequest(requestId: string) {
const [row] = await this.db
.select()
.from(teamCapabilityRequests)
.where(eq(teamCapabilityRequests.id, requestId))
.limit(1);
return row ?? null;
}
async decideRequest(
requestId: string,
decidedBy: string,
decision: 'approved' | 'rejected',
reason?: string,
) {
const [updated] = await this.db
.update(teamCapabilityRequests)
.set({
status: decision,
decidedBy,
decisionReason: reason ?? null,
decidedAt: new Date(),
})
.where(eq(teamCapabilityRequests.id, requestId))
.returning();
return updated ?? null;
}
}

View File

@@ -0,0 +1,131 @@
import { eq, and, sql } from 'drizzle-orm';
import { teams, teamMembers, users } from '../db/schema.js';
import type { Db } from '../db/connection.js';
import { TeamCapabilityGovernance } from './team-capability-governance.js';
export class TeamService {
constructor(private db: Db) {}
async create(ownerId: string, data: { name: string; slug: string }) {
return this.db.transaction(async (tx) => {
const [team] = await tx.insert(teams).values({
name: data.name,
slug: data.slug,
ownerId,
}).returning();
await tx.insert(teamMembers).values({
teamId: team.id,
userId: ownerId,
role: 'owner',
});
// Seed default capability policies
const governance = new TeamCapabilityGovernance(tx);
await governance.seedDefaultPolicies(team.id, ownerId);
return team;
});
}
async getBySlug(slug: string) {
const [team] = await this.db.select().from(teams).where(eq(teams.slug, slug)).limit(1);
return team ?? null;
}
async listForUser(userId: string) {
const rows = await this.db
.select({
id: teams.id,
name: teams.name,
slug: teams.slug,
ownerId: teams.ownerId,
createdAt: teams.createdAt,
role: teamMembers.role,
})
.from(teamMembers)
.innerJoin(teams, eq(teamMembers.teamId, teams.id))
.where(eq(teamMembers.userId, userId));
return rows;
}
async update(teamId: string, data: { name: string }) {
const [updated] = await this.db
.update(teams)
.set({ name: data.name })
.where(eq(teams.id, teamId))
.returning();
return updated ?? null;
}
async addMember(teamId: string, userId: string, role: 'admin' | 'member') {
const [member] = await this.db.insert(teamMembers).values({
teamId,
userId,
role,
}).returning();
return member;
}
async removeMember(teamId: string, userId: string) {
// Prevent removing the owner
const membership = await this.getMembership(teamId, userId);
if (!membership) return false;
if (membership.role === 'owner') {
throw new Error('Cannot remove the team owner');
}
await this.db
.delete(teamMembers)
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
return true;
}
async updateMember(
teamId: string,
userId: string,
data: { role?: 'admin' | 'member'; roleDescription?: string; interests?: string[] },
) {
const setData: Record<string, unknown> = {};
if (data.role !== undefined) setData.role = data.role;
if (data.roleDescription !== undefined) setData.roleDescription = data.roleDescription;
if (data.interests !== undefined) setData.interests = data.interests;
if (Object.keys(setData).length === 0) return null;
const [updated] = await this.db
.update(teamMembers)
.set(setData)
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
.returning();
return updated ?? null;
}
async getMembership(teamId: string, userId: string) {
const [membership] = await this.db
.select()
.from(teamMembers)
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)))
.limit(1);
return membership ?? null;
}
async getMembers(teamId: string) {
const rows = await this.db
.select({
userId: teamMembers.userId,
role: teamMembers.role,
roleDescription: teamMembers.roleDescription,
interests: teamMembers.interests,
joinedAt: teamMembers.joinedAt,
displayName: users.displayName,
email: users.email,
avatarUrl: users.avatarUrl,
})
.from(teamMembers)
.innerJoin(users, eq(teamMembers.userId, users.id))
.where(eq(teamMembers.teamId, teamId));
return rows;
}
}

View File

@@ -0,0 +1,59 @@
import { eq } from 'drizzle-orm';
import { users } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export interface ClerkUserData {
clerkId: string;
displayName: string;
email: string;
avatarUrl?: string | null;
}
export class UserService {
constructor(private db: Db) {}
async getByClerkId(clerkId: string) {
const [user] = await this.db.select().from(users).where(eq(users.clerkId, clerkId)).limit(1);
return user ?? null;
}
async getById(id: string) {
const [user] = await this.db.select().from(users).where(eq(users.id, id)).limit(1);
return user ?? null;
}
/**
* Create or update a user from Clerk JWT claims.
* Used by auth plugin for auto-provisioning on first auth,
* and by webhook for ongoing sync.
*/
async upsertFromClerk(data: ClerkUserData) {
const existing = await this.getByClerkId(data.clerkId);
if (existing) {
// Update display name / email / avatar if changed
await this.db.update(users)
.set({
displayName: data.displayName,
email: data.email,
avatarUrl: data.avatarUrl ?? null,
updatedAt: new Date(),
})
.where(eq(users.clerkId, data.clerkId));
// Return fresh copy
return (await this.getByClerkId(data.clerkId))!;
}
// Insert new user
const [created] = await this.db.insert(users)
.values({
clerkId: data.clerkId,
displayName: data.displayName,
email: data.email,
avatarUrl: data.avatarUrl ?? null,
})
.returning();
return created;
}
}