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:
@@ -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[] {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 }),
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { WaggleConfig, type ProviderEntry, type TeamServerConfig } from '../src/config.js';
|
||||
import { WaggleConfig, type ProviderEntry } from '../src/config.js';
|
||||
|
||||
describe('WaggleConfig', () => {
|
||||
const tempDirs: string[] = [];
|
||||
@@ -100,58 +100,23 @@ describe('WaggleConfig', () => {
|
||||
expect(config.getConfigDir()).toBe(configDir);
|
||||
});
|
||||
|
||||
describe('team server config', () => {
|
||||
it('returns null when no team server configured', () => {
|
||||
describe('commercial-edition keys', () => {
|
||||
it('ignores a teamServer key and keeps it in config.json on save', () => {
|
||||
const configDir = makeTempDir();
|
||||
const teamServer = { url: 'https://team.waggle.dev', token: 'clerk-jwt-token' };
|
||||
fs.writeFileSync(
|
||||
path.join(configDir, 'config.json'),
|
||||
JSON.stringify({ defaultModel: 'claude-sonnet-4-6', providers: {}, teamServer }),
|
||||
);
|
||||
|
||||
const config = new WaggleConfig(configDir);
|
||||
|
||||
expect(config.getTeamServer()).toBeNull();
|
||||
expect(config.isTeamConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('sets and gets team server config', () => {
|
||||
const configDir = makeTempDir();
|
||||
const config = new WaggleConfig(configDir);
|
||||
|
||||
const teamConfig: TeamServerConfig = {
|
||||
url: 'https://team.waggle.dev',
|
||||
token: 'clerk-jwt-token',
|
||||
userId: 'user-123',
|
||||
displayName: 'Marko',
|
||||
};
|
||||
|
||||
config.setTeamServer(teamConfig);
|
||||
expect('getTeamServer' in config).toBe(false);
|
||||
config.setDefaultModel('gpt-4o');
|
||||
config.save();
|
||||
|
||||
const config2 = new WaggleConfig(configDir);
|
||||
const loaded = config2.getTeamServer();
|
||||
expect(loaded).toEqual(teamConfig);
|
||||
expect(config2.isTeamConnected()).toBe(true);
|
||||
});
|
||||
|
||||
it('clears team server config', () => {
|
||||
const configDir = makeTempDir();
|
||||
const config = new WaggleConfig(configDir);
|
||||
|
||||
config.setTeamServer({ url: 'https://team.waggle.dev' });
|
||||
config.clearTeamServer();
|
||||
config.save();
|
||||
|
||||
const config2 = new WaggleConfig(configDir);
|
||||
expect(config2.getTeamServer()).toBeNull();
|
||||
expect(config2.isTeamConnected()).toBe(false);
|
||||
});
|
||||
|
||||
it('persists team server through save/load cycle', () => {
|
||||
const configDir = makeTempDir();
|
||||
const config = new WaggleConfig(configDir);
|
||||
|
||||
config.setTeamServer({ url: 'https://example.com', userId: 'u1' });
|
||||
config.save();
|
||||
|
||||
const config2 = new WaggleConfig(configDir);
|
||||
expect(config2.getTeamServer()!.url).toBe('https://example.com');
|
||||
expect(config2.getTeamServer()!.userId).toBe('u1');
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(configDir, 'config.json'), 'utf-8'));
|
||||
expect(raw.defaultModel).toBe('gpt-4o');
|
||||
expect(raw.teamServer).toEqual(teamServer);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { frameToEntity, entityToSyncedFrame, TeamSync, type TeamSyncConfig } from '../src/team-sync.js';
|
||||
import type { MemoryFrame } from '@waggle/hive-mind-core';
|
||||
|
||||
describe('frameToEntity', () => {
|
||||
it('converts a MemoryFrame to team entity format', () => {
|
||||
const frame: MemoryFrame = {
|
||||
id: 42,
|
||||
frame_type: 'I',
|
||||
gop_id: 'project-context',
|
||||
t: 3,
|
||||
base_frame_id: null,
|
||||
content: 'The project uses React and TypeScript',
|
||||
importance: 'important',
|
||||
access_count: 5,
|
||||
created_at: '2026-03-12T10:00:00.000Z',
|
||||
last_accessed: '2026-03-12T12:00:00.000Z',
|
||||
};
|
||||
|
||||
const entity = frameToEntity(frame, 'user-abc', 'Marko');
|
||||
|
||||
expect(entity.entityType).toBe('memory_frame');
|
||||
expect(entity.name).toBe('project-context');
|
||||
expect(entity.properties.frameType).toBe('I');
|
||||
expect(entity.properties.t).toBe(3);
|
||||
expect(entity.properties.baseFrameId).toBeNull();
|
||||
expect(entity.properties.content).toBe('The project uses React and TypeScript');
|
||||
expect(entity.properties.importance).toBe('important');
|
||||
expect(entity.properties.authorId).toBe('user-abc');
|
||||
expect(entity.properties.authorName).toBe('Marko');
|
||||
expect(entity.properties.localId).toBe(42);
|
||||
});
|
||||
|
||||
it('preserves P-frame base_frame_id', () => {
|
||||
const frame: MemoryFrame = {
|
||||
id: 43,
|
||||
frame_type: 'P',
|
||||
gop_id: 'project-context',
|
||||
t: 4,
|
||||
base_frame_id: 42,
|
||||
content: 'Updated: now also using Tailwind',
|
||||
importance: 'normal',
|
||||
access_count: 0,
|
||||
created_at: '2026-03-12T11:00:00.000Z',
|
||||
last_accessed: '2026-03-12T11:00:00.000Z',
|
||||
};
|
||||
|
||||
const entity = frameToEntity(frame, 'user-xyz', 'Ana');
|
||||
|
||||
expect(entity.properties.frameType).toBe('P');
|
||||
expect(entity.properties.baseFrameId).toBe(42);
|
||||
expect(entity.properties.authorName).toBe('Ana');
|
||||
});
|
||||
});
|
||||
|
||||
describe('entityToSyncedFrame', () => {
|
||||
it('converts a team entity back to SyncedFrame', () => {
|
||||
const entity = {
|
||||
id: 'uuid-remote-1',
|
||||
name: 'project-context',
|
||||
properties: {
|
||||
frameType: 'I',
|
||||
t: 3,
|
||||
baseFrameId: null,
|
||||
content: 'The project uses React and TypeScript',
|
||||
importance: 'important',
|
||||
authorId: 'user-abc',
|
||||
authorName: 'Marko',
|
||||
localId: 42,
|
||||
},
|
||||
createdAt: '2026-03-12T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const frame = entityToSyncedFrame(entity);
|
||||
|
||||
expect(frame.remoteId).toBe('uuid-remote-1');
|
||||
expect(frame.gopId).toBe('project-context');
|
||||
expect(frame.t).toBe(3);
|
||||
expect(frame.frameType).toBe('I');
|
||||
expect(frame.content).toBe('The project uses React and TypeScript');
|
||||
expect(frame.importance).toBe('important');
|
||||
expect(frame.authorId).toBe('user-abc');
|
||||
expect(frame.authorName).toBe('Marko');
|
||||
expect(frame.createdAt).toBe('2026-03-12T10:00:00.000Z');
|
||||
});
|
||||
|
||||
it('handles missing properties gracefully', () => {
|
||||
const entity = {
|
||||
id: 'uuid-remote-2',
|
||||
name: 'some-gop',
|
||||
properties: {},
|
||||
createdAt: '2026-03-12T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const frame = entityToSyncedFrame(entity);
|
||||
|
||||
expect(frame.remoteId).toBe('uuid-remote-2');
|
||||
expect(frame.gopId).toBe('some-gop');
|
||||
expect(frame.t).toBe(0);
|
||||
expect(frame.frameType).toBe('I');
|
||||
expect(frame.content).toBe('');
|
||||
expect(frame.importance).toBe('normal');
|
||||
expect(frame.authorId).toBe('');
|
||||
expect(frame.authorName).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TeamSync', () => {
|
||||
const mockConfig: TeamSyncConfig = {
|
||||
teamServerUrl: 'https://team.waggle.dev',
|
||||
teamSlug: 'test-team',
|
||||
authToken: 'test-jwt-token',
|
||||
userId: 'user-abc',
|
||||
displayName: 'Marko',
|
||||
};
|
||||
|
||||
let fetchSpy: ReturnType<typeof vi.fn>;
|
||||
let globalFetchSpy: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchSpy = vi.fn();
|
||||
globalFetchSpy = vi.fn().mockRejectedValue(new Error('raw global fetch used'));
|
||||
vi.stubGlobal('fetch', globalFetchSpy);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('pushFrame', () => {
|
||||
it('sends frame to team server entities endpoint', async () => {
|
||||
fetchSpy.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ id: 'remote-uuid-1' }),
|
||||
});
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frame: MemoryFrame = {
|
||||
id: 1,
|
||||
frame_type: 'I',
|
||||
gop_id: 'test-gop',
|
||||
t: 0,
|
||||
base_frame_id: null,
|
||||
content: 'Test content',
|
||||
importance: 'normal',
|
||||
access_count: 0,
|
||||
created_at: '2026-03-12T10:00:00.000Z',
|
||||
last_accessed: '2026-03-12T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const result = await sync.pushFrame(frame);
|
||||
|
||||
expect(result).toEqual({ remoteId: 'remote-uuid-1' });
|
||||
expect(fetchSpy).toHaveBeenCalledOnce();
|
||||
expect(globalFetchSpy).not.toHaveBeenCalled();
|
||||
|
||||
const [url, opts] = fetchSpy.mock.calls[0];
|
||||
expect(url).toBe('https://team.waggle.dev/api/teams/test-team/entities');
|
||||
expect(opts.method).toBe('POST');
|
||||
expect(opts.headers['Authorization']).toBe('Bearer test-jwt-token');
|
||||
|
||||
const body = JSON.parse(opts.body);
|
||||
expect(body.entityType).toBe('memory_frame');
|
||||
expect(body.name).toBe('test-gop');
|
||||
expect(body.properties.content).toBe('Test content');
|
||||
expect(body.properties.authorId).toBe('user-abc');
|
||||
expect(body.properties.authorName).toBe('Marko');
|
||||
});
|
||||
|
||||
it('returns null on server error', async () => {
|
||||
fetchSpy.mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
statusText: 'Internal Server Error',
|
||||
});
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frame: MemoryFrame = {
|
||||
id: 1, frame_type: 'I', gop_id: 'test', t: 0, base_frame_id: null,
|
||||
content: 'x', importance: 'normal', access_count: 0,
|
||||
created_at: '2026-03-12T10:00:00.000Z', last_accessed: '2026-03-12T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const result = await sync.pushFrame(frame);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null on network error', async () => {
|
||||
fetchSpy.mockRejectedValue(new Error('Network unreachable'));
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frame: MemoryFrame = {
|
||||
id: 1, frame_type: 'I', gop_id: 'test', t: 0, base_frame_id: null,
|
||||
content: 'x', importance: 'normal', access_count: 0,
|
||||
created_at: '2026-03-12T10:00:00.000Z', last_accessed: '2026-03-12T10:00:00.000Z',
|
||||
};
|
||||
|
||||
const result = await sync.pushFrame(frame);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pullFrames', () => {
|
||||
it('fetches frames from team server', async () => {
|
||||
fetchSpy.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ([
|
||||
{
|
||||
id: 'uuid-1',
|
||||
name: 'gop-a',
|
||||
properties: { frameType: 'I', t: 0, content: 'First', importance: 'important', authorId: 'u1', authorName: 'Marko' },
|
||||
createdAt: '2026-03-12T10:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'uuid-2',
|
||||
name: 'gop-b',
|
||||
properties: { frameType: 'P', t: 1, content: 'Second', importance: 'normal', authorId: 'u2', authorName: 'Ana' },
|
||||
createdAt: '2026-03-12T11:00:00.000Z',
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frames = await sync.pullFrames();
|
||||
|
||||
expect(frames).toHaveLength(2);
|
||||
expect(frames[0].gopId).toBe('gop-a');
|
||||
expect(frames[0].authorName).toBe('Marko');
|
||||
expect(frames[1].gopId).toBe('gop-b');
|
||||
expect(frames[1].authorName).toBe('Ana');
|
||||
expect(globalFetchSpy).not.toHaveBeenCalled();
|
||||
|
||||
const [url, opts] = fetchSpy.mock.calls[0];
|
||||
expect(url).toContain('/api/teams/test-team/entities?type=memory_frame');
|
||||
expect(opts.headers['Authorization']).toBe('Bearer test-jwt-token');
|
||||
});
|
||||
|
||||
it('filters by since timestamp when provided', async () => {
|
||||
fetchSpy.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ([
|
||||
{
|
||||
id: 'uuid-1', name: 'gop-a',
|
||||
properties: { frameType: 'I', t: 0, content: 'Old', authorId: 'u1', authorName: 'M' },
|
||||
createdAt: '2026-03-11T10:00:00.000Z',
|
||||
},
|
||||
{
|
||||
id: 'uuid-2', name: 'gop-b',
|
||||
properties: { frameType: 'I', t: 0, content: 'New', authorId: 'u2', authorName: 'A' },
|
||||
createdAt: '2026-03-12T15:00:00.000Z',
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frames = await sync.pullFrames('2026-03-12T00:00:00.000Z');
|
||||
|
||||
// Only the frame after the since timestamp
|
||||
expect(frames).toHaveLength(1);
|
||||
expect(frames[0].content).toBe('New');
|
||||
});
|
||||
|
||||
it('returns empty array on server error', async () => {
|
||||
fetchSpy.mockResolvedValue({ ok: false, status: 500, statusText: 'Error' });
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frames = await sync.pullFrames();
|
||||
expect(frames).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns empty array on network error', async () => {
|
||||
fetchSpy.mockRejectedValue(new Error('Offline'));
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
const frames = await sync.pullFrames();
|
||||
expect(frames).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sync timestamp tracking', () => {
|
||||
it('starts with null timestamp', () => {
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
expect(sync.getLastSyncTimestamp()).toBeNull();
|
||||
});
|
||||
|
||||
it('updates timestamp after successful pull', async () => {
|
||||
fetchSpy.mockResolvedValue({ ok: true, json: async () => ([]) });
|
||||
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
await sync.pullFrames();
|
||||
|
||||
expect(sync.getLastSyncTimestamp()).toBeTruthy();
|
||||
});
|
||||
|
||||
it('allows manual timestamp setting', () => {
|
||||
const sync = new TeamSync(mockConfig, fetchSpy);
|
||||
sync.setLastSyncTimestamp('2026-03-12T10:00:00.000Z');
|
||||
expect(sync.getLastSyncTimestamp()).toBe('2026-03-12T10:00:00.000Z');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -370,24 +370,18 @@ describe('WorkspaceManager', () => {
|
||||
name: 'Team Project',
|
||||
group: 'Work',
|
||||
teamId: 'team-abc-123',
|
||||
teamServerUrl: 'https://team.waggle.dev',
|
||||
teamRole: 'member',
|
||||
teamUserId: 'user-xyz',
|
||||
});
|
||||
|
||||
expect(ws.teamId).toBe('team-abc-123');
|
||||
expect(ws.teamServerUrl).toBe('https://team.waggle.dev');
|
||||
expect(ws.teamRole).toBe('member');
|
||||
expect(ws.teamUserId).toBe('user-xyz');
|
||||
});
|
||||
|
||||
it('creates solo workspace without team fields', () => {
|
||||
const ws = manager.create({ name: 'Solo', group: 'Personal' });
|
||||
|
||||
expect(ws.teamId).toBeUndefined();
|
||||
expect(ws.teamServerUrl).toBeUndefined();
|
||||
expect(ws.teamRole).toBeUndefined();
|
||||
expect(ws.teamUserId).toBeUndefined();
|
||||
});
|
||||
|
||||
it('isTeamWorkspace returns true for team workspaces', () => {
|
||||
@@ -395,7 +389,6 @@ describe('WorkspaceManager', () => {
|
||||
name: 'Team WS',
|
||||
group: 'Work',
|
||||
teamId: 'team-1',
|
||||
teamServerUrl: 'https://example.com',
|
||||
});
|
||||
expect(manager.isTeamWorkspace('team-ws')).toBe(true);
|
||||
});
|
||||
@@ -411,9 +404,9 @@ describe('WorkspaceManager', () => {
|
||||
|
||||
it('listTeamWorkspaces filters to team-connected only', () => {
|
||||
manager.create({ name: 'Solo A', group: 'Work' });
|
||||
manager.create({ name: 'Team B', group: 'Work', teamId: 'team-1', teamServerUrl: 'https://a.com' });
|
||||
manager.create({ name: 'Team B', group: 'Work', teamId: 'team-1' });
|
||||
manager.create({ name: 'Solo C', group: 'Personal' });
|
||||
manager.create({ name: 'Team D', group: 'Work', teamId: 'team-2', teamServerUrl: 'https://b.com' });
|
||||
manager.create({ name: 'Team D', group: 'Work', teamId: 'team-2' });
|
||||
|
||||
const teamWs = manager.listTeamWorkspaces();
|
||||
expect(teamWs).toHaveLength(2);
|
||||
@@ -425,16 +418,12 @@ describe('WorkspaceManager', () => {
|
||||
name: 'Persist Test',
|
||||
group: 'Work',
|
||||
teamId: 'team-persist',
|
||||
teamServerUrl: 'https://persist.dev',
|
||||
teamRole: 'admin',
|
||||
teamUserId: 'user-persist',
|
||||
});
|
||||
|
||||
const ws = manager.get('persist-test');
|
||||
expect(ws!.teamId).toBe('team-persist');
|
||||
expect(ws!.teamServerUrl).toBe('https://persist.dev');
|
||||
expect(ws!.teamRole).toBe('admin');
|
||||
expect(ws!.teamUserId).toBe('user-persist');
|
||||
});
|
||||
|
||||
it('updates team fields', () => {
|
||||
|
||||
Reference in New Issue
Block a user