feat(#71): implement graph data API
Implemented three new API endpoints for knowledge graph visualization: 1. GET /api/knowledge/graph - Full knowledge graph - Returns all entries and links with optional filtering - Supports filtering by tags, status, and node count limit - Includes orphan detection (entries with no links) 2. GET /api/knowledge/graph/stats - Graph statistics - Total entries and links counts - Orphan entries detection - Average links per entry - Top 10 most connected entries - Tag distribution across entries 3. GET /api/knowledge/graph/:slug - Entry-centered subgraph - Returns graph centered on specific entry - Supports depth parameter (1-5) for traversal distance - Includes all connected nodes up to specified depth New Files: - apps/api/src/knowledge/graph.controller.ts - apps/api/src/knowledge/graph.controller.spec.ts Modified Files: - apps/api/src/knowledge/dto/graph-query.dto.ts (added GraphFilterDto) - apps/api/src/knowledge/entities/graph.entity.ts (extended with new types) - apps/api/src/knowledge/services/graph.service.ts (added new methods) - apps/api/src/knowledge/services/graph.service.spec.ts (added tests) - apps/api/src/knowledge/knowledge.module.ts (registered controller) - apps/api/src/knowledge/dto/index.ts (exported new DTOs) - docs/scratchpads/71-graph-data-api.md (implementation notes) Test Coverage: 21 tests (all passing) - 14 service tests including orphan detection, filtering, statistics - 7 controller tests for all three endpoints Follows TDD principles with tests written before implementation. All code quality gates passed (lint, typecheck, tests). Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
232
apps/orchestrator/src/spawner/agent-lifecycle.service.ts
Normal file
232
apps/orchestrator/src/spawner/agent-lifecycle.service.ts
Normal file
@@ -0,0 +1,232 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ValkeyService } from '../valkey/valkey.service';
|
||||
import type { AgentState, AgentStatus, AgentEvent } from '../valkey/types';
|
||||
import { isValidAgentTransition } from '../valkey/types/state.types';
|
||||
|
||||
/**
|
||||
* Service responsible for managing agent lifecycle state transitions
|
||||
*
|
||||
* Manages state transitions through the agent lifecycle:
|
||||
* spawning → running → completed/failed/killed
|
||||
*
|
||||
* - Enforces valid state transitions using state machine
|
||||
* - Persists agent state changes to Valkey
|
||||
* - Emits pub/sub events on state changes
|
||||
* - Tracks agent metadata (startedAt, completedAt, error)
|
||||
*/
|
||||
@Injectable()
|
||||
export class AgentLifecycleService {
|
||||
private readonly logger = new Logger(AgentLifecycleService.name);
|
||||
|
||||
constructor(private readonly valkeyService: ValkeyService) {
|
||||
this.logger.log('AgentLifecycleService initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition agent from spawning to running state
|
||||
* @param agentId Unique agent identifier
|
||||
* @returns Updated agent state
|
||||
* @throws Error if agent not found or invalid transition
|
||||
*/
|
||||
async transitionToRunning(agentId: string): Promise<AgentState> {
|
||||
this.logger.log(`Transitioning agent ${agentId} to running`);
|
||||
|
||||
const currentState = await this.getAgentState(agentId);
|
||||
this.validateTransition(currentState.status, 'running');
|
||||
|
||||
// Set startedAt timestamp if not already set
|
||||
const startedAt = currentState.startedAt || new Date().toISOString();
|
||||
|
||||
// Update state in Valkey
|
||||
const updatedState = await this.valkeyService.updateAgentStatus(
|
||||
agentId,
|
||||
'running',
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Ensure startedAt is set
|
||||
if (!updatedState.startedAt) {
|
||||
updatedState.startedAt = startedAt;
|
||||
await this.valkeyService.setAgentState(updatedState);
|
||||
}
|
||||
|
||||
// Emit event
|
||||
await this.publishStateChangeEvent('agent.running', updatedState);
|
||||
|
||||
this.logger.log(`Agent ${agentId} transitioned to running`);
|
||||
return updatedState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition agent to completed state
|
||||
* @param agentId Unique agent identifier
|
||||
* @returns Updated agent state
|
||||
* @throws Error if agent not found or invalid transition
|
||||
*/
|
||||
async transitionToCompleted(agentId: string): Promise<AgentState> {
|
||||
this.logger.log(`Transitioning agent ${agentId} to completed`);
|
||||
|
||||
const currentState = await this.getAgentState(agentId);
|
||||
this.validateTransition(currentState.status, 'completed');
|
||||
|
||||
// Set completedAt timestamp
|
||||
const completedAt = new Date().toISOString();
|
||||
|
||||
// Update state in Valkey
|
||||
const updatedState = await this.valkeyService.updateAgentStatus(
|
||||
agentId,
|
||||
'completed',
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Ensure completedAt is set
|
||||
if (!updatedState.completedAt) {
|
||||
updatedState.completedAt = completedAt;
|
||||
await this.valkeyService.setAgentState(updatedState);
|
||||
}
|
||||
|
||||
// Emit event
|
||||
await this.publishStateChangeEvent('agent.completed', updatedState);
|
||||
|
||||
this.logger.log(`Agent ${agentId} transitioned to completed`);
|
||||
return updatedState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition agent to failed state with error
|
||||
* @param agentId Unique agent identifier
|
||||
* @param error Error message
|
||||
* @returns Updated agent state
|
||||
* @throws Error if agent not found or invalid transition
|
||||
*/
|
||||
async transitionToFailed(agentId: string, error: string): Promise<AgentState> {
|
||||
this.logger.log(`Transitioning agent ${agentId} to failed: ${error}`);
|
||||
|
||||
const currentState = await this.getAgentState(agentId);
|
||||
this.validateTransition(currentState.status, 'failed');
|
||||
|
||||
// Set completedAt timestamp
|
||||
const completedAt = new Date().toISOString();
|
||||
|
||||
// Update state in Valkey
|
||||
const updatedState = await this.valkeyService.updateAgentStatus(
|
||||
agentId,
|
||||
'failed',
|
||||
error,
|
||||
);
|
||||
|
||||
// Ensure completedAt is set
|
||||
if (!updatedState.completedAt) {
|
||||
updatedState.completedAt = completedAt;
|
||||
await this.valkeyService.setAgentState(updatedState);
|
||||
}
|
||||
|
||||
// Emit event
|
||||
await this.publishStateChangeEvent('agent.failed', updatedState, error);
|
||||
|
||||
this.logger.error(`Agent ${agentId} transitioned to failed: ${error}`);
|
||||
return updatedState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transition agent to killed state
|
||||
* @param agentId Unique agent identifier
|
||||
* @returns Updated agent state
|
||||
* @throws Error if agent not found or invalid transition
|
||||
*/
|
||||
async transitionToKilled(agentId: string): Promise<AgentState> {
|
||||
this.logger.log(`Transitioning agent ${agentId} to killed`);
|
||||
|
||||
const currentState = await this.getAgentState(agentId);
|
||||
this.validateTransition(currentState.status, 'killed');
|
||||
|
||||
// Set completedAt timestamp
|
||||
const completedAt = new Date().toISOString();
|
||||
|
||||
// Update state in Valkey
|
||||
const updatedState = await this.valkeyService.updateAgentStatus(
|
||||
agentId,
|
||||
'killed',
|
||||
undefined,
|
||||
);
|
||||
|
||||
// Ensure completedAt is set
|
||||
if (!updatedState.completedAt) {
|
||||
updatedState.completedAt = completedAt;
|
||||
await this.valkeyService.setAgentState(updatedState);
|
||||
}
|
||||
|
||||
// Emit event
|
||||
await this.publishStateChangeEvent('agent.killed', updatedState);
|
||||
|
||||
this.logger.warn(`Agent ${agentId} transitioned to killed`);
|
||||
return updatedState;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current agent lifecycle state
|
||||
* @param agentId Unique agent identifier
|
||||
* @returns Agent state or null if not found
|
||||
*/
|
||||
async getAgentLifecycleState(agentId: string): Promise<AgentState | null> {
|
||||
return this.valkeyService.getAgentState(agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* List all agent lifecycle states
|
||||
* @returns Array of all agent states
|
||||
*/
|
||||
async listAgentLifecycleStates(): Promise<AgentState[]> {
|
||||
return this.valkeyService.listAgents();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent state and throw if not found
|
||||
* @param agentId Unique agent identifier
|
||||
* @returns Agent state
|
||||
* @throws Error if agent not found
|
||||
*/
|
||||
private async getAgentState(agentId: string): Promise<AgentState> {
|
||||
const state = await this.valkeyService.getAgentState(agentId);
|
||||
|
||||
if (!state) {
|
||||
throw new Error(`Agent ${agentId} not found`);
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate state transition is allowed
|
||||
* @param from Current state
|
||||
* @param to Target state
|
||||
* @throws Error if transition is invalid
|
||||
*/
|
||||
private validateTransition(from: AgentStatus, to: AgentStatus): void {
|
||||
if (!isValidAgentTransition(from, to)) {
|
||||
throw new Error(`Invalid state transition from ${from} to ${to}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish state change event
|
||||
* @param eventType Type of event
|
||||
* @param state Updated agent state
|
||||
* @param error Optional error message
|
||||
*/
|
||||
private async publishStateChangeEvent(
|
||||
eventType: 'agent.running' | 'agent.completed' | 'agent.failed' | 'agent.killed',
|
||||
state: AgentState,
|
||||
error?: string,
|
||||
): Promise<void> {
|
||||
const event: AgentEvent = {
|
||||
type: eventType,
|
||||
agentId: state.agentId,
|
||||
taskId: state.taskId,
|
||||
timestamp: new Date().toISOString(),
|
||||
error,
|
||||
};
|
||||
|
||||
await this.valkeyService.publishEvent(event);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user