---
name: backend-development-feature-development
description: "Orchestrate end-to-end backend feature development from requirements to deployment. Use when coordinating multi-phase feature delivery across teams and services."
risk: critical
source: community
date_added: "2026-02-27"
---

Orchestrate end-to-end feature development from requirements to production deployment:

[Extended thinking: This workflow orchestrates specialized agents through comprehensive feature development phases - from discovery and planning through implementation, testing, and deployment. Each phase builds on previous outputs, ensuring coherent feature delivery. The workflow supports multiple development methodologies (traditional, TDD/BDD, DDD), feature complexity levels, and modern deployment strategies including feature flags, gradual rollouts, and observability-first development. Agents receive detailed context from previous phases to maintain consistency and quality throughout the development lifecycle.]

## Use this skill when

- Coordinating end-to-end feature delivery across backend, frontend, and data
- Managing requirements, architecture, implementation, testing, and rollout
- Planning multi-service changes with deployment and monitoring needs
- Aligning teams on scope, risks, and success metrics

## Do not use this skill when

- The task is a small, isolated backend change or bug fix
- You only need a single specialist task, not a full workflow
- There is no deployment or cross-team coordination involved

## Instructions

1. Confirm feature scope, success metrics, and constraints.
2. Select a methodology and define phase outputs.
3. Orchestrate implementation, testing, and security validation.
4. Prepare rollout, monitoring, and documentation plans.

## Safety

- Avoid production changes without approvals and rollback plans.
- Validate data migrations and feature flags in staging first.

## Configuration Options

### Development Methodology

- **traditional**: Sequential development with testing after implementation
- **tdd**: Test-Driven Development with red-green-refactor cycles
- **bdd**: Behavior-Driven Development with scenario-based testing
- **ddd**: Domain-Driven Design with bounded contexts and aggregates

### Feature Complexity

- **simple**: Single service, minimal integration (1-2 days)
- **medium**: Multiple services, moderate integration (3-5 days)
- **complex**: Cross-domain, extensive integration (1-2 weeks)
- **epic**: Major architectural changes, multiple teams (2+ weeks)

### Deployment Strategy

- **direct**: Immediate rollout to all users
- **canary**: Gradual rollout starting with 5% of traffic
- **feature-flag**: Controlled activation via feature toggles
- **blue-green**: Zero-downtime deployment with instant rollback
- **a-b-test**: Split traffic for experimentation and metrics

## Phase 1: Discovery & Requirements Planning

1. **Business Analysis & Requirements**
   - Use Task tool with subagent_type="business-analytics::business-analyst"
   - Prompt: "Analyze feature requirements for: $ARGUMENTS. Define user stories, acceptance criteria, success metrics, and business value. Identify stakeholders, dependencies, and risks. Create feature specification document with clear scope boundaries."
   - Expected output: Requirements document with user stories, success metrics, risk assessment
   - Context: Initial feature request and business context

2. **Technical Architecture Design**
   - Use Task tool with subagent_type="comprehensive-review::architect-review"
   - Prompt: "Design technical architecture for feature: $ARGUMENTS. Using requirements: [include business analysis from step 1]. Define service boundaries, API contracts, data models, integration points, and technology stack. Consider scalability, performance, and security requirements."
   - Expected output: Technical design document with architecture diagrams, API specifications, data models
   - Context: Business requirements, existing system architecture

3. **Feasibility & Risk Assessment**
   - Use Task tool with subagent_type="security-scanning::security-auditor"
   - Prompt: "Assess security implications and risks for feature: $ARGUMENTS. Review architecture: [include technical design from step 2]. Identify security requirements, compliance needs, data privacy concerns, and potential vulnerabilities."
   - Expected output: Security assessment with risk matrix, compliance checklist, mitigation strategies
   - Context: Technical design, regulatory requirements

## Phase 2: Implementation & Development

4. **Backend Services Implementation**
   - Use Task tool with subagent_type="backend-architect"
   - Prompt: "Implement backend services for: $ARGUMENTS. Follow technical design: [include architecture from step 2]. Build RESTful/GraphQL APIs, implement business logic, integrate with data layer, add resilience patterns (circuit breakers, retries), implement caching strategies. Include feature flags for gradual rollout."
   - Expected output: Backend services with APIs, business logic, database integration, feature flags
   - Context: Technical design, API contracts, data models

5. **Frontend Implementation**
   - Use Task tool with subagent_type="frontend-mobile-development::frontend-developer"
   - Prompt: "Build frontend components for: $ARGUMENTS. Integrate with backend APIs: [include API endpoints from step 4]. Implement responsive UI, state management, error handling, loading states, and analytics tracking. Add feature flag integration for A/B testing capabilities."
   - Expected output: Frontend components with API integration, state management, analytics
   - Context: Backend APIs, UI/UX designs, user stories

6. **Data Pipeline & Integration**
   - Use Task tool with subagent_type="data-engineering::data-engineer"
   - Prompt: "Build data pipelines for: $ARGUMENTS. Design ETL/ELT processes, implement data validation, create analytics events, set up data quality monitoring. Integrate with product analytics platforms for feature usage tracking."
   - Expected output: Data pipelines, analytics events, data quality checks
   - Context: Data requirements, analytics needs, existing data infrastructure

## Phase 3: Testing & Quality Assurance

7. **Automated Test Suite**
   - Use Task tool with subagent_type="unit-testing::test-automator"
   - Prompt: "Create comprehensive test suite for: $ARGUMENTS. Write unit tests for backend: [from step 4] and frontend: [from step 5]. Add integration tests for API endpoints, E2E tests for critical user journeys, performance tests for scalability validation. Ensure minimum 80% code coverage."
   - Expected output: Test suites with unit, integration, E2E, and performance tests
   - Context: Implementation code, acceptance criteria, test requirements

8. **Security Validation**
   - Use Task tool with subagent_type="security-scanning::security-auditor"
   - Prompt: "Perform security testing for: $ARGUMENTS. Review implementation: [include backend and frontend from steps 4-5]. Run OWASP checks, penetration testing, dependency scanning, and compliance validation. Verify data encryption, authentication, and authorization."
   - Expected output: Security test results, vulnerability report, remediation actions
   - Context: Implementation code, security requirements

9. **Performance Optimization**
   - Use Task tool with subagent_type="application-performance::performance-engineer"
   - Prompt: "Optimize performance for: $ARGUMENTS. Analyze backend services: [from step 4] and frontend: [from step 5]. Profile code, optimize queries, implement caching, reduce bundle sizes, improve load times. Set up performance budgets and monitoring."
   - Expected output: Performance improvements, optimization report, performance metrics
   - Context: Implementation code, performance requirements

## Phase 4: Deployment & Monitoring

10. **Deployment Strategy & Pipeline**
    - Use Task tool with subagent_type="deployment-strategies::deployment-engineer"
    - Prompt: "Prepare deployment for: $ARGUMENTS. Create CI/CD pipeline with automated tests: [from step 7]. Configure feature flags for gradual rollout, implement blue-green deployment, set up rollback procedures. Create deployment runbook and rollback plan."
    - Expected output: CI/CD pipeline, deployment configuration, rollback procedures
    - Context: Test suites, infrastructure requirements, deployment strategy

11. **Observability & Monitoring**
    - Use Task tool with subagent_type="observability-monitoring::observability-engineer"
    - Prompt: "Set up observability for: $ARGUMENTS. Implement distributed tracing, custom metrics, error tracking, and alerting. Create dashboards for feature usage, performance metrics, error rates, and business KPIs. Set up SLOs/SLIs with automated alerts."
    - Expected output: Monitoring dashboards, alerts, SLO definitions, observability infrastructure
    - Context: Feature implementation, success metrics, operational requirements

12. **Documentation & Knowledge Transfer**
    - Use Task tool with subagent_type="documentation-generation::docs-architect"
    - Prompt: "Generate comprehensive documentation for: $ARGUMENTS. Create API documentation, user guides, deployment guides, troubleshooting runbooks. Include architecture diagrams, data flow diagrams, and integration guides. Generate automated changelog from commits."
    - Expected output: API docs, user guides, runbooks, architecture documentation
    - Context: All previous phases' outputs

## Execution Parameters

### Required Parameters

- **--feature**: Feature name and description
- **--methodology**: Development approach (traditional|tdd|bdd|ddd)
- **--complexity**: Feature complexity level (simple|medium|complex|epic)

### Optional Parameters

- **--deployment-strategy**: Deployment approach (direct|canary|feature-flag|blue-green|a-b-test)
- **--test-coverage-min**: Minimum test coverage threshold (default: 80%)
- **--performance-budget**: Performance requirements (e.g., <200ms response time)
- **--rollout-percentage**: Initial rollout percentage for gradual deployment (default: 5%)
- **--feature-flag-service**: Feature flag provider (launchdarkly|split|unleash|custom)
- **--analytics-platform**: Analytics integration (segment|amplitude|mixpanel|custom)
- **--monitoring-stack**: Observability tools (datadog|newrelic|grafana|custom)

## Success Criteria

- All acceptance criteria from business requirements are met
- Test coverage exceeds minimum threshold (80% default)
- Security scan shows no critical vulnerabilities
- Performance meets defined budgets and SLOs
- Feature flags configured for controlled rollout
- Monitoring and alerting fully operational
- Documentation complete and approved
- Successful deployment to production with rollback capability
- Product analytics tracking feature usage
- A/B test metrics configured (if applicable)

## Rollback Strategy

If issues arise during or after deployment:

1. Immediate feature flag disable (< 1 minute)
2. Blue-green traffic switch (< 5 minutes)
3. Full deployment rollback via CI/CD (< 15 minutes)
4. Database migration rollback if needed (coordinate with data team)
5. Incident post-mortem and fixes before re-deployment

Feature description: $ARGUMENTS

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: backend-security-coder
description: Expert in secure backend coding practices specializing in input validation, authentication, and API security. Use PROACTIVELY for backend security implementations or security code reviews.
risk: critical
source: community
date_added: '2026-02-27'
---

## Use this skill when

- Working on backend security coder tasks or workflows
- Needing guidance, best practices, or checklists for backend security coder

## Do not use this skill when

- The task is unrelated to backend security coder
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

You are a backend security coding expert specializing in secure development practices, vulnerability prevention, and secure architecture implementation.

## Purpose
Expert backend security developer with comprehensive knowledge of secure coding practices, vulnerability prevention, and defensive programming techniques. Masters input validation, authentication systems, API security, database protection, and secure error handling. Specializes in building security-first backend applications that resist common attack vectors.

