# DSS PowerTools: Adaptive Plugin Architecture

**Unified LOCAL/REMOTE Design System Development Tools**

---

## Executive Summary

**Vision**: A single Claude Code plugin that gives developers "superpowers" for design system work in both LOCAL (direct machine access) and REMOTE (server-based) modes.

**Key Innovation**: Adaptive Strategy Pattern that provides identical UX while routing to mode-specific implementations.

**Timeline**: 20 days (4 weeks)

**Current Assets**:
- Browser-logger.js with auto-sync (DONE)
- API server with browser log endpoints (DONE)
- Debug MCP tools (DONE)
- Task queue integration (DONE)
- dss-claude-plugin structure (EXISTS)

---

## Architecture Overview

```
┌─────────────────────────────────────────────────────────────┐
│                    DSS PowerTools Plugin                     │
│                                                              │
│  ┌────────────────────────────────────────────────────┐    │
│  │              Core Foundation                        │    │
│  │  - DSSConfig (mode detection)                      │    │
│  │  - DSSContext (singleton, capabilities)            │    │
│  │  - Strategy Registry (factory pattern)             │    │
│  └────────────────────────────────────────────────────┘    │
│                          │                                   │
│         ┌────────────────┴────────────────┐                 │
│         │                                 │                 │
│  ┌──────▼──────┐                  ┌──────▼──────┐         │
│  │ LOCAL Mode  │                  │ REMOTE Mode │         │
│  │             │                  │             │         │
│  │ Playwright  │                  │ HTTP API    │         │
│  │ CDP         │                  │ Browser-Log │         │
│  │ Filesystem  │                  │ Shadow State│         │
│  │ Screenshots │                  │ Server API  │         │
│  └─────────────┘                  └─────────────┘         │
│                                                              │
│  Same Commands │ Different Implementations                  │
└─────────────────────────────────────────────────────────────┘
```

---

## Mode Comparison

| Feature | LOCAL Mode | REMOTE Mode |
|---------|------------|-------------|
| **Browser Access** | Chrome DevTools Protocol (CDP) | browser-logger.js auto-sync |
| **Screenshots** | Playwright (local capture) | Server-side Playwright API |
| **File Access** | Direct filesystem | Upload to API / Git sync |
| **Storybook** | localhost:6006 | Server-hosted instance |
| **Real-time Debug** | Live CDP connection | Historical logs + Shadow State |
| **Setup Complexity** | Chrome with --remote-debugging-port | Just network access |
| **Offline Support** | Full functionality | Limited to cached data |
| **Best For** | Active development | Code review, monitoring, remote teams |

---

## Implementation Phases

### Phase 1: Core Foundation (Days 1-3)

**Objective**: Build mode-aware infrastructure without breaking existing functionality

**Day 1**: Mode Detection
```python
# dss-claude-plugin/core/config.py
class DSSConfig(BaseModel):
    mode: Literal["local", "remote", "auto"] = "auto"

    @classmethod
    async def detect_mode(cls):
        # 1. Check DSS_MODE env var
        # 2. Check ~/.dss/config.json
        # 3. Ping localhost:6006 (API health)
        # 4. Default to "remote" (safer)
```

**Day 2**: Context Manager
```python
# dss-claude-plugin/core/context.py
class DSSContext:
    _instance = None  # Singleton

    async def initialize(self):
        self.mode = await DSSConfig.detect_mode()
        await self._verify_capabilities()

    def get_strategy(self, strategy_type: str):
        # Factory: returns LOCAL or REMOTE strategy
```

**Day 3**: Strategy Interfaces
```python
# dss-claude-plugin/strategies/base.py
class BrowserStrategy(ABC):
    @abstractmethod
    async def get_console_logs(...) -> List[Dict]: ...

    @abstractmethod
    async def capture_screenshot(...) -> str: ...

    @abstractmethod
    async def get_dom_snapshot() -> str: ...
```

**Deliverables**:
- [ ] config.py with mode detection (80% test coverage)
- [ ] context.py singleton with capabilities
- [ ] base.py with all strategy ABCs
- [ ] Unit tests passing

---

### Phase 2: LOCAL Mode Implementation (Days 4-7)

**Objective**: Enable local development superpowers

**Key Technologies**:
- Playwright (browser automation)
- Chrome DevTools Protocol (real-time access)
- Direct filesystem access

