refactor(server): move the team runtime into a postponed package (P1.1)

Team mode stays in the repository but is not built or shipped (ADR-0003).

- The team server (index.ts, config, db, daemons, plugins, proactive,
  routes, scheduler, services, ws, drizzle migrations) and its tests move
  from @waggle/server to packages/team-server (@waggle/team-server,
  private). It keeps its own copies of the logger and the agent-group
  executor, so it does not import @waggle/server. @clerk/fastify, bullmq,
  ioredis, postgres, drizzle-orm, drizzle-kit, cron-parser and
  @waggle/waggle-dance leave @waggle/server; the launcher drops the same
  team-only dependencies.
- build:packages no longer builds waggle-dance or the worker: nothing in
  the community edition imports them, and the worker's project reference
  would otherwise build the team server. The worker now imports from
  team-server; the team Dockerfile builds both explicitly.
- The sidecar no longer starts the team server when DATABASE_URL is set,
  and loses the team routes (/api/team/*, /api/teams), the WaggleDance
  routes and bridge (/api/waggle-dance/*), the Team server binding and
  egress guard, the WebSocket team client, the TeamSync cache and pushes,
  team audit forwarding, team workspace registration and the team
  capability-policy lookup in chat. The in-process room signal bus stays:
  agent groups, fleet runs and external tool runs use it.
  middleware/audit.ts was dead and is deleted.
- @waggle/core loses TeamSync and the teamServer part of WaggleConfig. A
  teamServer key in config.json is ignored and kept on save, as P0.1 does
  for the tier keys. Workspaces lose teamServerUrl and teamUserId; teamId
  and teamRole stay because workspaces from a shared data directory still
  carry them and the viewer write guards read them. POST /api/workspaces
  ignores team fields.
- The sidecar bundle no longer marks the team packages as external.

The agent still references the TeamSync type in orchestrator.ts and
pattern-write-back.ts; those files are being rewritten in P1.5 and drop
it there.

Logs UF-030 and UF-031 (team sync and team policy defects found while
removing the code).
This commit is contained in:
shumeiko.it
2026-10-24 11:53:23 +02:00
parent 0cbde468a9
commit c25efe6c44
136 changed files with 450 additions and 4990 deletions

View File

@@ -1,42 +0,0 @@
export interface ServerConfig {
port: number;
host: string;
databaseUrl: string;
redisUrl: string;
clerkSecretKey: string;
clerkPublishableKey: string;
corsOrigin: string[];
}
export function loadConfig(): ServerConfig {
return {
port: parseInt(process.env.PORT ?? '3100', 10),
host: process.env.HOST ?? '0.0.0.0',
databaseUrl: (() => {
const url = process.env.DATABASE_URL;
if (!url) {
if (process.env.NODE_ENV === 'production') {
throw new Error('DATABASE_URL environment variable is required');
}
return 'postgres://localhost:5434/waggle';
}
return url;
})(),
redisUrl: process.env.REDIS_URL ?? 'redis://localhost:6381',
clerkSecretKey: process.env.CLERK_SECRET_KEY ?? '',
clerkPublishableKey: process.env.CLERK_PUBLISHABLE_KEY ?? '',
corsOrigin: (() => {
const origins = process.env.CORS_ORIGIN;
if (!origins) {
// Fail closed in production: a missing CORS_ORIGIN must not silently
// fall back to a localhost dev origin (which both blocks the real prod
// frontend AND leaves an unintended localhost origin allowed).
if (process.env.NODE_ENV === 'production') {
throw new Error('CORS_ORIGIN environment variable is required in production');
}
return ['http://localhost:5173'];
}
return origins.split(',').map((o) => o.trim()).filter(Boolean);
})(),
};
}

View File

@@ -1,126 +0,0 @@
import { eq, and, desc, gte, sql } from 'drizzle-orm';
import { agentJobs, teamResources, tasks, messages, teamMembers } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class HiveMindAgent {
constructor(private db: Db) {}
async generateWeeklyDigest(teamId: string): Promise<{ digest: WeeklyDigest; messageId: string }> {
const oneWeekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
// Aggregate metrics
const jobsCompleted = await this.db.select().from(agentJobs)
.where(and(
eq(agentJobs.teamId, teamId),
eq(agentJobs.status, 'completed'),
gte(agentJobs.completedAt, oneWeekAgo),
));
const tasksCompleted = await this.db.select().from(tasks)
.where(and(
eq(tasks.teamId, teamId),
eq(tasks.status, 'done'),
));
const resourcesShared = await this.db.select().from(teamResources)
.where(and(
eq(teamResources.teamId, teamId),
gte(teamResources.createdAt, oneWeekAgo),
));
const waggleMessages = await this.db.select().from(messages)
.where(and(
eq(messages.teamId, teamId),
gte(messages.createdAt, oneWeekAgo),
));
// Detect duplicate work (similar task titles by different users)
const duplicates = this.detectDuplicateWork(tasksCompleted);
// Find high-rated resources as best practices
const bestPractices = await this.db.select().from(teamResources)
.where(and(
eq(teamResources.teamId, teamId),
gte(teamResources.rating, sql`3.0`),
))
.orderBy(desc(teamResources.rating))
.limit(5);
const digest: WeeklyDigest = {
period: { from: oneWeekAgo, to: new Date() },
metrics: {
jobsCompleted: jobsCompleted.length,
tasksCompleted: tasksCompleted.length,
resourcesShared: resourcesShared.length,
waggleMessages: waggleMessages.length,
},
duplicateWork: duplicates,
bestPractices: bestPractices.map(r => ({ name: r.name, type: r.resourceType, rating: r.rating })),
recommendations: this.generateRecommendations(jobsCompleted, duplicates, bestPractices),
};
// Get a team member to attribute the broadcast to
const [firstMember] = await this.db.select().from(teamMembers)
.where(eq(teamMembers.teamId, teamId))
.limit(1);
const senderId = firstMember?.userId ?? '';
// Broadcast digest as Waggle Dance message
const [msg] = await this.db.insert(messages).values({
teamId,
senderId,
type: 'broadcast',
subtype: 'discovery',
content: { type: 'weekly_digest', digest },
}).returning();
return { digest, messageId: msg.id };
}
private detectDuplicateWork(tasksList: Array<{ title: string; createdBy: string }>): DuplicateWork[] {
// Group by similar titles (case-insensitive first 20 chars)
const groups = new Map<string, { titles: string[]; users: Set<string> }>();
for (const task of tasksList) {
const key = task.title.toLowerCase().substring(0, 20);
if (!groups.has(key)) groups.set(key, { titles: [], users: new Set() });
groups.get(key)!.titles.push(task.title);
groups.get(key)!.users.add(task.createdBy);
}
return Array.from(groups.values())
.filter(g => g.users.size > 1)
.map(g => ({ titles: g.titles, users: Array.from(g.users) }));
}
private generateRecommendations(jobs: unknown[], duplicates: DuplicateWork[], bestPractices: unknown[]): string[] {
const recommendations: string[] = [];
if (duplicates.length > 0) {
recommendations.push(`${duplicates.length} potential duplicate work detected. Consider checking the hive before starting tasks.`);
}
if (bestPractices.length > 0) {
recommendations.push(`${bestPractices.length} highly-rated resources available. Share them team-wide.`);
}
if (jobs.length > 50) {
recommendations.push('High job volume this week. Consider automating recurring tasks with cron schedules.');
}
return recommendations;
}
}
interface DuplicateWork {
titles: string[];
users: string[];
}
interface WeeklyDigest {
period: { from: Date; to: Date };
metrics: {
jobsCompleted: number;
tasksCompleted: number;
resourcesShared: number;
waggleMessages: number;
};
duplicateWork: DuplicateWork[];
bestPractices: Array<{ name: string; type: string; rating: number }>;
recommendations: string[];
}

View File

@@ -1,127 +0,0 @@
import { eq, and, desc } from 'drizzle-orm';
import { scoutFindings, agents, teamMembers, teamResources } from '../db/schema.js';
import type { Db } from '../db/connection.js';
interface Finding {
source: string;
category: string;
title: string;
summary: string;
relevanceScore: number;
url: string | null;
}
export class ScoutAgent {
constructor(private db: Db) {}
async scan(userId: string, teamId: string): Promise<Array<typeof scoutFindings.$inferSelect>> {
const findings: Finding[] = [];
// Source 1: Check team resources for newly shared items
findings.push(...await this.checkTeamResources(teamId));
// Source 2: Mock marketplace check (would check npm/MCP registry in production)
findings.push(...await this.checkMarketplace(userId));
// Score relevance based on user's agent configs and role
const scored = await this.scoreRelevance(findings, userId, teamId);
// Filter out findings with titles already dismissed by this user
const existingDismissed = await this.db.select().from(scoutFindings)
.where(and(
eq(scoutFindings.userId, userId),
eq(scoutFindings.status, 'dismissed'),
));
const dismissedTitles = new Set(existingDismissed.map(f => f.title));
const filtered = scored.filter(f => !dismissedTitles.has(f.title));
// Store findings
const stored = [];
for (const finding of filtered) {
const [entry] = await this.db.insert(scoutFindings).values({
userId,
teamId,
source: finding.source,
category: finding.category,
title: finding.title,
summary: finding.summary,
relevanceScore: finding.relevanceScore,
url: finding.url,
status: 'new',
}).returning();
stored.push(entry);
}
return stored;
}
private async checkTeamResources(teamId: string): Promise<Finding[]> {
const recent = await this.db.select().from(teamResources)
.where(eq(teamResources.teamId, teamId))
.orderBy(desc(teamResources.createdAt))
.limit(5);
return recent.map(r => ({
source: 'team' as const,
category: r.resourceType === 'skill' ? 'skill' : 'practice',
title: `New team resource: ${r.name}`,
summary: r.description ?? `A ${r.resourceType} shared by a team member`,
relevanceScore: 0.5,
url: null,
}));
}
private async checkMarketplace(_userId: string): Promise<Finding[]> {
// Mock: In production, would check npm registry for MCP packages, skill marketplace, etc.
return [];
}
private async scoreRelevance(findings: Finding[], userId: string, teamId: string): Promise<Finding[]> {
// Load user's agent configs for interest matching
const userAgents = await this.db.select().from(agents)
.where(eq(agents.userId, userId));
// Load member interests
const [membership] = await this.db.select().from(teamMembers)
.where(and(eq(teamMembers.teamId, teamId), eq(teamMembers.userId, userId)));
const interests = (membership?.interests as string[]) ?? [];
const agentTools = userAgents.flatMap(a => (a.tools as string[]) ?? []);
return findings.map(f => {
let score = f.relevanceScore;
// Boost if matches user interests
if (interests.some(i => f.title.toLowerCase().includes(i.toLowerCase()))) score += 0.3;
// Boost if matches agent tool names
if (agentTools.some(t => f.title.toLowerCase().includes(t.toLowerCase()))) score += 0.2;
return { ...f, relevanceScore: Math.min(score, 1.0) };
});
}
async adopt(findingId: string, userId: string) {
const [updated] = await this.db.update(scoutFindings)
.set({ status: 'adopted' })
.where(and(
eq(scoutFindings.id, findingId),
eq(scoutFindings.userId, userId),
))
.returning();
return updated ?? null;
}
async dismiss(findingId: string, userId: string) {
const [updated] = await this.db.update(scoutFindings)
.set({ status: 'dismissed' })
.where(and(
eq(scoutFindings.id, findingId),
eq(scoutFindings.userId, userId),
))
.returning();
return updated ?? null;
}
async listFindings(userId: string) {
return this.db.select().from(scoutFindings)
.where(eq(scoutFindings.userId, userId));
}
}

View File

@@ -1,94 +0,0 @@
import { eq, desc, and, sql } from 'drizzle-orm';
import { agentJobs, agentAuditLog } from '../db/schema.js';
import type { Db } from '../db/connection.js';
import { SUBCONSCIOUS_INTERACTION_THRESHOLD } from '@waggle/shared';
export class SubconsciousAgent {
constructor(private db: Db) {}
async shouldReflect(userId: string): Promise<boolean> {
// Count completed jobs since last reflection
const lastReflection = await this.db.select().from(agentAuditLog)
.where(and(
eq(agentAuditLog.userId, userId),
eq(agentAuditLog.actionType, 'subconscious_reflection'),
))
.orderBy(desc(agentAuditLog.createdAt))
.limit(1);
const since = lastReflection[0]?.createdAt ?? new Date(0);
const sinceIso = since.toISOString();
const recentJobs = await this.db.select().from(agentJobs)
.where(and(
eq(agentJobs.userId, userId),
eq(agentJobs.status, 'completed'),
sql`${agentJobs.completedAt} > ${sinceIso}::timestamptz`,
));
return recentJobs.length >= SUBCONSCIOUS_INTERACTION_THRESHOLD;
}
async reflect(userId: string): Promise<{ auditEntry: typeof agentAuditLog.$inferSelect; insights: Insight[] }> {
// Get recent completed jobs
const recentJobs = await this.db.select().from(agentJobs)
.where(and(
eq(agentJobs.userId, userId),
eq(agentJobs.status, 'completed'),
))
.orderBy(desc(agentJobs.completedAt))
.limit(20);
// Analyze patterns
const insights = this.analyzePatterns(recentJobs);
// Log the reflection
const [auditEntry] = await this.db.insert(agentAuditLog).values({
userId,
agentName: 'subconscious',
actionType: 'subconscious_reflection',
description: `Reflected on ${recentJobs.length} recent jobs. Found ${insights.length} insights.`,
afterState: { insights },
requiresApproval: insights.some(i => i.type === 'prompt_change'),
}).returning();
return { auditEntry, insights };
}
private analyzePatterns(jobs: Array<typeof agentJobs.$inferSelect>): Insight[] {
const insights: Insight[] = [];
// Pattern: repeated job types
const typeCounts = new Map<string, number>();
for (const job of jobs) {
typeCounts.set(job.jobType, (typeCounts.get(job.jobType) ?? 0) + 1);
}
for (const [type, count] of typeCounts) {
if (count >= 5) {
insights.push({
type: 'prompt_change',
description: `Job type "${type}" executed ${count} times recently`,
recommendation: `Consider optimizing the system prompt for ${type} tasks`,
});
}
}
// Pattern: failed jobs
const failedCount = jobs.filter(j => j.status === 'failed').length;
if (failedCount >= 3) {
insights.push({
type: 'tool_issue',
description: `${failedCount} jobs failed recently`,
recommendation: 'Review tool configurations and consider adding error handling',
});
}
return insights;
}
}
interface Insight {
type: string;
description: string;
recommendation: string;
}

View File

@@ -1,16 +0,0 @@
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema.js';
export function createDb(connectionString: string) {
const client = postgres(connectionString);
return drizzle(client, { schema });
}
export type Db = ReturnType<typeof createDb>;
/** The transaction handle drizzle passes to `db.transaction(cb)`. */
export type DbTransaction = Parameters<Parameters<Db['transaction']>[0]>[0];
/** A query executor that is either the root db or an open transaction. */
export type DbExecutor = Db | DbTransaction;

View File

@@ -1,20 +0,0 @@
import { migrate } from 'drizzle-orm/postgres-js/migrator';
import { createDb } from './connection.js';
import { createLogger } from '../local/logger.js';
const log = createLogger('migrate');
const connectionString = process.env.DATABASE_URL;
if (!connectionString) throw new Error('DATABASE_URL environment variable is required');
async function main() {
const db = createDb(connectionString!);
await migrate(db, { migrationsFolder: './drizzle' });
log.info('Migrations complete');
process.exit(0);
}
main().catch((err) => {
log.error('Migration failed:', err);
process.exit(1);
});

View File

@@ -1,234 +0,0 @@
import {
pgTable, uuid, text, timestamp, boolean, real, integer, jsonb, primaryKey,
} from 'drizzle-orm/pg-core';
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
clerkId: text('clerk_id').unique().notNull(),
displayName: text('display_name').notNull(),
email: text('email').unique().notNull(),
avatarUrl: text('avatar_url'),
mindPath: text('mind_path'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teams = pgTable('teams', {
id: uuid('id').primaryKey().defaultRandom(),
name: text('name').notNull(),
slug: text('slug').unique().notNull(),
ownerId: uuid('owner_id').references(() => users.id).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamMembers = pgTable('team_members', {
teamId: uuid('team_id').references(() => teams.id).notNull(),
userId: uuid('user_id').references(() => users.id).notNull(),
role: text('role').notNull().default('member'),
roleDescription: text('role_description'),
interests: jsonb('interests').$type<string[]>(),
joinedAt: timestamp('joined_at', { withTimezone: true }).defaultNow().notNull(),
}, (t) => [primaryKey({ columns: [t.teamId, t.userId] })]);
export const agents = pgTable('agents', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').references(() => users.id).notNull(),
teamId: uuid('team_id').references(() => teams.id),
name: text('name').notNull(),
role: text('role'),
systemPrompt: text('system_prompt'),
model: text('model').notNull().default('claude-haiku-4-5'),
tools: jsonb('tools').$type<string[]>().notNull().default([]),
config: jsonb('config').$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const agentGroups = pgTable('agent_groups', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').references(() => users.id).notNull(),
name: text('name').notNull(),
description: text('description'),
strategy: text('strategy').notNull().default('parallel'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const agentGroupMembers = pgTable('agent_group_members', {
groupId: uuid('group_id').references(() => agentGroups.id).notNull(),
agentId: uuid('agent_id').references(() => agents.id).notNull(),
roleInGroup: text('role_in_group').notNull().default('worker'),
executionOrder: integer('execution_order').notNull().default(0),
}, (t) => [primaryKey({ columns: [t.groupId, t.agentId] })]);
export const tasks = pgTable('tasks', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
title: text('title').notNull(),
description: text('description'),
status: text('status').notNull().default('open'),
priority: text('priority').notNull().default('normal'),
createdBy: uuid('created_by').references(() => users.id).notNull(),
assignedTo: uuid('assigned_to').references(() => users.id),
parentTaskId: uuid('parent_task_id'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});
export const messages = pgTable('messages', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
senderId: uuid('sender_id').references(() => users.id).notNull(),
type: text('type').notNull(),
subtype: text('subtype').notNull(),
content: jsonb('content').$type<Record<string, unknown>>().notNull(),
referenceId: uuid('reference_id'),
routing: jsonb('routing').$type<Array<{ userId: string; reason: string }>>(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamEntities = pgTable('team_entities', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
entityType: text('entity_type').notNull(),
name: text('name').notNull(),
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
validFrom: timestamp('valid_from', { withTimezone: true }).defaultNow().notNull(),
validTo: timestamp('valid_to', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamRelations = pgTable('team_relations', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
sourceId: uuid('source_id').references(() => teamEntities.id).notNull(),
targetId: uuid('target_id').references(() => teamEntities.id).notNull(),
relationType: text('relation_type').notNull(),
confidence: real('confidence').notNull().default(1.0),
properties: jsonb('properties').$type<Record<string, unknown>>().notNull().default({}),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamResources = pgTable('team_resources', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
resourceType: text('resource_type').notNull(),
name: text('name').notNull(),
description: text('description'),
config: jsonb('config').$type<Record<string, unknown>>().notNull(),
sharedBy: uuid('shared_by').references(() => users.id).notNull(),
rating: real('rating').notNull().default(0),
useCount: integer('use_count').notNull().default(0),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamCapabilityPolicies = pgTable('team_capability_policies', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
role: text('role').notNull(),
allowedSources: jsonb('allowed_sources').$type<string[]>().notNull().default([]),
blockedTools: jsonb('blocked_tools').$type<string[]>().notNull().default([]),
approvalThreshold: text('approval_threshold').notNull().default('none'),
updatedBy: uuid('updated_by').references(() => users.id),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamCapabilityOverrides = pgTable('team_capability_overrides', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
capabilityName: text('capability_name').notNull(),
capabilityType: text('capability_type').notNull(),
decision: text('decision').notNull(),
reason: text('reason').notNull().default(''),
decidedBy: uuid('decided_by').references(() => users.id).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
decidedAt: timestamp('decided_at', { withTimezone: true }).defaultNow().notNull(),
});
export const teamCapabilityRequests = pgTable('team_capability_requests', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
requestedBy: uuid('requested_by').references(() => users.id).notNull(),
capabilityName: text('capability_name').notNull(),
capabilityType: text('capability_type').notNull(),
justification: text('justification').notNull(),
status: text('status').notNull().default('pending'),
decidedBy: uuid('decided_by').references(() => users.id),
decisionReason: text('decision_reason'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
decidedAt: timestamp('decided_at', { withTimezone: true }),
});
export const agentJobs = pgTable('agent_jobs', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
userId: uuid('user_id').references(() => users.id).notNull(),
jobType: text('job_type').notNull(),
status: text('status').notNull().default('queued'),
input: jsonb('input').$type<Record<string, unknown>>().notNull(),
output: jsonb('output').$type<Record<string, unknown>>(),
startedAt: timestamp('started_at', { withTimezone: true }),
completedAt: timestamp('completed_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const cronSchedules = pgTable('cron_schedules', {
id: uuid('id').primaryKey().defaultRandom(),
teamId: uuid('team_id').references(() => teams.id).notNull(),
createdBy: uuid('created_by').references(() => users.id).notNull(),
name: text('name').notNull(),
cronExpr: text('cron_expr').notNull(),
jobType: text('job_type').notNull(),
jobConfig: jsonb('job_config').$type<Record<string, unknown>>().notNull().default({}),
enabled: boolean('enabled').notNull().default(true),
lastRunAt: timestamp('last_run_at', { withTimezone: true }),
nextRunAt: timestamp('next_run_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const scoutFindings = pgTable('scout_findings', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').references(() => users.id),
teamId: uuid('team_id').references(() => teams.id),
source: text('source').notNull(),
category: text('category').notNull(),
title: text('title').notNull(),
summary: text('summary'),
relevanceScore: real('relevance_score').notNull().default(0),
url: text('url'),
status: text('status').notNull().default('new'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const proactivePatterns = pgTable('proactive_patterns', {
id: uuid('id').primaryKey().defaultRandom(),
name: text('name').notNull(),
trigger: jsonb('trigger').$type<Record<string, unknown>>().notNull(),
suggestionType: text('suggestion_type').notNull(),
template: text('template').notNull(),
enabled: boolean('enabled').notNull().default(true),
});
export const suggestionsLog = pgTable('suggestions_log', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').references(() => users.id).notNull(),
patternId: uuid('pattern_id').references(() => proactivePatterns.id).notNull(),
context: jsonb('context').$type<Record<string, unknown>>().notNull(),
status: text('status').notNull().default('pending'),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});
export const agentAuditLog = pgTable('agent_audit_log', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').references(() => users.id).notNull(),
teamId: uuid('team_id').references(() => teams.id),
agentName: text('agent_name').notNull(),
actionType: text('action_type').notNull(),
description: text('description').notNull(),
beforeState: jsonb('before_state').$type<Record<string, unknown>>(),
afterState: jsonb('after_state').$type<Record<string, unknown>>(),
requiresApproval: boolean('requires_approval').notNull().default(false),
approved: boolean('approved'),
approvedBy: uuid('approved_by').references(() => users.id),
createdAt: timestamp('created_at', { withTimezone: true }).defaultNow().notNull(),
});

View File

@@ -1,98 +0,0 @@
import Fastify from 'fastify';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import cors from '@fastify/cors';
import websocket from '@fastify/websocket';
import { loadConfig, type ServerConfig } from './config.js';
import { createDb, type Db } from './db/connection.js';
import redisPlugin from './plugins/redis.js';
import authPlugin from './plugins/auth.js';
import { webhookRoutes } from './routes/webhooks.js';
import { teamRoutes } from './routes/teams.js';
import { agentRoutes } from './routes/agents.js';
import { taskRoutes } from './routes/tasks.js';
import { messageRoutes } from './routes/messages.js';
import { knowledgeRoutes } from './routes/knowledge.js';
import { resourceRoutes } from './routes/resources.js';
import { jobRoutes } from './routes/jobs.js';
import { cronRoutes } from './routes/cron.js';
import { suggestionRoutes } from './routes/suggestions.js';
import { scoutRoutes } from './routes/scout.js';
import { auditRoutes } from './routes/audit.js';
import { capabilityGovernanceRoutes } from './routes/capability-governance.js';
import { analyticsRoutes } from './routes/analytics.js';
import { wsGateway } from './ws/gateway.js';
import { JobService } from './services/job-service.js';
import { CronRunner } from './scheduler/cron-runner.js';
import { createLogger } from './local/logger.js';
const log = createLogger('server');
declare module 'fastify' {
interface FastifyInstance {
config: ServerConfig;
db: Db;
jobService: JobService;
}
}
export async function buildServer(configOverrides?: Partial<ServerConfig>) {
const config = { ...loadConfig(), ...configOverrides };
const server = Fastify({ logger: true });
server.decorate('config', config);
const db = createDb(config.databaseUrl);
server.decorate('db', db);
await server.register(cors, { origin: config.corsOrigin });
await server.register(websocket);
await server.register(redisPlugin);
await server.register(authPlugin);
await server.register(webhookRoutes);
await server.register(teamRoutes);
await server.register(agentRoutes);
await server.register(taskRoutes);
await server.register(messageRoutes);
await server.register(knowledgeRoutes);
// Job service (must be decorated before job routes)
const jobService = new JobService(db, config.redisUrl);
server.decorate('jobService', jobService);
const cronRunner = new CronRunner(db, jobService, error => {
server.log.error({ err: error }, 'Cron scheduler tick failed');
});
server.addHook('onReady', async () => {
cronRunner.start();
});
server.addHook('onClose', async () => {
await cronRunner.stop();
await jobService.close();
});
await server.register(resourceRoutes);
await server.register(jobRoutes);
await server.register(cronRoutes);
await server.register(suggestionRoutes);
await server.register(scoutRoutes);
await server.register(auditRoutes);
await server.register(capabilityGovernanceRoutes);
await server.register(analyticsRoutes);
await server.register(wsGateway);
// Health check
server.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
return server;
}
// Start server if run directly
export function isDirectModule(entryPath: string | undefined, moduleUrl: string): boolean {
return entryPath !== undefined && pathToFileURL(resolve(entryPath)).href === moduleUrl;
}
if (isDirectModule(process.argv[1], import.meta.url)) {
const server = await buildServer();
await server.listen({ port: server.config.port, host: server.config.host });
log.info(`Waggle server listening on ${server.config.host}:${server.config.port}`);
}

View File

@@ -10,10 +10,8 @@ import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify';
import cors from '@fastify/cors';
import fastifyStatic from '@fastify/static';
import websocket from '@fastify/websocket';
import { MindDB, MultiMind, WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TeamSync, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, harvestSetHash, type WorkspaceConfig } from '@waggle/core';
import { MindDB, MultiMind, WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, MultiMindCache, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, FrameStore, SessionStore, SuppressionStore, InstallAuditStore, CronStore, AwarenessLayer, VaultStore, SkillHashStore, HarvestSourceStore, ClaudeCodeAdapter, reconcileIndexes, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore, harvestSetHash } from '@waggle/core';
import { corsOriginAllowed } from './cors-config.js';
import { getBoundTeamServer } from './team-server-binding.js';
import { fetchTeamServer } from './team-server-egress.js';
import { getStorageProvider } from './storage/index.js';
import { isLoopbackBind, resolveBindHost } from './net-config.js';
import { isLocalRequest } from './origin-guard.js';
@@ -82,7 +80,6 @@ import { embeddingRoutes, buildEmbeddingStatusPayload } from './routes/embedding
import { sessionRoutes } from './routes/sessions.js';
import { knowledgeRoutes } from './routes/knowledge.js';
import { litellmRoutes } from './routes/litellm.js';
import { waggleDanceRoutes } from './routes/waggle-dance.js';
import { ingestRoutes, readFileRegistry } from './routes/ingest.js';
import { mindRoutes } from './routes/mind.js';
import { agentRoutes } from './routes/agent.js';
@@ -92,12 +89,12 @@ import { skillsHygieneRoutes } from './routes/skills-hygiene.js';
import { skillsAuditRoutes } from './routes/skills-audit.js';
import { approvalRoutes } from './routes/approval.js';
import { anthropicProxyRoutes } from './routes/anthropic-proxy.js';
import { teamRoutes } from './routes/team.js';
import { taskRoutes } from './routes/tasks.js';
import { capabilitiesRoutes } from './routes/capabilities.js';
import { toolsRoutes } from './routes/tools.js';
import { externalToolRunRoutes } from './routes/external-tool-runs.js';
import { routeProposalRoutes } from './routes/route-proposals.js';
import { SignalBus } from './signal-bus.js';
import { commandRoutes } from './routes/commands.js';
import { commandRoutes as commandCenterRoutes } from './routes/command.js';
import { homeRoutes } from './routes/home.js';
@@ -129,7 +126,6 @@ import { costRoutes } from './routes/cost.js';
import { backupRoutes } from './routes/backup.js';
import { offlineRoutes } from './routes/offline.js';
import { eventRoutes, closeAuditDb, cleanupAuditEvents, emitAuditEvent } from './routes/events.js';
import { closeTeamsDb } from './routes/team.js';
import { pinRoutes } from './routes/pins.js';
import { documentRoutes } from './routes/documents.js';
import { fileRoutes } from './routes/files.js';
@@ -2003,13 +1999,12 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
await server.register(skillsAuditRoutes);
await server.register(approvalRoutes);
await server.register(anthropicProxyRoutes);
await server.register(teamRoutes);
await server.register(taskRoutes);
await server.register(capabilitiesRoutes);
await server.register(toolsRoutes);
await server.register(externalToolRunRoutes);
await server.register(routeProposalRoutes);
await server.register(waggleDanceRoutes);
server.decorate('signalBus', new SignalBus());
await server.register(commandRoutes);
// UX-Refactor Phase 1: Home Cockpit (S01) + Command Center (S00/S03) surfaces.
// commandCenterRoutes registers the singular /api/command/* aliases (B4) — it
@@ -2092,7 +2087,7 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
});
server.decorate('channelManager', channelManager);
// Auto-start enabled channels once the server is up; skip under test to
// keep unit runs hermetic (mirrors the teams-server VITEST guard below).
// keep unit runs hermetic.
if (!process.env.VITEST && process.env.NODE_ENV !== 'test') {
server.addHook('onReady', async () => {
await channelManager.startEnabled();
@@ -2347,7 +2342,6 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
workspaces: ['GET /api/workspaces', 'POST /api/workspaces', 'GET /api/workspaces/:id', 'PUT /api/workspaces/:id', 'DELETE /api/workspaces/:id', 'GET /api/workspaces/:id/cost', 'GET /api/workspaces/:id/context', 'GET /api/workspaces/:id/files', 'GET /api/workspaces/:id/storage', 'GET /api/workspaces/:id/storage/files', 'GET /api/workspaces/:id/storage/read', 'POST /api/workspaces/:id/storage/write', 'DELETE /api/workspaces/:id/storage/delete'],
memory: ['GET /api/memory/search', 'GET /api/memory/frames', 'POST /api/memory/frames', 'DELETE /api/memory/frames/:id', 'GET /api/memory/stats', 'GET /api/memory/graph'],
sessions: ['GET /api/workspaces/:workspaceId/sessions', 'POST /api/workspaces/:workspaceId/sessions', 'PATCH /api/sessions/:sessionId', 'DELETE /api/sessions/:sessionId', 'GET /api/sessions/:sessionId/summary'],
teams: ['GET /api/teams', 'POST /api/teams', 'GET /api/teams/:id', 'PUT /api/teams/:id', 'DELETE /api/teams/:id', 'POST /api/teams/:id/members', 'PUT /api/teams/:id/members/:userId', 'DELETE /api/teams/:id/members/:userId', 'GET /api/teams/:id/activity'],
events: ['GET /api/events', 'GET /api/events/stats', 'GET /api/events/stream'],
settings: ['GET /api/settings', 'PUT /api/settings', 'PATCH /api/settings', 'POST /api/settings/test-key', 'POST /api/settings/probe-provider'],
vault: ['GET /api/vault', 'POST /api/vault', 'DELETE /api/vault/:name'],
@@ -2529,9 +2523,8 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
await memory.close();
waggleDb.close();
// Close audit DB, teams DB, and telemetry
// Close audit DB and telemetry
closeAuditDb();
closeTeamsDb();
try { telemetry.close(); } catch { /* already closed */ }
// Close marketplace DB
@@ -2566,36 +2559,5 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
return { done, cancel: () => { cancelled = true; } };
})();
// ── Start Teams server if PostgreSQL is configured (TEAMS tier) ──
// Skip in test environment to avoid port conflicts and addHook-after-listen errors
if (process.env.DATABASE_URL && !process.env.VITEST && process.env.NODE_ENV !== 'test') {
// DAY0V-03 / F-02: cloud-mode detected (DATABASE_URL set) — require CLERK_SECRET_KEY.
// The Teams server registers wsGateway, which itself hard-fails in NODE_ENV=production
// when the key is absent (see packages/server/src/ws/gateway.ts DAY0V-01 fix). We surface
// the misconfiguration here too so the operator sees a single clear log line instead of
// a buildServer rejection further down.
if (!process.env.CLERK_SECRET_KEY) {
log.error(
'[teams-server] CLERK_SECRET_KEY missing while DATABASE_URL is set. Cloud/Teams ' +
'deployment requires both. Skipping Teams server startup — set CLERK_SECRET_KEY ' +
'and restart, or unset DATABASE_URL to run desktop-only.',
);
} else {
const teamsPort = parseInt(process.env.TEAMS_SERVER_PORT ?? '3101', 10);
import('../index.js').then(({ buildServer }) => {
buildServer().then(teamsServer => {
teamsServer.listen({ port: teamsPort, host: '127.0.0.1' }, (err) => {
if (err) {
log.info(`[teams-server] Failed to start: ${err.message}`);
} else {
log.info(`[teams-server] Running at http://127.0.0.1:${teamsPort}`);
}
});
server.addHook('onClose', async () => { await teamsServer.close(); });
}).catch(err => log.info(`[teams-server] Build failed: ${(err as Error).message}`));
}).catch(() => { /* Teams server optional — non-blocking */ });
}
}
return server;
}

View File

@@ -1,77 +0,0 @@
/**
* chat-governance.ts — Direct governance permission lookup for the chat route.
*
* Replaces the HTTP loopback call to /api/team/governance/permissions
* with a direct function call that accesses the same data source.
*/
import { WaggleConfig } from '@waggle/core';
import { fetchTeamServer } from '../team-server-egress.js';
/** Cached governance policies — same TTL as team.ts route cache (5 minutes) */
const policyCache = new Map<string, { permissions: unknown; fetchedAt: number }>();
const CACHE_TTL_MS = 5 * 60 * 1000;
export interface GovernancePolicies {
blockedTools?: string[];
allowedSources?: string[];
}
/**
* Fetch governance permissions for the given workspace directly from the team server.
* This replaces the HTTP self-call (`fetch('http://127.0.0.1:${port}/api/team/governance/permissions')`)
* that previously looped back through the Fastify route.
*
* Returns the role-specific policy if found, or undefined if governance is unavailable.
*/
export async function getGovernancePermissions(
dataDir: string,
workspaceId: string,
teamRole: string | undefined,
): Promise<GovernancePolicies | undefined> {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (!teamServer?.url || !teamServer?.token) {
return undefined;
}
// Check cache
const cacheKey = workspaceId ?? 'default';
const cached = policyCache.get(cacheKey);
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
return extractRolePolicy(cached.permissions, teamRole);
}
try {
const teamSlug = (teamServer as unknown as Record<string, unknown>).teamSlug as string ?? 'default';
const url = `${teamServer.url.replace(/\/$/, '')}/api/teams/${teamSlug}/capability-policies`;
const res = await fetchTeamServer(url, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`${res.status}`);
const policies = await res.json();
policyCache.set(cacheKey, { permissions: policies, fetchedAt: Date.now() });
return extractRolePolicy(policies, teamRole);
} catch {
// Return cached if available, otherwise undefined
if (cached) return extractRolePolicy(cached.permissions, teamRole);
return undefined;
}
}
/** Extract blocked tools from the role-specific policy within the permissions array */
function extractRolePolicy(
permissions: unknown,
teamRole: string | undefined,
): GovernancePolicies | undefined {
if (!Array.isArray(permissions)) return undefined;
const rolePolicy = permissions.find(
(p: Record<string, unknown>) => p.role === teamRole,
);
if (rolePolicy?.blockedTools) {
return { blockedTools: rolePolicy.blockedTools as string[] };
}
return undefined;
}

View File

@@ -37,7 +37,7 @@ const NON_RETAINED_TURN_CONTENT = '[Not retained: memory disabled for this turn]
function resolvePersona(id: string) {
return listPersonas().find(p => p.id === id) ?? null;
}
import { TeamSync, WaggleConfig, type CronStore, type SavePendingActionInput } from '@waggle/core';
import { WaggleConfig, type CronStore, type SavePendingActionInput } from '@waggle/core';
import { PERSONAL_SCOPE, workspaceScope } from '@waggle/memory-contract';
// ── Extracted modules ──────────────────────────────────────────────────
@@ -63,7 +63,6 @@ import {
selectChatPromptPackageMode,
type ChatPromptPackageMode,
} from './chat-prompt-packaging.js';
import { getGovernancePermissions } from './chat-governance.js';
import { applyPersonaToolFilter, filterMcpToolsForPersona, selectToolsForTurn } from '../persona-tool-filter.js';
import { decideReviewTurnTool } from '../held-action-executor.js';
import { assertSafeSegment } from './validate.js';
@@ -77,8 +76,6 @@ import { bindModelSpendBudget } from '../model-spend-meter.js';
import { resolveWorkspaceExecutionRoot } from '../workspace-execution-root.js';
import type { WorkspaceTurnScope } from '../workspace-turn-coordinator.js';
import { bindChatCollaborationTools } from '../chat-collaboration.js';
import { getBoundTeamServer } from '../team-server-binding.js';
import { fetchTeamServer } from '../team-server-egress.js';
import { getResolvedChatWorkspaceId } from '../security-middleware.js';
import type { GoalAncestry } from '@waggle/shared';
import { GENERATION_FAILED_PREFIX, RISK_LEVELS, type RiskLevel } from '@waggle/shared';
@@ -2487,30 +2484,7 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
windowedMessages = applyContextWindow(history);
}
// Governance policies for team workspaces — direct call (no HTTP loopback)
let governancePolicies: { blockedTools?: string[]; allowedSources?: string[] } | undefined;
if (wsConfig?.teamId && effectiveWorkspace) {
try {
governancePolicies = await getGovernancePermissions(
server.localConfig.dataDir,
effectiveWorkspace,
wsConfig.teamRole,
);
throwIfTurnAborted();
} catch {
throwIfTurnAborted();
// Governance not available — allow all.
}
}
if (!hasCustomRunner) {
// Remove governance-blocked definitions before serialization, while
// retaining the executor's deny check as defense in depth.
const blockedTools = new Set(governancePolicies?.blockedTools ?? []);
if (blockedTools.size > 0) {
effectiveTools = effectiveTools.filter(tool => !blockedTools.has(tool.name));
spawnAvailableTools = spawnAvailableTools.filter(tool => !blockedTools.has(tool.name));
}
effectiveTools = filterToolsByTurnMutationPolicy(
effectiveTools,
turnMutationPolicy,
@@ -2571,7 +2545,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
allowDerivedPersistence,
securityContext: {
hooks: requestHookRegistry,
blockedTools: governancePolicies?.blockedTools,
allowedToolNames: spawnAllowedToolNames,
},
parentSignal: turnSignal,
@@ -2813,7 +2786,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
reasoning: reasoningForModelAttempt(resolvedModel),
hooks: requestHookRegistry,
capabilityRouter,
governancePolicies,
signal: turnSignal,
turnId, // H-AUDIT-1: propagate trace ID into the loop
@@ -2896,42 +2868,6 @@ ${wsConfig?.templateId ? `- Workspace template: ${wsConfig.templateId} — tailo
const filePath = String(input.path);
sendEvent('file_created', { filePath, fileAction });
}
// TeamSync push — after save_memory in team workspace (fire-and-forget)
if (allowMemoryPersistence && name === 'save_memory' && !result.startsWith('Error')) {
const pushWsConfig = activeExecutionWorkspaceId
? server.workspaceManager?.get(activeExecutionWorkspaceId)
: undefined;
if (pushWsConfig?.teamId) {
try {
const waggleConfig = new WaggleConfig(server.localConfig.dataDir);
const teamServer = getBoundTeamServer(pushWsConfig.teamServerUrl, waggleConfig.getTeamServer());
if (teamServer?.token) {
const sync = new TeamSync({
teamServerUrl: teamServer.url,
teamSlug: pushWsConfig.teamId,
authToken: teamServer.token,
userId: teamServer.userId ?? 'local-user',
displayName: teamServer.displayName ?? 'You',
}, fetchTeamServer);
// Fire-and-forget push — non-blocking
sync.pushFrame({
id: Date.now(),
gop_id: sessionId ?? 'unknown',
t: 0,
frame_type: 'I',
base_frame_id: null,
content: typeof result === 'string' ? result.slice(0, 500) : '',
importance: 'normal',
source: 'agent_inferred',
access_count: 0,
created_at: new Date().toISOString(),
last_accessed: new Date().toISOString(),
}).catch(err => log.warn('[waggle] TeamSync push failed:', err.message));
}
} catch { /* TeamSync not available */ }
}
}
},
};

View File

@@ -15,8 +15,6 @@ import path from 'node:path';
import type { FastifyPluginAsync, FastifyInstance } from 'fastify';
import Database from 'better-sqlite3';
import { validateOrigin } from '../cors-config.js';
import { getBoundTeamServer } from '../team-server-binding.js';
import { fetchTeamServer } from '../team-server-egress.js';
// ── Event types ─────────────────────────────────────────────────────
@@ -145,35 +143,6 @@ export function emitAuditEvent(
timestamp: new Date().toISOString(),
};
server.eventBus?.emit('audit_event', fullEvent);
// TeamSync: Push audit event to team server (fire-and-forget)
try {
const wsConfig = event.workspaceId ? server.workspaceManager?.get(event.workspaceId) : null;
if (wsConfig?.teamId && wsConfig?.teamServerUrl) {
(async () => {
try {
const { WaggleConfig } = await import('@waggle/core');
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = getBoundTeamServer(wsConfig.teamServerUrl, waggleConfig.getTeamServer());
if (teamServer?.token) {
fetchTeamServer(`${teamServer.url}/api/teams/${wsConfig.teamId}/audit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${teamServer.token}`,
},
body: JSON.stringify({
...event,
timestamp: new Date().toISOString(),
source: 'local-agent',
}),
signal: AbortSignal.timeout(3000),
}).catch(() => { /* non-blocking */ });
}
} catch { /* team push is best-effort */ }
})();
}
} catch { /* team push is best-effort */ }
} catch {
// Non-blocking — audit logging must never crash the main flow
}

View File

@@ -152,8 +152,8 @@ export async function fleetRoutes(fastify: FastifyInstance) {
//
// Scoped out vs chat parity (separate followup): credential pool +
// provider fallback chain, trace recorder for evolution substrate,
// file_created events, TeamSync push, governance.allowedSources
// enforcement, custom user-system-prompt + profile injection. Spawn
// file_created events, governance.allowedSources enforcement,
// custom user-system-prompt + profile injection. Spawn
// uses the orchestrator's bare buildSystemPrompt() — enough for
// autonomous tool-use, not as personalized as chat.
const spawnSessionId = `spawn-${Date.now()}`;

View File

@@ -17,6 +17,7 @@
import type { FastifyPluginAsync } from 'fastify';
import fs from 'node:fs';
import path from 'node:path';
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
/** Minimal shape of an OpenAI-compatible chat-completions response. */
interface ChatCompletionResponse {
@@ -220,20 +221,22 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
profile.industry && `Industry: ${profile.industry}`,
].filter(Boolean).join('. ');
if (identity) {
const frames = orch.getFrames();
const sessions = orch.getSessions();
const active = sessions.getActive();
const gopId = active.length > 0 ? active[0].gop_id : sessions.create().gop_id;
// Replace-on-update (the W4.3 profile-card lane): a profile save
// updates THE identity card — every save appending another
// "User identity:" frame filled the memory list with duplicates.
frames.deleteByContentPrefix('User identity: ');
const latestI = frames.getLatestIFrame(gopId);
if (latestI) {
frames.createPFrame(gopId, `User identity: ${identity}`, latestI.id, 'important');
} else {
frames.createIFrame(gopId, `User identity: ${identity}`, 'important');
// "User identity:" memory filled the memory list with duplicates.
const memory = orch.getMemory();
const cards = await memory.list({ scopes: [PERSONAL_SCOPE], kinds: ['profile'], limit: 1000 });
for (const card of cards) {
if (card.text.startsWith('User identity: ')) await memory.forget(card.id);
}
await memory.remember({
scope: PERSONAL_SCOPE,
text: `User identity: ${identity}`,
kind: 'profile',
importance: 'important',
source: 'user_stated',
origin: 'profile',
});
// profile.json is the authoritative identity source: a profile save
// SUPERSEDES the structured IdentityLayer row (org/title), so stale

View File

@@ -448,8 +448,6 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
// does not ship (ADR-0003).
available: false,
enabled: raw.cloudSyncEnabled === true,
teamServerUrl: (raw.teamServer as Record<string, unknown>)?.url ?? null,
connected: !!((raw.teamServer as Record<string, unknown>)?.token),
};
});

View File

@@ -1,848 +0,0 @@
/**
* Team routes for the local server.
*
* These routes handle team server connection from the desktop app:
* - POST /api/team/connect — connect to team server (validate token, store config)
* - POST /api/team/disconnect — disconnect from team server
* - GET /api/team/status — get current team connection status
*/
import path from 'node:path';
import crypto from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import Database from 'better-sqlite3';
import { WaggleConfig } from '@waggle/core';
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
import { emitNotification } from './notifications.js';
import { emitAuditEvent } from './events.js';
// ── Local team DB ────────────────────────────────────────────────────
type TeamRole = 'owner' | 'admin' | 'member' | 'viewer';
interface TeamRow {
id: string;
name: string;
description: string;
owner_id: string;
created: string;
updated: string;
}
interface MemberRow {
team_id: string;
user_id: string;
role: TeamRole;
display_name: string;
email: string | null;
joined: string;
}
let teamsDb: Database.Database | null = null;
function getTeamsDb(dataDir: string): Database.Database {
if (teamsDb) return teamsDb;
const dbPath = path.join(dataDir, 'teams.db');
teamsDb = new Database(dbPath);
teamsDb.pragma('journal_mode = WAL');
teamsDb.pragma('synchronous = NORMAL');
teamsDb.exec(`
CREATE TABLE IF NOT EXISTS teams (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
owner_id TEXT NOT NULL,
created TEXT NOT NULL DEFAULT (datetime('now')),
updated TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS team_members (
team_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'member' CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
display_name TEXT NOT NULL DEFAULT '',
email TEXT,
joined TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (team_id, user_id),
FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_team_members_user ON team_members (user_id);
`);
return teamsDb;
}
export function closeTeamsDb(): void {
if (teamsDb) {
try { teamsDb.close(); } catch { /* ignore */ }
teamsDb = null;
}
}
function getLocalUserId(dataDir: string): string {
try {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (teamServer?.userId && teamServer.userId !== 'unknown') return teamServer.userId;
} catch { /* ignore */ }
return 'local-user';
}
function getLocalDisplayName(dataDir: string): string {
try {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (teamServer?.displayName) return teamServer.displayName;
} catch { /* ignore */ }
return 'You';
}
function hasAllowedTeamServerProtocol(url: URL, allowLocal: boolean): boolean {
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
const isExplicitLoopback = hostname === 'localhost'
|| hostname.endsWith('.localhost')
|| hostname === '::1'
|| /^127(?:\.\d{1,3}){3}$/.test(hostname);
return url.protocol === 'https:' || (url.protocol === 'http:' && allowLocal && isExplicitLoopback);
}
function normalizeTeamServerBaseUrl(value: string, allowLocal: boolean): string | null {
try {
const url = new URL(value);
if (url.username || url.password || url.search || url.hash) return null;
if (!hasAllowedTeamServerProtocol(url, allowLocal)) return null;
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
} catch {
return null;
}
}
function fetchTeamServer(url: string, init: RequestInit = {}): Promise<Response> {
const parsed = new URL(url);
if (parsed.username || parsed.password || parsed.hash
|| !hasAllowedTeamServerProtocol(parsed, allowLocalFromEnv())) {
return Promise.reject(new Error('Blocked insecure Team server URL'));
}
return safeFetch(url, init, {
allowLocal: allowLocalFromEnv(),
maxRedirects: 0,
});
}
export async function teamRoutes(fastify: FastifyInstance) {
const dataDir = fastify.localConfig.dataDir;
/**
* POST /api/team/connect
* Connect to a team server by validating the token against the server's health endpoint.
*/
fastify.post('/api/team/connect', async (request, reply) => {
const { serverUrl, token } = request.body as { serverUrl: string; token: string };
if (!serverUrl || !token) {
return reply.code(400).send({ error: 'serverUrl and token are required' });
}
const normalizedServerUrl = normalizeTeamServerBaseUrl(serverUrl, allowLocalFromEnv());
if (!normalizedServerUrl) {
return reply.code(400).send({
error: 'Team server URL must use HTTPS; HTTP is allowed only for explicitly enabled loopback servers',
});
}
// Validate by calling the team server health endpoint
try {
const healthUrl = `${normalizedServerUrl}/health`;
const healthRes = await fetchTeamServer(healthUrl, {
headers: { 'Authorization': `Bearer ${token}` },
signal: AbortSignal.timeout(5000),
});
if (!healthRes.ok) {
return reply.code(502).send({ error: `Team server returned ${healthRes.status}` });
}
} catch (err: unknown) {
const name = err instanceof Error ? err.name : '';
if (name === 'TimeoutError' || name === 'AbortError') {
return reply.code(504).send({ error: 'Team server connection timed out' });
}
const message = err instanceof Error ? err.message : String(err);
return reply.code(502).send({ error: `Cannot reach team server: ${message}` });
}
// Try to get user info from the team server
let userId = 'unknown';
let displayName = 'Unknown User';
try {
const teamsRes = await fetchTeamServer(`${normalizedServerUrl}/api/teams`, {
headers: { 'Authorization': `Bearer ${token}` },
signal: AbortSignal.timeout(5000),
});
if (teamsRes.ok) {
// Token is valid and user has access — extract from response is not possible without user endpoint
// For now, we know the connection works
userId = 'authenticated';
displayName = 'Team User';
}
} catch {
// Non-critical — connection itself was validated by health check
}
// Store team server config
const waggleConfig = new WaggleConfig(dataDir);
waggleConfig.setTeamServer({
url: normalizedServerUrl,
token,
userId,
displayName,
});
waggleConfig.save();
const connection = {
serverUrl: normalizedServerUrl,
token: '***', // Don't send token back
userId,
displayName,
};
return reply.code(200).send(connection);
});
/**
* POST /api/team/disconnect
* Disconnect from the team server.
*/
fastify.post('/api/team/disconnect', async (_request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
waggleConfig.clearTeamServer();
waggleConfig.save();
return reply.code(200).send({ disconnected: true });
});
/**
* GET /api/team/teams
* List teams the connected user belongs to (proxied from team server).
*/
fastify.get('/api/team/teams', async (_request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (!teamServer || !teamServer.token) {
return reply.code(401).send({ error: 'Not connected to a team server' });
}
try {
const teamsUrl = `${teamServer.url}/api/teams`;
const res = await fetchTeamServer(teamsUrl, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) {
return reply.code(res.status).send({ error: `Team server returned ${res.status}` });
}
const teams = await res.json();
return reply.code(200).send(teams);
} catch (err: unknown) {
const name = err instanceof Error ? err.name : '';
if (name === 'TimeoutError' || name === 'AbortError') {
return reply.code(504).send({ error: 'Team server request timed out' });
}
const message = err instanceof Error ? err.message : String(err);
return reply.code(502).send({ error: `Cannot reach team server: ${message}` });
}
});
/**
* GET /api/team/presence?workspaceId=X
* Get team presence data for a workspace (proxied from team server, or mock if unavailable).
*/
fastify.get<{
Querystring: { workspaceId?: string };
}>('/api/team/presence', async (request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (!teamServer || !teamServer.token) {
return reply.code(200).send({ members: [] });
}
// Try to fetch real presence from team server
try {
const presenceUrl = `${teamServer.url}/api/presence`;
const res = await fetchTeamServer(presenceUrl, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(3000),
});
if (res.ok) {
const data = await res.json();
// Emit presence update for WebSocket subscribers
fastify.eventBus.emit('presence_update', data);
return reply.code(200).send(data);
}
} catch {
// Team server unavailable — return self as online (local-only fallback)
}
// Fallback: return current user as online
const fallbackData = {
members: [{
userId: teamServer.userId ?? 'self',
displayName: teamServer.displayName ?? 'You',
status: 'online',
lastActivity: new Date().toISOString(),
}],
};
// Emit presence update for WebSocket subscribers
fastify.eventBus.emit('presence_update', fallbackData);
return reply.code(200).send(fallbackData);
});
/**
* GET /api/team/status
* Get current team connection status.
*/
fastify.get('/api/team/status', async (_request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (!teamServer) {
return reply.code(200).send({ connected: false });
}
return reply.code(200).send({
connected: true,
serverUrl: teamServer.url,
userId: teamServer.userId ?? 'unknown',
displayName: teamServer.displayName ?? 'Team User',
});
});
/**
* GET /api/team/members
* List team members. Proxies to team server or returns local user when disconnected.
*/
fastify.get('/api/team/members', async () => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (teamServer) {
try {
const res = await fetchTeamServer(`${teamServer.url}/api/team/members`, {
headers: { Authorization: `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(3000),
});
if (res.ok) return res.json();
} catch { /* fall through */ }
}
return { members: [{ id: 'local', name: 'You', status: 'online' }] };
});
/**
* GET /api/team/activity?workspaceId=X&limit=N
* Get recent team activity for a workspace.
* Proxies to team server or returns empty when disconnected.
*/
fastify.get<{
Querystring: { workspaceId?: string; limit?: string };
}>('/api/team/activity', async (request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
const limit = Math.min(parseInt(request.query.limit ?? '20', 10) || 20, 50);
if (!teamServer || !teamServer.token) {
return reply.code(200).send({ items: [] });
}
// Try to fetch activity from team server's entities API
// (synced frames = memory additions, which are our primary activity source)
try {
const workspaceId = request.query.workspaceId;
const entitiesUrl = `${teamServer.url}/api/entities?type=memory_frame&limit=${limit}`;
const res = await fetchTeamServer(entitiesUrl, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(5000),
});
if (res.ok) {
const data = await res.json() as { entities?: Array<{
id: string;
metadata?: { authorName?: string; authorId?: string; frameType?: string; content?: string };
createdAt?: string;
}> };
const items = (data.entities ?? []).map((e) => ({
id: e.id,
type: 'memory' as const,
authorName: e.metadata?.authorName ?? 'Unknown',
authorId: e.metadata?.authorId,
summary: e.metadata?.content
? (e.metadata.content.length > 120 ? e.metadata.content.slice(0, 120) + '...' : e.metadata.content)
: `Added ${e.metadata?.frameType ?? 'frame'}`,
timestamp: e.createdAt ?? new Date().toISOString(),
}));
return reply.code(200).send({ items });
}
} catch {
// Team server unavailable — return empty
}
return reply.code(200).send({ items: [] });
});
/**
* GET /api/team/messages?workspaceId=X&limit=N
* Get recent Waggle Dance messages for a workspace.
* Proxies to team server or returns empty when disconnected.
*/
fastify.get<{
Querystring: { workspaceId?: string; limit?: string };
}>('/api/team/messages', async (request, reply) => {
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
const limit = Math.min(parseInt(request.query.limit ?? '20', 10) || 20, 50);
if (!teamServer || !teamServer.token) {
return reply.code(200).send({ messages: [] });
}
try {
const teamSlug = (teamServer as { teamSlug?: string }).teamSlug ?? 'default';
const messagesUrl = `${teamServer.url}/api/teams/${teamSlug}/messages?limit=${limit}`;
const res = await fetchTeamServer(messagesUrl, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(5000),
});
if (res.ok) {
const data = await res.json() as { messages?: unknown[] } | unknown[];
const messages = (Array.isArray(data) ? data : data?.messages) ?? [];
if (Array.isArray(messages) && messages.length > 0) {
emitNotification(fastify, {
title: 'Team message',
body: 'New message from team',
category: 'message',
});
}
return reply.code(200).send({ messages });
}
} catch {
// Team server unavailable — return empty
}
return reply.code(200).send({ messages: [] });
});
// --- Capability Governance Proxy ---
// In-memory policy cache: teamId → { permissions, fetchedAt }
const policyCache = new Map<string, { permissions: unknown; fetchedAt: number }>();
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
// Listen for policy update events to invalidate cache
if (fastify.eventBus) {
fastify.eventBus.on('capability_policy_update', (data: { teamId?: string } | undefined) => {
if (data?.teamId) policyCache.delete(data.teamId);
else policyCache.clear(); // Clear all if no specific teamId
});
}
// GET /api/team/governance/permissions — get effective permissions for current user
fastify.get('/api/team/governance/permissions', async (request, reply) => {
const { workspaceId } = request.query as { workspaceId?: string };
const waggleConfig = new WaggleConfig(dataDir);
const teamServer = waggleConfig.getTeamServer();
if (!teamServer?.url || !teamServer?.token) {
return { connected: false, permissions: null };
}
// Check cache
const cacheKey = workspaceId ?? 'default';
const cached = policyCache.get(cacheKey);
if (cached && Date.now() - cached.fetchedAt < CACHE_TTL_MS) {
return { connected: true, permissions: cached.permissions };
}
try {
const teamSlug = (teamServer as { teamSlug?: string }).teamSlug ?? 'default';
const url = `${teamServer.url.replace(/\/$/, '')}/api/teams/${teamSlug}/capability-policies`;
const res = await fetchTeamServer(url, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`${res.status}`);
const policies = await res.json();
policyCache.set(cacheKey, { permissions: policies, fetchedAt: Date.now() });
return { connected: true, permissions: policies };
} catch {
// Return cached if available, otherwise null
if (cached) return { connected: true, permissions: cached.permissions, stale: true };
return { connected: true, permissions: null };
}
});
// ═══════════════════════════════════════════════════════════════════
// F3: Local team entity CRUD — works in solo mode with local userId
// ═══════════════════════════════════════════════════════════════════
const db = getTeamsDb(dataDir);
const userId = getLocalUserId(dataDir);
// POST /api/teams — create a team
fastify.post<{
Body: { name: string; description?: string };
}>('/api/teams', async (request, reply) => {
const { name, description } = request.body ?? {};
if (!name || typeof name !== 'string' || name.trim().length === 0) {
return reply.code(400).send({ error: 'name is required' });
}
const id = `team-${crypto.randomUUID().slice(0, 8)}`;
const uid = getLocalUserId(dataDir);
const displayName = getLocalDisplayName(dataDir);
const now = new Date().toISOString();
db.prepare(`
INSERT INTO teams (id, name, description, owner_id, created, updated)
VALUES (?, ?, ?, ?, ?, ?)
`).run(id, name.trim(), description?.trim() ?? '', uid, now, now);
// Auto-add creator as owner member
db.prepare(`
INSERT INTO team_members (team_id, user_id, role, display_name, joined)
VALUES (?, ?, 'owner', ?, ?)
`).run(id, uid, displayName, now);
emitAuditEvent(fastify, { workspaceId: 'global', eventType: 'workspace_create', input: JSON.stringify({ teamId: id, name }) });
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(id) as TeamRow;
const members = db.prepare('SELECT * FROM team_members WHERE team_id = ?').all(id) as MemberRow[];
return reply.code(201).send({ ...normalizeTeam(team), members: members.map(normalizeMember) });
});
// GET /api/teams — list teams for current user
fastify.get('/api/teams', async () => {
const uid = getLocalUserId(dataDir);
const rows = db.prepare(`
SELECT t.* FROM teams t
JOIN team_members m ON t.id = m.team_id
WHERE m.user_id = ?
ORDER BY t.created DESC
`).all(uid) as TeamRow[];
return { teams: rows.map(normalizeTeam) };
});
// GET /api/teams/:id — team detail with members
fastify.get<{ Params: { id: string } }>('/api/teams/:id', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const members = db.prepare('SELECT * FROM team_members WHERE team_id = ?').all(team.id) as MemberRow[];
// Team workspaces
const allWorkspaces = fastify.workspaceManager.list();
const teamWorkspaces = allWorkspaces.filter((ws) => ws.teamId === team.id || ws.team === team.id);
return {
...normalizeTeam(team),
members: members.map(normalizeMember),
workspaces: teamWorkspaces,
};
});
// PUT /api/teams/:id — update team
fastify.put<{
Params: { id: string };
Body: { name?: string; description?: string };
}>('/api/teams/:id', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const uid = getLocalUserId(dataDir);
const member = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
if (!member || (member.role !== 'owner' && member.role !== 'admin')) {
return reply.code(403).send({ error: 'Only owner or admin can update team' });
}
const { name, description } = request.body ?? {};
const updates: string[] = [];
const params: unknown[] = [];
if (name !== undefined) { updates.push('name = ?'); params.push(name.trim()); }
if (description !== undefined) { updates.push('description = ?'); params.push(description.trim()); }
if (updates.length > 0) {
updates.push("updated = datetime('now')");
params.push(team.id);
db.prepare(`UPDATE teams SET ${updates.join(', ')} WHERE id = ?`).run(...params);
}
return db.prepare('SELECT * FROM teams WHERE id = ?').get(team.id);
});
// DELETE /api/teams/:id — delete team (owner only)
fastify.delete<{ Params: { id: string } }>('/api/teams/:id', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const uid = getLocalUserId(dataDir);
if (team.owner_id !== uid) {
return reply.code(403).send({ error: 'Only the team owner can delete the team' });
}
// Remove all members first (CASCADE should handle this but be explicit)
db.prepare('DELETE FROM team_members WHERE team_id = ?').run(team.id);
db.prepare('DELETE FROM teams WHERE id = ?').run(team.id);
// Unlink workspaces from this team
const allWorkspaces = fastify.workspaceManager.list();
for (const ws of allWorkspaces) {
if (ws.teamId === team.id || ws.team === team.id) {
fastify.workspaceManager.update(ws.id, { teamId: undefined, team: null });
}
}
emitAuditEvent(fastify, { workspaceId: 'global', eventType: 'workspace_delete', input: JSON.stringify({ teamId: team.id }) });
return reply.code(204).send();
});
// ── Member management ────────────────────────────────────────────
// POST /api/teams/:id/members — invite/add member
fastify.post<{
Params: { id: string };
Body: { userId?: string; email?: string; displayName?: string; role?: TeamRole };
}>('/api/teams/:id/members', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
// Check permission: owner or admin can add members
const uid = getLocalUserId(dataDir);
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
if (!self || (self.role !== 'owner' && self.role !== 'admin')) {
return reply.code(403).send({ error: 'Only owner or admin can add members' });
}
const { userId: newUserId, email, displayName, role } = request.body ?? {};
const memberUserId = newUserId ?? email ?? `user-${crypto.randomUUID().slice(0, 8)}`;
const memberRole: TeamRole = role && ['owner', 'admin', 'member', 'viewer'].includes(role) ? role : 'member';
// Check if already a member
const existing = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, memberUserId);
if (existing) {
return reply.code(409).send({ error: 'User is already a team member' });
}
db.prepare(`
INSERT INTO team_members (team_id, user_id, role, display_name, email, joined)
VALUES (?, ?, ?, ?, ?, datetime('now'))
`).run(team.id, memberUserId, memberRole, displayName ?? memberUserId, email ?? null);
const member = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, memberUserId) as MemberRow;
return reply.code(201).send(normalizeMember(member));
});
// PUT /api/teams/:id/members/:userId — change member role
fastify.put<{
Params: { id: string; userId: string };
Body: { role: TeamRole };
}>('/api/teams/:id/members/:userId', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const uid = getLocalUserId(dataDir);
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
if (!self || self.role !== 'owner') {
return reply.code(403).send({ error: 'Only the team owner can change roles' });
}
const { role } = request.body ?? {};
if (!role || !['owner', 'admin', 'member', 'viewer'].includes(role)) {
return reply.code(400).send({ error: 'Invalid role. Must be: owner, admin, member, or viewer' });
}
const target = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow | undefined;
if (!target) return reply.code(404).send({ error: 'Member not found' });
db.prepare('UPDATE team_members SET role = ? WHERE team_id = ? AND user_id = ?').run(role, team.id, request.params.userId);
const updated = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow;
return normalizeMember(updated);
});
// PATCH /api/teams/:id/members/:userId — alias for PUT (common API convention)
fastify.patch<{
Params: { id: string; userId: string };
Body: { role: TeamRole };
}>('/api/teams/:id/members/:userId', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const uid = getLocalUserId(dataDir);
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
if (!self || (self.role !== 'owner' && self.role !== 'admin')) {
return reply.code(403).send({ error: 'Only owner or admin can change roles' });
}
const { role } = request.body ?? {};
if (!role || !['owner', 'admin', 'member', 'viewer'].includes(role)) {
return reply.code(400).send({ error: 'Invalid role. Must be: owner, admin, member, or viewer' });
}
const target = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow | undefined;
if (!target) return reply.code(404).send({ error: 'Member not found' });
db.prepare('UPDATE team_members SET role = ? WHERE team_id = ? AND user_id = ?').run(role, team.id, request.params.userId);
const updated = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, request.params.userId) as MemberRow;
return normalizeMember(updated);
});
// DELETE /api/teams/:id/members/:userId — remove member
fastify.delete<{
Params: { id: string; userId: string };
}>('/api/teams/:id/members/:userId', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const uid = getLocalUserId(dataDir);
const self = db.prepare('SELECT * FROM team_members WHERE team_id = ? AND user_id = ?').get(team.id, uid) as MemberRow | undefined;
// Can remove: owner/admin can remove anyone, members can remove themselves
const targetUserId = request.params.userId;
const isSelf = targetUserId === uid;
if (!isSelf && (!self || (self.role !== 'owner' && self.role !== 'admin'))) {
return reply.code(403).send({ error: 'Insufficient permissions' });
}
// Can't remove the owner
if (team.owner_id === targetUserId) {
return reply.code(400).send({ error: 'Cannot remove the team owner. Transfer ownership first.' });
}
db.prepare('DELETE FROM team_members WHERE team_id = ? AND user_id = ?').run(team.id, targetUserId);
return { deleted: true, userId: targetUserId, teamId: team.id };
});
// GET /api/teams/:id/activity — aggregated events from team workspaces (uses F2 audit trail)
fastify.get<{
Params: { id: string };
Querystring: { limit?: string; from?: string };
}>('/api/teams/:id/activity', async (request, reply) => {
const team = db.prepare('SELECT * FROM teams WHERE id = ?').get(request.params.id) as TeamRow | undefined;
if (!team) return reply.code(404).send({ error: 'Team not found' });
const limit = Math.min(parseInt(request.query.limit ?? '50', 10) || 50, 200);
const from = request.query.from ?? new Date(Date.now() - 7 * 86400000).toISOString();
// Find all workspaces linked to this team
const allWorkspaces = fastify.workspaceManager.list();
const teamWsIds = allWorkspaces
.filter((ws) => ws.teamId === team.id || ws.team === team.id)
.map((ws) => ws.id);
if (teamWsIds.length === 0) {
return { items: [], teamId: team.id };
}
// Query audit events for all team workspaces
try {
const { getAuditDb } = await import('./events.js');
const auditDb = getAuditDb(dataDir);
const placeholders = teamWsIds.map(() => '?').join(',');
const events = auditDb.prepare(`
SELECT * FROM audit_events
WHERE workspace_id IN (${placeholders}) AND timestamp >= ?
ORDER BY id DESC LIMIT ?
`).all(...teamWsIds, from, limit) as Array<Record<string, unknown>>;
const items = events.map(e => ({
id: e.id,
timestamp: e.timestamp,
workspaceId: e.workspace_id,
eventType: e.event_type,
toolName: e.tool_name,
sessionId: e.session_id,
}));
return { items, teamId: team.id };
} catch {
return { items: [], teamId: team.id };
}
});
// GET /api/team/memory/search?q=query — search team memory frames
fastify.get<{ Querystring: { q?: string; limit?: string } }>(
'/api/team/memory/search',
async (request, reply) => {
const config = new WaggleConfig(fastify.localConfig.dataDir);
const teamServer = config.getTeamServer();
if (!teamServer?.url || !teamServer?.token) {
return reply.code(400).send({ error: 'Not connected to team server' });
}
const { q, limit: limitStr } = request.query;
if (!q) return reply.code(400).send({ error: 'q parameter required' });
const limit = Math.min(parseInt(limitStr ?? '20', 10), 50);
try {
const url = `${teamServer.url}/api/entities?type=memory_frame&limit=${limit}`;
const res = await fetchTeamServer(url, {
headers: { 'Authorization': `Bearer ${teamServer.token}` },
});
if (!res.ok) return { results: [], count: 0 };
const entities = await res.json() as Array<{
id: string; name: string;
properties: Record<string, unknown>;
sharedBy?: string; createdAt: string;
}>;
// Client-side keyword filter (team server doesn't have FTS yet)
const terms = q.toLowerCase().split(/\s+/).filter(t => t.length > 1);
const matched = entities.filter(e => {
const content = ((e.properties?.content as string) ?? '').toLowerCase();
return terms.some(t => content.includes(t));
});
const results = matched.slice(0, limit).map(e => ({
id: e.id,
content: (e.properties?.content as string) ?? '',
authorId: (e.properties?.authorId as string) ?? e.sharedBy ?? '',
authorName: (e.properties?.authorName as string) ?? 'Team member',
importance: (e.properties?.importance as string) ?? 'normal',
timestamp: e.createdAt,
source: 'team',
}));
return { results, count: results.length };
} catch {
return { results: [], count: 0 };
}
},
);
}
// ── Helpers ─────────────────────────────────────────────────────────
function normalizeTeam(row: TeamRow) {
return {
id: row.id,
name: row.name,
description: row.description,
ownerId: row.owner_id,
created: row.created,
updated: row.updated,
};
}
function normalizeMember(row: MemberRow) {
return {
userId: row.user_id,
role: row.role,
displayName: row.display_name,
email: row.email,
joined: row.joined,
};
}