## When to Use vs Security Auditor
- **Use this agent for**: Hands-on backend security coding, API security implementation, database security configuration, authentication system coding, vulnerability fixes
- **Use security-auditor for**: High-level security audits, compliance assessments, DevSecOps pipeline design, threat modeling, security architecture reviews, penetration testing planning
- **Key difference**: This agent focuses on writing secure backend code, while security-auditor focuses on auditing and assessing security posture

## Capabilities

### General Secure Coding Practices
- **Input validation and sanitization**: Comprehensive input validation frameworks, allowlist approaches, data type enforcement
- **Injection attack prevention**: SQL injection, NoSQL injection, LDAP injection, command injection prevention techniques
- **Error handling security**: Secure error messages, logging without information leakage, graceful degradation
- **Sensitive data protection**: Data classification, secure storage patterns, encryption at rest and in transit
- **Secret management**: Secure credential storage, environment variable best practices, secret rotation strategies
- **Output encoding**: Context-aware encoding, preventing injection in templates and APIs

### HTTP Security Headers and Cookies
- **Content Security Policy (CSP)**: CSP implementation, nonce and hash strategies, report-only mode
- **Security headers**: HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy implementation
- **Cookie security**: HttpOnly, Secure, SameSite attributes, cookie scoping and domain restrictions
- **CORS configuration**: Strict CORS policies, preflight request handling, credential-aware CORS
- **Session management**: Secure session handling, session fixation prevention, timeout management

### CSRF Protection
- **Anti-CSRF tokens**: Token generation, validation, and refresh strategies for cookie-based authentication
- **Header validation**: Origin and Referer header validation for non-GET requests
- **Double-submit cookies**: CSRF token implementation in cookies and headers
- **SameSite cookie enforcement**: Leveraging SameSite attributes for CSRF protection
- **State-changing operation protection**: Authentication requirements for sensitive actions

### Output Rendering Security
- **Context-aware encoding**: HTML, JavaScript, CSS, URL encoding based on output context
- **Template security**: Secure templating practices, auto-escaping configuration
- **JSON response security**: Preventing JSON hijacking, secure API response formatting
- **XML security**: XML external entity (XXE) prevention, secure XML parsing
- **File serving security**: Secure file download, content-type validation, path traversal prevention

### Database Security
- **Parameterized queries**: Prepared statements, ORM security configuration, query parameterization
- **Database authentication**: Connection security, credential management, connection pooling security
- **Data encryption**: Field-level encryption, transparent data encryption, key management
- **Access control**: Database user privilege separation, role-based access control
- **Audit logging**: Database activity monitoring, change tracking, compliance logging
- **Backup security**: Secure backup procedures, encryption of backups, access control for backup files

### API Security
- **Authentication mechanisms**: JWT security, OAuth 2.0/2.1 implementation, API key management
- **Authorization patterns**: RBAC, ABAC, scope-based access control, fine-grained permissions
- **Input validation**: API request validation, payload size limits, content-type validation
- **Rate limiting**: Request throttling, burst protection, user-based and IP-based limiting
- **API versioning security**: Secure version management, backward compatibility security
- **Error handling**: Consistent error responses, security-aware error messages, logging strategies

### External Requests Security
- **Allowlist management**: Destination allowlisting, URL validation, domain restriction
- **Request validation**: URL sanitization, protocol restrictions, parameter validation
- **SSRF prevention**: Server-side request forgery protection, internal network isolation
- **Timeout and limits**: Request timeout configuration, response size limits, resource protection
- **Certificate validation**: SSL/TLS certificate pinning, certificate authority validation
- **Proxy security**: Secure proxy configuration, header forwarding restrictions

### Authentication and Authorization
- **Multi-factor authentication**: TOTP, hardware tokens, biometric integration, backup codes
- **Password security**: Hashing algorithms (bcrypt, Argon2), salt generation, password policies
- **Session security**: Secure session tokens, session invalidation, concurrent session management
- **JWT implementation**: Secure JWT handling, signature verification, token expiration
- **OAuth security**: Secure OAuth flows, PKCE implementation, scope validation

### Logging and Monitoring
- **Security logging**: Authentication events, authorization failures, suspicious activity tracking
- **Log sanitization**: Preventing log injection, sensitive data exclusion from logs
- **Audit trails**: Comprehensive activity logging, tamper-evident logging, log integrity
- **Monitoring integration**: SIEM integration, alerting on security events, anomaly detection
- **Compliance logging**: Regulatory requirement compliance, retention policies, log encryption

### Cloud and Infrastructure Security
- **Environment configuration**: Secure environment variable management, configuration encryption
- **Container security**: Secure Docker practices, image scanning, runtime security
- **Secrets management**: Integration with HashiCorp Vault, AWS Secrets Manager, Azure Key Vault
- **Network security**: VPC configuration, security groups, network segmentation
- **Identity and access management**: IAM roles, service account security, principle of least privilege

## Behavioral Traits
- Validates and sanitizes all user inputs using allowlist approaches
- Implements defense-in-depth with multiple security layers
- Uses parameterized queries and prepared statements exclusively
- Never exposes sensitive information in error messages or logs
- Applies principle of least privilege to all access controls
- Implements comprehensive audit logging for security events
- Uses secure defaults and fails securely in error conditions
- Regularly updates dependencies and monitors for vulnerabilities
- Considers security implications in every design decision
- Maintains separation of concerns between security layers

## Knowledge Base
- OWASP Top 10 and secure coding guidelines
- Common vulnerability patterns and prevention techniques
- Authentication and authorization best practices
- Database security and query parameterization
- HTTP security headers and cookie security
- Input validation and output encoding techniques
- Secure error handling and logging practices
- API security and rate limiting strategies
- CSRF and SSRF prevention mechanisms
- Secret management and encryption practices

## Response Approach
1. **Assess security requirements** including threat model and compliance needs
2. **Implement input validation** with comprehensive sanitization and allowlist approaches
3. **Configure secure authentication** with multi-factor authentication and session management
4. **Apply database security** with parameterized queries and access controls
5. **Set security headers** and implement CSRF protection for web applications
6. **Implement secure API design** with proper authentication and rate limiting
7. **Configure secure external requests** with allowlists and validation
8. **Set up security logging** and monitoring for threat detection
9. **Review and test security controls** with both automated and manual testing

## Example Interactions
- "Implement secure user authentication with JWT and refresh token rotation"
- "Review this API endpoint for injection vulnerabilities and implement proper validation"
- "Configure CSRF protection for cookie-based authentication system"
- "Implement secure database queries with parameterization and access controls"
- "Set up comprehensive security headers and CSP for web application"
- "Create secure error handling that doesn't leak sensitive information"
- "Implement rate limiting and DDoS protection for public API endpoints"
- "Design secure external service integration with allowlist validation"

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: backtesting-frameworks
description: "Build robust, production-grade backtesting systems that avoid common pitfalls and produce reliable strategy performance estimates."
risk: safe
source: community
date_added: "2026-02-27"
---

# Backtesting Frameworks

Build robust, production-grade backtesting systems that avoid common pitfalls and produce reliable strategy performance estimates.

## Use this skill when

- Developing trading strategy backtests
- Building backtesting infrastructure
- Validating strategy performance and robustness
- Avoiding common backtesting biases
- Implementing walk-forward analysis

## Do not use this skill when

- You need live trading execution or investment advice
- Historical data quality is unknown or incomplete
- The task is only a quick performance summary

## Instructions

- Define hypothesis, universe, timeframe, and evaluation criteria.
- Build point-in-time data pipelines and realistic cost models.
- Implement event-driven simulation and execution logic.
- Use train/validation/test splits and walk-forward testing.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Safety

- Do not present backtests as guarantees of future performance.
- Avoid providing financial or investment advice.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: bamboohr-automation
description: "Automate BambooHR tasks via Rube MCP (Composio): employees, time-off, benefits, dependents, employee updates. Always search tools first for current schemas."
risk: critical
source: community
date_added: "2026-02-27"
---

# BambooHR Automation via Rube MCP

Automate BambooHR human resources operations through Composio's BambooHR toolkit via Rube MCP.

## Prerequisites

- Rube MCP must be connected (RUBE_SEARCH_TOOLS available)
- Active BambooHR connection via `RUBE_MANAGE_CONNECTIONS` with toolkit `bamboohr`
- Always call `RUBE_SEARCH_TOOLS` first to get current tool schemas

## Setup

**Get Rube MCP**: Add `https://rube.app/mcp` as an MCP server in your client configuration. No API keys needed — just add the endpoint and it works.

1. Verify Rube MCP is available by confirming `RUBE_SEARCH_TOOLS` responds
2. Call `RUBE_MANAGE_CONNECTIONS` with toolkit `bamboohr`
3. If connection is not ACTIVE, follow the returned auth link to complete BambooHR authentication
4. Confirm connection status shows ACTIVE before running any workflows

## Core Workflows

### 1. List and Search Employees

**When to use**: User wants to find employees or get the full employee directory

**Tool sequence**:
1. `BAMBOOHR_GET_ALL_EMPLOYEES` - Get the employee directory [Required]
2. `BAMBOOHR_GET_EMPLOYEE` - Get detailed info for a specific employee [Optional]

**Key parameters**:
- For GET_ALL_EMPLOYEES: No required parameters; returns directory
- For GET_EMPLOYEE:
  - `id`: Employee ID (numeric)
  - `fields`: Comma-separated list of fields to return (e.g., 'firstName,lastName,department,jobTitle')

**Pitfalls**:
- Employee IDs are numeric integers
- GET_ALL_EMPLOYEES returns basic directory info; use GET_EMPLOYEE for full details
- The `fields` parameter controls which fields are returned; omitting it may return minimal data
- Common fields: firstName, lastName, department, division, jobTitle, workEmail, status
- Inactive/terminated employees may be included; check `status` field

### 2. Track Employee Changes

**When to use**: User wants to detect recent employee data changes for sync or auditing

**Tool sequence**:
1. `BAMBOOHR_EMPLOYEE_GET_CHANGED` - Get employees with recent changes [Required]

**Key parameters**:
- `since`: ISO 8601 datetime string for change detection threshold
- `type`: Type of changes to check (e.g., 'inserted', 'updated', 'deleted')

**Pitfalls**:
- `since` parameter is required; use ISO 8601 format (e.g., '2024-01-15T00:00:00Z')
- Returns IDs of changed employees, not full employee data
- Must call GET_EMPLOYEE separately for each changed employee's details
- Useful for incremental sync workflows; cache the last sync timestamp

