# Tools Templates Reference

Complete documentation of all available templates for creating new Tools in the Tools ecosystem.

## Quick Overview

```
shared/templates/
├── rust-core/              # Rust library templates (Tier 1)
├── rust-cli/               # Rust CLI templates (Tier 3)
├── rust-api/               # Rust REST API templates (Tier 2)
├── nushell-tool/           # NuShell complete tool
├── documentation/          # Documentation templates
└── TEMPLATE_README.md      # This file
```

## Rust Core Library Templates (`rust-core/`)

### Purpose
Create the core library (Tier 1) - reusable business logic without UI/API.

### Files Included

#### 1. `Cargo.toml.template`
**Purpose**: Workspace and dependencies configuration

**When to use**:
- Creating crates/tool-core/Cargo.toml
- First file to copy from template

**Key content**:
- Workspace version inheritance
- tools-shared dependency
- serde, tokio, uuid, chrono dependencies
- Forbid unsafe code
- Clippy warnings configuration

**Customization**:
```bash
# Variables to replace
{{TOOL_NAME}}           → Your tool name (e.g., tracking-manager)
{{tool_name_kebab}}     → kebab-case (e.g., tracking-manager)

# Example:
{{TOOL_NAME}}-core becomes tracking-manager-core
lib name becomes tracking_manager_core
```

#### 2. `lib.rs.template`
**Purpose**: Main library entry point with module structure

**When to use**:
- Creating crates/tool-core/src/lib.rs
- Second file to copy and customize

**Key content**:
- Module declarations (error, types, handlers)
- Public API re-exports
- Documentation with examples
- Feature descriptions
- VERSION constant
- Unit tests

**Customization**:
```rust
// Update these sections:
//! {{TOOL_NAME}} Core Library       → Your tool description
//! A production-ready library for [description of what this tool does]

// Update Features:
//! - [Feature 1]
//! - [Feature 2]
//! - [Feature 3]

// Update Quick Start example:
pub use {{TOOL_NAME}}_core::{{MainType}};
```

#### 3. `error.rs.template`
**Purpose**: Canonical error struct pattern following Microsoft Pragmatic Rust Guidelines

**When to use**:
- Creating crates/tool-core/src/error.rs
- Defines all error types for your tool

**Key content**:
- `{{ToolName}}Error` struct with context and backtrace
- `{{ToolName}}ErrorKind` enum with error variants
- Proper Display and Error trait implementations
- Backtrace support for debugging
- Source chain for error context

**Error Variants** (customize for your domain):
```rust
#[derive(Debug)]
#[non_exhaustive]
pub enum {{ToolName}}ErrorKind {
    ConfigError(String),       // Configuration issues
    IoError(String),           // File I/O errors
    ValidationError(String),   // Input validation
    DatabaseError(String),     // Database operations
    Unknown(String),           // Catch-all
}
```

**Adding custom variant**:
```rust
// 1. Add to enum
CustomError(String),

// 2. Add to Display impl
Self::CustomError(msg) => write!(f, "Custom error: {}", msg),

// 3. Add test
#[test]
fn test_custom_error() { ... }
```

**Customization**: Replace `{{ToolName}}` with your tool name (CamelCase)

#### 4. `src/types.rs.template`
**Purpose**: Domain types and data structures

**When to use**:
- Creating crates/tool-core/src/types.rs
- Defines the primary domain type ({{MainType}})

**Key content**:
- `{{MainType}}` struct with standard fields
- UUID-based identification
- Timestamp tracking (created_at, updated_at)
- Serialization support (serde)
- Builder-like mutation methods
- Metadata field for extensibility
- Comprehensive tests

**Standard Fields** (in template):
```rust
pub id: String,                    // UUID v4
pub name: String,                  // Display name
pub description: String,           // Description
pub metadata: serde_json::Value,   // Extensibility
pub created_at: DateTime<Utc>,     // Creation time
pub updated_at: DateTime<Utc>,     // Last modified
```

**Customization**:
```rust
// 1. Add domain-specific fields:
pub status: ItemStatus,
pub priority: u8,
pub tags: Vec<String>,

// 2. Add domain-specific methods:
pub fn publish(&mut self) { ... }
pub fn archive(&mut self) { ... }

// 3. Add domain-specific tests:
#[test]
fn test_publish() { ... }
```

#### 5. `src/handlers/mod.rs.template`
**Purpose**: Handlers module structure and organization