View File

@@ -1,382 +0,0 @@
import type { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { evaluateExternalMemoryIngress } from '@waggle/core';
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
import {
validateMessageTypeCombo,
WaggleDanceDispatcher,
type DispatchDeps,
} from '@waggle/waggle-dance';
import type {
CollaborationWorkerRun,
WaggleMessage,
MessageType,
MessageSubtype,
} from '@waggle/shared';
import { SignalBus } from '../signal-bus.js';
import { installWaggleDanceBridge } from '../waggle-dance-bridge.js';
/**
* AI-OS Phase 1B — local-sidecar surface for the WaggleDance v2
* cross-tool activity bus.
*
* Endpoints:
*
* POST /api/waggle-dance/signal
* Body: { type, subtype, content, senderId?, teamId?,
* referenceId?, routing? }
* Returns: { dispatched, message }
*
* Normalizes the incoming payload into a full WaggleMessage
* (auto-fills id, createdAt, sensible defaults), validates the
* type/subtype combo, then dispatches through WaggleDanceDispatcher
* with real v2 deps (emit→bus, response→bus).
*
* GET /api/waggle-dance/signals
* Query: { subtype?, tool?, teamId?, limit?, since? }
* Returns: WaggleMessage[]
*
* Returns the in-memory ring buffer snapshot, newest first,
* filtered by the optional query params.
*
* Design notes:
*
* - The signal bus is created once per server instance and exposed
* via `server.signalBus`. Tests can replace it via decoration.
* - The dispatcher's emitSignal pushes into the bus AND records the
* message (so GET /signals returns it). recordResponse does the
* same — responses are also visible in the activity feed.
* - Personal-tier eligibility: when teamId is absent, defaults to
* `personal::<senderId>` so a user's own bus does not require
* a real Teams subscription. This is the moat.
* - Model recommendation: stubbed to null in this route (real
* wiring lives in Phase 3); dispatcher returns a friendly
* "no recommender configured" string.
*/
// Local request schema — relaxed from the cloud sendMessageSchema
// because hook senders don't have user-UUID identities. We accept
// any non-empty senderId string ('claude-code-hook', 'cursor-hook')
// or auto-default to 'local'.
const signalRequestSchema = z.object({
type: z.enum(['broadcast', 'request', 'response']),
subtype: z.enum([
'knowledge_check', 'task_delegation', 'skill_request', 'model_recommendation',
'knowledge_match', 'task_claim', 'discovery', 'routed_share',
'skill_share', 'model_recipe',
]),
content: z.record(z.unknown()),
senderId: z.string().min(1).max(200).optional(),
teamId: z.string().min(1).max(200).optional(),
referenceId: z.string().min(1).max(200).nullable().optional(),
routing: z
.array(z.object({ userId: z.string(), reason: z.string() }))
.nullable()
.optional(),
});
const signalsQuerySchema = z.object({
subtype: z.string().optional(),
tool: z.string().optional(),
teamId: z.string().optional(),
limit: z.coerce.number().int().positive().max(1000).optional(),
since: z.string().optional(),
});
const QUARANTINED_AGENT_SIGNAL = '[Quarantined agent signal]';
declare module 'fastify' {
interface FastifyInstance {
/** AI-OS Phase 1B signal bus — shared across waggle-dance routes. */
signalBus?: SignalBus;
}
}
const waggleDanceRoutesImpl: FastifyPluginAsync = async (server) => {
// Lazily create the bus on first plugin registration. The decorator
// makes it available to other plugins (Phase 1C SSE adapter, tests).
// Wrapped with fastify-plugin below so the decoration is visible
// on the parent FastifyInstance, not just inside this plugin.
if (!server.signalBus) {
server.decorate('signalBus', new SignalBus());
// Bridge the v2 bus into the legacy /api/waggle/signals stream so
// the existing UI surfaces cross-tool activity with zero frontend
// changes. Phase 1C wiring.
installWaggleDanceBridge(server.signalBus!);
}
const bus = server.signalBus!;
// ── POST /api/waggle-dance/signal ─────────────────────────────────
server.post('/api/waggle-dance/signal', async (request, reply) => {
const parsed = signalRequestSchema.safeParse(request.body);
if (!parsed.success) {
return reply
.code(400)
.send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const body = parsed.data;
const runAuth = authenticateRunRequest(server, request);
if (runAuth === null) {
return reply.code(401).send({ error: 'Unauthorized', code: 'INVALID_RUN_TOKEN' });
}
// Validate type/subtype combo via the protocol module.
if (
!validateMessageTypeCombo(
body.type as MessageType,
body.subtype as MessageSubtype,
)
) {
return reply.code(400).send({
error: `Invalid type-subtype combination: ${body.type}/${body.subtype}`,
});
}
if (runAuth) {
const violation = validateRunEnvelope(runAuth, body);
if (violation) return reply.code(403).send({ error: 'Forbidden', code: 'RUN_SCOPE_VIOLATION', message: violation });
}
const senderId = runAuth ? `run::${runAuth.id}` : (body.senderId ?? 'local');
const teamId = runAuth ? `room::${runAuth.roomId}` : (body.teamId ?? `personal::${senderId}`);
const signalContent = runAuth && isDurableAuthenticatedSignal(
body.type as MessageType,
body.subtype as MessageSubtype,
)
? guardAuthenticatedSignalSummary(body.content)
: body.content;
const message: WaggleMessage = {
id: randomUUID(),
teamId,
senderId,
type: body.type as MessageType,
subtype: body.subtype as MessageSubtype,
content: runAuth ? {
...signalContent,
roomId: runAuth.roomId,
runId: runAuth.id,
workspaceId: runAuth.workspaceId,
} : signalContent,
referenceId: body.referenceId ?? null,
routing: body.routing ?? null,
createdAt: new Date(),
};
// Real v2 deps: emit→bus, response→bus, recommendModel→null stub.
// v1 deps are stubbed locally (the cross-tool bus does not run
// the team-internal task_delegation / knowledge_check paths
// through this route — those go through the team workspace).
const deps: DispatchDeps = {
searchMemory: async () => 'memory search not available on local bus',
resolveCapability: () => [],
spawnWorker: async (task: string, role: string) =>
`local bus does not spawn workers (task=${task}, role=${role})`,
emitSignal: async (msg) => {
bus.record(msg);
},
recordResponse: async (msg) => {
bus.record(msg);
},
recommendModel: async () => null,
};
const dispatcher = new WaggleDanceDispatcher(deps);
const dispatchResult = await dispatcher.dispatch(message);
if (!dispatchResult.handled) {
return reply
.code(400)
.send({ error: dispatchResult.error, message });
}
// Request handlers execute their local behavior but do not persist the
// envelope. Record successful requests once so Room peers can receive and
// answer them; broadcasts and responses are recorded by their callbacks.
if (message.type === 'request') {
bus.record(message);
}
if (runAuth) recordAuthenticatedRunSignal(server, runAuth, message);
return reply.code(201).send({
dispatched: true,
response: dispatchResult.response,
message,
});
});
// ── GET /api/waggle-dance/signals ─────────────────────────────────
server.get('/api/waggle-dance/signals', async (request, reply) => {
const parsed = signalsQuerySchema.safeParse(request.query);
if (!parsed.success) {
return reply
.code(400)
.send({ error: 'Invalid query', details: parsed.error.flatten() });
}
const q = parsed.data;
const runAuth = authenticateRunRequest(server, request);
if (runAuth === null) {
return reply.code(401).send({ error: 'Unauthorized', code: 'INVALID_RUN_TOKEN' });
}
const runTeamId = runAuth ? `room::${runAuth.roomId}` : undefined;
if (runTeamId && q.teamId && q.teamId !== runTeamId) {
return reply.code(403).send({ error: 'Forbidden', code: 'RUN_SCOPE_VIOLATION' });
}
// Validate subtype against the protocol enum if provided.
const allowedSubtypes: MessageSubtype[] = [
'knowledge_check', 'task_delegation', 'skill_request', 'model_recommendation',
'knowledge_match', 'task_claim', 'discovery', 'routed_share',
'skill_share', 'model_recipe',
];
if (q.subtype && !allowedSubtypes.includes(q.subtype as MessageSubtype)) {
return reply.code(400).send({ error: `Unknown subtype: ${q.subtype}` });
}
const signals = bus.query({
subtype: q.subtype as MessageSubtype | undefined,
tool: q.tool,
teamId: runTeamId ?? q.teamId,
limit: q.limit,
since: q.since,
});
return reply.code(200).send({ signals, total: signals.length });
});
};
function recordAuthenticatedRunSignal(
server: FastifyInstance,
run: CollaborationWorkerRun,
message: WaggleMessage,
): void {
if (!isDurableAuthenticatedSignal(message.type, message.subtype)) return;
const summary = signalSummary(message.content);
if (!summary) return;
const durableSummary = summary.slice(0, 4_000);
const safeSummary = evaluateExternalMemoryIngress({ content: durableSummary }).action === 'allow'
? durableSummary
: QUARANTINED_AGENT_SIGNAL;
const current = server.agentRunRegistry.get(run.id);
if (!current || current.kind !== 'worker') return;
const workspaceFrameIds = { ...(current.memoryRefs.workspaceFrameIds ?? {}) };
const rawFrameId = message.content.frameId;
const frameId = typeof rawFrameId === 'string' && rawFrameId.trim()
? rawFrameId.trim()
: typeof rawFrameId === 'number' ? String(rawFrameId) : undefined;
const workspaceStored = frameId !== undefined
&& message.content.memoryWorkspace === run.workspaceId;
if (workspaceStored) {
workspaceFrameIds[run.workspaceId] = [
...new Set([...(workspaceFrameIds[run.workspaceId] ?? []), frameId]),
];
}
server.agentRunRegistry.update(run.id, {
...(['queued', 'starting'].includes(current.status) ? { status: 'running' } : {}),
progress: { phase: message.subtype, message: safeSummary.slice(0, 500) },
result: { summary: safeSummary },
memoryRefs: { workspaceFrameIds },
});
// Index the signal in personal memory; the run's memoryRefs follow when the write lands.
void server.memory.remember({
scope: PERSONAL_SCOPE,
text: `[Agent collaboration signal]\nRoom: ${run.roomId}\nRun: ${run.id}\nWorkspace: ${run.workspaceId}\nTool: ${run.executor.toolId ?? 'agent'}\nSubtype: ${message.subtype}\nSummary: ${safeSummary.slice(0, 1_000)}`,
kind: 'note',
source: 'agent_inferred',
origin: 'agent-signals',
metadata: {
messageId: message.id,
roomId: run.roomId,
runId: run.id,
workspaceId: run.workspaceId,
toolId: run.executor.toolId ?? null,
subtype: message.subtype,
},
}).then(([change]) => {
const latest = server.agentRunRegistry.get(run.id);
if (!change || !latest) return;
const personalFrameIds = [...new Set([...latest.memoryRefs.personalFrameIds, change.record.id])];
server.agentRunRegistry.update(run.id, {
memoryRefs: {
status: workspaceStored ? 'complete' : latest.memoryRefs.status,
personalFrameIds,
},
});
}).catch((err: unknown) => {
server.log.warn({ err, runId: run.id }, 'failed to index authenticated agent signal');
});
}
function isDurableAuthenticatedSignal(type: MessageType, subtype: MessageSubtype): boolean {
return type !== 'request' && subtype !== 'task_claim';
}
function guardAuthenticatedSignalSummary(content: Record<string, unknown>): Record<string, unknown> {
for (const key of ['summary', 'result', 'text', 'topic', 'message']) {
const value = content[key];
if (typeof value !== 'string' || !value.trim()) continue;
const reflectedSummary = value.trim();
const durableSummary = reflectedSummary.slice(0, 4_000);
const durableDecision = evaluateExternalMemoryIngress({ content: durableSummary });
const reflectedDecision = reflectedSummary === durableSummary
? durableDecision
: evaluateExternalMemoryIngress({ content: reflectedSummary });
return durableDecision.action === 'allow' && reflectedDecision.action === 'allow'
? content
: { ...content, [key]: QUARANTINED_AGENT_SIGNAL };
}
return content;
}
function signalSummary(content: Record<string, unknown>): string | undefined {
for (const key of ['summary', 'result', 'text', 'topic', 'message']) {
const value = content[key];
if (typeof value === 'string' && value.trim()) return value.trim();
}
return undefined;
}
function authenticateRunRequest(
server: FastifyInstance,
request: FastifyRequest,
): CollaborationWorkerRun | undefined | null {
const raw = request.headers['x-waggle-run-token'];
if (raw === undefined) return undefined;
if (typeof raw !== 'string') return null;
return server.agentRunRegistry?.authenticateCredential(raw) ?? null;
}
function validateRunEnvelope(
run: CollaborationWorkerRun,
body: {
senderId?: string;
teamId?: string;
content: Record<string, unknown>;
},
): string | undefined {
if (body.senderId && body.senderId !== `run::${run.id}`) return 'senderId is outside the credential scope';
if (body.teamId && body.teamId !== `room::${run.roomId}`) return 'teamId is outside the credential scope';
const reserved: Array<[string, string]> = [
['roomId', run.roomId], ['runId', run.id], ['workspaceId', run.workspaceId],
];
for (const [key, expected] of reserved) {
const value = body.content[key];
if (value !== undefined && value !== expected) return `${key} is outside the credential scope`;
}
return undefined;
}
/**
* Plugin wrapped with fastify-plugin so the `signalBus` decoration
* propagates to the parent FastifyInstance. Without this wrapper,
* Fastify's default encapsulation would scope the decoration to
* this plugin only, and tests / other plugins (Phase 1C SSE adapter)
* could not access the shared bus.
*/
export const waggleDanceRoutes: FastifyPluginAsync = fp(waggleDanceRoutesImpl, {
name: 'waggle-dance-routes',
});

View File

@@ -4,15 +4,13 @@ import path from 'node:path';
import Database from 'better-sqlite3';
import type { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { MindDB, WaggleConfig, createFileStore, reconcileFtsIndex } from '@waggle/core';
import { MindDB, createFileStore, reconcileFtsIndex } from '@waggle/core';
import { assertSafeSegment } from './validate.js';
import { validateBody } from '../../validate-body.js';
import { getBoundTeamServer } from '../team-server-binding.js';
import { fetchTeamServer } from '../team-server-egress.js';
/** POST /api/workspaces body — create a workspace (name + group required). Model
* format + local-path existence get deeper checks in the handler; enum fields
* are constrained here so a bad `tone`/`storageType`/`teamRole` 400s cleanly. */
* are constrained here so a bad `tone`/`storageType` 400s cleanly. */
const createWorkspaceSchema = z.object({
name: z.string().min(1).max(200),
group: z.string().min(1).max(200),
@@ -26,10 +24,6 @@ const createWorkspaceSchema = z.object({
storageType: z.enum(['virtual', 'local', 'team']).optional(),
storagePath: z.string().optional(),
storageConfig: z.record(z.string(), z.unknown()).optional(),
teamId: z.string().optional(),
teamServerUrl: z.string().optional(),
teamRole: z.enum(['owner', 'admin', 'member', 'viewer']).optional(),
teamUserId: z.string().optional(),
});
/**
@@ -322,13 +316,9 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
storageType?: 'virtual' | 'local' | 'team';
storagePath?: string;
storageConfig?: Record<string, unknown>;
teamId?: string;
teamServerUrl?: string;
teamRole?: 'owner' | 'admin' | 'member' | 'viewer';
teamUserId?: string;
};
}>('/api/workspaces', { preHandler: validateBody(createWorkspaceSchema) }, async (request, reply) => {
const { name, group, icon, model, personaId, directory, tone, teamId, teamServerUrl, teamRole, teamUserId, storageType, storagePath, storageConfig } = request.body;
const { name, group, icon, model, personaId, directory, tone, storageType, storagePath, storageConfig } = request.body;
// BUG-R3-03: Validate model ID if provided
if (model && !isValidModelId(model)) {
@@ -358,23 +348,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
}
}
let boundTeamServerUrl = teamServerUrl;
let teamServerToken: string | undefined;
const hasTeamId = typeof teamId === 'string' && teamId.trim().length > 0;
const hasTeamServerUrl = typeof teamServerUrl === 'string' && teamServerUrl.trim().length > 0;
if ((teamId !== undefined || teamServerUrl !== undefined) && (!hasTeamId || !hasTeamServerUrl)) {
return reply.status(400).send({ error: 'Team workspaces require both teamId and teamServerUrl' });
}
if (teamId && teamServerUrl) {
const configuredTeamServer = new WaggleConfig(server.localConfig.dataDir).getTeamServer();
const boundTeamServer = getBoundTeamServer(teamServerUrl, configuredTeamServer);
if (!boundTeamServer) {
return reply.status(400).send({ error: 'Team workspace URL must match the configured Team server' });
}
boundTeamServerUrl = boundTeamServer.url;
teamServerToken = boundTeamServer.token;
}
let preparedLocalProvider: { ensureStructure?: () => void } | undefined;
const createdLocalDirectories: string[] = [];
const rollbackPreparedLocalDirectories = () => {
@@ -432,7 +405,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
try {
const created = server.workspaceManager.create({
name, group, icon, model, personaId, directory, tone,
teamId, teamServerUrl: boundTeamServerUrl, teamRole, teamUserId,
...(resolvedTemplateId && { templateId: resolvedTemplateId }),
});
createdWorkspaceId = created.id;
@@ -541,33 +513,6 @@ export const workspaceRoutes: FastifyPluginAsync = async (server) => {
}).catch(() => { /* pack install is best-effort */ });
}
// Register workspace on team server (fire-and-forget)
if (teamId && boundTeamServerUrl && teamServerToken) {
try {
fetchTeamServer(`${boundTeamServerUrl}/api/teams/${teamId}/entities`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${teamServerToken}`,
},
body: JSON.stringify({
entityType: 'workspace',
name: ws.id,
properties: {
displayName: ws.name,
group: ws.group,
model: ws.model,
personaId: ws.personaId,
createdBy: teamUserId ?? 'local-user',
},
}),
signal: AbortSignal.timeout(5000),
}).catch(err => {
log.warn(`[waggle] Team workspace registration failed:`, err.message);
});
} catch { /* team registration is best-effort */ }
}
return reply.status(201).send(ws);
});

View File

@@ -40,6 +40,13 @@ export interface SignalFilter {
export type SignalSubscriber = (signal: WaggleMessage) => void;
declare module 'fastify' {
interface FastifyInstance {
/** Room signal bus shared by the local collaboration routes; decorated by buildLocalServer. */
signalBus?: SignalBus;
}
}
export class SignalBus {
private buffer: WaggleMessage[] = [];
private subscribers: Set<SignalSubscriber> = new Set();

View File

@@ -1,14 +0,0 @@
import type { TeamServerConfig } from '@waggle/core';
import { normalizeTeamServerBaseUrl } from './team-server-egress.js';
/** Bind a stored workspace destination to the currently configured Team credentials. */
export function getBoundTeamServer(
workspaceUrl: string | undefined,
configured: TeamServerConfig | null,
): TeamServerConfig | null {
if (!workspaceUrl || !configured?.url) return null;
const workspaceBaseUrl = normalizeTeamServerBaseUrl(workspaceUrl);
const configuredBaseUrl = normalizeTeamServerBaseUrl(configured.url);
if (!workspaceBaseUrl || !configuredBaseUrl || workspaceBaseUrl !== configuredBaseUrl) return null;
return { ...configured, url: configuredBaseUrl };
}

View File

@@ -1,34 +0,0 @@
import { allowLocalFromEnv, safeFetch } from '@waggle/agent';
function hasAllowedProtocol(url: URL, allowLocal: boolean): boolean {
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
const isExplicitLoopback = hostname === 'localhost'
|| hostname.endsWith('.localhost')
|| hostname === '::1'
|| /^127(?:\.\d{1,3}){3}$/.test(hostname);
return url.protocol === 'https:' || (url.protocol === 'http:' && allowLocal && isExplicitLoopback);
}
export function normalizeTeamServerBaseUrl(
value: string,
allowLocal = allowLocalFromEnv(),
): string | null {
try {
const url = new URL(value);
if (url.username || url.password || url.search || url.hash || !hasAllowedProtocol(url, allowLocal)) {
return null;
}
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`;
} catch {
return null;
}
}
export async function fetchTeamServer(url: string, init: RequestInit = {}): Promise<Response> {
const parsed = new URL(url);
const allowLocal = allowLocalFromEnv();
if (parsed.username || parsed.password || parsed.hash || !hasAllowedProtocol(parsed, allowLocal)) {
throw new Error('Blocked insecure Team server URL');
}
return safeFetch(url, init, { allowLocal, maxRedirects: 0 });
}

View File

@@ -1,143 +0,0 @@
/**
* AI-OS Phase 1C — bridge the new WaggleDance v2 signal bus into the
* legacy `/api/waggle/signals` stream consumed by the WaggleDanceApp UI.
*
* Why a bridge:
*
* The existing UI hook (`useWaggleDance`) talks to `/api/waggle/signals`
* + `/api/waggle/stream` (SSE). Those endpoints have a higher-level
* signal shape (`{type, workspaceId, content, metadata, timestamp,
* acknowledged}`) where `type` is one of five UX categories —
* discovery / handoff / insight / alert / coordination.
*
* The new v2 bus uses the protocol shape (`WaggleMessage` with
* `subtype` of one of ten Waggle Dance protocol subtypes). To let
* the UI surface cross-tool activity with NO frontend changes, we
* subscribe the bus and re-emit each signal through the legacy
* `emitWaggleSignal` with a mapped shape.
*
* The mapping is many-to-five:
*
* discovery / knowledge_check / skill_request → 'discovery'
* task_delegation / skill_share / routed_share → 'handoff'
* knowledge_match → 'insight'
* task_claim / model_recipe / model_recommendation → 'coordination'
* (content.priority === 'critical') → 'alert' (overrides)
*
* Provenance is preserved in `metadata`:
* { subtype, senderId, tool, teamId, referenceId, routing }
*
* Tests cover both the mapping (unit) and the end-to-end flow
* (POST /api/waggle-dance/signal → GET /api/waggle/signals).
*/
import type { WaggleMessage, MessageSubtype } from '@waggle/shared';
import { SignalBus } from './signal-bus.js';
import { emitWaggleSignal } from './routes/waggle-signals.js';
/**
* Categorize a Waggle Dance subtype into one of the five UX
* signal categories the existing UI knows how to render.
*
* Exported for unit testing.
*/
export function categorizeSubtype(
subtype: MessageSubtype,
): 'discovery' | 'handoff' | 'insight' | 'alert' | 'coordination' {
switch (subtype) {
case 'discovery':
case 'knowledge_check':
case 'skill_request':
return 'discovery';
case 'task_delegation':
case 'skill_share':
case 'routed_share':
return 'handoff';
case 'knowledge_match':
return 'insight';
case 'task_claim':
case 'model_recipe':
case 'model_recommendation':
return 'coordination';
default:
// Defense in depth — runtime-malformed subtypes get a safe
// bucket so the UI doesn't drop them silently.
return 'coordination';
}
}
/**
* Build the human-readable `content` field for the legacy signal
* from a v2 WaggleMessage. The UI shows this as the primary text.
*/
export function buildLegacyContent(message: WaggleMessage): string {
const { content, subtype } = message;
// Prefer a topic / title / query field if present, then fall back
// to a structural summary.
const topic =
(content.topic as string) ??
(content.title as string) ??
(content.query as string) ??
(content.task as string) ??
(content.skill as string) ??
null;
if (topic) return `${subtype}: ${topic}`;
// For broadcasts/responses without a topic, summarize the keys.
const keys = Object.keys(content);
if (keys.length === 0) return `${subtype}`;
return `${subtype} (${keys.slice(0, 3).join(', ')})`;
}
/**
* Determine the priority for the legacy signal. `content.priority`
* wins if present and valid; otherwise infer a default from subtype.
*/
function inferPriority(message: WaggleMessage): 'low' | 'normal' | 'high' | 'critical' {
const explicit = message.content.priority;
if (
explicit === 'low' ||
explicit === 'normal' ||
explicit === 'high' ||
explicit === 'critical'
) {
return explicit;
}
// Importance hint from hooks may surface as content.importance
const importance = message.content.importance;
if (importance === 'high') return 'high';
if (importance === 'critical') return 'critical';
return 'normal';
}
/**
* Subscribe to the v2 signal bus and re-emit each signal through
* the legacy `emitWaggleSignal` so the existing UI sees cross-tool
* activity with zero frontend changes.
*
* Returns the unsubscribe function so the bridge can be torn down
* (used in tests).
*/
export function installWaggleDanceBridge(bus: SignalBus): () => void {
return bus.subscribe((msg) => {
const priority = inferPriority(msg);
// Critical priority always renders as 'alert' regardless of subtype.
const type = priority === 'critical' ? 'alert' : categorizeSubtype(msg.subtype);
emitWaggleSignal({
type: `waggle-dance:${type}`,
workspaceId: msg.teamId,
content: buildLegacyContent(msg),
metadata: {
subtype: msg.subtype,
senderId: msg.senderId,
tool: msg.content.tool ?? null,
teamId: msg.teamId,
referenceId: msg.referenceId,
routing: msg.routing,
priority,
// Keep the protocol message verbatim for any UI that wants
// to drill into the raw protocol payload.
protocolMessage: msg,
},
});
});
}

View File

@@ -1,139 +0,0 @@
/**
* WsTeamClient — WebSocket client connecting local server to team server
* for real-time Waggle Dance agent-to-agent communication.
*
* Protocol:
* 1. Connect to ws://{serverUrl}/ws
* 2. Send: { type: 'authenticate', token: '...' }
* 3. Receive: { type: 'authenticated', userId: '...' }
* 4. Send: { type: 'join_team', teamSlug: '...' }
* 5. Receive: { type: 'joined_team', teamSlug: '...' }
* 6. Receive: { type: 'waggle_message', message: WaggleMessage }
*/
import { EventEmitter } from 'node:events';
import type { WebSocket as WsWebSocket, RawData } from 'ws';
import { createLogger } from './logger.js';
const log = createLogger('team-ws');
export interface WsTeamClientConfig {
serverUrl: string;
token: string;
teamSlug: string;
}
/** Inbound events from the team WebSocket server. */
interface TeamServerEvent {
type: string;
teamSlug?: string;
message?: unknown;
}
export class WsTeamClient extends EventEmitter {
private config: WsTeamClientConfig;
private ws: WsWebSocket | null = null;
private reconnectDelay = 1000;
private maxReconnectDelay = 30000;
private shouldReconnect = true;
private _authenticated = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
constructor(config: WsTeamClientConfig) {
super();
this.config = config;
}
async connect(): Promise<void> {
if (this.ws) return; // Already connecting/connected
try {
const { default: WebSocket } = await import('ws');
const url = this.config.serverUrl.replace(/^http/, 'ws') + '/ws';
this.ws = new WebSocket(url);
this.ws.on('open', () => {
this.reconnectDelay = 1000; // Reset backoff on success
// Step 1: Authenticate
this.send({ type: 'authenticate', token: this.config.token });
});
this.ws.on('message', (data: RawData) => {
try {
const event = JSON.parse(data.toString()) as TeamServerEvent;
this.handleEvent(event);
} catch { /* invalid JSON — ignore */ }
});
this.ws.on('close', () => {
this._authenticated = false;
this.ws = null;
this.emit('disconnect');
this.scheduleReconnect();
});
this.ws.on('error', (err: Error) => {
log.warn('WS team client error:', err.message);
// 'close' event will follow — reconnect happens there
});
} catch (err) {
log.warn('WS team client connect failed:', (err as Error).message);
this.ws = null;
this.scheduleReconnect();
}
}
private handleEvent(event: TeamServerEvent): void {
switch (event.type) {
case 'authenticated':
this._authenticated = true;
// Step 2: Join team
this.send({ type: 'join_team', teamSlug: this.config.teamSlug });
break;
case 'joined_team':
this.emit('connected', { teamSlug: event.teamSlug });
break;
case 'waggle_message':
this.emit('message', event.message);
break;
case 'error':
log.warn('WS team server error:', event.message);
break;
}
}
private scheduleReconnect(): void {
if (!this.shouldReconnect) return;
if (this.reconnectTimer) return; // Already scheduled
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.connect().catch(() => { /* handled in connect */ });
}, this.reconnectDelay);
this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
}
disconnect(): void {
this.shouldReconnect = false;
this._authenticated = false;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
try { this.ws.close(); } catch { /* ignore */ }
this.ws = null;
}
}
isConnected(): boolean {
return this._authenticated && this.ws?.readyState === 1; // WebSocket.OPEN
}
send(event: unknown): void {
if (this.ws?.readyState === 1) {
this.ws.send(JSON.stringify(event));
}
}
}