### 3. Manage Time-Off

**When to use**: User wants to view time-off balances, request time off, or manage requests

**Tool sequence**:
1. `BAMBOOHR_GET_META_TIME_OFF_TYPES` - List available time-off types [Prerequisite]
2. `BAMBOOHR_GET_TIME_OFF_BALANCES` - Check current balances [Optional]
3. `BAMBOOHR_GET_TIME_OFF_REQUESTS` - List existing requests [Optional]
4. `BAMBOOHR_CREATE_TIME_OFF_REQUEST` - Submit a new request [Optional]
5. `BAMBOOHR_UPDATE_TIME_OFF_REQUEST` - Modify or approve/deny a request [Optional]

**Key parameters**:
- For balances: `employeeId`, time-off type ID
- For requests: `start`, `end` (date range), `employeeId`
- For creation:
  - `employeeId`: Employee to request for
  - `timeOffTypeId`: Type ID from GET_META_TIME_OFF_TYPES
  - `start`: Start date (YYYY-MM-DD)
  - `end`: End date (YYYY-MM-DD)
  - `amount`: Number of days/hours
  - `notes`: Optional notes for the request
- For update: `requestId`, `status` ('approved', 'denied', 'cancelled')

**Pitfalls**:
- Time-off type IDs are numeric; resolve via GET_META_TIME_OFF_TYPES first
- Date format is 'YYYY-MM-DD' for start and end dates
- Balances may be in hours or days depending on company configuration
- Request status updates require appropriate permissions (manager/admin)
- Creating a request does NOT auto-approve it; separate approval step needed

### 4. Update Employee Information

**When to use**: User wants to modify employee profile data

**Tool sequence**:
1. `BAMBOOHR_GET_EMPLOYEE` - Get current employee data [Prerequisite]
2. `BAMBOOHR_UPDATE_EMPLOYEE` - Update employee fields [Required]

**Key parameters**:
- `id`: Employee ID (numeric, required)
- Field-value pairs for the fields to update (e.g., `department`, `jobTitle`, `workPhone`)

**Pitfalls**:
- Only fields included in the request are updated; others remain unchanged
- Some fields are read-only and cannot be updated via API
- Field names must match BambooHR's expected field names exactly
- Updates are audited; changes appear in the employee's change history
- Verify current values with GET_EMPLOYEE before updating to avoid overwriting

### 5. Manage Dependents and Benefits

**When to use**: User wants to view employee dependents or benefit coverage

**Tool sequence**:
1. `BAMBOOHR_DEPENDENTS_GET_ALL` - List all dependents [Required]
2. `BAMBOOHR_BENEFIT_GET_COVERAGES` - Get benefit coverage details [Optional]

**Key parameters**:
- For dependents: Optional `employeeId` filter
- For benefits: Depends on schema; check RUBE_SEARCH_TOOLS for current parameters

**Pitfalls**:
- Dependent data includes sensitive PII; handle with appropriate care
- Benefit coverages may include multiple plan types per employee
- Not all BambooHR plans include benefits administration; check account features
- Data access depends on API key permissions

## Common Patterns

### ID Resolution

**Employee name -> Employee ID**:
```
1. Call BAMBOOHR_GET_ALL_EMPLOYEES
2. Find employee by name in directory results
3. Extract id (numeric) for detailed operations
```

**Time-off type name -> Type ID**:
```
1. Call BAMBOOHR_GET_META_TIME_OFF_TYPES
2. Find type by name (e.g., 'Vacation', 'Sick Leave')
3. Extract id for time-off requests
```

### Incremental Sync Pattern

For keeping external systems in sync with BambooHR:
```
1. Store last_sync_timestamp
2. Call BAMBOOHR_EMPLOYEE_GET_CHANGED with since=last_sync_timestamp
3. For each changed employee ID, call BAMBOOHR_GET_EMPLOYEE
4. Process updates in external system
5. Update last_sync_timestamp
```

### Time-Off Workflow

```
1. GET_META_TIME_OFF_TYPES -> find type ID
2. GET_TIME_OFF_BALANCES -> verify available balance
3. CREATE_TIME_OFF_REQUEST -> submit request
4. UPDATE_TIME_OFF_REQUEST -> approve/deny (manager action)
```

## Known Pitfalls

**Employee IDs**:
- Always numeric integers
- Resolve names to IDs via GET_ALL_EMPLOYEES
- Terminated employees retain their IDs

**Date Formats**:
- Time-off dates: 'YYYY-MM-DD'
- Change detection: ISO 8601 with timezone
- Inconsistent formats between endpoints; check each endpoint's schema

**Permissions**:
- API key permissions determine accessible fields and operations
- Some operations require admin or manager-level access
- Time-off approvals require appropriate role permissions

**Sensitive Data**:
- Employee data includes PII (names, addresses, SSN, etc.)
- Handle all responses with appropriate security measures
- Dependent data is especially sensitive

**Rate Limits**:
- BambooHR API has rate limits per API key
- Bulk operations should be throttled
- GET_ALL_EMPLOYEES is more efficient than individual GET_EMPLOYEE calls

**Response Parsing**:
- Response data may be nested under `data` key
- Employee fields vary based on `fields` parameter
- Empty fields may be omitted or returned as null
- Parse defensively with fallbacks

## Quick Reference

| Task | Tool Slug | Key Params |
|------|-----------|------------|
| List all employees | BAMBOOHR_GET_ALL_EMPLOYEES | (none) |
| Get employee details | BAMBOOHR_GET_EMPLOYEE | id, fields |
| Track changes | BAMBOOHR_EMPLOYEE_GET_CHANGED | since, type |
| Time-off types | BAMBOOHR_GET_META_TIME_OFF_TYPES | (none) |
| Time-off balances | BAMBOOHR_GET_TIME_OFF_BALANCES | employeeId |
| List time-off requests | BAMBOOHR_GET_TIME_OFF_REQUESTS | start, end, employeeId |
| Create time-off request | BAMBOOHR_CREATE_TIME_OFF_REQUEST | employeeId, timeOffTypeId, start, end |
| Update time-off request | BAMBOOHR_UPDATE_TIME_OFF_REQUEST | requestId, status |
| Update employee | BAMBOOHR_UPDATE_EMPLOYEE | id, (field updates) |
| List dependents | BAMBOOHR_DEPENDENTS_GET_ALL | employeeId |
| Benefit coverages | BAMBOOHR_BENEFIT_GET_COVERAGES | (check schema) |

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: base
description: "Database management, forms, reports, and data operations with LibreOffice Base."
category: database-processing
risk: safe
source: personal
date_added: "2026-02-27"
---

# LibreOffice Base

## Overview

LibreOffice Base skill for creating, managing, and automating database workflows using the native ODB (OpenDocument Database) format.

## When to Use This Skill

Use this skill when:
- Creating new databases in ODB format
- Connecting to external databases (MySQL, PostgreSQL, etc.)
- Automating database operations and reports
- Creating forms and reports
- Building database applications

## Core Capabilities

### 1. Database Creation
- Create new ODB databases from scratch
- Design tables, views, and relationships
- Create embedded HSQLDB/Firebird databases
- Connect to external databases

### 2. Data Operations
- Import data from CSV, spreadsheets
- Export data to various formats
- Query execution and management
- Batch data processing

### 3. Form and Report Automation
- Create data entry forms
- Design custom reports
- Automate report generation
- Build form templates

### 4. Query and SQL
- Visual query design
- SQL query execution
- Query optimization
- Result set manipulation

### 5. Integration
- Command-line automation
- Python scripting with UNO
- JDBC/ODBC connectivity

## Workflows

### Creating a New Database

#### Method 1: Command-Line
```bash
soffice --base
```

#### Method 2: Python with UNO
```python
import uno

def create_database():
    local_ctx = uno.getComponentContext()
    resolver = local_ctx.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", local_ctx
    )
    ctx = resolver.resolve(
        "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext"
    )
    smgr = ctx.ServiceManager
    doc = smgr.createInstanceWithContext("com.sun.star.sdb.DatabaseDocument", ctx)
    doc.storeToURL("file:///path/to/database.odb", ())
    doc.close(True)
```

### Connecting to External Database

```python
import uno

def connect_to_mysql(host, port, database, user, password):
    local_ctx = uno.getComponentContext()
    resolver = local_ctx.ServiceManager.createInstanceWithContext(
        "com.sun.star.bridge.UnoUrlResolver", local_ctx
    )
    ctx = resolver.resolve(
        "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext"
    )
    smgr = ctx.ServiceManager

    doc = smgr.createInstanceWithContext("com.sun.star.sdb.DatabaseDocument", ctx)
    datasource = doc.getDataSource()
    datasource.URL = f"sdbc:mysql:jdbc:mysql://{host}:{port}/{database}"
    datasource.Properties["UserName"] = user
    datasource.Properties["Password"] = password

    doc.storeToURL("file:///path/to/connected.odb", ())
    return doc
```

## Database Connection Reference

### Supported Database Types
- HSQLDB (embedded)
- Firebird (embedded)
- MySQL/MariaDB
- PostgreSQL
- SQLite
- ODBC data sources
- JDBC data sources

### Connection Strings

```
# MySQL
sdbc:mysql:jdbc:mysql://localhost:3306/database

# PostgreSQL
sdbc:postgresql://localhost:5432/database

# SQLite
sdbc:sqlite:file:///path/to/database.db

# ODBC
sdbc:odbc:DSN_NAME
```

## Command-Line Reference

```bash
soffice --headless
soffice --base  # Base
```

## Python Libraries

```bash
pip install pyodbc    # ODBC connectivity
pip install sqlalchemy # SQL toolkit
```

## Best Practices

1. Use parameterized queries
2. Create indexes for performance
3. Backup databases regularly
4. Use transactions for data integrity
5. Store ODB source files in version control
6. Document database schema
7. Use appropriate data types
8. Handle connection errors gracefully

## Troubleshooting

### Cannot open socket
```bash
killall soffice.bin
soffice --headless --accept="socket,host=localhost,port=8100;urp;"
```

### Connection Issues
- Verify database server is running
- Check connection string format
- Ensure JDBC/ODBC drivers are installed
- Verify network connectivity

## Resources

