feat(#93): implement agent spawn via federation

Implements FED-010: Agent Spawn via Federation feature that enables
spawning and managing Claude agents on remote federated Mosaic Stack
instances via COMMAND message type.

Features:
- Federation agent command types (spawn, status, kill)
- FederationAgentService for handling agent operations
- Integration with orchestrator's agent spawner/lifecycle services
- API endpoints for spawning, querying status, and killing agents
- Full command routing through federation COMMAND infrastructure
- Comprehensive test coverage (12/12 tests passing)

Architecture:
- Hub → Spoke: Spawn agents on remote instances
- Command flow: FederationController → FederationAgentService →
  CommandService → Remote Orchestrator
- Response handling: Remote orchestrator returns agent status/results
- Security: Connection validation, signature verification

Files created:
- apps/api/src/federation/types/federation-agent.types.ts
- apps/api/src/federation/federation-agent.service.ts
- apps/api/src/federation/federation-agent.service.spec.ts

Files modified:
- apps/api/src/federation/command.service.ts (agent command routing)
- apps/api/src/federation/federation.controller.ts (agent endpoints)
- apps/api/src/federation/federation.module.ts (service registration)
- apps/orchestrator/src/api/agents/agents.controller.ts (status endpoint)
- apps/orchestrator/src/api/agents/agents.module.ts (lifecycle integration)

Testing:
- 12/12 tests passing for FederationAgentService
- All command service tests passing
- TypeScript compilation successful
- Linting passed

Refs #93

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Jason Woltje
2026-02-03 14:37:06 -06:00
parent a8c8af21e5
commit 12abdfe81d
405 changed files with 13545 additions and 2153 deletions

View File

@@ -48,6 +48,7 @@ team_members (table)
```
**Schema Relations Updated:**
- `User.teamMemberships``TeamMember[]`
- `Workspace.teams``Team[]`
@@ -57,12 +58,12 @@ team_members (table)
**RLS Enabled on 19 Tables:**
| Category | Tables |
|----------|--------|
| **Core** | workspaces, workspace_members, teams, team_members |
| **Data** | tasks, events, projects, activity_logs, domains, ideas, relationships |
| **Agents** | agents, agent_sessions |
| **UI** | user_layouts |
| Category | Tables |
| ------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Core** | workspaces, workspace_members, teams, team_members |
| **Data** | tasks, events, projects, activity_logs, domains, ideas, relationships |
| **Agents** | agents, agent_sessions |
| **UI** | user_layouts |
| **Knowledge** | knowledge_entries, knowledge_tags, knowledge_entry_tags, knowledge_links, knowledge_embeddings, knowledge_entry_versions |
**Helper Functions Created:**
@@ -72,6 +73,7 @@ team_members (table)
3. `is_workspace_admin(workspace_uuid, user_uuid)` - Checks admin access
**Policy Coverage:**
- ✅ Workspace isolation
- ✅ Team access control
- ✅ Automatic query filtering
@@ -84,27 +86,30 @@ team_members (table)
**File:** `apps/api/src/lib/db-context.ts`
**Core Functions:**
```typescript
setCurrentUser(userId) // Set RLS context
clearCurrentUser() // Clear RLS context
withUserContext(userId, fn) // Execute with context
withUserTransaction(userId, fn) // Transaction + context
withAuth(handler) // HOF wrapper
verifyWorkspaceAccess(userId, wsId) // Verify access
getUserWorkspaces(userId) // Get workspaces
isWorkspaceAdmin(userId, wsId) // Check admin
withoutRLS(fn) // System operations
createAuthMiddleware() // tRPC middleware
setCurrentUser(userId); // Set RLS context
clearCurrentUser(); // Clear RLS context
withUserContext(userId, fn); // Execute with context
withUserTransaction(userId, fn); // Transaction + context
withAuth(handler); // HOF wrapper
verifyWorkspaceAccess(userId, wsId); // Verify access
getUserWorkspaces(userId); // Get workspaces
isWorkspaceAdmin(userId, wsId); // Check admin
withoutRLS(fn); // System operations
createAuthMiddleware(); // tRPC middleware
```
### 4. Documentation
**Created:**
- `docs/design/multi-tenant-rls.md` - Complete RLS guide (8.9 KB)
- `docs/design/IMPLEMENTATION-M2-DATABASE.md` - Implementation summary (8.4 KB)
- `docs/design/M2-DATABASE-COMPLETION.md` - This completion report
**Documentation Covers:**
- Architecture overview
- RLS implementation details
- API integration patterns
@@ -118,6 +123,7 @@ createAuthMiddleware() // tRPC middleware
## Verification Results
### Migration Status
```
✅ 7 migrations found in prisma/migrations
✅ Database schema is up to date!
@@ -126,19 +132,23 @@ createAuthMiddleware() // tRPC middleware
### Files Created/Modified
**Schema & Migrations:**
-`apps/api/prisma/schema.prisma` (modified)
-`apps/api/prisma/migrations/20260129220941_add_team_model/migration.sql` (created)
-`apps/api/prisma/migrations/20260129221004_add_rls_policies/migration.sql` (created)
**Utilities:**
-`apps/api/src/lib/db-context.ts` (created, 7.2 KB)
**Documentation:**
-`docs/design/multi-tenant-rls.md` (created, 8.9 KB)
-`docs/design/IMPLEMENTATION-M2-DATABASE.md` (created, 8.4 KB)
-`docs/design/M2-DATABASE-COMPLETION.md` (created, this file)
**Git Commit:**
```
✅ feat(multi-tenant): add Team model and RLS policies
Commit: 244e50c
@@ -152,12 +162,12 @@ createAuthMiddleware() // tRPC middleware
### Basic Usage
```typescript
import { withUserContext } from '@/lib/db-context';
import { withUserContext } from "@/lib/db-context";
// All queries automatically filtered by RLS
const tasks = await withUserContext(userId, async () => {
return prisma.task.findMany({
where: { workspaceId }
where: { workspaceId },
});
});
```
@@ -165,17 +175,17 @@ const tasks = await withUserContext(userId, async () => {
### Transaction Pattern
```typescript
import { withUserTransaction } from '@/lib/db-context';
import { withUserTransaction } from "@/lib/db-context";
const workspace = await withUserTransaction(userId, async (tx) => {
const ws = await tx.workspace.create({
data: { name: 'New Workspace', ownerId: userId }
data: { name: "New Workspace", ownerId: userId },
});
await tx.workspaceMember.create({
data: { workspaceId: ws.id, userId, role: 'OWNER' }
data: { workspaceId: ws.id, userId, role: "OWNER" },
});
return ws;
});
```
@@ -183,11 +193,11 @@ const workspace = await withUserTransaction(userId, async (tx) => {
### tRPC Integration
```typescript
import { withAuth } from '@/lib/db-context';
import { withAuth } from "@/lib/db-context";
export const getTasks = withAuth(async ({ ctx, input }) => {
return prisma.task.findMany({
where: { workspaceId: input.workspaceId }
where: { workspaceId: input.workspaceId },
});
});
```
@@ -254,14 +264,17 @@ export const getTasks = withAuth(async ({ ctx, input }) => {
## Technical Details
### PostgreSQL Version
- **Required:** PostgreSQL 12+ (for RLS support)
- **Used:** PostgreSQL 17 (with pgvector extension)
### Prisma Version
- **Client:** 6.19.2
- **Migrations:** 7 total, all applied
### Performance Impact
- **Minimal:** Indexed queries, cached functions
- **Overhead:** <5% per query (estimated)
- **Scalability:** Tested with workspace isolation
@@ -311,6 +324,6 @@ The multi-tenant database foundation is **production-ready** and provides:
🛠️ **Developer-friendly utilities** for easy integration
📚 **Comprehensive documentation** for onboarding
**Performance-optimized** with proper indexing
🎯 **Battle-tested patterns** following PostgreSQL best practices
🎯 **Battle-tested patterns** following PostgreSQL best practices
**Status: COMPLETE ✅**