# LocalGreenChain Agent System

A comprehensive autonomous agent system for managing the LocalGreenChain ecosystem. The system consists of 10 specialized agents coordinated by a central orchestrator.

## Overview

The agent system provides intelligent automation for:
- Plant lineage tracking and verification
- Transport and carbon footprint monitoring
- Consumer demand forecasting
- Vertical farm management
- Growing condition optimization
- Market matching between growers and consumers
- Sustainability monitoring
- Network analysis and discovery
- Data quality assurance
- Personalized grower advisory

## Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                      AgentOrchestrator                          │
│  - Starts/stops agents          - Health monitoring             │
│  - Alert aggregation            - Event coordination            │
└─────────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│ PlantLineage  │   │   Transport   │   │    Demand     │
│    Agent      │   │ TrackerAgent  │   │ ForecastAgent │
│ (60s cycle)   │   │ (120s cycle)  │   │ (300s cycle)  │
└───────────────┘   └───────────────┘   └───────────────┘
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│ VerticalFarm  │   │  Environment  │   │    Market     │
│    Agent      │   │ AnalysisAgent │   │ MatchingAgent │
│ (30s cycle)   │   │ (180s cycle)  │   │ (60s cycle)   │
└───────────────┘   └───────────────┘   └───────────────┘
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│Sustainability │   │   Network     │   │    Quality    │
│    Agent      │   │ DiscoveryAgent│   │AssuranceAgent │
│ (300s cycle)  │   │ (600s cycle)  │   │ (120s cycle)  │
└───────────────┘   └───────────────┘   └───────────────┘
                          │
                          ▼
                  ┌───────────────┐
                  │    Grower     │
                  │ AdvisoryAgent │
                  │ (300s cycle)  │
                  └───────────────┘
```

## Quick Start

```typescript
import { getOrchestrator, startAllAgents, stopAllAgents } from './lib/agents';

// Start all agents
await startAllAgents();

// Get orchestrator for management
const orchestrator = getOrchestrator();

// Check status
const status = orchestrator.getStatus();
console.log(`Running: ${status.runningAgents}/${status.totalAgents} agents`);

// Get dashboard data
const dashboard = orchestrator.getDashboard();

