Skip to main content

ADR-027-v4: Implementation Coordination Framework (Part 2: Technical)

Document: ADR-027-v4-implementation-coordination-framework-part2-technical
Version: 1.0.0
Purpose: Technical implementation for multi-agent ADR-to-code coordination system
Audience: AI agents, developers implementing coordination framework
Date Created: 2025-09-01
Date Modified: 2025-09-01
QA Reviewed: Pending
Status: DRAFT
Related: ADR-027-part1-narrative, Harper Reed llm Workflow

Table of Contents​

↑ Back to Top

1. Prompt Library System​

ADR-to-Prompt Generator​

// src/coordination/prompt_generator.rs
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImplementationPrompt {
pub adr_number: String,
pub component: String,
pub context: String,
pub task: String,
pub constraints: Vec<String>,
pub success_criteria: Vec<String>,
}

pub struct PromptLibrary {
pub base_template: String,
pub adr_specific: HashMap<String, ImplementationPrompt>,
}

impl PromptLibrary {
pub fn generate_for_adr(&self, adr_number: &str, part2_content: &str) -> Result<ImplementationPrompt> {
let template = format!(r#"
You are implementing {adr_number} component.

CONTEXT:
{context}

TASK:
Implement the complete {component} system as specified in the ADR Part 2.

CONSTRAINTS:
- Use existing CODITECT patterns from /src/
- Follow logging standard: use coditect::logging::Logger
- Implement ALL tests before code
- Claim files via CODI before editing
- Update progress every 10 minutes

SUCCESS CRITERIA:
- All tests pass
- Code follows ADR specifications exactly
- Integration points work with other components
- Performance meets ADR targets

FILES TO IMPLEMENT:
{file_list}

DEPENDENCIES:
{dependencies}
"#);

Ok(ImplementationPrompt {
adr_number: adr_number.to_string(),
component: self.extract_component_name(part2_content)?,
context: self.extract_context(part2_content)?,
task: template,
constraints: self.extract_constraints(part2_content)?,
success_criteria: self.extract_success_criteria(part2_content)?,
})
}
}

Agent Specialization Templates​

pub struct AgentSpecialization {
pub agent_type: String,
pub expertise: Vec<String>,
pub file_patterns: Vec<String>,
pub prompt_template: String,
}

pub const API_AGENT: AgentSpecialization = AgentSpecialization {
agent_type: "api_specialist".to_string(),
expertise: vec!["REST".to_string(), "authentication".to_string(), "middleware".to_string()],
file_patterns: vec!["src/api/**".to_string(), "src/handlers/**".to_string()],
prompt_template: r#"
You are the API_SPECIALIST agent. You implement REST endpoints, authentication, and middleware.

Your expertise:
- Actix-web framework patterns
- JWT authentication flows
- Request/response validation
- Rate limiting implementation
- API documentation generation

Your file boundaries:
- src/api/
- src/handlers/
- src/auth/
- src/middleware/

NEVER edit files outside your boundaries.
"#.to_string(),
};

↑ Back to Top

2. Agent Coordination Protocol​

Work Assignment System​

// src/coordination/assignment.rs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkAssignment {
pub assignment_id: Uuid,
pub agent_session: String,
pub adr_component: String,
pub file_claims: Vec<String>,
pub dependencies: Vec<String>,
pub status: AssignmentStatus,
pub started_at: DateTime<Utc>,
pub estimated_completion: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AssignmentStatus {
Assigned,
InProgress,
TestingPhase,
QAReview,
Completed,
Blocked(String),
}

pub struct CoordinationEngine {
assignments: Arc<RwLock<HashMap<String, WorkAssignment>>>,
file_locks: Arc<RwLock<HashMap<String, String>>>,
codi_logger: Logger,
}

impl CoordinationEngine {
pub async fn assign_work(&self, session_id: &str, adr_component: &str) -> Result<WorkAssignment> {
let files = self.get_files_for_component(adr_component).await?;

// Check file availability
for file in &files {
if self.file_locks.read().await.contains_key(file) {
return Err(anyhow::anyhow!("File {} locked by another agent", file));
}
}

// Create assignment
let assignment = WorkAssignment {
assignment_id: Uuid::new_v4(),
agent_session: session_id.to_string(),
adr_component: adr_component.to_string(),
file_claims: files.clone(),
dependencies: self.get_dependencies(adr_component).await?,
status: AssignmentStatus::Assigned,
started_at: Utc::now(),
estimated_completion: None,
};

// Lock files
for file in &files {
self.file_locks.write().await.insert(file.clone(), session_id.to_string());
}

// Log assignment
self.codi_logger.log(&format!(
"WORK_ASSIGNMENT {} → {} files: {:?}",
session_id, adr_component, files
)).await?;

Ok(assignment)
}
}

Dependency Management​

pub struct DependencyGraph {
edges: HashMap<String, Vec<String>>,
}

impl DependencyGraph {
pub fn can_start(&self, component: &str, completed: &HashSet<String>) -> bool {
let deps = self.edges.get(component).unwrap_or(&vec![]);
deps.iter().all(|dep| completed.contains(dep))
}

pub fn get_ready_components(&self, completed: &HashSet<String>) -> Vec<String> {
self.edges.keys()
.filter(|comp| self.can_start(comp, completed))
.cloned()
.collect()
}
}

// Dependency definitions
pub const ADR_DEPENDENCIES: &[(&str, &[&str])] = &[
("ADR-001-foundation", &[]),
("ADR-002-data-model", &["ADR-001-foundation"]),
("ADR-003-multi-tenant", &["ADR-001-foundation", "ADR-002-data-model"]),
("ADR-004-api", &["ADR-002-data-model", "ADR-003-multi-tenant"]),
("ADR-005-auth", &["ADR-004-api"]),
("ADR-006-websocket", &["ADR-004-api", "ADR-005-auth"]),
];

↑ Back to Top

3. File-Level Locking​

Lock Management System​

// src/coordination/file_locks.rs
pub struct FileLockManager {
locks: Arc<RwLock<HashMap<String, FileLock>>>,
codi_integration: CodiIntegration,
}

#[derive(Debug, Clone)]
pub struct FileLock {
pub file_path: String,
pub owner_session: String,
pub locked_at: DateTime<Utc>,
pub lock_type: LockType,
pub estimated_duration: Duration,
}

#[derive(Debug, Clone)]
pub enum LockType {
Exclusive, // Only one agent can edit
Shared, // Multiple agents can read
Coordination, // Coordination between agents required
}

impl FileLockManager {
pub async fn claim_files(&self, session_id: &str, files: &[String]) -> Result<()> {
let mut locks = self.locks.write().await;

// Check availability
for file in files {
if let Some(existing) = locks.get(file) {
if existing.owner_session != session_id {
return Err(anyhow::anyhow!(
"File {} locked by {}", file, existing.owner_session
));
}
}
}

// Claim locks
for file in files {
locks.insert(file.clone(), FileLock {
file_path: file.clone(),
owner_session: session_id.to_string(),
locked_at: Utc::now(),
lock_type: LockType::Exclusive,
estimated_duration: Duration::minutes(30),
});

// Log via CODI
self.codi_integration.log_file_claim(session_id, file).await?;
}

Ok(())
}

pub async fn release_files(&self, session_id: &str) -> Result<()> {
let mut locks = self.locks.write().await;
let released: Vec<String> = locks.iter()
.filter(|(_, lock)| lock.owner_session == session_id)
.map(|(file, _)| file.clone())
.collect();

for file in &released {
locks.remove(file);
self.codi_integration.log_file_release(session_id, file).await?;
}

Ok(())
}
}

↑ Back to Top

4. CODI Integration​

Enhanced Logging for Coordination​

// src/coordination/codi_integration.rs
pub struct CodiIntegration {
logger: Logger,
}

impl CodiIntegration {
pub async fn log_assignment(&self, session_id: &str, assignment: &WorkAssignment) -> Result<()> {
let entry = LogEntry {
timestamp: Utc::now(),
level: LogLevel::Info,
component: "coordination.assignment",
action: "work_assigned",
session_id: Some(session_id.to_string()),
details: json!({
"assignment_id": assignment.assignment_id,
"adr_component": assignment.adr_component,
"file_claims": assignment.file_claims,
"dependencies": assignment.dependencies,
}),
};

self.logger.log(entry).await
}

pub async fn log_progress(&self, session_id: &str, component: &str, progress: f64) -> Result<()> {
let entry = LogEntry {
timestamp: Utc::now(),
level: LogLevel::Info,
component: "coordination.progress",
action: "progress_update",
session_id: Some(session_id.to_string()),
details: json!({
"component": component,
"progress_percent": progress,
"status": if progress >= 100.0 { "complete" } else { "in_progress" }
}),
};

self.logger.log(entry).await
}
}

Real-time Dashboard Integration​

// src/coordination/dashboard.rs
pub async fn get_coordination_status() -> Result<CoordinationStatus> {
let assignments = get_active_assignments().await?;
let file_locks = get_current_file_locks().await?;
let recent_logs = get_recent_codi_logs(Duration::minutes(10)).await?;

Ok(CoordinationStatus {
active_sessions: assignments.len(),
files_locked: file_locks.len(),
components_in_progress: assignments.iter()
.filter(|a| matches!(a.status, AssignmentStatus::InProgress))
.count(),
recent_activity: recent_logs.len(),
next_available_components: get_ready_components(&assignments).await?,
})
}

↑ Back to Top

5. Quality Gates​

Automated Testing Pipeline​

// src/coordination/quality_gates.rs
pub struct QualityGate {
pub gate_type: GateType,
pub requirements: Vec<Requirement>,
pub automated_checks: Vec<AutomatedCheck>,
}

#[derive(Debug)]
pub enum GateType {
PreImplementation, // Before agent starts coding
PostImplementation, // After component complete
Integration, // Before merging components
PreDeployment, // Before production deployment
}

pub struct AutomatedCheck {
pub name: String,
pub command: String,
pub success_criteria: String,
pub timeout: Duration,
}

impl QualityGate {
pub async fn validate(&self, component: &str, session_id: &str) -> Result<GateResult> {
let mut results = Vec::new();

for check in &self.automated_checks {
let result = self.run_check(check, component).await?;
results.push(result);

if !result.passed {
return Ok(GateResult::Failed(result.error_message));
}
}

Ok(GateResult::Passed)
}
}

// Pre-defined quality gates
pub const PRE_IMPLEMENTATION_GATE: QualityGate = QualityGate {
gate_type: GateType::PreImplementation,
requirements: vec![
Requirement::TestsWritten,
Requirement::DependenciesAvailable,
Requirement::FilesClaimable,
],
automated_checks: vec![
AutomatedCheck {
name: "ADR Part 2 exists".to_string(),
command: "test -f docs/architecture/{adr}-part2-technical.md".to_string(),
success_criteria: "File exists".to_string(),
timeout: Duration::seconds(5),
},
],
};

↑ Back to Top

6. Testing Framework​

Component Integration Tests​

// src/coordination/integration_tests.rs
#[tokio::test]
async fn test_multi_agent_coordination() {
let coordination = CoordinationEngine::new().await;

// Simulate multiple agents requesting work
let session1 = coordination.assign_work("session1", "ADR-004-api").await.unwrap();
let session2 = coordination.assign_work("session2", "ADR-005-auth").await.unwrap();

// Verify file locks prevent conflicts
assert!(coordination.assign_work("session3", "ADR-004-api").await.is_err());

// Complete work and verify handoff
coordination.complete_assignment("session1").await.unwrap();
let session3 = coordination.assign_work("session3", "ADR-006-websocket").await.unwrap();

assert_eq!(session3.dependencies, vec!["ADR-004-api", "ADR-005-auth"]);
}

End-to-End Workflow Test​

#[tokio::test]
async fn test_adr_to_production_pipeline() {
// 1. Generate prompts from ADR
let prompts = PromptLibrary::generate_for_adr("ADR-004", &adr_004_content).await.unwrap();

// 2. Assign to specialized agent
let assignment = coordination.assign_work("api_agent", "ADR-004-api").await.unwrap();

// 3. Simulate agent implementation
let implementation = simulate_agent_work(&prompts.task).await.unwrap();

// 4. Run quality gates
let gate_result = PRE_DEPLOYMENT_GATE.validate("ADR-004-api", "api_agent").await.unwrap();
assert!(matches!(gate_result, GateResult::Passed));

// 5. Verify deployment readiness
assert!(implementation.tests_pass);
assert!(implementation.meets_performance_targets);
}

Implementation Note: This technical specification provides the exact framework for coordinating 26 ADRs across multiple AI agents. Each component can be implemented independently while maintaining system integrity through automated coordination.

↑ Back to Top