← back to Designer Wallcoverings

DW-Agents/dw-agents/agent-legal-team/MEMORY.md

308 lines


## 🚨 CRITICAL: Agent Uptime Protocol

**ALWAYS KEEP AGENTS RUNNING - THIS IS NON-NEGOTIABLE**

### Rules for Claude:
1. **BEFORE any work**: Check `pm2 list` to verify all agents are online
2. **AFTER any changes**: Restart affected agents immediately with `pm2 restart [agent-name]`
3. **NEVER leave agents down**: If any agent shows status other than 'online', restart it immediately
4. **Auto-save configuration**: Run `pm2 save` after any PM2 changes
5. **Memory rule**: ALWAYS document important patterns and decisions in this MEMORY.md file

### PM2 Commands Reference:
```bash
pm2 list                    # Check all agent status
pm2 restart [name]          # Restart specific agent
pm2 restart all             # Restart all agents
pm2 save                    # Save current configuration
pm2 logs [name] --lines 50  # Check agent logs
```

### Agent Dependencies:
- All agents depend on: master-hub (9712), task-orchestrator (9900)
- Shopify agents need: SHOPIFY_ACCESS_TOKEN, SHOPIFY_STORE_DOMAIN
- Slack agents need: SLACK_BOT_TOKEN
- Claude agents need: ANTHROPIC_API_KEY



### Automated Monitoring (Added 2025-11-07)
- **Cron Schedule**: Every 5 minutes (*/5 * * * *)
- **Script**: /root/DW-Agents/scripts/agent-health-check.sh
- **Log**: /root/DW-Agents/logs/health-check-cron.log
- **Actions**: Auto-restart any down agents, save PM2 config
- **Purpose**: Live monitoring - ensures all agents stay online 24/7




### ⚡ IMMEDIATE Health Check After Updates
**Run health check IMMEDIATELY after ANY change:**

```bash
# After editing any agent code:
bash /root/DW-Agents/scripts/post-update-check.sh [agent-name]

# Quick restart + verify:
bash /root/DW-Agents/scripts/quick-restart.sh [agent-name]

# After any PM2 changes:
pm2 restart [agent-name] && bash /root/DW-Agents/scripts/post-update-check.sh [agent-name]

# Full system check:
bash /root/DW-Agents/scripts/agent-health-check.sh
```

**Examples:**
```bash
# Updated shopify-store agent code
bash /root/DW-Agents/scripts/quick-restart.sh dw-shopify-store

# Modified ecosystem.config.js
bash /root/DW-Agents/scripts/agent-health-check.sh

# Changed digital-samples agent
pm2 restart dw-digital-samples && bash /root/DW-Agents/scripts/post-update-check.sh dw-digital-samples
```


---

# Legal Team Agent - Memory

## Last Updated
2025-11-07

## Version
1.0.110725

## Settlement Compliance Monitor

### Primary Mission
Automatically review ALL products changing from DRAFT → ACTIVE for settlement agreement violations.

### Settlement Criteria

**VIOLATION occurs when BOTH Part A AND Part B are present:**

**Part A - Prohibited Design Pattern (ALL 3 must be present):**
1. Repeating patterns with directional variation amongst leaves/palm fronds
2. Open space between leaves
3. More than one ink color

**Part B - Prohibited Specific Elements (ANY 1):**
- Banana FRUIT or banana PODS (NOT leaves - **banana leaves are OK!**)
- Grape fruit/clusters
- Birds
- Butterflies

**Acceptable Tropical Design Elements (at least ONE):**
- Tree trunks
- Clearly represented branches
- Fruit or animal elements (EXCEPT prohibited ones)

### DO NOT REANALYZE Rule
- ALWAYS check Shopify metafields BEFORE analyzing
- If product has `legal.settlement_verified`, `legal.settlement_analysis`, and `legal.settlement_status` → return cached result
- Never re-analyze products already verified
- All results stored permanently in Shopify

### Automatic DRAFT → ACTIVE Monitoring
- **Method**: GraphQL polling (every 2 minutes)
- Queries Shopify for products with `status:active` updated since last check
- ALWAYS checks metafields FIRST - DO NOT REANALYZE if already verified
- Only analyzes products without existing legal metafields
- Escalates violations to needs-attention agent (port 9900)
- Sends urgent notifications for violations
- **Polling interval**: 2 minutes
- **Initial check**: 10 seconds after startup

### Data Storage Locations
**Shopify Metafields:**
- `legal.settlement_verified` - ISO date of verification
- `legal.settlement_analysis` - Full analysis text with criteria
- `legal.settlement_status` - VIOLATION or COMPLIANT

**Product Body HTML:**
- Formatted analysis with status, description, criteria breakdown, verification date

**In-Memory:**
- `violationsList` array - All detected violations
- Updates violations display at top of page every 10 seconds

