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

@@ -6,9 +6,7 @@
"name": "Mosaic Stack Team",
"email": "support@mosaicstack.dev"
},
"skills": [
"gantt"
],
"skills": ["gantt"],
"commands": [
{
"name": "gantt-api",
@@ -17,12 +15,7 @@
}
],
"environment": {
"required": [
"MOSAIC_WORKSPACE_ID",
"MOSAIC_API_TOKEN"
],
"optional": [
"MOSAIC_API_URL"
]
"required": ["MOSAIC_WORKSPACE_ID", "MOSAIC_API_TOKEN"],
"optional": ["MOSAIC_API_URL"]
}
}

View File

@@ -13,13 +13,15 @@ Clawdbot skill for querying and analyzing project timelines, task dependencies,
## Installation
1. **Copy skill to Clawdbot plugins directory:**
```bash
cp -r ~/src/mosaic-stack-worktrees/feature-26-gantt-skill/packages/skills/gantt ~/.claude/plugins/mosaic-plugin-gantt
```
2. **Set up environment variables:**
Add to your `.env` or shell profile:
```bash
export MOSAIC_API_URL="http://localhost:3000"
export MOSAIC_WORKSPACE_ID="your-workspace-uuid"
@@ -83,6 +85,7 @@ The `gantt-api.sh` helper script can be used directly:
### Authentication
All requests require headers:
- `X-Workspace-Id`: Workspace UUID
- `Authorization`: Bearer {token}

View File

@@ -9,6 +9,7 @@ This skill enables querying project timelines, task dependencies, critical path
## Overview
The Mosaic Stack provides project management capabilities with support for:
- Project timelines with start/end dates
- Task dependencies and scheduling
- Task status tracking (NOT_STARTED, IN_PROGRESS, PAUSED, COMPLETED, ARCHIVED)
@@ -20,43 +21,51 @@ The Mosaic Stack provides project management capabilities with support for:
**Base URL**: Configured via `MOSAIC_API_URL` environment variable (default: `http://localhost:3000`)
### Projects
- `GET /projects` - List all projects with pagination
- `GET /projects/:id` - Get project details with tasks
### Tasks
- `GET /tasks` - List all tasks with optional filters
- Query params: `projectId`, `status`, `priority`, `assigneeId`, `page`, `limit`
## Authentication
Requests require authentication headers:
- `X-Workspace-Id`: Workspace UUID (from `MOSAIC_WORKSPACE_ID` env var)
- `Authorization`: Bearer token (from `MOSAIC_API_TOKEN` env var)
## Trigger Phrases & Examples
**Query project timeline:**
- "Show me the timeline for [project name]"
- "What's the status of [project]?"
- "Give me an overview of Project Alpha"
**Check task dependencies:**
- "What blocks task [task name]?"
- "What are the dependencies for [task]?"
- "Show me what's blocking [task]"
**Project status overview:**
- "Project status for [project]"
- "How is [project] doing?"
- "Summary of [project]"
**Identify critical path:**
- "Find the critical path for [project]"
- "What's the critical path?"
- "Show me blockers for [project]"
- "Which tasks can't be delayed in [project]?"
**Find upcoming deadlines:**
- "What tasks are due soon in [project]?"
- "Show me tasks approaching deadline"
- "What's due this week?"
@@ -64,6 +73,7 @@ Requests require authentication headers:
## Data Models
### Project
```typescript
{
id: string;
@@ -79,6 +89,7 @@ Requests require authentication headers:
```
### Task
```typescript
{
id: string;
@@ -122,6 +133,7 @@ Use `gantt-api.sh` for API queries:
## PDA-Friendly Language
When presenting information, use supportive, non-judgmental language:
- **"Target passed"** instead of "OVERDUE" or "LATE"
- **"Approaching target"** for near-deadline tasks
- **"Paused"** not "BLOCKED" or "STUCK"

View File

@@ -1,58 +1,58 @@
/**
* Example: Calculate and display critical path for a project
*
*
* Usage:
* npx tsx examples/critical-path.ts <project-id>
*/
import { createGanttClientFromEnv } from '../index.js';
import { createGanttClientFromEnv } from "../index.js";
async function main(): Promise<void> {
const projectId = process.argv[2];
if (!projectId) {
console.error('Usage: npx tsx examples/critical-path.ts <project-id>');
console.error("Usage: npx tsx examples/critical-path.ts <project-id>");
process.exit(1);
}
const client = createGanttClientFromEnv();
console.log(`Calculating critical path for project ${projectId}...\n`);
const criticalPath = await client.calculateCriticalPath(projectId);
console.log(`Critical Path (${criticalPath.totalDuration} days):`);
console.log('='.repeat(50));
console.log("=".repeat(50));
for (const item of criticalPath.path) {
const statusIcon = item.task.status === 'COMPLETED' ? '✓' :
item.task.status === 'IN_PROGRESS' ? '⊙' : '□';
const statusIcon =
item.task.status === "COMPLETED" ? "✓" : item.task.status === "IN_PROGRESS" ? "⊙" : "□";
console.log(`${statusIcon} ${item.task.title}`);
console.log(` Duration: ${item.duration} days`);
console.log(` Cumulative: ${item.cumulativeDuration} days`);
console.log(` Status: ${item.task.status}`);
if (item.task.metadata.dependencies && item.task.metadata.dependencies.length > 0) {
console.log(` Depends on: ${item.task.metadata.dependencies.length} task(s)`);
}
console.log('');
console.log("");
}
if (criticalPath.nonCriticalTasks.length > 0) {
console.log('\nNon-Critical Tasks (can be delayed):');
console.log('='.repeat(50));
console.log("\nNon-Critical Tasks (can be delayed):");
console.log("=".repeat(50));
for (const item of criticalPath.nonCriticalTasks.sort((a, b) => a.slack - b.slack)) {
console.log(`- ${item.task.title}`);
console.log(` Slack: ${item.slack} days`);
console.log(` Status: ${item.task.status}`);
console.log('');
console.log("");
}
}
}
main().catch(error => {
console.error('Error:', error.message);
main().catch((error) => {
console.error("Error:", error.message);
process.exit(1);
});

View File

@@ -1,69 +1,73 @@
/**
* Example: Query project timeline and display statistics
*
*
* Usage:
* npx tsx examples/query-timeline.ts <project-id>
*/
import { createGanttClientFromEnv } from '../index.js';
import { createGanttClientFromEnv } from "../index.js";
async function main(): Promise<void> {
const projectId = process.argv[2];
if (!projectId) {
console.error('Usage: npx tsx examples/query-timeline.ts <project-id>');
console.error("Usage: npx tsx examples/query-timeline.ts <project-id>");
process.exit(1);
}
const client = createGanttClientFromEnv();
console.log(`Fetching timeline for project ${projectId}...\n`);
const timeline = await client.getProjectTimeline(projectId);
console.log(`Project: ${timeline.project.name}`);
console.log(`Status: ${timeline.project.status}`);
if (timeline.project.startDate && timeline.project.endDate) {
console.log(`Timeline: ${timeline.project.startDate}${timeline.project.endDate}`);
}
console.log(`\nTasks (${timeline.stats.total} total):`);
console.log(` ✓ Completed: ${timeline.stats.completed}`);
console.log(` ⊙ In Progress: ${timeline.stats.inProgress}`);
console.log(` □ Not Started: ${timeline.stats.notStarted}`);
console.log(` ⏸ Paused: ${timeline.stats.paused}`);
console.log(` ⚠ Target passed: ${timeline.stats.targetPassed}`);
console.log('\nTask List:');
console.log("\nTask List:");
const statusIcon = (status: string): string => {
switch (status) {
case 'COMPLETED': return '✓';
case 'IN_PROGRESS': return '⊙';
case 'PAUSED': return '⏸';
case 'ARCHIVED': return '📦';
default: return '□';
case "COMPLETED":
return "✓";
case "IN_PROGRESS":
return "⊙";
case "PAUSED":
return "⏸";
case "ARCHIVED":
return "📦";
default:
return "□";
}
};
const now = new Date();
for (const task of timeline.tasks) {
const icon = statusIcon(task.status);
const dueInfo = task.dueDate
? ` Due: ${task.dueDate}`
: '';
const targetPassed = task.dueDate && new Date(task.dueDate) < now && task.status !== 'COMPLETED'
? ' (target passed)'
: '';
const dueInfo = task.dueDate ? ` Due: ${task.dueDate}` : "";
const targetPassed =
task.dueDate && new Date(task.dueDate) < now && task.status !== "COMPLETED"
? " (target passed)"
: "";
console.log(`${icon} ${task.title} [${task.status}]${dueInfo}${targetPassed}`);
}
}
main().catch(error => {
console.error('Error:', error.message);
main().catch((error) => {
console.error("Error:", error.message);
process.exit(1);
});

View File

@@ -1,9 +1,9 @@
/**
* Mosaic Stack Gantt API Client
*
*
* Provides typed client for querying project timelines, tasks, and dependencies
* from Mosaic Stack's API.
*
*
* @example
* ```typescript
* const client = new GanttClient({
@@ -11,7 +11,7 @@
* workspaceId: process.env.MOSAIC_WORKSPACE_ID,
* apiToken: process.env.MOSAIC_API_TOKEN,
* });
*
*
* const projects = await client.listProjects();
* const timeline = await client.getProjectTimeline('project-id');
* const criticalPath = await client.calculateCriticalPath('project-id');
@@ -24,9 +24,9 @@ export interface GanttClientConfig {
apiToken: string;
}
export type ProjectStatus = 'PLANNING' | 'ACTIVE' | 'ON_HOLD' | 'COMPLETED' | 'ARCHIVED';
export type TaskStatus = 'NOT_STARTED' | 'IN_PROGRESS' | 'PAUSED' | 'COMPLETED' | 'ARCHIVED';
export type TaskPriority = 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
export type ProjectStatus = "PLANNING" | "ACTIVE" | "ON_HOLD" | "COMPLETED" | "ARCHIVED";
export type TaskStatus = "NOT_STARTED" | "IN_PROGRESS" | "PAUSED" | "COMPLETED" | "ARCHIVED";
export type TaskPriority = "LOW" | "MEDIUM" | "HIGH" | "URGENT";
export interface ProjectMetadata {
[key: string]: unknown;
@@ -133,15 +133,12 @@ export class GanttClient {
/**
* Make an authenticated API request
*/
private async request<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const url = `${this.config.apiUrl}${endpoint}`;
const headers = {
'Content-Type': 'application/json',
'X-Workspace-Id': this.config.workspaceId,
'Authorization': `Bearer ${this.config.apiToken}`,
"Content-Type": "application/json",
"X-Workspace-Id": this.config.workspaceId,
Authorization: `Bearer ${this.config.apiToken}`,
...options.headers,
};
@@ -167,12 +164,12 @@ export class GanttClient {
status?: ProjectStatus;
}): Promise<PaginatedResponse<Project>> {
const queryParams = new URLSearchParams();
if (params?.page) queryParams.set('page', params.page.toString());
if (params?.limit) queryParams.set('limit', params.limit.toString());
if (params?.status) queryParams.set('status', params.status);
if (params?.page) queryParams.set("page", params.page.toString());
if (params?.limit) queryParams.set("limit", params.limit.toString());
if (params?.status) queryParams.set("status", params.status);
const query = queryParams.toString();
const endpoint = `/projects${query ? `?${query}` : ''}`;
const endpoint = `/projects${query ? `?${query}` : ""}`;
return this.request<PaginatedResponse<Project>>(endpoint);
}
@@ -196,15 +193,15 @@ export class GanttClient {
limit?: number;
}): Promise<PaginatedResponse<Task>> {
const queryParams = new URLSearchParams();
if (params?.projectId) queryParams.set('projectId', params.projectId);
if (params?.status) queryParams.set('status', params.status);
if (params?.priority) queryParams.set('priority', params.priority);
if (params?.assigneeId) queryParams.set('assigneeId', params.assigneeId);
if (params?.page) queryParams.set('page', params.page.toString());
if (params?.limit) queryParams.set('limit', params.limit.toString());
if (params?.projectId) queryParams.set("projectId", params.projectId);
if (params?.status) queryParams.set("status", params.status);
if (params?.priority) queryParams.set("priority", params.priority);
if (params?.assigneeId) queryParams.set("assigneeId", params.assigneeId);
if (params?.page) queryParams.set("page", params.page.toString());
if (params?.limit) queryParams.set("limit", params.limit.toString());
const query = queryParams.toString();
const endpoint = `/tasks${query ? `?${query}` : ''}`;
const endpoint = `/tasks${query ? `?${query}` : ""}`;
return this.request<PaginatedResponse<Task>>(endpoint);
}
@@ -227,12 +224,12 @@ export class GanttClient {
const now = new Date();
const stats = {
total: tasks.length,
completed: tasks.filter(t => t.status === 'COMPLETED').length,
inProgress: tasks.filter(t => t.status === 'IN_PROGRESS').length,
notStarted: tasks.filter(t => t.status === 'NOT_STARTED').length,
paused: tasks.filter(t => t.status === 'PAUSED').length,
targetPassed: tasks.filter(t => {
if (!t.dueDate || t.status === 'COMPLETED') return false;
completed: tasks.filter((t) => t.status === "COMPLETED").length,
inProgress: tasks.filter((t) => t.status === "IN_PROGRESS").length,
notStarted: tasks.filter((t) => t.status === "NOT_STARTED").length,
paused: tasks.filter((t) => t.status === "PAUSED").length,
targetPassed: tasks.filter((t) => {
if (!t.dueDate || t.status === "COMPLETED") return false;
return new Date(t.dueDate) < now;
}).length,
};
@@ -248,25 +245,21 @@ export class GanttClient {
const dependencyIds = task.metadata.dependencies ?? [];
// Fetch tasks this task depends on (blocking tasks)
const blockedBy = await Promise.all(
dependencyIds.map(id => this.getTask(id))
);
const blockedBy = await Promise.all(dependencyIds.map((id) => this.getTask(id)));
// Find tasks that depend on this task
const allTasksResponse = await this.getTasks({
projectId: task.projectId ?? undefined,
limit: 1000,
});
const blocks = allTasksResponse.data.filter(t =>
t.metadata.dependencies?.includes(taskId)
);
const blocks = allTasksResponse.data.filter((t) => t.metadata.dependencies?.includes(taskId));
return { task, blockedBy, blocks };
}
/**
* Calculate critical path for a project
*
*
* Uses the Critical Path Method (CPM) to find the longest dependency chain
*/
async calculateCriticalPath(projectId: string): Promise<CriticalPath> {
@@ -274,7 +267,7 @@ export class GanttClient {
const tasks = tasksResponse.data;
// Build dependency graph
const taskMap = new Map(tasks.map(t => [t.id, t]));
const taskMap = new Map(tasks.map((t) => [t.id, t]));
const durations = new Map<string, number>();
const earliestStart = new Map<string, number>();
const latestStart = new Map<string, number>();
@@ -285,7 +278,10 @@ export class GanttClient {
? new Date(task.metadata.startDate)
: new Date(task.createdAt);
const end = task.dueDate ? new Date(task.dueDate) : new Date();
const duration = Math.max(1, Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)));
const duration = Math.max(
1,
Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))
);
durations.set(task.id, duration);
}
@@ -332,9 +328,7 @@ export class GanttClient {
if (!task) return projectDuration;
// Find all tasks that depend on this task
const dependents = tasks.filter(t =>
t.metadata.dependencies?.includes(taskId)
);
const dependents = tasks.filter((t) => t.metadata.dependencies?.includes(taskId));
if (dependents.length === 0) {
// No dependents, latest start = project end - duration
@@ -383,7 +377,7 @@ export class GanttClient {
// Build critical path chain
const path = criticalTasks
.sort((a, b) => (earliestStart.get(a.id) ?? 0) - (earliestStart.get(b.id) ?? 0))
.map(task => ({
.map((task) => ({
task,
duration: durations.get(task.id) ?? 1,
cumulativeDuration: (earliestStart.get(task.id) ?? 0) + (durations.get(task.id) ?? 1),
@@ -399,16 +393,13 @@ export class GanttClient {
/**
* Find tasks approaching their due date (within specified days)
*/
async getTasksApproachingDueDate(
projectId: string,
daysThreshold: number = 7
): Promise<Task[]> {
async getTasksApproachingDueDate(projectId: string, daysThreshold: number = 7): Promise<Task[]> {
const tasksResponse = await this.getTasks({ projectId, limit: 1000 });
const now = new Date();
const threshold = new Date(now.getTime() + daysThreshold * 24 * 60 * 60 * 1000);
return tasksResponse.data.filter(task => {
if (!task.dueDate || task.status === 'COMPLETED') return false;
return tasksResponse.data.filter((task) => {
if (!task.dueDate || task.status === "COMPLETED") return false;
const dueDate = new Date(task.dueDate);
return dueDate >= now && dueDate <= threshold;
});
@@ -425,7 +416,7 @@ export function createGanttClientFromEnv(): GanttClient {
if (!apiUrl || !workspaceId || !apiToken) {
throw new Error(
'Missing required environment variables: MOSAIC_API_URL, MOSAIC_WORKSPACE_ID, MOSAIC_API_TOKEN'
"Missing required environment variables: MOSAIC_API_URL, MOSAIC_WORKSPACE_ID, MOSAIC_API_TOKEN"
);
}

View File

@@ -17,4 +17,4 @@ export {
type ProjectTimeline,
type DependencyChain,
type CriticalPath,
} from './gantt-client.js';
} from "./gantt-client.js";