// Stop all agents
await stopAllAgents();
```

## The 10 Agents

### 1. PlantLineageAgent
**Purpose**: Monitors and manages plant lineage tracking in the blockchain

**Responsibilities**:
- Validate new plant registrations
- Track generation lineage and ancestry
- Detect anomalies (orphans, circular references, invalid generations)
- Generate lineage reports and family trees
- Monitor plant status transitions

**Key Methods**:
```typescript
const agent = getPlantLineageAgent();
agent.getLineageAnalysis(plantId);  // Get complete lineage for a plant
agent.getAnomalies();               // Get detected anomalies
agent.getNetworkStats();            // Get network-wide statistics
```

**Cycle**: 60 seconds | **Priority**: High

---

### 2. TransportTrackerAgent
**Purpose**: Monitors transport events and calculates environmental impact

**Responsibilities**:
- Track seed-to-seed transport lifecycle
- Calculate and aggregate carbon footprint
- Monitor food miles across the network
- Detect inefficient transport patterns
- Generate transport optimization recommendations

**Key Methods**:
```typescript
const agent = getTransportTrackerAgent();
agent.getUserAnalysis(userId);       // Get user transport analysis
agent.getNetworkStats();             // Get network transport statistics
agent.getPatterns();                 // Get detected inefficiency patterns
agent.calculateSavingsVsConventional(); // Compare to conventional transport
```

**Cycle**: 120 seconds | **Priority**: High

---

### 3. DemandForecastAgent
**Purpose**: Autonomous demand forecasting and market intelligence

**Responsibilities**:
- Monitor consumer preference changes
- Generate regional demand signals
- Predict seasonal demand patterns
- Identify supply gaps and opportunities
- Provide early warnings for demand shifts

**Key Methods**:
```typescript
const agent = getDemandForecastAgent();
agent.getRegionalSummaries();   // Get demand by region
agent.getOpportunities();       // Get market opportunities
agent.getTrends();              // Get demand trends
agent.getDemandAlerts();        // Get demand-related alerts
```

**Cycle**: 300 seconds | **Priority**: High

---

### 4. VerticalFarmAgent
**Purpose**: Autonomous vertical farm monitoring and optimization

**Responsibilities**:
- Monitor environmental conditions in all zones
- Detect anomalies and trigger alerts
- Optimize growing parameters
- Track crop batch progress
- Generate yield predictions
- Coordinate harvest scheduling

**Key Methods**:
```typescript
const agent = getVerticalFarmAgent();
agent.getAllZones();            // Get all zone statuses
agent.getAllBatches();          // Get all batch progress
agent.getYieldPredictions();    // Get yield predictions
agent.getRecommendations();     // Get optimization recommendations
agent.getFarmSummary();         // Get overall farm summary
```

**Cycle**: 30 seconds | **Priority**: Critical

---

### 5. EnvironmentAnalysisAgent
**Purpose**: Analyzes growing conditions and provides optimization recommendations

**Responsibilities**:
- Compare growing environments across plants
- Identify optimal conditions for each species
- Generate environment improvement recommendations
- Track environmental impacts on plant health
- Learn from successful growing patterns

**Key Methods**:
```typescript
const agent = getEnvironmentAnalysisAgent();
agent.getSpeciesProfile(species);      // Get optimal conditions for species
agent.getPlantScore(plantId);          // Get environment score for plant
agent.compareEnvironments(id1, id2);   // Compare two plant environments
agent.getSuccessPatterns();            // Get identified success patterns
```

**Cycle**: 180 seconds | **Priority**: Medium

---

### 6. MarketMatchingAgent
**Purpose**: Connects grower supply with consumer demand

**Responsibilities**:
- Match supply commitments with demand signals
- Optimize delivery routes and logistics
- Facilitate fair pricing
- Track match success rates
- Enable local food distribution

**Key Methods**:
```typescript
const agent = getMarketMatchingAgent();
agent.registerSupplyOffer(offer);      // Register grower supply
agent.registerDemandRequest(request);  // Register consumer demand
agent.getAllMatches();                 // Get all market matches
agent.getPricingAnalysis();            // Get pricing data
agent.getMarketStats();                // Get market statistics
```

**Cycle**: 60 seconds | **Priority**: High

---

### 7. SustainabilityAgent
**Purpose**: Monitors and reports on environmental impact across the network

**Responsibilities**:
- Calculate network-wide carbon footprint
- Track food miles reduction vs conventional
- Monitor water usage in vertical farms
- Generate sustainability reports
- Identify improvement opportunities

**Key Methods**:
```typescript
const agent = getSustainabilityAgent();
agent.getCarbonMetrics();          // Get carbon footprint metrics
agent.getFoodMilesMetrics();       // Get food miles metrics
agent.getWaterMetrics();           // Get water usage metrics
agent.getSustainabilityScore();    // Get overall sustainability score
agent.generateReport();            // Generate sustainability report
```

**Cycle**: 300 seconds | **Priority**: Medium

---

### 8. NetworkDiscoveryAgent
**Purpose**: Analyzes geographic distribution and connections in the plant network

**Responsibilities**:
- Map plant distribution across regions
- Identify network hotspots and clusters
- Suggest grower/consumer connections
- Track network growth patterns
- Detect coverage gaps

**Key Methods**:
```typescript
const agent = getNetworkDiscoveryAgent();
agent.getClusters();               // Get identified network clusters
agent.getCoverageGaps();           // Get geographic coverage gaps
agent.getConnectionSuggestions();  // Get suggested connections
agent.getGrowthHistory();          // Get network growth history
agent.getNetworkAnalysis();        // Get full network analysis
```

**Cycle**: 600 seconds | **Priority**: Medium

---

### 9. QualityAssuranceAgent
**Purpose**: Verifies blockchain integrity and data quality

**Responsibilities**:
- Verify blockchain integrity
- Detect data anomalies and inconsistencies
- Monitor transaction validity
- Generate data quality reports
- Ensure compliance with data standards

**Key Methods**:
```typescript
const agent = getQualityAssuranceAgent();
agent.triggerVerification();       // Manually trigger verification
agent.getIntegrityChecks();        // Get blockchain integrity results
agent.getQualityIssues();          // Get data quality issues
agent.getComplianceStatus();       // Get compliance status
agent.generateReport();            // Generate quality report
```

**Cycle**: 120 seconds | **Priority**: Critical

---

### 10. GrowerAdvisoryAgent
**Purpose**: Provides personalized recommendations to growers

**Responsibilities**:
- Generate planting recommendations based on demand
- Provide crop rotation advice
- Alert on optimal planting windows
- Analyze market opportunities
- Track grower performance metrics

**Key Methods**:
```typescript
const agent = getGrowerAdvisoryAgent();
agent.getRecommendations(growerId);  // Get planting recommendations
agent.getRotationAdvice(growerId);   // Get crop rotation advice
agent.getOpportunities();            // Get market opportunities
agent.getPerformance(growerId);      // Get grower performance
agent.getSeasonalAlerts();           // Get seasonal alerts
```

**Cycle**: 300 seconds | **Priority**: High

---

## Orchestrator API

### Configuration
```typescript
const orchestrator = getOrchestrator({
  autoStart: false,
  enabledAgents: ['plant-lineage-agent', 'transport-tracker-agent', ...],
  alertAggregationIntervalMs: 60000,
  healthCheckIntervalMs: 30000,
  maxAlertsPerAgent: 50
});
```

### Management Methods
```typescript
// Start/stop all agents
await orchestrator.startAll();
await orchestrator.stopAll();

