Phase 2: Distributed AI Runtime & Secure Control Mesh
このコンテンツはまだ日本語訳がありません。
Phase 2: Distributed AI Runtime & Secure Control Mesh
Section titled “Phase 2: Distributed AI Runtime & Secure Control Mesh”CoderClaw Phase 2 introduces a networked, distributed AI node architecture with secure remote orchestration capabilities while maintaining deterministic execution and security boundaries.
Foundation: CoderClaw is built on CoderClaw’s proven multi-channel gateway architecture. Phase 2 adds enterprise-ready features for distributed execution, security, and team collaboration.
Overview
Section titled “Overview”Phase 2 transforms CoderClaw from a local-only development runtime into a distributed system that can:
- Execute tasks locally or remotely
- Manage distributed task lifecycles
- Enforce security policies across sessions
- Support team-wide collaboration
- Integrate with CI/CD systems
Architecture
Section titled “Architecture”Key Components
Section titled “Key Components”┌─────────────────────────────────────────────┐│ Runtime Interface Contract ││ (Submit, Stream, Query, Cancel, List) │└─────────────────┬───────────────────────────┘ │ ┌─────────────┴──────────────┐ │ Transport Adapter │ │ (Protocol Agnostic) │ └─────────────┬───────────────┘ │ ┌─────────────┴──────────────┐ │ Distributed Task Engine │ │ (State Machine + Audit) │ └─────────────┬───────────────┘ │ ┌─────────────┴──────────────┐ │ Security Service (RBAC) │ │ (Identity + Policy) │ └─────────────────────────────┘1. Transport Abstraction Layer
Section titled “1. Transport Abstraction Layer”The transport layer provides a protocol-agnostic interface for task execution:
Runtime Interface Contract
Section titled “Runtime Interface Contract”interface RuntimeInterface { // Task management submitTask(request: TaskSubmitRequest): Promise<TaskState>; getTaskState(taskId: string): Promise<TaskState | null>; streamTaskUpdates(taskId: string): AsyncIterableIterator<TaskUpdateEvent>; cancelTask(taskId: string): Promise<boolean>;
// Resource discovery listAgents(): Promise<AgentInfo[]>; listSkills(): Promise<SkillInfo[]>;
// Health getStatus(): Promise<RuntimeStatus>;}Transport Adapters
Section titled “Transport Adapters”Transport adapters implement the communication layer without assumptions about protocol:
- LocalTransportAdapter: In-process execution (reference implementation)
- HTTPTransportAdapter: REST API-based (future)
- WebSocketTransportAdapter: Real-time streaming (future)
- gRPCTransportAdapter: High-performance RPC (future)
Example usage:
import { CoderClawRuntime, LocalTransportAdapter } from "coderclaw/transport";
// Create runtime with local adapterconst adapter = new LocalTransportAdapter(context);const runtime = new CoderClawRuntime(adapter, "local-only");
// Submit a taskconst task = await runtime.submitTask({ description: "Implement feature X", input: "Add authentication to the API", agentId: "code-creator",});
// Stream updatesfor await (const update of runtime.streamTaskUpdates(task.id)) { console.log(`Status: ${update.status}, Progress: ${update.progress}`);}2. Distributed Task Lifecycle
Section titled “2. Distributed Task Lifecycle”Task State Machine
Section titled “Task State Machine”Tasks follow a well-defined state machine:
PENDING → PLANNING → RUNNING → COMPLETED ↓ ↓ ↑ ↓ WAITING ───────┘ ↓ ↓ └─→ CANCELLED ↓ FAILEDState Transitions:
PENDING → PLANNING: Task analysis beginsPLANNING → RUNNING: Execution startsRUNNING → WAITING: Waiting for external inputWAITING → RUNNING: Resuming after waitRUNNING → COMPLETED: Successful completionAny → FAILED: Error occurredAny (non-terminal) → CANCELLED: User cancellation
Task Features
Section titled “Task Features”Globally Unique IDs: Each task gets a UUID for distributed tracking
Persistence: Tasks are stored and can survive restarts
Resumability: Tasks can be paused and resumed
Audit Trail: Complete event history for each task
// Get task stateconst task = await taskEngine.getTask(taskId);console.log(`Status: ${task.status}`);
// Get event historyconst events = await taskEngine.getTaskEvents(taskId);events.forEach((event) => { console.log(`${event.timestamp}: ${event.event} - ${event.message}`);});3. Identity & Security Model
Section titled “3. Identity & Security Model”Components
Section titled “Components”Identity Providers:
- OIDC
- GitHub SSO
- Google OAuth
- Local authentication
Device Trust Levels:
trusted: Fully trusted deviceverified: Identity verifieduntrusted: Unknown or untrusted
Permissions (RBAC):
task:submit- Submit new taskstask:read- View task statustask:cancel- Cancel tasksagent:invoke- Invoke agentsskill:execute- Execute skillsconfig:read- Read configurationconfig:write- Modify configurationadmin:all- Full system access
Built-in Roles
Section titled “Built-in Roles”const BUILTIN_ROLES = { admin: { permissions: ["admin:all"], }, developer: { permissions: ["task:submit", "task:read", "task:cancel", "agent:invoke", "skill:execute"], }, readonly: { permissions: ["task:read", "config:read"], }, ci: { permissions: ["task:submit", "task:read", "agent:invoke"], },};Policy Enforcement
Section titled “Policy Enforcement”Session-level permissions:
const session = await securityService.createSession(userId, deviceId, ["developer"]);Repo-level policy (.coderClaw/security.yaml):
enforceTrust: trueminimumTrustLevel: verifiedallowedRoles: - developer - admin
agentPolicies: - agentId: code-modifier allowedRoles: [developer, admin] requireDeviceTrust: verified
skillPolicies: - skillId: shell-exec dangerous: true requiredPermissions: [skill:execute] allowedRoles: [developer]Security Checks
Section titled “Security Checks”// Check permissionconst result = await securityService.checkPermission(context, "task:submit");
if (!result.allowed) { throw new Error(result.reason);}
// Check agent accessconst agentAccess = await securityService.checkAgentAccess(context, "code-modifier");
// Check skill accessconst skillAccess = await securityService.checkSkillAccess(context, "shell-exec");Audit Logging
Section titled “Audit Logging”All actions are audited:
await securityService.audit({ action: "task.submit", userId: user.id, sessionId: session.sessionId, resourceType: "task", resourceId: task.id, result: "allowed",});
// Query audit logsconst logs = await securityService.getAuditLog({ userId: "user-123", action: "task.submit", startDate: new Date("2024-01-01"),});4. Remote Orchestration
Section titled “4. Remote Orchestration”Multi-Session Isolation
Section titled “Multi-Session Isolation”Each remote session is isolated:
- Separate task queues
- Independent memory scope
- Per-session permissions
- Session-specific audit trail
Secure Streaming
Section titled “Secure Streaming”Task updates stream securely:
// Client subscribes to task updatesfor await (const update of runtime.streamTaskUpdates(taskId)) { // Real-time status updates handleUpdate(update);}Remote Command Execution
Section titled “Remote Command Execution”// Remote task submissionconst task = await runtime.submitTask({ description: "Run tests", input: "npm test", sessionId: remoteSessionId, metadata: { source: "ci-pipeline", trigger: "pull-request", },});5. Deployment Modes
Section titled “5. Deployment Modes”Local-Only Mode
Section titled “Local-Only Mode”Default single-machine setup (backward compatible with CoderClaw):
const runtime = new CoderClawRuntime(new LocalTransportAdapter(context), "local-only");Remote-Enabled Mode
Section titled “Remote-Enabled Mode”Accepts remote connections with authentication:
const runtime = new CoderClawRuntime(new HTTPTransportAdapter(config), "remote-enabled");Distributed Cluster Mode
Section titled “Distributed Cluster Mode”Full distributed deployment (future):
const runtime = new CoderClawRuntime(new ClusterTransportAdapter(config), "distributed-cluster");6. Team & Enterprise Features
Section titled “6. Team & Enterprise Features”Shared Agent Registries
Section titled “Shared Agent Registries”Teams can share custom agents:
agents: - id: team-reviewer name: Team Code Reviewer description: Enforces team standards capabilities: [review, lint, format]Centralized Skill Distribution
Section titled “Centralized Skill Distribution”Skills can be distributed team-wide:
# Install team skillcoderclaw skill install team/security-scanner --registry team-registryTeam-Wide Policy Enforcement
Section titled “Team-Wide Policy Enforcement”organizationPolicy: enforceTrust: true minimumTrustLevel: verified requiredSkills: [security-scanner] deniedSkills: [dangerous-exec]CI Integration
Section titled “CI Integration”- name: Run AI Code Review uses: coderclaw/action@v2 with: task: "Review pull request" agent: "code-reviewer" mode: "remote-enabled"7. Configuration
Section titled “7. Configuration”Runtime Configuration
Section titled “Runtime Configuration”mode: remote-enabled
transport: type: local enabled: true
security: enforceTrust: true requireAuth: true defaultRoles: [developer]
deployment: mode: remote-enabled allowRemoteSessions: true maxConcurrentTasks: 10Security Configuration
Section titled “Security Configuration”identity: providers: - oidc - github
deviceTrust: minimumLevel: verified autoTrustLocal: true
roles: custom-developer: inherits: developer additionalPermissions: - config:write8. Best Practices
Section titled “8. Best Practices”Security
Section titled “Security”- Always enforce device trust in production
- Use repo-level policies to restrict dangerous operations
- Enable audit logging for compliance
- Rotate session tokens regularly
- Review audit logs periodically
Performance
Section titled “Performance”- Use appropriate deployment mode for your scale
- Configure task timeouts to prevent resource exhaustion
- Monitor active task count and set limits
- Implement graceful shutdown for long-running tasks
Operations
Section titled “Operations”- Test security policies in staging environment
- Document custom roles and permissions for your team
- Maintain audit trail for security incidents
- Implement monitoring for task execution metrics
9. Migration Guide
Section titled “9. Migration Guide”From Phase 1 to Phase 2
Section titled “From Phase 1 to Phase 2”Phase 2 is backward compatible with Phase 1:
// Phase 1: Direct orchestrator usageimport { globalOrchestrator } from "coderclaw/coderclaw";const workflow = globalOrchestrator.createWorkflow(steps);
// Phase 2: Enhanced orchestrator with transportimport { globalEnhancedOrchestrator } from "coderclaw/coderclaw/orchestrator-enhanced";const workflow = globalEnhancedOrchestrator.createWorkflow(steps);Existing code continues to work. New features are opt-in:
- Transport adapters (optional)
- Security policies (defaults to permissive)
- Remote orchestration (disabled by default)
10. API Reference
Section titled “10. API Reference”API documentation:
- Transport API (
src/transport/) - Security API (
src/security/) - Task Engine API (
src/transport/task-engine.ts)
11. Examples
Section titled “11. Examples”See the examples/phase2/ directory for:
- Remote task submission
- Security policy configuration
- Custom transport adapter implementation
- CI/CD integration
- Team collaboration setup