# Code Standards & Development Guidelines --- ## 1. Python Code Standards (Search Engine & Design System) ### 1.1 General Style **Compliance:** PEP 8 with pragmatism **Tools:** Black (code formatter), flake8 (linter), mypy (type checking) **Min Python:** 3.8+ ### 1.2 File Structure ```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module docstring (purpose, usage, examples) """ import from import import from import # ============ CONFIGURATION ============ CONSTANT_NAME = value DICT_CONFIG = {...} # ============ CLASS DEFINITIONS ============ class ClassName: """Class docstring""" def __init__(self): """Initialize""" pass def method_name(self): """Method docstring""" pass # ============ FUNCTION DEFINITIONS ============ def function_name(param1, param2): """Function docstring with Args, Returns, Raises""" pass # ============ MAIN ENTRY ============ if __name__ == "__main__": main() ``` ### 1.3 Naming Conventions | Type | Format | Example | |------|--------|---------| | **Constants** | UPPER_SNAKE_CASE | `MAX_RESULTS = 3` | | **Functions** | snake_case | `def _load_csv():` | | **Classes** | PascalCase | `class BM25:` | | **Private** | _snake_case prefix | `def _internal_function():` | | **Dunder** | __name__ (avoid custom) | `__init__, __str__` | | **Variables** | snake_case | `query_result = []` | ### 1.4 Docstring Format ```python def search(query, domain=None, max_results=MAX_RESULTS): """ Main search function with auto-domain detection. Args: query (str): Search query string domain (str, optional): Specific domain to search. If None, auto-detect. max_results (int): Maximum number of results (default: 3) Returns: dict: Result dictionary with keys: domain, query, file, count, results Raises: FileNotFoundError: If CSV file not found ValueError: If domain is invalid Example: >>> result = search("minimalism", "style", 5) >>> print(result['count']) # 3 """ pass ``` ### 1.5 Imports & Dependencies **Rule:** Minimize external dependencies for portability ```python # Good import csv from pathlib import Path from math import log # Avoid import numpy # Not in stdlib, adds weight import requests # Use only if absolutely necessary ``` **Organization:** 1. Stdlib imports first 2. Third-party imports next (none for search engine) 3. Local imports last 4. Blank line between groups ### 1.6 Error Handling ```python # Good try: result = _search_csv(filepath, columns, query, max_results) except FileNotFoundError: return {"error": f"File not found: {filepath}", "domain": domain} except Exception as e: logger.error(f"Unexpected error: {e}") raise # Avoid try: # code except: pass # Silent failures are bad ``` ### 1.7 Type Hints **Required for:** - Public function signatures - Class methods with complex logic - Design system generator (all methods) **Format:** ```python def _search_csv( filepath: Path, search_cols: list[str], output_cols: list[str], query: str, max_results: int ) -> list[dict]: """Search CSV and return results.""" pass # Return types def get_results(self) -> dict[str, any]: pass ``` ### 1.8 Code Comments **Good comments explain WHY, not WHAT:** ```python # Good # BM25 uses k1=1.5 and b=0.75 (standard tuning for document length normalization) idf = log((self.N - freq + 0.5) / (freq + 0.5) + 1) # Avoid # Calculate log idf = log((self.N - freq + 0.5) / (freq + 0.5) + 1) # Good # Exclude words < 3 chars to reduce noise (and, the, a, etc.) return [w for w in text.split() if len(w) > 2] # Avoid # Filter words return [w for w in text.split() if len(w) > 2] ``` ### 1.9 Line Length - **Maximum:** 100 characters (flexible for URLs/strings) - **Readability:** Break long lines at logical operators ```python # Good if (config_exists and permission_granted and not already_installed): proceed() # Avoid if config_exists and permission_granted and not already_installed and something_else: proceed() ``` ### 1.10 CSV Handling **Rules:** 1. Always use UTF-8 encoding 2. Handle missing fields gracefully 3. Preserve field order for consistency 4. Use DictReader/DictWriter for clarity ```python # Good with open(filepath, 'r', encoding='utf-8') as f: reader = csv.DictReader(f) data = list(reader) # Handle missing value = row.get('Column', 'default_value') # Avoid open(filepath) # No encoding specified row['Column'] # KeyError if missing ``` ### 1.11 Windows Compatibility ```python # Good - UTF-8 for emoji/special chars on Windows if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8': sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') # Good - Use pathlib for cross-platform paths from pathlib import Path filepath = Path(__file__).parent / "data" / "styles.csv" # Avoid filepath = f"{os.getcwd()}\\data\\styles.csv" # Windows-specific ``` --- ## 2. TypeScript Code Standards (CLI) ### 2.1 General Style **Compliance:** ESLint (airbnb config) + Prettier **Min TypeScript:** 4.8+ **Target:** Node 18+ ### 2.2 File Structure ```typescript /** * Module purpose and usage */ import type { TypeName } from './types/index'; import { functionName } from './utils/logger'; // ============ TYPES ============ interface ConfigOptions { platform: string; offline?: boolean; } // ============ CONSTANTS ============ const PLATFORMS = ['claude', 'cursor', 'windsurf'] as const; const DEFAULT_TIMEOUT = 30000; // ============ EXPORTED FUNCTIONS ============ export async function initCommand(options: ConfigOptions): Promise { // implementation } // ============ PRIVATE FUNCTIONS ============ function detectPlatform(): string { // implementation } // ============ MAIN ENTRY ============ export default function main() { // entry point } ``` ### 2.3 Naming Conventions | Type | Format | Example | |------|--------|---------| | **Constants** | UPPER_SNAKE_CASE | `const MAX_RETRIES = 3` | | **Functions** | camelCase | `function detectPlatform()` | | **Classes** | PascalCase | `class TemplateRenderer` | | **Interfaces** | PascalCase | `interface ConfigOptions` | | **Types** | PascalCase | `type Platform = 'claude' \| 'cursor'` | | **Variables** | camelCase | `let platformName = 'claude'` | | **Private** | leadingUnderscore | `_internalFunction()` | | **Files** | kebab-case | `template-renderer.ts`, `detect.ts` | ### 2.4 Type Definitions **Rules:** 1. Always export types from `types/index.ts` 2. Use `type` for unions/aliases, `interface` for objects 3. Strict null checking enabled ```typescript // types/index.ts export interface InitOptions { platform: 'claude' | 'cursor' | 'windsurf'; offline?: boolean; outputDir?: string; } export type Platform = InitOptions['platform']; // Usage export async function init(options: InitOptions): Promise { const platform: Platform = options.platform; } ``` ### 2.5 Async/Await ```typescript // Good async function downloadAssets(): Promise { try { const data = await fetchFromGitHub(url); await writeFiles(data); } catch (error) { logger.error(`Download failed: ${error.message}`); throw new Error('Failed to download assets'); } } // Avoid function downloadAssets() { return new Promise((resolve, reject) => { // callback hell }); } ``` ### 2.6 Error Handling ```typescript // Good - Custom error types class InstallerError extends Error { constructor(message: string, public platform?: string) { super(message); this.name = 'InstallerError'; } } // Usage try { await installSkill(platform); } catch (error) { if (error instanceof InstallerError) { logger.error(`Installation failed for ${error.platform}: ${error.message}`); } else { throw error; } } ``` ### 2.7 Comments & Documentation ```typescript /** * Detects the current AI coding assistant platform. * * @returns The detected platform name, or 'unknown' if not detected * * @example * const platform = detectPlatform(); * console.log(platform); // 'claude' */ function detectPlatform(): string { // implementation } ``` ### 2.8 Module Exports ```typescript // Good - Named exports for tree-shaking export { initCommand } from './commands/init'; export { updateCommand } from './commands/update'; export type { ConfigOptions } from './types/index'; // Avoid export default { initCommand, updateCommand }; // Default export export * from './types'; // Wildcard exports (less clear) ``` --- ## 3. CSV Data Format Standards ### 3.1 Structure Requirements **Rules:** 1. UTF-8 encoding (no BOM) 2. Unix line endings (LF, not CRLF) 3. Comma-separated values 4. Header row with descriptive names 5. Consistent data types per column ### 3.2 CSV Header Naming ```csv # Good - Clear, no special chars Style Category,Type,Keywords,Best For,Performance,Accessibility # Avoid StyleCat,T,KW,BF,Perf,A11y # Unclear abbreviations style_category,type,keywords # snake_case in CSV (use PascalCase) ``` ### 3.3 Field Requirements **All Fields:** - Non-empty unless explicitly optional - Properly escaped if containing quotes/commas - Consistent data type per column ```csv Style Category,Keywords,Best For "Glassmorphism","glass, frosted, transparency, modern",SaaS apps "Claymorphism","clay, soft, rounded, tactile",Educational apps ``` ### 3.4 Data Consistency | Domain | Requirement | Example | |--------|------------|---------| | **Styles** | Consistent capitalization | "Glassmorphism" not "glassmorphism" | | **Colors** | Valid hex format | #E8B4B8 not E8B4B8 or #e8b4b8 (case-insensitive OK) | | **Products** | Consistent categories | "SaaS" not "saas" or "SAAS" | | **URLs** | Absolute, http/https | https://fonts.google.com/... | | **Lists** | Comma-separated, consistent | "item1, item2, item3" | ### 3.5 Search Column Selection **Rules:** 1. Include searchable columns in config 2. Exclude very long text (use truncation in output) 3. Prioritize frequently-searched fields ```python # In core.py CSV_CONFIG "style": { "file": "styles.csv", "search_cols": ["Style Category", "Keywords", "Best For", "Type", "AI Prompt Keywords"], "output_cols": ["Style Category", "Type", "Keywords", ..., "Design System Variables"] } ``` ### 3.6 Size Guidelines | File | Max Rows | Max Size | Rationale | |------|----------|----------|-----------| | styles.csv | 100 | 100KB | Most important, larger acceptable | | typography.csv | 100 | 50KB | Detailed font information | | products.csv | 150 | 50KB | Comprehensive product coverage | | colors.csv | 150 | 50KB | Industry-specific palettes | | Others | 50 | 20KB | Specialized domains | --- ## 4. Git & Version Control ### 4.1 Branching Strategy **Pattern:** `/` ```bash # Feature development git checkout -b feat/add-design-system-caching git checkout -b feat/support-droid-platform # Bug fixes git checkout -b fix/windows-unicode-emoji git checkout -b fix/version-mismatch-plugin # Documentation git checkout -b docs/update-codebase-summary # Refactoring git checkout -b refactor/modularize-design-system # Never commit directly to main ``` ### 4.2 Commit Message Format **Standard:** Conventional Commits ``` ():