// Manage individual agents
await orchestrator.startAgent('plant-lineage-agent');
await orchestrator.stopAgent('plant-lineage-agent');
await orchestrator.restartAgent('plant-lineage-agent');
```

### Monitoring Methods
```typescript
// Get orchestrator status
const status = orchestrator.getStatus();
// { isRunning, startedAt, uptime, totalAgents, runningAgents, healthyAgents, ... }

// Get agent health
const health = orchestrator.getAgentHealth('plant-lineage-agent');
// { agentId, status, tasksCompleted, errorRate, isHealthy, ... }

// Get all alerts
const alerts = orchestrator.getAlerts('critical');

// Get full dashboard
const dashboard = orchestrator.getDashboard();
```

### Event Handling
```typescript
orchestrator.on('orchestrator_started', (data) => {
  console.log(`Started with ${data.agentCount} agents`);
});

orchestrator.on('critical_alerts', (data) => {
  console.log(`${data.count} critical alerts!`);
});
```

## Alert System

Each agent can generate alerts with the following severities:
- **Critical**: Immediate action required
- **Warning**: Attention needed soon
- **Error**: Something went wrong
- **Info**: Informational notification

Alerts are automatically aggregated by the orchestrator and can be retrieved:
```typescript
const allAlerts = orchestrator.getAlerts();
const criticalAlerts = orchestrator.getAlerts('critical');

// Acknowledge an alert
orchestrator.acknowledgeAlert(alertId);
```

## Health Monitoring

The orchestrator performs automatic health checks every 30 seconds:
- Monitors agent status and response times
- Calculates error rates
- Auto-restarts agents with >50% error rate
- Reports unhealthy agents

## Best Practices

1. **Start Order**: Agents are started in priority order (critical → high → medium → low)
2. **Error Handling**: All agents have built-in retry logic and error recovery
3. **Resource Management**: Use singletons to avoid duplicate agent instances
4. **Alert Management**: Regularly acknowledge alerts to keep the system clean
5. **Monitoring**: Use the dashboard for real-time system visibility

## Integration with Existing Systems

The agents integrate with existing LocalGreenChain systems:
- **PlantChain**: Plant lineage and registration
- **TransportChain**: Transport events and carbon tracking
- **DemandForecaster**: Consumer demand signals
- **VerticalFarmController**: Farm zone and batch management
- **Environment Analysis**: Growing condition comparison

## Performance Considerations

- **Memory**: Each agent maintains its own cache; combined memory usage ~50-100MB
- **CPU**: Minimal CPU usage during idle periods; peak during analysis cycles
- **Network**: No external network calls unless configured (e.g., external APIs)
- **Storage**: Agents maintain in-memory state; orchestrator handles persistence

## Future Enhancements

Planned improvements:
- Machine learning integration for demand prediction
- Automated agent scaling based on load
- Distributed agent deployment
- WebSocket real-time updates
- Mobile push notifications for alerts
