# syntaxis Best Practices

## Project-Specific Guidelines

### 1. Configuration Management
- All configuration in TOML files (never hardcoded)
- Support environment variable overrides
- Validate configuration at startup
- Document all configuration options

Example:
```rust
#[derive(Deserialize)]
pub struct WorkspaceConfig {
    pub project_root: String,
    pub database_url: String,
    pub cache_ttl_secs: u64,
}

let config = WorkspaceConfig::from_file("workspace.toml")?;
```

### 2. Task State Tracking
syntaxis-core provides TaskStatus and TaskStateChange for tracking task evolution:

```rust
#[derive(Debug, Clone, Copy)]
pub enum TaskStatus {
    Pending,
    InProgress,
    Blocked,
    Completed,
    Cancelled,
}

pub struct TaskStateChange {
    pub id: String,
    pub task_id: String,
    pub from_state: TaskStatus,
    pub to_state: TaskStatus,
    pub changed_at: DateTime<Utc>,
    pub changed_by: String,
    pub reason: Option<String>,
    pub metadata: serde_json::Value,
}
```

### 3. Phase-Based Project Orchestration
Projects follow distinct phases defined in PROJECT_RULES.md:

```rust
// Use PhaseManager for orchestration
let mut phase_manager = PhaseManager::new(project_id);
phase_manager.advance_phase(CurrentPhase::InitialSetup)?;
phase_manager.validate_prerequisites()?;
```

### 4. Multi-Interface Consistency
Ensure consistency across all interfaces (CLI, TUI, Dashboard, API):

- Same error messages and codes
- Consistent naming conventions
- Unified configuration
- Shared domain models (syntaxis-core)

### 5. Database Interaction
Use SQLx with proper connection pooling:

```rust
use sqlx::sqlite::SqlitePool;

let pool = SqlitePool::connect("sqlite:workspace.db").await?;
let project = sqlx::query!("SELECT * FROM projects WHERE id = ?", project_id)
    .fetch_one(&pool)
    .await?;
```

### 6. Error Responses
API and CLI errors should be consistent:

```rust
#[derive(Error, Debug)]
pub enum WorkspaceError {
    #[error("Project not found: {0}")]
    ProjectNotFound(String),

    #[error("Invalid task state transition: {from} -> {to}")]
    InvalidTransition { from: String, to: String },

    #[error("Database error: {0}")]
    Database(#[from] sqlx::Error),
}
```

### 7. Logging Best Practices
Use structured logging throughout:

```rust
use tracing::{info, error, span, Level};

let span = span!(Level::INFO, "project_creation", project_id = ?id);
let _enter = span.enter();
info!("Creating new project");

// Automatic context logging
```

### 8. Testing Strategy
- Unit tests for business logic
- Integration tests for workflows
- Property-based tests for edge cases
- Benchmark critical paths

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_phase_transition() {
        let mut manager = PhaseManager::new("test");
        assert!(manager.advance_phase(Phase::InitialSetup).is_ok());
    }
}
```

### 9. Documentation Standards

**Public APIs must have:**
- Clear description of purpose
- Parameter documentation
- Return type documentation
- Example usage
- Error conditions

```rust
/// Creates a new project with validation
///
/// # Arguments
/// * `name` - Project name (non-empty)
/// * `description` - Project description
///
/// # Returns
/// * `Ok(Project)` - Successfully created project
/// * `Err(WorkspaceError)` - If validation fails
///
/// # Errors
/// - `InvalidName` - If name is empty
/// - `Database` - If database operation fails
///
/// # Example
/// ```
/// let project = ProjectManager::create("my-project", "desc")?;
/// ```
pub fn create(name: &str, description: &str) -> Result<Project> {
    // Implementation
}
```

### 10. VAPORA Integration Points

syntaxis is designed for VAPORA integration:

- Task state changes trigger VAPORA events
- Phase transitions notify orchestration engine
- Project metadata supports VAPORA requirements
- REST API (in progress) will provide integration hooks

### 11. Code Organization

Keep related functionality together:

```
syntaxis-core/
├── error.rs              # Error types
├── types/
│   ├── project.rs       # Project domain
│   ├── task.rs          # Task domain
│   └── phase.rs         # Phase domain
├── managers/
│   ├── project.rs       # ProjectManager
│   ├── phase.rs         # PhaseManager
│   └── task.rs          # TaskManager
├── persistence/
│   ├── mod.rs           # PersistenceLayer trait
│   ├── memory.rs        # In-memory implementation
│   └── sqlite.rs        # SQLite implementation
└── lib.rs               # Module root & exports
```

### 12. Performance Considerations

- Use connection pooling for database
- Cache frequently accessed data
- Lazy load relationships
- Profile with flamegraph for hot paths
- Benchmark critical operations

```bash
# Profile performance
cargo flamegraph --bin syntaxis-cli -- --help

# Benchmark specific operation
cargo bench -p syntaxis-core
```

### 13. Security Practices

- Never log sensitive data
- Validate all user input
- Use environment variables for secrets
- Audit API access (when API is enabled)
- Regular dependency audits

```bash
# Check for vulnerabilities
cargo audit

# Check specific crate
cargo audit -p syntaxis-core
```

### 14. Dependency Management

- Keep dependencies minimal
- Use workspace.dependencies for consistency
- Pin security-critical versions
- Review breaking changes before updates
- Document why each dependency is needed

```toml
[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
thiserror = "2.0"
tokio = { version = "1", features = ["full"] }
```

### 15. Backward Compatibility

- Avoid breaking public API changes
- Use feature flags for experimental features
- Deprecate gradually before removal
- Document migration paths for users

## Quick Reference: Common Tasks

### Adding a new feature to syntaxis-core
1. Create types in `syntaxis-core/src/types/`
2. Create manager in `syntaxis-core/src/managers/`
3. Add persistence layer support
4. Write 15+ unit tests
5. Add integration test to syntaxis-cli
6. Update documentation

### Adding a CLI command
1. Create handler in `syntaxis-cli/src/handlers/`
2. Wire up in `syntaxis-cli/src/main.rs`
3. Test with actual workspace project
4. Update help/documentation

### Adding Dashboard component
1. Create component in `syntaxis-dashboard/src/components/`
2. Integrate with state in `syntaxis-dashboard/src/state/`
3. Write HTML rendering tests
4. Test in browser at http://localhost:3000

## For Details

- [PROJECT_RULES.md](./.claude/PROJECT_RULES.md) - Architecture & standards
- [CODE_STANDARDS.md](./.claude/CODE_STANDARDS.md) - Testing & verification
- [DEVELOPMENT.md](./.claude/DEVELOPMENT.md) - Development workflow