**Day 4-5**: Playwright Integration
```python
# strategies/local/browser.py
class LocalBrowserStrategy(BrowserStrategy):
    async def connect(self):
        # Connect to localhost:9222 (Chrome CDP)
        p = await async_playwright().start()
        self.browser = await p.chromium.connect_over_cdp("localhost:9222")

    async def capture_screenshot(self, selector=None):
        # Capture directly from local browser
        path = Path.home() / ".dss" / "screenshots" / f"{uuid.uuid4()}.png"
        await self.page.screenshot(path=str(path))
        return str(path)
```

**Day 6-7**: Testing & Filesystem Strategy

**Deliverables**:
- [ ] Playwright browser control working
- [ ] CDP real-time console access
- [ ] Local screenshot capture
- [ ] Filesystem scanning strategy

---

### Phase 3: REMOTE Mode Implementation (Days 8-12)

**Objective**: Leverage existing browser-logger.js and create Shadow State

**Key Innovation from Gemini 3 Pro**: "Shadow State Pattern"
- Browser captures DOM snapshots on errors/navigation
- Server stores snapshots alongside logs
- Tools query "most recent state" like it's real-time

**Day 8-10**: Shadow State Implementation
```javascript
// admin-ui/js/core/browser-logger.js (enhancement)
class BrowserLogger {
    captureDOMSnapshot() {
        return {
            html: document.documentElement.outerHTML,
            url: window.location.href,
            timestamp: Date.now(),
            viewport: {width: window.innerWidth, height: window.innerHeight}
        };
    }

    setupSnapshotCapture() {
        // On error: immediate snapshot + sync
        window.addEventListener('error', () => {
            this.log('snapshot', 'error', 'DOM Snapshot', {
                snapshot: this.captureDOMSnapshot()
            });
            this.syncToServer();  // Beacon for reliability
        });

        // On navigation: capture new state
        let lastUrl = location.href;
        setInterval(() => {
            if (location.href !== lastUrl) {
                lastUrl = location.href;
                this.log('snapshot', 'navigation', 'Page Changed', {
                    snapshot: this.captureDOMSnapshot()
                });
            }
        }, 1000);
    }
}
```

**Day 11-12**: Remote Strategy Implementation
```python
# strategies/remote/browser.py
class RemoteBrowserStrategy(BrowserStrategy):
    async def get_console_logs(self, session_id=None):
        # Query API for browser logs
        url = f"{self.api_url}/api/browser-logs/{session_id or 'latest'}"
        resp = await self.client.get(url)
        return resp.json().get("logs", [])

    async def get_dom_snapshot(self):
        # Get Shadow State (most recent snapshot)
        logs = await self.get_console_logs()
        snapshots = [l for l in logs if l.get("category") == "snapshot"]
        if snapshots:
            return snapshots[-1]["data"]["snapshot"]["html"]
        return "<html><body>No snapshot available</body></html>"
```

**Deliverables**:
- [ ] Shadow State working in browser-logger.js
- [ ] DOM snapshots captured on errors/navigation
- [ ] Remote strategy fetching logs via API
- [ ] Server-side screenshot API endpoint (NEW)

---

### Phase 4: Unified Commands & Testing (Days 13-16)

**Objective**: Make all commands mode-aware with seamless UX

**Day 13**: Command Unification
```python
# Example: /dss-screenshot command
async def handle_screenshot(args):
    ctx = await DSSContext.get_instance()

    # Get strategy for current mode
    browser_strategy = ctx.get_strategy("browser")

    # Same interface, different implementation
    screenshot = await browser_strategy.capture_screenshot(
        selector=args.get("selector"),
        full_page=args.get("fullpage", False)
    )

    return {
        "mode": ctx.mode,
        "screenshot": screenshot,  # Local path OR remote URL
        "capabilities": ctx.capabilities
    }
```

**Day 14**: New Management Commands
- `/dss-config set local|remote` - Change mode
- `/dss-config get` - Show current mode & capabilities
- `/dss-status` - Health check for current mode

**Day 15-16**: Integration Testing

**Test Matrix**:
| Test Scenario | LOCAL | REMOTE |
|--------------|-------|---------|
| Screenshot | Playwright | Server API |
| Console logs | CDP | browser-logger.js |
| Token extract | Filesystem | API upload |
| DOM snapshot | CDP live | Shadow State |
| Mode switch | Config change | Config change |

**Deliverables**:
- [ ] All commands mode-aware
- [ ] `/dss-config` and `/dss-status` working
- [ ] 90%+ test coverage
- [ ] Integration tests passing

---

### Phase 5: Multi-Agent Zen Challenge (Days 17-20)

**Objective**: Create compelling multi-agent collaboration scenario