**When to use**:
- Creating crates/tool-core/src/handlers/mod.rs
- Organizes business logic layer

**Key content**:
- Module declarations (service)
- Public API exports
- Re-export pattern for clean API

**Customization**:
```rust
// Add more modules as needed:
pub mod service;
pub mod validators;  // Add validation logic
pub mod processors;  // Add processing logic

pub use service::{{MainType}}Service;
pub use validators::*;
pub use processors::*;
```

#### 6. `src/handlers/service.rs.template`
**Purpose**: Service layer with CRUD operations

**When to use**:
- Creating crates/tool-core/src/handlers/service.rs
- Main business logic implementation

**Key content**:
- `{{MainType}}Service` struct with in-memory storage
- CRUD operations: create, get, list, update, delete
- Async/await with tokio
- Proper error handling
- 7+ comprehensive tests

**Standard Operations**:
```rust
pub async fn create(&self, name, description) -> Result<{{MainType}}>
pub async fn get(&self, id) -> Result<{{MainType}}>
pub async fn list(&self) -> Result<Vec<{{MainType}}>
pub async fn update(&self, id, name, description) -> Result<{{MainType}}>
pub async fn delete(&self, id) -> Result<()>
```

**Customization**:
1. Replace in-memory HashMap with persistent storage (SQLite, PostgreSQL)
2. Add domain-specific operations
3. Implement search, filtering, sorting
4. Add transaction support
5. Extend tests for new features

**Storage Options**:
- In-memory (template default) - for dev/testing
- SQLite (recommended) - for single-user
- PostgreSQL - for production/multi-user
- SurrealDB - for advanced features

---

## Rust CLI Template (`rust-cli/`)

### Purpose
Create the CLI layer (Tier 3) - user-friendly command-line interface.

### Files Included

#### `main.rs.template`
**Purpose**: Complete CLI entry point with command parsing and configuration discovery

**When to use**:
- Creating crates/tool-cli/src/main.rs
- Provides user interface to core library

**Key content**:
- clap CLI parser with derive macros
- Configuration discovery using tools-shared
- Verbose logging support
- Help text with configuration search order
- Example subcommands (list, summary, create, version)
- Proper error handling

**Subcommands** (customize for your domain):
```rust
Commands::List { filter, limit } → List items with optional filtering
Commands::Summary { group_by }  → Show statistics
Commands::Create { name, description } → Create new item
Commands::Version               → Show version
```

**Key Features**:
```rust
// Configuration discovery (REQUIRED for all Rust CLIs):
let config_path = find_config_path("tool-name.toml")
    .unwrap_or_else(|| PathBuf::from(".project/tool-name.toml"));

// Help text with search order (REQUIRED):
#[command(long_about = r#"TOOL_NAME

CONFIGURATION SEARCH:
  Looks for config in order (uses first found):

  1. .project/tool-name.toml
  2. .vapora/tool-name.toml
  3. .coder/tool-name.toml
  4. ./tool-name.toml
"#)]

// Logging support:
let log_level = if cli.verbose { "debug" } else { "info" };
```

**Customization**:
1. Add domain-specific subcommands
2. Implement command handlers that use core service
3. Add output formatting (JSON, table, etc.)
4. Add configuration loading and validation
5. Add more options and flags as needed

**Important Requirements**:
- ✅ MUST use tools-shared for config discovery
- ✅ MUST have help text with configuration search order
- ✅ MUST include verbose logging
- ✅ MUST handle errors gracefully
- ✅ MUST show version from Cargo.toml

---

## Rust API Template (`rust-api/`)

### Purpose
Create REST API layer (Tier 2, optional) - HTTP server interface.

### Files Included

#### `Cargo.toml.template`
**Purpose**: API server dependencies

**Key dependencies**:
- axum - Web framework
- tokio - Async runtime
- serde/serde_json - Serialization
- tracing - Structured logging

#### `main.rs.template`
**Purpose**: Complete REST API server

**When to use**:
- Creating crates/tool-api/src/main.rs
- Provides HTTP interface to core library

**Key content**:
- axum router with CRUD routes
- Proper HTTP status codes
- JSON request/response
- Error handling
- Health check endpoint
- State management with Arc