View File

@@ -1,42 +0,0 @@
import type { AuditService } from '../services/audit-service.js';
import type { agentAuditLog } from '../db/schema.js';
export function createAuditWrapper(auditService: AuditService) {
return async function auditAction(params: {
userId: string;
teamId?: string;
agentName: string;
actionType: string;
description: string;
beforeState?: Record<string, unknown>;
requiresApproval?: boolean;
action: () => Promise<Record<string, unknown>>;
}): Promise<{ auditEntry: typeof agentAuditLog.$inferSelect; result?: Record<string, unknown> }> {
if (params.requiresApproval) {
// Don't execute -- just log for approval
const auditEntry = await auditService.log({
userId: params.userId,
teamId: params.teamId,
agentName: params.agentName,
actionType: params.actionType,
description: params.description,
beforeState: params.beforeState,
requiresApproval: true,
});
return { auditEntry };
}
// Execute and log
const result = await params.action();
const auditEntry = await auditService.log({
userId: params.userId,
teamId: params.teamId,
agentName: params.agentName,
actionType: params.actionType,
description: params.description,
beforeState: params.beforeState,
afterState: result,
});
return { auditEntry, result };
};
}

View File

@@ -1,61 +0,0 @@
import fp from 'fastify-plugin';
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { createClerkClient, verifyToken } from '@clerk/fastify';
import { UserService } from '../services/user-service.js';
export type AuthenticateFn = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
declare module 'fastify' {
interface FastifyRequest {
userId: string; // our internal user UUID
clerkId: string;
}
interface FastifyInstance {
authenticate: AuthenticateFn;
_authHandler: { fn: AuthenticateFn };
}
}
export default fp(async function authPlugin(fastify: FastifyInstance) {
const clerkSecretKey = fastify.config.clerkSecretKey;
const clerk = createClerkClient({ secretKey: clerkSecretKey });
const userService = new UserService(fastify.db);
const clerkAuth: AuthenticateFn = async function (request, reply) {
const token = request.headers.authorization?.replace('Bearer ', '');
if (!token) {
return reply.code(401).send({ error: 'Missing authorization token' });
}
try {
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
request.clerkId = payload.sub;
// Look up internal user, auto-provision if not found
let user = await userService.getByClerkId(payload.sub);
if (!user) {
// Auto-create user from Clerk JWT claims (self-healing: works even if webhook was missed)
const clerkUser = await clerk.users.getUser(payload.sub);
user = await userService.upsertFromClerk({
clerkId: payload.sub,
displayName: `${clerkUser.firstName ?? ''} ${clerkUser.lastName ?? ''}`.trim() || payload.sub,
email: clerkUser.emailAddresses?.[0]?.emailAddress ?? '',
avatarUrl: clerkUser.imageUrl ?? null,
});
}
request.userId = user.id;
} catch {
return reply.code(401).send({ error: 'Invalid token' });
}
};
// Use an indirection object so tests can swap the auth handler after routes are registered
const handler = { fn: clerkAuth };
fastify.decorate('_authHandler', handler);
fastify.decorate('authenticate', async function (request: FastifyRequest, reply: FastifyReply) {
return handler.fn(request, reply);
});
});

