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

@@ -9,22 +9,16 @@ export interface ProviderEntry {
baseUrl?: string;
}
export interface TeamServerConfig {
url: string;
token?: string;
userId?: string;
displayName?: string;
}
export interface CliConfig {
allowlist?: string[];
}
// Keys the commercial edition writes (tier, trialStartedAt, teamServer) are not
// read here but stay in config.json on save: both editions may share ~/.waggle.
interface ConfigData {
defaultModel: string;
providers: Record<string, ProviderEntry>;
mindPath?: string;
teamServer?: TeamServerConfig;
/** Governed CLI programs the agent may execute. */
cli?: CliConfig;
/** F8: Daily cost budget in dollars. null = no limit. */
@@ -199,24 +193,6 @@ export class WaggleConfig {
this.data.maxIterations = Math.max(5, Math.min(500, max));
}
// --- Team Server (Phase 5) ---
getTeamServer(): TeamServerConfig | null {
return this.data.teamServer ?? null;
}
setTeamServer(config: TeamServerConfig): void {
this.data.teamServer = config;
}
clearTeamServer(): void {
delete this.data.teamServer;
}
isTeamConnected(): boolean {
return this.data.teamServer !== null && this.data.teamServer !== undefined && typeof this.data.teamServer.url === 'string' && this.data.teamServer.url.length > 0;
}
// --- Governed CLI access ---
getCliAllowlist(): string[] {

View File

@@ -11,7 +11,7 @@
//
// Waggle-specific (non-extracted) modules below the substrate re-exports stay
// in this package: config, multi-mind, workspace orchestration, vault, telemetry,
// install-audit, cron-store, skill-hashes, team-sync, file-store, file-indexer,
// install-audit, cron-store, skill-hashes, file-store, file-indexer,
// memory-import.
// ── Waggle infrastructure (not memory) ──
@@ -140,9 +140,8 @@ export {
} from '@waggle/hive-mind-core';
// ── Waggle-specific orchestration (stays in @waggle/core) ──
export { WaggleConfig, type ProviderEntry, type TeamServerConfig } from './config.js';
export { WaggleConfig, type ProviderEntry } from './config.js';
export { needsMigration, migrateToMultiMind } from './migration.js';
export { TeamSync, frameToEntity, entityToSyncedFrame, type TeamSyncConfig, type SyncedFrame } from './team-sync.js';
export {
InstallAuditStore, INSTALL_AUDIT_TABLE_SQL,
type InstallAuditEntry, type RecordAuditInput,

View File

@@ -1,190 +0,0 @@
/**
* TeamSync — Syncs memory frames between local .mind and team server.
*
* Uses the team server's entities API (entityType='memory_frame') for storage.
* Push-on-write: new frames are pushed to team server after local write.
* Pull-on-activate: frames are pulled from team server when workspace is activated.
* Attribution: each frame carries the author's userId and displayName.
*
* Sync protocol:
* - Frames are identified by a composite key: gopId + t (group-of-pictures ID + temporal index)
* - Pull uses ?type=memory_frame&since=<timestamp> to get only new frames
* - Push sends each frame as a teamEntity with entityType='memory_frame'
* - Last-write-wins at frame level (frames are append-mostly, conflicts are rare)
*/
import type { MemoryFrame, FrameType, Importance } from '@waggle/hive-mind-core';
import { createCoreLogger } from './logger.js';
const log = createCoreLogger('team-sync');
export interface TeamSyncConfig {
teamServerUrl: string;
teamSlug: string;
authToken: string;
userId: string;
displayName: string;
}
export type TeamSyncFetch = (url: string, init?: RequestInit) => Promise<Response>;
export interface SyncedFrame {
/** Server-side entity ID (UUID). */
remoteId: string;
gopId: string;
t: number;
frameType: FrameType;
content: string;
importance: Importance;
authorId: string;
authorName: string;
createdAt: string;
}
/**
* Convert a local MemoryFrame to the team server entity format.
*/
export function frameToEntity(frame: MemoryFrame, authorId: string, authorName: string) {
return {
entityType: 'memory_frame',
name: frame.gop_id,
properties: {
frameType: frame.frame_type,
t: frame.t,
baseFrameId: frame.base_frame_id,
content: frame.content,
importance: frame.importance,
authorId,
authorName,
localId: frame.id,
},
};
}
/**
* Convert a team server entity back to a SyncedFrame.
*/
export function entityToSyncedFrame(entity: {
id: string;
name: string;
properties: Record<string, unknown>;
createdAt: string;
}): SyncedFrame {
const props = entity.properties;
return {
remoteId: entity.id,
gopId: entity.name,
t: (props.t as number) ?? 0,
frameType: (props.frameType as FrameType) ?? 'I',
content: (props.content as string) ?? '',
importance: (props.importance as Importance) ?? 'normal',
authorId: (props.authorId as string) ?? '',
authorName: (props.authorName as string) ?? '',
createdAt: entity.createdAt,
};
}
/**
* TeamSync handles push/pull of memory frames to/from the team server.
* This is a stateless client — call pushFrame() after writing locally,
* call pullFrames() on workspace activation.
*/
export class TeamSync {
private config: TeamSyncConfig;
private fetchTeamServer: TeamSyncFetch;
private lastSyncTimestamp: string | null = null;
constructor(config: TeamSyncConfig, fetchTeamServer: TeamSyncFetch) {
this.config = config;
this.fetchTeamServer = fetchTeamServer;
}
/**
* Push a single frame to the team server.
* Call this after writing a frame to the local workspace .mind.
*/
async pushFrame(frame: MemoryFrame): Promise<{ remoteId: string } | null> {
const entity = frameToEntity(frame, this.config.userId, this.config.displayName);
try {
const response = await this.fetchTeamServer(
`${this.config.teamServerUrl}/api/teams/${this.config.teamSlug}/entities`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.config.authToken}`,
},
body: JSON.stringify(entity),
}
);
if (!response.ok) {
log.error(`Push failed: ${response.status} ${response.statusText}`);
return null;
}
const created = await response.json() as { id: string };
return { remoteId: created.id };
} catch (err) {
log.error('Push error:', err);
return null;
}
}
/**
* Pull all memory frames from the team server.
* Returns frames sorted by creation time (newest first).
* Optionally pass `since` to get only frames created after that timestamp.
*/
async pullFrames(since?: string): Promise<SyncedFrame[]> {
try {
const url = `${this.config.teamServerUrl}/api/teams/${this.config.teamSlug}/entities?type=memory_frame`;
// Note: `since` filtering would require server-side support. For now, pull all and filter client-side.
const response = await this.fetchTeamServer(url, {
headers: {
'Authorization': `Bearer ${this.config.authToken}`,
},
});
if (!response.ok) {
log.error(`Pull failed: ${response.status} ${response.statusText}`);
return [];
}
const entities = await response.json() as Array<{
id: string;
name: string;
properties: Record<string, unknown>;
createdAt: string;
}>;
const frames = entities.map(entityToSyncedFrame);
// Client-side filter by timestamp if requested
if (since) {
return frames.filter(f => f.createdAt > since);
}
this.lastSyncTimestamp = new Date().toISOString();
return frames;
} catch (err) {
log.error('Pull error:', err);
return [];
}
}
/**
* Get the last sync timestamp (for incremental sync).
*/
getLastSyncTimestamp(): string | null {
return this.lastSyncTimestamp;
}
/**
* Set the last sync timestamp (e.g. loaded from persistent storage).
*/
setLastSyncTimestamp(ts: string): void {
this.lastSyncTimestamp = ts;
}
}

View File

@@ -28,14 +28,13 @@ export interface WorkspaceConfig {
created: string; // ISO 8601
// --- Team Mode fields (Phase 5) ---
// The community edition cannot create team workspaces (ADR-0003). These two
// fields stay because a data directory shared with the commercial edition may
// hold team workspaces, and the viewer write guards still honour their role.
/** Team ID on the team server. Present = team workspace. */
teamId?: string;
/** URL of the team server (e.g. "https://team.waggle.dev"). */
teamServerUrl?: string;
/** Current user's role in this team workspace. */
teamRole?: 'owner' | 'admin' | 'member' | 'viewer';
/** Current user's ID on the team server. */
teamUserId?: string;
// --- Budget ---
/** Monthly cost budget in USD. null = unlimited. */
@@ -94,9 +93,7 @@ export interface CreateWorkspaceOptions {
// --- Team Mode fields (Phase 5) ---
teamId?: string;
teamServerUrl?: string;
teamRole?: 'owner' | 'admin' | 'member' | 'viewer';
teamUserId?: string;
// --- Tone/Voice (Wave 7.3) ---
tone?: 'professional' | 'casual' | 'technical' | 'legal' | 'marketing';
@@ -237,9 +234,7 @@ export class WorkspaceManager {
...(options.team !== undefined && { team: options.team }),
...(options.directory !== undefined && { directory: options.directory }),
...(options.teamId !== undefined && { teamId: options.teamId }),
...(options.teamServerUrl !== undefined && { teamServerUrl: options.teamServerUrl }),
...(options.teamRole !== undefined && { teamRole: options.teamRole }),
...(options.teamUserId !== undefined && { teamUserId: options.teamUserId }),
...(options.tone !== undefined && { tone: options.tone }),
...(options.optimizationEnabled !== undefined && { optimizationEnabled: options.optimizationEnabled }),
...(options.optimizationBudget !== undefined && { optimizationBudget: options.optimizationBudget }),