### Violations Display
- Prominent red pulsing section at TOP of dashboard
- Shows: SKU, Product ID, Full Analysis, Detection Date
- Links directly to Shopify admin for each violation
- Auto-updates every 10 seconds

### Shopify Webhook Setup Required
**Topic:** `products/update`
**URL:** `http://45.61.58.125:9878/api/webhook/product-update`
**Format:** JSON

### Integration Points
- **Needs-Attention Agent**: `http://localhost:9900/api/webhook/task`
- **Shopify Store**: designer-laboratory-sandbox.myshopify.com
- **Port**: 9878
- **Dashboard**: http://45.61.58.125:9878

---
## Memory Log

### 2025-11-07 - Version 1.0.110725 Updates
- **CRITICAL CLARIFICATION**: Banana LEAVES are OK - only banana FRUIT/PODS are prohibited
- Updated all settlement criteria displays and AI prompts
- Implemented GraphQL polling for DRAFT→ACTIVE monitoring (every 2 minutes)
- Fixed Set Draft button to use GraphQL mutation for real updates
- DO NOT REANALYZE: checks metafields before any analysis
- Violations displayed at TOP of dashboard with pulsing red alert

### 2025-11-07 - DRAFT→ACTIVE Monitoring Implemented
- Replaced webhook approach with GraphQL polling (Shopify requires HTTPS for webhooks)
- Polling interval: 2 minutes
- Checks for products with `status:active` updated since last check
- Violations automatically escalated to needs-attention agent
- Initial check runs 10 seconds after startup


---

## 📝 Creating New Agents - REQUIRED CHECKLIST

**When creating ANY new agent, ALWAYS follow these steps:**

### 1. Universal UI Components (REQUIRED)
```javascript
// Import at top of agent file
const { getUniversalHeader, BRAND_COLORS } = require('../shared-ui-components.js');

// In HTML response, inject header at top:
const html = `
<!DOCTYPE html>
<html>
<head>
  <title>${agentName} - DW-Agents</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
  </style>
</head>
<body style="padding: 20px;">
  ${getUniversalHeader('Agent Name', PORT, 30)}

  <!-- Rest of agent content here -->

</body>
</html>
`;
```

### 2. Chat API Endpoint (REQUIRED)
```javascript
// Add this endpoint to every agent:
app.post('/api/chat', requireAuth, async (req, res) => {
  try {
    const { message } = req.body;

    const response = await anthropic.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 1024,
      messages: [{
        role: 'user',
        content: `You are the ${AGENT_NAME} agent. User says: ${message}`
      }]
    });

    res.json({
      response: response.content[0].text,
      success: true
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
```

### 3. PM2 Configuration (REQUIRED)
Add to `/root/DW-Agents/ecosystem.config.js`:
```javascript
{
  name: 'dw-agent-name',
  script: './node_modules/.bin/tsx',
  args: 'agent-name-agent.ts',
  cwd: '/root/DW-Agents',
  instances: 1,
  autorestart: true,
  watch: false,
  max_memory_restart: '500M',
  env: {
    NODE_ENV: 'production',
    PORT: XXXX,
    ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY
  },
  error_file: '/root/DW-Agents/logs/agent-name-error.log',
  out_file: '/root/DW-Agents/logs/agent-name-out.log'
}
```

### 4. Directory Structure (REQUIRED)
```bash
mkdir -p /root/DW-Agents/agent-[name]
cd /root/DW-Agents/agent-[name]

# Create files:
touch [name]-agent.ts
touch README.md
touch MEMORY.md
```

### 5. Update Master Hub (REQUIRED)
Add to `/root/DW-Agents/master-hub.ts` AGENTS array:
```javascript
{
  id: 'agent-name',
  name: 'Agent Display Name',
  port: XXXX,
  url: 'http://45.61.58.125:XXXX',
  status: 'online',
  description: 'What this agent does',
  icon: '🤖',
  color: '#667eea'
}
```

### 6. Update AGENTS_INDEX.md (REQUIRED)
Add entry to `/root/DW-Agents/AGENTS_INDEX.md`

### 7. Start & Verify (REQUIRED)
```bash
# Start agent
pm2 start ecosystem.config.js --only dw-agent-name

# Open firewall port
sudo ufw allow XXXX

# Verify immediately
bash /root/DW-Agents/scripts/post-update-check.sh dw-agent-name

# Save PM2 config
pm2 save

# Restart master hub
pm2 restart dw-master-hub
```

### 8. Test Checklist
- [ ] Universal header visible at top
- [ ] Chat input working and responsive
- [ ] Refresh button working
- [ ] Live countdown ticking down
- [ ] Agent appears in Master Hub
- [ ] PM2 shows status: online
- [ ] Logs showing no errors