View File

@@ -1,24 +0,0 @@
import fp from 'fastify-plugin';
import Redis from 'ioredis';
import type { FastifyInstance } from 'fastify';
declare module 'fastify' {
interface FastifyInstance {
redis: Redis;
redisSub: Redis;
}
}
export default fp(async function redisPlugin(fastify: FastifyInstance) {
const redisUrl = fastify.config.redisUrl;
const redis = new Redis(redisUrl);
const redisSub = new Redis(redisUrl);
fastify.decorate('redis', redis);
fastify.decorate('redisSub', redisSub);
fastify.addHook('onClose', async () => {
await redis.quit();
await redisSub.quit();
});
});

View File

@@ -1,39 +0,0 @@
export interface PatternDef {
name: string;
triggerCondition: string;
suggestionType: string;
template: string;
}
export const BUILT_IN_PATTERNS: PatternDef[] = [
{
name: 'recurring_task',
triggerCondition: 'Same task type executed 3+ times',
suggestionType: 'cron',
template: 'This task runs frequently. Would you like to automate it as a scheduled job?',
},
{
name: 'data_report',
triggerCondition: 'Job output contains structured data/metrics',
suggestionType: 'dashboard',
template: 'This produces data regularly. Want to create a dashboard for it?',
},
{
name: 'relevant_to_others',
triggerCondition: 'Job output matches other team member interests',
suggestionType: 'share',
template: 'This result might be relevant to {targetUser}. Share it?',
},
{
name: 'expensive_model',
triggerCondition: 'Job used expensive model for simple task',
suggestionType: 'upgrade',
template: 'This task could use a cheaper model. Try {cheaperModel} next time?',
},
{
name: 'manual_repetition',
triggerCondition: 'User performs same manual steps repeatedly',
suggestionType: 'skill',
template: 'You keep doing this manually. Want to create a reusable skill for it?',
},
];