**Standard Endpoints** (customize for your domain):
```
GET  /health              → Health check (200 OK)
GET  /{{main_type_plural}}         → List all items
GET  /{{main_type_plural}}/:id     → Get specific item
POST /{{main_type_plural}}         → Create new item
PUT  /{{main_type_plural}}/:id     → Update item
DELETE /{{main_type_plural}}/:id   → Delete item
```

**Customization**:
1. Add domain-specific endpoints
2. Add request/response validation
3. Add filtering, sorting, pagination
4. Add authentication/authorization
5. Add error response formatting
6. Add structured logging

---

## NuShell Tool Template (`nushell-tool/`)

### Purpose
Create complete NuShell-based tool (single-file implementation).

### Files Included

#### `tool.nu.template`
**Purpose**: Complete NuShell tool with configuration discovery

**When to use**:
- Creating scripts/tool-id.nu
- For simple utilities or scripts
- Alternative to Rust for lightweight tools

**Key content**:
- Configuration discovery (same search order as Rust)
- Standard functions: list, create, summary, validate config
- Main entry point with help
- Proper error handling with logging

**Customization**:
1. Add domain-specific functions
2. Implement actual logic instead of placeholders
3. Add validation functions
4. Add data persistence if needed
5. Add comprehensive documentation in function comments

---

## Documentation Templates (`documentation/`)

### Purpose
Provide consistent structure for README, QUICKSTART, and other documentation.

### Files Included

#### `README.md.template`
**Purpose**: Complete feature reference documentation

**Sections**:
1. **Title & Description** - What is this tool?
2. **Features** - List 5-10 key features with descriptions
3. **Architecture** - Explain 3-tier structure
4. **Installation** - Step-by-step setup
5. **Configuration** - Configuration discovery section (REQUIRED)
6. **CLI Commands** - Reference for all commands
7. **API Endpoints** - If REST API included
8. **Examples** - Real-world usage examples
9. **Troubleshooting** - Common problems and solutions
10. **Development** - How to extend/contribute

