← back to Designer Wallcoverings

DW-Agents/dw-agents/DWLegalTeam/README.md

353 lines

# DWLegalTeam Directory

## Purpose
Specialized legal compliance system for monitoring Designer Wallcoverings settlement agreement obligations, particularly focused on tropical design pattern restrictions.

## Overview
Separate standalone legal agent implementation with its own dependencies and Azure Cognitive Services integration for advanced image and pattern analysis.

## Directory Structure
```
/root/DW-Agents/DWLegalTeam/
├── legal-agent.ts              # Main legal compliance agent (86KB)
├── shared-auth.ts              # Authentication module
├── .env                        # Environment variables (legal-specific)
├── package.json                # Node.js dependencies
├── package-lock.json           # Dependency lock file
├── node_modules/               # Installed dependencies
├── test-cote-azure-5-methods.ts    # Azure testing (5 methods)
└── test-cote-azure-NOW.ts          # Azure testing (current)
```

## Main Components

### legal-agent.ts (86,145 bytes)
**Purpose**: Core legal compliance monitoring agent

**Responsibilities**:
- Settlement agreement compliance checking
- Tropical design pattern violation detection
- Product catalog scanning and analysis
- Real-time violation alerts
- Compliance audit trail generation
- Legal document management

**Key Features**:
- **Settlement Compliance Monitoring**:
  - Automated product catalog scanning
  - Pattern recognition for restricted designs
  - Tropical theme violation detection
  - Real-time compliance alerts

- **Image Analysis**:
  - Azure Cognitive Services integration
  - Pattern matching algorithms
  - Design element classification
  - Similarity detection

- **Violation Tracking**:
  - Violation database management
  - Historical violation records
  - Compliance trend analysis
  - Risk assessment

- **Reporting**:
  - Compliance status reports
  - Violation summaries
  - Audit trail documentation
  - Executive compliance dashboards

**Integration Points**:
- Shopify Store Agent (7238) - Product catalog access
- Master Hub (9893) - Compliance reporting
- Needs Attention Agent (9886) - Violation alerts
- Task Orchestrator (9900) - Remediation tasks

### Azure Cognitive Services Integration

#### test-cote-azure-5-methods.ts (13,220 bytes)
**Purpose**: Testing suite for 5 Azure CV methods

**Tested Methods**:
1. **Image Analysis**: Extract visual features
2. **Object Detection**: Identify objects in images
3. **Tag Generation**: Generate image tags
4. **Description**: Generate image descriptions
5. **Pattern Matching**: Custom pattern detection

#### test-cote-azure-NOW.ts (3,768 bytes)
**Purpose**: Current Azure integration testing

**Features**:
- Real-time API testing
- Response validation
- Performance benchmarking
- Error handling verification

## Configuration

### Environment Variables (.env)
```bash
# Azure Cognitive Services
AZURE_CV_ENDPOINT=https://[region].api.cognitive.microsoft.com/
AZURE_CV_KEY=[subscription-key]

# Shopify Integration
SHOPIFY_STORE_DOMAIN=designer-laboratory-sandbox.myshopify.com
SHOPIFY_ACCESS_TOKEN=[access-token]

# Legal Agent Port
PORT=9878

# Anthropic AI
ANTHROPIC_API_KEY=[api-key]
```

### Dependencies (package.json)
```json
{
  "name": "dw-legal-team",
  "version": "1.0.0",
  "dependencies": {
    "@anthropic-ai/sdk": "^0.32.1",
    "@azure/cognitiveservices-computervision": "^8.2.0",
    "express": "^4.18.2",
    "dotenv": "^17.2.3",
    "node-fetch": "^3.3.2"
  }
}
```

## Settlement Agreement Compliance

### Monitored Restrictions
1. **Tropical Design Patterns**:
   - Palm trees, tropical leaves
   - Exotic flowers, hibiscus patterns
   - Beach/coastal themes
   - Tropical fruit motifs

2. **Restricted Elements**:
   - Specific color combinations
   - Pattern layouts matching settlements
   - Trademarked design elements
   - Protected intellectual property

### Compliance Workflow
1. **Product Upload**: New product added to Shopify
2. **Automated Scan**: Legal agent analyzes product images
3. **Pattern Detection**: Azure CV identifies design elements
4. **Compliance Check**: Compare against restricted patterns
5. **Violation Alert**: Notify if violation detected
6. **Remediation Task**: Create task for product review/removal
7. **Audit Trail**: Log all compliance checks

## Detection Algorithms

