From 7f1d0db8edf40b7d4071917357ca416f61569c0b Mon Sep 17 00:00:00 2001 From: Oleg Alexandrov Date: Mon, 22 Sep 2025 10:00:04 +0300 Subject: [PATCH 1/2] feat(status): add INIT_AGENT_NOT_SUITABLE status code Added new initialization status code to handle cases when agent is not suitable for operation. Also added specification documents for exception handling and implementation of 'on' functionality. Removed obsolete pull request documentation files. --- .../contracts/contract-tests.md | 274 ++++++++++++++++++ .../contracts/exceptions-contract.md | 239 +++++++++++++++ .../004-exception-handling/data-model.md | 145 +++++++++ .specify/specs/004-exception-handling/plan.md | 232 +++++++++++++++ .../004-exception-handling/quickstart.md | 136 +++++++++ .../specs/004-exception-handling/research.md | 46 +++ .specify/specs/004-exception-handling/spec.md | 34 +++ .specify/specs/005-implement-the-on/spec.md | 121 ++++++++ HOW_TO_CREATE_PULL_REQUESTS.md | 113 -------- PULL_REQUEST_INSTRUCTIONS.md | 75 ----- src/metaexpert/_status.py | 1 + 11 files changed, 1228 insertions(+), 188 deletions(-) create mode 100644 .specify/specs/004-exception-handling/contracts/contract-tests.md create mode 100644 .specify/specs/004-exception-handling/contracts/exceptions-contract.md create mode 100644 .specify/specs/004-exception-handling/data-model.md create mode 100644 .specify/specs/004-exception-handling/plan.md create mode 100644 .specify/specs/004-exception-handling/quickstart.md create mode 100644 .specify/specs/004-exception-handling/research.md create mode 100644 .specify/specs/004-exception-handling/spec.md create mode 100644 .specify/specs/005-implement-the-on/spec.md delete mode 100644 HOW_TO_CREATE_PULL_REQUESTS.md delete mode 100644 PULL_REQUEST_INSTRUCTIONS.md diff --git a/.specify/specs/004-exception-handling/contracts/contract-tests.md b/.specify/specs/004-exception-handling/contracts/contract-tests.md new file mode 100644 index 0000000..cd32b44 --- /dev/null +++ b/.specify/specs/004-exception-handling/contracts/contract-tests.md @@ -0,0 +1,274 @@ +# Contract Tests: Exception Handling Module + +These tests verify that the exception classes in the MetaExpert library conform to the defined API contract. + +## Test Structure +Each test file validates one aspect of the exception module contract. + +## Test Files to Create + +1. `test_base_exceptions.py` - Tests for MetaExpertError base class +2. `test_configuration_exceptions.py` - Tests for configuration-related exceptions +3. `test_api_exceptions.py` - Tests for API-related exceptions +4. `test_trading_exceptions.py` - Tests for trading-related exceptions +5. `test_validation_exceptions.py` - Tests for validation-related exceptions +6. `test_market_data_exceptions.py` - Tests for market data-related exceptions +7. `test_process_exceptions.py` - Tests for process-related exceptions + +## Test Requirements + +### test_base_exceptions.py +```python +import pytest +from metaexpert.exceptions import MetaExpertError + +def test_metaexpert_error_inheritance(): + """Test that MetaExpertError inherits from Exception""" + assert issubclass(MetaExpertError, Exception) + +def test_metaexpert_error_creation(): + """Test that MetaExpertError can be instantiated with a message""" + error = MetaExpertError("Test error message") + assert str(error) == "Test error message" + +def test_metaexpert_error_with_args(): + """Test that MetaExpertError can be instantiated with additional arguments""" + error = MetaExpertError("Test error", "arg1", "arg2") + assert str(error) == "Test error" + assert error.args == ("arg1", "arg2") +``` + +### test_configuration_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + ConfigurationError, + InvalidConfigurationError, + MissingConfigurationError +) + +def test_configuration_error_inheritance(): + """Test that ConfigurationError inherits from MetaExpertError""" + assert issubclass(ConfigurationError, MetaExpertError) + +def test_invalid_configuration_error_creation(): + """Test that InvalidConfigurationError can be instantiated with required attributes""" + error = InvalidConfigurationError("api_key", "invalid_value") + assert error.config_key == "api_key" + assert error.config_value == "invalid_value" + +def test_invalid_configuration_error_message(): + """Test that InvalidConfigurationError has a proper error message""" + error = InvalidConfigurationError("api_key", "invalid_value") + assert "api_key" in str(error) + assert "invalid_value" in str(error) + +def test_missing_configuration_error_creation(): + """Test that MissingConfigurationError can be instantiated with required attributes""" + error = MissingConfigurationError("api_secret") + assert error.config_key == "api_secret" + +def test_missing_configuration_error_message(): + """Test that MissingConfigurationError has a proper error message""" + error = MissingConfigurationError("api_secret") + assert "api_secret" in str(error) +``` + +### test_api_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + APIError, + AuthenticationError, + RateLimitError, + NetworkError +) + +def test_api_error_inheritance(): + """Test that APIError inherits from MetaExpertError""" + assert issubclass(APIError, MetaExpertError) + +def test_authentication_error_creation(): + """Test that AuthenticationError can be instantiated with required attributes""" + error = AuthenticationError("binance") + assert error.exchange == "binance" + +def test_authentication_error_message(): + """Test that AuthenticationError has a proper error message""" + error = AuthenticationError("binance") + assert "binance" in str(error) + +def test_rate_limit_error_creation(): + """Test that RateLimitError can be instantiated with required attributes""" + error = RateLimitError("binance", 60) + assert error.exchange == "binance" + assert error.retry_after == 60 + +def test_rate_limit_error_optional_retry(): + """Test that RateLimitError can be instantiated without retry_after""" + error = RateLimitError("binance") + assert error.exchange == "binance" + assert error.retry_after is None + +def test_network_error_creation(): + """Test that NetworkError can be instantiated with required attributes""" + error = NetworkError("https://api.binance.com", "Connection timeout") + assert error.url == "https://api.binance.com" + assert error.reason == "Connection timeout" + +def test_network_error_optional_reason(): + """Test that NetworkError can be instantiated without reason""" + error = NetworkError("https://api.binance.com") + assert error.url == "https://api.binance.com" + assert error.reason is None +``` + +### test_trading_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + TradingError, + InsufficientFundsError, + InvalidOrderError, + OrderNotFoundError +) + +def test_trading_error_inheritance(): + """Test that TradingError inherits from MetaExpertError""" + assert issubclass(TradingError, MetaExpertError) + +def test_insufficient_funds_error_creation(): + """Test that InsufficientFundsError can be instantiated with required attributes""" + error = InsufficientFundsError(100.0, 200.0, "USDT") + assert error.available == 100.0 + assert error.required == 200.0 + assert error.currency == "USDT" + +def test_insufficient_funds_error_message(): + """Test that InsufficientFundsError has a proper error message""" + error = InsufficientFundsError(100.0, 200.0, "USDT") + assert "100.0" in str(error) + assert "200.0" in str(error) + assert "USDT" in str(error) + +def test_invalid_order_error_creation(): + """Test that InvalidOrderError can be instantiated with required attributes""" + order_details = {"symbol": "BTCUSDT", "side": "BUY", "quantity": 1.0} + error = InvalidOrderError(order_details) + assert error.order_details == order_details + +def test_order_not_found_error_creation(): + """Test that OrderNotFoundError can be instantiated with required attributes""" + error = OrderNotFoundError("123456") + assert error.order_id == "123456" + +def test_order_not_found_error_message(): + """Test that OrderNotFoundError has a proper error message""" + error = OrderNotFoundError("123456") + assert "123456" in str(error) +``` + +### test_validation_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + ValidationError, + InvalidDataError, + MissingDataError +) + +def test_validation_error_inheritance(): + """Test that ValidationError inherits from MetaExpertError""" + assert issubclass(ValidationError, MetaExpertError) + +def test_invalid_data_error_creation(): + """Test that InvalidDataError can be instantiated with required attributes""" + data = {"invalid": "data"} + error = InvalidDataError(data, "Malformed JSON") + assert error.data == data + assert error.reason == "Malformed JSON" + +def test_invalid_data_error_message(): + """Test that InvalidDataError has a proper error message""" + data = {"invalid": "data"} + error = InvalidDataError(data, "Malformed JSON") + assert "Malformed JSON" in str(error) + +def test_missing_data_error_creation(): + """Test that MissingDataError can be instantiated with required attributes""" + error = MissingDataError("timestamp") + assert error.field_name == "timestamp" + +def test_missing_data_error_message(): + """Test that MissingDataError has a proper error message""" + error = MissingDataError("timestamp") + assert "timestamp" in str(error) +``` + +### test_market_data_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + MarketDataError, + UnsupportedPairError, + InvalidTimeframeError +) + +def test_market_data_error_inheritance(): + """Test that MarketDataError inherits from MetaExpertError""" + assert issubclass(MarketDataError, MetaExpertError) + +def test_unsupported_pair_error_creation(): + """Test that UnsupportedPairError can be instantiated with required attributes""" + error = UnsupportedPairError("BTCUSD") + assert error.pair == "BTCUSD" + +def test_unsupported_pair_error_message(): + """Test that UnsupportedPairError has a proper error message""" + error = UnsupportedPairError("BTCUSD") + assert "BTCUSD" in str(error) + +def test_invalid_timeframe_error_creation(): + """Test that InvalidTimeframeError can be instantiated with required attributes""" + error = InvalidTimeframeError("5s") + assert error.timeframe == "5s" + +def test_invalid_timeframe_error_message(): + """Test that InvalidTimeframeError has a proper error message""" + error = InvalidTimeframeError("5s") + assert "5s" in str(error) +``` + +### test_process_exceptions.py +```python +import pytest +from metaexpert.exceptions import ( + ProcessError, + InitializationError, + ShutdownError +) + +def test_process_error_inheritance(): + """Test that ProcessError inherits from MetaExpertError""" + assert issubclass(ProcessError, MetaExpertError) + +def test_initialization_error_creation(): + """Test that InitializationError can be instantiated with required attributes""" + error = InitializationError("websocket_client") + assert error.component == "websocket_client" + +def test_initialization_error_message(): + """Test that InitializationError has a proper error message""" + error = InitializationError("websocket_client") + assert "websocket_client" in str(error) + +def test_shutdown_error_creation(): + """Test that ShutdownError can be instantiated with required attributes""" + error = ShutdownError("logger") + assert error.component == "logger" + +def test_shutdown_error_message(): + """Test that ShutdownError has a proper error message""" + error = ShutdownError("logger") + assert "logger" in str(error) +``` \ No newline at end of file diff --git a/.specify/specs/004-exception-handling/contracts/exceptions-contract.md b/.specify/specs/004-exception-handling/contracts/exceptions-contract.md new file mode 100644 index 0000000..225c5e0 --- /dev/null +++ b/.specify/specs/004-exception-handling/contracts/exceptions-contract.md @@ -0,0 +1,239 @@ +# Exception Module API Contract + +## Overview +This document describes the API contract for the MetaExpert exceptions module. The module provides a structured hierarchy of custom exception classes to handle various error conditions specific to the library. + +## Module Interface + +### Import +```python +from metaexpert.exceptions import ( + MetaExpertError, + ConfigurationError, + InvalidConfigurationError, + MissingConfigurationError, + APIError, + AuthenticationError, + RateLimitError, + NetworkError, + TradingError, + InsufficientFundsError, + InvalidOrderError, + OrderNotFoundError, + ValidationError, + InvalidDataError, + MissingDataError, + MarketDataError, + UnsupportedPairError, + InvalidTimeframeError, + ProcessError, + InitializationError, + ShutdownError +) +``` + +## Exception Classes + +### MetaExpertError +Base class for all custom exceptions in the MetaExpert library. + +**Constructor**: +```python +MetaExpertError(message: str, *args) +``` + +**Attributes**: +- message (str): Human-readable error message +- args (tuple): Additional arguments + +### ConfigurationError +Base class for configuration-related errors. + +### InvalidConfigurationError +Raised when configuration values are invalid or missing. + +**Constructor**: +```python +InvalidConfigurationError(config_key: str, config_value: Any, message: str = None) +``` + +**Attributes**: +- config_key (str): The configuration key that is invalid +- config_value (Any): The invalid configuration value +- message (str): Human-readable error message + +### MissingConfigurationError +Raised when required configuration is missing. + +**Constructor**: +```python +MissingConfigurationError(config_key: str, message: str = None) +``` + +**Attributes**: +- config_key (str): The missing configuration key +- message (str): Human-readable error message + +### APIError +Base class for API-related errors. + +### AuthenticationError +Raised when API authentication fails. + +**Constructor**: +```python +AuthenticationError(exchange: str, message: str = None) +``` + +**Attributes**: +- exchange (str): The exchange where authentication failed +- message (str): Human-readable error message + +### RateLimitError +Raised when API rate limits are exceeded. + +**Constructor**: +```python +RateLimitError(exchange: str, retry_after: int = None, message: str = None) +``` + +**Attributes**: +- exchange (str): The exchange that imposed the rate limit +- retry_after (int): Seconds to wait before retrying (if provided by API) +- message (str): Human-readable error message + +### NetworkError +Raised when there are network connectivity issues. + +**Constructor**: +```python +NetworkError(url: str, reason: str = None, message: str = None) +``` + +**Attributes**: +- url (str): The URL that failed to connect +- reason (str): Reason for the network failure +- message (str): Human-readable error message + +### TradingError +Base class for trading-related errors. + +### InsufficientFundsError +Raised when there are insufficient funds for a trade. + +**Constructor**: +```python +InsufficientFundsError(available: float, required: float, currency: str, message: str = None) +``` + +**Attributes**: +- available (float): Available funds +- required (float): Required funds +- currency (str): Currency code +- message (str): Human-readable error message + +### InvalidOrderError +Raised when an order is invalid. + +**Constructor**: +```python +InvalidOrderError(order_details: dict, message: str = None) +``` + +**Attributes**: +- order_details (dict): Details of the invalid order +- message (str): Human-readable error message + +### OrderNotFoundError +Raised when an order cannot be found. + +**Constructor**: +```python +OrderNotFoundError(order_id: str, message: str = None) +``` + +**Attributes**: +- order_id (str): The ID of the missing order +- message (str): Human-readable error message + +### ValidationError +Base class for data validation errors. + +### InvalidDataError +Raised when data is invalid or malformed. + +**Constructor**: +```python +InvalidDataError(data: Any, reason: str = None, message: str = None) +``` + +**Attributes**: +- data (Any): The invalid data +- reason (str): Reason for the validation failure +- message (str): Human-readable error message + +### MissingDataError +Raised when required data is missing. + +**Constructor**: +```python +MissingDataError(field_name: str, message: str = None) +``` + +**Attributes**: +- field_name (str): The name of the missing field +- message (str): Human-readable error message + +### MarketDataError +Base class for market data-related errors. + +### UnsupportedPairError +Raised when a trading pair is not supported. + +**Constructor**: +```python +UnsupportedPairError(pair: str, message: str = None) +``` + +**Attributes**: +- pair (str): The unsupported trading pair +- message (str): Human-readable error message + +### InvalidTimeframeError +Raised when a timeframe is invalid. + +**Constructor**: +```python +InvalidTimeframeError(timeframe: str, message: str = None) +``` + +**Attributes**: +- timeframe (str): The invalid timeframe +- message (str): Human-readable error message + +### ProcessError +Base class for process-related errors. + +### InitializationError +Raised when initialization fails. + +**Constructor**: +```python +InitializationError(component: str, message: str = None) +``` + +**Attributes**: +- component (str): The component that failed to initialize +- message (str): Human-readable error message + +### ShutdownError +Raised when shutdown fails. + +**Constructor**: +```python +ShutdownError(component: str, message: str = None) +``` + +**Attributes**: +- component (str): The component that failed to shut down +- message (str): Human-readable error message \ No newline at end of file diff --git a/.specify/specs/004-exception-handling/data-model.md b/.specify/specs/004-exception-handling/data-model.md new file mode 100644 index 0000000..a4fd41c --- /dev/null +++ b/.specify/specs/004-exception-handling/data-model.md @@ -0,0 +1,145 @@ +# Data Model: Exception Handling Module + +## Overview +This document describes the data model for the exceptions module in the MetaExpert library. The module will provide a structured hierarchy of custom exception classes to handle various error conditions specific to the library. + +## Base Exception Class + +### MetaExpertError +- **Parent Class**: Exception +- **Description**: Base class for all custom exceptions in the MetaExpert library +- **Attributes**: + - message (str): Human-readable error message + - *args: Additional arguments passed to the exception + +## Configuration Exceptions + +### ConfigurationError +- **Parent Class**: MetaExpertError +- **Description**: Base class for configuration-related errors +- **Usage**: Raised when there are issues with library configuration + +### InvalidConfigurationError +- **Parent Class**: ConfigurationError +- **Description**: Raised when configuration values are invalid or missing +- **Attributes**: + - config_key (str): The configuration key that is invalid + - config_value (Any): The invalid configuration value + +### MissingConfigurationError +- **Parent Class**: ConfigurationError +- **Description**: Raised when required configuration is missing +- **Attributes**: + - config_key (str): The missing configuration key + +## API Exceptions + +### APIError +- **Parent Class**: MetaExpertError +- **Description**: Base class for API-related errors +- **Usage**: Raised when there are issues with exchange API interactions + +### AuthenticationError +- **Parent Class**: APIError +- **Description**: Raised when API authentication fails +- **Attributes**: + - exchange (str): The exchange where authentication failed + +### RateLimitError +- **Parent Class**: APIError +- **Description**: Raised when API rate limits are exceeded +- **Attributes**: + - exchange (str): The exchange that imposed the rate limit + - retry_after (int): Seconds to wait before retrying (if provided by API) + +### NetworkError +- **Parent Class**: APIError +- **Description**: Raised when there are network connectivity issues +- **Attributes**: + - url (str): The URL that failed to connect + - reason (str): Reason for the network failure + +## Trading Exceptions + +### TradingError +- **Parent Class**: MetaExpertError +- **Description**: Base class for trading-related errors +- **Usage**: Raised when there are issues with trading operations + +### InsufficientFundsError +- **Parent Class**: TradingError +- **Description**: Raised when there are insufficient funds for a trade +- **Attributes**: + - available (float): Available funds + - required (float): Required funds + - currency (str): Currency code + +### InvalidOrderError +- **Parent Class**: TradingError +- **Description**: Raised when an order is invalid +- **Attributes**: + - order_details (dict): Details of the invalid order + +### OrderNotFoundError +- **Parent Class**: TradingError +- **Description**: Raised when an order cannot be found +- **Attributes**: + - order_id (str): The ID of the missing order + +## Data Validation Exceptions + +### ValidationError +- **Parent Class**: MetaExpertError +- **Description**: Base class for data validation errors +- **Usage**: Raised when data validation fails + +### InvalidDataError +- **Parent Class**: ValidationError +- **Description**: Raised when data is invalid or malformed +- **Attributes**: + - data (Any): The invalid data + - reason (str): Reason for the validation failure + +### MissingDataError +- **Parent Class**: ValidationError +- **Description**: Raised when required data is missing +- **Attributes**: + - field_name (str): The name of the missing field + +## Market Data Exceptions + +### MarketDataError +- **Parent Class**: MetaExpertError +- **Description**: Base class for market data-related errors +- **Usage**: Raised when there are issues with market data + +### UnsupportedPairError +- **Parent Class**: MarketDataError +- **Description**: Raised when a trading pair is not supported +- **Attributes**: + - pair (str): The unsupported trading pair + +### InvalidTimeframeError +- **Parent Class**: MarketDataError +- **Description**: Raised when a timeframe is invalid +- **Attributes**: + - timeframe (str): The invalid timeframe + +## Process Exceptions + +### ProcessError +- **Parent Class**: MetaExpertError +- **Description**: Base class for process-related errors +- **Usage**: Raised when there are issues with process execution + +### InitializationError +- **Parent Class**: ProcessError +- **Description**: Raised when initialization fails +- **Attributes**: + - component (str): The component that failed to initialize + +### ShutdownError +- **Parent Class**: ProcessError +- **Description**: Raised when shutdown fails +- **Attributes**: + - component (str): The component that failed to shut down \ No newline at end of file diff --git a/.specify/specs/004-exception-handling/plan.md b/.specify/specs/004-exception-handling/plan.md new file mode 100644 index 0000000..8af7d7d --- /dev/null +++ b/.specify/specs/004-exception-handling/plan.md @@ -0,0 +1,232 @@ + +# Implementation Plan: Exception Handling Module + +**Branch**: `001-analysis-and-enhancement` | **Date**: 2025-09-22 | **Spec**: [D:\\Projects\\src\\github.com\\teratron\\metaexpert\\specs\\001-analysis-and-enhancement\\spec.md](file:///D:/Projects/src/github.com/teratron/metaexpert/specs/001-analysis-and-enhancement/spec.md) +**Input**: Feature specification from `/specs/001-analysis-and-enhancement/spec.md` + +## Execution Flow (/plan command scope) +``` +1. Load feature spec from Input path + → If not found: ERROR "No feature spec at {path}" +2. Fill Technical Context (scan for NEEDS CLARIFICATION) + → Detect Project Type from context (web=frontend+backend, mobile=app+api) + → Set Structure Decision based on project type +3. Fill the Constitution Check section based on the content of the constitution document. +4. Evaluate Constitution Check section below + → If violations exist: Document in Complexity Tracking + → If no justification possible: ERROR "Simplify approach first" + → Update Progress Tracking: Initial Constitution Check +5. Execute Phase 0 → research.md + → If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns" +6. Execute Phase 1 → contracts, data-model.md, quickstart.md, agent-specific template file (e.g., `CLAUDE.md` for Claude Code, `.github/copilot-instructions.md` for GitHub Copilot, `GEMINI.md` for Gemini CLI, `QWEN.md` for Qwen Code or `AGENTS.md` for opencode). +7. Re-evaluate Constitution Check section + → If new violations: Refactor design, return to Phase 1 + → Update Progress Tracking: Post-Design Constitution Check +8. Plan Phase 2 → Describe task generation approach (DO NOT create tasks.md) +9. STOP - Ready for /tasks command +``` + +**IMPORTANT**: The /plan command STOPS at step 7. Phases 2-4 are executed by other commands: +- Phase 2: /tasks command creates tasks.md +- Phase 3-4: Implementation execution (manual or via tools) + +## Summary +The primary requirement is to add a dedicated exceptions module to handle custom errors specific to the library. This module should be logically structured and integrate with existing components. The technical approach will involve creating a new Python module with custom exception classes that inherit from a base exception class, ensuring proper integration with existing code, and providing comprehensive documentation and tests. + +## Technical Context +**Language/Version**: Python 3.12 +**Primary Dependencies**: Standard Python library +**Storage**: N/A +**Testing**: pytest +**Target Platform**: Cross-platform +**Project Type**: single +**Performance Goals**: N/A +**Constraints**: Must integrate with existing components without breaking changes +**Scale/Scope**: Library-level feature + +Exception Module Requirements: +- Create dedicated exceptions module for the library +- Handle custom errors specific to the library +- Logically structured with clear hierarchy +- Integrates with existing components +- Follow Library-First Development principle +- Well-documented with clear error messages + +## Constitution Check +*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* + +1. **Library-First Development**: ✅ This feature follows the Library-First Development principle as it creates a standalone library module for exception handling that is self-contained and independently testable. + +2. **CLI Interface Standard**: N/A - This is a library feature that doesn't directly expose functionality via CLI. + +3. **Test-First Development**: ✅ Will follow Test-First Development by creating tests for the exception classes before implementation. + +4. **Integration Testing Coverage**: ✅ Will include integration testing to ensure the exceptions module integrates properly with existing components. + +5. **Observability & Versioning**: ✅ Will follow structured logging principles where applicable and maintain versioning consistency. + +6. **Additional Constraints**: ✅ Will use Python 3.12 as required and manage dependencies through pyproject.toml. Will follow MIT licensing standards. + +No violations identified at this stage. + +## Project Structure + +### Documentation (this feature) +``` +specs/[###-feature]/ +├── plan.md # This file (/plan command output) +├── research.md # Phase 0 output (/plan command) +├── data-model.md # Phase 1 output (/plan command) +├── quickstart.md # Phase 1 output (/plan command) +├── contracts/ # Phase 1 output (/plan command) +└── tasks.md # Phase 2 output (/tasks command - NOT created by /plan) +``` + +### Source Code (repository root) +``` +# Option 1: Single project (DEFAULT) +src/ +├── models/ +├── services/ +├── cli/ +└── lib/ + +tests/ +├── contract/ +├── integration/ +└── unit/ + +# Option 2: Web application (when "frontend" + "backend" detected) +backend/ +├── src/ +│ ├── models/ +│ ├── services/ +│ └── api/ +└── tests/ + +frontend/ +├── src/ +│ ├── components/ +│ ├── pages/ +│ └── services/ +└── tests/ + +# Option 3: Mobile + API (when "iOS/Android" detected) +api/ +└── [same as backend above] + +ios/ or android/ +└── [platform-specific structure] +``` + +**Structure Decision**: DEFAULT to Option 1 as this is a single project feature that adds a new module to the existing library structure. + +## Phase 0: Outline & Research +1. **Extract unknowns from Technical Context** above: + - For each NEEDS CLARIFICATION → research task + - For each dependency → best practices task + - For each integration → patterns task + +2. **Generate and dispatch research agents**: + ``` + For each unknown in Technical Context: + Task: "Research {unknown} for {feature context}" + For each technology choice: + Task: "Find best practices for {tech} in {domain}" + ``` + +3. **Consolidate findings** in `research.md` using format: + - Decision: [what was chosen] + - Rationale: [why chosen] + - Alternatives considered: [what else evaluated] + +**Output**: research.md with all NEEDS CLARIFICATION resolved + +## Phase 1: Design & Contracts +*Prerequisites: research.md complete* + +1. **Extract entities from feature spec** → `data-model.md`: + - Entity name, fields, relationships + - Validation rules from requirements + - State transitions if applicable + +2. **Generate API contracts** from functional requirements: + - For each user action → endpoint + - Use standard REST/GraphQL patterns + - Output OpenAPI/GraphQL schema to `/contracts/` + +3. **Generate contract tests** from contracts: + - One test file per endpoint + - Assert request/response schemas + - Tests must fail (no implementation yet) + +4. **Extract test scenarios** from user stories: + - Each story → integration test scenario + - Quickstart test = story validation steps + +5. **Update agent file incrementally** (O(1) operation): + - Run `.specify/scripts/powershell/update-agent-context.ps1 -AgentType qwen` + **IMPORTANT**: Execute it exactly as specified above. Do not add or remove any arguments. + - If exists: Add only NEW tech from current plan + - Preserve manual additions between markers + - Update recent changes (keep last 3) + - Keep under 150 lines for token efficiency + - Output to repository root + +**Output**: data-model.md, /contracts/*, failing tests, quickstart.md, agent-specific file + +## Phase 2: Task Planning Approach +*This section describes what the /tasks command will do - DO NOT execute during /plan* + +**Task Generation Strategy**: +- Load `.specify/templates/tasks-template.md` as base +- Generate tasks from Phase 1 design docs (contracts, data model, quickstart) +- Create contract test tasks for each exception class [P] +- Create implementation tasks for each exception class [P] +- Create integration test tasks to verify exception handling in existing components +- Create documentation tasks to update relevant documentation files + +**Ordering Strategy**: +- TDD order: Tests before implementation +- Dependency order: Base exception class before derived classes +- Mark [P] for parallel execution (independent files) + +**Estimated Output**: 25-30 numbered, ordered tasks in tasks.md + +**IMPORTANT**: This phase is executed by the /tasks command, NOT by /plan + +## Phase 3+: Future Implementation +*These phases are beyond the scope of the /plan command* + +**Phase 3**: Task execution (/tasks command creates tasks.md) +**Phase 4**: Implementation (execute tasks.md following constitutional principles) +**Phase 5**: Validation (run tests, execute quickstart.md, performance validation) + +## Complexity Tracking +*Fill ONLY if Constitution Check has violations that must be justified* + +| Violation | Why Needed | Simpler Alternative Rejected Because | +|-----------|------------|-------------------------------------| +| [e.g., 4th project] | [current need] | [why 3 projects insufficient] | +| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] | + + +## Progress Tracking +*This checklist is updated during execution flow* + +**Phase Status**: +- [x] Phase 0: Research complete (/plan command) +- [x] Phase 1: Design complete (/plan command) +- [x] Phase 2: Task planning complete (/plan command - describe approach only) +- [ ] Phase 3: Tasks generated (/tasks command) +- [ ] Phase 4: Implementation complete +- [ ] Phase 5: Validation passed + +**Gate Status**: +- [x] Initial Constitution Check: PASS +- [x] Post-Design Constitution Check: PASS +- [x] All NEEDS CLARIFICATION resolved +- [x] Complexity deviations documented (No deviations required) + +--- +*Based on Constitution v2.1.1 - See `/memory/constitution.md`* diff --git a/.specify/specs/004-exception-handling/quickstart.md b/.specify/specs/004-exception-handling/quickstart.md new file mode 100644 index 0000000..a05c30a --- /dev/null +++ b/.specify/specs/004-exception-handling/quickstart.md @@ -0,0 +1,136 @@ +# Quickstart: Exception Handling Module + +## Overview +This quickstart guide demonstrates how to use the MetaExpert exceptions module to handle errors in your trading applications. + +## Installation +The exceptions module is part of the MetaExpert library. No additional installation is required. + +## Basic Usage + +### Importing Exceptions +```python +from metaexpert.exceptions import ( + MetaExpertError, + ConfigurationError, + APIError, + TradingError, + ValidationError +) +``` + +### Handling Configuration Errors +```python +from metaexpert.exceptions import InvalidConfigurationError, MissingConfigurationError + +try: + # Some code that might raise configuration errors + pass +except InvalidConfigurationError as e: + print(f"Invalid configuration: {e.config_key} = {e.config_value}") +except MissingConfigurationError as e: + print(f"Missing configuration: {e.config_key}") +``` + +### Handling API Errors +```python +from metaexpert.exceptions import AuthenticationError, RateLimitError, NetworkError + +try: + # Some code that interacts with an exchange API + pass +except AuthenticationError as e: + print(f"Authentication failed for {e.exchange}") +except RateLimitError as e: + print(f"Rate limit exceeded for {e.exchange}") + if e.retry_after: + print(f"Retry after {e.retry_after} seconds") +except NetworkError as e: + print(f"Network error connecting to {e.url}: {e.reason}") +``` + +### Handling Trading Errors +```python +from metaexpert.exceptions import InsufficientFundsError, InvalidOrderError + +try: + # Some code that places trades + pass +except InsufficientFundsError as e: + print(f"Insufficient funds: need {e.required} {e.currency}, have {e.available}") +except InvalidOrderError as e: + print(f"Invalid order: {e.order_details}") +``` + +### Custom Exception Handling +```python +from metaexpert.exceptions import MetaExpertError + +try: + # Some code that might raise MetaExpert exceptions + pass +except MetaExpertError as e: + # This will catch all MetaExpert-specific exceptions + print(f"MetaExpert error: {e}") +``` + +## Best Practices + +1. **Be Specific**: Catch specific exception types rather than using broad exception handling. +2. **Provide Context**: Include relevant information in exception messages to help with debugging. +3. **Graceful Degradation**: Handle exceptions in a way that allows your application to continue operating when possible. +4. **Logging**: Log exceptions appropriately for debugging and monitoring. + +## Example: Complete Error Handling +```python +import logging +from metaexpert import MetaExpert +from metaexpert.exceptions import ( + AuthenticationError, + InsufficientFundsError, + NetworkError, + InvalidConfigurationError +) + +logger = logging.getLogger(__name__) + +def run_trading_bot(): + try: + # Initialize the trading bot + bot = MetaExpert( + exchange="binance", + api_key="your_api_key", + api_secret="your_api_secret" + ) + + # Run the bot + bot.run() + + except AuthenticationError as e: + logger.error(f"Authentication failed: {e}") + # Handle authentication failure (e.g., prompt for new credentials) + + except InsufficientFundsError as e: + logger.warning(f"Insufficient funds: {e}") + # Handle insufficient funds (e.g., reduce position size) + + except NetworkError as e: + logger.error(f"Network error: {e}") + # Handle network issues (e.g., retry with exponential backoff) + + except InvalidConfigurationError as e: + logger.error(f"Configuration error: {e}") + # Handle configuration issues (e.g., prompt for correct values) + + except Exception as e: + logger.error(f"Unexpected error: {e}") + # Handle any other unexpected errors + +if __name__ == "__main__": + run_trading_bot() +``` + +## Next Steps +1. Review the full API documentation in the contracts directory +2. Explore the data model in data-model.md +3. Check out the unit tests for examples of how to test exception handling \ No newline at end of file diff --git a/.specify/specs/004-exception-handling/research.md b/.specify/specs/004-exception-handling/research.md new file mode 100644 index 0000000..a29b7e3 --- /dev/null +++ b/.specify/specs/004-exception-handling/research.md @@ -0,0 +1,46 @@ +# Research: Exception Handling Module + +## Overview +This document outlines the research findings for implementing a dedicated exceptions module in the MetaExpert library. The goal is to create a well-structured, logically organized module for handling custom errors specific to the library. + +## Decision +Create a new `exceptions.py` module in the `src/metaexpert` directory that follows Python best practices for exception handling. The module will include: +1. A base exception class that inherits from Python's built-in Exception class +2. Specific exception classes for different error conditions in the library +3. Proper integration with existing components + +## Rationale +1. **Current State**: The library currently handles errors using generic Python exceptions and logging, but lacks a structured approach to custom exceptions. +2. **Best Practices**: Python libraries typically provide custom exception hierarchies to allow users to handle specific error conditions appropriately. +3. **Integration**: The new module will integrate seamlessly with existing components without breaking changes. +4. **Maintainability**: A centralized exceptions module will make it easier to manage and extend error handling in the future. + +## Alternatives Considered +1. **Keep using generic exceptions**: Continue using generic Python exceptions like ValueError, RuntimeError, etc. + - Rejected because it doesn't provide the specificity needed for library users to handle different error conditions appropriately. + +2. **Distribute exceptions across modules**: Place exception classes in the modules where they are used. + - Rejected because it would make error handling inconsistent and harder to manage. + +3. **Create multiple exception modules**: Create separate modules for different categories of exceptions. + - Rejected because the library is not large enough to warrant multiple exception modules at this time. + +## Research Findings +1. **Python Exception Hierarchy**: Python's built-in exceptions form a hierarchy with `BaseException` at the top and `Exception` as the base class for all built-in, non-system-exiting exceptions. +2. **Library Design Patterns**: Well-designed Python libraries typically have a single exceptions module that contains all custom exception classes. +3. **Integration Patterns**: Custom exceptions should integrate with existing error handling without requiring changes to existing code. + +## Implementation Approach +1. **Base Exception Class**: Create a `MetaExpertError` class that inherits from `Exception` as the base for all custom exceptions. +2. **Specific Exception Classes**: Create specific exception classes for different error categories: + - Configuration errors + - API errors + - Trading errors + - Data validation errors +3. **Documentation**: Provide clear docstrings for each exception class explaining when it should be raised and how to handle it. +4. **Testing**: Create unit tests for each exception class to ensure proper behavior. + +## Technical Considerations +1. **Backward Compatibility**: The new exceptions module should not break existing functionality. +2. **Import Structure**: The module should be easily importable from the main package. +3. **Error Messages**: Exception messages should be clear and helpful to library users. \ No newline at end of file diff --git a/.specify/specs/004-exception-handling/spec.md b/.specify/specs/004-exception-handling/spec.md new file mode 100644 index 0000000..edda14c --- /dev/null +++ b/.specify/specs/004-exception-handling/spec.md @@ -0,0 +1,34 @@ +# Feature Specification: Exception Handling Module + +## Overview +Add a dedicated exceptions module to the project to handle custom errors specific to the library. The module should be logically structured and integrate with existing components. + +## Requirements +1. Create a dedicated exceptions module for the library +2. The module should handle custom errors specific to the library +3. The module should be logically structured +4. The module should integrate with existing components +5. Follow the Library-First Development principle from the constitution +6. Ensure all exceptions are properly documented +7. Provide clear error messages for developers using the library + +## User Stories +1. As a developer, I want to use specific exception types so that I can handle different error conditions appropriately +2. As a library user, I want clear error messages so that I can quickly understand what went wrong +3. As a maintainer, I want a centralized place for all custom exceptions so that I can easily manage them + +## Technical Requirements +1. The exceptions module should be in the src/metaexpert directory +2. The module should follow Python best practices for exception handling +3. The module should integrate with existing components without breaking changes +4. All exceptions should inherit from a base exception class +5. The module should be well-documented with docstrings +6. The module should include unit tests + +## Acceptance Criteria +1. A new exceptions module exists in the project +2. The module contains logically organized custom exception classes +3. The module integrates with existing components +4. Unit tests pass for all new exception classes +5. Existing functionality is not broken by the new module +6. Documentation is updated to reflect the new module \ No newline at end of file diff --git a/.specify/specs/005-implement-the-on/spec.md b/.specify/specs/005-implement-the-on/spec.md new file mode 100644 index 0000000..9ff6209 --- /dev/null +++ b/.specify/specs/005-implement-the-on/spec.md @@ -0,0 +1,121 @@ +# Feature Specification: Implement on_init Handler for Expert Loading + +**Feature Branch**: `005-implement-the-on` +**Created**: 2025-09-22 +**Status**: Draft +**Input**: User description: "Implement the on_init handler in src/metaexpert/_expert.py and src/metaexpert/service.py to process the on_init event triggered upon expert loading. The handler should support void or int return types, with no parameters (def on_init() -> None | int). Non-zero return values indicate failed initialization, triggering a on_deinit event with reason REASON_INITFAILED. Use an ENUM_INIT_RETCODE-style enumeration (INIT_SUCCEEDED, INIT_FAILED, INIT_PARAMETERS_INCORRECT, INIT_AGENT_NOT_SUITABLE) to manage initialization outcomes, optimize testing agent selection (e.g., via system resource checks), and ensure compatibility with template.py. Update documentation in @/docs/ with English docstrings." + +## Execution Flow (main) +``` +1. Parse user description from Input + → If empty: ERROR "No feature description provided" +2. Extract key concepts from description + → Identify: actors, actions, data, constraints +3. For each unclear aspect: + → Mark with [NEEDS CLARIFICATION: specific question] +4. Fill User Scenarios & Testing section + → If no clear user flow: ERROR "Cannot determine user scenarios" +5. Generate Functional Requirements + → Each requirement must be testable + → Mark ambiguous requirements +6. Identify Key Entities (if data involved) +7. Run Review Checklist + → If any [NEEDS CLARIFICATION]: WARN "Spec has uncertainties" + → If implementation details found: ERROR "Remove tech details" +8. Return: SUCCESS (spec ready for planning) +``` + +--- + +## ⚡ Quick Guidelines +- ✅ Focus on WHAT users need and WHY +- ❌ Avoid HOW to implement (no tech stack, APIs, code structure) +- 👥 Written for business stakeholders, not developers + +### Section Requirements +- **Mandatory sections**: Must be completed for every feature +- **Optional sections**: Include only when relevant to the feature +- When a section doesn't apply, remove it entirely (don't leave as "N/A") + +### For AI Generation +When creating this spec from a user prompt: +1. **Mark all ambiguities**: Use [NEEDS CLARIFICATION: specific question] for any assumption you'd need to make +2. **Don't guess**: If the prompt doesn't specify something (e.g., "login system" without auth method), mark it +3. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item +4. **Common underspecified areas**: + - User types and permissions + - Data retention/deletion policies + - Performance targets and scale + - Error handling behaviors + - Integration requirements + - Security/compliance needs + +--- + +## User Scenarios & Testing *(mandatory)* + +### Primary User Story +As a developer using the MetaExpert library, I want to implement custom initialization logic in my trading strategy that can indicate success or failure, so that I can properly set up my strategy before trading begins and handle initialization failures gracefully. + +### Acceptance Scenarios +1. **Given** a trading strategy with an on_init handler that returns None, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. +2. **Given** a trading strategy with an on_init handler that returns 0, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. +3. **Given** a trading strategy with an on_init handler that returns a non-zero value, **When** the expert is loaded, **Then** the initialization is considered failed, the on_deinit handler is called with REASON_INITFAILED, and trading does not proceed. +4. **Given** a trading strategy without an on_init handler, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. + +### Edge Cases +- What happens when the on_init handler raises an exception? +- How does the system handle different non-zero return values? +- What happens if the on_init handler takes parameters (which it shouldn't)? +- How does the system handle initialization when system resources are insufficient? + +## Requirements *(mandatory)* + +### Functional Requirements +- **FR-001**: System MUST allow developers to implement an on_init handler in their trading strategies +- **FR-002**: System MUST support on_init handlers with no parameters +- **FR-003**: System MUST support on_init handlers with return types of None or int +- **FR-004**: System MUST treat None or 0 return values as successful initialization +- **FR-005**: System MUST treat non-zero return values as failed initialization +- **FR-006**: System MUST trigger the on_deinit handler with REASON_INITFAILED when initialization fails +- **FR-007**: System MUST provide an ENUM_INIT_RETCODE-style enumeration with values INIT_SUCCEEDED, INIT_FAILED, INIT_PARAMETERS_INCORRECT, INIT_AGENT_NOT_SUITABLE +- **FR-008**: System MUST be compatible with the existing template.py structure +- **FR-009**: System MUST include proper English documentation in the docs directory + +### Key Entities *(include if feature involves data)* +- **on_init Handler**: A function that runs when an expert is loaded, allowing developers to perform initialization tasks +- **Initialization Return Code**: An enumeration value that indicates the success or failure of initialization +- **REASON_INITFAILED**: A constant that indicates initialization failure as the reason for deinitialization + +--- + +## Review & Acceptance Checklist +*GATE: Automated checks run during main() execution* + +### Content Quality +- [x] No implementation details (languages, frameworks, APIs) +- [x] Focused on user value and business needs +- [x] Written for non-technical stakeholders +- [x] All mandatory sections completed + +### Requirement Completeness +- [x] No [NEEDS CLARIFICATION] markers remain +- [x] Requirements are testable and unambiguous +- [x] Success criteria are measurable +- [x] Scope is clearly bounded +- [x] Dependencies and assumptions identified + +--- + +## Execution Status +*Updated by main() during processing* + +- [x] User description parsed +- [x] Key concepts extracted +- [x] Ambiguities marked +- [x] User scenarios defined +- [x] Requirements generated +- [x] Entities identified +- [x] Review checklist passed + +--- \ No newline at end of file diff --git a/HOW_TO_CREATE_PULL_REQUESTS.md b/HOW_TO_CREATE_PULL_REQUESTS.md deleted file mode 100644 index 4244b70..0000000 --- a/HOW_TO_CREATE_PULL_REQUESTS.md +++ /dev/null @@ -1,113 +0,0 @@ -# How to Create Pull Requests - -## Method 1: Using GitHub Web Interface (Recommended) - -### Step 1: Navigate to the Repository -1. Go to https://github.com/teratron/metaexpert -2. Make sure you're logged into your GitHub account - -### Step 2: Create the First Pull Request -1. Click on the "Pull requests" tab -2. Click the "New pull request" button -3. Set the base branch to `001-analysis-and-enhancement` -4. Set the compare branch to `feature/analysis-and-enhancement` -5. You should see a message indicating "Able to merge" -6. Add the following title: - ``` - feat: Merge feature/analysis-and-enhancement into 001-analysis-and-enhancement - ``` -7. Add the following description: - ``` - This PR merges the feature/analysis-and-enhancement branch into the 001-analysis-and-enhancement branch. - - Changes include: - - Enhanced configuration system with complete exchange support - - Improved template structure alignment - - Updated documentation and specifications - - Enhanced CLI argument parsing - - Better logging configuration - - All conflicts have been resolved and branches are synchronized. - ``` -8. Click "Create pull request" -9. Review the changes and click "Merge pull request" -10. Confirm the merge - -### Step 3: Create the Second Pull Request (Optional) -If you want to merge into master: - -1. Click on the "Pull requests" tab -2. Click the "New pull request" button -3. Set the base branch to `master` -4. Set the compare branch to `001-analysis-and-enhancement` -5. Add the following title: - ``` - feat: Merge analysis-and-enhancement improvements into master - ``` -6. Add the following description: - ``` - This PR merges the analysis-and-enhancement improvements into master. - - Changes include: - - Enhanced configuration system with complete exchange support (Binance, Bybit, OKX, Bitget, Kucoin) - - Improved template structure alignment with all configuration parameters - - Updated documentation and specifications - - Enhanced CLI argument parsing with better organization - - Better logging configuration with structured logging support - - All conflicts have been resolved. - ``` -7. Click "Create pull request" -8. Review the changes and click "Merge pull request" -9. Confirm the merge - -## Method 2: Using Git Commands and GitHub API - -If you have the GitHub CLI installed, you can use these commands: - -### First Pull Request -```bash -gh pr create \ - --base 001-analysis-and-enhancement \ - --head feature/analysis-and-enhancement \ - --title "feat: Merge feature/analysis-and-enhancement into 001-analysis-and-enhancement" \ - --body "This PR merges the feature/analysis-and-enhancement branch into the 001-analysis-and-enhancement branch. - -Changes include: -- Enhanced configuration system with complete exchange support -- Improved template structure alignment -- Updated documentation and specifications -- Enhanced CLI argument parsing -- Better logging configuration - -All conflicts have been resolved and branches are synchronized." -``` - -### Second Pull Request -```bash -gh pr create \ - --base master \ - --head 001-analysis-and-enhancement \ - --title "feat: Merge analysis-and-enhancement improvements into master" \ - --body "This PR merges the analysis-and-enhancement improvements into master. - -Changes include: -- Enhanced configuration system with complete exchange support (Binance, Bybit, OKX, Bitget, Kucoin) -- Improved template structure alignment with all configuration parameters -- Updated documentation and specifications -- Enhanced CLI argument parsing with better organization -- Better logging configuration with structured logging support - -All conflicts have been resolved." -``` - -## Verification - -After creating the pull requests, you can verify that the branches are synchronized by running: - -```bash -git diff feature/analysis-and-enhancement..001-analysis-and-enhancement -``` - -This should return no output, indicating that the branches are identical. -``` \ No newline at end of file diff --git a/PULL_REQUEST_INSTRUCTIONS.md b/PULL_REQUEST_INSTRUCTIONS.md deleted file mode 100644 index 4d3a7bb..0000000 --- a/PULL_REQUEST_INSTRUCTIONS.md +++ /dev/null @@ -1,75 +0,0 @@ -# Pull Request Instructions - -## Branch Synchronization Summary - -Both branches `feature/analysis-and-enhancement` and `001-analysis-and-enhancement` have been synchronized with all changes merged. There are no differences between the branches now. - -## Pull Request Creation Instructions - -To create the pull requests as requested, follow these steps on GitHub: - -### PR 1: Merge feature/analysis-and-enhancement into 001-analysis-and-enhancement - -1. Go to the GitHub repository: https://github.com/teratron/metaexpert -2. Click on "Pull requests" tab -3. Click "New pull request" -4. Set the base branch to `001-analysis-and-enhancement` -5. Set the compare branch to `feature/analysis-and-enhancement` -6. Since both branches are now synchronized, this PR will show "Able to merge. These branches can be automatically merged" -7. Add a title: "feat: Merge feature/analysis-and-enhancement into 001-analysis-and-enhancement" -8. Add description: - ``` - This PR merges the feature/analysis-and-enhancement branch into the 001-analysis-and-enhancement branch. - - Changes include: - - Enhanced configuration system with complete exchange support - - Improved template structure alignment - - Updated documentation and specifications - - Enhanced CLI argument parsing - - Better logging configuration - - All conflicts have been resolved and branches are synchronized. - ``` -9. Click "Create pull request" - -### PR 2: Merge 001-analysis-and-enhancement into master (if needed) - -If you also want to merge the 001-analysis-and-enhancement branch into master: - -1. Go to the GitHub repository: https://github.com/teratron/metaexpert -2. Click on "Pull requests" tab -3. Click "New pull request" -4. Set the base branch to `master` -5. Set the compare branch to `001-analysis-and-enhancement` -6. Add a title: "feat: Merge analysis-and-enhancement improvements into master" -7. Add description: - ``` - This PR merges the analysis-and-enhancement improvements into master. - - Changes include: - - Enhanced configuration system with complete exchange support (Binance, Bybit, OKX, Bitget, Kucoin) - - Improved template structure alignment with all configuration parameters - - Updated documentation and specifications - - Enhanced CLI argument parsing with better organization - - Better logging configuration with structured logging support - - All conflicts have been resolved. - ``` -8. Click "Create pull request" - -## Conflict Resolution Summary - -All conflicts between the branches have been resolved: -1. Both branches now contain the same enhanced configuration system -2. Documentation and specification files are synchronized -3. Code changes in src/metaexpert/exchanges/binance/__init__.py are aligned -4. All new files have been added to both branches - -## Verification - -To verify that the branches are synchronized, you can run: -``` -git diff feature/analysis-and-enhancement..001-analysis-and-enhancement -``` - -This should return no output, indicating that the branches are identical. \ No newline at end of file diff --git a/src/metaexpert/_status.py b/src/metaexpert/_status.py index a4243ac..32cf264 100644 --- a/src/metaexpert/_status.py +++ b/src/metaexpert/_status.py @@ -8,3 +8,4 @@ class InitStatus(Enum): INIT_SUCCEEDED = 1 INIT_FAILED = 2 INIT_PARAMETERS_INCORRECT = 3 + INIT_AGENT_NOT_SUITABLE = 4 From 752c60c648297835f9fc6e31a131c174ff5f533c Mon Sep 17 00:00:00 2001 From: Oleg Alexandrov Date: Mon, 22 Sep 2025 10:21:46 +0300 Subject: [PATCH 2/2] refactor: move specs directory from .specify to project root Relocate all specification files from .specify/specs/ to specs/ directory to improve visibility and accessibility of project documentation and specifications. --- .specify/specs/005-implement-the-on/spec.md | 121 ------------------ .../config-research.md | 0 .../contracts/config-management.md | 0 .../contracts/template-create.md | 0 .../data-model.md | 0 .../enhanced-config-design.md | 0 .../execution-report.md | 0 .../001-analysis-and-enhancement/plan.md | 0 .../quickstart.md | 0 .../001-analysis-and-enhancement/research.md | 0 .../001-analysis-and-enhancement/spec.md | 0 .../001-analysis-and-enhancement/tasks.md | 0 .../workspace-cleanup-summary.md | 0 .../contracts/logging-configure.md | 0 .../002-logging-enhancement/data-model.md | 0 .../002-logging-enhancement/manual-testing.md | 0 .../002-logging-enhancement/plan.md | 0 .../002-logging-enhancement/quickstart.md | 0 .../002-logging-enhancement/research.md | 0 .../002-logging-enhancement/spec.md | 0 .../002-logging-enhancement/tasks.md | 0 .../contracts/cli-parse.md | 0 .../003-cli-enhancement/data-model.md | 0 .../003-cli-enhancement/manual-testing.md | 0 .../003-cli-enhancement/plan.md | 0 .../003-cli-enhancement/quickstart.md | 0 .../003-cli-enhancement/research.md | 0 .../003-cli-enhancement/spec.md | 0 .../003-cli-enhancement/tasks.md | 0 .../contracts/contract-tests.md | 0 .../contracts/exceptions-contract.md | 0 .../004-exception-handling/data-model.md | 0 .../004-exception-handling/plan.md | 0 .../004-exception-handling/quickstart.md | 0 .../004-exception-handling/research.md | 0 .../004-exception-handling/spec.md | 0 36 files changed, 121 deletions(-) delete mode 100644 .specify/specs/005-implement-the-on/spec.md rename {.specify/specs => specs}/001-analysis-and-enhancement/config-research.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/contracts/config-management.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/contracts/template-create.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/data-model.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/enhanced-config-design.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/execution-report.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/plan.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/quickstart.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/research.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/spec.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/tasks.md (100%) rename {.specify/specs => specs}/001-analysis-and-enhancement/workspace-cleanup-summary.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/contracts/logging-configure.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/data-model.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/manual-testing.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/plan.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/quickstart.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/research.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/spec.md (100%) rename {.specify/specs => specs}/002-logging-enhancement/tasks.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/contracts/cli-parse.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/data-model.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/manual-testing.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/plan.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/quickstart.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/research.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/spec.md (100%) rename {.specify/specs => specs}/003-cli-enhancement/tasks.md (100%) rename {.specify/specs => specs}/004-exception-handling/contracts/contract-tests.md (100%) rename {.specify/specs => specs}/004-exception-handling/contracts/exceptions-contract.md (100%) rename {.specify/specs => specs}/004-exception-handling/data-model.md (100%) rename {.specify/specs => specs}/004-exception-handling/plan.md (100%) rename {.specify/specs => specs}/004-exception-handling/quickstart.md (100%) rename {.specify/specs => specs}/004-exception-handling/research.md (100%) rename {.specify/specs => specs}/004-exception-handling/spec.md (100%) diff --git a/.specify/specs/005-implement-the-on/spec.md b/.specify/specs/005-implement-the-on/spec.md deleted file mode 100644 index 9ff6209..0000000 --- a/.specify/specs/005-implement-the-on/spec.md +++ /dev/null @@ -1,121 +0,0 @@ -# Feature Specification: Implement on_init Handler for Expert Loading - -**Feature Branch**: `005-implement-the-on` -**Created**: 2025-09-22 -**Status**: Draft -**Input**: User description: "Implement the on_init handler in src/metaexpert/_expert.py and src/metaexpert/service.py to process the on_init event triggered upon expert loading. The handler should support void or int return types, with no parameters (def on_init() -> None | int). Non-zero return values indicate failed initialization, triggering a on_deinit event with reason REASON_INITFAILED. Use an ENUM_INIT_RETCODE-style enumeration (INIT_SUCCEEDED, INIT_FAILED, INIT_PARAMETERS_INCORRECT, INIT_AGENT_NOT_SUITABLE) to manage initialization outcomes, optimize testing agent selection (e.g., via system resource checks), and ensure compatibility with template.py. Update documentation in @/docs/ with English docstrings." - -## Execution Flow (main) -``` -1. Parse user description from Input - → If empty: ERROR "No feature description provided" -2. Extract key concepts from description - → Identify: actors, actions, data, constraints -3. For each unclear aspect: - → Mark with [NEEDS CLARIFICATION: specific question] -4. Fill User Scenarios & Testing section - → If no clear user flow: ERROR "Cannot determine user scenarios" -5. Generate Functional Requirements - → Each requirement must be testable - → Mark ambiguous requirements -6. Identify Key Entities (if data involved) -7. Run Review Checklist - → If any [NEEDS CLARIFICATION]: WARN "Spec has uncertainties" - → If implementation details found: ERROR "Remove tech details" -8. Return: SUCCESS (spec ready for planning) -``` - ---- - -## ⚡ Quick Guidelines -- ✅ Focus on WHAT users need and WHY -- ❌ Avoid HOW to implement (no tech stack, APIs, code structure) -- 👥 Written for business stakeholders, not developers - -### Section Requirements -- **Mandatory sections**: Must be completed for every feature -- **Optional sections**: Include only when relevant to the feature -- When a section doesn't apply, remove it entirely (don't leave as "N/A") - -### For AI Generation -When creating this spec from a user prompt: -1. **Mark all ambiguities**: Use [NEEDS CLARIFICATION: specific question] for any assumption you'd need to make -2. **Don't guess**: If the prompt doesn't specify something (e.g., "login system" without auth method), mark it -3. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item -4. **Common underspecified areas**: - - User types and permissions - - Data retention/deletion policies - - Performance targets and scale - - Error handling behaviors - - Integration requirements - - Security/compliance needs - ---- - -## User Scenarios & Testing *(mandatory)* - -### Primary User Story -As a developer using the MetaExpert library, I want to implement custom initialization logic in my trading strategy that can indicate success or failure, so that I can properly set up my strategy before trading begins and handle initialization failures gracefully. - -### Acceptance Scenarios -1. **Given** a trading strategy with an on_init handler that returns None, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. -2. **Given** a trading strategy with an on_init handler that returns 0, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. -3. **Given** a trading strategy with an on_init handler that returns a non-zero value, **When** the expert is loaded, **Then** the initialization is considered failed, the on_deinit handler is called with REASON_INITFAILED, and trading does not proceed. -4. **Given** a trading strategy without an on_init handler, **When** the expert is loaded, **Then** the initialization is considered successful and trading proceeds normally. - -### Edge Cases -- What happens when the on_init handler raises an exception? -- How does the system handle different non-zero return values? -- What happens if the on_init handler takes parameters (which it shouldn't)? -- How does the system handle initialization when system resources are insufficient? - -## Requirements *(mandatory)* - -### Functional Requirements -- **FR-001**: System MUST allow developers to implement an on_init handler in their trading strategies -- **FR-002**: System MUST support on_init handlers with no parameters -- **FR-003**: System MUST support on_init handlers with return types of None or int -- **FR-004**: System MUST treat None or 0 return values as successful initialization -- **FR-005**: System MUST treat non-zero return values as failed initialization -- **FR-006**: System MUST trigger the on_deinit handler with REASON_INITFAILED when initialization fails -- **FR-007**: System MUST provide an ENUM_INIT_RETCODE-style enumeration with values INIT_SUCCEEDED, INIT_FAILED, INIT_PARAMETERS_INCORRECT, INIT_AGENT_NOT_SUITABLE -- **FR-008**: System MUST be compatible with the existing template.py structure -- **FR-009**: System MUST include proper English documentation in the docs directory - -### Key Entities *(include if feature involves data)* -- **on_init Handler**: A function that runs when an expert is loaded, allowing developers to perform initialization tasks -- **Initialization Return Code**: An enumeration value that indicates the success or failure of initialization -- **REASON_INITFAILED**: A constant that indicates initialization failure as the reason for deinitialization - ---- - -## Review & Acceptance Checklist -*GATE: Automated checks run during main() execution* - -### Content Quality -- [x] No implementation details (languages, frameworks, APIs) -- [x] Focused on user value and business needs -- [x] Written for non-technical stakeholders -- [x] All mandatory sections completed - -### Requirement Completeness -- [x] No [NEEDS CLARIFICATION] markers remain -- [x] Requirements are testable and unambiguous -- [x] Success criteria are measurable -- [x] Scope is clearly bounded -- [x] Dependencies and assumptions identified - ---- - -## Execution Status -*Updated by main() during processing* - -- [x] User description parsed -- [x] Key concepts extracted -- [x] Ambiguities marked -- [x] User scenarios defined -- [x] Requirements generated -- [x] Entities identified -- [x] Review checklist passed - ---- \ No newline at end of file diff --git a/.specify/specs/001-analysis-and-enhancement/config-research.md b/specs/001-analysis-and-enhancement/config-research.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/config-research.md rename to specs/001-analysis-and-enhancement/config-research.md diff --git a/.specify/specs/001-analysis-and-enhancement/contracts/config-management.md b/specs/001-analysis-and-enhancement/contracts/config-management.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/contracts/config-management.md rename to specs/001-analysis-and-enhancement/contracts/config-management.md diff --git a/.specify/specs/001-analysis-and-enhancement/contracts/template-create.md b/specs/001-analysis-and-enhancement/contracts/template-create.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/contracts/template-create.md rename to specs/001-analysis-and-enhancement/contracts/template-create.md diff --git a/.specify/specs/001-analysis-and-enhancement/data-model.md b/specs/001-analysis-and-enhancement/data-model.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/data-model.md rename to specs/001-analysis-and-enhancement/data-model.md diff --git a/.specify/specs/001-analysis-and-enhancement/enhanced-config-design.md b/specs/001-analysis-and-enhancement/enhanced-config-design.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/enhanced-config-design.md rename to specs/001-analysis-and-enhancement/enhanced-config-design.md diff --git a/.specify/specs/001-analysis-and-enhancement/execution-report.md b/specs/001-analysis-and-enhancement/execution-report.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/execution-report.md rename to specs/001-analysis-and-enhancement/execution-report.md diff --git a/.specify/specs/001-analysis-and-enhancement/plan.md b/specs/001-analysis-and-enhancement/plan.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/plan.md rename to specs/001-analysis-and-enhancement/plan.md diff --git a/.specify/specs/001-analysis-and-enhancement/quickstart.md b/specs/001-analysis-and-enhancement/quickstart.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/quickstart.md rename to specs/001-analysis-and-enhancement/quickstart.md diff --git a/.specify/specs/001-analysis-and-enhancement/research.md b/specs/001-analysis-and-enhancement/research.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/research.md rename to specs/001-analysis-and-enhancement/research.md diff --git a/.specify/specs/001-analysis-and-enhancement/spec.md b/specs/001-analysis-and-enhancement/spec.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/spec.md rename to specs/001-analysis-and-enhancement/spec.md diff --git a/.specify/specs/001-analysis-and-enhancement/tasks.md b/specs/001-analysis-and-enhancement/tasks.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/tasks.md rename to specs/001-analysis-and-enhancement/tasks.md diff --git a/.specify/specs/001-analysis-and-enhancement/workspace-cleanup-summary.md b/specs/001-analysis-and-enhancement/workspace-cleanup-summary.md similarity index 100% rename from .specify/specs/001-analysis-and-enhancement/workspace-cleanup-summary.md rename to specs/001-analysis-and-enhancement/workspace-cleanup-summary.md diff --git a/.specify/specs/002-logging-enhancement/contracts/logging-configure.md b/specs/002-logging-enhancement/contracts/logging-configure.md similarity index 100% rename from .specify/specs/002-logging-enhancement/contracts/logging-configure.md rename to specs/002-logging-enhancement/contracts/logging-configure.md diff --git a/.specify/specs/002-logging-enhancement/data-model.md b/specs/002-logging-enhancement/data-model.md similarity index 100% rename from .specify/specs/002-logging-enhancement/data-model.md rename to specs/002-logging-enhancement/data-model.md diff --git a/.specify/specs/002-logging-enhancement/manual-testing.md b/specs/002-logging-enhancement/manual-testing.md similarity index 100% rename from .specify/specs/002-logging-enhancement/manual-testing.md rename to specs/002-logging-enhancement/manual-testing.md diff --git a/.specify/specs/002-logging-enhancement/plan.md b/specs/002-logging-enhancement/plan.md similarity index 100% rename from .specify/specs/002-logging-enhancement/plan.md rename to specs/002-logging-enhancement/plan.md diff --git a/.specify/specs/002-logging-enhancement/quickstart.md b/specs/002-logging-enhancement/quickstart.md similarity index 100% rename from .specify/specs/002-logging-enhancement/quickstart.md rename to specs/002-logging-enhancement/quickstart.md diff --git a/.specify/specs/002-logging-enhancement/research.md b/specs/002-logging-enhancement/research.md similarity index 100% rename from .specify/specs/002-logging-enhancement/research.md rename to specs/002-logging-enhancement/research.md diff --git a/.specify/specs/002-logging-enhancement/spec.md b/specs/002-logging-enhancement/spec.md similarity index 100% rename from .specify/specs/002-logging-enhancement/spec.md rename to specs/002-logging-enhancement/spec.md diff --git a/.specify/specs/002-logging-enhancement/tasks.md b/specs/002-logging-enhancement/tasks.md similarity index 100% rename from .specify/specs/002-logging-enhancement/tasks.md rename to specs/002-logging-enhancement/tasks.md diff --git a/.specify/specs/003-cli-enhancement/contracts/cli-parse.md b/specs/003-cli-enhancement/contracts/cli-parse.md similarity index 100% rename from .specify/specs/003-cli-enhancement/contracts/cli-parse.md rename to specs/003-cli-enhancement/contracts/cli-parse.md diff --git a/.specify/specs/003-cli-enhancement/data-model.md b/specs/003-cli-enhancement/data-model.md similarity index 100% rename from .specify/specs/003-cli-enhancement/data-model.md rename to specs/003-cli-enhancement/data-model.md diff --git a/.specify/specs/003-cli-enhancement/manual-testing.md b/specs/003-cli-enhancement/manual-testing.md similarity index 100% rename from .specify/specs/003-cli-enhancement/manual-testing.md rename to specs/003-cli-enhancement/manual-testing.md diff --git a/.specify/specs/003-cli-enhancement/plan.md b/specs/003-cli-enhancement/plan.md similarity index 100% rename from .specify/specs/003-cli-enhancement/plan.md rename to specs/003-cli-enhancement/plan.md diff --git a/.specify/specs/003-cli-enhancement/quickstart.md b/specs/003-cli-enhancement/quickstart.md similarity index 100% rename from .specify/specs/003-cli-enhancement/quickstart.md rename to specs/003-cli-enhancement/quickstart.md diff --git a/.specify/specs/003-cli-enhancement/research.md b/specs/003-cli-enhancement/research.md similarity index 100% rename from .specify/specs/003-cli-enhancement/research.md rename to specs/003-cli-enhancement/research.md diff --git a/.specify/specs/003-cli-enhancement/spec.md b/specs/003-cli-enhancement/spec.md similarity index 100% rename from .specify/specs/003-cli-enhancement/spec.md rename to specs/003-cli-enhancement/spec.md diff --git a/.specify/specs/003-cli-enhancement/tasks.md b/specs/003-cli-enhancement/tasks.md similarity index 100% rename from .specify/specs/003-cli-enhancement/tasks.md rename to specs/003-cli-enhancement/tasks.md diff --git a/.specify/specs/004-exception-handling/contracts/contract-tests.md b/specs/004-exception-handling/contracts/contract-tests.md similarity index 100% rename from .specify/specs/004-exception-handling/contracts/contract-tests.md rename to specs/004-exception-handling/contracts/contract-tests.md diff --git a/.specify/specs/004-exception-handling/contracts/exceptions-contract.md b/specs/004-exception-handling/contracts/exceptions-contract.md similarity index 100% rename from .specify/specs/004-exception-handling/contracts/exceptions-contract.md rename to specs/004-exception-handling/contracts/exceptions-contract.md diff --git a/.specify/specs/004-exception-handling/data-model.md b/specs/004-exception-handling/data-model.md similarity index 100% rename from .specify/specs/004-exception-handling/data-model.md rename to specs/004-exception-handling/data-model.md diff --git a/.specify/specs/004-exception-handling/plan.md b/specs/004-exception-handling/plan.md similarity index 100% rename from .specify/specs/004-exception-handling/plan.md rename to specs/004-exception-handling/plan.md diff --git a/.specify/specs/004-exception-handling/quickstart.md b/specs/004-exception-handling/quickstart.md similarity index 100% rename from .specify/specs/004-exception-handling/quickstart.md rename to specs/004-exception-handling/quickstart.md diff --git a/.specify/specs/004-exception-handling/research.md b/specs/004-exception-handling/research.md similarity index 100% rename from .specify/specs/004-exception-handling/research.md rename to specs/004-exception-handling/research.md diff --git a/.specify/specs/004-exception-handling/spec.md b/specs/004-exception-handling/spec.md similarity index 100% rename from .specify/specs/004-exception-handling/spec.md rename to specs/004-exception-handling/spec.md