Simplify code documentation, remove organism terminology
- Remove biological metaphors from docstrings (organism, sensory, genetic, nutrient, etc.) - Simplify documentation to be minimal and structured for fast model parsing - Complete SQLite to JSON storage migration (project_manager.py, json_store.py) - Add Integrations and IntegrationHealth classes to json_store.py - Add kill_port() function to server.py for port conflict handling - All 33 tests pass 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,27 +1,19 @@
|
||||
"""
|
||||
DSS SENSORY ORGANS - Figma Integration Toolkit
|
||||
DSS Figma Integration
|
||||
|
||||
The DSS sensory organs allow the design system organism to perceive and
|
||||
digest visual designs from Figma. This toolkit extracts genetic information
|
||||
(tokens, components, styles) from the Figma sensory perception and transforms
|
||||
it into nutrients for the organism.
|
||||
Extracts design system data from Figma:
|
||||
- Tokens (colors, spacing, typography)
|
||||
- Components (definitions, variants)
|
||||
- Styles (text, fill, effect styles)
|
||||
|
||||
Tool Suite (Sensory Perception Functions):
|
||||
1. figma_extract_variables - 🩸 Perceive design tokens as blood nutrients
|
||||
2. figma_extract_components - 🧬 Perceive component DNA blueprints
|
||||
3. figma_extract_styles - 🎨 Perceive visual expressions and patterns
|
||||
4. figma_sync_tokens - 🔄 Distribute nutrients through circulatory system
|
||||
5. figma_visual_diff - 👁️ Detect changes in visual expression
|
||||
6. figma_validate_components - 🧬 Verify genetic code integrity
|
||||
7. figma_generate_code - 📝 Encode genetic information into code
|
||||
|
||||
Architecture:
|
||||
- Sensory Perception: HTTPx client with SQLite caching (organism's memory)
|
||||
- Token Metabolism: Design token transformation pipeline
|
||||
- Code Generation: Genetic encoding into multiple framework languages
|
||||
|
||||
Framework: DSS Organism Framework
|
||||
See: docs/DSS_ORGANISM_GUIDE.md#sensory-organs
|
||||
Tools:
|
||||
1. figma_extract_variables - Extract design tokens
|
||||
2. figma_extract_components - Extract component definitions
|
||||
3. figma_extract_styles - Extract style definitions
|
||||
4. figma_sync_tokens - Sync tokens to codebase
|
||||
5. figma_visual_diff - Compare versions
|
||||
6. figma_validate_components - Validate component structure
|
||||
7. figma_generate_code - Generate component code
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -66,57 +58,34 @@ class StyleDefinition:
|
||||
|
||||
class FigmaClient:
|
||||
"""
|
||||
👁️ FIGMA SENSORY RECEPTOR - Organism's visual perception system
|
||||
|
||||
The sensory receptor connects the DSS organism to Figma's visual information.
|
||||
It perceives visual designs and caches genetic information (tokens, components)
|
||||
in the organism's short-term memory (SQLite cache) for efficient digestion.
|
||||
Figma API client with caching.
|
||||
|
||||
Features:
|
||||
- Real-time sensory perception (live Figma API connection)
|
||||
- Memory caching (SQLite persistence with TTL)
|
||||
- Rate limiting awareness (respects Figma's biological constraints)
|
||||
- Mock perception mode (for organism development without external connection)
|
||||
- Live API connection or mock mode
|
||||
- Response caching with TTL
|
||||
- Rate limit handling
|
||||
"""
|
||||
|
||||
def __init__(self, token: Optional[str] = None):
|
||||
# Establish sensory connection (use provided token or config default)
|
||||
self.token = token or config.figma.token
|
||||
self.base_url = "https://api.figma.com/v1"
|
||||
self.cache_ttl = config.figma.cache_ttl
|
||||
self._use_real_api = bool(self.token) # Real sensory perception vs mock dreams
|
||||
self._use_real_api = bool(self.token)
|
||||
|
||||
def _cache_key(self, endpoint: str) -> str:
|
||||
return f"figma:{hashlib.md5(endpoint.encode()).hexdigest()}"
|
||||
|
||||
async def _request(self, endpoint: str) -> Dict[str, Any]:
|
||||
"""
|
||||
👁️ SENSORY PERCEPTION - Fetch visual information from Figma
|
||||
|
||||
The sensory receptor reaches out to Figma to perceive visual designs.
|
||||
If the organism is in development mode, it uses dream data (mocks).
|
||||
Otherwise, it queries the external Figma organism and stores perceived
|
||||
information in its own memory (SQLite cache) for quick recall.
|
||||
|
||||
Flow:
|
||||
1. Check if sensory is in development mode (mock perception)
|
||||
2. Check organism's memory cache for previous perception
|
||||
3. If memory miss, perceive from external source (Figma API)
|
||||
4. Store new perception in memory for future recognition
|
||||
5. Log the perceptual event
|
||||
"""
|
||||
"""Fetch data from Figma API with caching."""
|
||||
if not self._use_real_api:
|
||||
# Sensory hallucinations for development (mock perception)
|
||||
return self._get_mock_data(endpoint)
|
||||
|
||||
cache_key = self._cache_key(endpoint)
|
||||
|
||||
# Check organism memory first (short-term memory - SQLite)
|
||||
cached = Cache.get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
# Perceive from external source (live Figma perception)
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}{endpoint}",
|
||||
@@ -125,14 +94,12 @@ class FigmaClient:
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# Store perception in organism memory for future recognition
|
||||
Cache.set(cache_key, data, ttl=self.cache_ttl)
|
||||
|
||||
# Log the perceptual event
|
||||
ActivityLog.log(
|
||||
action="figma_sensory_perception",
|
||||
entity_type="sensory_organs",
|
||||
details={"endpoint": endpoint, "cached": False, "perception": "live"}
|
||||
action="figma_api_request",
|
||||
entity_type="figma",
|
||||
details={"endpoint": endpoint, "cached": False}
|
||||
)
|
||||
|
||||
return data
|
||||
@@ -219,22 +186,16 @@ class FigmaClient:
|
||||
|
||||
class FigmaToolSuite:
|
||||
"""
|
||||
👁️ SENSORY ORGANS DIGESTION CENTER - Transform visual perception into nutrients
|
||||
Figma extraction toolkit.
|
||||
|
||||
The sensory digestion center transforms raw visual information from Figma
|
||||
into usable nutrients (tokens, components) that the DSS organism can
|
||||
incorporate into its body. This complete toolkit:
|
||||
Capabilities:
|
||||
- Extract tokens, components, styles from Figma
|
||||
- Validate component structure
|
||||
- Generate component code (React, Vue, Web Components)
|
||||
- Sync tokens to codebase
|
||||
- Compare visual versions
|
||||
|
||||
- Perceives visual designs (sensory organs)
|
||||
- Extracts genetic code (tokens, components, styles)
|
||||
- Validates genetic integrity (schema validation)
|
||||
- Encodes information (code generation for multiple frameworks)
|
||||
- Distributes nutrients (token syncing to codebase)
|
||||
- Detects mutations (visual diffs)
|
||||
|
||||
The organism can operate in two modes:
|
||||
- LIVE: Directly perceiving from external Figma organism
|
||||
- MOCK: Using dream data for development without external dependency
|
||||
Modes: live (API) or mock (development)
|
||||
"""
|
||||
|
||||
def __init__(self, token: Optional[str] = None, output_dir: str = "./output"):
|
||||
@@ -245,34 +206,21 @@ class FigmaToolSuite:
|
||||
|
||||
@property
|
||||
def mode(self) -> str:
|
||||
"""
|
||||
Return sensory perception mode: 'live' (external Figma) or 'mock' (dreams/development)
|
||||
"""
|
||||
"""Return mode: 'live' (API) or 'mock' (development)."""
|
||||
return "live" if self._is_real_api else "mock"
|
||||
|
||||
# === Tool 1: Extract Variables/Tokens ===
|
||||
|
||||
async def extract_variables(self, file_key: str, format: str = "css") -> Dict[str, Any]:
|
||||
"""
|
||||
🩸 EXTRACT CIRCULATORY TOKENS - Perceive design tokens as nutrients
|
||||
|
||||
The sensory organs perceive design tokens (variables) from Figma and
|
||||
convert them into circulatory nutrients (design tokens) that flow through
|
||||
the organism's body. These are the fundamental nutrients that color blood,
|
||||
determine tissue spacing, and define typographic patterns.
|
||||
Extract design tokens from Figma variables.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (visual perception target)
|
||||
format: Output format for encoded nutrients (css, json, scss, js)
|
||||
file_key: Figma file key
|
||||
format: Output format (css, json, scss, js)
|
||||
|
||||
Returns:
|
||||
Dict with extracted tokens ready for circulation:
|
||||
- success: Perception completed without errors
|
||||
- tokens_count: Number of nutrients extracted
|
||||
- collections: Token collections (by system)
|
||||
- output_path: File where nutrients are stored
|
||||
- tokens: Complete nutrient definitions
|
||||
- formatted_output: Encoded output in requested format
|
||||
Dict with: success, tokens_count, collections, output_path, tokens, formatted_output
|
||||
"""
|
||||
data = await self.client.get_variables(file_key)
|
||||
|
||||
@@ -326,23 +274,13 @@ class FigmaToolSuite:
|
||||
|
||||
async def extract_components(self, file_key: str) -> Dict[str, Any]:
|
||||
"""
|
||||
🧬 EXTRACT GENETIC BLUEPRINTS - Perceive component DNA
|
||||
|
||||
The sensory organs perceive component definitions (visual DNA) from Figma
|
||||
and extract genetic blueprints that describe how tissues are constructed.
|
||||
Components are the fundamental building blocks (genes) that encode
|
||||
the organism's form, function, and behavior patterns.
|
||||
Extract component definitions from Figma.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (visual genetic source)
|
||||
file_key: Figma file key
|
||||
|
||||
Returns:
|
||||
Dict with extracted component DNA:
|
||||
- success: Genetic extraction successful
|
||||
- components_count: Number of DNA blueprints found
|
||||
- component_sets_count: Number of genetic variant groups
|
||||
- output_path: File where genetic information is stored
|
||||
- components: Complete component definitions with properties
|
||||
Dict with: success, components_count, component_sets_count, output_path, components
|
||||
"""
|
||||
definitions: List[ComponentDefinition] = []
|
||||
component_sets_count = 0
|
||||
@@ -423,23 +361,13 @@ class FigmaToolSuite:
|
||||
|
||||
async def extract_styles(self, file_key: str) -> Dict[str, Any]:
|
||||
"""
|
||||
🎨 EXTRACT VISUAL EXPRESSION PATTERNS - Perceive style definitions
|
||||
|
||||
The sensory organs perceive visual expressions (text, color, effect styles)
|
||||
from Figma and categorize them by their biological purpose: how text
|
||||
appears (typography), how colors flow (pigmentation), and how depth
|
||||
and dimension manifest through effects.
|
||||
Extract style definitions from Figma.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (visual style source)
|
||||
file_key: Figma file key
|
||||
|
||||
Returns:
|
||||
Dict with extracted style definitions organized by type:
|
||||
- success: Style extraction successful
|
||||
- styles_count: Total style definitions found
|
||||
- by_type: Styles organized by category (TEXT, FILL, EFFECT, GRID)
|
||||
- output_path: File where style definitions are stored
|
||||
- styles: Complete style information by type
|
||||
Dict with: success, styles_count, by_type, output_path, styles
|
||||
"""
|
||||
definitions: List[StyleDefinition] = []
|
||||
by_type = {"TEXT": [], "FILL": [], "EFFECT": [], "GRID": []}
|
||||
@@ -510,25 +438,15 @@ class FigmaToolSuite:
|
||||
|
||||
async def sync_tokens(self, file_key: str, target_path: str, format: str = "css") -> Dict[str, Any]:
|
||||
"""
|
||||
🔄 CIRCULATE NUTRIENTS - Distribute tokens through the organism
|
||||
|
||||
The organism absorbs nutrients from Figma's visual designs and circulates
|
||||
them through its body by syncing to the code codebase. This ensures the
|
||||
organism's physical form (code) stays synchronized with its genetic design
|
||||
(Figma tokens).
|
||||
Sync design tokens from Figma to codebase.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (nutrient source)
|
||||
target_path: Codebase file path (circulation destination)
|
||||
format: Output format for encoded nutrients
|
||||
file_key: Figma file key
|
||||
target_path: Target file path
|
||||
format: Output format
|
||||
|
||||
Returns:
|
||||
Dict with sync result:
|
||||
- success: Circulation completed
|
||||
- has_changes: Whether genetic material changed
|
||||
- tokens_synced: Number of nutrients distributed
|
||||
- target_path: Location where nutrients were circulated
|
||||
- backup_created: Whether old nutrients were preserved
|
||||
Dict with: success, has_changes, tokens_synced, target_path, backup_created
|
||||
"""
|
||||
# Extract current tokens
|
||||
result = await self.extract_variables(file_key, format)
|
||||
@@ -597,47 +515,37 @@ class FigmaToolSuite:
|
||||
|
||||
async def validate_components(self, file_key: str, schema_path: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
🧬 GENETIC INTEGRITY CHECK - Validate component DNA health
|
||||
|
||||
The immune system examines extracted component DNA against genetic
|
||||
rules (schema) to ensure all components are healthy, properly named,
|
||||
and fully documented. Invalid components are flagged as mutations that
|
||||
could endanger the organism's health.
|
||||
Validate component definitions against rules.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (genetic source)
|
||||
schema_path: Optional path to validation rules (genetic schema)
|
||||
file_key: Figma file key
|
||||
schema_path: Optional validation schema path
|
||||
|
||||
Returns:
|
||||
Dict with validation results:
|
||||
- success: Validation completed without system errors
|
||||
- valid: Whether all genetic material is healthy
|
||||
- components_checked: Number of DNA blueprints examined
|
||||
- issues: List of genetic problems found
|
||||
- summary: Count of errors, warnings, and info messages
|
||||
Dict with: success, valid, components_checked, issues, summary
|
||||
"""
|
||||
components = await self.extract_components(file_key)
|
||||
|
||||
issues: List[Dict[str, Any]] = []
|
||||
|
||||
# Run genetic integrity checks
|
||||
# Run validation checks
|
||||
for comp in components["components"]:
|
||||
# Rule 1: 🧬 Genetic naming convention (capitalize first letter)
|
||||
# Rule 1: Naming convention (capitalize first letter)
|
||||
if not comp["name"][0].isupper():
|
||||
issues.append({
|
||||
"component": comp["name"],
|
||||
"rule": "naming-convention",
|
||||
"severity": "warning",
|
||||
"message": f"🧬 Genetic mutation detected: '{comp['name']}' should follow naming convention (start with capital letter)"
|
||||
"message": f"'{comp['name']}' should start with capital letter"
|
||||
})
|
||||
|
||||
# Rule 2: 📋 Genetic documentation (description required)
|
||||
# Rule 2: Description required
|
||||
if not comp.get("description"):
|
||||
issues.append({
|
||||
"component": comp["name"],
|
||||
"rule": "description-required",
|
||||
"severity": "info",
|
||||
"message": f"📝 Genetic annotation missing: '{comp['name']}' should have a description to document its biological purpose"
|
||||
"message": f"'{comp['name']}' should have a description"
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -657,25 +565,15 @@ class FigmaToolSuite:
|
||||
async def generate_code(self, file_key: str, component_name: str,
|
||||
framework: str = "webcomponent") -> Dict[str, Any]:
|
||||
"""
|
||||
📝 ENCODE GENETIC MATERIAL - Generate component code from DNA
|
||||
|
||||
The organism translates genetic blueprints (component DNA) from Figma
|
||||
into executable code that can be expressed in multiple biological contexts
|
||||
(frameworks). This genetic encoding allows the component DNA to manifest
|
||||
as living tissue in different ecosystems.
|
||||
Generate component code from Figma definition.
|
||||
|
||||
Args:
|
||||
file_key: Figma file key (genetic source)
|
||||
component_name: Name of component DNA to encode
|
||||
framework: Target biological context (webcomponent, react, vue)
|
||||
file_key: Figma file key
|
||||
component_name: Component to generate
|
||||
framework: Target framework (webcomponent, react, vue)
|
||||
|
||||
Returns:
|
||||
Dict with generated code:
|
||||
- success: Genetic encoding successful
|
||||
- component: Component name
|
||||
- framework: Target framework
|
||||
- output_path: File where genetic code is written
|
||||
- code: The encoded genetic material ready for expression
|
||||
Dict with: success, component, framework, output_path, code
|
||||
"""
|
||||
components = await self.extract_components(file_key)
|
||||
|
||||
@@ -685,7 +583,7 @@ class FigmaToolSuite:
|
||||
if not comp:
|
||||
return {
|
||||
"success": False,
|
||||
"error": f"🛡️ Genetic material not found: Component '{component_name}' does not exist in the perceived DNA"
|
||||
"error": f"Component '{component_name}' not found"
|
||||
}
|
||||
|
||||
# Generate code based on framework
|
||||
|
||||
Reference in New Issue
Block a user