**Challenge Name**: "Cross-Reality Design System Audit"

**Scenario**: Audit design system across 3 environments:
1. Local Development (LOCAL mode)
2. Staging Server (REMOTE mode)
3. Production (REMOTE mode)

**Agent Roles**:
1. **Architect** - Plans audit strategy
2. **Local Scout** - Audits local (LOCAL mode)
3. **Staging Inspector** - Audits staging (REMOTE mode)
4. **Production Monitor** - Monitors prod (REMOTE mode)
5. **Synthesizer** - Combines findings, creates report

**Challenge Flow**:
```
Architect (Planning)
    |
    v
  ┌─┴─┬─────┬─────┐
  |   |     |     |
Local Staging Prod Monitor
Scout Inspector     (Remote)
  |   |     |
  └─┬─┴─────┘
    |
    v
Synthesizer (Report)
```

**Collaboration Mechanism**:
- Agents share session IDs via task-queue
- Screenshots stored centrally
- Token discrepancies flagged
- Console errors deduplicated
- Final report synthesizes all findings

**Deliverables**:
- [ ] Challenge file: `challenges/cross-reality-audit.md`
- [ ] Test with 5 real agents
- [ ] Documentation: `docs/MULTI-AGENT-COLLABORATION.md`
- [ ] Example scenarios

---

## Success Metrics

**Technical Excellence**:
- Mode switching < 2 seconds
- Zero breaking changes
- 90%+ test coverage
- All async-compatible

**Developer Experience**:
- Commands work identically in both modes
- Clear status indicators
- Helpful error messages
- Seamless migration

**Multi-Agent Capability**:
- 5 agents collaborate across modes
- Session IDs enable data sharing
- Task queue integration works
- Reports are comprehensive

---

## Risk Register

| Risk | Impact | Mitigation |
|------|--------|------------|
| Playwright install fails | HIGH | Graceful degradation, clear docs |
| Mode detection ambiguous | MEDIUM | Prompt user, default REMOTE |
| Shadow State too slow | LOW | Async capture, size limits |
| API breaking changes | HIGH | Feature flags, versioning |
| CDP port conflicts | LOW | Configurable port, auto-detect |

---

## First Steps (Day 1)

**Morning**:
1. Create `dss-claude-plugin/core/` directory
2. Implement `config.py` with mode detection
3. Write unit tests for config
4. Test with environment variables

**Afternoon**:
5. Implement `context.py` singleton
6. Add capability verification
7. Test capability caching
8. Document context lifecycle

---

## Documentation Plan

**Architecture Docs**:
- `ARCHITECTURE.md` - System design
- `STRATEGY-PATTERN.md` - Implementation details
- `MODE-DETECTION.md` - How mode is chosen

**User Guides**:
- `GETTING-STARTED.md` - Quick start
- `LOCAL-MODE.md` - LOCAL setup & usage
- `REMOTE-MODE.md` - REMOTE setup & usage
- `MODE-SWITCHING.md` - How to switch modes

**Developer Docs**:
- `CONTRIBUTING.md` - How to add strategies
- `TESTING.md` - Test strategy
- `API.md` - Internal APIs

---

## Key Insights from Gemini 3 Pro Analysis

**1. Impedance Mismatch**
- LOCAL is query-based (imperative)
- REMOTE is event-based (historical)
- Solution: Shadow State bridges the gap

**2. Beacon Strategy**
- Use `navigator.sendBeacon()` for critical logs
- Ensures data reaches server even during crashes
- Immediate XHR for errors

**3. Session ID Handshake**
- Browser generates unique session ID
- MCP server verifies session in API logs (REMOTE)
- Can connect to CDP and verify page URL (LOCAL)
- Avoids ambiguous mode detection

**4. Evolutionary vs Revolutionary**
- Better to evolve existing `dss-claude-plugin`
- Parallel "powertools" plugin adds migration complexity
- Backward compatibility is key

---

## Conclusion

This plan delivers a **unified developer experience** across LOCAL and REMOTE modes while maximizing the capabilities available in each environment. The adaptive architecture enables powerful multi-agent collaboration scenarios that weren't previously possible.

**Next Actions**:
1. Review and approve this plan
2. Create the full zen challenge file
3. Begin Phase 1 implementation (Days 1-3)
4. Iterate based on feedback

---

**Plan Created**: 2025-12-06
**Analysis By**: Claude Sonnet 4.5 + Gemini 3 Pro Preview
**Deep Thinking**: 17 steps, Very High Confidence
**Planning**: 6 steps, Complete
