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

@@ -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;
}