- [LibreOffice Base Guide](https://documentation.libreoffice.org/)
- [UNO API Reference](https://api.libreoffice.org/)
- [HSQLDB Documentation](http://hsqldb.org/)
- [Firebird Documentation](https://firebirdsql.org/)

## Related Skills

- writer
- calc
- impress
- draw
- workflow-automation

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: basecamp-automation
description: "Automate Basecamp project management, to-dos, messages, people, and to-do list organization via Rube MCP (Composio). Always search tools first for current schemas."
risk: critical
source: community
date_added: "2026-02-27"
---

# Basecamp Automation via Rube MCP

Automate Basecamp operations including project management, to-do list creation, task management, message board posting, people management, and to-do group organization through Composio's Basecamp toolkit.

## Prerequisites

- Rube MCP must be connected (RUBE_SEARCH_TOOLS available)
- Active Basecamp connection via `RUBE_MANAGE_CONNECTIONS` with toolkit `basecamp`
- Always call `RUBE_SEARCH_TOOLS` first to get current tool schemas

## Setup

**Get Rube MCP**: Add `https://rube.app/mcp` as an MCP server in your client configuration. No API keys needed — just add the endpoint and it works.

1. Verify Rube MCP is available by confirming `RUBE_SEARCH_TOOLS` responds
2. Call `RUBE_MANAGE_CONNECTIONS` with toolkit `basecamp`
3. If connection is not ACTIVE, follow the returned auth link to complete Basecamp OAuth
4. Confirm connection status shows ACTIVE before running any workflows

## Core Workflows

### 1. Manage To-Do Lists and Tasks

**When to use**: User wants to create to-do lists, add tasks, or organize work within a Basecamp project

**Tool sequence**:
1. `BASECAMP_GET_PROJECTS` - List projects to find the target bucket_id [Prerequisite]
2. `BASECAMP_GET_BUCKETS_TODOSETS` - Get the to-do set within a project [Prerequisite]
3. `BASECAMP_GET_BUCKETS_TODOSETS_TODOLISTS` - List existing to-do lists to avoid duplicates [Optional]
4. `BASECAMP_POST_BUCKETS_TODOSETS_TODOLISTS` - Create a new to-do list in a to-do set [Required for list creation]
5. `BASECAMP_GET_BUCKETS_TODOLISTS` - Get details of a specific to-do list [Optional]
6. `BASECAMP_POST_BUCKETS_TODOLISTS_TODOS` - Create a to-do item in a to-do list [Required for task creation]
7. `BASECAMP_CREATE_TODO` - Alternative tool for creating individual to-dos [Alternative]
8. `BASECAMP_GET_BUCKETS_TODOLISTS_TODOS` - List to-dos within a to-do list [Optional]

**Key parameters for creating to-do lists**:
- `bucket_id`: Integer project/bucket ID (from GET_PROJECTS)
- `todoset_id`: Integer to-do set ID (from GET_BUCKETS_TODOSETS)
- `name`: Title of the to-do list (required)
- `description`: HTML-formatted description (supports Rich text)

**Key parameters for creating to-dos**:
- `bucket_id`: Integer project/bucket ID
- `todolist_id`: Integer to-do list ID
- `content`: What the to-do is for (required)
- `description`: HTML details about the to-do
- `assignee_ids`: Array of integer person IDs
- `due_on`: Due date in `YYYY-MM-DD` format
- `starts_on`: Start date in `YYYY-MM-DD` format
- `notify`: Boolean to notify assignees (defaults to false)
- `completion_subscriber_ids`: Person IDs notified upon completion

**Pitfalls**:
- A project (bucket) can contain multiple to-do sets; selecting the wrong `todoset_id` creates lists in the wrong section
- Always check existing to-do lists before creating to avoid near-duplicate names
- Success payloads include user-facing URLs (`app_url`, `app_todos_url`); prefer returning these over raw IDs
- All IDs (`bucket_id`, `todoset_id`, `todolist_id`) are integers, not strings
- Descriptions support HTML formatting only, not Markdown

### 2. Post and Manage Messages

**When to use**: User wants to post messages to a project message board or update existing messages

**Tool sequence**:
1. `BASECAMP_GET_PROJECTS` - Find the target project and bucket_id [Prerequisite]
2. `BASECAMP_GET_MESSAGE_BOARD` - Get the message board ID for the project [Prerequisite]
3. `BASECAMP_CREATE_MESSAGE` - Create a new message on the board [Required]
4. `BASECAMP_POST_BUCKETS_MESSAGE_BOARDS_MESSAGES` - Alternative message creation tool [Fallback]
5. `BASECAMP_GET_MESSAGE` - Read a specific message by ID [Optional]
6. `BASECAMP_PUT_BUCKETS_MESSAGES` - Update an existing message [Optional]

**Key parameters**:
- `bucket_id`: Integer project/bucket ID
- `message_board_id`: Integer message board ID (from GET_MESSAGE_BOARD)
- `subject`: Message title (required)
- `content`: HTML body of the message
- `status`: Set to `"active"` to publish immediately
- `category_id`: Message type classification (optional)
- `subscriptions`: Array of person IDs to notify; omit to notify all project members

**Pitfalls**:
- `status="draft"` can produce HTTP 400; use `status="active"` as the reliable option
- `bucket_id` and `message_board_id` must belong to the same project; mismatches fail or misroute
- Message content supports HTML tags only; not Markdown
- Updates via `PUT_BUCKETS_MESSAGES` replace the entire body -- include the full corrected content, not just a diff
- Prefer `app_url` from the response for user-facing confirmation links
- Both `CREATE_MESSAGE` and `POST_BUCKETS_MESSAGE_BOARDS_MESSAGES` do the same thing; use CREATE_MESSAGE first and fall back to POST if it fails

### 3. Manage People and Access

**When to use**: User wants to list people, manage project access, or add new users

**Tool sequence**:
1. `BASECAMP_GET_PEOPLE` - List all people visible to the current user [Required]
2. `BASECAMP_GET_PROJECTS` - Find the target project [Prerequisite]
3. `BASECAMP_LIST_PROJECT_PEOPLE` - List people on a specific project [Required]
4. `BASECAMP_GET_PROJECTS_PEOPLE` - Alternative to list project members [Alternative]
5. `BASECAMP_PUT_PROJECTS_PEOPLE_USERS` - Grant or revoke project access [Required for access changes]

**Key parameters for PUT_PROJECTS_PEOPLE_USERS**:
- `project_id`: Integer project ID
- `grant`: Array of integer person IDs to add to the project
- `revoke`: Array of integer person IDs to remove from the project
- `create`: Array of objects with `name`, `email_address`, and optional `company_name`, `title` for new users
- At least one of `grant`, `revoke`, or `create` must be provided

**Pitfalls**:
- Person IDs are integers; always resolve names to IDs via GET_PEOPLE first
- `project_id` for people management is the same as `bucket_id` for other operations
- `LIST_PROJECT_PEOPLE` and `GET_PROJECTS_PEOPLE` are near-identical; use either
- Creating users via `create` also grants them project access in one step

### 4. Organize To-Dos with Groups

**When to use**: User wants to organize to-dos within a list into color-coded groups

**Tool sequence**:
1. `BASECAMP_GET_PROJECTS` - Find the target project [Prerequisite]
2. `BASECAMP_GET_BUCKETS_TODOLISTS` - Get the to-do list details [Prerequisite]
3. `BASECAMP_GET_TODOLIST_GROUPS` - List existing groups in a to-do list [Optional]
4. `BASECAMP_GET_BUCKETS_TODOLISTS_GROUPS` - Alternative group listing [Alternative]
5. `BASECAMP_POST_BUCKETS_TODOLISTS_GROUPS` - Create a new group in a to-do list [Required]
6. `BASECAMP_CREATE_TODOLIST_GROUP` - Alternative group creation tool [Alternative]

**Key parameters**:
- `bucket_id`: Integer project/bucket ID
- `todolist_id`: Integer to-do list ID
- `name`: Group title (required)
- `color`: Visual color identifier -- one of: `white`, `red`, `orange`, `yellow`, `green`, `blue`, `aqua`, `purple`, `gray`, `pink`, `brown`
- `status`: Filter for listing -- `"archived"` or `"trashed"` (omit for active groups)

**Pitfalls**:
- `POST_BUCKETS_TODOLISTS_GROUPS` and `CREATE_TODOLIST_GROUP` are near-identical; use either
- Color values must be from the fixed palette; arbitrary hex/rgb values are not supported
- Groups are sub-sections within a to-do list, not standalone entities

### 5. Browse and Inspect Projects

**When to use**: User wants to list projects, get project details, or explore project structure

**Tool sequence**:
1. `BASECAMP_GET_PROJECTS` - List all active projects [Required]
2. `BASECAMP_GET_PROJECT` - Get comprehensive details for a specific project [Optional]
3. `BASECAMP_GET_PROJECTS_BY_PROJECT_ID` - Alternative project detail retrieval [Alternative]

**Key parameters**:
- `status`: Filter by `"archived"` or `"trashed"`; omit for active projects
- `project_id`: Integer project ID for detailed retrieval

**Pitfalls**:
- Projects are sorted by most recently created first
- The response includes a `dock` array with tools (todoset, message_board, etc.) and their IDs
- Use the dock tool IDs to find `todoset_id`, `message_board_id`, etc. for downstream operations

## Common Patterns

### ID Resolution
Basecamp uses a hierarchical ID structure. Always resolve top-down:
- **Project (bucket_id)**: `BASECAMP_GET_PROJECTS` -- find by name, capture the `id`
- **To-do set (todoset_id)**: Found in project dock or via `BASECAMP_GET_BUCKETS_TODOSETS`
- **Message board (message_board_id)**: Found in project dock or via `BASECAMP_GET_MESSAGE_BOARD`
- **To-do list (todolist_id)**: `BASECAMP_GET_BUCKETS_TODOSETS_TODOLISTS`
- **People (person_id)**: `BASECAMP_GET_PEOPLE` or `BASECAMP_LIST_PROJECT_PEOPLE`
- Note: `bucket_id` and `project_id` refer to the same entity in different contexts

### Pagination
Basecamp uses page-based pagination on list endpoints:
- Response headers or body may indicate more pages available
- `GET_PROJECTS`, `GET_BUCKETS_TODOSETS_TODOLISTS`, and list endpoints return paginated results
- Continue fetching until no more results are returned

### Content Formatting
- All rich text fields use HTML, not Markdown
- Wrap content in `<div>` tags; use `<strong>`, `<em>`, `<ul>`, `<ol>`, `<li>`, `<a>` etc.
- Example: `<div><strong>Important:</strong> Complete by Friday</div>`

## Known Pitfalls

### ID Formats
- All Basecamp IDs are integers, not strings or UUIDs
- `bucket_id` = `project_id` (same entity, different parameter names across tools)
- To-do set IDs, to-do list IDs, and message board IDs are found in the project's `dock` array
- Person IDs are integers; resolve names via `GET_PEOPLE` before operations

### Status Field
- `status="draft"` for messages can cause HTTP 400; always use `status="active"`
- Project/to-do list status filters: `"archived"`, `"trashed"`, or omit for active

### Content Format
- HTML only, never Markdown
- Updates replace the entire body, not a partial diff
- Invalid HTML tags may be silently stripped

### Rate Limits
- Basecamp API has rate limits; space out rapid sequential requests
- Large projects with many to-dos should be paginated carefully

### URL Handling
- Prefer `app_url` from API responses for user-facing links
- Do not reconstruct Basecamp URLs manually from IDs

## Quick Reference

| Task | Tool Slug | Key Params |
|------|-----------|------------|
| List projects | `BASECAMP_GET_PROJECTS` | `status` |
| Get project | `BASECAMP_GET_PROJECT` | `project_id` |
| Get project detail | `BASECAMP_GET_PROJECTS_BY_PROJECT_ID` | `project_id` |
| Get to-do set | `BASECAMP_GET_BUCKETS_TODOSETS` | `bucket_id`, `todoset_id` |
| List to-do lists | `BASECAMP_GET_BUCKETS_TODOSETS_TODOLISTS` | `bucket_id`, `todoset_id` |
| Get to-do list | `BASECAMP_GET_BUCKETS_TODOLISTS` | `bucket_id`, `todolist_id` |
| Create to-do list | `BASECAMP_POST_BUCKETS_TODOSETS_TODOLISTS` | `bucket_id`, `todoset_id`, `name` |
| Create to-do | `BASECAMP_POST_BUCKETS_TODOLISTS_TODOS` | `bucket_id`, `todolist_id`, `content` |
| Create to-do (alt) | `BASECAMP_CREATE_TODO` | `bucket_id`, `todolist_id`, `content` |
| List to-dos | `BASECAMP_GET_BUCKETS_TODOLISTS_TODOS` | `bucket_id`, `todolist_id` |
| List to-do groups | `BASECAMP_GET_TODOLIST_GROUPS` | `bucket_id`, `todolist_id` |
| Create to-do group | `BASECAMP_POST_BUCKETS_TODOLISTS_GROUPS` | `bucket_id`, `todolist_id`, `name`, `color` |
| Create to-do group (alt) | `BASECAMP_CREATE_TODOLIST_GROUP` | `bucket_id`, `todolist_id`, `name` |
| Get message board | `BASECAMP_GET_MESSAGE_BOARD` | `bucket_id`, `message_board_id` |
| Create message | `BASECAMP_CREATE_MESSAGE` | `bucket_id`, `message_board_id`, `subject`, `status` |
| Create message (alt) | `BASECAMP_POST_BUCKETS_MESSAGE_BOARDS_MESSAGES` | `bucket_id`, `message_board_id`, `subject` |
| Get message | `BASECAMP_GET_MESSAGE` | `bucket_id`, `message_id` |
| Update message | `BASECAMP_PUT_BUCKETS_MESSAGES` | `bucket_id`, `message_id` |
| List all people | `BASECAMP_GET_PEOPLE` | (none) |
| List project people | `BASECAMP_LIST_PROJECT_PEOPLE` | `project_id` |
| Manage access | `BASECAMP_PUT_PROJECTS_PEOPLE_USERS` | `project_id`, `grant`, `revoke`, `create` |

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: baseline-ui
description: Quickly deslop UI code by fixing spacing, hierarchy, typography, and small layout issues. Use when the interface needs a fast cleanup or polish pass.
risk: critical
source: https://github.com/ibelick/ui-skills/tree/main/skills/baseline-ui
source_repo: ibelick/ui-skills
source_type: community
date_added: 2026-07-01
license: MIT
license_source: https://github.com/ibelick/ui-skills/blob/main/LICENSE
---

# Baseline UI
## When to Use

Use this skill when you need quickly deslop UI code by fixing spacing, hierarchy, typography, and small layout issues. Use when the interface needs a fast cleanup or polish pass.

Enforces an opinionated UI baseline to prevent AI-generated interface slop.

## How to use

- `/baseline-ui`
  Apply these constraints to any UI work in this conversation.

- `/baseline-ui <file>`
  Review the file against all constraints below and output:
  - violations (quote the exact line/snippet)
  - why it matters (1 short sentence)
  - a concrete fix (code-level suggestion)

## Stack

- MUST use Tailwind CSS defaults unless custom values already exist or are explicitly requested
- MUST use `motion/react` (formerly `framer-motion`) when JavaScript animation is required
- SHOULD use `tw-animate-css` for entrance and micro-animations in Tailwind CSS
- MUST use `cn` utility (`clsx` + `tailwind-merge`) for class logic

## Components

- MUST use accessible component primitives for anything with keyboard or focus behavior (`Base UI`, `React Aria`, `Radix`)
- MUST use the project’s existing component primitives first
- NEVER mix primitive systems within the same interaction surface
- SHOULD prefer [`Base UI`](https://base-ui.com/react/components) for new primitives if compatible with the stack
- MUST add an `aria-label` to icon-only buttons
- NEVER rebuild keyboard or focus behavior by hand unless explicitly requested

## Interaction

- MUST use an `AlertDialog` for destructive or irreversible actions
- SHOULD use structural skeletons for loading states
- NEVER use `h-screen`, use `h-dvh`
- MUST respect `safe-area-inset` for fixed elements
- MUST show errors next to where the action happens
- NEVER block paste in `input` or `textarea` elements

## Animation

- NEVER add animation unless it is explicitly requested
- MUST animate only compositor props (`transform`, `opacity`)
- NEVER animate layout properties (`width`, `height`, `top`, `left`, `margin`, `padding`)
- SHOULD avoid animating paint properties (`background`, `color`) except for small, local UI (text, icons)
- SHOULD use `ease-out` on entrance
- NEVER exceed `200ms` for interaction feedback
- MUST pause looping animations when off-screen
- SHOULD respect `prefers-reduced-motion`
- NEVER introduce custom easing curves unless explicitly requested
- SHOULD avoid animating large images or full-screen surfaces

## Typography

- MUST use `text-balance` for headings and `text-pretty` for body/paragraphs
- MUST use `tabular-nums` for data
- SHOULD use `truncate` or `line-clamp` for dense UI
- NEVER modify `letter-spacing` (`tracking-*`) unless explicitly requested

## Layout

- MUST use a fixed `z-index` scale (no arbitrary `z-*`)
- SHOULD use `size-*` for square elements instead of `w-*` + `h-*`

## Performance

- NEVER animate large `blur()` or `backdrop-filter` surfaces
- NEVER apply `will-change` outside an active animation
- NEVER use `useEffect` for anything that can be expressed as render logic

## Design

- NEVER use gradients unless explicitly requested
- NEVER use purple or multicolor gradients
- NEVER use glow effects as primary affordances
- SHOULD use Tailwind CSS default shadow scale unless explicitly requested
- MUST give empty states one clear next action
- SHOULD limit accent color usage to one per view
- SHOULD use existing theme or Tailwind CSS color tokens before introducing new ones

## Limitations

- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.


---
name: bash
description: "Language-specific super-code guidelines for bash."
risk: safe
source: community
date_added: "2026-06-16"
---
# Bash / Shell: Idiomatic Efficiency Reference

## When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for bash.

## Table of Contents
1. [Quoting & Word Splitting](#quoting)
2. [Conditionals & Tests](#conditionals)
3. [Loops & Iteration](#loops)
4. [Pipes & Process Substitution](#pipes)
5. [Functions & Return Values](#functions)
6. [Error Handling](#errors)
7. [Anti-patterns specific to Bash](#antipatterns)

---

## 1. Quoting & Word Splitting {#quoting}

```bash
# ❌ Unquoted variable (word splitting + globbing)
for f in $files; do rm $f; done

# ✅
for f in "${files[@]}"; do rm -- "$f"; done
```

```bash
# ❌ Unquoted command substitution
path=$(find . -name config)
cat $path  # breaks on spaces

# ✅
path="$(find . -name config)"
cat "$path"
```

```bash
# ❌ Using backticks for command substitution
result=`echo hello`

# ✅ — $() nests cleanly
result=$(echo hello)
```

```bash
# ❌ String comparison without quotes
if [ $var = "hello" ]; then  # breaks if var is empty or has spaces

# ✅
if [[ "$var" = "hello" ]]; then
```

**Rule: double-quote every `$variable` and `$(command)` unless you specifically need splitting.**

---

## 2. Conditionals & Tests {#conditionals}

```bash
# ❌ Single bracket test (POSIX but fragile)
if [ -f "$file" -a -r "$file" ]; then

# ✅ — [[ is safer, supports &&/||, no word splitting inside
if [[ -f "$file" && -r "$file" ]]; then
```

```bash
# ❌ Testing command exit status with if [ $? -eq 0 ]
grep -q pattern file
if [ $? -eq 0 ]; then echo "found"; fi

# ✅ — test command directly
if grep -q pattern file; then echo "found"; fi
```

```bash
# ❌ String equality with == outside [[
if [ "$a" == "$b" ]; then  # == not POSIX in [ ]

# ✅
if [[ "$a" == "$b" ]]; then  # Bash
# or POSIX:
if [ "$a" = "$b" ]; then
```

```bash
# ❌ Arithmetic with [ ] and string comparison
if [ "$count" -gt 10 ]; then

# ✅ — (( )) for arithmetic
if (( count > 10 )); then
```

---

## 3. Loops & Iteration {#loops}

```bash
# ❌ Parsing ls output
for f in $(ls *.txt); do process "$f"; done

# ✅ — glob directly
for f in *.txt; do
    [[ -e "$f" ]] || continue  # handle no-match
    process "$f"
done
```

```bash
# ❌ Reading file line-by-line with for
for line in $(cat file.txt); do  # splits on words, not lines

# ✅
while IFS= read -r line; do
    process "$line"
done < file.txt
```

```bash
# ❌ Seq for counting
for i in $(seq 1 10); do

# ✅ — brace expansion (Bash)
for i in {1..10}; do
# or C-style:
for (( i = 1; i <= 10; i++ )); do
```

```bash
# ❌ Processing command output line-by-line with pipe (subshell trap)
count=0
cat file.txt | while read -r line; do
    (( count++ ))  # count resets after loop — subshell
done
echo "$count"  # always 0

# ✅ — redirect, not pipe
count=0
while IFS= read -r line; do
    (( count++ ))
done < file.txt
echo "$count"
```

---

## 4. Pipes & Process Substitution {#pipes}

```bash
# ❌ Chained grep | grep for AND
grep "error" log.txt | grep "timeout"

# ✅ — single grep with pattern
grep -E "error.*timeout|timeout.*error" log.txt
# or awk for complex logic:
awk '/error/ && /timeout/' log.txt
```

```bash
# ❌ cat + pipe (UUOC — Useless Use of Cat)
cat file.txt | grep pattern

# ✅
grep pattern file.txt
```

```bash
# ❌ Temp file for diff between commands
cmd1 > /tmp/a.txt
cmd2 > /tmp/b.txt
diff /tmp/a.txt /tmp/b.txt
rm /tmp/a.txt /tmp/b.txt

# ✅ — process substitution
diff <(cmd1) <(cmd2)
```

```bash
# ❌ Ignoring pipe failures (only last command's exit code)
false | true
echo $?  # 0 — false's failure hidden

# ✅
set -o pipefail
false | true
echo $?  # 1
```

---

## 5. Functions & Return Values {#functions}

```bash
# ❌ Using return for string values
get_name() {
    return "Alice"  # return is for exit codes (0-255)
}

# ✅ — echo + capture
get_name() {
    echo "Alice"
}
name=$(get_name)
```

```bash
# ❌ Global variables modified inside functions
result=""
compute() { result="done"; }

# ✅ — use local, return via stdout
compute() {
    local tmp
    tmp=$(do_work)
    echo "$tmp"
}
result=$(compute)
```

```bash
# ❌ Function keyword (not POSIX)
function my_func {

# ✅
my_func() {
```

---

## 6. Error Handling {#errors}

```bash
# ❌ No error handling — script continues after failure
cd /some/dir
rm -rf *  # if cd fails, deletes from wrong directory

# ✅
set -euo pipefail

cd /some/dir || { echo "cd failed" >&2; exit 1; }
rm -rf ./*
```

```bash
# ❌ No cleanup on exit
tmpfile=$(mktemp)
# ... script might exit early, leaving tmpfile

# ✅ — trap for cleanup
tmpfile=$(mktemp)
trap 'rm -f "$tmpfile"' EXIT
```

```bash
# ❌ Silencing errors blindly
command 2>/dev/null

# ✅ — redirect only when you know what you're suppressing
command 2>/dev/null || true  # explicit: we expect and accept failure
```

**Start every script with `set -euo pipefail`. Remove selectively where needed.**

---

## 7. Anti-patterns specific to Bash {#antipatterns}

| Anti-pattern | Preferred |
|---|---|
| Parsing `ls` output | glob: `for f in *.txt` |
| `cat file \| grep` | `grep pattern file` |
| Unquoted `$var` | `"$var"` always |
| `[ ]` for complex tests | `[[ ]]` |
| Backtick substitution | `$(command)` |
| `$?` check after command | `if command; then` |
| `echo` for debug | `printf '%s\n'` (portable) |
| No `set -euo pipefail` | always set at script top |
| Temp files without cleanup | `trap 'rm -f "$tmp"' EXIT` |
| `eval` with user input | avoid; use arrays for dynamic commands |
| `#!/bin/sh` with Bash features | `#!/usr/bin/env bash` |
| String math `expr 1 + 1` | `$(( 1 + 1 ))` |
| `test -z` for number comparison | `(( ))` for arithmetic |

## Limitations
- These are language-specific guidelines and do not cover overall architectural decisions.
- Over-compression might reduce readability; apply judgement.


---
name: bash-defensive-patterns
description: "Master defensive Bash programming techniques for production-grade scripts. Use when writing robust shell scripts, CI/CD pipelines, or system utilities requiring fault tolerance and safety."
risk: safe
source: community
date_added: "2026-02-27"
---

# Bash Defensive Patterns

Comprehensive guidance for writing production-ready Bash scripts using defensive programming techniques, error handling, and safety best practices to prevent common pitfalls and ensure reliability.

## Use this skill when

- Writing production automation scripts
- Building CI/CD pipeline scripts
- Creating system administration utilities
- Developing error-resilient deployment automation
- Writing scripts that must handle edge cases safely
- Building maintainable shell script libraries
- Implementing comprehensive logging and monitoring
- Creating scripts that must work across different platforms

## Do not use this skill when

- You need a single ad-hoc shell command, not a script
- The target environment requires strict POSIX sh only
- The task is unrelated to shell scripting or automation

## Instructions

1. Confirm the target shell, OS, and execution environment.
2. Enable strict mode and safe defaults from the start.
3. Validate inputs, quote variables, and handle files safely.
4. Add logging, error traps, and basic tests.

## Safety

- Avoid destructive commands without confirmation or dry-run flags.
- Do not run scripts as root unless strictly required.

Refer to `resources/implementation-playbook.md` for detailed patterns, checklists, and templates.

## Resources

- `resources/implementation-playbook.md` for detailed patterns, checklists, and templates.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: bash-linux
description: "Bash/Linux terminal patterns. Critical commands, piping, error handling, scripting. Use when working on macOS or Linux systems."
risk: critical
source: community
date_added: "2026-02-27"
---

# Bash Linux Patterns

> Essential patterns for Bash on Linux/macOS.

---

## 1. Operator Syntax

### Chaining Commands

| Operator | Meaning | Example |
|----------|---------|---------|
| `;` | Run sequentially | `cmd1; cmd2` |
| `&&` | Run if previous succeeded | `npm install && npm run dev` |
| `\|\|` | Run if previous failed | `npm test \|\| echo "Tests failed"` |
| `\|` | Pipe output | `ls \| grep ".js"` |

---

## 2. File Operations

### Essential Commands

| Task | Command |
|------|---------|
| List all | `ls -la` |
| Find files | `find . -name "*.js" -type f` |
| File content | `cat file.txt` |
| First N lines | `head -n 20 file.txt` |
| Last N lines | `tail -n 20 file.txt` |
| Follow log | `tail -f log.txt` |
| Search in files | `grep -r "pattern" --include="*.js"` |
| File size | `du -sh *` |
| Disk usage | `df -h` |

---

## 3. Process Management

| Task | Command |
|------|---------|
| List processes | `ps aux` |
| Find by name | `ps aux \| grep node` |
| Kill by PID | `kill -9 <PID>` |
| Find port user | `lsof -i :3000` |
| Kill port | `kill -9 $(lsof -t -i :3000)` |
| Background | `npm run dev &` |
| Jobs | `jobs -l` |
| Bring to front | `fg %1` |

---

## 4. Text Processing

### Core Tools

| Tool | Purpose | Example |
|------|---------|---------|
| `grep` | Search | `grep -rn "TODO" src/` |
| `sed` | Replace | `sed -i 's/old/new/g' file.txt` |
| `awk` | Extract columns | `awk '{print $1}' file.txt` |
| `cut` | Cut fields | `cut -d',' -f1 data.csv` |
| `sort` | Sort lines | `sort -u file.txt` |
| `uniq` | Unique lines | `sort file.txt \| uniq -c` |
| `wc` | Count | `wc -l file.txt` |

---

## 5. Environment Variables

| Task | Command |
|------|---------|
| View all | `env` or `printenv` |
| View one | `echo $PATH` |
| Set temporary | `export VAR="value"` |
| Set in script | `VAR="value" command` |
| Add to PATH | `export PATH="$PATH:/new/path"` |

---

## 6. Network

| Task | Command |
|------|---------|
| Download | `curl -O https://example.com/file` |
| API request | `curl -X GET https://api.example.com` |
| POST JSON | `curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' URL` |
| Check port | `nc -zv localhost 3000` |
| Network info | `ifconfig` or `ip addr` |

---

## 7. Script Template

```bash
#!/bin/bash
set -euo pipefail  # Exit on error, undefined var, pipe fail

# Colors (optional)
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Functions
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# Main
main() {
    log_info "Starting..."
    # Your logic here
    log_info "Done!"
}

main "$@"
```

---

## 8. Common Patterns

### Check if command exists

```bash
if command -v node &> /dev/null; then
    echo "Node is installed"
fi
```

### Default variable value

```bash
NAME=${1:-"default_value"}
```

### Read file line by line

```bash
while IFS= read -r line; do
    echo "$line"
done < file.txt
```

### Loop over files

```bash
for file in *.js; do
    echo "Processing $file"
done
```

---

## 9. Differences from PowerShell

| Task | PowerShell | Bash |
|------|------------|------|
| List files | `Get-ChildItem` | `ls -la` |
| Find files | `Get-ChildItem -Recurse` | `find . -type f` |
| Environment | `$env:VAR` | `$VAR` |
| String concat | `"$a$b"` | `"$a$b"` (same) |
| Null check | `if ($x)` | `if [ -n "$x" ]` |
| Pipeline | Object-based | Text-based |

---

## 10. Error Handling

### Set options

```bash
set -e          # Exit on error
set -u          # Exit on undefined variable
set -o pipefail # Exit on pipe failure
set -x          # Debug: print commands
```

### Trap for cleanup

```bash
cleanup() {
    echo "Cleaning up..."
    rm -f /tmp/tempfile
}
trap cleanup EXIT
```

---

> **Remember:** Bash is text-based. Use `&&` for success chains, `set -e` for safety, and quote your variables!

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: bash-pro
description: 'Master of defensive Bash scripting for production automation, CI/CD

  pipelines, and system utilities. Expert in safe, portable, and testable shell

  scripts.

  '
risk: critical
source: community
date_added: '2026-02-27'
---
## Use this skill when

- Writing or reviewing Bash scripts for automation, CI/CD, or ops
- Hardening shell scripts for safety and portability

## Do not use this skill when

- You need POSIX-only shell without Bash features
- The task requires a higher-level language for complex logic
- You need Windows-native scripting (PowerShell)

## Instructions

1. Define script inputs, outputs, and failure modes.
2. Apply strict mode and safe argument parsing.
3. Implement core logic with defensive patterns.
4. Add tests and linting with Bats and ShellCheck.

## Safety

- Treat input as untrusted; avoid eval and unsafe globbing.
- Prefer dry-run modes before destructive actions.

## Focus Areas

- Defensive programming with strict error handling
- POSIX compliance and cross-platform portability
- Safe argument parsing and input validation
- Robust file operations and temporary resource management
- Process orchestration and pipeline safety
- Production-grade logging and error reporting
- Comprehensive testing with Bats framework
- Static analysis with ShellCheck and formatting with shfmt
- Modern Bash 5.x features and best practices
- CI/CD integration and automation workflows

## Approach

- Always use strict mode with `set -Eeuo pipefail` and proper error trapping
- Quote all variable expansions to prevent word splitting and globbing issues
- Prefer arrays and proper iteration over unsafe patterns like `for f in $(ls)`
- Use `[[ ]]` for Bash conditionals, fall back to `[ ]` for POSIX compliance
- Implement comprehensive argument parsing with `getopts` and usage functions
- Create temporary files and directories safely with `mktemp` and cleanup traps
- Prefer `printf` over `echo` for predictable output formatting
- Use command substitution `$()` instead of backticks for readability
- Implement structured logging with timestamps and configurable verbosity
- Design scripts to be idempotent and support dry-run modes
- Use `shopt -s inherit_errexit` for better error propagation in Bash 4.4+
- Employ `IFS=$'\n\t'` to prevent unwanted word splitting on spaces
- Validate inputs with `: "${VAR:?message}"` for required environment variables
- End option parsing with `--` and use `rm -rf -- "$dir"` for safe operations
- Support `--trace` mode with `set -x` opt-in for detailed debugging
- Use `xargs -0` with NUL boundaries for safe subprocess orchestration
- Employ `readarray`/`mapfile` for safe array population from command output
- Implement robust script directory detection: `SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"`
- Use NUL-safe patterns: `find -print0 | while IFS= read -r -d '' file; do ...; done`

## Compatibility & Portability

- Use `#!/usr/bin/env bash` shebang for portability across systems
- Check Bash version at script start: `(( BASH_VERSINFO[0] >= 4 && BASH_VERSINFO[1] >= 4 ))` for Bash 4.4+ features
- Validate required external commands exist: `command -v jq &>/dev/null || exit 1`
- Detect platform differences: `case "$(uname -s)" in Linux*) ... ;; Darwin*) ... ;; esac`
- Handle GNU vs BSD tool differences (e.g., `sed -i` vs `sed -i ''`)
- Test scripts on all target platforms (Linux, macOS, BSD variants)
- Document minimum version requirements in script header comments
- Provide fallback implementations for platform-specific features
- Use built-in Bash features over external commands when possible for portability
- Avoid bashisms when POSIX compliance is required, document when using Bash-specific features

## Readability & Maintainability

- Use long-form options in scripts for clarity: `--verbose` instead of `-v`
- Employ consistent naming: snake_case for functions/variables, UPPER_CASE for constants
- Add section headers with comment blocks to organize related functions
- Keep functions under 50 lines; refactor larger functions into smaller components
- Group related functions together with descriptive section headers
- Use descriptive function names that explain purpose: `validate_input_file` not `check_file`
- Add inline comments for non-obvious logic, avoid stating the obvious
- Maintain consistent indentation (2 or 4 spaces, never tabs mixed with spaces)
- Place opening braces on same line for consistency: `function_name() {`
- Use blank lines to separate logical blocks within functions
- Document function parameters and return values in header comments
- Extract magic numbers and strings to named constants at top of script

## Safety & Security Patterns

- Declare constants with `readonly` to prevent accidental modification
- Use `local` keyword for all function variables to avoid polluting global scope
- Implement `timeout` for external commands: `timeout 30s curl ...` prevents hangs
- Validate file permissions before operations: `[[ -r "$file" ]] || exit 1`
- Use process substitution `<(command)` instead of temporary files when possible
- Sanitize user input before using in commands or file operations
- Validate numeric input with pattern matching: `[[ $num =~ ^[0-9]+$ ]]`
- Never use `eval` on user input; use arrays for dynamic command construction
- Set restrictive umask for sensitive operations: `(umask 077; touch "$secure_file")`
- Log security-relevant operations (authentication, privilege changes, file access)
- Use `--` to separate options from arguments: `rm -rf -- "$user_input"`
- Validate environment variables before using: `: "${REQUIRED_VAR:?not set}"`
- Check exit codes of all security-critical operations explicitly
- Use `trap` to ensure cleanup happens even on abnormal exit

## Performance Optimization

- Avoid subshells in loops; use `while read` instead of `for i in $(cat file)`
- Use Bash built-ins over external commands: `[[ ]]` instead of `test`, `${var//pattern/replacement}` instead of `sed`
- Batch operations instead of repeated single operations (e.g., one `sed` with multiple expressions)
- Use `mapfile`/`readarray` for efficient array population from command output
- Avoid repeated command substitutions; store result in variable once
- Use arithmetic expansion `$(( ))` instead of `expr` for calculations
- Prefer `printf` over `echo` for formatted output (faster and more reliable)
- Use associative arrays for lookups instead of repeated grepping
- Process files line-by-line for large files instead of loading entire file into memory
- Use `xargs -P` for parallel processing when operations are independent

## Documentation Standards

- Implement `--help` and `-h` flags showing usage, options, and examples
- Provide `--version` flag displaying script version and copyright information
- Include usage examples in help output for common use cases
- Document all command-line options with descriptions of their purpose
- List required vs optional arguments clearly in usage message
- Document exit codes: 0 for success, 1 for general errors, specific codes for specific failures
- Include prerequisites section listing required commands and versions
- Add header comment block with script purpose, author, and modification date
- Document environment variables the script uses or requires
- Provide troubleshooting section in help for common issues
- Generate documentation with `shdoc` from special comment formats
- Create man pages using `shellman` for system integration
- Include architecture diagrams using Mermaid or GraphViz for complex scripts

## Modern Bash Features (5.x)

- **Bash 5.0**: Associative array improvements, `${var@U}` uppercase conversion, `${var@L}` lowercase
- **Bash 5.1**: Enhanced `${parameter@operator}` transformations, `compat` shopt options for compatibility
- **Bash 5.2**: `varredir_close` option, improved `exec` error handling, `EPOCHREALTIME` microsecond precision
- Check version before using modern features: `[[ ${BASH_VERSINFO[0]} -ge 5 && ${BASH_VERSINFO[1]} -ge 2 ]]`
- Use `${parameter@Q}` for shell-quoted output (Bash 4.4+)
- Use `${parameter@E}` for escape sequence expansion (Bash 4.4+)
- Use `${parameter@P}` for prompt expansion (Bash 4.4+)
- Use `${parameter@A}` for assignment format (Bash 4.4+)
- Employ `wait -n` to wait for any background job (Bash 4.3+)
- Use `mapfile -d delim` for custom delimiters (Bash 4.4+)

## CI/CD Integration

- **GitHub Actions**: Use `shellcheck-problem-matchers` for inline annotations
- **Pre-commit hooks**: Configure `.pre-commit-config.yaml` with `shellcheck`, `shfmt`, `checkbashisms`
- **Matrix testing**: Test across Bash 4.4, 5.0, 5.1, 5.2 on Linux and macOS
- **Container testing**: Use official bash:5.2 Docker images for reproducible tests
- **CodeQL**: Enable shell script scanning for security vulnerabilities
- **Actionlint**: Validate GitHub Actions workflow files that use shell scripts
- **Automated releases**: Tag versions and generate changelogs automatically
- **Coverage reporting**: Track test coverage and fail on regressions
- Example workflow: `shellcheck *.sh && shfmt -d *.sh && bats test/`

## Security Scanning & Hardening

- **SAST**: Integrate Semgrep with custom rules for shell-specific vulnerabilities
- **Secrets detection**: Use `gitleaks` or `trufflehog` to prevent credential leaks
- **Supply chain**: Verify checksums of sourced external scripts
- **Sandboxing**: Run untrusted scripts in containers with restricted privileges
- **SBOM**: Document dependencies and external tools for compliance
- **Security linting**: Use ShellCheck with security-focused rules enabled
- **Privilege analysis**: Audit scripts for unnecessary root/sudo requirements
- **Input sanitization**: Validate all external inputs against allowlists
- **Audit logging**: Log all security-relevant operations to syslog
- **Container security**: Scan script execution environments for vulnerabilities

## Observability & Logging

- **Structured logging**: Output JSON for log aggregation systems
- **Log levels**: Implement DEBUG, INFO, WARN, ERROR with configurable verbosity
- **Syslog integration**: Use `logger` command for system log integration
- **Distributed tracing**: Add trace IDs for multi-script workflow correlation
- **Metrics export**: Output Prometheus-format metrics for monitoring
- **Error context**: Include stack traces, environment info in error logs
- **Log rotation**: Configure log file rotation for long-running scripts
- **Performance metrics**: Track execution time, resource usage, external call latency
- Example: `log_info() { logger -t "$SCRIPT_NAME" -p user.info "$*"; echo "[INFO] $*" >&2; }`

## Quality Checklist

- Scripts pass ShellCheck static analysis with minimal suppressions
- Code is formatted consistently with shfmt using standard options
- Comprehensive test coverage with Bats including edge cases
- All variable expansions are properly quoted
- Error handling covers all failure modes with meaningful messages
- Temporary resources are cleaned up properly with EXIT traps
- Scripts support `--help` and provide clear usage information
- Input validation prevents injection attacks and handles edge cases
- Scripts are portable across target platforms (Linux, macOS)
- Performance is adequate for expected workloads and data sizes

## Output

- Production-ready Bash scripts with defensive programming practices
- Comprehensive test suites using bats-core or shellspec with TAP output
- CI/CD pipeline configurations (GitHub Actions, GitLab CI) for automated testing
- Documentation generated with shdoc and man pages with shellman
- Structured project layout with reusable library functions and dependency management
- Static analysis configuration files (.shellcheckrc, .shfmt.toml, .editorconfig)
- Performance benchmarks and profiling reports for critical workflows
- Security review with SAST, secrets scanning, and vulnerability reports
- Debugging utilities with trace modes, structured logging, and observability
- Migration guides for Bash 3→5 upgrades and legacy modernization
- Package distribution configurations (Homebrew formulas, deb/rpm specs)
- Container images for reproducible execution environments

## Essential Tools

### Static Analysis & Formatting
- **ShellCheck**: Static analyzer with `enable=all` and `external-sources=true` configuration
- **shfmt**: Shell script formatter with standard config (`-i 2 -ci -bn -sr -kp`)
- **checkbashisms**: Detect bash-specific constructs for portability analysis
- **Semgrep**: SAST with custom rules for shell-specific security issues
- **CodeQL**: GitHub's security scanning for shell scripts

### Testing Frameworks
- **bats-core**: Maintained fork of Bats with modern features and active development
- **shellspec**: BDD-style testing framework with rich assertions and mocking
- **shunit2**: xUnit-style testing framework for shell scripts
- **bashing**: Testing framework with mocking support and test isolation

### Modern Development Tools
- **bashly**: CLI framework generator for building command-line applications
- **basher**: Bash package manager for dependency management
- **bpkg**: Alternative bash package manager with npm-like interface
- **shdoc**: Generate markdown documentation from shell script comments
- **shellman**: Generate man pages from shell scripts

### CI/CD & Automation
- **pre-commit**: Multi-language pre-commit hook framework
- **actionlint**: GitHub Actions workflow linter
- **gitleaks**: Secrets scanning to prevent credential leaks
- **Makefile**: Automation for lint, format, test, and release workflows

## Common Pitfalls to Avoid

- `for f in $(ls ...)` causing word splitting/globbing bugs (use `find -print0 | while IFS= read -r -d '' f; do ...; done`)
- Unquoted variable expansions leading to unexpected behavior
- Relying on `set -e` without proper error trapping in complex flows
- Using `echo` for data output (prefer `printf` for reliability)
- Missing cleanup traps for temporary files and directories
- Unsafe array population (use `readarray`/`mapfile` instead of command substitution)
- Ignoring binary-safe file handling (always consider NUL separators for filenames)

## Dependency Management

- **Package managers**: Use `basher` or `bpkg` for installing shell script dependencies
- **Vendoring**: Copy dependencies into project for reproducible builds
- **Lock files**: Document exact versions of dependencies used
- **Checksum verification**: Verify integrity of sourced external scripts
- **Version pinning**: Lock dependencies to specific versions to prevent breaking changes
- **Dependency isolation**: Use separate directories for different dependency sets
- **Update automation**: Automate dependency updates with Dependabot or Renovate
- **Security scanning**: Scan dependencies for known vulnerabilities
- Example: `basher install username/repo@version` or `bpkg install username/repo -g`

## Advanced Techniques

- **Error Context**: Use `trap 'echo "Error at line $LINENO: exit $?" >&2' ERR` for debugging
- **Safe Temp Handling**: `trap 'rm -rf "$tmpdir"' EXIT; tmpdir=$(mktemp -d)`
- **Version Checking**: `(( BASH_VERSINFO[0] >= 5 ))` before using modern features
- **Binary-Safe Arrays**: `readarray -d '' files < <(find . -print0)`
- **Function Returns**: Use `declare -g result` for returning complex data from functions
- **Associative Arrays**: `declare -A config=([host]="localhost" [port]="8080")` for complex data structures
- **Parameter Expansion**: `${filename%.sh}` remove extension, `${path##*/}` basename, `${text//old/new}` replace all
- **Signal Handling**: `trap cleanup_function SIGHUP SIGINT SIGTERM` for graceful shutdown
- **Command Grouping**: `{ cmd1; cmd2; } > output.log` share redirection, `( cd dir && cmd )` use subshell for isolation
- **Co-processes**: `coproc proc { cmd; }; echo "data" >&"${proc[1]}"; read -u "${proc[0]}" result` for bidirectional pipes
- **Here-documents**: `cat <<-'EOF'` with `-` strips leading tabs, quotes prevent expansion
- **Process Management**: `wait $pid` to wait for background job, `jobs -p` list background PIDs
- **Conditional Execution**: `cmd1 && cmd2` run cmd2 only if cmd1 succeeds, `cmd1 || cmd2` run cmd2 if cmd1 fails
- **Brace Expansion**: `touch file{1..10}.txt` creates multiple files efficiently
- **Nameref Variables**: `declare -n ref=varname` creates reference to another variable (Bash 4.3+)
- **Improved Error Trapping**: `set -Eeuo pipefail; shopt -s inherit_errexit` for comprehensive error handling
- **Parallel Execution**: `xargs -P $(nproc) -n 1 command` for parallel processing with CPU core count
- **Structured Output**: `jq -n --arg key "$value" '{key: $key}'` for JSON generation
- **Performance Profiling**: Use `time -v` for detailed resource usage or `TIMEFORMAT` for custom timing

## References & Further Reading

### Style Guides & Best Practices
- [Google Shell Style Guide](https://google.github.io/styleguide/shellguide.html) - Comprehensive style guide covering quoting, arrays, and when to use shell
- [Bash Pitfalls](https://mywiki.wooledge.org/BashPitfalls) - Catalog of common Bash mistakes and how to avoid them
- [Bash Hackers Wiki](https://wiki.bash-hackers.org/) - Comprehensive Bash documentation and advanced techniques
- [Defensive BASH Programming](https://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) - Modern defensive programming patterns

### Tools & Frameworks
- [ShellCheck](https://github.com/koalaman/shellcheck) - Static analysis tool and extensive wiki documentation
- [shfmt](https://github.com/mvdan/sh) - Shell script formatter with detailed flag documentation
- [bats-core](https://github.com/bats-core/bats-core) - Maintained Bash testing framework
- [shellspec](https://github.com/shellspec/shellspec) - BDD-style testing framework for shell scripts
- [bashly](https://bashly.dannyb.co/) - Modern Bash CLI framework generator
- [shdoc](https://github.com/reconquest/shdoc) - Documentation generator for shell scripts

### Security & Advanced Topics
- [Bash Security Best Practices](https://github.com/carlospolop/PEASS-ng) - Security-focused shell script patterns
- [Awesome Bash](https://github.com/awesome-lists/awesome-bash) - Curated list of Bash resources and tools
- [Pure Bash Bible](https://github.com/dylanaraps/pure-bash-bible) - Collection of pure bash alternatives to external commands

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: bash-scripting
description: "Bash scripting workflow for creating production-ready shell scripts with defensive patterns, error handling, and testing."
category: granular-workflow-bundle
risk: safe
source: personal
date_added: "2026-02-27"
---

# Bash Scripting Workflow

## Overview

Specialized workflow for creating robust, production-ready bash scripts with defensive programming patterns, comprehensive error handling, and automated testing.

## When to Use This Workflow

Use this workflow when:
- Creating automation scripts
- Writing system administration tools
- Building deployment scripts
- Developing backup solutions
- Creating CI/CD scripts

## Workflow Phases

### Phase 1: Script Design

#### Skills to Invoke
- `bash-pro` - Professional scripting
- `bash-defensive-patterns` - Defensive patterns

#### Actions
1. Define script purpose
2. Identify inputs/outputs
3. Plan error handling
4. Design logging strategy
5. Document requirements

#### Copy-Paste Prompts
```
Use @bash-pro to design production-ready bash script
```

### Phase 2: Script Structure

#### Skills to Invoke
- `bash-pro` - Script structure
- `bash-defensive-patterns` - Safety patterns

#### Actions
1. Add shebang and strict mode
2. Create usage function
3. Implement argument parsing
4. Set up logging
5. Add cleanup handlers

#### Copy-Paste Prompts
```
Use @bash-defensive-patterns to implement strict mode and error handling
```

### Phase 3: Core Implementation

#### Skills to Invoke
- `bash-linux` - Linux commands
- `linux-shell-scripting` - Shell scripting

#### Actions
1. Implement main functions
2. Add input validation
3. Create helper functions
4. Handle edge cases
5. Add progress indicators

#### Copy-Paste Prompts
```
Use @bash-linux to implement system commands
```

### Phase 4: Error Handling

#### Skills to Invoke
- `bash-defensive-patterns` - Error handling
- `error-handling-patterns` - Error patterns

#### Actions
1. Add trap handlers
2. Implement retry logic
3. Create error messages
4. Set up exit codes
5. Add rollback capability

#### Copy-Paste Prompts
```
Use @bash-defensive-patterns to add comprehensive error handling
```

### Phase 5: Logging

#### Skills to Invoke
- `bash-pro` - Logging patterns

#### Actions
1. Create logging function
2. Add log levels
3. Implement timestamps
4. Configure log rotation
5. Add debug mode

#### Copy-Paste Prompts
```
Use @bash-pro to implement structured logging
```

### Phase 6: Testing

#### Skills to Invoke
- `bats-testing-patterns` - Bats testing
- `shellcheck-configuration` - ShellCheck

#### Actions
1. Write Bats tests
2. Run ShellCheck
3. Test edge cases
4. Verify error handling
5. Test with different inputs

#### Copy-Paste Prompts
```
Use @bats-testing-patterns to write script tests
```

```
Use @shellcheck-configuration to lint bash script
```

### Phase 7: Documentation

#### Skills to Invoke
- `documentation-templates` - Documentation

#### Actions
1. Add script header
2. Document functions
3. Create usage examples
4. List dependencies
5. Add troubleshooting section

#### Copy-Paste Prompts
```
Use @documentation-templates to document bash script
```

## Script Template

```bash
#!/usr/bin/env bash
set -euo pipefail

readonly SCRIPT_NAME=$(basename "$0")
readonly SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
error() { log "ERROR: $*" >&2; exit 1; }

usage() { cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS]
Options:
    -h, --help      Show help
    -v, --verbose   Verbose output
EOF
}

main() {
    log "Script started"
    # Implementation
    log "Script completed"
}

main "$@"
```

## Quality Gates

- [ ] ShellCheck passes
- [ ] Bats tests pass
- [ ] Error handling works
- [ ] Logging functional
- [ ] Documentation complete

## Related Workflow Bundles

- `os-scripting` - OS scripting
- `linux-troubleshooting` - Linux troubleshooting
- `cloud-devops` - DevOps automation

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: bats-testing-patterns
description: "Master Bash Automated Testing System (Bats) for comprehensive shell script testing. Use when writing tests for shell scripts, CI/CD pipelines, or requiring test-driven development of shell utilities."
risk: critical
source: community
date_added: "2026-02-27"
---

# Bats Testing Patterns

Comprehensive guidance for writing comprehensive unit tests for shell scripts using Bats (Bash Automated Testing System), including test patterns, fixtures, and best practices for production-grade shell testing.

## Use this skill when

- Writing unit tests for shell scripts
- Implementing TDD for scripts
- Setting up automated testing in CI/CD pipelines
- Testing edge cases and error conditions
- Validating behavior across shell environments

## Do not use this skill when

- The project does not use shell scripts
- You need integration tests beyond shell behavior
- The goal is only linting or formatting

## Instructions

- Confirm shell dialects and supported environments.
- Set up a test structure with helpers and fixtures.
- Write tests for exit codes, output, and side effects.
- Add setup/teardown and run tests in CI.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.