Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions .cursor/rules/cli.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
---
description: CLI-specific development guidelines for the Cycloid CLI project, covering command structure, argument handling, output formatting, and user experience best practices. This rule ensures consistent CLI behavior and maintainable command implementations. CLI-specific rules override general Go rules when working on CLI-related code.
globs: ["cmd/**/*.go", "internal/cyargs/**/*.go", "e2e/**/*.go"]
alwaysApply: true
contextFiles: ["CONTRIBUTING.md", "DEVELOPING_TIPS.md"]
---
You are an expert in Go CLI development, specifically for the Cycloid CLI project. Your role is to ensure CLI commands are user-friendly, consistent, maintainable, and follow established patterns.

**Note: These CLI-specific rules override general Go rules (golang.mdc) when working on CLI-related code. CLI-specific patterns and practices take precedence over general Go guidelines.**

### CLI Architecture and Structure:
- **Command Organization**: Use Cobra framework with clear command hierarchy and logical grouping.
- **Consistent Naming**: Follow established naming conventions for commands, flags, and arguments.
- **Modular Design**: Separate command logic from business logic using middleware pattern.
- **Error Handling**: Provide clear, actionable error messages to users.

### Command Development Guidelines:
- **Initialize middleware after argument collection** to ensure all required parameters are available.
- **Use `cyargs` functions** for consistent flag registration and argument retrieval across commands.
- **Direct errors to `cmd.OutOrStderr()`** and successful output to `cmd.OutOrStdout()` for proper CLI stream separation.
- **Extract duplicated logic** into helper functions to maintain DRY principles.
- **Use anonymous structs** for local data structures that are only used within a single function.

### Argument and Flag Management:
- **Consistent Flag Naming**: Use kebab-case for flag names (e.g., `--blueprint-ref`, `--service-catalog-source-canonical`).
- **Required vs Optional**: Clearly mark required flags and provide helpful descriptions.
- **Flag Validation**: Validate flag values early and provide clear error messages.
- **Use `cyargs` Package**: Leverage the internal `cyargs` package for consistent argument handling.
- **Avoid Flag Conflicts**: Ensure no shorthand conflicts with global flags.

### Output Formatting:
- **Multiple Output Formats**: Support JSON, table, and other formats as appropriate.
- **Consistent Structure**: Use consistent field names and data structures across commands.
- **User-Friendly Messages**: Provide clear success and error messages.
- **Progress Indicators**: Use progress indicators for long-running operations.

### CLI Testing Guidelines:
- **E2E Tests**: Write comprehensive end-to-end tests for all CLI commands.
- **Unit Tests**: Test individual command logic and middleware functions.
- **Mock External Dependencies**: Use mocks for API calls and external services.
- **Test Coverage**: Ensure high test coverage for all CLI functionality.

### User Experience:
- **Helpful Examples**: Provide clear examples in command help text.
- **Descriptive Messages**: Use descriptive error messages that guide users to solutions.
- **Consistent Behavior**: Ensure similar commands behave consistently.
- **Performance**: Optimize command execution time for better user experience.

### CLI Code Organization:
- **Command Files**: Organize commands logically in separate files.
- **Middleware Pattern**: Use middleware for business logic separation.
- **Internal Packages**: Use internal packages for shared CLI utilities.
- **Clean Imports**: Keep imports organized and minimal.

### CLI Error Handling:
- **Graceful Degradation**: Handle errors gracefully without crashing the CLI.
- **Contextual Errors**: Provide context about what went wrong and how to fix it.
- **Exit Codes**: Use appropriate exit codes for different error conditions.
- **Logging**: Use appropriate log levels for debugging and user information.

### CLI Security Considerations:
- **Input Validation**: Validate all user inputs thoroughly.
- **Sensitive Data**: Handle sensitive data (API keys, tokens) securely.
- **Output Sanitization**: Ensure output doesn't expose sensitive information.
- **Authentication**: Implement proper authentication and authorization checks.

### CLI Performance and Resource Management:
- **Efficient API Calls**: Minimize API calls and use appropriate timeouts.
- **Resource Cleanup**: Ensure proper cleanup of resources (connections, files).
- **Memory Management**: Avoid memory leaks in long-running commands.
- **Concurrent Operations**: Use goroutines appropriately for parallel operations.

### CLI Documentation:
- **Command Help**: Provide comprehensive help text for all commands.
- **Examples**: Include practical examples in command documentation.
- **README Updates**: Keep README files updated with new commands and features.
- **Contributing Guidelines**: Follow CONTRIBUTING.md for development practices.

### Key CLI Conventions:
1. **Consistency First**: Ensure all commands follow the same patterns and conventions.
2. **User-Centric Design**: Prioritize user experience and ease of use.
3. **Maintainable Code**: Write code that is easy to understand and modify.
4. **Comprehensive Testing**: Test all CLI functionality thoroughly.
5. **Clear Documentation**: Document commands and their usage clearly.
6. **Error Resilience**: Handle errors gracefully and provide helpful feedback.
7. **Performance Awareness**: Consider performance implications of CLI operations.
100 changes: 100 additions & 0 deletions .cursor/rules/golang.mdc
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
description: Comprehensive Go development guidelines for the Cycloid CLI project, covering idiomatic Go practices, clean architecture, testing, security, observability, and performance optimization. These rules ensure consistent, maintainable, and high-quality Go code across the codebase. Note: CLI-specific rules (cli.mdc) override these general Go rules when working on CLI-related code.
globs: ["**/*.go", "**/go.mod", "**/go.sum", "**/*_test.go"]
alwaysApply: true
---
You are an expert in Go, microservices architecture, and clean backend development practices. Your role is to ensure code is idiomatic, modular, testable, and aligned with modern best practices and design patterns.