View File

@@ -1,182 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { AgentGroupMemberNotFoundError, AgentService } from '../services/agent-service.js';
import { TeamService } from '../services/team-service.js';
import { createAgentSchema, createAgentGroupSchema } from '@waggle/shared';
export async function agentRoutes(fastify: FastifyInstance) {
const agentService = new AgentService(fastify.db);
const teamService = new TeamService(fastify.db);
// POST /api/agents — create sub-agent definition
fastify.post('/api/agents', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const parsed = createAgentSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const agent = await agentService.create(request.userId, parsed.data);
return reply.code(201).send(agent);
});
// GET /api/agents — list user's agents
fastify.get('/api/agents', { preHandler: [fastify.authenticate] }, async (request) => {
return agentService.list(request.userId);
});
// PATCH /api/agents/:id — update agent config
fastify.patch('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
// Verify ownership by attempting update scoped to userId
const existing = await agentService.getById(id);
if (!existing) {
return reply.code(404).send({ error: 'Agent not found' });
}
if (existing.userId !== request.userId) {
return reply.code(403).send({ error: 'Not authorized to update this agent' });
}
const body = request.body as Record<string, unknown>;
const updated = await agentService.update(id, request.userId, body);
if (!updated) {
return reply.code(400).send({ error: 'No valid fields to update' });
}
return updated;
});
// DELETE /api/agents/:id — delete agent
fastify.delete('/api/agents/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
const existing = await agentService.getById(id);
if (!existing) {
return reply.code(404).send({ error: 'Agent not found' });
}
if (existing.userId !== request.userId) {
return reply.code(403).send({ error: 'Not authorized to delete this agent' });
}
await agentService.delete(id, request.userId);
return reply.code(204).send();
});
// POST /api/agent-groups — create agent group with members
fastify.post('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const parsed = createAgentGroupSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
try {
const group = await agentService.createGroup(request.userId, parsed.data);
return reply.code(201).send(group);
} catch (error) {
if (error instanceof AgentGroupMemberNotFoundError) {
return reply.code(404).send({ error: 'Agent not found' });
}
throw error;
}
});
// GET /api/agent-groups — list user's groups
fastify.get('/api/agent-groups', { preHandler: [fastify.authenticate] }, async (request) => {
return agentService.listGroups(request.userId);
});
// GET /api/agent-groups/:id — get group with members
fastify.get('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
const group = await agentService.getGroup(id, request.userId);
if (!group) {
return reply.code(404).send({ error: 'Agent group not found' });
}
return group;
});
// PATCH /api/agent-groups/:id — update group name, description, strategy, or members
fastify.patch('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
const body = request.body as {
name?: string;
description?: string;
strategy?: string;
members?: Array<{ agentId: string; roleInGroup?: string; executionOrder?: number }>;
};
try {
const updated = await agentService.updateGroup(id, request.userId, body);
if (!updated) {
return reply.code(404).send({ error: 'Agent group not found' });
}
return updated;
} catch (error) {
if (error instanceof AgentGroupMemberNotFoundError) {
return reply.code(404).send({ error: 'Agent not found' });
}
throw error;
}
});
// DELETE /api/agent-groups/:id — delete group and its members
fastify.delete('/api/agent-groups/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
const deleted = await agentService.deleteGroup(id, request.userId);
if (!deleted) {
return reply.code(404).send({ error: 'Agent group not found' });
}
return reply.code(204).send();
});
// POST /api/agent-groups/:id/run — execute group on a task
fastify.post('/api/agent-groups/:id/run', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { id } = request.params as { id: string };
// Verify group ownership
const group = await agentService.getGroup(id, request.userId);
if (!group) {
return reply.code(404).send({ error: 'Agent group not found' });
}
const body = request.body as { task?: string; teamId?: string } | undefined;
const task = body?.task ?? '';
if (!task.trim()) {
return reply.code(400).send({ error: 'task is required' });
}
if (!body?.teamId) {
return reply.code(400).send({ error: 'teamId is required to queue a group run' });
}
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(body.teamId)) {
return reply.code(400).send({ error: 'teamId must be a valid UUID' });
}
const membership = await teamService.getMembership(body.teamId, request.userId);
if (!membership) {
return reply.code(404).send({ error: 'Team not found' });
}
// Build workflow template from group definition
const { buildWorkflowFromGroup } = await import('../services/agent-group-executor.js');
const workflow = buildWorkflowFromGroup({ ...group, description: group.description ?? undefined }, task);
// Queue the same job type handled by the worker. The former path only
// inserted a database row with an unsupported job type, so runs stayed
// queued forever and no worker ever executed the workflow.
const job = await fastify.jobService.createJob(body.teamId, request.userId, 'group', {
groupId: id,
taskInput: { task },
});
return reply.code(202).send({
jobId: job.id,
workflow: {
name: workflow.name,
steps: workflow.steps.length,
strategy: group.strategy,
aggregation: workflow.aggregation,
},
message: `Group "${group.name}" execution started with ${workflow.steps.length} agents using ${group.strategy} strategy.`,
});
});
}