**Required Sections** (don't skip):
- Configuration discovery with search order
- Installation from source
- Example usage

#### `QUICKSTART.md.template`
**Purpose**: 5-10 minute setup guide

**Sections**:
1. **Installation** - Fastest setup path
2. **Basic Usage** - Minimal working example
3. **Configuration** - Quick config setup
4. **First Command** - "Hello World" equivalent
5. **Next Steps** - Links to full documentation

**Important**: Must be doable in 5-10 minutes end-to-end

#### `architecture.md.template`
**Purpose**: Detailed system design documentation

**Sections**:
1. **Overview** - High-level description
2. **3-Tier Architecture** - Explain each tier
3. **Data Flow** - How data moves through system
4. **Component Diagram** - ASCII or link to diagram
5. **Module Organization** - Directory structure
6. **Error Handling** - How errors propagate
7. **Configuration** - Configuration system explanation
8. **Extension Points** - How to extend tool

#### `configuration.md.template`
**Purpose**: Configuration system documentation

**Sections**:
1. **Configuration Files** - TOML structure
2. **Search Order** - Where tool looks for config
3. **Environment Variables** - ENV var support
4. **Default Values** - What defaults are used
5. **Validation** - Config validation rules
6. **Examples** - Real config examples
7. **Troubleshooting** - Config problems

#### `examples/config.toml.template`
**Purpose**: Annotated configuration example

**Content**:
- Complete, valid TOML configuration
- Comments explaining each section
- All available options documented
- Ready to copy and modify

**Structure**:
```toml
# Section 1: Main settings
[tool_name]
setting1 = "value1"
setting2 = 42

# Section 2: Advanced options
[tool_name.advanced]
feature_flag = true

# Section 3: Database
[database]
type = "sqlite"
path = ".project/tool.db"
```

---

## Template Variable Reference

### Standard Variables (Use in ALL templates)

| Variable | Type | Example | Where Used |
|----------|------|---------|-----------|
| `{{TOOL_NAME}}` | Module name | TrackingManager | error.rs, lib.rs, help text |
| `{{ToolName}}` | CamelCase type | TrackingManager | error.rs (ErrorKind, Error structs) |
| `{{tool_name_kebab}}` | Command name | tracking-manager | main.rs, config file names, commands |
| `{{MainType}}` | Domain type | TrackingItem | types.rs (struct name), service.rs |
| `{{main_type_plural}}` | Plural | items | API routes, help text |
| `{{SHORT_DESCRIPTION}}` | One-liner | Unified change tracking | Help text, README |

### Replacement Examples

**For a "Blog" tool:**
```
{{TOOL_NAME}}           → Blog
{{ToolName}}            → Blog
{{tool_name_kebab}}     → blog
{{MainType}}            → BlogPost
{{main_type_plural}}    → posts
{{SHORT_DESCRIPTION}}   → Create and manage blog posts
```

**For "Analytics Tool":**
```
{{TOOL_NAME}}           → AnalyticsTool
{{ToolName}}            → AnalyticsTool
{{tool_name_kebab}}     → analytics-tool
{{MainType}}            → AnalyticsEvent
{{main_type_plural}}    → events
{{SHORT_DESCRIPTION}}   → Collect and analyze usage metrics
```

---

## How to Use Templates

### Quick Start (5 minutes)

1. **Copy template to your project**:
   ```bash
   cp /Users/Akasha/Tools/shared/templates/rust-core/lib.rs.template \
      crates/my-tool-core/src/lib.rs
   ```

2. **Replace variables** (find & replace):
   ```bash
   # Use your editor's find & replace
   {{TOOL_NAME}}        → MyTool
   {{ToolName}}         → MyTool
   {{tool_name_kebab}}  → my-tool
   {{MainType}}         → MyItem
   ```

3. **Customize for your domain**:
   - Add domain-specific fields to types.rs
   - Implement business logic in service.rs
   - Add domain-specific commands to CLI

4. **Test**:
   ```bash
   cargo check
   cargo test
   ```

### Detailed Process

1. **Read the template** - Understand what it does
2. **Review variables** - See what needs replacement
3. **Copy to project** - Use exact filename from template
4. **Replace all variables** - Use find & replace systematically
5. **Customize content** - Add domain-specific logic
6. **Add tests** - Extend test coverage
7. **Verify compilation** - `cargo check && cargo test`
8. **Documentation** - Update doc comments
9. **Quality check** - `cargo clippy && cargo fmt`
10. **Commit** - Save your work

---

## Template Quality Guarantees

All templates in this directory are:
- ✅ Production-ready code
- ✅ Follow Microsoft Pragmatic Rust Guidelines
- ✅ No unsafe code
- ✅ Comprehensive tests included
- ✅ 100% API documented
- ✅ Properly error handled
- ✅ Compiled and verified
- ✅ Integrated with tools-shared (Rust)

---

## Testing Templates

Before using a template in your project:

```bash
# Verify template compiles and runs tests
cd /Users/Akasha/Tools/shared/templates/rust-core
cargo test --template  # (if implemented)
```

---

## Common Customizations

### Add a new error variant:

In `error.rs`:
```rust
pub enum {{ToolName}}ErrorKind {
    // ... existing
    NetworkError(String),  // ← Add this
}

impl fmt::Display for {{ToolName}}ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            // ... existing
            Self::NetworkError(msg) => write!(f, "Network error: {}", msg),
        }
    }
}
```

### Add a new service method:

In `handlers/service.rs`:
```rust
impl {{MainType}}Service {
    pub async fn search(&self, query: &str) -> Result<Vec<{{MainType}}>> {
        let items = self.items.lock().await;
        Ok(items.values()
            .filter(|item| item.name.contains(query))
            .cloned()
            .collect())
    }
}
```

### Add a new CLI command:

In `main.rs`:
```rust
#[derive(Subcommand)]
enum Commands {
    // ... existing
    Search {
        query: String,
    },
}

match cli.command {
    Commands::Search { query } => {
        println!("Searching for: {}", query);
    }
}
```

---

## Next Steps

1. **Choose a template** - Decide Rust vs NuShell
2. **Copy files** - Copy from shared/templates/ to your project
3. **Replace variables** - Systematically replace all {{VARIABLE}}
4. **Customize** - Add your domain logic
5. **Test** - `cargo test --workspace`
6. **Document** - Fill in your specific details
7. **Validate** - Run `/validate-tool` command
8. **Integrate** - Add to Tools ecosystem

---

## Reference

- **Complete Guideline**: `/Users/Akasha/Tools/NEW_TOOL_GUIDELINE.md`
- **Tool Creator Skill**: `.claude/skills/new-tool-creator.md`
- **Template Usage Skill**: `.claude/skills/template-usage.md`
- **New Tool Command**: `/new-tool`
- **Example Tools**: tracking-manager, doc-syntaxis, presentation-generator