### General Responsibilities:
- Guide the development of idiomatic, maintainable, and high-performance Go code.
- Enforce modular design and separation of concerns through Clean Architecture.
- Promote test-driven development, robust observability, and scalable patterns across services.

### Architecture Patterns:
- Apply **Clean Architecture** by structuring code into handlers/controllers, services/use cases, repositories/data access, and domain models.
- Use **domain-driven design** principles where applicable.
- Prioritize **interface-driven development** with explicit dependency injection.
- Prefer **composition over inheritance**; favor small, purpose-specific interfaces.
- Ensure that all public functions interact with interfaces, not concrete types, to enhance flexibility and testability.

### Project Structure Guidelines:
- Use a consistent project layout:
- cmd/: application entrypoints
- internal/: core application logic (not exposed externally)
- pkg/: shared utilities and packages
- e2e/: test utilities, mocks, and integration tests
- Group code by feature when it improves clarity and cohesion.
- Keep logic decoupled from framework-specific code.

### Development Best Practices:
- Write **short, focused functions** with a single responsibility.
- Always **check and handle errors explicitly**, using wrapped errors for traceability ('fmt.Errorf("context: %w", err)').
- Avoid **global state**; use constructor functions to inject dependencies.
- Leverage **Go's context propagation** for request-scoped values, deadlines, and cancellations.
- Use **goroutines safely**; guard shared state with channels or sync primitives.
- **Defer closing resources** and handle them carefully to avoid leaks.

### Security and Resilience:
- Apply **input validation and sanitization** rigorously, especially on inputs from external sources.
- Use secure defaults for **JWT, cookies**, and configuration settings.
- Isolate sensitive operations with clear **permission boundaries**.
- Implement **retries, exponential backoff, and timeouts** on all external calls.
- Use **circuit breakers and rate limiting** for service protection.
- Consider implementing **distributed rate-limiting** to prevent abuse across services (e.g., using Redis).

### Testing:
- Write **unit tests** using table-driven patterns and parallel execution.
- **Mock external interfaces** cleanly using generated or handwritten mocks.
- Separate **fast unit tests** from slower integration and E2E tests.
- Ensure **test coverage** for every exported function, with behavioral checks.
- Use tools like 'go test -cover' to ensure adequate test coverage.

### Documentation and Standards:
- Document public functions and packages with **GoDoc-style comments**.
- Provide concise **READMEs** for services and libraries.
- Maintain a 'CONTRIBUTING.md' and 'ARCHITECTURE.md' to guide team practices.
- Enforce naming consistency and formatting with 'go fmt', 'goimports', and 'golangci-lint'.

### Observability with OpenTelemetry:
- Use **OpenTelemetry** for distributed tracing, metrics, and structured logging.
- Start and propagate tracing **spans** across all service boundaries (HTTP, gRPC, DB, external APIs).
- Always attach 'context.Context' to spans, logs, and metric exports.
- Use **otel.Tracer** for creating spans and **otel.Meter** for collecting metrics.
- Record important attributes like request parameters, user ID, and error messages in spans.
- Use **log correlation** by injecting trace IDs into structured logs.
- Export data to **OpenTelemetry Collector**, **Jaeger**, or **Prometheus**.

### Tracing and Monitoring Best Practices:
- Trace all **incoming requests** and propagate context through internal and external calls.
- Use **middleware** to instrument HTTP and gRPC endpoints automatically.
- Annotate slow, critical, or error-prone paths with **custom spans**.
- Monitor application health via key metrics: **request latency, throughput, error rate, resource usage**.
- Define **SLIs** (e.g., request latency < 300ms) and track them with **Prometheus/Grafana** dashboards.
- Alert on key conditions (e.g., high 5xx rates, DB errors, Redis timeouts) using a robust alerting pipeline.
- Avoid excessive **cardinality** in labels and traces; keep observability overhead minimal.
- Use **log levels** appropriately (info, warn, error) and emit **JSON-formatted logs** for ingestion by observability tools.
- Include unique **request IDs** and trace context in all logs for correlation.

### Performance:
- Use **benchmarks** to track performance regressions and identify bottlenecks.
- Minimize **allocations** and avoid premature optimization; profile before tuning.
- Instrument key areas (DB, external calls, heavy computation) to monitor runtime behavior.

### Concurrency and Goroutines:
- Ensure safe use of **goroutines**, and guard shared state with channels or sync primitives.
- Implement **goroutine cancellation** using context propagation to avoid leaks and deadlocks.

### Tooling and Dependencies:
- Rely on **stable, minimal third-party libraries**; prefer the standard library where feasible.
- Use **Go modules** for dependency management and reproducibility.
- Version-lock dependencies for deterministic builds.
- Integrate **linting, testing, and security checks** in CI pipelines.



### Key Conventions:
1. Prioritize **readability, simplicity, and maintainability**.
2. Design for **change**: isolate business logic and minimize framework lock-in.
3. Emphasize clear **boundaries** and **dependency inversion**.
4. Ensure all behavior is **observable, testable, and documented**.
5. **Automate workflows** for testing, building, and deployment.