View File

@@ -1,44 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { AnalyticsService } from '../services/analytics-service.js';
import { TeamService } from '../services/team-service.js';
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
export async function analyticsRoutes(fastify: FastifyInstance) {
const analyticsService = new AnalyticsService(fastify.db);
const teamService = new TeamService(fastify.db);
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
if (userLevel < ROLE_HIERARCHY['admin']) {
reply.code(403).send({ error: 'Admin access required' });
return null;
}
return team;
}
// GET /api/admin/teams/:slug/analytics — team usage analytics dashboard
fastify.get('/api/admin/teams/:slug/analytics', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await requireAdmin(request, reply, slug);
if (!team) return;
const analytics = await analyticsService.getAnalytics(team.id);
return analytics;
});
}

View File

@@ -1,99 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { AuditService } from '../services/audit-service.js';
import { TeamService } from '../services/team-service.js';
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
export async function auditRoutes(fastify: FastifyInstance) {
const auditService = new AuditService(fastify.db);
const teamService = new TeamService(fastify.db);
async function requireAdmin(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
if (userLevel < ROLE_HIERARCHY['admin']) {
reply.code(403).send({ error: 'Admin access required' });
return null;
}
return team;
}
// GET /api/admin/teams/:slug/audit -- list audit entries
fastify.get('/api/admin/teams/:slug/audit', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await requireAdmin(request, reply, slug);
if (!team) return;
const query = request.query as { actionType?: string; agentName?: string };
const entries = await auditService.list(team.id, {
actionType: query.actionType,
agentName: query.agentName,
});
return entries;
});
// GET /api/admin/teams/:slug/audit/pending -- list pending approvals
fastify.get('/api/admin/teams/:slug/audit/pending', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await requireAdmin(request, reply, slug);
if (!team) return;
return auditService.getPendingApprovals(team.id);
});
// POST /api/admin/teams/:slug/audit/:id/approve -- approve pending action
fastify.post('/api/admin/teams/:slug/audit/:id/approve', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await requireAdmin(request, reply, slug);
if (!team) return;
const entry = await auditService.getById(id);
if (!entry) {
return reply.code(404).send({ error: 'Audit entry not found' });
}
if (entry.teamId !== team.id) {
return reply.code(404).send({ error: 'Audit entry not found' });
}
const updated = await auditService.approve(id, request.userId);
return updated;
});
// POST /api/admin/teams/:slug/audit/:id/reject -- reject pending action
fastify.post('/api/admin/teams/:slug/audit/:id/reject', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await requireAdmin(request, reply, slug);
if (!team) return;
const entry = await auditService.getById(id);
if (!entry) {
return reply.code(404).send({ error: 'Audit entry not found' });
}
if (entry.teamId !== team.id) {
return reply.code(404).send({ error: 'Audit entry not found' });
}
const updated = await auditService.reject(id, request.userId);
return updated;
});
}

View File

@@ -1,289 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { TeamService } from '../services/team-service.js';
import { TeamCapabilityGovernance } from '../services/team-capability-governance.js';
import { MessageService } from '../services/message-service.js';
const ROLE_HIERARCHY: Record<string, number> = {
member: 1,
admin: 2,
owner: 3,
};
const VALID_ROLES = ['owner', 'admin', 'member'];
const VALID_SOURCES = ['native', 'skill', 'plugin', 'mcp', 'subagent'];
const VALID_THRESHOLDS = ['low', 'medium', 'high', 'none'];
export async function capabilityGovernanceRoutes(fastify: FastifyInstance) {
const teamService = new TeamService(fastify.db);
const governance = new TeamCapabilityGovernance(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return { team, membership };
}
function requireAdmin(membership: { role: string }, reply: FastifyReply): boolean {
const level = ROLE_HIERARCHY[membership.role] ?? 0;
if (level < ROLE_HIERARCHY.admin) {
reply.code(403).send({ error: 'Admin or owner role required' });
return false;
}
return true;
}
// --- Policies ---
// GET /api/teams/:slug/capability-policies — list all policies
fastify.get('/api/teams/:slug/capability-policies', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
const policies = await governance.listPolicies(ctx.team.id);
return policies;
});
// PUT /api/teams/:slug/capability-policies/:role — update policy
fastify.put('/api/teams/:slug/capability-policies/:role', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, role } = request.params as { slug: string; role: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
if (!requireAdmin(ctx.membership, reply)) return;
if (!VALID_ROLES.includes(role)) {
return reply.code(400).send({ error: `Invalid role. Must be one of: ${VALID_ROLES.join(', ')}` });
}
const body = request.body as {
allowedSources?: string[];
blockedTools?: string[];
approvalThreshold?: string;
};
if (body.allowedSources) {
for (const s of body.allowedSources) {
if (!VALID_SOURCES.includes(s)) {
return reply.code(400).send({ error: `Invalid source: ${s}. Must be one of: ${VALID_SOURCES.join(', ')}` });
}
}
}
if (body.approvalThreshold && !VALID_THRESHOLDS.includes(body.approvalThreshold)) {
return reply.code(400).send({ error: `Invalid threshold. Must be one of: ${VALID_THRESHOLDS.join(', ')}` });
}
const policy = await governance.upsertPolicy(ctx.team.id, role, body, request.userId);
return policy;
});
// --- Overrides ---
// GET /api/teams/:slug/capability-overrides — list all overrides
fastify.get('/api/teams/:slug/capability-overrides', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
const overrides = await governance.listOverrides(ctx.team.id);
return overrides;
});
// POST /api/teams/:slug/capability-overrides — create override
fastify.post('/api/teams/:slug/capability-overrides', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
if (!requireAdmin(ctx.membership, reply)) return;
const body = request.body as {
capabilityName?: string;
capabilityType?: string;
decision?: string;
reason?: string;
};
if (!body.capabilityName || !body.capabilityType || !body.decision) {
return reply.code(400).send({ error: 'capabilityName, capabilityType, and decision are required' });
}
if (body.decision !== 'approved' && body.decision !== 'blocked') {
return reply.code(400).send({ error: 'decision must be approved or blocked' });
}
try {
const override = await governance.createOverride(
ctx.team.id,
{
capabilityName: body.capabilityName,
capabilityType: body.capabilityType,
decision: body.decision as 'approved' | 'blocked',
reason: body.reason,
},
request.userId,
);
return reply.code(201).send(override);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : '';
const code = (err && typeof err === 'object' && 'code' in err) ? (err as { code?: unknown }).code : undefined;
if (message.includes('unique') || message.includes('UNIQUE') || code === '23505') {
return reply.code(409).send({ error: 'Override already exists for this capability' });
}
throw err;
}
});
// DELETE /api/teams/:slug/capability-overrides/:id — delete override
fastify.delete('/api/teams/:slug/capability-overrides/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
if (!requireAdmin(ctx.membership, reply)) return;
const deleted = await governance.deleteOverride(ctx.team.id, id);
if (!deleted) {
return reply.code(404).send({ error: 'Override not found' });
}
return reply.code(204).send();
});
// --- Requests ---
// POST /api/teams/:slug/capability-requests — submit request
fastify.post('/api/teams/:slug/capability-requests', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
const body = request.body as {
capabilityName?: string;
capabilityType?: string;
justification?: string;
};
if (!body.capabilityName || !body.capabilityType || !body.justification) {
return reply.code(400).send({ error: 'capabilityName, capabilityType, and justification are required' });
}
const result = await governance.submitRequest(ctx.team.id, request.userId, {
capabilityName: body.capabilityName,
capabilityType: body.capabilityType,
justification: body.justification,
});
if (result.duplicate) {
return reply.code(409).send({ error: 'A pending request for this capability already exists' });
}
return reply.code(201).send(result.request);
});
// GET /api/teams/:slug/capability-requests — list requests
fastify.get('/api/teams/:slug/capability-requests', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
const query = request.query as { status?: string };
const allRequests = await governance.listRequests(ctx.team.id, query.status);
// Non-admin users only see their own requests
const level = ROLE_HIERARCHY[ctx.membership.role] ?? 0;
if (level < ROLE_HIERARCHY.admin) {
return allRequests.filter((r) => r.requestedBy === request.userId);
}
return allRequests;
});
// PATCH /api/teams/:slug/capability-requests/:id — decide request
fastify.patch('/api/teams/:slug/capability-requests/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const ctx = await resolveTeam(request, reply, slug);
if (!ctx) return;
if (!requireAdmin(ctx.membership, reply)) return;
const body = request.body as { status?: string; reason?: string };
if (!body.status || (body.status !== 'approved' && body.status !== 'rejected')) {
return reply.code(400).send({ error: 'status must be approved or rejected' });
}
const capRequest = await governance.getRequest(ctx.team.id, id);
if (!capRequest) {
return reply.code(404).send({ error: 'Request not found' });
}
if (capRequest.status !== 'pending') {
return reply.code(400).send({ error: 'Request has already been decided' });
}
const decided = await governance.decideRequest(
ctx.team.id,
id,
request.userId,
body.status as 'approved' | 'rejected',
body.reason,
);
// On approve: auto-create override
if (body.status === 'approved') {
try {
await governance.createOverride(
ctx.team.id,
{
capabilityName: capRequest.capabilityName,
capabilityType: capRequest.capabilityType,
decision: 'approved',
reason: body.reason,
},
request.userId,
);
} catch (_err) {
// Override may already exist — ignore conflict
}
}
// Send Waggle Dance notification (non-critical)
try {
const messageService = new MessageService(fastify.db);
await messageService.send(ctx.team.id, request.userId, {
type: 'response',
subtype: 'capability_decision',
content: { capabilityName: capRequest.capabilityName, decision: body.status, reason: body.reason ?? '' },
routing: [{ userId: capRequest.requestedBy, reason: 'capability_request_decision' }],
});
} catch (_err) {
// Non-critical — don't fail the request
}
return decided;
});
}

