Initial commit: Clean DSS implementation

Migrated from design-system-swarm with fresh git history.
Old project history preserved in /home/overbits/apps/design-system-swarm

Core components:
- MCP Server (Python FastAPI with mcp 1.23.1)
- Claude Plugin (agents, commands, skills, strategies, hooks, core)
- DSS Backend (dss-mvp1 - token translation, Figma sync)
- Admin UI (Node.js/React)
- Server (Node.js/Express)
- Storybook integration (dss-mvp1/.storybook)

Self-contained configuration:
- All paths relative or use DSS_BASE_PATH=/home/overbits/dss
- PYTHONPATH configured for dss-mvp1 and dss-claude-plugin
- .env file with all configuration
- Claude plugin uses ${CLAUDE_PLUGIN_ROOT} for portability

Migration completed: $(date)
🤖 Clean migration with full functionality preserved
This commit is contained in:
Digital Production Factory
2025-12-09 18:45:48 -03:00
commit 276ed71f31
884 changed files with 373737 additions and 0 deletions

View File

@@ -0,0 +1,313 @@
# Workflow 01: Capture Browser Logs
**Purpose**: Capture and retrieve all browser-side logs from DSS dashboard for debugging
**When to Use**:
- User reports dashboard not loading
- JavaScript errors in browser
- Network request failures
- Performance issues
- Configuration problems
**Estimated Time**: 2-5 minutes
---
## Prerequisites
- Dashboard accessible (https://dss.overbits.luz.uy/ or http://localhost:3456/admin-ui/index.html)
- Browser DevTools available (Chrome, Firefox, Edge, Safari)
- Browser logger module loaded (browser-logger.js)
---
## Step-by-Step Procedure
### Step 1: Open DSS Dashboard
**Action**:
```
Navigate to: https://dss.overbits.luz.uy/
Or local: http://localhost:3456/admin-ui/index.html
```
**Expected Result**: Dashboard loads (may require credentials)
**Troubleshooting**:
- If 401 Unauthorized: Provide htpasswd credentials
- If connection refused: Check API server running on port 3456
- If 500 error: Check server logs with `journalctl -u dss-api -f`
---
### Step 2: Open Browser DevTools
**Action**:
```
Chrome/Edge: F12 or Cmd+Option+I (Mac) or Ctrl+Shift+I (Windows)
Firefox: F12 or Cmd+Option+K (Mac) or Ctrl+Shift+K (Windows)
Safari: Cmd+Option+C (Mac, requires enabling in Preferences)
```
**Expected Result**: DevTools panel opens at bottom or side of browser
**Go to Console Tab**: Click "Console" in the top menu of DevTools
---
### Step 3: Verify Browser Logger is Loaded
**Action**:
```javascript
// In console, type:
window.__DSS_BROWSER_LOGS
```
**Expected Result**:
```javascript
{
all: ƒ (),
errors: ƒ (),
network: ƒ (),
diagnostic: ƒ (),
export: ƒ (),
print: ƒ (),
clear: ƒ ()
}
```
**Troubleshooting**:
- If `undefined`: Browser logger not loaded. Check Network tab for `/admin-ui/js/core/browser-logger.js` (should be 200 OK)
- If 404 on browser-logger.js: File not imported in index.html
- Manually load: `import('/admin-ui/js/core/browser-logger.js').then(() => console.log('Loaded'))`
---
### Step 4: Get Diagnostic Summary
**Action**:
```javascript
window.__DSS_BROWSER_LOGS.diagnostic()
```
**Expected Result**:
```javascript
{
sessionId: "session-1733456789-xyz123",
uptime: 45230, // ms since page load
totalLogs: 127,
errorCount: 3,
warnCount: 5,
networkRequests: 12,
memory: {
usedJSHeapSize: 15728640,
jsHeapSizeLimit: 2172649472,
usagePercent: "0.72"
},
url: "https://dss.overbits.luz.uy/",
userAgent: "Mozilla/5.0...",
recentErrors: [...], // Last 5 errors
recentNetworkRequests: [...] // Last 5 requests
}
```
**Analysis**:
- `errorCount > 0`: Check recentErrors for critical issues
- `networkRequests == 0`: No API calls made (possible config issue)
- `usagePercent > 80`: Memory leak or performance issue
---
### Step 5: Retrieve Specific Log Types
**Get All Errors**:
```javascript
window.__DSS_BROWSER_LOGS.errors()
```
**Get Network Activity**:
```javascript
window.__DSS_BROWSER_LOGS.network()
```
**Get All Logs**:
```javascript
window.__DSS_BROWSER_LOGS.all()
```
**Expected Result**: Array of log entries with timestamps, levels, categories, messages, and data
**Analysis Tips**:
- Look for `level: 'error'` entries first
- Check `category: 'fetchError'` for failed API calls
- Check `status: 404` or `status: 500` in network logs
- Check `category: 'uncaughtError'` for JavaScript exceptions
---
### Step 6: Search for Specific Issues
**Search by Keyword**:
```javascript
window.__DSS_BROWSER_LOGGER.getLogs({
search: 'config', // Search term
level: 'error', // Filter by level
limit: 50 // Max results
})
```
**Search by Time Range**:
```javascript
const oneHourAgo = Date.now() - (60 * 60 * 1000);
window.__DSS_BROWSER_LOGGER.getLogs({
minTime: oneHourAgo,
limit: 100
})
```
**Expected Result**: Filtered log entries matching criteria
---
### Step 7: Export Logs for Analysis
**Export as JSON**:
```javascript
const data = window.__DSS_BROWSER_LOGS.export();
console.log(JSON.stringify(data, null, 2));
```
**Download to File**:
```javascript
const data = window.__DSS_BROWSER_LOGS.export();
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'dss-browser-logs-' + Date.now() + '.json';
a.click();
```
**Expected Result**:
- JSON export displays in console
- File downloads with name like `dss-browser-logs-1733456789000.json`
---
### Step 8: Send Logs to Server (Optional)
**Manual Upload**:
```javascript
const logs = window.__DSS_BROWSER_LOGS.export();
fetch('/api/browser-logs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(logs)
}).then(r => r.json()).then(console.log);
```
**Expected Result**:
```json
{
"status": "stored",
"sessionId": "session-1733456789-xyz123"
}
```
**Retrieve from Server**:
```bash
curl http://localhost:3456/api/browser-logs/session-1733456789-xyz123
```
---
## Common Issues and Solutions
### Issue 1: No Logs Captured
**Symptoms**: `totalLogs: 0` or empty arrays
**Causes**:
- Browser logger loaded after app initialized
- Logger not intercepting console calls
- Storage disabled (private browsing)
**Solution**:
1. Reload page with DevTools open
2. Check browser-logger.js import order (should be first)
3. Check console for storage errors
---
### Issue 2: Logs Not Persisting Across Reloads
**Symptoms**: Logs disappear on page refresh
**Causes**:
- sessionStorage disabled
- Private/Incognito mode
- Storage quota exceeded
**Solution**:
1. Check browser privacy settings
2. Use regular browsing mode
3. Clear old logs: `window.__DSS_BROWSER_LOGS.clear()`
---
### Issue 3: Network Logs Missing
**Symptoms**: `networkRequests: 0` but API calls visible in Network tab
**Causes**:
- Browser logger loaded after fetch calls
- Using XMLHttpRequest instead of fetch
- API calls made before logger init
**Solution**:
1. Ensure browser-logger.js is first script loaded
2. Reload page to capture from start
3. Check if app uses XMLHttpRequest (not currently intercepted)
---
## Success Criteria
- ✅ Diagnostic shows session info and uptime
- ✅ Logs captured for errors, warnings, network requests
- ✅ Can export logs as JSON
- ✅ Can search and filter logs
- ✅ Memory usage tracked
---
## Next Steps
After capturing browser logs:
1. **If errors found**: Use Workflow 02 (Diagnose Errors)
2. **If performance issues**: Use Workflow 03 (Debug Performance)
3. **If API failures**: Check server logs with `journalctl -u dss-api -f`
4. **If configuration issues**: Check `/api/config` endpoint response
---
## Related Documentation
- `.dss/BROWSER_LOG_CAPTURE_PROCEDURE.md` - Detailed browser logger documentation
- `.dss/GET_BROWSER_LOGS.sh` - Quick reference hook script
- `admin-ui/js/core/browser-logger.js` - Logger source code
- `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` - Overall debug architecture
---
## MCP Tool Access
**From Claude Code**:
```
Use tool: dss_get_browser_diagnostic
Or: dss_get_browser_errors
Or: dss_get_browser_network
```
These MCP tools automatically retrieve browser logs via the API layer.

View File

@@ -0,0 +1,477 @@
# Workflow 02: Diagnose Errors
**Purpose**: Systematically diagnose and resolve errors in DSS dashboard and API
**When to Use**:
- Dashboard displays error messages
- API requests failing
- JavaScript exceptions in browser
- Server health check shows degraded status
- User reports functionality not working
**Estimated Time**: 10-30 minutes
---
## Prerequisites
- Browser logs captured (use Workflow 01 if needed)
- Access to server logs (`journalctl` or log files)
- API server running
- Database accessible
---
## Step-by-Step Procedure
### Step 1: Identify Error Scope
**Action**: Determine if error is browser-side, API-side, or database-side
**Browser-Side Check**:
```javascript
// In browser console
const errors = window.__DSS_BROWSER_LOGS.errors();
console.table(errors);
```
**API-Side Check**:
```bash
# Check API health
curl http://localhost:3456/health
```
**Expected Results**:
```json
{
"status": "healthy|degraded|error",
"database": "ok|error",
"mcp": "ok|error",
"figma": "ok|not_configured|error"
}
```
**Database Check**:
```bash
sqlite3 /home/overbits/dss/.dss/dss.db "SELECT name FROM sqlite_master WHERE type='table';"
```
**Decision Matrix**:
- Browser errors only → Browser-side issue (Step 2)
- API health degraded → Server-side issue (Step 3)
- Database errors → Database issue (Step 4)
- Multiple components failing → System-wide issue (Step 5)
---
### Step 2: Diagnose Browser-Side Errors
**Get Error Details**:
```javascript
const errors = window.__DSS_BROWSER_LOGS.errors();
errors.forEach(e => {
console.group(`ERROR: ${e.message}`);
console.log('Timestamp:', new Date(e.timestamp).toLocaleString());
console.log('Category:', e.category);
console.log('Data:', e.data);
if (e.data.stack) {
console.log('Stack:', e.data.stack);
}
console.groupEnd();
});
```
**Common Browser Errors**:
#### Error Type 1: Uncaught TypeError
```javascript
{
message: "Cannot read property 'x' of undefined",
category: "uncaughtError",
data: {
filename: "/admin-ui/js/core/app.js",
lineno: 42,
colno: 15
}
}
```
**Diagnosis**:
- Variable not initialized
- API response structure unexpected
- Async timing issue
**Solution**:
1. Check line 42 in app.js
2. Add null checks before property access
3. Verify API response format
---
#### Error Type 2: Network/Fetch Error
```javascript
{
message: "GET /api/config",
category: "fetchError",
data: {
error: "Failed to fetch",
url: "/api/config"
}
}
```
**Diagnosis**:
- API endpoint not responding
- CORS issue
- Network timeout
**Solution**:
1. Check if API server running: `ps aux | grep "uvicorn.*server:app"`
2. Test endpoint directly: `curl http://localhost:3456/api/config`
3. Check server logs: `journalctl -u dss-api -n 50`
---
#### Error Type 3: Module Loading Error
```javascript
{
message: "Failed to load module script",
category: "uncaughtError",
data: {
filename: "/admin-ui/js/core/missing-module.js"
}
}
```
**Diagnosis**:
- File not found (404)
- Import path incorrect
- Module syntax error
**Solution**:
1. Check file exists: `ls -la admin-ui/js/core/missing-module.js`
2. Check import paths in HTML and JS files
3. Check browser Network tab for 404 errors
---
### Step 3: Diagnose API-Side Errors
**Check API Health**:
```bash
curl http://localhost:3456/health
```
**If degraded, check server logs**:
```bash
# Last 100 lines
journalctl -u dss-api -n 100
# Follow live logs
journalctl -u dss-api -f
# Filter for errors
journalctl -u dss-api | grep -i error
```
**Common API Errors**:
#### Error Type 1: Import Error (like previous bug)
```
[HEALTH] Database error: NameError: name 'get_connection' is not defined
```
**Diagnosis**: Missing import in server.py
**Solution**:
1. Find the function being called
2. Check imports at top of server.py
3. Add missing import
4. Restart API server: `systemctl restart dss-api`
---
#### Error Type 2: Database Connection Error
```
sqlite3.OperationalError: unable to open database file
```
**Diagnosis**:
- Database file missing
- Permission denied
- File corrupted
**Solution**:
1. Check file exists: `ls -la .dss/dss.db`
2. Check permissions: `chmod 644 .dss/dss.db`
3. Check directory permissions: `chmod 755 .dss`
4. Verify database integrity: `sqlite3 .dss/dss.db "PRAGMA integrity_check;"`
---
#### Error Type 3: Port Already in Use
```
ERROR: [Errno 98] Address already in use
```
**Diagnosis**: Another process using port 3456
**Solution**:
```bash
# Find process using port
lsof -i :3456
# Kill process
kill -9 <PID>
# Restart API server
systemctl restart dss-api
```
---
### Step 4: Diagnose Database Errors
**Check Database Health**:
```bash
sqlite3 /home/overbits/dss/.dss/dss.db << EOF
PRAGMA integrity_check;
SELECT COUNT(*) as table_count FROM sqlite_master WHERE type='table';
.tables
EOF
```
**Expected Result**:
```
ok
22
ActivityLog Components ESREDefinitions ...
```
**Common Database Errors**:
#### Error Type 1: Locked Database
```
sqlite3.OperationalError: database is locked
```
**Diagnosis**: Another process has database open
**Solution**:
```bash
# Find processes with database open
lsof | grep dss.db
# If safe, close the connection
# Or restart API server: systemctl restart dss-api
```
---
#### Error Type 2: Corrupted Database
```
PRAGMA integrity_check;
*** in database main ***
Page 123: btree page has out-of-order cells
```
**Diagnosis**: Database file corrupted
**Solution**:
```bash
# Backup first
cp .dss/dss.db .dss/dss.db.backup
# Try to recover
sqlite3 .dss/dss.db ".recover" | sqlite3 .dss/dss_recovered.db
# If successful, replace
mv .dss/dss.db .dss/dss.db.corrupted
mv .dss/dss_recovered.db .dss/dss.db
# Restart API
systemctl restart dss-api
```
---
#### Error Type 3: Missing Tables
```
sqlite3.OperationalError: no such table: Projects
```
**Diagnosis**: Database not initialized or schema changed
**Solution**:
```bash
# Check if database has any tables
sqlite3 .dss/dss.db ".tables"
# If empty, reinitialize
cd /home/overbits/dss
python3 -c "from storage.database import init_database; init_database()"
# Restart API
systemctl restart dss-api
```
---
### Step 5: Diagnose System-Wide Issues
**Check all components**:
```bash
# API server
systemctl status dss-api
# MCP server
systemctl status dss-mcp
# Database
ls -lh .dss/dss.db
# Disk space
df -h .
# Memory
free -h
```
**Common System Issues**:
#### Issue 1: Out of Disk Space
```
No space left on device
```
**Solution**:
```bash
# Find large files
du -h . | sort -h | tail -20
# Clean up logs
journalctl --vacuum-time=7d
# Clean npm cache
npm cache clean --force
```
---
#### Issue 2: Out of Memory
```
MemoryError: Unable to allocate...
```
**Solution**:
```bash
# Check memory usage
free -h
# Find memory-hungry processes
ps aux --sort=-%mem | head -10
# Restart services
systemctl restart dss-api dss-mcp
```
---
#### Issue 3: Service Not Running
```
systemctl status dss-api
● dss-api.service
Loaded: loaded
Active: failed (Result: exit-code)
```
**Solution**:
```bash
# Check why it failed
journalctl -u dss-api -n 50
# Try to start manually
cd /home/overbits/dss
uvicorn tools.api.server:app --host 0.0.0.0 --port 3456
# Check for errors in output
# If successful, restart service
systemctl restart dss-api
```
---
## Error Resolution Checklist
- [ ] Captured error message and stack trace
- [ ] Identified error scope (browser/API/database/system)
- [ ] Checked relevant logs
- [ ] Identified root cause
- [ ] Applied fix
- [ ] Restarted affected services
- [ ] Verified fix with health check
- [ ] Tested functionality in browser
- [ ] Documented issue and solution
---
## Verification Steps
After applying fix:
1. **Health Check**:
```bash
curl http://localhost:3456/health
```
Expected: `{"status": "healthy", ...}`
2. **Browser Check**:
```javascript
window.__DSS_BROWSER_LOGS.diagnostic()
```
Expected: `errorCount: 0` (or reduced)
3. **Functionality Check**: Test the specific feature that was failing
4. **Monitor**: Watch for 5-10 minutes to ensure error doesn't recur
---
## Success Criteria
- ✅ Root cause identified
- ✅ Fix applied and tested
- ✅ Health check returns "healthy"
- ✅ No new errors in browser logs
- ✅ Functionality restored
- ✅ Issue documented
---
## Next Steps
- If performance issues remain: Use Workflow 03 (Debug Performance)
- If multiple errors persist: Consider full system restart
- If complex issue: Create detailed diagnostic report
- Document solution in `.dss/KNOWN_ISSUES.md`
---
## Related Documentation
- `.dss/DSS_DIAGNOSTIC_REPORT_20251206.md` - Example diagnostic report
- `.dss/DEBUG_SESSION_SUMMARY.md` - Previous debugging session
- `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` - Debug tool architecture
---
## MCP Tool Access
**From Claude Code**:
```
Use tool: dss_get_browser_errors
Use tool: dss_get_server_diagnostic
```
These retrieve error information automatically via MCP.

View File

@@ -0,0 +1,553 @@
# Workflow 03: Debug Performance Issues
**Purpose**: Diagnose and resolve performance issues in DSS dashboard and API
**When to Use**:
- Dashboard loads slowly
- API requests taking too long
- Browser becomes unresponsive
- High memory usage warnings
- Long task warnings in logs
**Estimated Time**: 15-45 minutes
---
## Prerequisites
- Browser logger active (window.__DSS_BROWSER_LOGS available)
- Access to server logs and metrics
- Basic understanding of performance metrics
- DevTools Performance panel knowledge
---
## Step-by-Step Procedure
### Step 1: Gather Performance Baseline
**Browser Performance Metrics**:
```javascript
// Get diagnostic with performance data
const diag = window.__DSS_BROWSER_LOGS.diagnostic();
console.table({
'Uptime (ms)': diag.uptime,
'Total Logs': diag.totalLogs,
'Network Requests': diag.networkRequests,
'Memory Used (MB)': (diag.memory.usedJSHeapSize / 1024 / 1024).toFixed(2),
'Memory Limit (MB)': (diag.memory.jsHeapSizeLimit / 1024 / 1024).toFixed(2),
'Memory Usage %': diag.memory.usagePercent
});
// Get performance entries
const perfMetrics = window.__DSS_BROWSER_LOGS.getLogs({ category: 'performance' });
console.table(perfMetrics);
```
**Expected Baseline**:
- Page load: <2000ms
- DOM content loaded: <500ms
- API requests: <200ms each
- Memory usage: <50%
- No long tasks >100ms
**Performance Issues Indicators**:
- Page load >5000ms → Slow initial load (Step 2)
- API requests >1000ms → Slow API (Step 3)
- Memory usage >80% → Memory leak (Step 4)
- Multiple long tasks >100ms → CPU bottleneck (Step 5)
---
### Step 2: Diagnose Slow Page Load
**Get Page Load Metrics**:
```javascript
const perfData = performance.getEntriesByType('navigation')[0];
console.table({
'DNS Lookup (ms)': perfData.domainLookupEnd - perfData.domainLookupStart,
'TCP Connection (ms)': perfData.connectEnd - perfData.connectStart,
'Request (ms)': perfData.responseStart - perfData.requestStart,
'Response (ms)': perfData.responseEnd - perfData.responseStart,
'DOM Processing (ms)': perfData.domInteractive - perfData.domLoading,
'DOM Content Loaded (ms)': perfData.domContentLoadedEventEnd - perfData.domContentLoadedEventStart,
'Total Load (ms)': perfData.loadEventEnd - perfData.fetchStart
});
```
**Diagnosis Matrix**:
| Slow Phase | Cause | Solution |
|------------|-------|----------|
| DNS Lookup >100ms | DNS issues | Check DNS settings, use different DNS |
| TCP Connection >200ms | Network latency | Check connection, use CDN |
| Response >1000ms | Large HTML file | Minify HTML, lazy load components |
| DOM Processing >2000ms | Heavy JavaScript | Code splitting, lazy imports |
| DOM Content Loaded >500ms | Blocking scripts | Async/defer scripts, move to bottom |
**Common Fixes**:
#### Issue 1: Large Initial Bundle
```javascript
// Check resource sizes
performance.getEntriesByType('resource').forEach(r => {
if (r.transferSize > 100000) { // >100KB
console.log(`Large file: ${r.name} (${(r.transferSize / 1024).toFixed(2)} KB)`);
}
});
```
**Solution**:
- Split large JavaScript files
- Use code splitting with dynamic imports
- Compress assets (gzip/brotli)
---
#### Issue 2: Blocking Scripts
```html
<!-- Bad: Blocking -->
<script src="/admin-ui/js/app.js"></script>
<!-- Good: Async -->
<script src="/admin-ui/js/app.js" defer></script>
<script type="module" src="/admin-ui/js/app.js"></script>
```
---
### Step 3: Diagnose Slow API Requests
**Get Network Performance**:
```javascript
const network = window.__DSS_BROWSER_LOGS.network();
const slowRequests = network.filter(r => r.data.duration > 500);
console.group('Slow Requests (>500ms)');
console.table(slowRequests.map(r => ({
URL: r.data.url,
Method: r.data.method,
Status: r.data.status,
Duration: r.data.duration + 'ms'
})));
console.groupEnd();
```
**Server-Side Check**:
```bash
# Check API response times in server logs
journalctl -u dss-api -n 200 | grep "INFO.*GET\|POST"
# Check database query times (if logged)
journalctl -u dss-api -n 200 | grep "query took"
```
**Common Slow API Issues**:
#### Issue 1: Database Query Slow (N+1 Problem)
```python
# Bad: N+1 queries
for project in projects:
components = get_components(project.id) # Separate query each time
# Good: Single query with JOIN
components = get_all_components_with_projects()
```
**Diagnosis**:
```bash
# Enable SQLite query logging
sqlite3 .dss/dss.db
.log stdout
.timer on
SELECT * FROM Projects;
```
**Solution**:
- Use JOINs instead of multiple queries
- Add indexes on frequently queried columns
- Cache repeated queries
---
#### Issue 2: Large Response Payload
```javascript
// Check response sizes
network.forEach(r => {
if (r.data.headers && r.data.headers['content-length']) {
const sizeKB = parseInt(r.data.headers['content-length']) / 1024;
if (sizeKB > 100) {
console.log(`Large response: ${r.data.url} (${sizeKB.toFixed(2)} KB)`);
}
}
});
```
**Solution**:
- Implement pagination (limit results to 50-100 items)
- Use field selection (only return needed fields)
- Compress responses (gzip)
- Add API caching
---
#### Issue 3: Synchronous Processing
```python
# Bad: Synchronous heavy processing
def get_analysis():
data = fetch_all_data()
analysis = process_data(data) # Blocking, takes 5 seconds
return analysis
# Good: Async or background job
async def get_analysis():
data = await fetch_all_data()
# Trigger background job, return immediately
job_id = queue_analysis(data)
return {"status": "processing", "job_id": job_id}
```
---
### Step 4: Diagnose Memory Leaks
**Check Memory Usage**:
```javascript
// Get current memory
const mem = performance.memory;
console.table({
'Used (MB)': (mem.usedJSHeapSize / 1024 / 1024).toFixed(2),
'Total (MB)': (mem.totalJSHeapSize / 1024 / 1024).toFixed(2),
'Limit (MB)': (mem.jsHeapSizeLimit / 1024 / 1024).toFixed(2),
'Usage %': ((mem.usedJSHeapSize / mem.jsHeapSizeLimit) * 100).toFixed(2)
});
// Monitor over time
let memorySnapshots = [];
setInterval(() => {
const m = performance.memory;
memorySnapshots.push({
time: Date.now(),
used: m.usedJSHeapSize
});
if (memorySnapshots.length > 20) memorySnapshots.shift();
// Check if memory is growing
const first = memorySnapshots[0].used;
const last = memorySnapshots[memorySnapshots.length - 1].used;
const growth = ((last - first) / first * 100).toFixed(2);
console.log(`Memory growth over ${memorySnapshots.length} checks: ${growth}%`);
}, 5000);
```
**Memory Leak Indicators**:
- Memory usage steadily increasing (>10% per minute)
- Memory warnings in browser logs
- Browser becoming slow/unresponsive over time
**Common Memory Leak Causes**:
#### Cause 1: Event Listeners Not Removed
```javascript
// Bad: Creates new listener on each render, never removes
function render() {
window.addEventListener('resize', handleResize);
}
// Good: Remove old listener
let resizeHandler = null;
function render() {
if (resizeHandler) {
window.removeEventListener('resize', resizeHandler);
}
resizeHandler = handleResize;
window.addEventListener('resize', resizeHandler);
}
```
---
#### Cause 2: Detached DOM Nodes
```javascript
// Bad: References keep DOM nodes in memory
let cachedNodes = [];
function cacheNode(node) {
cachedNodes.push(node); // Node stays in memory even if removed from DOM
}
// Good: Use WeakMap for node cache
let cachedNodes = new WeakMap();
function cacheNode(node, data) {
cachedNodes.set(node, data); // Auto-removed when node is GC'd
}
```
---
#### Cause 3: Timers Not Cleared
```javascript
// Bad: Timer keeps running even after component unmounted
setInterval(() => {
updateData();
}, 1000);
// Good: Clear timer on unmount
let timerId = null;
function startTimer() {
timerId = setInterval(updateData, 1000);
}
function stopTimer() {
if (timerId) clearInterval(timerId);
}
```
**Diagnosis Tools**:
1. Chrome DevTools → Memory → Take heap snapshot
2. Compare snapshots over time
3. Look for "Detached DOM tree" entries
4. Find objects growing in number
---
### Step 5: Diagnose CPU Bottlenecks
**Get Long Tasks**:
```javascript
const longTasks = window.__DSS_BROWSER_LOGS.getLogs({
category: 'longTask',
limit: 50
});
console.group('Long Tasks (>50ms)');
console.table(longTasks.map(t => ({
Name: t.data.name,
Duration: t.data.duration.toFixed(2) + 'ms',
Time: new Date(t.timestamp).toLocaleTimeString()
})));
console.groupEnd();
```
**Performance Profiling**:
1. Open DevTools → Performance
2. Click Record
3. Perform slow action
4. Stop recording
5. Analyze flame graph for long tasks
**Common CPU Bottlenecks**:
#### Issue 1: Synchronous Loop Over Large Array
```javascript
// Bad: Blocks UI for large arrays
function processItems(items) {
items.forEach(item => {
expensiveOperation(item); // If items.length = 10000, UI freezes
});
}
// Good: Batch processing with breaks
async function processItems(items) {
const batchSize = 100;
for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
batch.forEach(item => expensiveOperation(item));
await new Promise(resolve => setTimeout(resolve, 0)); // Give UI a break
}
}
```
---
#### Issue 2: Frequent DOM Manipulation
```javascript
// Bad: Multiple reflows
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
container.appendChild(div); // Reflow on each append
}
// Good: Single reflow with fragment
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const div = document.createElement('div');
div.textContent = i;
fragment.appendChild(div);
}
container.appendChild(fragment); // Single reflow
```
---
#### Issue 3: Inefficient Rendering
```javascript
// Bad: Re-render entire list on every change
function renderList(items) {
container.innerHTML = ''; // Destroy all
items.forEach(item => {
container.appendChild(createItem(item)); // Recreate all
});
}
// Good: Update only changed items (use virtual DOM or diff)
function renderList(items, previousItems) {
const changes = diff(items, previousItems);
changes.forEach(change => {
if (change.type === 'add') {
container.appendChild(createItem(change.item));
} else if (change.type === 'remove') {
change.element.remove();
} else if (change.type === 'update') {
updateItem(change.element, change.item);
}
});
}
```
---
### Step 6: Server-Side Performance Check
**Check Server Resource Usage**:
```bash
# CPU usage
top -b -n 1 | grep "uvicorn\|python"
# Memory usage
ps aux --sort=-%mem | grep "uvicorn\|python" | head -5
# Disk I/O
iostat -x 1 5
# Network
iftop -t -s 10
```
**Check Database Performance**:
```bash
# Database size
ls -lh .dss/dss.db
# Table sizes
sqlite3 .dss/dss.db << EOF
SELECT name, COUNT(*) as row_count
FROM sqlite_master sm
LEFT JOIN pragma_table_info(sm.name) ON 1=1
WHERE sm.type='table'
GROUP BY name;
EOF
# Check for missing indexes
sqlite3 .dss/dss.db << EOF
SELECT name, sql FROM sqlite_master
WHERE type='index' AND sql IS NOT NULL;
EOF
```
**Database Optimization**:
```bash
# Vacuum to reclaim space and reorganize
sqlite3 .dss/dss.db "VACUUM;"
# Analyze to update statistics
sqlite3 .dss/dss.db "ANALYZE;"
# Check index usage (run slow query with EXPLAIN QUERY PLAN)
sqlite3 .dss/dss.db << EOF
EXPLAIN QUERY PLAN
SELECT * FROM Projects WHERE name LIKE '%test%';
EOF
```
---
## Performance Optimization Checklist
### Browser Optimizations
- [ ] Code splitting implemented
- [ ] Lazy loading for routes/components
- [ ] Images optimized and lazy-loaded
- [ ] Scripts deferred or async
- [ ] CSS minified and critical CSS inlined
- [ ] Service worker for caching
- [ ] Event listeners properly cleaned up
- [ ] No memory leaks detected
### API Optimizations
- [ ] Database queries optimized (indexes, JOINs)
- [ ] Response pagination implemented
- [ ] API caching enabled
- [ ] Compression enabled (gzip/brotli)
- [ ] Connection pooling configured
- [ ] Async processing for heavy tasks
- [ ] Rate limiting to prevent abuse
### System Optimizations
- [ ] Database vacuumed and analyzed
- [ ] Log rotation configured
- [ ] Disk space sufficient (>20% free)
- [ ] Memory sufficient (>30% free)
- [ ] Supervisord restart policies configured
---
## Success Criteria
- ✅ Page load <2000ms
- ✅ API requests <200ms
- ✅ Memory usage <50%
- ✅ No long tasks >100ms
- ✅ No memory growth over time
- ✅ Smooth scrolling and interactions
---
## Performance Metrics to Track
**Browser**:
- First Contentful Paint (FCP): <1000ms
- Largest Contentful Paint (LCP): <2500ms
- Time to Interactive (TTI): <3000ms
- Total Blocking Time (TBT): <200ms
- Cumulative Layout Shift (CLS): <0.1
**API**:
- Response time p50: <100ms
- Response time p95: <500ms
- Response time p99: <1000ms
- Throughput: >100 req/sec
- Error rate: <1%
**Database**:
- Query time p50: <10ms
- Query time p95: <50ms
- Query time p99: <100ms
- Connection pool usage: <80%
---
## Next Steps
- If performance acceptable: Document baseline for monitoring
- If still slow: Use Chrome Performance Profiler for deeper analysis
- If database slow: Consider adding indexes or caching layer
- If memory leaks: Use Chrome Memory Profiler to find retaining paths
- Schedule regular performance audits (monthly)
---
## Related Documentation
- `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` - Performance monitoring in MCP
- `admin-ui/js/core/browser-logger.js` - Performance capture implementation
- Web Vitals: https://web.dev/vitals/
---
## MCP Tool Access
**From Claude Code**:
```
Use tool: dss_get_browser_diagnostic (includes memory metrics)
Use tool: dss_get_server_diagnostic (includes performance metrics)
```

View File

@@ -0,0 +1,533 @@
# Workflow 04: Debug Workflow Execution
**Purpose**: Meta-workflow for debugging the workflow system itself and MCP tool integration
**When to Use**:
- Workflow execution fails
- MCP tools not responding
- Workflow steps don't produce expected results
- API endpoints returning errors
- Communication between layers broken
**Estimated Time**: 10-20 minutes
---
## Prerequisites
- Understanding of 3-layer architecture (Browser → API → MCP)
- Access to server logs
- MCP server running
- API server running
---
## Architecture Overview
```
┌─────────────────────────────────────────────────────────────┐
│ Layer 1: Browser (JavaScript) │
│ - browser-logger.js: Captures logs → sessionStorage │
│ - window.__DSS_BROWSER_LOGS API │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Layer 2: API Server (Python/FastAPI) │
│ - POST /api/browser-logs: Receive logs from browser │
│ - GET /api/browser-logs/:id: Retrieve logs │
│ - GET /api/debug/diagnostic: System status │
│ - GET /api/debug/workflows: List workflows │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Layer 3: MCP Server (Python/MCP) │
│ - dss_get_browser_diagnostic: Get browser summary │
│ - dss_get_browser_errors: Get browser errors │
│ - dss_get_browser_network: Get network requests │
│ - dss_get_server_diagnostic: Get server health │
│ - dss_run_workflow: Execute workflow │
│ - dss_list_workflows: List available workflows │
└─────────────────────────────────────────────────────────────┘
```
---
## Step-by-Step Procedure
### Step 1: Verify All Services Running
**Check API Server**:
```bash
# Check if running
systemctl status dss-api
# Or check process
ps aux | grep "uvicorn.*tools.api.server:app"
# Check port listening
lsof -i :3456
```
**Expected**:
```
● dss-api.service - DSS API Server
Loaded: loaded
Active: active (running)
```
**If not running**:
```bash
# Start service
systemctl start dss-api
# Or run manually for debugging
cd /home/overbits/dss
uvicorn tools.api.server:app --host 0.0.0.0 --port 3456
```
---
**Check MCP Server**:
```bash
# Check if running
systemctl status dss-mcp
# Or check process
ps aux | grep "tools.dss_mcp.server"
# Check port listening
lsof -i :3457
```
**Expected**:
```
● dss-mcp.service - DSS MCP Server
Loaded: loaded
Active: active (running)
```
**If not running**:
```bash
# Start service
systemctl start dss-mcp
# Or run manually for debugging
cd /home/overbits/dss
python3 -m tools.dss_mcp.server
```
---
### Step 2: Test Each Layer Independently
**Layer 1 - Browser Test**:
```javascript
// In browser console at https://dss.overbits.luz.uy/
// Check logger loaded
console.log(window.__DSS_BROWSER_LOGS ? '✅ Logger loaded' : '❌ Logger not loaded');
// Test logging
console.log('Test log');
console.error('Test error');
// Check logs captured
const logs = window.__DSS_BROWSER_LOGS.all();
console.log(`Captured ${logs.length} logs`);
// Test export
const exported = window.__DSS_BROWSER_LOGS.export();
console.log('Export structure:', Object.keys(exported));
```
**Expected**:
```
✅ Logger loaded
Captured 5 logs
Export structure: ["sessionId", "exportedAt", "logs", "diagnostic"]
```
---
**Layer 2 - API Test**:
```bash
# Test health endpoint
curl http://localhost:3456/health
# Test debug diagnostic
curl http://localhost:3456/api/debug/diagnostic
# Test workflows list
curl http://localhost:3456/api/debug/workflows
# Test browser logs receive (POST)
curl -X POST http://localhost:3456/api/browser-logs \
-H "Content-Type: application/json" \
-d '{
"sessionId": "test-123",
"logs": [{"level": "log", "message": "test"}]
}'
# Test browser logs retrieve (GET)
curl http://localhost:3456/api/browser-logs/test-123
```
**Expected**:
```json
{"status": "healthy", "database": "ok", "mcp": "ok"}
{"status": "healthy", "browser_sessions": 1, ...}
{"workflows": ["01-capture-browser-logs", ...]}
{"status": "stored", "sessionId": "test-123"}
{"sessionId": "test-123", "logs": [...]}
```
---
**Layer 3 - MCP Test**:
```bash
# Test MCP server directly (if running on localhost:3457)
curl http://localhost:3457/tools
# Or use Claude Code to test MCP tools
# (These are available as mcp__dss__get_browser_diagnostic etc.)
```
**Expected**: List of available MCP tools
---
### Step 3: Test Data Flow End-to-End
**Full Flow Test**:
1. **Generate browser logs**:
```javascript
// In browser console
console.log('Flow test: Step 1');
console.error('Flow test: Error');
fetch('/api/config');
```
2. **Export from browser**:
```javascript
const logs = window.__DSS_BROWSER_LOGS.export();
console.log('Exported', logs.logs.length, 'logs');
```
3. **Upload to API**:
```javascript
fetch('/api/browser-logs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(logs)
}).then(r => r.json()).then(result => {
console.log('Uploaded:', result.sessionId);
return result.sessionId;
});
```
4. **Retrieve via API**:
```bash
# Use session ID from step 3
curl http://localhost:3456/api/browser-logs/<SESSION_ID>
```
5. **Access via MCP** (from Claude Code):
```
Use tool: dss_get_browser_diagnostic
```
**Expected**: Data flows through all 3 layers successfully
---
### Step 4: Debug Common Workflow Issues
#### Issue 1: Workflow Not Found
**Symptoms**:
```bash
curl http://localhost:3456/api/debug/workflows
# Returns empty array or missing workflow
```
**Diagnosis**:
```bash
# Check if workflow files exist
ls -la /home/overbits/dss/.dss/WORKFLOWS/
# Check file permissions
chmod 644 .dss/WORKFLOWS/*.md
```
**Solution**:
- Ensure workflow .md files exist in `.dss/WORKFLOWS/`
- Check filenames match expected pattern: `NN-workflow-name.md`
- Restart API server to reload workflow list
---
#### Issue 2: MCP Tool Returns Error
**Symptoms**:
```
Error: Connection refused
Error: Tool not found
Error: Invalid parameters
```
**Diagnosis**:
```bash
# Check MCP server logs
journalctl -u dss-mcp -n 50
# Check API server logs
journalctl -u dss-api -n 50
# Test API endpoint directly
curl http://localhost:3456/api/debug/diagnostic
```
**Solution**:
- If connection refused: Start MCP server
- If tool not found: Check tool registration in `tools/dss_mcp/server.py`
- If invalid parameters: Check tool schema matches input
- Check for Python exceptions in logs
---
#### Issue 3: Browser Logs Not Captured
**Symptoms**:
```javascript
window.__DSS_BROWSER_LOGS.all()
// Returns []
```
**Diagnosis**:
```javascript
// Check if logger initialized
console.log(window.__DSS_BROWSER_LOGGER);
// Check sessionStorage
console.log(sessionStorage.getItem('dss-browser-logs-' + window.__DSS_BROWSER_LOGGER?.sessionId));
// Check for errors
window.__DSS_BROWSER_LOGS.errors();
```
**Solution**:
- If logger undefined: Import browser-logger.js in HTML
- If sessionStorage empty: Check browser privacy settings
- If capturing but not storing: Check storage quota
- Force reload with DevTools open
---
#### Issue 4: API Endpoint Not Found
**Symptoms**:
```bash
curl http://localhost:3456/api/debug/diagnostic
# 404 Not Found
```
**Diagnosis**:
```bash
# Check if endpoint registered in server.py
grep -n "debug/diagnostic" tools/api/server.py
# Check API server started correctly
journalctl -u dss-api -n 20 | grep -i error
# Check routes registered
curl http://localhost:3456/docs
# (FastAPI auto-generated docs)
```
**Solution**:
- If endpoint not in code: Add endpoint to `tools/api/server.py`
- If server error: Fix error and restart
- If routes not registered: Check decorator syntax (`@app.get(...)`)
---
### Step 5: Verify Workflow Execution
**Test Workflow Execution**:
```bash
# List available workflows
curl http://localhost:3456/api/debug/workflows
# Execute a workflow (when implemented)
curl -X POST http://localhost:3456/api/debug/workflows/01-capture-browser-logs
```
**Or via MCP**:
```
Use tool: dss_list_workflows
Use tool: dss_run_workflow with workflow_name="01-capture-browser-logs"
```
**Expected**: Workflow steps execute in order and return results
---
### Step 6: Check Persistence (Supervisord)
**Verify Services Auto-Restart**:
```bash
# Check supervisor status
supervisorctl status
# Test auto-restart
supervisorctl stop dss-api
sleep 5
supervisorctl status dss-api # Should auto-restart
# Check supervisor logs
tail -f /var/log/supervisor/dss-api-stdout.log
tail -f /var/log/supervisor/dss-mcp-stdout.log
```
**Expected**:
```
dss-api RUNNING pid 12345, uptime 0:00:05
dss-mcp RUNNING pid 12346, uptime 0:00:05
```
---
## Debugging Checklist
- [ ] API server running and accessible on port 3456
- [ ] MCP server running and accessible on port 3457
- [ ] Browser logger loaded in dashboard
- [ ] API health endpoint returns "healthy"
- [ ] API debug endpoints respond correctly
- [ ] Workflow files exist in `.dss/WORKFLOWS/`
- [ ] MCP tools registered and accessible
- [ ] Data flows from browser → API → MCP
- [ ] Supervisord manages services
- [ ] Services auto-restart on failure
---
## Common Error Messages
### "NameError: name 'get_connection' is not defined"
**Cause**: Missing import in server.py
**Solution**: Add to imports: `from storage.database import get_connection`
### "ModuleNotFoundError: No module named 'tools.dss_mcp.tools.debug_tools'"
**Cause**: debug_tools.py not created or not in path
**Solution**: Create `tools/dss_mcp/tools/debug_tools.py` with tool definitions
### "Address already in use"
**Cause**: Port 3456 or 3457 already in use
**Solution**: Find and kill process: `lsof -i :3456` then `kill -9 <PID>`
### "sessionStorage is not defined"
**Cause**: Running in Node.js or non-browser environment
**Solution**: Only use browser logger in actual browser context
### "Cannot read property 'diagnostic' of undefined"
**Cause**: Browser logger not loaded
**Solution**: Import browser-logger.js before other scripts
---
## Success Criteria
- ✅ All services running (API, MCP)
- ✅ Each layer tested independently
- ✅ End-to-end data flow working
- ✅ Workflows executable
- ✅ MCP tools accessible from Claude Code
- ✅ Auto-restart working via supervisord
- ✅ No errors in logs
---
## Workflow Development Guide
**Creating New Workflows**:
1. Create `.dss/WORKFLOWS/NN-workflow-name.md`
2. Use this template:
```markdown
# Workflow NN: Title
**Purpose**: What this workflow does
**When to Use**: Scenarios
**Estimated Time**: X-Y minutes
---
## Prerequisites
- Required conditions
- Required tools
---
## Step-by-Step Procedure
### Step 1: Title
**Action**: What to do
**Expected Result**: What should happen
**Troubleshooting**: If issues occur
### Step 2: Title
...
---
## Success Criteria
- ✅ Criterion 1
- ✅ Criterion 2
---
## Related Documentation
- Link 1
- Link 2
```
3. Test workflow manually following steps
4. Document actual results and refine
5. Restart API server to load new workflow
---
## Next Steps
- If all layers working: Workflows are ready to use
- If issues found: Document in `.dss/KNOWN_ISSUES.md`
- If new workflow needed: Create following template above
- Regular testing: Run this workflow monthly to verify system health
---
## Related Documentation
- `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` - Complete architecture spec
- `.dss/WORKFLOWS/01-capture-browser-logs.md` - Browser log workflow
- `.dss/WORKFLOWS/02-diagnose-errors.md` - Error diagnosis workflow
- `.dss/WORKFLOWS/03-debug-performance.md` - Performance workflow
---
## MCP Tool Access
**From Claude Code**:
```
Use tool: dss_list_workflows
Use tool: dss_run_workflow
Use tool: dss_get_server_diagnostic
```
These tools enable workflow execution and debugging from Claude Code.

262
.dss/WORKFLOWS/README.md Normal file
View File

@@ -0,0 +1,262 @@
# DSS Debug Workflows
**Purpose**: Step-by-step procedures for common debugging tasks in Design System Swarm
**How to Use**: Each workflow is a standalone markdown document with:
- Clear prerequisites
- Step-by-step instructions with console commands
- Expected results for each step
- Troubleshooting guidance
- Success criteria
---
## Available Workflows
### [01 - Capture Browser Logs](01-capture-browser-logs.md)
**Purpose**: Capture and retrieve all browser-side logs from DSS dashboard
**When to Use**:
- User reports dashboard not loading
- JavaScript errors in browser
- Network request failures
- Performance issues
**Estimated Time**: 2-5 minutes
**Key Steps**:
1. Open dashboard and DevTools
2. Verify browser logger loaded
3. Get diagnostic summary
4. Retrieve specific log types
5. Export logs for analysis
---
### [02 - Diagnose Errors](02-diagnose-errors.md)
**Purpose**: Systematically diagnose and resolve errors in DSS dashboard and API
**When to Use**:
- Dashboard displays error messages
- API requests failing
- Server health check shows degraded status
- User reports functionality not working
**Estimated Time**: 10-30 minutes
**Key Steps**:
1. Identify error scope (browser/API/database/system)
2. Diagnose browser-side errors
3. Diagnose API-side errors
4. Diagnose database errors
5. Diagnose system-wide issues
6. Verify fix
---
### [03 - Debug Performance](03-debug-performance.md)
**Purpose**: Diagnose and resolve performance issues in DSS dashboard and API
**When to Use**:
- Dashboard loads slowly
- API requests taking too long
- Browser becomes unresponsive
- High memory usage warnings
**Estimated Time**: 15-45 minutes
**Key Steps**:
1. Gather performance baseline
2. Diagnose slow page load
3. Diagnose slow API requests
4. Diagnose memory leaks
5. Diagnose CPU bottlenecks
6. Server-side performance check
---
### [04 - Workflow Debugging](04-workflow-debugging.md)
**Purpose**: Debug the workflow system itself and MCP tool integration
**When to Use**:
- Workflow execution fails
- MCP tools not responding
- API endpoints returning errors
- Communication between layers broken
**Estimated Time**: 10-20 minutes
**Key Steps**:
1. Verify all services running
2. Test each layer independently
3. Test data flow end-to-end
4. Debug common workflow issues
5. Verify workflow execution
6. Check persistence (supervisord)
---
## Quick Reference
### Access from Command Line
```bash
# View workflow list
ls -1 /home/overbits/dss/.dss/WORKFLOWS/*.md
# Read a workflow
cat /home/overbits/dss/.dss/WORKFLOWS/01-capture-browser-logs.md
# Quick hook for browser logs
/home/overbits/dss/.dss/GET_BROWSER_LOGS.sh
```
### Access from API
```bash
# List workflows
curl http://localhost:3456/api/debug/workflows
# Execute workflow (when implemented)
curl -X POST http://localhost:3456/api/debug/workflows/01-capture-browser-logs
```
### Access from MCP (Claude Code)
```
Use tool: dss_list_workflows
Use tool: dss_run_workflow with workflow_name="01-capture-browser-logs"
```
---
## Workflow Categories
### User-Facing Issues
- **01 - Capture Browser Logs**: First step for any dashboard issue
- **02 - Diagnose Errors**: When specific errors occur
### Performance Issues
- **03 - Debug Performance**: Slow loading, high memory, CPU bottlenecks
### System Issues
- **04 - Workflow Debugging**: When the debug tools themselves fail
---
## Architecture Context
These workflows operate within the 3-layer debug architecture:
```
┌──────────────────────────────────────────┐
│ Layer 1: Browser (JavaScript) │
│ - browser-logger.js captures logs │
│ - window.__DSS_BROWSER_LOGS API │
└──────────────────────────────────────────┘
┌──────────────────────────────────────────┐
│ Layer 2: API Server (FastAPI) │
│ - /api/browser-logs endpoints │
│ - /api/debug/* endpoints │
└──────────────────────────────────────────┘
┌──────────────────────────────────────────┐
│ Layer 3: MCP Server (Python/MCP) │
│ - dss_get_browser_diagnostic │
│ - dss_get_browser_errors │
│ - dss_run_workflow │
└──────────────────────────────────────────┘
```
See `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` for complete architecture details.
---
## Development Guide
### Creating New Workflows
1. **Choose Number**: Next sequential number (05, 06, etc.)
2. **Create File**: `.dss/WORKFLOWS/NN-workflow-name.md`
3. **Use Template**: See workflow 04 for template structure
4. **Include**:
- Purpose and when to use
- Prerequisites
- Step-by-step instructions with commands
- Expected results for each step
- Troubleshooting guidance
- Success criteria
- Related documentation
5. **Test**: Run through workflow manually
6. **Refine**: Update based on actual experience
7. **Restart API**: To load new workflow in system
### Workflow Template Structure
```markdown
# Workflow NN: Title
**Purpose**: Brief description
**When to Use**: Scenarios
**Estimated Time**: X-Y minutes
---
## Prerequisites
- Required items
---
## Step-by-Step Procedure
### Step 1: Title
**Action**: Commands or actions
**Expected Result**: What should happen
**Troubleshooting**: If issues occur
---
## Success Criteria
- ✅ Checkpoints
---
## Related Documentation
- Links to related docs
```
---
## Maintenance
### Regular Testing
- Run workflow 04 monthly to verify system health
- Update workflows when architecture changes
- Add new workflows for recurring issues
### Update Triggers
- New debug tools added
- Architecture changes
- New common issues discovered
- User feedback on workflows
---
## Related Documentation
- `.dss/MCP_DEBUG_TOOLS_ARCHITECTURE.md` - Complete MCP integration architecture
- `.dss/BROWSER_LOG_CAPTURE_PROCEDURE.md` - Browser logger details
- `.dss/GET_BROWSER_LOGS.sh` - Quick reference hook
- `.dss/DSS_DIAGNOSTIC_REPORT_20251206.md` - Example diagnostic report
- `.dss/DEBUG_SESSION_SUMMARY.md` - Previous debug session
---
## Implementation Status
-**Workflow 01**: Capture Browser Logs - Complete
-**Workflow 02**: Diagnose Errors - Complete
-**Workflow 03**: Debug Performance - Complete
-**Workflow 04**: Workflow Debugging - Complete
-**API Integration**: Endpoints need implementation
-**MCP Integration**: Tools need implementation
-**Supervisord**: Service configs need creation
See architecture doc for full implementation checklist.