### Pattern Recognition
```typescript
interface PatternDetection {
  pattern: string;           // Pattern name
  confidence: number;        // 0-100 confidence score
  restricted: boolean;       // Is this restricted?
  elements: string[];        // Detected design elements
  similarity: number;        // Similarity to known violations
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
}
```

### Violation Criteria
- **Critical**: >90% match to restricted pattern
- **High**: 70-90% similarity to violations
- **Medium**: 50-70% similarity
- **Low**: <50% but contains restricted elements

## Azure Cognitive Services Usage

### Image Analysis API
```typescript
// Analyze product image
const analysis = await azureCV.analyzeImage(imageUrl, {
  visualFeatures: [
    'Categories',
    'Description',
    'Tags',
    'Objects',
    'Color',
    'ImageType'
  ]
});
```

### Custom Vision (Trained Model)
- Trained on settlement-restricted patterns
- Custom classifier for tropical designs
- Continuous learning from violations
- Regular model updates

## Alerts and Notifications

### Violation Alerts
When violation detected:
1. **Immediate Alert**: Needs Attention Agent
2. **Email Notification**: Legal team
3. **Task Creation**: Remediation task in orchestrator
4. **Slack Message**: #legal-compliance channel
5. **Dashboard Update**: Legal compliance dashboard

### Alert Levels
- **Critical**: Immediate action required (product live)
- **High**: Review within 24 hours
- **Medium**: Review within 1 week
- **Low**: Routine review

## Compliance Reporting

### Daily Reports
- Products scanned: Count
- Violations detected: Count and details
- Risk level distribution
- Compliance rate percentage

### Monthly Reports
- Compliance trend analysis
- Violation patterns
- Risk assessment
- Recommendations

### Audit Trail
Complete record of:
- All compliance checks performed
- Violation detections
- Remediation actions taken
- Product modifications
- Timestamps and user actions

## Integration with Main System

### Standalone vs. Integrated
**Standalone Features**:
- Own dependencies (Azure SDK)
- Separate .env configuration
- Independent node_modules
- Isolated testing suite

**Integration Points**:
- Uses shared-auth.ts from main system
- Connects to Task Orchestrator (9900)
- Reports to Master Hub (9893)
- Accesses Shopify via main credentials

## API Endpoints (Port 9878)

```
GET  /                    - Legal compliance dashboard
POST /scan-product        - Scan single product
POST /scan-catalog        - Scan entire catalog
GET  /violations          - List all violations
GET  /compliance-report   - Generate report
POST /chat                - AI legal assistant
```

## Security & Access

### Authentication
- Uses shared SSO authentication
- Legal team access only
- Audit trail of all access
- Restricted dashboard visibility

### Data Privacy
- Settlement terms: Confidential
- Violation records: Internal only
- Product analysis: Encrypted
- Azure API keys: Environment variables only

## Maintenance

### Regular Tasks
- **Daily**: Automated catalog scan
- **Weekly**: Azure model performance review
- **Monthly**: Compliance reporting
- **Quarterly**: Settlement agreement review

### Updates
- Azure SDK updates
- Pattern database updates
- Model retraining
- Settlement agreement changes

## Testing

### Run Azure Tests
```bash
cd /root/DW-Agents/DWLegalTeam

# Test 5 methods
npx tsx test-cote-azure-5-methods.ts

# Test current implementation
npx tsx test-cote-azure-NOW.ts
```

### Manual Testing
```bash
# Start legal agent
pm2 start legal

# Check status
pm2 status legal

# View logs
pm2 logs legal

# Restart
pm2 restart legal
```

## Performance

### Azure API Limits
- Requests per second: 10
- Monthly quota: 5,000 transactions
- Rate limiting: Implemented

### Optimization
- Image caching for repeated scans
- Batch processing for catalog scans
- Async processing for large catalogs
- Result caching (24-hour TTL)

## Troubleshooting

### Azure Connection Issues
1. Verify Azure credentials in .env
2. Check Azure subscription status
3. Validate endpoint URL
4. Test with test-cote-azure-NOW.ts

### False Positives
1. Review detection thresholds
2. Update pattern database
3. Retrain custom vision model
4. Manual review and override

### Performance Issues
1. Check Azure API quota usage
2. Review image cache hit rate
3. Optimize batch processing
4. Monitor response times

## Related Components
- **agent-legal-team/** - Main legal agent directory
- **Master Hub (9893)**: Compliance oversight
- **Shopify Store Agent (7238)**: Product data source
- **Task Orchestrator (9900)**: Remediation workflow

## Future Enhancements
- Machine learning for pattern detection
- Automated product modification suggestions
- Integration with legal document management
- Competitor monitoring for violations
- Predictive compliance risk scoring