View File

@@ -1,84 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { CronService } from '../services/cron-service.js';
import { TeamService } from '../services/team-service.js';
import { createCronSchema } from '@waggle/shared';
export async function cronRoutes(fastify: FastifyInstance) {
const cronService = new CronService(fastify.db);
const teamService = new TeamService(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return team;
}
// POST /api/teams/:slug/cron — create a cron schedule
fastify.post('/api/teams/:slug/cron', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = createCronSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
try {
const schedule = await cronService.create(team.id, request.userId, parsed.data);
return reply.code(201).send(schedule);
} catch (err: unknown) {
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
}
});
// GET /api/teams/:slug/cron — list schedules for team
fastify.get('/api/teams/:slug/cron', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const schedules = await cronService.list(team.id);
return schedules;
});
// PATCH /api/teams/:slug/cron/:id — update a cron schedule
fastify.patch('/api/teams/:slug/cron/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const body = request.body as {
name?: string;
cronExpr?: string;
enabled?: boolean;
jobConfig?: Record<string, unknown>;
};
try {
const updated = await cronService.update(team.id, id, body);
if (!updated) {
return reply.code(404).send({ error: 'Schedule not found' });
}
return updated;
} catch (err: unknown) {
return reply.code(400).send({ error: 'Invalid cron expression', message: err instanceof Error ? err.message : String(err) });
}
});
}

View File

@@ -1,101 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { queueJobSchema } from '@waggle/shared';
import { AgentService } from '../services/agent-service.js';
import { TeamService } from '../services/team-service.js';
export async function jobRoutes(fastify: FastifyInstance) {
const agentService = new AgentService(fastify.db);
const teamService = new TeamService(fastify.db);
// GET /api/jobs?teamSlug=... - list jobs for a team
fastify.get('/api/jobs', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { teamSlug, limit } = request.query as { teamSlug?: string; limit?: string };
if (!teamSlug) {
return reply.code(400).send({ error: 'teamSlug query parameter is required' });
}
const team = await teamService.getBySlug(teamSlug);
if (!team) return reply.code(404).send({ error: 'Team not found' });
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) return reply.code(403).send({ error: 'Not a member of this team' });
const jobs = await fastify.jobService.listByTeam(team.id, limit ? parseInt(limit, 10) : 50);
return jobs;
});
// POST /api/jobs - queue a new job
fastify.post('/api/jobs', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const parsed = queueJobSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const teamId = parsed.data.teamId;
if (!teamId) {
return reply.code(400).send({ error: 'teamId is required' });
}
const membership = await teamService.getMembership(teamId, request.userId);
if (!membership) {
return reply.code(404).send({ error: 'Team not found' });
}
if (parsed.data.jobType === 'group') {
const groupId = parsed.data.input.groupId;
if (typeof groupId !== 'string') {
return reply.code(400).send({ error: 'groupId is required for group jobs' });
}
const group = await agentService.getGroup(groupId, request.userId);
if (!group) {
return reply.code(404).send({ error: 'Agent group not found' });
}
}
const job = await fastify.jobService.createJob(
teamId,
request.userId,
parsed.data.jobType,
parsed.data.input,
);
return reply.code(202).send({ jobId: job.id, status: job.status });
});
// POST /api/jobs/:id/cancel - cancel a running or queued job
fastify.post('/api/jobs/:id/cancel', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { id } = request.params as { id: string };
const job = await fastify.jobService.getJob(id);
if (!job) return reply.code(404).send({ error: 'Job not found' });
const membership = await teamService.getMembership(job.teamId, request.userId);
if (!membership) return reply.code(404).send({ error: 'Job not found' });
if (job.status !== 'queued' && job.status !== 'running') {
return reply.code(409).send({ error: `Cannot cancel job with status "${job.status}"` });
}
const updated = await fastify.jobService.cancelJob(id);
return { cancelled: true, jobId: updated?.id ?? id };
});
// GET /api/jobs/:id - get job status
fastify.get('/api/jobs/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { id } = request.params as { id: string };
const job = await fastify.jobService.getJob(id);
if (!job) return reply.code(404).send({ error: 'Job not found' });
const membership = await teamService.getMembership(job.teamId, request.userId);
if (!membership) return reply.code(404).send({ error: 'Job not found' });
return job;
});
}

View File

@@ -1,108 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { KnowledgeService } from '../services/knowledge-service.js';
import { TeamService } from '../services/team-service.js';
import { createEntitySchema, createRelationSchema } from '@waggle/shared';
export async function knowledgeRoutes(fastify: FastifyInstance) {
const knowledgeService = new KnowledgeService(fastify.db);
const teamService = new TeamService(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return team;
}
// POST /api/teams/:slug/entities — share entity to team graph
fastify.post('/api/teams/:slug/entities', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = createEntitySchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const entity = await knowledgeService.createEntity(team.id, request.userId, parsed.data);
return reply.code(201).send(entity);
});
// GET /api/teams/:slug/entities — list/search entities
fastify.get('/api/teams/:slug/entities', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const query = request.query as { type?: string; search?: string };
const filters: { entityType?: string; search?: string } = {};
if (query.type) filters.entityType = query.type;
if (query.search) filters.search = query.search;
const entities = await knowledgeService.listEntities(team.id, filters);
return entities;
});
// POST /api/teams/:slug/relations — create relation
fastify.post('/api/teams/:slug/relations', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = createRelationSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const relation = await knowledgeService.createRelation(team.id, parsed.data);
if (!relation) {
return reply.code(404).send({ error: 'Entity not found' });
}
return reply.code(201).send(relation);
});
// GET /api/teams/:slug/graph — query graph traversal
fastify.get('/api/teams/:slug/graph', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const query = request.query as { startId?: string; depth?: string; relationTypes?: string };
if (!query.startId) {
return reply.code(400).send({ error: 'startId query parameter is required' });
}
const depth = query.depth ? parseInt(query.depth, 10) : 2;
if (isNaN(depth) || depth < 1 || depth > 10) {
return reply.code(400).send({ error: 'depth must be between 1 and 10' });
}
const relationTypes = query.relationTypes
? query.relationTypes.split(',').map((s) => s.trim())
: undefined;
const result = await knowledgeService.queryGraph(team.id, query.startId, depth, relationTypes);
if (!result) {
return reply.code(404).send({ error: 'Entity not found' });
}
return result;
});
}

View File

@@ -1,96 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { MessageService } from '../services/message-service.js';
import { TeamService } from '../services/team-service.js';
import { sendMessageSchema } from '@waggle/shared';
import { validateMessageTypeCombo } from '@waggle/waggle-dance';
import type { MessageType, MessageSubtype } from '@waggle/shared';
import { z } from 'zod';
const hiveCheckSchema = z.object({
topic: z.string().min(1).max(500),
scope: z.string().max(200).optional(),
});
export async function messageRoutes(fastify: FastifyInstance) {
const messageService = new MessageService(fastify.db);
const teamService = new TeamService(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return team;
}
// POST /api/teams/:slug/messages — send Waggle Dance message
fastify.post('/api/teams/:slug/messages', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = sendMessageSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
// Validate type-subtype combination using waggle-dance protocol
if (!validateMessageTypeCombo(parsed.data.type as MessageType, parsed.data.subtype as MessageSubtype)) {
return reply.code(400).send({
error: `Invalid type-subtype combination: ${parsed.data.type}/${parsed.data.subtype}`,
});
}
const message = await messageService.send(
team.id,
request.userId,
parsed.data,
fastify.redis,
);
return reply.code(201).send(message);
});
// GET /api/teams/:slug/messages — list messages
fastify.get('/api/teams/:slug/messages', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const query = request.query as { type?: string; subtype?: string };
const filters: { type?: string; subtype?: string } = {};
if (query.type) filters.type = query.type;
if (query.subtype) filters.subtype = query.subtype;
const messageList = await messageService.list(team.id, filters);
return messageList;
});
// POST /api/teams/:slug/messages/hive-check — check the hive
fastify.post('/api/teams/:slug/messages/hive-check', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = hiveCheckSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const result = await messageService.checkHive(team.id, parsed.data);
return result;
});
}

View File

@@ -1,78 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { ResourceService } from '../services/resource-service.js';
import { TeamService } from '../services/team-service.js';
import { createResourceSchema } from '@waggle/shared';
export async function resourceRoutes(fastify: FastifyInstance) {
const resourceService = new ResourceService(fastify.db);
const teamService = new TeamService(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return team;
}
// POST /api/teams/:slug/resources — share a resource
fastify.post('/api/teams/:slug/resources', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = createResourceSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const resource = await resourceService.share(team.id, request.userId, parsed.data);
return reply.code(201).send(resource);
});
// GET /api/teams/:slug/resources — list resources
fastify.get('/api/teams/:slug/resources', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const query = request.query as { type?: string };
const resources = await resourceService.list(team.id, query.type);
return resources;
});
// PATCH /api/teams/:slug/resources/:id — rate a resource (also increments useCount)
fastify.patch('/api/teams/:slug/resources/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const body = request.body as { rating?: number };
if (body.rating === undefined || typeof body.rating !== 'number' || body.rating < 0 || body.rating > 5) {
return reply.code(400).send({ error: 'rating must be a number between 0 and 5' });
}
// Rate (uses running average) then increment use count
const rated = await resourceService.rate(team.id, id, body.rating);
if (!rated) {
return reply.code(404).send({ error: 'Resource not found' });
}
const updated = await resourceService.incrementUseCount(team.id, id);
return updated;
});
}

View File

@@ -1,35 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { ScoutAgent } from '../daemons/scout.js';
export async function scoutRoutes(fastify: FastifyInstance) {
const scout = new ScoutAgent(fastify.db);
// GET /api/scout/findings — list findings for the authenticated user
fastify.get('/api/scout/findings', {
preHandler: [fastify.authenticate],
}, async (request) => {
return scout.listFindings(request.userId);
});
// PATCH /api/scout/findings/:id — adopt or dismiss a finding
fastify.patch('/api/scout/findings/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { id } = request.params as { id: string };
const body = request.body as { status?: string };
if (!body.status || !['adopted', 'dismissed'].includes(body.status)) {
return reply.code(400).send({ error: 'status must be one of: adopted, dismissed' });
}
const action = body.status === 'adopted'
? scout.adopt(id, request.userId)
: scout.dismiss(id, request.userId);
const updated = await action;
if (!updated) {
return reply.code(404).send({ error: 'Finding not found' });
}
return updated;
});
}

View File

@@ -1,36 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { ProactiveService } from '../services/proactive-service.js';
export async function suggestionRoutes(fastify: FastifyInstance) {
const proactiveService = new ProactiveService(fastify.db);
// GET /api/suggestions — list pending suggestions for the authenticated user
fastify.get('/api/suggestions', {
preHandler: [fastify.authenticate],
}, async (request) => {
return proactiveService.listPending(request.userId);
});
// PATCH /api/suggestions/:id — accept, dismiss, or snooze a suggestion
fastify.patch('/api/suggestions/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { id } = request.params as { id: string };
const body = request.body as { status?: string };
if (!body.status || !['accepted', 'dismissed', 'snoozed'].includes(body.status)) {
return reply.code(400).send({ error: 'status must be one of: accepted, dismissed, snoozed' });
}
const updated = await proactiveService.updateStatus(
id,
request.userId,
body.status as 'accepted' | 'dismissed' | 'snoozed',
);
if (!updated) {
return reply.code(404).send({ error: 'Suggestion not found' });
}
return updated;
});
}

View File

@@ -1,115 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { TaskService } from '../services/task-service.js';
import { TeamService } from '../services/team-service.js';
import { createTaskSchema, updateTaskSchema } from '@waggle/shared';
export async function taskRoutes(fastify: FastifyInstance) {
const taskService = new TaskService(fastify.db);
const teamService = new TeamService(fastify.db);
async function resolveTeam(request: FastifyRequest, reply: FastifyReply, slug: string) {
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
return team;
}
// POST /api/teams/:slug/tasks — create task
fastify.post('/api/teams/:slug/tasks', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = createTaskSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const task = await taskService.create(team.id, request.userId, parsed.data);
return reply.code(201).send(task);
});
// GET /api/teams/:slug/tasks — list tasks
fastify.get('/api/teams/:slug/tasks', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug } = request.params as { slug: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const query = request.query as { status?: string; assignee?: string; priority?: string };
const filters: { status?: string; assignee?: string; priority?: string } = {};
if (query.status) filters.status = query.status;
if (query.assignee) filters.assignee = query.assignee;
if (query.priority) filters.priority = query.priority;
const taskList = await taskService.list(team.id, filters);
return taskList;
});
// GET /api/teams/:slug/tasks/:id — get task details
fastify.get('/api/teams/:slug/tasks/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const task = await taskService.get(id);
if (!task || task.teamId !== team.id) {
return reply.code(404).send({ error: 'Task not found' });
}
return task;
});
// PATCH /api/teams/:slug/tasks/:id — update task
fastify.patch('/api/teams/:slug/tasks/:id', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const parsed = updateTaskSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const existing = await taskService.get(id);
if (!existing || existing.teamId !== team.id) {
return reply.code(404).send({ error: 'Task not found' });
}
const updated = await taskService.update(id, parsed.data);
return updated;
});
// POST /api/teams/:slug/tasks/:id/claim — claim task
fastify.post('/api/teams/:slug/tasks/:id/claim', {
preHandler: [fastify.authenticate],
}, async (request, reply) => {
const { slug, id } = request.params as { slug: string; id: string };
const team = await resolveTeam(request, reply, slug);
if (!team) return;
const existing = await taskService.get(id);
if (!existing || existing.teamId !== team.id) {
return reply.code(404).send({ error: 'Task not found' });
}
const claimed = await taskService.claim(id, request.userId);
return claimed;
});
}

View File

@@ -1,184 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { TeamService } from '../services/team-service.js';
import { users } from '../db/schema.js';
import { eq } from 'drizzle-orm';
import { createTeamSchema, inviteMemberSchema, updateMemberSchema } from '@waggle/shared';
const ROLE_HIERARCHY: Record<string, number> = { member: 1, admin: 2, owner: 3 };
async function requireTeamRole(
server: FastifyInstance,
request: FastifyRequest,
reply: FastifyReply,
slug: string,
minRole: 'member' | 'admin' | 'owner',
) {
const teamService = new TeamService(server.db);
const team = await teamService.getBySlug(slug);
if (!team) {
reply.code(404).send({ error: 'Team not found' });
return null;
}
const membership = await teamService.getMembership(team.id, request.userId);
if (!membership) {
reply.code(403).send({ error: 'Not a member of this team' });
return null;
}
const userLevel = ROLE_HIERARCHY[membership.role] ?? 0;
const requiredLevel = ROLE_HIERARCHY[minRole] ?? 0;
if (userLevel < requiredLevel) {
reply.code(403).send({ error: 'Insufficient permissions' });
return null;
}
return { team, membership };
}
export async function teamRoutes(fastify: FastifyInstance) {
const teamService = new TeamService(fastify.db);
// POST /api/teams — create team
fastify.post('/api/teams', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const parsed = createTeamSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
// Check slug uniqueness
const existing = await teamService.getBySlug(parsed.data.slug);
if (existing) {
return reply.code(409).send({ error: 'Team slug already exists' });
}
const team = await teamService.create(request.userId, parsed.data);
return reply.code(201).send(team);
});
// GET /api/teams — list user's teams
fastify.get('/api/teams', { preHandler: [fastify.authenticate] }, async (request) => {
return teamService.listForUser(request.userId);
});
// GET /api/teams/:slug — get team details with members
fastify.get('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { slug } = request.params as { slug: string };
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
if (!result) return;
const members = await teamService.getMembers(result.team.id);
return { ...result.team, members };
});
// PATCH /api/teams/:slug — update team (admin+)
fastify.patch('/api/teams/:slug', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { slug } = request.params as { slug: string };
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
if (!result) return;
const body = request.body as { name?: string };
if (!body.name || typeof body.name !== 'string' || body.name.length < 1 || body.name.length > 100) {
return reply.code(400).send({ error: 'Invalid name' });
}
const updated = await teamService.update(result.team.id, { name: body.name });
return updated;
});
// POST /api/teams/:slug/members — invite member (admin+)
fastify.post('/api/teams/:slug/members', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { slug } = request.params as { slug: string };
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
if (!result) return;
const parsed = inviteMemberSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
// Look up user by email
const [targetUser] = await fastify.db
.select()
.from(users)
.where(eq(users.email, parsed.data.email))
.limit(1);
if (!targetUser) {
return reply.code(404).send({ error: 'User not found with that email' });
}
// Check if already a member
const existingMembership = await teamService.getMembership(result.team.id, targetUser.id);
if (existingMembership) {
return reply.code(409).send({ error: 'User is already a member of this team' });
}
const member = await teamService.addMember(result.team.id, targetUser.id, parsed.data.role);
return reply.code(201).send(member);
});
// DELETE /api/teams/:slug/members/:userId — remove member (admin+)
fastify.delete('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { slug, userId } = request.params as { slug: string; userId: string };
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
if (!result) return;
try {
const removed = await teamService.removeMember(result.team.id, userId);
if (!removed) {
return reply.code(404).send({ error: 'Member not found' });
}
return reply.code(204).send();
} catch (err: unknown) {
if (err instanceof Error && err.message === 'Cannot remove the team owner') {
return reply.code(403).send({ error: err.message });
}
throw err;
}
});
// PATCH /api/teams/:slug/members/:userId — update member
fastify.patch('/api/teams/:slug/members/:userId', { preHandler: [fastify.authenticate] }, async (request, reply) => {
const { slug, userId: targetUserId } = request.params as { slug: string; userId: string };
const parsed = updateMemberSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: 'Validation failed', details: parsed.error.flatten() });
}
// Determine required role: role changes need admin+, self-updates for roleDescription/interests are ok
const isSelfUpdate = request.userId === targetUserId;
const isRoleChange = parsed.data.role !== undefined;
if (isRoleChange || !isSelfUpdate) {
// Need admin+ for role changes or updating other members
const result = await requireTeamRole(fastify, request, reply, slug, 'admin');
if (!result) return;
try {
const updated = await teamService.updateMember(result.team.id, targetUserId, parsed.data);
if (!updated) {
return reply.code(404).send({ error: 'Member not found' });
}
return updated;
} catch (err: unknown) {
if (err instanceof Error && err.message === 'Cannot change the team owner role') {
return reply.code(403).send({ error: err.message });
}
throw err;
}
} else {
// Self-update: only roleDescription and interests (no role field)
const result = await requireTeamRole(fastify, request, reply, slug, 'member');
if (!result) return;
const { role: _discard, ...safeData } = parsed.data;
const updated = await teamService.updateMember(result.team.id, targetUserId, safeData);
if (!updated) {
return reply.code(404).send({ error: 'Member not found' });
}
return updated;
}
});
}

