### Example Output File Specification Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/context-engineering.md This markdown specifies the required output files for a project, detailing the purpose of each file. It's used to guide AI model generation by defining the expected structure and components of the codebase. ```markdown ## Required Output Files 1. **models.py**: SQLAlchemy ORM classes with ForeignKey relationships 2. **schemas.py**: Pydantic validation models 3. **routers/order.py**: FastAPI route handlers (create, read, update, delete) 4. **main.py**: Application entry point with dependency injection 5. **requirements.txt**: Python package dependencies ``` -------------------------------- ### Claude Code Prompt Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/context-engineering.md An example prompt for Claude Code demonstrating how to reference specific documentation sections and define implementation tasks and constraints. ```markdown Reference: auth-module.mdc#API_Interface Task: Implement POST /login endpoint Constraints: - Use OAuth 2.0 with PKCE (see core-standards.mdc) - Return JWT in httpOnly cookie (security requirement) - Log all attempts to audit trail ``` -------------------------------- ### Product Requirements Document (PRD) Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md An example PRD for a comment system, including market analysis, MVP scope, and key metrics. ```markdown ## PRD: Comment System ### Market Analysis Competitors (Twitter, Facebook, Medium) all have nested comment systems. User surveys: 70% want to comment, 20% want threaded replies. ### MVP Scope Phase 1: Basic comments (no nesting) — 2 weeks Phase 2: Nested replies (1 level) — 2 weeks Phase 3: Rich text editor — TBD ### Metrics - Comment adoption: Target 40% of users comment - Engagement: Average 3 comments per post - Response time: 1 second for create ``` -------------------------------- ### BDD: Gherkin Feature File Examples Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Shows examples of feature files written in Gherkin syntax for Behavior-Driven Development. ```gherkin Feature: User authentication Scenario: User logs in with valid credentials Given a user with email "user@example.com" and password "secret123" When the user submits the login form with their credentials Then the user should be logged in And the user should see the dashboard Scenario: User logs in with invalid password Given a user with email "user@example.com" registered When the user submits the login form with wrong password Then the user should see error "Invalid password" And the user should NOT be logged in ``` -------------------------------- ### Example Sync Workflow Steps Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/vibe-engineering.md Illustrates a workflow where a user defines a feature in a spec file, uses AI to generate requirements and tasks, implements the feature, and reviews a pull request to ensure synchronization. ```bash 1. User writes spec: "Add comment feature with nested replies" → Saved to spec.md 2. User runs: /spec-create → AI reads spec.md → Generates: requirements, design, tasks, tests → Saved to spec.json 3. User runs: /spec-execute task-001 → AI reads spec.json + codebase context → Implements feature → Runs tests 4. User reviews PR → Changes align with spec → Tests all pass → Merge 5. Code + spec + tests all in sync ✓ ``` -------------------------------- ### Requirements Document Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md An example of a requirements document outlining user stories, acceptance criteria, and constraints for a comment system. ```markdown ## Requirements ### User Stories 1. As a user, I want to comment on posts so that I can provide feedback 2. As a comment author, I want to delete my comments so I can remove outdated thoughts 3. As a post author, I want to see comment count so I know engagement ### Acceptance Criteria - User can write comment in 500 chars max - Comment appears immediately after posting - Only comment author can delete - Comments persist across sessions ### Constraints - Can use existing User/Post tables - Comments should work on mobile (responsive) - Support up to 10K comments per post ``` -------------------------------- ### Strategy Pattern Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/topic-how_to_vibe_a_suitable_system_architecture/README.md Illustrates the Strategy pattern, defining a family of algorithms that can be interchanged. Suitable when multiple ways exist to perform a task and one needs to be selected at runtime. ```java interface PaymentStrategy { void pay(int amount); } class CreditCardPayment implements PaymentStrategy { public void pay(int amount) { System.out.println("用信用卡支付 " + amount + " 元"); } } class MobilePayment implements PaymentStrategy { public void pay(int amount) { System.out.println("用手機支付 " + amount + " 元"); } } class ShoppingCart { private PaymentStrategy paymentStrategy; public void setPaymentStrategy(PaymentStrategy strategy) { this.paymentStrategy = strategy; } public void checkout(int amount) { paymentStrategy.pay(amount); } } ``` -------------------------------- ### Example Spec Structure for Feature: Comment System Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Illustrates a typical structure for a feature specification using markdown, including requirements, implementation plan, and acceptance criteria. ```markdown # Feature: Comment System ## Requirements - User can POST comment on post - Comment max 500 chars - Only author can DELETE ## Implementation Plan 1. Database schema 2. ORM models 3. API endpoints 4. Frontend integration ## Acceptance Criteria - All tests pass - 80%+ coverage - Performance: < 1sec latency ``` -------------------------------- ### Template Method Pattern Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/topic-how_to_vibe_a_suitable_system_architecture/README.md Demonstrates the Template Method pattern where a fixed algorithm skeleton is defined, and specific steps are deferred to subclasses. Useful for fixed processes with variable steps. ```java abstract class CookingProcess { // 模板方法 - 定義烹飪流程 public final void cook() { prepareIngredients(); cooking(); serve(); } protected abstract void prepareIngredients(); // 子類實現 protected abstract void cooking(); // 子類實現 protected void serve() { System.out.println("裝盤上菜"); } } class MakePasta extends CookingProcess { protected void prepareIngredients() { System.out.println("準備義大利麵和醬料"); } protected void cooking() { System.out.println("煮麵配醬"); } } ``` -------------------------------- ### Factory Pattern Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/topic-how_to_vibe_a_suitable_system_architecture/README.md Shows the Factory pattern for object creation, decoupling the client from the instantiation logic. Use when object creation is complex or depends on varying conditions. ```java interface Vehicle { void start(); } class Car implements Vehicle { public void start() { System.out.println("汽車啟動"); } } class Motorcycle implements Vehicle { public void start() { System.out.println("機車啟動"); } } class VehicleFactory { public static Vehicle createVehicle(String type) { if ("car".equals(type)) { return new Car(); } else if ("motorcycle".equals(type)) { return new Motorcycle(); } return null; } } ``` -------------------------------- ### Arrange-Act-Assert Pattern Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Demonstrates the Arrange-Act-Assert pattern for structuring tests. Use this pattern to clearly separate test setup, execution, and verification steps. ```python def test_calculate_order_discount(): # ARRANGE order = Order.create(items=[ OrderItem(Product(price=100), qty=1), OrderItem(Product(price=50), qty=2), ]) # ACT order.apply_discount(percent=10) # ASSERT assert order.total() == 180 # 200 * 0.9 ``` -------------------------------- ### Behave Feature File Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Example of a feature file for Behave, a BDD framework for Python. Used to define user scenarios and expected outcomes. ```gherkin Feature: User login Scenario: Valid credentials Given a user with email "user@example.com" When user logs in with password "secret" Then user should be authenticated ``` -------------------------------- ### Cucumber Feature File Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Example of a feature file for Cucumber, a BDD framework for Java and JavaScript. Used to define API authentication scenarios. ```gherkin Feature: API authentication Scenario: Valid token Given user has valid JWT token When API receives request with token Then response should be 200 ``` -------------------------------- ### Singleton Pattern Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/topic-how_to_vibe_a_suitable_system_architecture/README.md Implements the Singleton pattern to ensure a class has only one instance and provides a global access point. Ideal for managing resources like database connections or loggers. ```java class DatabaseConnection { private static DatabaseConnection instance; // 私有構造函數,防止外部創建實例 private DatabaseConnection() {} // 線程安全的獲取實例方法 public static synchronized DatabaseConnection getInstance() { if (instance == null) { instance = new DatabaseConnection(); } return instance; } public void connect() { System.out.println("連接數據庫"); } } ``` -------------------------------- ### Provide Feedback to AI for Optimization Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Example feedback to AI suggesting an optimization for atomic counter increments using Django's F() expression. ```markdown Feedback to AI: "Test test_concurrent_comments_count_accurate is failing. The issue is a race condition in comment_count increment. Use Django's F() expression for atomic increment: Post.objects.filter(id=post_id).update( comment_count=F('comment_count') + 1 ) Revise the implementation." ``` -------------------------------- ### BDD: Python Step Definitions (Behave) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Provides Python code examples for step definitions using the Behave framework, linking Gherkin steps to executable code. ```python from behave import given, when, then @given('a user with email "{email}" and password "{password}"') def step_create_user(context, email, password): context.user = User.create(email=email, password=password) @when('the user submits the login form with their credentials') def step_user_login(context): context.login_result = login(context.user.email, context.user.password) @then('the user should be logged in') def step_verify_logged_in(context): assert context.login_result.success is True assert context.login_result.user_id == context.user.id ``` -------------------------------- ### Python Mutation Testing Example Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Demonstrates how a good test can catch a bug introduced by mutation, while a bad test might pass. Use this to verify your test suite's effectiveness. ```python # Implementation with bug: def calculate_discount(price, rate): return price * rate # WRONG: should be (1 - rate) # Good test catches this: assert calculate_discount(100, 0.1) == 90 # Fails! Reveals bug. # Bad test doesn't catch this: assert calculate_discount(100, 0) >= 0 # Passes even with bug! ``` -------------------------------- ### Report Test Failure to AI Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Example of a precise failure report for a test case, detailing the expected vs. actual results and the root cause. ```markdown FAILURE: test_concurrent_comments_count_accurate When two users comment simultaneously: Expected: post.comment_count == 2 Actual: post.comment_count == 1 (race condition) Root cause: Comment.save() increments counter; doesn't use atomic transaction Fix: Use database-level atomic increment or transaction lock ``` -------------------------------- ### Kiro IDE Specification-Driven Development Workflow Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Illustrates the command sequence for initiating and progressing through a Specification-Driven Development workflow in Kiro IDE. ```bash /kiro:spec-init → /kiro:spec-requirements → /kiro:spec-design → /kiro:spec-tasks → /kiro:spec-impl → /kiro:spec-verify ``` -------------------------------- ### Monolith to Microservices Architecture Evolution Stages Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Illustrates the progression from an MVP Monolith through Modular Monolith and Strangler Pattern to a Multi-Service architecture. This path is taken when services need independent scaling, different ownership, or distinct technology choices. ```text Stage 1: MVP Monolith [All features in one binary] ↓ Metrics: Deployment time < 15min, one team, < 100K lines Stage 2: Modular Monolith [Same binary, but clearly separated modules] ↓ Action: Identify candidate services for extraction Stage 3: Strangler Pattern [New service added; route subset of traffic] [Legacy monolith + New service run in parallel] ↓ Action: Gradually shift traffic from monolith to service Stage 4: Multi-Service [Multiple services in production] ↓ Complexity: Distributed tracing, deployment orchestration needed ``` -------------------------------- ### Generate Project Context with Repomix Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Command to generate a markdown file containing project context for AI agents. This includes project structure, key files, and configurations. ```bash repomix --output context.md # Creates complete project context for pasting to AI # Then in Claude Code: "Reference the attached context.md; implement feature X" ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Organize project documentation using a standard set of Markdown files at the project root. ```markdown project-root/ ├── README.md # Project overview ├── ARCHITECTURE.md # System design ├── API.md # API specification ├── DEVELOPMENT.md # Development guidelines └── TESTING.md # Testing strategy ``` -------------------------------- ### Repository Structure Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/README.md Illustrates the directory structure of the Open Vibe Developers project, showing the main README, license, and topic-specific subdirectories. ```tree open-vibe-developers/ ├── README.md # Main entry point ├── LICENCE # License file ├── topic-how_to_build_context_for_vibe_coding/ # Context engineering topic ├── topic-how_to_vibe_a_suitable_system_architecture/ # Architecture design topic ├── topic-how_to_make_ai_coding_work_well_in_projects/ # Project integration topic └── topic-how_to_combine_vibe_coding_with_testing/ # Testing methodology topic ``` -------------------------------- ### Technology Stack Specification (tech.md) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Document the technology stack, including backend, frontend, and infrastructure components, in a `tech.md` file. ```markdown # Technology Stack ## Backend - Framework: FastAPI 0.95+ - Database: PostgreSQL 14+ - Cache: Redis 7+ - Language: Python 3.10+ ## Frontend - Framework: React 18+ - State: Redux Toolkit - UI: Material-UI v5 ## Infrastructure - Container: Docker - Orchestration: Kubernetes - CI/CD: GitHub Actions ``` -------------------------------- ### TDD: Calculate Discount Logic Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Demonstrates the Test-Driven Development cycle: writing a failing test, implementing the minimum code to pass, and then refactoring. ```python def test_calculate_discount(): assert calculate_discount(100, 0.1) == 90 ``` ```python def calculate_discount(price, rate): return price * (1 - rate) ``` ```python def calculate_discount(price: float, discount_rate: float) -> float: """Calculate discounted price.""" if not 0 <= discount_rate <= 1: raise ValueError("Discount rate must be 0-1") return price * (1 - discount_rate) ``` -------------------------------- ### MDC Knowledge Base Directory Structure Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/context-engineering.md Illustrates the hierarchical organization of Modular Documentation Components (MDC) files within a knowledge base. ```bash knowledge-base/ ├── index.mdc # Navigation and structure ├── core-standards.mdc # Coding standards & conventions ├── team-protocol.mdc # Workflow & collaboration norms ├── auth-module.mdc # Authentication system docs ├── project-a.mdc # Project-specific context └── templates/ ├── api-endpoint.mdc # API documentation template ├── class-design.mdc # Class/method template └── test-spec.mdc # Test case template ``` -------------------------------- ### Project Context Specification (project.md) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Define business goals, constraints, and high-level project requirements in a `project.md` file for long-term AI context. ```markdown # Project: E-Commerce Platform ## Business Goals - Ship comment system by end of Q1 - 99.9% uptime SLA - Support 100K concurrent users ## Constraints - PostgreSQL database (no NoSQL) - FastAPI backend - React frontend - < $1000/month infrastructure ``` -------------------------------- ### Codebase Structure Specification (structure.md) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Outline the project's codebase structure using a `structure.md` file, detailing directories and their purposes. ```markdown # Codebase Structure ``` backend/ ├── src/ │ ├── models/ # ORM classes │ ├── services/ # Business logic │ ├── handlers/ # HTTP routes │ └── middleware/ # Middleware ├── tests/ ├── migrations/ └── requirements.txt frontend/ ├── src/ │ ├── components/ │ ├── pages/ │ ├── store/ │ └── styles/ ├── tests/ └── package.json ``` ``` -------------------------------- ### Boundary Testing for Discounts Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Tests edge cases for discount calculations, including zero percent, full discount, and invalid negative or above-one percentages. Ensures discount logic handles boundaries correctly. ```python def test_discount_zero_percent(): assert calculate_discount(100, 0) == 100 # No discount def test_discount_one_hundred_percent(): assert calculate_discount(100, 1) == 0 # Full discount def test_discount_invalid_negative(): with pytest.raises(ValueError): calculate_discount(100, -0.1) def test_discount_invalid_above_one(): with pytest.raises(ValueError): calculate_discount(100, 1.5) ``` -------------------------------- ### Python Step Definitions for User Registration Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/methodologies.md These Python step definitions, using the 'behave' framework, implement the Gherkin scenarios for user registration. They define the logic for Given, When, and Then steps, interacting with user and email systems. ```python from behave import given, when, then @given('a new user') def step_new_user(context): context.user = User() @when('user provides email "{email}" and password "{password}"') def step_user_registers(context, email, password): context.result = context.user.register(email, password) @then('user account is created') def step_account_created(context): assert context.result.success assert User.find_by_email(email).exists() @then('user receives welcome email') def step_email_sent(context): assert email_queue.has_message(to=email, subject="Welcome") ``` -------------------------------- ### Manual API Test for Creating a Comment Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Perform a manual test by sending a POST request to create a comment via the API. Includes authorization and request body. ```bash curl -X POST http://localhost:8000/api/v1/posts/abc/comments \ -H "Authorization: Bearer token" \ -d '{"text": "Great post!"}' ``` -------------------------------- ### Strategy Pattern Structure (Java) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Defines a family of interchangeable algorithms. The client can select and use a strategy at runtime, enabling behavioral flexibility without changing client code. Useful when multiple implementation choices exist. ```java interface Strategy { void execute(); } class StrategyA implements Strategy { public void execute() { /* implementation A */ } } class Client { private Strategy strategy; public void setStrategy(Strategy s) { this.strategy = s; } public void run() { strategy.execute(); } } ``` -------------------------------- ### Run Unit Tests with Coverage Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Execute unit tests for the comments module and generate a coverage report using pytest. ```bash # Coverage pytest tests/test_comments.py --cov=src.comments ``` -------------------------------- ### Python Test for Order Workflow Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md This test demonstrates a complete order workflow, including creation, payment, shipping, and delivery. It serves as an executable specification for the user journey. ```python def test_order_workflow(): """Complete order workflow: create → pay → ship → deliver.""" # This test documents the entire user journey user = create_user() order = user.create_order(items=[...]) assert order.status == "pending" order.process_payment(method="credit_card", amount=100) assert order.status == "paid" order.ship() assert order.status == "shipped" order.deliver() assert order.status == "delivered" ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Execute unit tests for the comments module using pytest. This command also shows verbose output. ```bash # Unit tests pytest tests/test_comments.py -v ``` -------------------------------- ### Template Method Pattern Structure (Java) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Defines an algorithm skeleton in a base class, allowing subclasses to implement specific steps without altering the algorithm's structure. Useful for fixed workflows with variable implementations. ```java abstract class Algorithm { public final void execute() { step1(); step2(); step3(); } protected abstract void step1(); protected abstract void step2(); protected void step3() { /* default */ } } class ConcreteAlgorithm extends Algorithm { protected void step1() { /* specific implementation */ } protected void step2() { /* specific implementation */ } } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/project-integration.md Execute integration tests for the comment API using pytest. Assumes all tests pass. ```bash # Integration tests pytest tests/integration/test_comment_api.py -v ``` -------------------------------- ### MDC File Structure Template Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/context-engineering.md Defines a standard Markdown format for individual MDC files, covering module name, description, technology, API, data model, logic, testing, and constraints. ```markdown ## Module Name: [X] ### Functional Description [2-3 sentences on what this does and why] ### Technology Stack - Framework: [X] - Database: [X] - Libraries: [A], [B] ### API Interface - POST /endpoint — Description - GET /endpoint/{id} — Description ### Data Model [Table or diagram] ### Logic Flow [Sequence diagram or pseudocode] ### Testing Scenarios - Scenario A: [condition] → [expected result] - Scenario B: [condition] → [expected result] ### Known Constraints - [Constraint 1] - [Constraint 2] ``` -------------------------------- ### TDD: Standard Test Structure Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Illustrates a common structure for unit tests using the Arrange-Act-Assert (AAA) pattern. ```python def test_[feature]_[scenario]_[expected_result](): # ARRANGE: Set up test data user = User(name="Alice", balance=100) # ACT: Perform the action result = user.spend_money(amount=30) # ASSERT: Verify expected outcome assert user.balance == 70 assert result.success is True ``` -------------------------------- ### AI Implementation for Comment Creation Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/vibe-engineering.md This Python function provides an implementation for creating a comment, designed to pass the associated unit test. It handles database session management. ```python def create_comment(post_id, parent_id=None, **kwargs): comment = Comment(post_id=post_id, parent_id=parent_id, ...) db.session.add(comment) db.session.commit() return comment ``` -------------------------------- ### Image Generation Queue (Python) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Handles image generation requests asynchronously using a queue. The API immediately returns a job ID, and a separate worker processes the request. This decouples the frontend from backend processing speed. ```python # User requests image → immediately return queue ID # Worker processes asynchronously queue.push({ 'user_id': request.user_id, 'prompt': request.prompt, 'model': 'stable-diffusion-3' }) return {'status': 'queued', 'job_id': job_id} # Poll later or webhook GET /jobs/{job_id} → {'status': 'processing', 'position': 5} GET /jobs/{job_id} → {'status': 'complete', 'image_url': '...'} ``` -------------------------------- ### Python Domain Entities and Business Rules for E-commerce Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Defines core domain entities like Order and OrderItem, and illustrates business rules as Python tests using pytest. These tests encode invariants such as order total calculation and shipping/refund constraints. ```python from typing import List # Assuming Product, Customer, OrderStatus, BusinessRuleViolation are defined elsewhere # Domain entities class Order: def __init__(self, items: List[OrderItem], customer: Customer): self.items = items self.customer = customer self.status = OrderStatus.PENDING def total(self) -> float: # Placeholder for actual total calculation logic return sum(item.price() for item in self.items if not item.is_cancelled) def ship(self): # Placeholder for ship logic if not self.is_paid(): raise BusinessRuleViolation("Payment required before shipment.") # ... other shipping logic def refund(self, amount: float): # Placeholder for refund logic if amount > self.total_paid(): # Assuming total_paid() exists raise BusinessRuleViolation("Cannot refund more than original payment.") # ... other refund logic def is_paid(self) -> bool: # Placeholder for payment status check return True # Example value def total_paid(self) -> float: # Placeholder for total paid amount return 100.0 # Example value class OrderItem: def __init__(self, product: Product, quantity: int): self.product = product self.quantity = quantity self.is_cancelled = False def price(self) -> float: return self.product.price * self.quantity def cancel(self): self.is_cancelled = True # Mock definitions for Product, Customer, OrderStatus, BusinessRuleViolation for completeness class Product: def __init__(self, price: float): self.price = price class Customer: pass class OrderStatus: PENDING = "pending" SHIPPED = "shipped" CANCELLED = "cancelled" class BusinessRuleViolation(Exception): pass # Helper functions for tests def create_order_with_items(items_data): items = [OrderItem(Product(price=data['price']), data['quantity']) for data in items_data] return Order(items, Customer()) def create_order_with_total(total_amount): # This helper might need adjustment based on how total is calculated and paid # For simplicity, creating a dummy order that satisfies the refund test condition items = [OrderItem(Product(price=total_amount), 1)] order = Order(items, Customer()) # Mocking payment status if needed by order.refund logic return order # Domain business rules (encoded in tests) import pytest def test_order_total_excludes_cancelled_items(): """Business rule: Cancelled items don't contribute to total.""" order = create_order_with_items([ {"price": 100, "quantity": 2}, {"price": 50, "quantity": 1}, ]) order.items[1].cancel() assert order.total() == 200 def test_order_cannot_ship_without_payment(): """Business rule: Payment required before shipment.""" # Assuming create_order_with_items can create an order that is not paid order = create_order_with_items([{"price": 100, "quantity": 1}]) # Mocking order.is_paid() to return False for this test case order.is_paid = lambda: False with pytest.raises(BusinessRuleViolation, match="Payment required before shipment."): order.ship() def test_refund_must_be_less_than_original_payment(): """Business rule: Cannot refund more than charged.""" order = create_order_with_total(100) # Mocking total_paid() to return a specific value for the test order.total_paid = lambda: 100.0 with pytest.raises(BusinessRuleViolation, match="Cannot refund more than original payment."): order.refund(amount=150) ``` -------------------------------- ### Feature Specification in Markdown Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Use Markdown for capturing feature requirements and acceptance criteria in a structured format. ```markdown ## Feature: Comments ### Requirements - Users can comment on posts - Comments are searchable ### Acceptance Criteria - [ ] API endpoint POST /posts/{id}/comments works - [ ] Comment appears in list - [ ] Search finds comments ### Technical Notes - Use PostgreSQL - Cache with Redis ``` -------------------------------- ### State Verification After Operation Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Verifies the state of a user object after a payment process. This test checks for expected changes in status, balance, and update timestamps. ```python def test_user_status_after_payment(): user = create_user(status="pending") process_payment(user, amount=50) user.refresh_from_db() assert user.status == "active" assert user.balance == 50 assert user.updated_at > datetime.now() - timedelta(seconds=1) ``` -------------------------------- ### C4 Model Architecture Diagram using PlantUML Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/tools-and-frameworks.md Defines a simple C4 model architecture with a web API, database, and cache using PlantUML syntax. This is useful for visualizing system components and their interactions. ```puml @startuml !define CONTAINER(name, description) card name [description] CONTAINER(web_api, "Web API\n[FastAPI]") CONTAINER(database, "Database\n[PostgreSQL]") CONTAINER(cache, "Cache\n[Redis]") web_api --> database : queries web_api --> cache : reads/writes @enduml ``` -------------------------------- ### Factory Pattern Structure (Java) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Abstracts the object creation process, hiding implementation details. This promotes loose coupling between object creation and usage. Ideal when creation logic is complex or varies by type. ```java class Factory { public static Object create(String type) { switch(type) { case "A": return new ConcreteA(); case "B": return new ConcreteB(); } } } ``` -------------------------------- ### ML Inference Service Isolation (Diagram) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Illustrates a system architecture change to isolate slow ML inference. The original blocking pattern is replaced with an asynchronous pattern using a queue and a dedicated ML worker, improving API response times. ```text Before: [Web API] → [ML Model] → [Database] Problem: ML inference (slow) blocks API responses After: [Web API] → [Queue] ← [ML Worker with GPU] ↓ [Cache] Problem solved: API responds immediately; GPU worker processes asynchronously ``` -------------------------------- ### Singleton Pattern Structure (Java) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Ensures that a class has only one instance and provides a global point of access to it. This pattern is useful for resource conservation, such as managing database connections or configuration objects. ```java class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } } ``` -------------------------------- ### Gherkin Feature File for User Registration Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/methodologies.md This Gherkin feature file defines the expected behavior for user registration in a clear, business-readable format. It outlines a specific scenario for successful registration. ```gherkin Feature: User registration Scenario: User registers with valid email Given a new user When user provides email "alice@example.com" and password "secure123" Then user account is created And user receives welcome email ``` -------------------------------- ### Error Handling for Payment Failures Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/testing-frameworks.md Tests error handling for insufficient funds and invalid payment amounts. Uses `pytest.raises` to assert that specific exceptions are thrown with expected details. ```python def test_payment_insufficient_funds(): user = create_user(balance=20) with pytest.raises(InsufficientFundsError) as exc_info: process_payment(user, amount=50) assert exc_info.value.required == 50 assert exc_info.value.available == 20 def test_payment_invalid_amount(): user = create_user(balance=100) with pytest.raises(ValueError, match="Amount must be positive"): process_payment(user, amount=-10) ``` -------------------------------- ### LLM API Response Cache (Python) Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/system-architecture.md Caches Language Model responses using Redis to reduce inference cost and latency for common queries. Set a Time-To-Live (TTL) for cache entries. ```python # Cache LLM responses keyed by (model, prompt_hash) # TTL: 24 hours # Savings: 90% of inference cost for common queries key = f"{model}:{hash(prompt)}" cached = redis.get(key) if cached: return cached # Sub-millisecond response else: response = call_llm(prompt) redis.set(key, response, ex=86400) # 24h TTL return response ``` -------------------------------- ### Unit Test for Comment Creation Source: https://github.com/gitycc/open-vibe-developers/blob/main/_autodocs/vibe-engineering.md This Python test function defines the expected behavior for creating a comment, including its relationship to a parent comment and post. It serves as a contract for the implementation. ```python def test_create_comment_as_reply(): # Given: A post and parent comment post = create_post() parent = create_comment(post_id=post.id) # When: User creates reply reply = create_comment(post_id=post.id, parent_id=parent.id) # Then: Reply linked to parent assert reply.parent_id == parent.id assert parent.replies.count() == 1 ```