View File

@@ -1,57 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { verifyWebhook } from '@clerk/fastify/webhooks';
import { users } from '../db/schema.js';
import { eq } from 'drizzle-orm';
/** Subset of the Clerk user webhook payload `data` object that we consume. */
interface ClerkWebhookUserData {
id: string;
first_name?: string | null;
last_name?: string | null;
email_addresses?: Array<{ email_address?: string }>;
image_url?: string | null;
}
export async function webhookRoutes(fastify: FastifyInstance) {
fastify.post('/api/webhooks/clerk', async (request, reply) => {
let event: { type: string; data: ClerkWebhookUserData };
try {
event = await verifyWebhook(request) as typeof event;
} catch (error) {
fastify.log.warn({ err: error }, 'Clerk webhook verification failed');
return reply.code(400).send({ error: 'Invalid webhook signature' });
}
switch (event.type) {
case 'user.created': {
const d = event.data;
await fastify.db.insert(users).values({
clerkId: d.id,
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim() || d.id,
email: d.email_addresses?.[0]?.email_address ?? '',
avatarUrl: d.image_url ?? null,
}).onConflictDoNothing();
break;
}
case 'user.updated': {
const d = event.data;
await fastify.db.update(users)
.set({
displayName: `${d.first_name ?? ''} ${d.last_name ?? ''}`.trim(),
email: d.email_addresses?.[0]?.email_address ?? '',
avatarUrl: d.image_url ?? null,
updatedAt: new Date(),
})
.where(eq(users.clerkId, d.id));
break;
}
case 'user.deleted': {
const d = event.data;
await fastify.db.delete(users).where(eq(users.clerkId, d.id));
break;
}
}
return reply.code(200).send({ received: true });
});
}

View File

@@ -1,110 +0,0 @@
import { lte, eq, and } from 'drizzle-orm';
import { createHash } from 'node:crypto';
import cronParser from 'cron-parser';
const { parseExpression } = cronParser;
import { cronSchedules } from '../db/schema.js';
import type { Db } from '../db/connection.js';
import type { JobService } from '../services/job-service.js';
import { scheduledJobTypeSchema } from '@waggle/shared';
function occurrenceJobId(scheduleId: string, scheduledFor: Date): string {
const bytes = createHash('sha256')
.update(scheduleId)
.update('\0')
.update(scheduledFor.toISOString())
.digest()
.subarray(0, 16);
bytes[6] = (bytes[6] & 0x0f) | 0x80;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = bytes.toString('hex');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
export class CronRunner {
private interval: ReturnType<typeof setInterval> | null = null;
private tickInFlight: Promise<number> | null = null;
constructor(
private db: Db,
private jobService: JobService,
private onError: (error: unknown) => void = () => undefined,
) {}
start(intervalMs = 60_000) {
if (this.interval) return;
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
throw new Error('Cron interval must be a positive number');
}
const runTick = () => {
if (this.tickInFlight) return;
const tick = this.tick()
.catch(error => {
this.onError(error);
return 0;
})
.finally(() => {
if (this.tickInFlight === tick) this.tickInFlight = null;
});
this.tickInFlight = tick;
};
runTick();
this.interval = setInterval(runTick, intervalMs);
this.interval.unref?.();
}
async stop() {
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
await this.tickInFlight;
}
async tick() {
const now = new Date();
// Find all enabled schedules that are due
const due = await this.db.select().from(cronSchedules)
.where(and(
eq(cronSchedules.enabled, true),
lte(cronSchedules.nextRunAt, now),
));
let queuedCount = 0;
for (const schedule of due) {
const jobType = scheduledJobTypeSchema.safeParse(schedule.jobType);
if (!jobType.success || !schedule.nextRunAt) continue;
try {
// Validate legacy rows before queueing so a poison cron expression
// cannot create a duplicate job on every scheduler pass.
const nextRunAt = parseExpression(schedule.cronExpr).next().toDate();
await this.jobService.createJob(
schedule.teamId,
schedule.createdBy,
jobType.data,
schedule.jobConfig as Record<string, unknown>,
occurrenceJobId(schedule.id, schedule.nextRunAt),
);
const [advanced] = await this.db.update(cronSchedules)
.set({ lastRunAt: now, nextRunAt })
.where(and(
eq(cronSchedules.id, schedule.id),
eq(cronSchedules.nextRunAt, schedule.nextRunAt),
))
.returning({ id: cronSchedules.id });
if (advanced) queuedCount++;
} catch (error) {
// One malformed or temporarily failing schedule must not starve the
// remaining due work. The lifecycle runner supplies the server logger.
this.onError(error);
}
}
return queuedCount;
}
}

View File

@@ -1,241 +0,0 @@
import { eq, and, inArray } from 'drizzle-orm';
import { agents, agentGroups, agentGroupMembers, agentJobs } from '../db/schema.js';
import type { Db } from '../db/connection.js';
export class AgentGroupMemberNotFoundError extends Error {}
export class AgentService {
constructor(private db: Db) {}
private async groupMembersOwned(userId: string, agentIds: string[]): Promise<boolean> {
const uniqueAgentIds = [...new Set(agentIds)];
if (uniqueAgentIds.length === 0) return true;
const ownedAgents = await this.db
.select({ id: agents.id })
.from(agents)
.where(and(eq(agents.userId, userId), inArray(agents.id, uniqueAgentIds)));
return ownedAgents.length === uniqueAgentIds.length;
}
private async assertGroupMembersOwned(userId: string, agentIds: string[]): Promise<void> {
if (!(await this.groupMembersOwned(userId, agentIds))) {
throw new AgentGroupMemberNotFoundError();
}
}
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 }>;
}) {
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
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));
if (!(await this.groupMembersOwned(userId, members.map((member) => member.agentId)))) {
return null;
}
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;
if (data.members) {
await this.assertGroupMembersOwned(userId, data.members.map((member) => member.agentId));
}
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

@@ -1,291 +0,0 @@
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

@@ -1,74 +0,0 @@
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

@@ -1,90 +0,0 @@
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';
import { scheduledJobTypeSchema } from '@waggle/shared';
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 jobType = scheduledJobTypeSchema.safeParse(data.jobType);
if (!jobType.success) {
throw new Error(`Unsupported scheduled job type: ${data.jobType}`);
}
const [schedule] = await this.db.insert(cronSchedules).values({
teamId,
createdBy: userId,
name: data.name,
cronExpr: data.cronExpr,
jobType: jobType.data,
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(teamId: string, 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(and(
eq(cronSchedules.id, id),
eq(cronSchedules.teamId, teamId),
))
.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

@@ -1,103 +0,0 @@
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>,
jobId?: string,
) {
const [created] = await this.db.insert(agentJobs).values({
...(jobId ? { id: jobId } : {}),
teamId,
userId,
jobType,
status: 'queued',
input,
}).onConflictDoNothing({ target: agentJobs.id }).returning();
const job = created ?? (jobId ? await this.getJob(jobId) : null);
if (!job) throw new Error('Failed to create job');
if (job.teamId !== teamId || job.userId !== userId || job.jobType !== jobType) {
throw new Error('Job idempotency key collision');
}
await this.queue.add(job.jobType, {
jobId: job.id,
teamId: job.teamId,
userId: job.userId,
jobType: job.jobType,
input: job.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

@@ -1,168 +0,0 @@
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 endpointIds = [...new Set([data.sourceId, data.targetId])];
const ownedEndpoints = await this.db
.select({ id: teamEntities.id })
.from(teamEntities)
.where(and(
eq(teamEntities.teamId, teamId),
inArray(teamEntities.id, endpointIds),
));
if (ownedEndpoints.length !== endpointIds.length) return null;
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 [startEntity] = await this.db
.select()
.from(teamEntities)
.where(and(
eq(teamEntities.id, startEntityId),
eq(teamEntities.teamId, teamId),
))
.limit(1);
if (!startEntity) return null;
const visited = new Set<string>([startEntityId]);
const resultEntities: Array<typeof teamEntities.$inferSelect> = [startEntity];
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;
}
return {
entities: resultEntities,
relations: resultRelations,
};
}
}

View File

@@ -1,119 +0,0 @@
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

@@ -1,102 +0,0 @@
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,
userId: string,
status: 'accepted' | 'dismissed' | 'snoozed',
) {
const [updated] = await this.db.update(suggestionsLog)
.set({ status })
.where(and(
eq(suggestionsLog.id, suggestionId),
eq(suggestionsLog.userId, userId),
))
.returning();
return updated ?? null;
}
}

View File

@@ -1,89 +0,0 @@
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(teamId: string, resourceId: string, rating: number) {
const [resource] = await this.db
.select()
.from(teamResources)
.where(and(
eq(teamResources.id, resourceId),
eq(teamResources.teamId, teamId),
))
.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(and(
eq(teamResources.id, resourceId),
eq(teamResources.teamId, teamId),
))
.returning();
return updated;
}
async incrementUseCount(teamId: string, resourceId: string) {
const [resource] = await this.db
.select()
.from(teamResources)
.where(and(
eq(teamResources.id, resourceId),
eq(teamResources.teamId, teamId),
))
.limit(1);
if (!resource) return null;
const [updated] = await this.db.update(teamResources)
.set({ useCount: resource.useCount + 1 })
.where(and(
eq(teamResources.id, resourceId),
eq(teamResources.teamId, teamId),
))
.returning();
return updated;
}
}

View File

@@ -1,91 +0,0 @@
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

@@ -1,379 +0,0 @@
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(teamId: string, overrideId: string) {
const [deleted] = await this.db
.delete(teamCapabilityOverrides)
.where(and(
eq(teamCapabilityOverrides.teamId, teamId),
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(teamId: string, requestId: string) {
const [row] = await this.db
.select()
.from(teamCapabilityRequests)
.where(and(
eq(teamCapabilityRequests.teamId, teamId),
eq(teamCapabilityRequests.id, requestId),
))
.limit(1);
return row ?? null;
}
async decideRequest(
teamId: string,
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(and(
eq(teamCapabilityRequests.teamId, teamId),
eq(teamCapabilityRequests.id, requestId),
))
.returning();
return updated ?? null;
}
}

View File

@@ -1,139 +0,0 @@
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[] },
) {
if (data.role !== undefined) {
const membership = await this.getMembership(teamId, userId);
if (!membership) return null;
if (membership.role === 'owner') {
throw new Error('Cannot change the team owner role');
}
}
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

@@ -1,59 +0,0 @@
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;
}
}

View File

@@ -1,46 +0,0 @@
import type { WebSocket } from 'ws';
import type { WsServerEvent } from '@waggle/shared';
export class ConnectionManager {
private connections = new Map<string, Map<string, WebSocket>>(); // teamId -> userId -> ws
add(teamId: string, userId: string, ws: WebSocket): void {
if (!this.connections.has(teamId)) {
this.connections.set(teamId, new Map());
}
this.connections.get(teamId)!.set(userId, ws);
}
remove(teamId: string, userId: string): void {
this.connections.get(teamId)?.delete(userId);
if (this.connections.get(teamId)?.size === 0) {
this.connections.delete(teamId);
}
}
broadcast(teamId: string, event: WsServerEvent, excludeUserId?: string): void {
const team = this.connections.get(teamId);
if (!team) return;
const data = JSON.stringify(event);
for (const [userId, ws] of team) {
if (userId !== excludeUserId && ws.readyState === ws.OPEN) {
ws.send(data);
}
}
}
sendTo(teamId: string, userId: string, event: WsServerEvent): void {
const ws = this.connections.get(teamId)?.get(userId);
if (ws && ws.readyState === ws.OPEN) {
ws.send(JSON.stringify(event));
}
}
getConnectedUsers(teamId: string): string[] {
return Array.from(this.connections.get(teamId)?.keys() ?? []);
}
getTeamCount(): number {
return this.connections.size;
}
}

View File

@@ -1,264 +0,0 @@
import type { FastifyInstance } from 'fastify';
import type { WsClientEvent, WsServerEvent } from '@waggle/shared';
import { createClerkClient, verifyToken } from '@clerk/fastify';
import { ConnectionManager } from './connection-manager.js';
import { teams, messages, users } from '../db/schema.js';
import { eq } from 'drizzle-orm';
import { TeamService } from '../services/team-service.js';
export const connectionManager = new ConnectionManager();
/**
* Validate that a string looks like a JWT (3 dot-separated base64url segments).
* This is a structural check, not a cryptographic verification.
*/
function isJwtStructure(token: string): boolean {
const parts = token.split('.');
if (parts.length !== 3) return false;
// Each segment should be non-empty and valid base64url
const base64urlRegex = /^[A-Za-z0-9_-]+$/;
return parts.every((part) => part.length > 0 && base64urlRegex.test(part));
}
// Overridable verifier for testing — allows tests to swap in a mock
export type WsTokenVerifier = (token: string) => Promise<{ sub: string }>;
let _wsTokenVerifier: WsTokenVerifier | null = null;
/** Override the WS token verifier (for testing only) */
export function setWsTokenVerifier(verifier: WsTokenVerifier | null): void {
_wsTokenVerifier = verifier;
}
export async function wsGateway(fastify: FastifyInstance) {
const teamService = new TeamService(fastify.db);
// Create Clerk client for JWT verification if secret key is available
const clerkSecretKey = fastify.config.clerkSecretKey;
const clerk = clerkSecretKey
? createClerkClient({ secretKey: clerkSecretKey })
: null;
// Hard fail in production if no JWT verification path is configured. Without
// either a Clerk client or a test override, the gateway would have no way to
// cryptographically verify incoming tokens — the previous fallback (unsigned
// JWT decode) is forgeable. NODE_ENV !== 'production' (dev / desktop /
// testing) is allowed to start without the key, but connections without a
// verifier are rejected at request time below.
if (!clerk && !_wsTokenVerifier && process.env.NODE_ENV === 'production') {
throw new Error(
'[ws-gateway] CLERK_SECRET_KEY required in production. WebSocket gateway ' +
'refuses to start without cryptographic JWT verification configured. ' +
'Set CLERK_SECRET_KEY in environment or settings.json.',
);
}
if (!clerk && !_wsTokenVerifier) {
fastify.log.warn(
'[ws-gateway] CLERK_SECRET_KEY absent; WebSocket connections will be rejected. ' +
'This is dev/desktop mode — set CLERK_SECRET_KEY for cloud/SaaS deployments.',
);
}
fastify.get('/ws', { websocket: true }, (socket, request) => {
let userId: string | null = null;
let teamId: string | null = null;
socket.on('message', async (raw: Buffer | string) => {
try {
const event = JSON.parse(raw.toString()) as WsClientEvent;
switch (event.type) {
case 'authenticate': {
const token = event.token;
// Reject tokens that are not JWTs (plain userIds, random strings)
if (!isJwtStructure(token)) {
socket.send(
JSON.stringify({
type: 'error',
message: 'Invalid token: must be a valid JWT',
}),
);
return;
}
try {
let sub: string;
if (_wsTokenVerifier) {
// Test override path
const result = await _wsTokenVerifier(token);
sub = result.sub;
} else if (clerk) {
// Production path: full Clerk JWT verification. `clerk` is only
// non-null when clerkSecretKey is set, so the secretKey below is
// always present here.
const payload = await verifyToken(token, { secretKey: clerkSecretKey });
sub = payload.sub;
} else {
// No verifier available — reject. The startup check above ensures
// production cannot reach this branch. Dev/desktop without a key
// hits this and is rejected at connection time (no silent decode).
socket.send(
JSON.stringify({
type: 'error',
message: 'Authentication unavailable: server has no JWT verifier configured',
}),
);
socket.close();
return;
}
// Look up internal user by Clerk ID
const [user] = await fastify.db
.select()
.from(users)
.where(eq(users.clerkId, sub));
if (!user) {
socket.send(
JSON.stringify({
type: 'error',
message: 'User not found',
}),
);
return;
}
if (teamId && userId) {
connectionManager.remove(teamId, userId);
}
teamId = null;
userId = user.id;
socket.send(JSON.stringify({ type: 'authenticated', userId }));
} catch {
socket.send(
JSON.stringify({
type: 'error',
message: 'Token verification failed',
}),
);
}
break;
}
case 'join_team': {
if (!userId) {
socket.send(JSON.stringify({ type: 'error', message: 'Not authenticated' }));
return;
}
const [team] = await fastify.db
.select()
.from(teams)
.where(eq(teams.slug, event.teamSlug));
if (!team) {
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
return;
}
const membership = await teamService.getMembership(team.id, userId);
if (!membership) {
socket.send(JSON.stringify({ type: 'error', message: 'Team not found' }));
return;
}
// Leave previous team if any
if (teamId && userId) {
connectionManager.remove(teamId, userId);
}
teamId = team.id;
connectionManager.add(teamId, userId, socket);
// Subscribe to Redis channel for this team
const channel = `team:${teamId}:waggle`;
try {
const existingChannels = await fastify.redisSub.call('PUBSUB', 'CHANNELS', channel) as string[];
// Only subscribe if not already subscribed (redisSub is shared)
if (!existingChannels || !existingChannels.includes(channel)) {
await fastify.redisSub.subscribe(channel);
}
} catch {
// Redis subscribe failure is non-fatal — real-time updates won't work
// but join should still succeed
}
socket.send(JSON.stringify({ type: 'joined_team', teamSlug: event.teamSlug }));
break;
}
case 'send_message': {
if (!userId || !teamId) {
socket.send(JSON.stringify({ type: 'error', message: 'Not in a team' }));
return;
}
// Persist message
const [msg] = await fastify.db
.insert(messages)
.values({
teamId,
senderId: userId,
type: event.messageType,
subtype: event.subtype,
content: event.content,
})
.returning();
// Publish to Redis for cross-process delivery
await fastify.redis.publish(
`team:${teamId}:waggle`,
JSON.stringify(msg),
);
break;
}
}
} catch {
socket.send(JSON.stringify({ type: 'error', message: 'Invalid message' }));
}
});
socket.on('close', () => {
if (teamId && userId) {
connectionManager.remove(teamId, userId);
}
});
});
// Forward Redis pub/sub messages to WebSocket clients
fastify.redisSub.on('message', (channel: string, data: string) => {
const match = channel.match(/^team:(.+):waggle$/);
if (!match) return;
const tId = match[1];
try {
const event: WsServerEvent = { type: 'waggle_message', message: JSON.parse(data) };
connectionManager.broadcast(tId, event);
} catch {
// Ignore malformed messages from Redis
}
});
// Subscribe to job progress channels via pattern matching
await fastify.redisSub.psubscribe('job:*:progress');
// Forward job progress events to WebSocket clients
fastify.redisSub.on('pmessage', (_pattern: string, channel: string, data: string) => {
const jobMatch = channel.match(/^job:(.+):progress$/);
if (!jobMatch) return;
try {
const parsed = JSON.parse(data);
const event: WsServerEvent = {
type: 'job_progress',
jobId: jobMatch[1],
progress: parsed,
};
// Route to the team that owns this job
if (parsed.teamId) {
connectionManager.broadcast(parsed.teamId, event);
}
} catch {
// Ignore malformed messages from Redis
}
});
}