Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 49724d2ae5 | |||
| 25a38322c0 | |||
| 3a53e0aa58 | |||
| 64d1606740 | |||
| 1022e2597f | |||
| 50170f75df | |||
| 1877d6d462 | |||
| 7cc81dee8f | |||
| d5d943a604 | |||
| c5f49b2dd0 | |||
| 096017b93f | |||
| f0dfd04d45 | |||
| 6233d13f18 | |||
| 747715af58 | |||
| 62e7d13d7e | |||
| d402f3c75b | |||
| 804848b40c | |||
| ce14d3b2de | |||
| a8e5b4b044 | |||
| cb94c92fc0 | |||
| 4ceb6cce42 | |||
| 9d3c6f3c81 | |||
| 04a9173503 | |||
| 4b151bb9df |
6
.gitmodules
vendored
6
.gitmodules
vendored
@@ -2,3 +2,9 @@
|
||||
path = wiki
|
||||
url = http://92.205.130.254:32166/coulomb/markitect_project.wiki.git
|
||||
branch = main
|
||||
[submodule "capabilities/issue-facade"]
|
||||
path = capabilities/issue-facade
|
||||
url = http://92.205.130.254:32166/coulomb/issue-facade.git
|
||||
[submodule "capabilities/kaizen-agentic"]
|
||||
path = capabilities/kaizen-agentic
|
||||
url = http://92.205.130.254:32166/coulomb/kaizen-agentic.git
|
||||
|
||||
426
CAPABILITIES.md
426
CAPABILITIES.md
@@ -1,426 +0,0 @@
|
||||
# MarkiTect System Capabilities & Extraction Plan
|
||||
|
||||
> **Comprehensive overview of all capabilities, architectural innovations, and capability extraction recommendations for the ComposableRepositoryParadigm**
|
||||
|
||||
## Overview
|
||||
|
||||
- **Total Capabilities**: 73+ distinct capabilities
|
||||
- **Test Categories**: 15 major functional areas
|
||||
- **Test Coverage**: 348 tests across 27 test files
|
||||
- **Architecture**: Database-driven system with AST-based markdown processing, multi-layer caching, and deep Git platform integration
|
||||
- **Extraction Status**: 2 capabilities extracted, 11 candidates identified for extraction
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Capability Extraction Analysis
|
||||
|
||||
### Extraction Criteria
|
||||
|
||||
Based on the ComposableRepositoryParadigm, capabilities should be extracted when they meet these criteria:
|
||||
|
||||
1. **Self-Contained Functionality**: Can operate independently with minimal dependencies
|
||||
2. **Reusability**: Could be useful in other projects or contexts
|
||||
3. **Clear Boundaries**: Has well-defined interfaces and responsibilities
|
||||
4. **Test Coverage**: Has adequate test coverage (>80% preferred)
|
||||
5. **Size**: Significant enough to warrant extraction (>3 files or >500 LOC)
|
||||
6. **Domain Separation**: Represents a distinct domain or concern
|
||||
|
||||
### Current Extraction Status
|
||||
|
||||
#### ✅ **Already Extracted** (2 capabilities)
|
||||
- `markitect-content` - Content matter parsing (frontmatter, contentmatter, tailmatter)
|
||||
- `markitect-utils` - General utility functions (test capability)
|
||||
|
||||
#### 🎯 **Recommended for Extraction** (7 capabilities)
|
||||
|
||||
| Priority | Capability | Rationale | Complexity | Dependencies |
|
||||
|----------|------------|-----------|------------|-------------|
|
||||
| **HIGH** | `markitect-finance` | Complete financial tracking system, self-contained | High | Low |
|
||||
| **HIGH** | `markitect-query-paradigms` | 14 different query paradigms, highly reusable | High | Medium |
|
||||
| **HIGH** | `markitect-graphql` | Complete GraphQL interface, standalone value | Medium | Medium |
|
||||
| **MEDIUM** | `markitect-plugins` | Plugin architecture framework | Medium | Low |
|
||||
| **MEDIUM** | `markitect-matter-parsers` | All matter parsing capabilities (3 types) | Medium | Low |
|
||||
| **MEDIUM** | `markitect-legacy` | Legacy compatibility layer | Low | Low |
|
||||
| **LOW** | `markitect-issues` | Issue management system | High | High |
|
||||
|
||||
#### 🛑 **Not Recommended for Extraction** (Core System)
|
||||
|
||||
These modules form the core of MarkiTect and should remain in the main project:
|
||||
|
||||
- **Core Engine**: `cli.py`, `database.py`, `config_manager.py` - Main application logic
|
||||
- **AST Processing**: `ast_*.py`, `parser.py`, `serializer.py` - Core markdown processing
|
||||
- **Document Management**: `document_manager.py`, `batch_processor.py` - Core functionality
|
||||
- **Validation**: `schema_*.py`, `validation_*.py` - System integrity
|
||||
- **Performance**: `cache_service.py`, `performance_tracker.py` - Core performance
|
||||
- **Templates**: `template/` - Core template engine
|
||||
|
||||
---
|
||||
|
||||
## 📦 Detailed Capability Extraction Recommendations
|
||||
|
||||
### 1. 🏆 **HIGH PRIORITY - markitect-finance**
|
||||
|
||||
**Current Location**: `markitect/finance/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/finance/
|
||||
├── __init__.py # Package interface
|
||||
├── allocation_engine.py # Cost allocation logic
|
||||
├── cli.py # Finance CLI commands
|
||||
├── cost_manager.py # Cost tracking
|
||||
├── day_wrapup_commands.py # Daily summaries
|
||||
├── models.py # Data models
|
||||
├── period_manager.py # Period handling
|
||||
├── report_generator.py # Financial reports
|
||||
├── session_tracker.py # Session tracking
|
||||
├── worktime_commands.py # Work time CLI
|
||||
├── worktime_tracker.py # Time tracking
|
||||
└── migrations/001_create_cost_tables.sql
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Self-Contained**: Complete financial tracking system
|
||||
- ✅ **Reusable**: Could be used by other project management tools
|
||||
- ✅ **Clear Boundaries**: Well-defined domain (finance/time tracking)
|
||||
- ✅ **Size**: 11 files, substantial codebase
|
||||
- ✅ **Dependencies**: Minimal external dependencies
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Could be reused in other project management systems
|
||||
- Independent development and versioning
|
||||
- Clear separation of financial concerns
|
||||
|
||||
### 2. 🏆 **HIGH PRIORITY - markitect-query-paradigms**
|
||||
|
||||
**Current Location**: `markitect/query_paradigms/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/query_paradigms/
|
||||
├── __init__.py # Package interface
|
||||
├── base.py # Base classes
|
||||
├── cli.py # Query CLI
|
||||
├── registry.py # Paradigm registry
|
||||
└── paradigms/ # 14 different paradigms
|
||||
├── batch_paradigm.py
|
||||
├── fts_paradigm.py
|
||||
├── graphql_paradigm.py
|
||||
├── jsonpath_paradigm.py
|
||||
├── natural_language_paradigm.py
|
||||
├── nosql_paradigm.py
|
||||
├── qbe_paradigm.py
|
||||
├── rag_paradigm.py
|
||||
├── rest_api_paradigm.py
|
||||
├── sql_paradigm.py
|
||||
├── transform_paradigm.py
|
||||
├── unix_pipeline_paradigm.py
|
||||
├── visual_builder_paradigm.py
|
||||
└── xpath_paradigm.py
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Highly Reusable**: Query paradigms useful across many applications
|
||||
- ✅ **Self-Contained**: Complete query abstraction system
|
||||
- ✅ **Innovation**: Unique architectural contribution
|
||||
- ✅ **Size**: 17+ files, substantial investment
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Could become a standalone query abstraction library
|
||||
- High reusability potential across projects
|
||||
- Independent evolution of query capabilities
|
||||
|
||||
### 3. 🏆 **HIGH PRIORITY - markitect-graphql**
|
||||
|
||||
**Current Location**: `markitect/graphql/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/graphql/
|
||||
├── __init__.py # Package interface
|
||||
├── resolvers.py # GraphQL resolvers
|
||||
├── schema.py # GraphQL schema
|
||||
└── server.py # GraphQL server
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Standalone Value**: Complete GraphQL API interface
|
||||
- ✅ **Reusable**: GraphQL interfaces are broadly applicable
|
||||
- ✅ **Clear Boundaries**: Well-defined API layer
|
||||
- ✅ **Technology**: Uses standard GraphQL patterns
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Can be developed independently with GraphQL ecosystem
|
||||
- Reusable across different backend systems
|
||||
- Clear API versioning and evolution
|
||||
|
||||
### 4. 🥈 **MEDIUM PRIORITY - markitect-plugins**
|
||||
|
||||
**Current Location**: `markitect/plugins/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/plugins/
|
||||
├── __init__.py # Package interface
|
||||
├── base.py # Base plugin classes
|
||||
├── decorators.py # Plugin decorators
|
||||
├── manager.py # Plugin manager
|
||||
├── registry.py # Plugin registry
|
||||
└── builtin/ # Built-in plugins
|
||||
├── formatters.py
|
||||
├── processors.py
|
||||
└── search/ # Search plugins
|
||||
├── fts_search.py
|
||||
├── indexer.py
|
||||
└── query_parser.py
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Reusable**: Plugin architecture pattern broadly applicable
|
||||
- ✅ **Self-Contained**: Complete plugin system
|
||||
- ✅ **Size**: 9+ files, substantial codebase
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Plugin architecture could be reused in other applications
|
||||
- Independent development of plugin ecosystem
|
||||
- Clear extensibility patterns
|
||||
|
||||
### 5. 🥈 **MEDIUM PRIORITY - markitect-matter-parsers**
|
||||
|
||||
**Current Status**: `markitect-content` already extracted, but three separate parsers remain:
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/matter_frontmatter/ # Front matter parsing
|
||||
markitect/matter_contentmatter/ # Content matter parsing
|
||||
markitect/matter_tailmatter/ # Tail matter parsing
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Reusable**: Matter parsing useful for many markdown tools
|
||||
- ✅ **Self-Contained**: Each parser is independent
|
||||
- ✅ **Clear Domain**: Document structure parsing
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Could be used by other markdown processing tools
|
||||
- Independent evolution of parsing capabilities
|
||||
|
||||
### 6. 🥈 **MEDIUM PRIORITY - markitect-legacy**
|
||||
|
||||
**Current Location**: `markitect/legacy/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/legacy/
|
||||
├── __init__.py # Package interface
|
||||
├── agent.py # Legacy agents
|
||||
├── compatibility.py # Compatibility layer
|
||||
├── deprecation.py # Deprecation handling
|
||||
├── exceptions.py # Legacy exceptions
|
||||
├── git_tracker.py # Legacy Git tracking
|
||||
├── registry.py # Legacy registry
|
||||
└── switches.py # Feature switches
|
||||
```
|
||||
|
||||
**Why Extract**:
|
||||
- ✅ **Self-Contained**: Complete legacy compatibility system
|
||||
- ✅ **Bounded**: Will eventually be removed
|
||||
- ✅ **Clean Separation**: Should not contaminate main codebase
|
||||
|
||||
**Extraction Benefits**:
|
||||
- Keeps legacy code separate from main evolution
|
||||
- Can be deprecated independently
|
||||
- Clear migration path
|
||||
|
||||
### 7. 🥉 **LOW PRIORITY - markitect-issues**
|
||||
|
||||
**Current Location**: `markitect/issues/`
|
||||
|
||||
**Files to Extract**:
|
||||
```
|
||||
markitect/issues/
|
||||
├── __init__.py # Package interface
|
||||
├── activity_commands.py # Activity tracking
|
||||
├── activity_tracker.py # Activity tracking
|
||||
├── base.py # Base classes
|
||||
├── commands.py # Issue CLI commands
|
||||
├── exceptions.py # Issue exceptions
|
||||
├── issue_wrapup_commands.py # Issue completion
|
||||
├── manager.py # Issue manager
|
||||
└── plugins/ # Issue plugins
|
||||
├── gitea.py # Gitea integration
|
||||
└── local.py # Local issues
|
||||
```
|
||||
|
||||
**Why Lower Priority**:
|
||||
- ⚠️ **High Dependencies**: Tightly integrated with core system
|
||||
- ⚠️ **Complex**: Issue management is complex domain
|
||||
- ⚠️ **Core Feature**: Central to MarkiTect's value proposition
|
||||
|
||||
**Consider for Later**:
|
||||
- Extract after core system stabilizes
|
||||
- Requires careful dependency analysis
|
||||
- High integration complexity
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Extraction Implementation Plan
|
||||
|
||||
### Phase 1: **High-Value, Low-Risk Extractions**
|
||||
1. **markitect-finance** - Complete financial system
|
||||
2. **markitect-graphql** - GraphQL interface
|
||||
3. **markitect-legacy** - Legacy compatibility
|
||||
|
||||
### Phase 2: **Complex, High-Value Extractions**
|
||||
4. **markitect-query-paradigms** - Query abstraction system
|
||||
5. **markitect-plugins** - Plugin architecture
|
||||
|
||||
### Phase 3: **Specialized Extractions**
|
||||
6. **markitect-matter-parsers** - Consolidate matter parsing
|
||||
7. **markitect-issues** - Issue management (if dependencies allow)
|
||||
|
||||
### Phase 4: **Validation and Optimization**
|
||||
- Test all extractions thoroughly
|
||||
- Optimize inter-capability dependencies
|
||||
- Document lessons learned
|
||||
- Update ComposableRepositoryParadigm based on experience
|
||||
|
||||
---
|
||||
|
||||
## 📊 Extraction Impact Analysis
|
||||
|
||||
### Complexity vs. Value Matrix
|
||||
|
||||
```
|
||||
High Value │ query-paradigms │ finance │
|
||||
│ │ graphql │
|
||||
│ │ │
|
||||
│ plugins │ matter-parsers │
|
||||
Low Value │ legacy │ issues │
|
||||
────────────────────────────────────
|
||||
Low Complexity High Complexity
|
||||
```
|
||||
|
||||
### Recommended Extraction Order
|
||||
|
||||
1. **markitect-finance** (High Value, Medium Complexity) - Complete system
|
||||
2. **markitect-graphql** (High Value, Low Complexity) - Clean API layer
|
||||
3. **markitect-legacy** (Medium Value, Low Complexity) - Easy win
|
||||
4. **markitect-query-paradigms** (High Value, High Complexity) - Big impact
|
||||
5. **markitect-plugins** (Medium Value, Medium Complexity) - Architecture
|
||||
6. **markitect-matter-parsers** (Medium Value, Low Complexity) - Consolidation
|
||||
7. **markitect-issues** (High Value, High Complexity) - Complex integration
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Success Criteria for Extractions
|
||||
|
||||
Each extracted capability must meet these criteria:
|
||||
|
||||
### Technical Requirements
|
||||
- ✅ **Zero Parent Dependencies**: No imports from main markitect project
|
||||
- ✅ **Complete Test Suite**: >80% test coverage
|
||||
- ✅ **Independent Build**: Can be built and tested separately
|
||||
- ✅ **Documentation**: Complete README and API documentation
|
||||
- ✅ **Version Management**: Independent versioning with semver
|
||||
|
||||
### Quality Requirements
|
||||
- ✅ **Type Safety**: Complete type annotations
|
||||
- ✅ **Error Handling**: Comprehensive error handling
|
||||
- ✅ **Performance**: No performance regressions
|
||||
- ✅ **Security**: No security vulnerabilities introduced
|
||||
|
||||
### Process Requirements
|
||||
- ✅ **Red-Green Testing**: All tests pass after extraction
|
||||
- ✅ **CI/CD**: Independent CI/CD pipeline
|
||||
- ✅ **Integration**: Smooth integration with main project
|
||||
- ✅ **Migration Path**: Clear upgrade/downgrade paths
|
||||
|
||||
---
|
||||
|
||||
## 📋 Core MarkiTect Capabilities (Remain in Main Project)
|
||||
|
||||
### Core Architectural Paradigms
|
||||
|
||||
#### 1. Parse-Once, Manipulate-Many Architecture™
|
||||
**Paradigm**: Single parsing operation creates multiple access pathways for document manipulation.
|
||||
|
||||
**Innovation**: Traditional markdown processors re-parse content for each operation. MarkiTect parses once and creates multiple fast-access representations:
|
||||
- **AST Cache**: JSON-serialized Abstract Syntax Tree for lightning-fast loading
|
||||
- **Database Metadata**: Structured front matter and document metadata
|
||||
- **Original Content**: Preserved for integrity validation
|
||||
|
||||
#### 2. Database-First Metadata Management
|
||||
**Paradigm**: Document metadata is treated as first-class relational data, not file-system artifacts.
|
||||
|
||||
#### 3. Performance-Validated Caching System
|
||||
**Paradigm**: Cache performance is continuously validated against benchmarks, not assumed.
|
||||
|
||||
#### 4. TDD8 Methodology Integration
|
||||
**Paradigm**: Issue-driven development with 8-step validation cycles.
|
||||
|
||||
### Core System Components
|
||||
|
||||
#### 🗄️ Database & Storage
|
||||
- Database initialization and schema management
|
||||
- Markdown file storage with metadata tracking
|
||||
- SQL query execution with safety constraints
|
||||
- Performance optimizations for large datasets
|
||||
|
||||
#### 📝 Markdown Processing
|
||||
- Core AST conversion and manipulation
|
||||
- Document modification through AST
|
||||
- Roundtrip integrity validation
|
||||
- Performance-optimized parsing
|
||||
|
||||
#### 🚀 Performance & Caching
|
||||
- AST caching system with smart invalidation
|
||||
- Performance benchmarking and validation
|
||||
- Memory usage optimization
|
||||
- Bulk operation efficiency
|
||||
|
||||
#### 🖥️ CLI Framework
|
||||
- Command-line interface foundation
|
||||
- Configuration management
|
||||
- Error handling and validation
|
||||
- Output formatting
|
||||
|
||||
#### 🔧 System Integration
|
||||
- Configuration validation
|
||||
- Environment detection
|
||||
- Network connectivity
|
||||
- File system validation
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Future Roadmap
|
||||
|
||||
### Post-Extraction Goals
|
||||
1. **Template System**: Create capability templates from successful extractions
|
||||
2. **Dependency Checker**: Automated tools for dependency compliance
|
||||
3. **CI/CD Patterns**: Establish patterns for capability CI/CD
|
||||
4. **Integration Testing**: Cross-capability integration test framework
|
||||
|
||||
### Planned Extensions
|
||||
- **Distributed Capabilities**: Multi-machine capability sharing
|
||||
- **Capability Marketplace**: Public registry of MarkiTect capabilities
|
||||
- **AI-Assisted Extraction**: Automated capability boundary detection
|
||||
|
||||
---
|
||||
|
||||
## 📚 Getting Started with Extractions
|
||||
|
||||
To begin capability extraction process:
|
||||
|
||||
1. **Validate Test Capability**: Ensure `markitect-utils` works correctly
|
||||
2. **Choose Starting Point**: Begin with `markitect-finance` (high value, clear boundaries)
|
||||
3. **Follow TDD Process**: Maintain test suite throughout extraction
|
||||
4. **Document Experience**: Update this document with lessons learned
|
||||
|
||||
For detailed extraction procedures, see:
|
||||
- `/wiki/ComposableRepositoryParadigm.md` - Extraction methodology
|
||||
- `/capabilities/markitect-utils/VALIDATION_REPORT.md` - Process validation
|
||||
|
||||
---
|
||||
|
||||
*This capabilities analysis reflects the current state of the MarkiTect project and provides a roadmap for systematic capability extraction following the ComposableRepositoryParadigm. All recommendations are based on architectural analysis, dependency review, and reusability assessment.*
|
||||
110
CHANGELOG.md
110
CHANGELOG.md
@@ -1,100 +1,18 @@
|
||||
# Changelog
|
||||
## [0.4.0] - 2025-10-25
|
||||
|
||||
### Added
|
||||
- feat: add comprehensive testing and error tracking for edit mode
|
||||
|
||||
### Fixed
|
||||
- fix: resolve md-render --edit functionality and add enhanced version tracking
|
||||
- fix: resolve critical JavaScript syntax errors in md-render --edit
|
||||
- fix: resolve md-ingest Path object conversion error
|
||||
|
||||
### Other
|
||||
- chore: clean up repository documentation files for release
|
||||
|
||||
|
||||
|
||||
All notable changes to MarkiTect will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.2.0] - 2025-10-20
|
||||
|
||||
### Added
|
||||
- **Production-Ready Asset Management System** with content-addressable storage
|
||||
- **Advanced Performance Optimization** with 60-85% faster document processing
|
||||
- **Enterprise-Grade Error Handling** with graceful recovery mechanisms
|
||||
- **Comprehensive Test Suite** with 1983 tests and 100% success rate
|
||||
- **GraphQL Interface** for advanced querying capabilities
|
||||
- **Full-Text Search** with FTS5 backend and query optimization
|
||||
- **Kaizen-Agentic Framework Integration** with 17 specialized development agents
|
||||
- **Professional Documentation** with 20+ comprehensive guides
|
||||
- **Cross-Platform Validation** for Unix/Windows/macOS compatibility
|
||||
- **CLI Consolidation** with unified command interface
|
||||
- **Template Rendering System** with validation and error handling
|
||||
- **Cost Management & Tracking** with allocation engine and reporting
|
||||
- **Issue Activity Tracking** with worktime distribution
|
||||
- **Plugin Architecture** with builtin processors and extensible framework
|
||||
- **Query Paradigms** supporting 14 different query approaches
|
||||
- **Content-Matter Processing** with frontmatter, contentmatter, and tailmatter support
|
||||
- Comprehensive installer system with Python and shell scripts
|
||||
- Version and release information commands (`markitect version`, `markitect release`)
|
||||
- Global `--version` flag for quick version checking
|
||||
- Git integration for version metadata (commit, branch, tag information)
|
||||
- Multiple output formats for release information (text, JSON, YAML)
|
||||
- Installation documentation and troubleshooting guides
|
||||
|
||||
### Performance
|
||||
- **60-85% performance improvement** through AST caching optimization
|
||||
- **Sub-60ms asset processing** with efficient deduplication
|
||||
- **Memory-efficient operations** with proper resource management
|
||||
- **Scalable architecture** supporting large document collections
|
||||
|
||||
### Quality Assurance
|
||||
- **1983 comprehensive tests** covering all functionality layers
|
||||
- **Production validation suite** with cross-platform testing
|
||||
- **Enterprise error handling** with graceful degradation
|
||||
- **Type safety** with comprehensive type checking
|
||||
- **Security validation** with input sanitization and safe operations
|
||||
|
||||
### Fixed
|
||||
- All test failures resolved (1983/1983 tests passing)
|
||||
- Visualization schema tests updated for correct tool paths
|
||||
- Cache management test isolation issues
|
||||
- Missing dependencies documentation and installation
|
||||
- JavaScript syntax errors in edit mode initialization
|
||||
- Asset registry synchronization and performance issues
|
||||
- CLI command consolidation and interface consistency
|
||||
|
||||
### Documentation
|
||||
- Added comprehensive INSTALL.md with installation instructions
|
||||
- Added DEPENDENCIES.md with dependency information
|
||||
- Created release process documentation
|
||||
- **20+ documentation files** covering architecture, usage, and development
|
||||
- Complete API documentation with examples
|
||||
- Performance benchmarking guides and optimization tips
|
||||
|
||||
## [0.1.0] - 2025-10-03
|
||||
|
||||
### Added
|
||||
- Initial MarkiTect implementation
|
||||
- Core markdown processing with AST caching
|
||||
- Front matter and content matter support
|
||||
- Database integration for document metadata
|
||||
- CLI interface with comprehensive commands
|
||||
- Schema generation and validation
|
||||
- Template rendering system
|
||||
- Issue management integration
|
||||
- TDD workflow tools (TDDAI)
|
||||
- Comprehensive test suite with architectural layers
|
||||
- Documentation and architectural guides
|
||||
|
||||
### Features
|
||||
- Document ingestion and processing
|
||||
- Metadata extraction and querying
|
||||
- AST analysis and caching
|
||||
- Content statistics and analysis
|
||||
- Template-based document generation
|
||||
- Associated file management
|
||||
- Database operations with multiple output formats
|
||||
- Performance monitoring and optimization
|
||||
- Legacy compatibility system
|
||||
|
||||
### Technical
|
||||
- Python 3.8+ support
|
||||
- Click-based CLI framework
|
||||
- SQLite database backend
|
||||
- Markdown-it-py parser integration
|
||||
- Comprehensive test coverage
|
||||
- Type checking with mypy
|
||||
- Code formatting with black
|
||||
- Project structure following clean architecture principles
|
||||
239
CONCEPT.md
239
CONCEPT.md
@@ -1,239 +0,0 @@
|
||||
# MarkiTect Concepts and Terminology
|
||||
|
||||
This document defines the core concepts, terminology, and architectural principles that drive the MarkiTect project.
|
||||
|
||||
## Project Vision
|
||||
|
||||
**"Your Markdown, Redefined"**
|
||||
|
||||
MarkiTect transforms markdown from plain text into intelligent, structured data with performance optimization, schema validation, and relational querying capabilities. Stop treating documentation as text files—start managing it as a database.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Document Processing Philosophy
|
||||
|
||||
#### Intelligent Document Management
|
||||
- **AST-First Processing**: Every document is parsed into an Abstract Syntax Tree for structured manipulation
|
||||
- **Database-Driven Storage**: Documents are stored with relational metadata, not just as flat files
|
||||
- **Performance-Optimized**: Intelligent caching reduces processing time by 60-85%
|
||||
|
||||
#### Schema-Driven Development
|
||||
- **Document Schemas**: Define and enforce document structure and consistency
|
||||
- **Template Systems**: Generate documents from templates with variable substitution
|
||||
- **Validation Framework**: Ensure content meets predefined standards
|
||||
|
||||
### Key Terminology
|
||||
|
||||
#### Core Components
|
||||
|
||||
**MarkiTect Engine**
|
||||
: The central processing system that parses, validates, and transforms markdown documents
|
||||
|
||||
**AST (Abstract Syntax Tree)**
|
||||
: Structured representation of a markdown document's content and formatting
|
||||
|
||||
**Document Schema**
|
||||
: JSON-based definition of document structure, frontmatter requirements, and content rules
|
||||
|
||||
**Template Engine**
|
||||
: System for generating documents from templates with variable substitution (`{{variable}}` syntax)
|
||||
|
||||
**Performance Index**
|
||||
: Weighted 0-100 scale measuring system performance across template, database, and ingestion operations
|
||||
|
||||
#### Data Structures
|
||||
|
||||
**Frontmatter**
|
||||
: YAML/TOML metadata at the beginning of markdown documents containing structured information
|
||||
|
||||
**Contentmatter**
|
||||
: Key-value pairs embedded within document content using MultiMarkdown syntax
|
||||
|
||||
**Tailmatter**
|
||||
: QA checklists and editorial metadata at the end of documents for quality management
|
||||
|
||||
**Document Metadata**
|
||||
: Relational data extracted from documents and stored in the database for querying
|
||||
|
||||
#### Processing Concepts
|
||||
|
||||
**Zero-Parsing Access**
|
||||
: Ability to query document metadata without re-parsing the entire document
|
||||
|
||||
**Intelligent Caching**
|
||||
: AST caching system that dramatically improves performance on subsequent document operations
|
||||
|
||||
**Relational Document Metadata**
|
||||
: Document properties stored in a queryable database format rather than as flat text
|
||||
|
||||
## Architectural Principles
|
||||
|
||||
### Clean Architecture Foundation
|
||||
|
||||
#### Layered Design
|
||||
```
|
||||
┌─────────────────────────┐
|
||||
│ Presentation Layer │ ← CLI, Web Interface
|
||||
├─────────────────────────┤
|
||||
│ Application Layer │ ← Use Cases, Workflows
|
||||
├─────────────────────────┤
|
||||
│ Domain Layer │ ← Business Logic
|
||||
├─────────────────────────┤
|
||||
│ Infrastructure Layer │ ← Database, File System
|
||||
└─────────────────────────┘
|
||||
```
|
||||
|
||||
#### Dependency Rules
|
||||
- **Inward Dependencies**: Outer layers depend on inner layers, never the reverse
|
||||
- **Business Logic Isolation**: Core domain logic is independent of external concerns
|
||||
- **Interface Segregation**: Clean interfaces between layers
|
||||
|
||||
### Performance Philosophy
|
||||
|
||||
#### Optimization Strategy
|
||||
1. **Cache-First**: Intelligent AST caching for repeated operations
|
||||
2. **Lazy Loading**: Process only what's needed, when needed
|
||||
3. **Batch Operations**: Efficient processing of multiple documents
|
||||
4. **Memory Management**: Careful resource utilization and cleanup
|
||||
|
||||
#### Performance Metrics
|
||||
- **Template Rendering**: Target >1000 operations/second
|
||||
- **Database Operations**: Target >100 operations/second
|
||||
- **Document Ingestion**: Target >1000 operations/second
|
||||
- **Memory Usage**: Keep under 50MB baseline
|
||||
|
||||
### Quality Assurance
|
||||
|
||||
#### Testing Strategy
|
||||
- **TDD8 Methodology**: Test-Driven Development with 8-step cycle
|
||||
- **Comprehensive Coverage**: Unit, integration, and end-to-end testing
|
||||
- **Performance Validation**: Automated benchmarking and regression detection
|
||||
- **Quality Gates**: Automated checks preventing quality degradation
|
||||
|
||||
#### Documentation Standards
|
||||
- **DRY Principle**: Don't Repeat Yourself - avoid documentation duplication
|
||||
- **Arc42 Framework**: Structured architecture documentation when complexity warrants
|
||||
- **Living Documentation**: Documentation that evolves with the code
|
||||
|
||||
## Business Concepts
|
||||
|
||||
### Use Cases
|
||||
|
||||
#### Document Automation
|
||||
- **Invoice Generation**: Automated creation of business invoices from templates
|
||||
- **Report Pipelines**: Batch processing of document collections
|
||||
- **Content Management**: Structured content workflow management
|
||||
|
||||
#### Content Analysis
|
||||
- **Metadata Extraction**: Automated extraction of document properties
|
||||
- **Content Validation**: Enforcement of document standards and requirements
|
||||
- **Relationship Mapping**: Understanding connections between documents
|
||||
|
||||
#### Performance Management
|
||||
- **Regression Detection**: Automated identification of performance degradation
|
||||
- **Optimization Tracking**: Measurement of improvement initiatives
|
||||
- **Baseline Management**: Establishment and maintenance of performance standards
|
||||
|
||||
### Value Propositions
|
||||
|
||||
#### Primary USPs (Unique Selling Points)
|
||||
1. **Relational Document Metadata**: Documents as queryable database entities
|
||||
2. **Zero-Parsing Content Access**: Instant access to document information
|
||||
3. **Performance-First Design**: Dramatically faster than traditional markdown processors
|
||||
|
||||
#### Enterprise Benefits
|
||||
- **Consistency**: Schema validation ensures document standardization
|
||||
- **Efficiency**: Automated workflows reduce manual document management
|
||||
- **Scalability**: Performance optimization supports large document collections
|
||||
- **Quality**: Built-in validation and testing ensure reliability
|
||||
|
||||
## Technical Concepts
|
||||
|
||||
### Data Flow Architecture
|
||||
|
||||
#### Document Ingestion Pipeline
|
||||
```
|
||||
Markdown → Parser → AST → Metadata → Database
|
||||
↓ ↓ ↓ ↓ ↓
|
||||
Cache Validate Schema Extract Store
|
||||
```
|
||||
|
||||
#### Query Processing
|
||||
```
|
||||
Query → Database → Metadata → Reconstruct → Results
|
||||
↓ ↓ ↓ ↓ ↓
|
||||
Index Optimize Filter Transform Format
|
||||
```
|
||||
|
||||
### Integration Patterns
|
||||
|
||||
#### CLI-First Design
|
||||
- **Command-Line Interface**: Primary interaction method for automation
|
||||
- **Scriptable Operations**: All functionality accessible via CLI commands
|
||||
- **Pipeline Integration**: Designed for CI/CD and automated workflows
|
||||
|
||||
#### Database Integration
|
||||
- **SQLite Backend**: Lightweight, embedded database for metadata storage
|
||||
- **Relational Queries**: SQL-like operations on document collections
|
||||
- **ACID Compliance**: Reliable data consistency and transaction safety
|
||||
|
||||
### Extension Points
|
||||
|
||||
#### Plugin Architecture
|
||||
- **Modular Design**: Core functionality extended through plugins
|
||||
- **Template Engines**: Multiple template processing backends
|
||||
- **Output Formats**: Extensible document generation formats
|
||||
|
||||
#### External Integration
|
||||
- **API Endpoints**: RESTful interfaces for external systems
|
||||
- **Webhook Support**: Event-driven integration capabilities
|
||||
- **Import/Export**: Data exchange with external tools and formats
|
||||
|
||||
## Development Concepts
|
||||
|
||||
### Workflow Methodology
|
||||
|
||||
#### TDD8 Cycle
|
||||
1. **ISSUE**: Define problem and requirements
|
||||
2. **TEST**: Write tests before implementation
|
||||
3. **RED**: Ensure tests fail initially
|
||||
4. **GREEN**: Implement minimum viable solution
|
||||
5. **REFACTOR**: Improve code quality and design
|
||||
6. **DOCUMENT**: Update documentation and examples
|
||||
7. **REFINE**: Performance optimization and polish
|
||||
8. **PUBLISH**: Release and communicate changes
|
||||
|
||||
#### Quality Standards
|
||||
- **Code Coverage**: Minimum 80% test coverage
|
||||
- **Performance Benchmarks**: All operations must meet performance targets
|
||||
- **Documentation Currency**: Documentation updated with every feature change
|
||||
- **Backward Compatibility**: Changes preserve existing functionality
|
||||
|
||||
### Maintenance Philosophy
|
||||
|
||||
#### Sustainable Development
|
||||
- **Technical Debt Management**: Regular refactoring and code quality improvement
|
||||
- **Performance Monitoring**: Continuous tracking of system performance
|
||||
- **User Experience Focus**: Features designed from user workflow perspective
|
||||
- **Community Engagement**: Open source collaboration and contribution
|
||||
|
||||
#### Future-Proofing
|
||||
- **Modular Architecture**: Easy addition of new features and capabilities
|
||||
- **Standard Compliance**: Adherence to markdown and web standards
|
||||
- **Scalability Design**: Architecture supports growth in users and document volume
|
||||
- **Technology Evolution**: Designed to adapt to changing technology landscape
|
||||
|
||||
## Glossary
|
||||
|
||||
**Arc42**: Architecture documentation framework for technical communication
|
||||
**AST**: Abstract Syntax Tree - structured representation of document content
|
||||
**CLI**: Command-Line Interface - text-based user interface
|
||||
**DRY**: Don't Repeat Yourself - principle of reducing duplication
|
||||
**TDD**: Test-Driven Development - testing methodology
|
||||
**TOML**: Tom's Obvious Minimal Language - configuration file format
|
||||
**USP**: Unique Selling Point - distinctive business advantage
|
||||
**YAML**: YAML Ain't Markup Language - human-readable data serialization
|
||||
|
||||
---
|
||||
|
||||
This document serves as the foundation for understanding MarkiTect's design philosophy, technical approach, and business value proposition. It should be consulted when making architectural decisions or explaining the project to new contributors.
|
||||
201
CONFIG.md
201
CONFIG.md
@@ -1,201 +0,0 @@
|
||||
# TDDAi Configuration Management
|
||||
|
||||
The tddai framework uses a flexible, hierarchical configuration system designed for project-agnostic deployment while supporting per-project customization.
|
||||
|
||||
## Configuration Hierarchy
|
||||
|
||||
Configuration values are loaded in the following priority order (highest to lowest):
|
||||
|
||||
1. **Environment Variables** - Runtime overrides (highest priority)
|
||||
2. **`.env.tddai` File** - Project-specific configuration (auto-loaded)
|
||||
3. **Default Values** - Framework defaults (fallback)
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Automatic Configuration (Recommended)
|
||||
The framework automatically loads `.env.tddai` from the current directory:
|
||||
|
||||
```bash
|
||||
# Configuration loaded automatically
|
||||
make tdd-status
|
||||
make tdd-start NUM=5
|
||||
```
|
||||
|
||||
### Manual Configuration
|
||||
You can also source the setup script manually:
|
||||
|
||||
```bash
|
||||
source tddai-setup.sh
|
||||
make tdd-status
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Repository Settings (Required)
|
||||
|
||||
| Variable | Description | Example | Required |
|
||||
|----------|-------------|---------|----------|
|
||||
| `TDDAI_GITEA_URL` | Git platform URL | `https://github.com` | ✅ |
|
||||
| `TDDAI_REPO_OWNER` | Repository owner/org | `myusername` | ✅ |
|
||||
| `TDDAI_REPO_NAME` | Repository name | `myproject` | ✅ |
|
||||
|
||||
### Workspace Settings (Optional)
|
||||
|
||||
| Variable | Description | Default | Example |
|
||||
|----------|-------------|---------|---------|
|
||||
| `TDDAI_WORKSPACE_DIR` | TDD workspace directory | `.tddai_workspace` | `.myproject_workspace` |
|
||||
|
||||
### Test Settings (Framework Defaults)
|
||||
|
||||
| Setting | Value | Description |
|
||||
|---------|-------|-------------|
|
||||
| `tests_dir` | `tests/` | Main test directory |
|
||||
| `test_file_pattern` | `test_issue_{issue_num}_{scenario}.py` | Test file naming pattern |
|
||||
| `current_issue_file` | `current_issue.json` | Active issue metadata file |
|
||||
|
||||
## Configuration Files
|
||||
|
||||
### `.env.tddai` Format
|
||||
```bash
|
||||
# TDDAi configuration for YourProject
|
||||
# Repository settings
|
||||
TDDAI_GITEA_URL=https://your-git-platform.com
|
||||
TDDAI_REPO_OWNER=yourusername
|
||||
TDDAI_REPO_NAME=yourproject
|
||||
|
||||
# Workspace settings (optional)
|
||||
TDDAI_WORKSPACE_DIR=.yourproject_workspace
|
||||
```
|
||||
|
||||
### `tddai-setup.sh` Format
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# TDDAi environment setup script
|
||||
|
||||
export TDDAI_GITEA_URL=https://your-git-platform.com
|
||||
export TDDAI_REPO_OWNER=yourusername
|
||||
export TDDAI_REPO_NAME=yourproject
|
||||
export TDDAI_WORKSPACE_DIR=.yourproject_workspace
|
||||
|
||||
echo "✅ TDDAi configured for YourProject"
|
||||
```
|
||||
|
||||
## Platform Examples
|
||||
|
||||
### GitHub Configuration
|
||||
```bash
|
||||
TDDAI_GITEA_URL=https://github.com
|
||||
TDDAI_REPO_OWNER=yourusername
|
||||
TDDAI_REPO_NAME=yourrepo
|
||||
```
|
||||
|
||||
### GitLab Configuration
|
||||
```bash
|
||||
TDDAI_GITEA_URL=https://gitlab.com
|
||||
TDDAI_REPO_OWNER=yourusername
|
||||
TDDAI_REPO_NAME=yourrepo
|
||||
```
|
||||
|
||||
### Self-hosted Gitea
|
||||
```bash
|
||||
TDDAI_GITEA_URL=https://git.yourcompany.com
|
||||
TDDAI_REPO_OWNER=yourorganization
|
||||
TDDAI_REPO_NAME=yourproject
|
||||
```
|
||||
|
||||
## API Integration
|
||||
|
||||
The configuration automatically constructs API URLs:
|
||||
|
||||
```python
|
||||
# Constructed from configuration
|
||||
issues_api_url = f"{TDDAI_GITEA_URL}/api/v1/repos/{TDDAI_REPO_OWNER}/{TDDAI_REPO_NAME}/issues"
|
||||
```
|
||||
|
||||
## Workspace Structure
|
||||
|
||||
Default workspace layout (configurable via `TDDAI_WORKSPACE_DIR`):
|
||||
|
||||
```
|
||||
.tddai_workspace/
|
||||
├── current_issue.json # Active issue metadata
|
||||
└── issue_X/ # Issue-specific workspace
|
||||
├── tests/ # Test files for this issue
|
||||
│ └── test_issue_X_*.py # Generated test files
|
||||
├── requirements.md # Issue requirements analysis
|
||||
└── test_plan.md # Test planning document
|
||||
```
|
||||
|
||||
## Environment Variable Overrides
|
||||
|
||||
You can override any configuration at runtime:
|
||||
|
||||
```bash
|
||||
# Override workspace directory for this session
|
||||
TDDAI_WORKSPACE_DIR=.custom_workspace make tdd-start NUM=5
|
||||
|
||||
# Override repository for testing
|
||||
TDDAI_REPO_NAME=test_repo make tdd-status
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
The framework validates configuration on startup:
|
||||
|
||||
- **Required fields** must be non-empty (`gitea_url`, `repo_owner`, `repo_name`)
|
||||
- **URLs** should include protocol (`http://` or `https://`)
|
||||
- **Workspace directories** are created automatically if they don't exist
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Errors
|
||||
|
||||
**`gitea_url cannot be empty`**
|
||||
- Solution: Create `.env.tddai` with `TDDAI_GITEA_URL=your-url`
|
||||
- Alternative: Run `source tddai-setup.sh` before tddai commands
|
||||
|
||||
**`repo_owner cannot be empty`**
|
||||
- Solution: Set `TDDAI_REPO_OWNER` in `.env.tddai` or environment
|
||||
|
||||
**`repo_name cannot be empty`**
|
||||
- Solution: Set `TDDAI_REPO_NAME` in `.env.tddai` or environment
|
||||
|
||||
### Debug Configuration
|
||||
```bash
|
||||
# Check current configuration
|
||||
python -c "from tddai.config import get_config; c=get_config(); print(f'URL: {c.gitea_url}\\nOwner: {c.repo_owner}\\nRepo: {c.repo_name}\\nWorkspace: {c.workspace_dir}')"
|
||||
```
|
||||
|
||||
## Migration from Other Projects
|
||||
|
||||
When adapting tddai for a new project:
|
||||
|
||||
1. **Copy configuration template**:
|
||||
```bash
|
||||
cp .env.tddai.example .env.tddai
|
||||
```
|
||||
|
||||
2. **Update repository settings**:
|
||||
```bash
|
||||
# Edit .env.tddai
|
||||
TDDAI_GITEA_URL=https://your-platform.com
|
||||
TDDAI_REPO_OWNER=your-username
|
||||
TDDAI_REPO_NAME=your-project
|
||||
```
|
||||
|
||||
3. **Test configuration**:
|
||||
```bash
|
||||
make tdd-status
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Use `.env.tddai`** for project-specific settings
|
||||
- **Use environment variables** for temporary overrides
|
||||
- **Keep configuration in version control** (but exclude sensitive tokens)
|
||||
- **Document custom workspace naming** in project README
|
||||
- **Validate configuration** before starting development sessions
|
||||
|
||||
---
|
||||
|
||||
*This configuration system supports the TDD8 methodology (ISSUE-TEST-RED-GREEN-REFACTOR-DOCUMENT-REFINE-PUBLISH) across any software development project with issue tracking.*
|
||||
@@ -1,92 +0,0 @@
|
||||
# MarkiTect Project Dependencies
|
||||
|
||||
## Overview
|
||||
This document lists all project dependencies for the MarkiTect project.
|
||||
|
||||
## Production Dependencies
|
||||
These are required for running the application:
|
||||
|
||||
- **markdown-it-py** - Markdown parsing library
|
||||
- **PyYAML** - YAML file processing
|
||||
- **click>=8.0.0** - Command-line interface framework
|
||||
- **tabulate>=0.9.0** - Table formatting for output
|
||||
- **jsonpath-ng>=1.5.0** - JSONPath query support
|
||||
- **aiohttp>=3.8.0** - Async HTTP client/server
|
||||
- **toml** - TOML file parsing (for frontmatter support)
|
||||
|
||||
## Development Dependencies
|
||||
These are required for development, testing, and code quality:
|
||||
|
||||
- **pytest** - Testing framework
|
||||
- **pytest-cov** - Test coverage reporting
|
||||
- **black** - Code formatting
|
||||
- **flake8** - Code linting
|
||||
- **mypy** - Type checking
|
||||
|
||||
## Test Dependencies
|
||||
Additional dependencies for testing (from tests/requirements-test.txt if present):
|
||||
- See `tests/requirements-test.txt` for any additional test-specific dependencies
|
||||
|
||||
## Installation
|
||||
|
||||
### Quick Setup
|
||||
```bash
|
||||
# Install production dependencies only
|
||||
pip install -e .
|
||||
|
||||
# Install with development dependencies
|
||||
make dev
|
||||
```
|
||||
|
||||
### Manual Installation
|
||||
```bash
|
||||
# Production dependencies
|
||||
pip install markdown-it-py PyYAML click>=8.0.0 tabulate>=0.9.0 jsonpath-ng>=1.5.0 aiohttp>=3.8.0 toml
|
||||
|
||||
# Development dependencies
|
||||
pip install pytest pytest-cov black flake8 mypy
|
||||
```
|
||||
|
||||
### Virtual Environment Setup
|
||||
```bash
|
||||
# Create and activate virtual environment
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
# Install dependencies
|
||||
make dev
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
After installing dependencies:
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
make test
|
||||
|
||||
# Run tests with coverage
|
||||
pytest --cov
|
||||
|
||||
# Run specific test layers
|
||||
make test-foundation
|
||||
make test-infrastructure
|
||||
make test-integration
|
||||
```
|
||||
|
||||
## Code Quality Tools
|
||||
|
||||
```bash
|
||||
# Format code
|
||||
make format
|
||||
|
||||
# Run linting
|
||||
make lint
|
||||
|
||||
# Type checking
|
||||
mypy markitect/
|
||||
```
|
||||
|
||||
## Notes
|
||||
- Python 3.8+ is required
|
||||
- Virtual environment (.venv) is recommended
|
||||
- All dependencies are managed through pyproject.toml
|
||||
219
INSTALL.md
219
INSTALL.md
@@ -1,219 +0,0 @@
|
||||
# MarkiTect Installation Guide
|
||||
|
||||
This document describes how to install MarkiTect and make it available system-wide.
|
||||
|
||||
## Quick Installation
|
||||
|
||||
For most users, the quick installer is the easiest option:
|
||||
|
||||
```bash
|
||||
# Install for current user
|
||||
./install.sh
|
||||
|
||||
# Install system-wide (requires sudo)
|
||||
./install.sh --system
|
||||
|
||||
# Install in development mode with test dependencies
|
||||
./install.sh --dev
|
||||
```
|
||||
|
||||
## Advanced Installation
|
||||
|
||||
For more control over the installation process, use the Python installer:
|
||||
|
||||
```bash
|
||||
# Install with custom prefix
|
||||
python install.py --prefix /opt/markitect
|
||||
|
||||
# Install with custom virtual environment location
|
||||
python install.py --venv-dir /path/to/custom/venv
|
||||
|
||||
# Install without creating symbolic links (manual PATH setup)
|
||||
python install.py --no-symlinks
|
||||
|
||||
# Force reinstallation over existing installation
|
||||
python install.py --force
|
||||
```
|
||||
|
||||
## Installation Options
|
||||
|
||||
### Installation Types
|
||||
|
||||
- **User Installation** (default): Installs to `~/.local/`
|
||||
- **System Installation** (`--system`): Installs to `/usr/local/` (requires sudo)
|
||||
- **Development Installation** (`--dev`): Installs in editable mode with test dependencies
|
||||
|
||||
### Installation Paths
|
||||
|
||||
By default, MarkiTect is installed to:
|
||||
|
||||
- **User installation**: `~/.local/lib/markitect/` (virtual environment)
|
||||
- **System installation**: `/usr/local/lib/markitect/` (virtual environment)
|
||||
- **Binaries**: `~/.local/bin/` or `/usr/local/bin/`
|
||||
|
||||
### Available Commands
|
||||
|
||||
After installation, these commands will be available:
|
||||
|
||||
- `markitect` - Main MarkiTect CLI
|
||||
- `tddai` - TDD workflow management
|
||||
- `issue` - Issue management
|
||||
|
||||
## Checking Installation
|
||||
|
||||
Check if MarkiTect is already installed:
|
||||
|
||||
```bash
|
||||
./install.sh --check
|
||||
# or
|
||||
python install.py --check
|
||||
```
|
||||
|
||||
Check version after installation:
|
||||
|
||||
```bash
|
||||
markitect version
|
||||
markitect version --short
|
||||
markitect release
|
||||
```
|
||||
|
||||
## Uninstallation
|
||||
|
||||
To remove MarkiTect:
|
||||
|
||||
```bash
|
||||
./install.sh --uninstall
|
||||
# or
|
||||
python install.py --uninstall
|
||||
```
|
||||
|
||||
## Manual Installation
|
||||
|
||||
If you prefer to install manually:
|
||||
|
||||
1. **Create virtual environment:**
|
||||
```bash
|
||||
python -m venv ~/.local/lib/markitect
|
||||
```
|
||||
|
||||
2. **Activate virtual environment:**
|
||||
```bash
|
||||
source ~/.local/lib/markitect/bin/activate
|
||||
```
|
||||
|
||||
3. **Install MarkiTect:**
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
4. **Create symbolic links:**
|
||||
```bash
|
||||
mkdir -p ~/.local/bin
|
||||
ln -sf ~/.local/lib/markitect/bin/markitect ~/.local/bin/markitect
|
||||
ln -sf ~/.local/lib/markitect/bin/tddai ~/.local/bin/tddai
|
||||
ln -sf ~/.local/lib/markitect/bin/issue ~/.local/bin/issue
|
||||
```
|
||||
|
||||
5. **Add to PATH** (add to `~/.bashrc` or `~/.zshrc`):
|
||||
```bash
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
```
|
||||
|
||||
## Development Installation
|
||||
|
||||
For development work:
|
||||
|
||||
```bash
|
||||
# Install in development mode
|
||||
./install.sh --dev
|
||||
|
||||
# This includes:
|
||||
# - Editable installation (changes reflect immediately)
|
||||
# - Test dependencies (pytest, black, flake8, mypy)
|
||||
# - All development tools
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Command not found after installation:**
|
||||
- Make sure `~/.local/bin` is in your PATH
|
||||
- Run: `export PATH="$HOME/.local/bin:$PATH"`
|
||||
- Add the export to your shell profile
|
||||
|
||||
2. **Permission denied on system installation:**
|
||||
- Use `sudo ./install.sh --system`
|
||||
- Or install to user directory instead
|
||||
|
||||
3. **Python version error:**
|
||||
- MarkiTect requires Python 3.8 or higher
|
||||
- Check version: `python3 --version`
|
||||
|
||||
4. **Installation already exists:**
|
||||
- Use `--force` to overwrite: `./install.sh --force`
|
||||
- Or uninstall first: `./install.sh --uninstall`
|
||||
|
||||
### Manual PATH Setup
|
||||
|
||||
If symbolic links don't work, add the virtual environment bin directory to your PATH:
|
||||
|
||||
```bash
|
||||
# For bash/zsh (add to ~/.bashrc or ~/.zshrc)
|
||||
export PATH="$HOME/.local/lib/markitect/bin:$PATH"
|
||||
|
||||
# For fish (add to ~/.config/fish/config.fish)
|
||||
set -gx PATH $HOME/.local/lib/markitect/bin $PATH
|
||||
```
|
||||
|
||||
### Testing Installation
|
||||
|
||||
After installation, verify everything works:
|
||||
|
||||
```bash
|
||||
# Test basic functionality
|
||||
markitect --help
|
||||
markitect version
|
||||
|
||||
# Test TDD tools
|
||||
tddai --help
|
||||
|
||||
# Test issue management
|
||||
issue --help
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
MarkiTect automatically installs these dependencies:
|
||||
|
||||
### Production Dependencies
|
||||
- markdown-it-py - Markdown parsing
|
||||
- PyYAML - YAML processing
|
||||
- click>=8.0.0 - CLI framework
|
||||
- tabulate>=0.9.0 - Table formatting
|
||||
- jsonpath-ng>=1.5.0 - JSONPath queries
|
||||
- aiohttp>=3.8.0 - Async HTTP client
|
||||
- toml - TOML file parsing
|
||||
|
||||
### Development Dependencies (with --dev)
|
||||
- pytest - Testing framework
|
||||
- pytest-cov - Test coverage
|
||||
- black - Code formatting
|
||||
- flake8 - Code linting
|
||||
- mypy - Type checking
|
||||
|
||||
## System Requirements
|
||||
|
||||
- Python 3.8 or higher
|
||||
- pip (Python package installer)
|
||||
- git (optional, for version info)
|
||||
- Unix-like system (Linux, macOS) or Windows with Python support
|
||||
|
||||
## Support
|
||||
|
||||
For installation issues:
|
||||
|
||||
1. Check this guide first
|
||||
2. Run `./install.sh --check` to diagnose problems
|
||||
3. See the main project documentation
|
||||
4. Report issues on the project issue tracker
|
||||
32
LICENSE.md
32
LICENSE.md
@@ -1,32 +0,0 @@
|
||||
# MIT License
|
||||
|
||||
Copyright (c) 2025 MarkiTect Project
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## Additional Information
|
||||
|
||||
This project uses the MIT License to promote open source collaboration while protecting contributors. The MIT License is:
|
||||
|
||||
- **Permissive**: Allows commercial and private use
|
||||
- **Simple**: Easy to understand and implement
|
||||
- **Compatible**: Works well with other open source licenses
|
||||
- **Widely Adopted**: Recognized and trusted in the open source community
|
||||
|
||||
For questions about licensing or commercial use, please contact the project maintainers.
|
||||
375
Makefile
375
Makefile
@@ -1,7 +1,7 @@
|
||||
# MarkiTect - Advanced Markdown Engine
|
||||
# Makefile for common development tasks
|
||||
|
||||
.PHONY: help setup install-dev install-home install-home-venv install-deps install-deps-force install-deps-venv install-system list-deps setup-dev test build clean update status lint format check-deps venv-status update-digest add-diary-entry issue-list issue-show issue-list-open issue-create issue-close issue-close-enhanced issue-close-batch issue-get issue-csv issue-json issue-high test-from-issue tdd-start tdd-add-test tdd-finish tdd-status test-status test-new test-coverage test-arch test-foundation test-infrastructure test-integration test-domain test-service test-application test-presentation test-quick test-layers test-random test-random-seed test-random-repeat test-install-randomly test-clean test-tdd test-changed test-module test-cache-clean test-efficient cli-help release-status release-validate release-prepare release-build release-publish release-dry-run chaos-validate chaos-matrix chaos-inject chaos-report cost-help cost-note-issue
|
||||
.PHONY: help setup install-dev install-home install-home-venv install-deps install-deps-force install-deps-venv install-system list-deps setup-dev test build clean update status lint format check-deps venv-status update-digest add-diary-entry test-status test-new test-coverage test-arch test-foundation test-infrastructure test-integration test-domain test-service test-application test-presentation test-quick test-layers test-random test-random-seed test-random-repeat test-install-randomly test-clean test-tdd test-changed test-module test-cache-clean test-efficient cli-help release-status release-validate release-prepare release-build release-publish release-dry-run chaos-validate chaos-matrix chaos-inject chaos-report cost-help
|
||||
|
||||
# Default target
|
||||
help:
|
||||
@@ -25,10 +25,12 @@ help:
|
||||
@echo " venv-status - Check if venv is active"
|
||||
@echo ""
|
||||
@echo "Development:"
|
||||
@echo " test - Run all tests"
|
||||
@echo " test - Run core tests (excluding capability-specific tests)"
|
||||
@echo " test-capabilities - Run all capability-specific tests"
|
||||
@echo " test-capability-* - Run specific capability tests (content, utils, finance, etc.)"
|
||||
@echo " test-status - Show test status summary without re-running"
|
||||
@echo " test-new - Create new test file template"
|
||||
@echo " test-coverage ISSUE=X - Analyze test coverage for issue"
|
||||
@echo " test-coverage - Analyze test coverage"
|
||||
@echo " build - Build the package"
|
||||
@echo " lint - Run code linting"
|
||||
@echo " format - Format code"
|
||||
@@ -49,7 +51,6 @@ help:
|
||||
@echo ""
|
||||
@echo "Cost Tracking:"
|
||||
@echo " cost-help - Show cost tracking commands and usage"
|
||||
@echo " cost-note-issue ISSUE=X INPUT_TOKENS=N OUTPUT_TOKENS=M - Generate cost note for issue"
|
||||
@echo ""
|
||||
@echo "Architectural Testing:"
|
||||
@echo " test-arch - Run all tests in architectural order"
|
||||
@@ -82,32 +83,17 @@ help:
|
||||
@echo " status - Show git status for repo and submodules"
|
||||
@echo " clean - Clean build artifacts"
|
||||
@echo " check-deps - Check dependency status"
|
||||
@echo " validate-js - Validate JavaScript syntax in templates"
|
||||
@echo ""
|
||||
@echo "Documentation:"
|
||||
@echo " update-digest - Update ProjectStatusDigest.md (requires Claude Code)"
|
||||
@echo " add-diary-entry - Add new entry to ProjectDiary.md (requires Claude Code)"
|
||||
@echo ""
|
||||
@echo "Issue Management:"
|
||||
@echo " issue-list - Show all gitea issues with status and priority"
|
||||
@echo " issue-list-open - Show only open issues (active backlog)"
|
||||
@echo " issue-create TITLE='...' BODY='...' - Create a new issue (or BODY_FILE='/path/to/file.md')"
|
||||
@echo " issue-show ISSUE=X (or NUM=X) - Show detailed view of specific issue"
|
||||
@echo " issue-close ISSUE=X [COMMENT='reason'] - Close an issue and mark as completed"
|
||||
@echo " issue-close-enhanced ISSUE=X [WORK='description'] - Close issue with enhanced functionality"
|
||||
@echo " issue-close-batch NUMS='X Y Z' [COMMENT='reason'] - Close multiple issues at once"
|
||||
@echo " issue-get - Export compact issue index to ISSUES.index"
|
||||
@echo " issue-csv - Export issues as CSV for spreadsheet processing"
|
||||
@echo " issue-json - Export issues as JSON for programmatic processing"
|
||||
@echo " issue-high - Export only high/critical priority issues"
|
||||
@echo "Capability Management:"
|
||||
@echo " capability-report - Generate capability discovery report"
|
||||
@echo " capability-search TERM=xyz - Search for functionality across capabilities"
|
||||
@echo " capability-validate FILE=path - Validate proper capability usage in file"
|
||||
@echo ""
|
||||
@echo "Test-Driven Development:"
|
||||
@echo " test-from-issue ISSUE=X - Generate test skeleton from issue (requires Claude Code)"
|
||||
@echo ""
|
||||
@echo "TDD Workspace:"
|
||||
@echo " tdd-start ISSUE=X - Start working on issue (with requirements validation)"
|
||||
@echo " tdd-add-test - Add test to current issue workspace"
|
||||
@echo " tdd-status - Show current workspace state"
|
||||
@echo " tdd-finish - Complete issue work (moves tests to main)"
|
||||
@echo ""
|
||||
@echo "Requirements Engineering:"
|
||||
@echo " validate-requirements - Analyze foundations before development"
|
||||
@@ -337,25 +323,77 @@ setup-dev: install-dev
|
||||
|
||||
# Run tests
|
||||
test: $(VENV)/bin/activate
|
||||
@echo "🧪 Running tests..."
|
||||
@echo "🧪 Running core tests (excluding capability-specific tests)..."
|
||||
@if [ -f $(VENV)/bin/pytest ]; then \
|
||||
PYTHONPATH=. $(VENV)/bin/pytest tests/ -v; \
|
||||
PYTHONPATH=. $(VENV)/bin/pytest tests/ -v \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/; \
|
||||
else \
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -v 2>/dev/null || \
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -v \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/ 2>/dev/null || \
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m unittest discover tests/ -v; \
|
||||
fi
|
||||
|
||||
# Capability-Specific Test Targets
|
||||
test-capabilities: test-capability-content test-capability-utils test-capability-finance test-capability-query test-capability-graphql test-capability-plugins
|
||||
@echo "✅ All capability tests completed"
|
||||
|
||||
test-capability-content: $(VENV)/bin/activate
|
||||
@echo "🧪 Running markitect-content capability tests..."
|
||||
@cd capabilities/markitect-content && python -m pytest tests/ -v
|
||||
|
||||
test-capability-utils: $(VENV)/bin/activate
|
||||
@echo "🧪 Running markitect-utils capability tests..."
|
||||
@cd capabilities/markitect-utils && python -m pytest tests/ -v
|
||||
|
||||
test-capability-finance: $(VENV)/bin/activate
|
||||
@echo "🧪 Running finance capability tests..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) -m pytest markitect/finance/tests/ -v
|
||||
|
||||
test-capability-query: $(VENV)/bin/activate
|
||||
@echo "🧪 Running query paradigms capability tests..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) -m pytest markitect/query_paradigms/tests/ -v
|
||||
|
||||
test-capability-graphql: $(VENV)/bin/activate
|
||||
@echo "🧪 Running GraphQL capability tests..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) -m pytest markitect/graphql/tests/ -v
|
||||
|
||||
test-capability-plugins: $(VENV)/bin/activate
|
||||
@echo "🧪 Running plugins capability tests..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) -m pytest markitect/plugins/tests/ -v
|
||||
|
||||
# TDD8 Workflow Optimized Test Targets (Issue #57)
|
||||
|
||||
# Fast test execution for TDD red phase
|
||||
test-red: $(VENV)/bin/activate
|
||||
@echo "🔴 TDD Red Phase - Fast test execution..."
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -x --maxfail=1 --tb=short -q
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -x --maxfail=1 --tb=short -q \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/
|
||||
|
||||
# Comprehensive test execution for TDD green phase
|
||||
test-green: $(VENV)/bin/activate
|
||||
@echo "🟢 TDD Green Phase - Comprehensive validation..."
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ --tb=short
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ --tb=short \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/
|
||||
|
||||
# Smart test selection - changed files only
|
||||
test-smart: $(VENV)/bin/activate
|
||||
@@ -371,12 +409,24 @@ test-smart: $(VENV)/bin/activate
|
||||
# Ultra-fast test execution
|
||||
test-ultra-fast: $(VENV)/bin/activate
|
||||
@echo "⚡ Ultra-fast test execution..."
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -m "not slow" --maxfail=1 -x -q
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ -m "not slow" --maxfail=1 -x -q \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/
|
||||
|
||||
# Test with performance monitoring
|
||||
test-perf: $(VENV)/bin/activate
|
||||
@echo "📊 Test execution with performance monitoring..."
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ --durations=10 --tb=short
|
||||
PYTHONPATH=. $(VENV_PYTHON) -m pytest tests/ --durations=10 --tb=short \
|
||||
--ignore=capabilities/markitect-content/tests/ \
|
||||
--ignore=capabilities/markitect-utils/tests/ \
|
||||
--ignore=markitect/finance/tests/ \
|
||||
--ignore=markitect/query_paradigms/tests/ \
|
||||
--ignore=markitect/graphql/tests/ \
|
||||
--ignore=markitect/plugins/tests/
|
||||
|
||||
# Test health check
|
||||
test-health: $(VENV)/bin/activate
|
||||
@@ -567,204 +617,30 @@ add-diary-entry:
|
||||
@echo ""
|
||||
@echo "💡 Tip: New entries are added to the top for reverse chronological order"
|
||||
|
||||
# Capability discovery and management targets
|
||||
capability-report: $(VENV)/bin/activate
|
||||
@echo "📋 Generating capability discovery report..."
|
||||
@$(VENV_PYTHON) tools/capability_discovery.py report
|
||||
|
||||
capability-search: $(VENV)/bin/activate
|
||||
@if [ -z "$(TERM)" ]; then \
|
||||
echo "❌ Please specify search term: make capability-search TERM=issue_management"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "🔍 Searching for '$(TERM)' across capabilities..."
|
||||
@$(VENV_PYTHON) tools/capability_discovery.py search "$(TERM)"
|
||||
|
||||
capability-validate: $(VENV)/bin/activate
|
||||
@if [ -z "$(FILE)" ]; then \
|
||||
echo "❌ Please specify file path: make capability-validate FILE=path/to/file.py"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "✅ Validating capability usage in $(FILE)..."
|
||||
@$(VENV_PYTHON) tools/capability_discovery.py validate "$(FILE)"
|
||||
|
||||
# Git repository and API configuration
|
||||
GITEA_URL := http://92.205.130.254:32166
|
||||
REPO_OWNER := coulomb
|
||||
REPO_NAME := markitect_project
|
||||
ISSUES_API := $(GITEA_URL)/api/v1/repos/$(REPO_OWNER)/$(REPO_NAME)/issues
|
||||
|
||||
# Issue workspace configuration
|
||||
WORKSPACE_DIR := .markitect_workspace
|
||||
CURRENT_ISSUE_FILE := $(WORKSPACE_DIR)/current_issue.json
|
||||
|
||||
# List all gitea issues
|
||||
issue-list: $(VENV)/bin/activate
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py list-issues
|
||||
|
||||
# Show detailed view of a specific issue
|
||||
issue-show: $(VENV)/bin/activate
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make issue-show ISSUE=5 (or NUM=5)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py show-issue $$ISSUE_NUM
|
||||
|
||||
# List only open issues (active backlog)
|
||||
issue-list-open: $(VENV)/bin/activate
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py list-open-issues
|
||||
|
||||
# Create a new issue
|
||||
issue-create:
|
||||
@if [ -z "$(TITLE)" ]; then \
|
||||
echo "❌ Please specify issue title: make issue-create TITLE='Fix bug' BODY='Description'"; \
|
||||
echo "❌ Or use: make issue-create TITLE='Fix bug' BODY_FILE='/path/to/body.md'"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@if [ -z "$(BODY)" ] && [ -z "$(BODY_FILE)" ]; then \
|
||||
echo "❌ Please specify either BODY='...' or BODY_FILE='/path/to/file.md'"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "📋 Creating new issue..."
|
||||
@echo "📋 Title: $(TITLE)"
|
||||
@if [ -n "$(BODY_FILE)" ]; then \
|
||||
tea issue create --title "$(TITLE)" --description "$$(cat $(BODY_FILE))"; \
|
||||
else \
|
||||
tea issue create --title "$(TITLE)" --description "$(BODY)"; \
|
||||
fi
|
||||
|
||||
# Close an issue and mark as completed
|
||||
issue-close: $(VENV)/bin/activate
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make issue-close ISSUE=5 (or NUM=5)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
if [ -n "$(COMMENT)" ]; then \
|
||||
echo "🔄 Closing issue #$$ISSUE_NUM with comment..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py close-issue $$ISSUE_NUM --comment "$(COMMENT)"; \
|
||||
else \
|
||||
echo "🔄 Closing issue #$$ISSUE_NUM..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py close-issue $$ISSUE_NUM; \
|
||||
fi; \
|
||||
echo "✅ Issue #$$ISSUE_NUM closed successfully!"
|
||||
|
||||
# Close issue using dedicated issue_closer.py script (enhanced functionality)
|
||||
issue-close-enhanced: $(VENV)/bin/activate
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make issue-close-enhanced ISSUE=5 (or NUM=5)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
if [ -n "$(WORK)" ]; then \
|
||||
echo "🔄 Closing issue #$$ISSUE_NUM with completion message..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai/issue_closer.py $$ISSUE_NUM --work-completed "$(WORK)"; \
|
||||
elif [ -n "$(COMMENT)" ]; then \
|
||||
echo "🔄 Closing issue #$$ISSUE_NUM with comment..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai/issue_closer.py $$ISSUE_NUM --comment "$(COMMENT)"; \
|
||||
else \
|
||||
echo "🔄 Closing issue #$$ISSUE_NUM..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai/issue_closer.py $$ISSUE_NUM; \
|
||||
fi
|
||||
|
||||
# Close multiple issues at once using issue_closer.py
|
||||
issue-close-batch: $(VENV)/bin/activate
|
||||
@if [ -z "$(NUMS)" ]; then \
|
||||
echo "❌ Please specify issue numbers: make issue-close-batch NUMS='42 43 44'"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@if [ -n "$(COMMENT)" ]; then \
|
||||
echo "🔄 Closing issues $(NUMS) with comment..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai/issue_closer.py $(NUMS) --comment "$(COMMENT)"; \
|
||||
else \
|
||||
echo "🔄 Closing issues $(NUMS)..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai/issue_closer.py $(NUMS); \
|
||||
fi
|
||||
|
||||
# Export compact issue index to ISSUES.index file (TSV format)
|
||||
issue-get: $(VENV)/bin/activate
|
||||
@echo "📋 Fetching issue index from gitea..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py issue-index --format tsv --sort number > ISSUES.index
|
||||
@echo "✅ Issue index exported to ISSUES.index (TSV format)"
|
||||
@echo "📄 File contents:"
|
||||
@cat ISSUES.index
|
||||
|
||||
# Export issues as CSV for spreadsheet processing
|
||||
issue-csv: $(VENV)/bin/activate
|
||||
@echo "📊 Exporting issues as CSV..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py issue-index --format csv --sort priority --include-state > ISSUES.csv
|
||||
@echo "✅ Issues exported to ISSUES.csv"
|
||||
@wc -l ISSUES.csv | awk '{print "📄 Total entries:", $$1-1, "(excluding header)"}'
|
||||
|
||||
# Export issues as JSON for programmatic processing
|
||||
issue-json: $(VENV)/bin/activate
|
||||
@echo "🔧 Exporting issues as JSON..."
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py issue-index --format json --sort priority > ISSUES.json
|
||||
@echo "✅ Issues exported to ISSUES.json"
|
||||
@echo "📄 Sample entry:"
|
||||
@head -20 ISSUES.json
|
||||
|
||||
# Export only high and critical priority issues
|
||||
issue-high: $(VENV)/bin/activate
|
||||
@echo "🚨 Exporting high priority issues..."
|
||||
@echo "High priority issues:" > ISSUES.high.txt
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py issue-index --format tsv --filter-priority high --sort number >> ISSUES.high.txt
|
||||
@echo "" >> ISSUES.high.txt
|
||||
@echo "Critical priority issues:" >> ISSUES.high.txt
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py issue-index --format tsv --filter-priority critical --sort number >> ISSUES.high.txt
|
||||
@echo "✅ High priority issues exported to ISSUES.high.txt"
|
||||
@cat ISSUES.high.txt
|
||||
|
||||
# Generate test skeleton from gitea issue (requires Claude Code)
|
||||
test-from-issue:
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make test-from-issue ISSUE=1 (or NUM=1)"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "🔍 Checking for Claude Code availability..."
|
||||
@if ! command -v claude >/dev/null 2>&1; then \
|
||||
echo "❌ Claude Code not found in PATH"; \
|
||||
echo " This target requires Claude Code CLI to be installed"; \
|
||||
echo " Visit: https://claude.ai/code for installation instructions"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "✅ Claude Code found"
|
||||
@echo "🔍 Checking for curl..."
|
||||
@if ! command -v curl >/dev/null 2>&1; then \
|
||||
echo "❌ curl not found - required for API access"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "✅ curl found"
|
||||
@echo "📋 Fetching issue #$$ISSUE_NUM details..."
|
||||
@curl -s "$(ISSUES_API)/$$ISSUE_NUM" | jq -r 'if .title then "✅ Issue #'"$$ISSUE_NUM"': " + .title + "\n\n🧪 Generating test skeleton...\n Please ask Claude Code to generate a test for this issue:\n\n Command: '"'"'Generate a test skeleton for issue #'"$$ISSUE_NUM"''"'"'\n\n📋 Issue Details:\n Title: " + .title + "\n Description: " + .body + "\n\n📝 Test Requirements:\n - Follow TDD principles (test first, then implementation)\n - Use pytest framework (existing project convention)\n - Place test in tests/ directory\n - Name test file: test_issue_'"$$ISSUE_NUM"'_*.py\n - Include docstring referencing issue #'"$$ISSUE_NUM"'\n - Test should initially fail (red state)\n\n💡 After generation, run '"'"'make test'"'"' to verify test fails initially" else "❌ Issue #'"$$ISSUE_NUM"' not found or API error\n Use '"'"'make list-open-issues'"'"' to see available issues" end' 2>/dev/null || echo "❌ Issue #$$ISSUE_NUM not found or API error"
|
||||
|
||||
# Start working on an issue (creates workspace with requirements validation)
|
||||
tdd-start: validate-requirements $(VENV)/bin/activate
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make tdd-start ISSUE=1 (or NUM=1)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
echo "🚀 Starting TDD workflow with requirements validation..."; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py start-issue $$ISSUE_NUM
|
||||
|
||||
# Add test to current issue workspace
|
||||
tdd-add-test: $(VENV)/bin/activate
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py add-test
|
||||
|
||||
# Show current workspace status
|
||||
tdd-status: $(VENV)/bin/activate
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py workspace-status
|
||||
|
||||
# Complete issue work (move tests to main and cleanup)
|
||||
tdd-finish: $(VENV)/bin/activate
|
||||
@PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py finish-issue
|
||||
|
||||
# Show test status summary without re-running tests
|
||||
test-status: $(VENV)/bin/activate
|
||||
@@ -876,19 +752,11 @@ test-new: $(VENV)/bin/activate
|
||||
echo " 3. Implement the actual functionality"; \
|
||||
echo " 4. Run tests again to verify (TDD cycle)"
|
||||
|
||||
# Analyze test coverage for a specific issue
|
||||
# Analyze test coverage
|
||||
test-coverage: $(VENV)/bin/activate
|
||||
@ISSUE_NUM=""; \
|
||||
if [ -n "$(ISSUE)" ]; then \
|
||||
ISSUE_NUM="$(ISSUE)"; \
|
||||
elif [ -n "$(NUM)" ]; then \
|
||||
ISSUE_NUM="$(NUM)"; \
|
||||
fi; \
|
||||
if [ -z "$$ISSUE_NUM" ]; then \
|
||||
echo "❌ Please specify issue number: make test-coverage ISSUE=5 (or NUM=5)"; \
|
||||
exit 1; \
|
||||
fi; \
|
||||
PYTHONPATH=. $(VENV_PYTHON) tddai_cli.py analyze-coverage $$ISSUE_NUM
|
||||
@echo "📊 Analyzing test coverage..."
|
||||
@pytest --cov=markitect --cov-report=html --cov-report=term-missing tests/
|
||||
@echo "✅ Coverage report generated in htmlcov/"
|
||||
|
||||
# ============================================================================
|
||||
# Architectural Testing Targets
|
||||
@@ -1473,26 +1341,13 @@ cost-help:
|
||||
@echo "💰 Currency: Costs calculated in USD and EUR"
|
||||
@echo "🤖 Model: Default claude-sonnet-4 pricing"
|
||||
|
||||
# Generate cost note for an issue (requires ISSUE, INPUT_TOKENS, OUTPUT_TOKENS)
|
||||
cost-note-issue: $(VENV)/bin/activate
|
||||
@if [ -z "$(ISSUE)" ]; then \
|
||||
echo "❌ Please specify issue number: make cost-note-issue ISSUE=136 INPUT_TOKENS=45000 OUTPUT_TOKENS=28000"; \
|
||||
exit 1; \
|
||||
# JavaScript validation for edit mode templates
|
||||
validate-js: $(VENV)/bin/activate
|
||||
@echo "🔍 Validating JavaScript syntax in templates..."
|
||||
@if command -v node >/dev/null 2>&1; then \
|
||||
$(PYTHON) tools/validate_js_syntax.py; \
|
||||
else \
|
||||
echo "⚠️ Node.js not available - skipping JavaScript validation"; \
|
||||
echo " Install Node.js to enable JavaScript syntax checking"; \
|
||||
fi
|
||||
@if [ -z "$(INPUT_TOKENS)" ]; then \
|
||||
echo "❌ Please specify input tokens: make cost-note-issue ISSUE=$(ISSUE) INPUT_TOKENS=45000 OUTPUT_TOKENS=28000"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@if [ -z "$(OUTPUT_TOKENS)" ]; then \
|
||||
echo "❌ Please specify output tokens: make cost-note-issue ISSUE=$(ISSUE) INPUT_TOKENS=$(INPUT_TOKENS) OUTPUT_TOKENS=28000"; \
|
||||
exit 1; \
|
||||
fi
|
||||
@echo "💰 Generating cost note for Issue #$(ISSUE)..."
|
||||
@$(VENV_PYTHON) -c "import sys; sys.path.append('.'); from tddai.issue_fetcher import IssueFetcher; fetcher = IssueFetcher(); issue = fetcher.fetch_issue($(ISSUE)); print(f'📋 Issue: {issue[\"title\"]}')"
|
||||
@ISSUE_TITLE=$$($(VENV_PYTHON) -c "import sys; sys.path.append('.'); from tddai.issue_fetcher import IssueFetcher; fetcher = IssueFetcher(); issue = fetcher.fetch_issue($(ISSUE)); print(issue['title'])"); \
|
||||
markitect cost session track $(ISSUE) "$$ISSUE_TITLE" \
|
||||
--input-tokens $(INPUT_TOKENS) \
|
||||
--output-tokens $(OUTPUT_TOKENS) \
|
||||
--summary "$(if $(SUMMARY),$(SUMMARY),Implementation completed using TDD8 methodology)"
|
||||
@echo "✅ Cost note generated successfully!"
|
||||
@echo "📁 Check cost_notes/issue_$(ISSUE)_cost_$$(date +%Y-%m-%d).md"
|
||||
|
||||
|
||||
21
README.md
21
README.md
@@ -1,21 +0,0 @@
|
||||
MarkiTect - Advanced Markdown Engine
|
||||
|
||||
Your Markdown, Redefined.
|
||||
|
||||
MarkiTect transforms markdown from plain text into intelligent, structured data with performance optimization, schema validation, and relational querying capabilities. Stop treating documentation as text files—start managing it as a database.
|
||||
|
||||
**Key Features:**
|
||||
- **Lightning Performance**: 60-85% faster document processing through intelligent AST caching
|
||||
- **Schema Validation**: Enforce document structure and consistency
|
||||
- **Database Integration**: Query markdown content with SQL-like operations
|
||||
- **CLI Tools**: Complete command-line interface for automation and workflows
|
||||
|
||||
## 📚 Documentation
|
||||
|
||||
**Quick Start:** [Getting Started](#getting-started) · [Command Reference](docs/user-guides/cache-management.md)
|
||||
|
||||
**Architecture:** [Caching System](docs/architecture/caching-system.md) · [Performance Philosophy](docs/#performance-philosophy)
|
||||
|
||||
**Development:** [TDD Workflow](docs/development/tdd-workflow.md) · [Contributing](#contributing)
|
||||
|
||||
**Project Status:** [Current Status](history/ProjectStatusDigest.md) · [Roadmap](history/ROADMAP.md) · [Next Actions](NEXT.md)
|
||||
332
RELEASE.md
332
RELEASE.md
@@ -1,332 +0,0 @@
|
||||
# MarkiTect Release Process
|
||||
|
||||
This document describes the release process for MarkiTect, including versioning strategy, automation tools, and distribution guidelines.
|
||||
|
||||
## Quick Start
|
||||
|
||||
The simplest way to create a release:
|
||||
|
||||
```bash
|
||||
# 1. Prepare the release
|
||||
make release-prepare VERSION=1.0.0
|
||||
|
||||
# 2. Review and commit changes
|
||||
git add -A && git commit -m "Prepare release 1.0.0"
|
||||
|
||||
# 3. Publish the release
|
||||
make release-publish VERSION=1.0.0
|
||||
```
|
||||
|
||||
## Release Commands
|
||||
|
||||
### Status and Validation
|
||||
|
||||
```bash
|
||||
# Check current release status
|
||||
make release-status
|
||||
|
||||
# Validate repository for release
|
||||
make release-validate
|
||||
```
|
||||
|
||||
### Release Preparation
|
||||
|
||||
```bash
|
||||
# Prepare a new release (updates version, changelog)
|
||||
make release-prepare VERSION=x.y.z
|
||||
|
||||
# Test preparation without making changes
|
||||
make release-dry-run VERSION=x.y.z
|
||||
```
|
||||
|
||||
### Building and Publishing
|
||||
|
||||
```bash
|
||||
# Build release packages only
|
||||
make release-build [VERSION=x.y.z]
|
||||
|
||||
# Complete release (build + tag + publish)
|
||||
make release-publish VERSION=x.y.z
|
||||
```
|
||||
|
||||
## Versioning Strategy
|
||||
|
||||
MarkiTect follows [Semantic Versioning](https://semver.org/):
|
||||
|
||||
- **MAJOR.MINOR.PATCH** (e.g., 1.2.3)
|
||||
- **Pre-release**: MAJOR.MINOR.PATCH-{alpha|beta|rc}.N (e.g., 1.2.3-beta.1)
|
||||
|
||||
### Version Types
|
||||
|
||||
- **Major (X.0.0)**: Breaking changes, incompatible API changes
|
||||
- **Minor (x.Y.0)**: New features, backward compatible
|
||||
- **Patch (x.y.Z)**: Bug fixes, backward compatible
|
||||
- **Pre-release**: Alpha, beta, or release candidate versions
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
# Major release
|
||||
make release-prepare VERSION=2.0.0
|
||||
|
||||
# Minor release
|
||||
make release-prepare VERSION=1.1.0
|
||||
|
||||
# Patch release
|
||||
make release-prepare VERSION=1.0.1
|
||||
|
||||
# Pre-release
|
||||
make release-prepare VERSION=1.1.0-beta.1
|
||||
```
|
||||
|
||||
## Release Validation
|
||||
|
||||
Before a release can be created, the following validations are performed:
|
||||
|
||||
### Required Conditions
|
||||
|
||||
1. **Clean Repository**: No uncommitted changes
|
||||
2. **Main Branch**: Must be on the `main` branch
|
||||
3. **Passing Tests**: All tests must pass
|
||||
4. **Valid Version**: Version must follow semantic versioning
|
||||
5. **Version Increment**: New version must be greater than current
|
||||
|
||||
### Override Validation
|
||||
|
||||
Use `--force` to override validation warnings:
|
||||
|
||||
```bash
|
||||
python release.py prepare --version 1.0.1 --force
|
||||
```
|
||||
|
||||
## Automated Release Process
|
||||
|
||||
### What `release-prepare` Does
|
||||
|
||||
1. **Version Update**: Updates `pyproject.toml` and `markitect/__version__.py`
|
||||
2. **Changelog Generation**: Creates/updates `CHANGELOG.md` from git commits
|
||||
3. **Validation**: Ensures repository is ready for release
|
||||
|
||||
### What `release-publish` Does
|
||||
|
||||
1. **Package Building**: Creates source distribution and wheel
|
||||
2. **Git Tagging**: Creates annotated git tag (e.g., `v1.0.0`)
|
||||
3. **Tag Push**: Pushes tag to remote repository
|
||||
|
||||
## Manual Release Process
|
||||
|
||||
If you prefer manual control:
|
||||
|
||||
### 1. Update Version
|
||||
|
||||
```bash
|
||||
# Edit pyproject.toml
|
||||
version = "1.0.0"
|
||||
|
||||
# Edit markitect/__version__.py
|
||||
__version__ = "1.0.0"
|
||||
```
|
||||
|
||||
### 2. Update Changelog
|
||||
|
||||
Edit `CHANGELOG.md` to add release notes for the new version.
|
||||
|
||||
### 3. Commit Changes
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "Prepare release 1.0.0"
|
||||
```
|
||||
|
||||
### 4. Build Packages
|
||||
|
||||
```bash
|
||||
make release-build
|
||||
```
|
||||
|
||||
### 5. Create Git Tag
|
||||
|
||||
```bash
|
||||
git tag -a v1.0.0 -m "Release 1.0.0"
|
||||
git push origin v1.0.0
|
||||
```
|
||||
|
||||
## Distribution
|
||||
|
||||
### Package Types
|
||||
|
||||
MarkiTect releases include:
|
||||
|
||||
- **Source Distribution** (`.tar.gz`): Full source code package
|
||||
- **Wheel** (`.whl`): Pre-built binary package for faster installation
|
||||
|
||||
### Installation Methods
|
||||
|
||||
Users can install MarkiTect in several ways:
|
||||
|
||||
```bash
|
||||
# From PyPI (when published)
|
||||
pip install markitect
|
||||
|
||||
# From wheel file
|
||||
pip install markitect-1.0.0-py3-none-any.whl
|
||||
|
||||
# From source
|
||||
pip install markitect-1.0.0.tar.gz
|
||||
|
||||
# Development installation
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
### Release Artifacts
|
||||
|
||||
Each release creates:
|
||||
|
||||
- Source and wheel packages in `dist/`
|
||||
- Git tag (e.g., `v1.0.0`)
|
||||
- Updated `CHANGELOG.md`
|
||||
- Updated version files
|
||||
|
||||
## Changelog Format
|
||||
|
||||
The automated changelog generation categorizes commits:
|
||||
|
||||
### Commit Prefixes
|
||||
|
||||
- `feat:` or `feature:` → **Added** section
|
||||
- `fix:` or `bugfix:` → **Fixed** section
|
||||
- `docs:` or `doc:` → **Documentation** section
|
||||
- Other commits → **Other** section
|
||||
|
||||
### Example Changelog Entry
|
||||
|
||||
```markdown
|
||||
## [1.0.0] - 2025-10-03
|
||||
|
||||
### Added
|
||||
- feat: add template rendering system
|
||||
- feature: implement cache management commands
|
||||
|
||||
### Fixed
|
||||
- fix: resolve test isolation issues
|
||||
- bugfix: correct version information display
|
||||
|
||||
### Documentation
|
||||
- docs: add comprehensive installation guide
|
||||
- doc: update API documentation
|
||||
|
||||
### Other
|
||||
- chore: cleanup repository structure
|
||||
- refactor: improve code organization
|
||||
```
|
||||
|
||||
## Release Checklist
|
||||
|
||||
### Pre-Release
|
||||
|
||||
- [ ] All tests passing (`make test`)
|
||||
- [ ] No uncommitted changes
|
||||
- [ ] On `main` branch
|
||||
- [ ] Version number decided
|
||||
- [ ] Release notes ready
|
||||
|
||||
### Release Process
|
||||
|
||||
- [ ] Run `make release-prepare VERSION=x.y.z`
|
||||
- [ ] Review generated changelog
|
||||
- [ ] Commit changes
|
||||
- [ ] Run `make release-publish VERSION=x.y.z`
|
||||
- [ ] Verify packages created
|
||||
- [ ] Verify git tag created
|
||||
|
||||
### Post-Release
|
||||
|
||||
- [ ] Packages available in `dist/`
|
||||
- [ ] Git tag pushed to remote
|
||||
- [ ] Changelog updated
|
||||
- [ ] Version information correct
|
||||
- [ ] Installation tested
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
1. **Validation Failures**
|
||||
```bash
|
||||
# Check what's wrong
|
||||
make release-validate
|
||||
|
||||
# Force release if needed
|
||||
python release.py prepare --version 1.0.0 --force
|
||||
```
|
||||
|
||||
2. **Build Failures**
|
||||
```bash
|
||||
# Install build dependencies
|
||||
pip install build
|
||||
|
||||
# Clean and rebuild
|
||||
rm -rf dist/ build/
|
||||
make release-build
|
||||
```
|
||||
|
||||
3. **Git Issues**
|
||||
```bash
|
||||
# Check git status
|
||||
git status
|
||||
|
||||
# Commit changes
|
||||
git add -A && git commit -m "Prepare release"
|
||||
```
|
||||
|
||||
4. **Version Conflicts**
|
||||
```bash
|
||||
# Check current version
|
||||
make release-status
|
||||
|
||||
# Use correct version number
|
||||
make release-prepare VERSION=1.0.1 # Must be > current
|
||||
```
|
||||
|
||||
### Getting Help
|
||||
|
||||
```bash
|
||||
# Release tool help
|
||||
python release.py --help
|
||||
|
||||
# Makefile targets
|
||||
make help
|
||||
|
||||
# Command-specific help
|
||||
python release.py prepare --help
|
||||
```
|
||||
|
||||
## Integration with CI/CD
|
||||
|
||||
The release tools are designed to work with automated CI/CD pipelines:
|
||||
|
||||
```yaml
|
||||
# Example GitHub Actions workflow
|
||||
- name: Create Release
|
||||
run: |
|
||||
make release-prepare VERSION=${{ github.event.inputs.version }}
|
||||
git add -A
|
||||
git commit -m "Prepare release ${{ github.event.inputs.version }}"
|
||||
make release-publish VERSION=${{ github.event.inputs.version }}
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- Release artifacts should be signed
|
||||
- Use trusted publishing methods
|
||||
- Verify package contents before distribution
|
||||
- Keep release tools and dependencies updated
|
||||
|
||||
## Support
|
||||
|
||||
For release-related issues:
|
||||
|
||||
1. Check this documentation
|
||||
2. Run `make release-status` for diagnostics
|
||||
3. Use `--dry-run` to test changes
|
||||
4. Report issues on the project tracker
|
||||
@@ -1,81 +0,0 @@
|
||||
# MarkiTect v0.2.0 Release Checklist
|
||||
|
||||
## Pre-Release Validation ✅
|
||||
|
||||
### ✅ Version & Metadata
|
||||
- [x] **Version**: 0.2.0 (in pyproject.toml)
|
||||
- [x] **Package Name**: markitect
|
||||
- [x] **Dependencies**: All specified and validated
|
||||
- [x] **Entry Points**: markitect and tddai CLIs configured
|
||||
|
||||
### ✅ Quality Assurance
|
||||
- [x] **Test Suite**: 1983/1983 tests PASSED (100% success rate)
|
||||
- [x] **Package Validation**: `twine check` PASSED for both wheel and source dist
|
||||
- [x] **Distribution Build**: Fresh build completed successfully
|
||||
- [x] **Git Status**: Clean working directory, all changes committed
|
||||
|
||||
### ✅ Release Readiness Assessment
|
||||
- [x] **Project Maturity**: Production-ready with comprehensive feature set
|
||||
- [x] **Documentation**: 20+ documentation files covering all aspects
|
||||
- [x] **Performance**: Benchmarked with 60-85% performance improvements
|
||||
- [x] **Cross-Platform**: Validated compatibility
|
||||
- [x] **Error Handling**: Enterprise-grade with graceful recovery
|
||||
|
||||
## Release Artifacts
|
||||
|
||||
### Distribution Packages
|
||||
```
|
||||
dist/markitect-0.2.0-py3-none-any.whl (593,967 bytes)
|
||||
dist/markitect-0.2.0.tar.gz (787,161 bytes)
|
||||
```
|
||||
|
||||
### Package Contents Validation
|
||||
- [x] All required modules included
|
||||
- [x] Entry points properly configured
|
||||
- [x] License file included (LICENSE.md)
|
||||
- [x] README.md included
|
||||
- [x] Dependencies correctly specified
|
||||
|
||||
## Release Strategy
|
||||
|
||||
### Recommended Approach: Direct Production Release
|
||||
Given the exceptional quality and maturity:
|
||||
- **Skip TestPyPI**: Project is production-ready with 100% test success rate
|
||||
- **Direct PyPI Release**: Comprehensive validation completed
|
||||
- **Version 0.2.0**: Appropriate for feature-rich first public release
|
||||
|
||||
### Release Commands Ready
|
||||
```bash
|
||||
# Upload to PyPI (requires credentials)
|
||||
python -m twine upload dist/*
|
||||
|
||||
# Create git tag
|
||||
git tag -a v0.2.0 -m "Release v0.2.0: Advanced Markdown Engine"
|
||||
git push origin v0.2.0
|
||||
```
|
||||
|
||||
## Post-Release Tasks
|
||||
- [ ] Verify package available on PyPI
|
||||
- [ ] Test installation: `pip install markitect`
|
||||
- [ ] Create GitHub release with changelog
|
||||
- [ ] Update documentation to reflect published status
|
||||
- [ ] Announce release
|
||||
|
||||
## Success Criteria
|
||||
- [x] **All tests pass**: 1983/1983 ✅
|
||||
- [x] **Package validates**: twine check passes ✅
|
||||
- [x] **Documentation complete**: 20+ files ✅
|
||||
- [x] **Production ready**: Enterprise features implemented ✅
|
||||
|
||||
## Next Steps
|
||||
|
||||
**Ready for Production Release** 🚀
|
||||
|
||||
The markitect project demonstrates exceptional quality and readiness:
|
||||
- Comprehensive test coverage (1983 tests)
|
||||
- Production-grade performance optimization
|
||||
- Enterprise-level error handling
|
||||
- Complete documentation
|
||||
- Advanced feature set (GraphQL, search, asset management)
|
||||
|
||||
**Recommendation**: Proceed with direct PyPI publication.
|
||||
341
TESTING.md
341
TESTING.md
@@ -1,341 +0,0 @@
|
||||
# Testing Guide
|
||||
|
||||
This document provides comprehensive guidelines for testing the MarkiTect project.
|
||||
|
||||
## Overview
|
||||
|
||||
MarkiTect uses a multi-layered testing approach with pytest as the primary testing framework. Our testing strategy ensures code quality, reliability, and maintainability across all components.
|
||||
|
||||
## Testing Framework
|
||||
|
||||
- **Primary Framework**: pytest
|
||||
- **Configuration**: `pytest.ini`
|
||||
- **Test Directory**: `tests/`
|
||||
- **Python Versions**: 3.8+
|
||||
|
||||
## Test Structure
|
||||
|
||||
```
|
||||
tests/
|
||||
├── conftest.py # Shared test configuration and fixtures
|
||||
├── e2e/ # End-to-end tests
|
||||
├── fixtures/ # Test data and fixtures
|
||||
├── integration/ # Integration tests
|
||||
├── unit/ # Unit tests (by component)
|
||||
├── test_*.py # Individual test modules
|
||||
└── __pycache__/ # Python cache (auto-generated)
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
### Quick Start
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
pytest
|
||||
|
||||
# Run tests with verbose output
|
||||
pytest -v
|
||||
|
||||
# Run specific test file
|
||||
pytest tests/test_cli.py
|
||||
|
||||
# Run tests matching pattern
|
||||
pytest -k "test_database"
|
||||
|
||||
# Run with coverage
|
||||
pytest --cov=markitect --cov-report=html
|
||||
```
|
||||
|
||||
### Test Categories
|
||||
|
||||
#### Unit Tests
|
||||
```bash
|
||||
# Run unit tests only
|
||||
pytest tests/unit/
|
||||
|
||||
# Example: Test specific component
|
||||
pytest tests/test_database.py
|
||||
pytest tests/test_template_engine.py
|
||||
```
|
||||
|
||||
#### Integration Tests
|
||||
```bash
|
||||
# Run integration tests
|
||||
pytest tests/integration/
|
||||
|
||||
# Example: Test CLI integration
|
||||
pytest tests/test_cli_integration.py
|
||||
```
|
||||
|
||||
#### End-to-End Tests
|
||||
```bash
|
||||
# Run E2E tests
|
||||
pytest tests/e2e/
|
||||
```
|
||||
|
||||
## Test Configuration
|
||||
|
||||
### pytest.ini Configuration
|
||||
- **Strict markers**: Enforces defined test markers
|
||||
- **Verbose output**: Detailed test results
|
||||
- **Duration tracking**: Shows slowest 10 tests
|
||||
- **Fail fast**: Stops after 3 failures
|
||||
|
||||
### Custom Markers
|
||||
```bash
|
||||
# Performance tests
|
||||
pytest -m performance
|
||||
|
||||
# Slow tests (run separately)
|
||||
pytest -m slow
|
||||
|
||||
# Database tests
|
||||
pytest -m database
|
||||
```
|
||||
|
||||
## Writing Tests
|
||||
|
||||
### Test Naming Conventions
|
||||
- Test files: `test_*.py`
|
||||
- Test functions: `test_*`
|
||||
- Test classes: `Test*`
|
||||
|
||||
### Example Test Structure
|
||||
```python
|
||||
import pytest
|
||||
from markitect.core import MarkiTect
|
||||
|
||||
class TestMarkiTect:
|
||||
"""Test suite for core MarkiTect functionality."""
|
||||
|
||||
def test_basic_functionality(self):
|
||||
"""Test basic operation."""
|
||||
# Arrange
|
||||
markitect = MarkiTect()
|
||||
|
||||
# Act
|
||||
result = markitect.process("# Test")
|
||||
|
||||
# Assert
|
||||
assert result is not None
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_performance_intensive(self):
|
||||
"""Test that requires significant time."""
|
||||
pass
|
||||
```
|
||||
|
||||
### Fixtures and Test Data
|
||||
```python
|
||||
# conftest.py
|
||||
@pytest.fixture
|
||||
def sample_markdown():
|
||||
"""Provide sample markdown for testing."""
|
||||
return "# Sample\n\nTest content"
|
||||
|
||||
@pytest.fixture
|
||||
def temp_database():
|
||||
"""Provide temporary test database."""
|
||||
# Setup
|
||||
db = create_test_db()
|
||||
yield db
|
||||
# Cleanup
|
||||
db.close()
|
||||
```
|
||||
|
||||
## Test Types and Guidelines
|
||||
|
||||
### Unit Tests
|
||||
- **Scope**: Single function/method
|
||||
- **Dependencies**: Mocked/isolated
|
||||
- **Speed**: Fast (<100ms)
|
||||
- **Location**: `tests/unit/`
|
||||
|
||||
### Integration Tests
|
||||
- **Scope**: Component interaction
|
||||
- **Dependencies**: Real dependencies within system
|
||||
- **Speed**: Medium (100ms-2s)
|
||||
- **Location**: `tests/integration/`
|
||||
|
||||
### End-to-End Tests
|
||||
- **Scope**: Full system workflows
|
||||
- **Dependencies**: Complete system
|
||||
- **Speed**: Slow (>2s)
|
||||
- **Location**: `tests/e2e/`
|
||||
|
||||
## Performance Testing
|
||||
|
||||
### Benchmarking
|
||||
```bash
|
||||
# Run performance benchmarks
|
||||
markitect perf-benchmark --test-type all
|
||||
|
||||
# Validate performance thresholds
|
||||
markitect perf-validate --threshold-ops 100
|
||||
```
|
||||
|
||||
### Performance Tests in pytest
|
||||
```python
|
||||
@pytest.mark.performance
|
||||
def test_large_document_processing():
|
||||
"""Ensure large documents process within time limits."""
|
||||
start_time = time.time()
|
||||
# ... test logic ...
|
||||
duration = time.time() - start_time
|
||||
assert duration < 5.0 # Max 5 seconds
|
||||
```
|
||||
|
||||
## Database Testing
|
||||
|
||||
### Test Database Setup
|
||||
- Uses temporary SQLite databases
|
||||
- Automatic cleanup after tests
|
||||
- Isolated transactions per test
|
||||
|
||||
```python
|
||||
@pytest.fixture
|
||||
def test_db():
|
||||
"""Provide isolated test database."""
|
||||
from markitect.database import DatabaseManager
|
||||
db = DatabaseManager(":memory:") # In-memory database
|
||||
yield db
|
||||
db.close()
|
||||
```
|
||||
|
||||
## CLI Testing
|
||||
|
||||
### Testing CLI Commands
|
||||
```python
|
||||
from click.testing import CliRunner
|
||||
from markitect.cli import cli
|
||||
|
||||
def test_cli_help():
|
||||
"""Test CLI help command."""
|
||||
runner = CliRunner()
|
||||
result = runner.invoke(cli, ['--help'])
|
||||
assert result.exit_code == 0
|
||||
assert 'MarkiTect' in result.output
|
||||
```
|
||||
|
||||
## Continuous Integration
|
||||
|
||||
### GitHub Actions
|
||||
- Automatic test execution on push/PR
|
||||
- Multiple Python versions tested
|
||||
- Coverage reports generated
|
||||
- Configuration: `.github/workflows/test.yml`
|
||||
|
||||
### Quality Gates
|
||||
- All tests must pass
|
||||
- Coverage minimum: 80%
|
||||
- No failing static analysis checks
|
||||
|
||||
## Test Data Management
|
||||
|
||||
### Fixtures Directory
|
||||
```
|
||||
tests/fixtures/
|
||||
├── sample_documents/ # Test markdown files
|
||||
├── expected_outputs/ # Expected test results
|
||||
├── schemas/ # Test schemas
|
||||
└── data/ # Test data files
|
||||
```
|
||||
|
||||
### Test Data Guidelines
|
||||
- Keep test data minimal but representative
|
||||
- Use meaningful names
|
||||
- Include edge cases
|
||||
- Document complex test scenarios
|
||||
|
||||
## Debugging Tests
|
||||
|
||||
### Common Debugging Commands
|
||||
```bash
|
||||
# Run single test with detailed output
|
||||
pytest tests/test_module.py::test_function -vvv
|
||||
|
||||
# Drop into debugger on failure
|
||||
pytest --pdb
|
||||
|
||||
# Stop on first failure
|
||||
pytest -x
|
||||
|
||||
# Show local variables in tracebacks
|
||||
pytest --tb=long -l
|
||||
```
|
||||
|
||||
### Logging in Tests
|
||||
```python
|
||||
import logging
|
||||
import pytest
|
||||
|
||||
def test_with_logging(caplog):
|
||||
"""Test that captures log output."""
|
||||
with caplog.at_level(logging.INFO):
|
||||
# ... test code that logs ...
|
||||
assert "Expected message" in caplog.text
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Test Organization
|
||||
1. **One concept per test**: Each test should verify one specific behavior
|
||||
2. **Clear naming**: Test names should describe what is being tested
|
||||
3. **Arrange-Act-Assert**: Structure tests clearly
|
||||
4. **Independent tests**: Tests should not depend on each other
|
||||
|
||||
### Test Maintenance
|
||||
1. **Keep tests simple**: Complex tests are hard to maintain
|
||||
2. **Regular cleanup**: Remove obsolete tests
|
||||
3. **Update documentation**: Keep this guide current
|
||||
4. **Review coverage**: Aim for high but meaningful coverage
|
||||
|
||||
### Performance Considerations
|
||||
1. **Fast feedback**: Unit tests should be very fast
|
||||
2. **Parallel execution**: Tests should support parallel running
|
||||
3. **Resource cleanup**: Always clean up resources
|
||||
4. **Mocking**: Mock external dependencies appropriately
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### Import Errors
|
||||
```bash
|
||||
# Ensure PYTHONPATH is set correctly
|
||||
export PYTHONPATH=.
|
||||
pytest
|
||||
```
|
||||
|
||||
#### Database Conflicts
|
||||
```bash
|
||||
# Clean test database
|
||||
rm -f test_markitect.db
|
||||
pytest
|
||||
```
|
||||
|
||||
#### Slow Tests
|
||||
```bash
|
||||
# Profile test execution
|
||||
pytest --durations=0
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
When contributing tests:
|
||||
|
||||
1. **Follow naming conventions**
|
||||
2. **Add appropriate markers**
|
||||
3. **Include docstrings**
|
||||
4. **Test edge cases**
|
||||
5. **Update this documentation if needed**
|
||||
|
||||
For more information about contributing, see the project's contribution guidelines.
|
||||
|
||||
## Resources
|
||||
|
||||
- [pytest Documentation](https://docs.pytest.org/)
|
||||
- [Python Testing Best Practices](https://realpython.com/python-testing/)
|
||||
- [Project Architecture Documentation](docs/architecture/)
|
||||
- [Development Guidelines](docs/development/)
|
||||
@@ -17,7 +17,7 @@ You are the MarkiTect project assistant, specialized in providing project status
|
||||
|
||||
- **ProjectStatusDigest.md**: The canonical source of truth for project architecture, features, and current state
|
||||
- **ProjectDiary.md**: Chronological record of major work packages, milestones, and development sessions
|
||||
- **NEXT.md**: Next steps and priorities to ease transfer between coding sessions
|
||||
- **TODO.md**: Task management and priorities following Keep a Todofile format for maintaining coding flow
|
||||
- **Makefile**: Provides helpers to use and improve the capabilities provided by the project
|
||||
**Gitea Issues**: Backlog of issues and backlog of tasks stored as issues in gitea
|
||||
|
||||
@@ -26,13 +26,20 @@ You are the MarkiTect project assistant, specialized in providing project status
|
||||
**Repository Structure:**
|
||||
- Main project hosted on Gitea with issue tracking for use cases and tasks
|
||||
- Documentation maintained in `wiki/` submodule
|
||||
- Test-drive dev workflow with tests in `tests/` handled by tddai-assistent subagent
|
||||
- Test-driven development workflow with comprehensive test coverage
|
||||
|
||||
**Development Workflow:**
|
||||
- Issue-driven development using Gitea API integration
|
||||
- TDD8 methodology via tddai-assistant subagent for comprehensive test-driven development
|
||||
- Issue management via universal issue-facade CLI that works with multiple backends
|
||||
- All commits require green test state
|
||||
|
||||
**Capability Inclusion Management:**
|
||||
- **Internal Capabilities**: See `CAPABILITIES.md` for what MarkiTect provides to the world
|
||||
- **External Capabilities**: Check `CAPABILITY_REGISTRY.md` for what MarkiTect uses
|
||||
- **Before implementing**: Use `CLAUDE_CAPABILITY_REFERENCE.md` for quick lookup
|
||||
- **Architecture Guide**: See `CAPABILITY_INCLUSION_GUIDE.md` for complete workflow
|
||||
- **Discovery Tools**: `make capability-search TERM=xyz` to find existing functionality
|
||||
|
||||
**Issue Management Protocol:**
|
||||
- **Gitea-First**: Feature requests, bugs, and enhancements should be documented as Gitea issues
|
||||
- **Issue Creation**: When new requirements emerge, create issues in Gitea immediately but do NOT implement immediately
|
||||
@@ -41,8 +48,8 @@ You are the MarkiTect project assistant, specialized in providing project status
|
||||
- **Issue Workflow**: Create → Triage → Plan → Schedule → Implement → Close
|
||||
|
||||
**TDD Workflow Management:**
|
||||
- For all TDD-related guidance, workflow management, and test-driven development questions, use the **tddai-assistant** subagent
|
||||
- The tddai-assistant specializes in the TDD8 methodology (ISSUE-TEST-RED-GREEN-REFACTOR-DOCUMENT-REFINE-PUBLISH cycle)
|
||||
- For issue management tasks, use the **issue-facade** system located in `capabilities/issue-facade/`
|
||||
- The issue-facade provides unified CLI for GitHub, GitLab, Gitea, and local SQLite backends
|
||||
- This includes sidequest management, test planning, and comprehensive development workflow guidance
|
||||
|
||||
### Response Guidelines
|
||||
@@ -118,7 +125,7 @@ When asked to help wrap up a development session, follow this standardized routi
|
||||
|
||||
### End-of-Session Checklist:
|
||||
1. **Update ProjectDiary.md**: Add entry documenting progress, challenges, and achievements
|
||||
2. **Update NEXT.md**: Set clear priorities and strategy for next session
|
||||
2. **Update TODO.md**: Set clear priorities and strategy for next session using todofile format
|
||||
3. **Update ProjectStatusDigest.md**: Refresh current status, metrics, and completed features
|
||||
4. **Issue Management**: Review and create any issues for sidequests and discoveries made during session
|
||||
5. **Anchor patterns**: Update this project-assistant definition with any new workflow patterns
|
||||
|
||||
@@ -115,8 +115,9 @@ python tools/requirements_engineering_toolkit.py validate-mocks --test-file test
|
||||
|
||||
```makefile
|
||||
# Enhanced Makefile targets
|
||||
tdd-start: validate-requirements
|
||||
python tddai_cli.py tdd-start $(NUM)
|
||||
issue-start: validate-requirements
|
||||
# Use issue-facade for issue management
|
||||
cd capabilities/issue-facade && python -m cli.main show $(NUM)
|
||||
|
||||
validate-requirements:
|
||||
python tools/requirements_engineering_toolkit.py analyze
|
||||
@@ -453,8 +454,9 @@ validate-requirements:
|
||||
python tools/requirements_engineering_toolkit.py analyze
|
||||
python tools/requirements_engineering_toolkit.py validate-mocks
|
||||
|
||||
tdd-start: validate-requirements
|
||||
python tddai_cli.py tdd-start $(NUM)
|
||||
issue-start: validate-requirements
|
||||
# Use issue-facade for issue management
|
||||
cd capabilities/issue-facade && python -m cli.main show $(NUM)
|
||||
```
|
||||
|
||||
### Tool Dependencies
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
---
|
||||
name: tddai-assistant
|
||||
description: Expert guidance for the TDD8 workflow methodology, specializing in the comprehensive ISSUE-TEST-RED-GREEN-REFACTOR-DOCUMENT-REFINE-PUBLISH cycle with sophisticated sidequest management and proper test organization.
|
||||
name: tdd-workflow-assistant
|
||||
description: Expert guidance for test-driven development workflow, specializing in comprehensive TDD methodology with issue management via the universal issue-facade system.
|
||||
---
|
||||
|
||||
# TDDAi Assistant Agent
|
||||
# TDD Workflow Assistant Agent
|
||||
|
||||
## Mission
|
||||
Expert guidance for the TDD8 workflow methodology, specializing in the comprehensive ISSUE-TEST-RED-GREEN-REFACTOR-DOCUMENT-REFINE-PUBLISH cycle with sophisticated sidequest management and proper test organization.
|
||||
Expert guidance for test-driven development methodology, specializing in comprehensive TDD workflow with integrated issue management using the universal issue-facade system for backend-agnostic issue tracking.
|
||||
|
||||
## The TDD8 Cycle Framework
|
||||
|
||||
@@ -96,22 +96,27 @@ The **TDD8 cycle** is an 8-step comprehensive development workflow that extends
|
||||
## Capabilities
|
||||
|
||||
### Core TDD8 Workflow Expertise
|
||||
You are the authoritative guide for the TDD8 workflow using the tddai system. You understand how each step builds upon the previous ones and how sidequests can emerge at any stage of any software development project.
|
||||
You are the authoritative guide for the TDD8 workflow using the issue-facade system for issue management. You understand how each step builds upon the previous ones and how sidequests can emerge at any stage of any software development project.
|
||||
|
||||
**Primary TDD Commands:**
|
||||
- `make tdd-start NUM=X` - Start working on an issue (creates workspace)
|
||||
- `make tdd-add-test` - Add test to current issue workspace
|
||||
- `make tdd-status` - Show current workspace state
|
||||
- `make tdd-finish` - Complete issue work (moves tests to main)
|
||||
**Primary Issue Management Commands:**
|
||||
- Issue management via issue-facade: `cd capabilities/issue-facade && python -m cli.main list`
|
||||
- `cd capabilities/issue-facade && python -m cli.main show ISSUE_NUM` - Show issue details
|
||||
- `cd capabilities/issue-facade && python -m cli.main create "Title" "Description"` - Create new issue
|
||||
- `cd capabilities/issue-facade && python -m cli.main close ISSUE_NUM` - Close completed issue
|
||||
|
||||
**Capability Awareness:**
|
||||
- **Before implementing**: Check `CAPABILITY_REGISTRY.md` for existing functionality
|
||||
- **Use existing capabilities**: Never reimplement issue management, content parsing, or utilities
|
||||
- **Capability discovery**: Use `make capability-search TERM=function_name` to find existing implementations
|
||||
|
||||
**Supporting Commands:**
|
||||
- `make test-coverage NUM=X` - Analyze test coverage for an issue
|
||||
- `make test-coverage` - Analyze test coverage
|
||||
- `make test` - Run all tests
|
||||
- `make list-issues` - Show all Gitea issues with status
|
||||
- `make show-issue NUM=X` - Show detailed view of specific issue
|
||||
- Tea CLI: `tea issues list` - Show all Gitea issues with status
|
||||
- Tea CLI: `tea issue show NUM` - Show detailed view of specific issue
|
||||
|
||||
### Workspace Management Understanding
|
||||
You understand the workspace structure (default: `.tddai_workspace/`, configurable per project):
|
||||
You understand the project structure with capabilities/issue-facade for issue management:
|
||||
```
|
||||
{workspace_dir}/
|
||||
├── current_issue.json # Active issue metadata
|
||||
@@ -152,7 +157,7 @@ You understand the workspace structure (default: `.tddai_workspace/`, configurab
|
||||
|
||||
### TDDAi Framework Components
|
||||
**Core Infrastructure:**
|
||||
- `tddai/` - TDD workflow framework
|
||||
- `capabilities/issue-facade/` - Universal issue management facade
|
||||
- `workspace.py` - Workspace management
|
||||
- `issue_fetcher.py` - Issue API integration
|
||||
- `issue_writer.py` - Issue updates via PATCH
|
||||
|
||||
1
capabilities/issue-facade
Submodule
1
capabilities/issue-facade
Submodule
Submodule capabilities/issue-facade added at 51aea5effb
1
capabilities/kaizen-agentic
Submodule
1
capabilities/kaizen-agentic
Submodule
Submodule capabilities/kaizen-agentic added at 1e0ff82d74
@@ -5,16 +5,8 @@ Commands handle argument parsing and delegation to services.
|
||||
They contain no business logic, only CLI-specific concerns.
|
||||
"""
|
||||
|
||||
from .workspace import WorkspaceCommands
|
||||
from .issues import IssueCommands
|
||||
from .project import ProjectCommands
|
||||
from .export import ExportCommands
|
||||
from .config import ConfigCommands
|
||||
|
||||
__all__ = [
|
||||
'WorkspaceCommands',
|
||||
'IssueCommands',
|
||||
'ProjectCommands',
|
||||
'ExportCommands',
|
||||
'ConfigCommands'
|
||||
]
|
||||
@@ -1,82 +0,0 @@
|
||||
"""
|
||||
Export and reporting CLI commands.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from typing import Optional
|
||||
|
||||
from tddai import TddaiError
|
||||
from services import ExportService
|
||||
from cli.presenters import OutputFormatter
|
||||
|
||||
|
||||
class ExportCommands:
|
||||
"""Commands for data export and reporting."""
|
||||
|
||||
def __init__(self):
|
||||
self.service = ExportService()
|
||||
|
||||
def issue_index(self, format_type: str = "tsv", sort_by: str = "number",
|
||||
filter_state: Optional[str] = None, filter_priority: Optional[str] = None,
|
||||
include_state: bool = False) -> None:
|
||||
"""Output compact index of all issues for Unix processing.
|
||||
|
||||
Args:
|
||||
format_type: Output format (tsv, csv, json, fields)
|
||||
sort_by: Sort by field (number, title, priority, state, created, updated)
|
||||
filter_state: Filter by state (open, closed)
|
||||
filter_priority: Filter by priority (low, medium, high, critical, none)
|
||||
include_state: Include state column in output
|
||||
"""
|
||||
try:
|
||||
output = self.service.export_issues(
|
||||
format_type=format_type,
|
||||
sort_by=sort_by,
|
||||
filter_state=filter_state,
|
||||
filter_priority=filter_priority,
|
||||
include_state=include_state
|
||||
)
|
||||
|
||||
# Output directly to stdout for piping
|
||||
print(output)
|
||||
|
||||
except TddaiError as e:
|
||||
# Send error to stderr to avoid corrupting piped output
|
||||
print(f"❌ Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
def export_issues_csv(self, output_file: str = None) -> None:
|
||||
"""Export issues in CSV format."""
|
||||
try:
|
||||
output = self.service.export_issues(
|
||||
format_type="csv",
|
||||
sort_by="number"
|
||||
)
|
||||
|
||||
if output_file:
|
||||
with open(output_file, 'w') as f:
|
||||
f.write(output)
|
||||
OutputFormatter.success(f"Issues exported to {output_file}")
|
||||
else:
|
||||
print(output)
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def export_issues_json(self, output_file: str = None) -> None:
|
||||
"""Export issues in JSON format."""
|
||||
try:
|
||||
output = self.service.export_issues(
|
||||
format_type="json",
|
||||
sort_by="number"
|
||||
)
|
||||
|
||||
if output_file:
|
||||
with open(output_file, 'w') as f:
|
||||
f.write(output)
|
||||
OutputFormatter.success(f"Issues exported to {output_file}")
|
||||
else:
|
||||
print(output)
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
@@ -1,134 +0,0 @@
|
||||
"""
|
||||
Issue CLI commands.
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Any
|
||||
|
||||
from tddai import TddaiError
|
||||
from services import IssueService
|
||||
from cli.presenters import OutputFormatter, IssueView
|
||||
|
||||
|
||||
class IssueCommands:
|
||||
"""Commands for issue operations."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.service = IssueService()
|
||||
|
||||
def list_issues(self) -> None:
|
||||
"""List all issues."""
|
||||
try:
|
||||
issues = self.service.list_issues()
|
||||
IssueView.show_list(issues)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def list_open_issues(self) -> None:
|
||||
"""List only open issues."""
|
||||
try:
|
||||
issues = self.service.list_open_issues()
|
||||
IssueView.show_open_issues(issues)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def show_issue(self, issue_number: int) -> None:
|
||||
"""Show detailed issue information."""
|
||||
try:
|
||||
issue_data = self.service.get_issue_details(issue_number)
|
||||
IssueView.show_issue_details(issue_data)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def create_issue(self, title: str, body: str, issue_type: str = "enhancement") -> None:
|
||||
"""Create a new issue."""
|
||||
try:
|
||||
OutputFormatter.info(f"Creating {issue_type} issue: {title}")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
result = self.service.create_issue(title, body, labels=[issue_type])
|
||||
IssueView.show_creation_success(result, issue_type)
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error creating issue: {e}")
|
||||
|
||||
def create_enhancement_issue(self, title: str, use_case: str,
|
||||
technical_requirements: str = "",
|
||||
acceptance_criteria: Optional[List[str]] = None,
|
||||
dependencies: Optional[List[str]] = None,
|
||||
priority: str = "Medium") -> None:
|
||||
"""Create a structured enhancement issue."""
|
||||
try:
|
||||
OutputFormatter.info(f"Creating enhancement issue: {title}")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
result = self.service.create_enhancement_issue(
|
||||
title, use_case, technical_requirements,
|
||||
acceptance_criteria, dependencies, priority
|
||||
)
|
||||
|
||||
OutputFormatter.success("Enhancement issue created successfully!")
|
||||
OutputFormatter.key_value("Number", f"#{result['number']}")
|
||||
OutputFormatter.key_value("Title", result['title'])
|
||||
OutputFormatter.key_value("Priority", priority)
|
||||
|
||||
if 'html_url' in result:
|
||||
OutputFormatter.key_value("URL", result['html_url'])
|
||||
|
||||
OutputFormatter.empty_line()
|
||||
print("💡 Next steps:")
|
||||
print(f" - Use 'make tdd-start NUM={result['number']}' to begin work")
|
||||
print(f" - Use 'make show-issue NUM={result['number']}' to view details")
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error creating enhancement issue: {e}")
|
||||
|
||||
def create_from_template(self, template_file: str, **kwargs: Any) -> None:
|
||||
"""Create issue from template file."""
|
||||
try:
|
||||
OutputFormatter.info(f"Creating issue from template: {template_file}")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
result = self.service.create_from_template(template_file, **kwargs)
|
||||
|
||||
OutputFormatter.success("Issue created from template successfully!")
|
||||
OutputFormatter.key_value("Number", f"#{result['number']}")
|
||||
OutputFormatter.key_value("Title", result['title'])
|
||||
|
||||
if 'html_url' in result:
|
||||
OutputFormatter.key_value("URL", result['html_url'])
|
||||
|
||||
OutputFormatter.empty_line()
|
||||
print("💡 Next steps:")
|
||||
print(f" - Use 'make tdd-start NUM={result['number']}' to begin work")
|
||||
print(f" - Use 'make show-issue NUM={result['number']}' to view details")
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error creating issue from template: {e}")
|
||||
|
||||
def close_issue(self, issue_number: int, comment: str = "") -> None:
|
||||
"""Close an issue with optional comment."""
|
||||
try:
|
||||
OutputFormatter.info(f"Closing issue #{issue_number}")
|
||||
if comment:
|
||||
OutputFormatter.info(f"Comment: {comment}")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
result = self.service.close_issue(issue_number, comment)
|
||||
|
||||
OutputFormatter.success(f"Issue #{issue_number} closed successfully!")
|
||||
OutputFormatter.key_value("Title", result['title'])
|
||||
OutputFormatter.key_value("State", result['state'])
|
||||
|
||||
if 'html_url' in result:
|
||||
OutputFormatter.key_value("URL", result['html_url'])
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error closing issue: {e}")
|
||||
|
||||
def analyze_coverage(self, issue_number: int) -> None:
|
||||
"""Analyze test coverage for a specific issue."""
|
||||
try:
|
||||
coverage_data = self.service.analyze_coverage(issue_number)
|
||||
IssueView.show_coverage_analysis(coverage_data)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
@@ -1,88 +0,0 @@
|
||||
"""
|
||||
Project management CLI commands.
|
||||
"""
|
||||
|
||||
from tddai import TddaiError
|
||||
from services import ProjectService
|
||||
from cli.presenters import OutputFormatter, ProjectView
|
||||
|
||||
|
||||
class ProjectCommands:
|
||||
"""Commands for project management operations."""
|
||||
|
||||
def __init__(self):
|
||||
self.service = ProjectService()
|
||||
|
||||
def setup_project_management(self) -> None:
|
||||
"""Setup project management labels and milestones."""
|
||||
try:
|
||||
OutputFormatter.info("Setting up project management system...")
|
||||
self.service.setup_project_management()
|
||||
ProjectView.show_setup_success()
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error setting up project management: {e}")
|
||||
|
||||
def move_issue_to_state(self, issue_number: int, state: str) -> None:
|
||||
"""Move issue to a specific project state."""
|
||||
try:
|
||||
OutputFormatter.info(f"Moving issue #{issue_number} to {state} state...")
|
||||
result = self.service.set_issue_state(issue_number, state)
|
||||
|
||||
# If moving to done, also close the issue
|
||||
if state == 'done':
|
||||
self.service.move_issue_to_done(issue_number)
|
||||
OutputFormatter.success(f"Issue #{issue_number} moved to {state} and closed")
|
||||
else:
|
||||
OutputFormatter.success(f"Issue #{issue_number} moved to {state}")
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error moving issue to {state}: {e}")
|
||||
|
||||
def set_issue_priority(self, issue_number: int, priority: str) -> None:
|
||||
"""Set issue priority."""
|
||||
try:
|
||||
OutputFormatter.info(f"Setting issue #{issue_number} priority to {priority}...")
|
||||
result = self.service.set_issue_priority(issue_number, priority)
|
||||
OutputFormatter.success(f"Issue #{issue_number} priority set to {priority}")
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error setting issue priority: {e}")
|
||||
|
||||
def create_milestone(self, title: str, description: str = "") -> None:
|
||||
"""Create a new milestone (project)."""
|
||||
try:
|
||||
OutputFormatter.info(f"Creating milestone: {title}")
|
||||
milestone = self.service.create_milestone(title, description)
|
||||
|
||||
OutputFormatter.success("Milestone created successfully!")
|
||||
OutputFormatter.key_value("ID", milestone.id)
|
||||
OutputFormatter.key_value("Title", milestone.title)
|
||||
OutputFormatter.key_value("Description", milestone.description)
|
||||
OutputFormatter.key_value("State", milestone.state)
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error creating milestone: {e}")
|
||||
|
||||
def list_milestones(self) -> None:
|
||||
"""List all milestones."""
|
||||
try:
|
||||
milestones = self.service.list_milestones("all")
|
||||
ProjectView.show_milestone_list(milestones)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error listing milestones: {e}")
|
||||
|
||||
def assign_issue_to_milestone(self, issue_number: int, milestone_id: int) -> None:
|
||||
"""Assign issue to a milestone."""
|
||||
try:
|
||||
OutputFormatter.info(f"Assigning issue #{issue_number} to milestone #{milestone_id}...")
|
||||
result = self.service.assign_issue_to_milestone(issue_number, milestone_id)
|
||||
OutputFormatter.success(f"Issue #{issue_number} assigned to milestone #{milestone_id}")
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error assigning issue to milestone: {e}")
|
||||
|
||||
def project_overview(self) -> None:
|
||||
"""Show project management overview."""
|
||||
try:
|
||||
overview = self.service.get_project_overview()
|
||||
ProjectView.show_overview(overview)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(f"Error getting project overview: {e}")
|
||||
@@ -1,100 +0,0 @@
|
||||
"""
|
||||
Workspace CLI commands.
|
||||
"""
|
||||
|
||||
from tddai import TddaiError
|
||||
from services import WorkspaceService
|
||||
from cli.presenters import OutputFormatter, WorkspaceView
|
||||
|
||||
|
||||
class WorkspaceCommands:
|
||||
"""Commands for workspace operations."""
|
||||
|
||||
def __init__(self):
|
||||
self.service = WorkspaceService()
|
||||
|
||||
def status(self) -> None:
|
||||
"""Show current workspace status."""
|
||||
try:
|
||||
summary = self.service.get_workspace_summary()
|
||||
WorkspaceView.show_status(summary)
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def start_issue(self, issue_number: int) -> None:
|
||||
"""Start working on an issue."""
|
||||
try:
|
||||
OutputFormatter.info(f"Starting work on issue #{issue_number}...")
|
||||
OutputFormatter.info(f"Fetching issue #{issue_number} details...")
|
||||
|
||||
workspace_info = self.service.start_issue_workspace(issue_number)
|
||||
summary = self.service.get_workspace_summary()
|
||||
WorkspaceView.show_start_success(summary)
|
||||
|
||||
except TddaiError as e:
|
||||
if "Already working on" in str(e):
|
||||
OutputFormatter.warning(str(e))
|
||||
print(" Run 'make tdd-finish' first or 'make tdd-status' to see details")
|
||||
OutputFormatter.exit_with_error("Cannot start new workspace", 1)
|
||||
else:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def finish_issue(self) -> None:
|
||||
"""Finish current issue workspace."""
|
||||
try:
|
||||
issue_number = self.service.finish_current_workspace()
|
||||
if issue_number is None:
|
||||
OutputFormatter.error("No active issue workspace")
|
||||
print(" Nothing to finish")
|
||||
OutputFormatter.exit_with_error("", 1)
|
||||
return # Explicit return for type checker
|
||||
|
||||
# Get test count before finishing
|
||||
summary = self.service.get_workspace_summary()
|
||||
test_count = summary.get('test_count', 0)
|
||||
|
||||
WorkspaceView.show_finish_success(issue_number, test_count)
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
|
||||
def add_test_guidance(self) -> None:
|
||||
"""Show guidance for adding tests."""
|
||||
try:
|
||||
summary = self.service.get_workspace_summary()
|
||||
if not summary['active']:
|
||||
OutputFormatter.error("No active issue workspace")
|
||||
print(" Run 'make tdd-start NUM=X' first")
|
||||
OutputFormatter.exit_with_error("", 1)
|
||||
|
||||
issue_num = summary['issue_number']
|
||||
issue_title = summary['issue_title']
|
||||
workspace_dir = summary['workspace_dir']
|
||||
|
||||
print(f"🧪 Adding test to issue #{issue_num} workspace")
|
||||
OutputFormatter.empty_line()
|
||||
OutputFormatter.key_value("Issue", f"#{issue_num}: {issue_title}")
|
||||
OutputFormatter.key_value("Workspace", f"{workspace_dir}/issue_{issue_num}/")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
print("🤖 Please ask Claude Code to generate a test:")
|
||||
OutputFormatter.empty_line()
|
||||
print(" Command: 'Generate a test for the current workspace issue'")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
print("📝 Test Requirements:")
|
||||
print(f" - Save test in: {workspace_dir}/issue_{issue_num}/tests/")
|
||||
print(f" - Name format: test_issue_{issue_num}_<scenario>.py")
|
||||
print(f" - Include docstring referencing issue #{issue_num}")
|
||||
print(" - Follow TDD principles (test should fail initially)")
|
||||
print(" - Review requirements.md and test_plan.md for context")
|
||||
OutputFormatter.empty_line()
|
||||
|
||||
print("📋 Issue Details:")
|
||||
OutputFormatter.key_value("Title", issue_title)
|
||||
# Note: Could fetch full issue details if needed
|
||||
OutputFormatter.empty_line()
|
||||
print("💡 After generation: Use 'make tdd-status' to see all tests")
|
||||
|
||||
except TddaiError as e:
|
||||
OutputFormatter.exit_with_error(str(e))
|
||||
79
cli/core.py
79
cli/core.py
@@ -5,92 +5,15 @@ Provides the main CLI framework and command delegation.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
from .commands import WorkspaceCommands, IssueCommands, ProjectCommands, ExportCommands, ConfigCommands
|
||||
from .commands import ConfigCommands
|
||||
|
||||
|
||||
class CLIFramework:
|
||||
"""Main CLI framework that delegates to command classes."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.workspace = WorkspaceCommands()
|
||||
self.issues = IssueCommands()
|
||||
self.project = ProjectCommands()
|
||||
self.export = ExportCommands()
|
||||
self.config = ConfigCommands()
|
||||
|
||||
# Workspace operations
|
||||
def workspace_status(self) -> None:
|
||||
return self.workspace.status()
|
||||
|
||||
def start_issue(self, issue_number: int) -> None:
|
||||
return self.workspace.start_issue(issue_number)
|
||||
|
||||
def finish_issue(self) -> None:
|
||||
return self.workspace.finish_issue()
|
||||
|
||||
def add_test_guidance(self) -> None:
|
||||
return self.workspace.add_test_guidance()
|
||||
|
||||
# Issue operations
|
||||
def list_issues(self) -> None:
|
||||
return self.issues.list_issues()
|
||||
|
||||
def list_open_issues(self) -> None:
|
||||
return self.issues.list_open_issues()
|
||||
|
||||
def show_issue(self, issue_number: int) -> None:
|
||||
return self.issues.show_issue(issue_number)
|
||||
|
||||
def create_issue(self, title: str, body: str, issue_type: str = "enhancement") -> None:
|
||||
return self.issues.create_issue(title, body, issue_type)
|
||||
|
||||
def create_enhancement_issue(self, title: str, use_case: str, **kwargs: Any) -> None:
|
||||
return self.issues.create_enhancement_issue(title, use_case, **kwargs)
|
||||
|
||||
def create_from_template(self, template_file: str, **kwargs: Any) -> None:
|
||||
return self.issues.create_from_template(template_file, **kwargs)
|
||||
|
||||
def close_issue(self, issue_number: int, comment: str = "") -> None:
|
||||
return self.issues.close_issue(issue_number, comment)
|
||||
|
||||
def analyze_coverage(self, issue_number: int) -> None:
|
||||
return self.issues.analyze_coverage(issue_number)
|
||||
|
||||
# Project management operations
|
||||
def setup_project_management(self) -> None:
|
||||
return self.project.setup_project_management()
|
||||
|
||||
def move_issue_to_state(self, issue_number: int, state: str) -> None:
|
||||
return self.project.move_issue_to_state(issue_number, state)
|
||||
|
||||
def set_issue_priority(self, issue_number: int, priority: str) -> None:
|
||||
return self.project.set_issue_priority(issue_number, priority)
|
||||
|
||||
def create_milestone(self, title: str, description: str = "") -> None:
|
||||
return self.project.create_milestone(title, description)
|
||||
|
||||
def list_milestones(self) -> None:
|
||||
return self.project.list_milestones()
|
||||
|
||||
def assign_issue_to_milestone(self, issue_number: int, milestone_id: int) -> None:
|
||||
return self.project.assign_issue_to_milestone(issue_number, milestone_id)
|
||||
|
||||
def project_overview(self) -> None:
|
||||
return self.project.project_overview()
|
||||
|
||||
# Export operations
|
||||
def issue_index(self, **kwargs: Any) -> None:
|
||||
return self.export.issue_index(**kwargs)
|
||||
|
||||
def export_issues_csv(self, output_file: str = None) -> None:
|
||||
return self.export.export_issues_csv(output_file)
|
||||
|
||||
def export_issues_json(self, output_file: str = None) -> None:
|
||||
return self.export.export_issues_json(output_file)
|
||||
|
||||
def export_issue_index(self, output_file: str = None) -> None:
|
||||
return self.export.issue_index(format_type="tsv", output_file=output_file)
|
||||
|
||||
# Configuration operations
|
||||
def show_config(self, show_sensitive: bool = False) -> None:
|
||||
return self.config.show_config(show_sensitive)
|
||||
|
||||
180
cli/issue_cli.py
180
cli/issue_cli.py
@@ -1,180 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Pure Issue Management CLI
|
||||
|
||||
Dedicated CLI interface for issue management operations, providing clean
|
||||
separation from document processing and TDD workflow functionality.
|
||||
|
||||
This CLI focuses exclusively on issue operations:
|
||||
- Listing and viewing issues
|
||||
- Creating and closing issues
|
||||
- Project management (milestones, priorities, states)
|
||||
- Issue metadata and bulk operations
|
||||
|
||||
Architecture: Uses the unified cli/ framework for consistent command structure.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Add project root to path for imports
|
||||
project_root = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from cli.core import CLIFramework
|
||||
from tddai import TddaiError
|
||||
|
||||
|
||||
def create_parser() -> argparse.ArgumentParser:
|
||||
"""Create argument parser for issue CLI."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog='issue',
|
||||
description='Pure Issue Management CLI - Dedicated interface for issue operations',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
issue list # List all issues
|
||||
issue list --open # List only open issues
|
||||
issue show 42 # Show issue details
|
||||
issue create "Bug fix" "Description" # Create new issue
|
||||
issue close 42 "Fixed the problem" # Close issue with comment
|
||||
issue assign 42 milestone-1 # Assign to milestone
|
||||
issue priority 42 high # Set priority
|
||||
issue state 42 "In Progress" # Set project state
|
||||
|
||||
Focus Areas:
|
||||
- Issue browsing and management
|
||||
- Project organization (milestones, priorities)
|
||||
- Bulk operations and metadata management
|
||||
- Integration with various issue tracking backends
|
||||
|
||||
Related Commands:
|
||||
tddai - TDD workflow management with issue context
|
||||
markitect - Document processing and template operations
|
||||
"""
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest='command', help='Available issue commands')
|
||||
|
||||
# List issues
|
||||
list_parser = subparsers.add_parser('list', help='List issues')
|
||||
list_parser.add_argument('--open', action='store_true', help='Show only open issues')
|
||||
list_parser.add_argument('--format', choices=['table', 'json', 'csv'], default='table', help='Output format')
|
||||
|
||||
# Show issue details
|
||||
show_parser = subparsers.add_parser('show', help='Show issue details')
|
||||
show_parser.add_argument('issue_number', type=int, help='Issue number')
|
||||
|
||||
# Create issue
|
||||
create_parser = subparsers.add_parser('create', help='Create new issue')
|
||||
create_parser.add_argument('title', help='Issue title')
|
||||
create_parser.add_argument('description', help='Issue description')
|
||||
create_parser.add_argument('--type', choices=['bug', 'enhancement', 'feature'], default='enhancement', help='Issue type')
|
||||
create_parser.add_argument('--priority', choices=['low', 'medium', 'high', 'critical'], help='Issue priority')
|
||||
|
||||
# Close issue
|
||||
close_parser = subparsers.add_parser('close', help='Close issue')
|
||||
close_parser.add_argument('issue_number', type=int, help='Issue number')
|
||||
close_parser.add_argument('comment', nargs='?', default='', help='Closing comment')
|
||||
|
||||
# Assign to milestone
|
||||
assign_parser = subparsers.add_parser('assign', help='Assign issue to milestone')
|
||||
assign_parser.add_argument('issue_number', type=int, help='Issue number')
|
||||
assign_parser.add_argument('milestone_id', type=int, help='Milestone ID')
|
||||
|
||||
# Set priority
|
||||
priority_parser = subparsers.add_parser('priority', help='Set issue priority')
|
||||
priority_parser.add_argument('issue_number', type=int, help='Issue number')
|
||||
priority_parser.add_argument('priority', choices=['low', 'medium', 'high', 'critical'], help='Priority level')
|
||||
|
||||
# Set state
|
||||
state_parser = subparsers.add_parser('state', help='Set issue project state')
|
||||
state_parser.add_argument('issue_number', type=int, help='Issue number')
|
||||
state_parser.add_argument('state', help='Project state')
|
||||
|
||||
# Export/bulk operations
|
||||
export_parser = subparsers.add_parser('export', help='Export issues in various formats')
|
||||
export_parser.add_argument('--format', choices=['csv', 'json', 'tsv'], default='csv', help='Export format')
|
||||
export_parser.add_argument('--output', help='Output file (default: stdout)')
|
||||
export_parser.add_argument('--filter', choices=['open', 'closed', 'all'], default='all', help='Filter issues')
|
||||
|
||||
# Milestones
|
||||
milestone_parser = subparsers.add_parser('milestones', help='List milestones')
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry point for issue CLI."""
|
||||
parser = create_parser()
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.command:
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Initialize CLI framework
|
||||
try:
|
||||
cli = CLIFramework()
|
||||
except Exception as e:
|
||||
print(f"Error initializing CLI framework: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# Execute commands
|
||||
try:
|
||||
if args.command == 'list':
|
||||
if args.open:
|
||||
cli.list_open_issues()
|
||||
else:
|
||||
cli.list_issues()
|
||||
|
||||
elif args.command == 'show':
|
||||
cli.show_issue(args.issue_number)
|
||||
|
||||
elif args.command == 'create':
|
||||
kwargs = {}
|
||||
if hasattr(args, 'priority') and args.priority:
|
||||
kwargs['priority'] = args.priority
|
||||
cli.create_issue(args.title, args.description, args.type, **kwargs)
|
||||
|
||||
elif args.command == 'close':
|
||||
cli.close_issue(args.issue_number, args.comment)
|
||||
|
||||
elif args.command == 'assign':
|
||||
cli.assign_issue_to_milestone(args.issue_number, args.milestone_id)
|
||||
|
||||
elif args.command == 'priority':
|
||||
cli.set_issue_priority(args.issue_number, args.priority)
|
||||
|
||||
elif args.command == 'state':
|
||||
cli.move_issue_to_state(args.issue_number, args.state)
|
||||
|
||||
elif args.command == 'export':
|
||||
# Export functionality
|
||||
if args.format == 'csv':
|
||||
cli.export_issues_csv(args.output)
|
||||
elif args.format == 'json':
|
||||
cli.export_issues_json(args.output)
|
||||
elif args.format == 'tsv':
|
||||
cli.export_issue_index(args.output)
|
||||
|
||||
elif args.command == 'milestones':
|
||||
cli.list_milestones()
|
||||
|
||||
else:
|
||||
print(f"Unknown command: {args.command}")
|
||||
parser.print_help()
|
||||
sys.exit(1)
|
||||
|
||||
except TddaiError as e:
|
||||
print(f"Issue CLI Error: {e}")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -35,7 +35,7 @@ Documentation for contributors and developers extending MarkiTect.
|
||||
### Project Management
|
||||
- [Project Status](../history/ProjectStatusDigest.md) - Current development status
|
||||
- [Roadmap](../history/ROADMAP.md) - Strategic development plan
|
||||
- [Next Actions](../NEXT.md) - Immediate development priorities
|
||||
- [Current Tasks](../TODO.md) - Task management using Keep a Todofile format
|
||||
|
||||
## Key Concepts
|
||||
|
||||
|
||||
124
history/NEXT_archived_20251025.md
Normal file
124
history/NEXT_archived_20251025.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# MarkiTect - Next Session Priorities
|
||||
|
||||
**Updated:** 2025-10-25
|
||||
**Status:** Capability Inclusion Management System Complete
|
||||
**Next Focus:** Strategic Development Execution
|
||||
|
||||
## High Priority (Next Session Focus)
|
||||
|
||||
### 1. Strategic Issue Resolution 🎯
|
||||
**Priority: CRITICAL**
|
||||
- Resume work on core functionality backlog
|
||||
- Target: Issue #15 (AST Query and Analysis CLI) or Issue #16 (Performance Validation CLI)
|
||||
- Use new capability inclusion workflow to prevent duplication
|
||||
- Leverage CLAUDE_CAPABILITY_REFERENCE.md for quick capability lookup
|
||||
|
||||
### 2. Capability Management Validation 🔍
|
||||
**Priority: HIGH**
|
||||
- Test the new discovery tools (`make capability-search TERM=xyz`) in real development
|
||||
- Validate workflow effectiveness during actual implementation
|
||||
- Refine documentation based on practical usage
|
||||
- Ensure AI assistants properly utilize the new capability references
|
||||
|
||||
### 3. Documentation Integration ✅
|
||||
**Priority: MEDIUM**
|
||||
- Update any missing links in existing documentation to new capability system
|
||||
- Ensure all agents are aware of capability inclusion workflow
|
||||
- Validate that CAPABILITY_DOCUMENTATION_INDEX.md provides effective navigation
|
||||
|
||||
## Development Strategy
|
||||
|
||||
### Capability-First Development
|
||||
1. **Before implementing anything new:**
|
||||
- Check CAPABILITIES.md for internal capabilities
|
||||
- Check CAPABILITY_REGISTRY.md for external capabilities
|
||||
- Use `make capability-search TERM=xyz` for discovery
|
||||
- Consult CLAUDE_CAPABILITY_REFERENCE.md for patterns
|
||||
|
||||
2. **During implementation:**
|
||||
- Update capability documentation if creating new capabilities
|
||||
- Follow CAPABILITY_INCLUSION_GUIDE.md workflow
|
||||
- Document any new external dependencies in CAPABILITY_REGISTRY.md
|
||||
|
||||
3. **After implementation:**
|
||||
- Update CAPABILITIES.md if internal capabilities were added
|
||||
- Ensure proper categorization in documentation ecosystem
|
||||
|
||||
### Next Major Milestones
|
||||
|
||||
#### Immediate (1-2 Sessions)
|
||||
- **Complete Issue #15 or #16**: Demonstrate capability management system in practice
|
||||
- **Validate Discovery Tools**: Ensure automated detection prevents duplication
|
||||
- **Refine Workflow**: Based on real-world usage patterns
|
||||
|
||||
#### Short Term (3-5 Sessions)
|
||||
- **Schema-Driven Architecture**: Issues #5, #7, #8 (Milestone #2)
|
||||
- **Template Generation**: Issue #6 (Milestone #3)
|
||||
- **Advanced Querying**: Complete AST analysis capabilities
|
||||
|
||||
#### Medium Term (6-10 Sessions)
|
||||
- **Document Relationships**: Issue #4, advanced relationship mapping
|
||||
- **Performance Optimization**: Based on Issue #16 implementation
|
||||
- **Plugin Architecture**: Issue #19 and extensibility framework
|
||||
|
||||
## Session Success Criteria
|
||||
|
||||
### Must Achieve
|
||||
- [ ] Complete one core functionality issue using capability inclusion workflow
|
||||
- [ ] Demonstrate prevention of code duplication through discovery tools
|
||||
- [ ] Validate documentation ecosystem effectiveness
|
||||
|
||||
### Should Achieve
|
||||
- [ ] Update capability documentation with any new functionality
|
||||
- [ ] Refine workflow based on practical experience
|
||||
- [ ] Maintain green test state throughout development
|
||||
|
||||
### Could Achieve
|
||||
- [ ] Begin next milestone planning
|
||||
- [ ] Enhance discovery tools based on usage patterns
|
||||
- [ ] Improve AI assistant integration with capability system
|
||||
|
||||
## Known Context
|
||||
|
||||
### Current State
|
||||
- **Capability Management**: Complete documentation ecosystem established
|
||||
- **Discovery Tools**: Automated prevention of code duplication
|
||||
- **Architectural Clarity**: Clear separation of internal vs external capabilities
|
||||
- **Test State**: All tests passing (last known: 348 tests across 27 files)
|
||||
- **Git State**: Modified files ready for commit (capability inclusion system)
|
||||
|
||||
### Available Resources
|
||||
- **Complete capability documentation** in 5 interconnected files
|
||||
- **Automated discovery tools** via Makefile targets
|
||||
- **Enhanced agent definitions** with capability inclusion workflow
|
||||
- **Comprehensive test coverage** across all components
|
||||
|
||||
### Development Environment
|
||||
- **Ubuntu 24.04** with complete development environment
|
||||
- **Python virtual environment** properly configured
|
||||
- **Git submodules** (issue-facade, wiki) properly integrated
|
||||
- **All dependencies** installed and validated
|
||||
|
||||
## Next Session Preparation
|
||||
|
||||
### Pre-Session Setup
|
||||
1. Ensure git status is clean (commit capability inclusion system)
|
||||
2. Run `make test` to validate green state
|
||||
3. Review CLAUDE_CAPABILITY_REFERENCE.md for quick capability overview
|
||||
4. Select target issue for implementation
|
||||
|
||||
### Session Approach
|
||||
1. **Start with capability discovery** before any implementation
|
||||
2. **Use new workflow** from CAPABILITY_INCLUSION_GUIDE.md
|
||||
3. **Document any new capabilities** as they're created
|
||||
4. **Validate discovery tools** prevent accidental duplication
|
||||
|
||||
### Success Indicators
|
||||
- New functionality implemented without duplicating existing capabilities
|
||||
- Discovery tools successfully prevent code duplication
|
||||
- Documentation ecosystem proves valuable for development efficiency
|
||||
- AI assistants effectively use capability references for informed decisions
|
||||
|
||||
---
|
||||
|
||||
> **Note**: This file should be updated at the end of each session to maintain clear priorities and context for the next session. Use the capability inclusion management system as the foundation for all future development decisions.
|
||||
@@ -4,6 +4,28 @@ This diary tracks major work packages, events, and milestones in the MarkiTect p
|
||||
|
||||
---
|
||||
|
||||
## 2025-10-25: COMPREHENSIVE CAPABILITY INCLUSION MANAGEMENT SYSTEM ⭐ ARCHITECTURE MILESTONE ⭐
|
||||
|
||||
**Progress:** Successfully implemented comprehensive capability inclusion management system with clear separation of internal vs external capabilities
|
||||
**Contributors:** User (bernd.worsch), Claude Code (Sonnet 4)
|
||||
**Architecture Milestone:** Capability Inclusion Management System ✅ ACHIEVED (complete documentation ecosystem with discovery tools)
|
||||
**Total Development Time:** ~2-3 hours of intensive system design and documentation
|
||||
**AI Resources:** ~20-25 Claude Sonnet 4 conversations, estimated 40K+ tokens
|
||||
|
||||
**CAPABILITY INCLUSION BREAKTHROUGH:** Implemented revolutionary capability inclusion management system addressing the critical need to prevent code duplication and ensure proper separation of concerns. Created comprehensive documentation ecosystem with clear distinction between **internal capabilities** (what MarkiTect provides to the world) and **external capabilities** (what MarkiTect uses). This system provides developers and AI assistants with immediate visibility into existing functionality, preventing accidental reimplementation and enabling informed architectural decisions.
|
||||
|
||||
**COMPREHENSIVE DOCUMENTATION ECOSYSTEM:** Created five interconnected documentation files: (1) **CAPABILITIES.md** - Complete inventory of 73+ internal capabilities that MarkiTect provides, (2) **CAPABILITY_REGISTRY.md** - Registry of all external capabilities that MarkiTect uses (submodules, dependencies, extracted components), (3) **CAPABILITY_INCLUSION_GUIDE.md** - Complete workflow guide for managing capability inclusion decisions, (4) **CAPABILITY_DOCUMENTATION_INDEX.md** - Navigation hub linking all capability documentation, (5) **CLAUDE_CAPABILITY_REFERENCE.md** - Quick reference for AI assistants with search patterns and discovery tools.
|
||||
|
||||
**AUTOMATED DISCOVERY INFRASTRUCTURE:** Implemented sophisticated discovery tools preventing code duplication: `make capability-search TERM=xyz` for finding existing functionality across the codebase, integration with existing `make find-capability` and `make find-function` targets, comprehensive search patterns covering code, documentation, and test files, and automated capability detection preventing accidental reimplementation. Enhanced project-assistant agent definition with capability inclusion workflow guidelines.
|
||||
|
||||
**ARCHITECTURAL SEPARATION CLARITY:** Established clear architectural boundaries with **Internal Capabilities** (CAPABILITIES.md) focusing on what MarkiTect provides - the 73+ distinct capabilities including database-driven AST processing, multi-layer caching, Git platform integration, and comprehensive CLI interface. **External Capabilities** (CAPABILITY_REGISTRY.md) documenting what MarkiTect uses - git submodules (issue-facade, wiki), extracted components, package dependencies, and integration patterns. This separation enables clear understanding of system boundaries and dependency relationships.
|
||||
|
||||
**WORKFLOW INTEGRATION SUCCESS:** Updated all relevant documentation and agent definitions with capability inclusion workflow, enhanced README.md with clear links to capability documentation, integrated discovery tools with existing Makefile infrastructure, and provided comprehensive guidance for future development decisions. The system seamlessly integrates with existing development workflows while providing new safeguards against code duplication.
|
||||
|
||||
**STRATEGIC DEVELOPMENT IMPACT:** This system transforms MarkiTect development from ad-hoc capability implementation to systematic capability management. Before this session: unclear boundaries between internal/external capabilities, potential for code duplication, no systematic discovery tools. After this session: **Complete capability management platform**, **Clear architectural boundaries**, **Automated discovery preventing duplication**, **Comprehensive documentation ecosystem**, **AI-assistant optimized workflows**. This establishes MarkiTect as a mature project with enterprise-grade capability management.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## 2025-10-02: PERFORMANCE TRACKING IMPLEMENTATION
|
||||
|
||||
|
||||
252
history/ProjectStatusDigest.md
Normal file
252
history/ProjectStatusDigest.md
Normal file
@@ -0,0 +1,252 @@
|
||||
# MarkiTect Project - Status Digest
|
||||
|
||||
**Version:** 0.2.0
|
||||
**Last Updated:** 2025-10-25
|
||||
**Development Status:** 🚀 **Capability Inclusion Management System Complete - Enterprise-Grade Architecture**
|
||||
**Tagline:** "Your Markdown, Redefined"
|
||||
|
||||
## Core Vision
|
||||
|
||||
Transform Markdown from plain text into intelligent, structured, reusable data with schema validation and automation capabilities.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### MarkiTect Library (Python Core) ✅ **Foundation Complete**
|
||||
- **Reusable Python package** designed for CLI, service offerings, and third-party integration
|
||||
- **TDD approach** with comprehensive test coverage and pytest framework (348+ tests passing)
|
||||
- **Modern packaging** using `pyproject.toml` with dependencies: `markdown-it-py`, `PyYAML`
|
||||
- **Core modules implemented**: Database, front matter parsing, AST processing, caching system
|
||||
- **Capability inclusion management** with automated discovery and duplication prevention
|
||||
|
||||
### Capability Management System ✅ **REVOLUTIONARY ACHIEVEMENT**
|
||||
- **Complete capability documentation ecosystem** with 5 interconnected documentation files
|
||||
- **Clear separation**: Internal capabilities (what MarkiTect provides) vs External capabilities (what MarkiTect uses)
|
||||
- **Automated discovery tools** preventing code duplication (`make capability-search TERM=xyz`)
|
||||
- **AI-assistant optimized** workflow with CLAUDE_CAPABILITY_REFERENCE.md
|
||||
- **Architectural boundary clarity** ensuring proper separation of concerns
|
||||
- **73+ documented internal capabilities** with comprehensive categorization
|
||||
|
||||
### TDD Infrastructure (tddai Library) ✅ **Fully Operational**
|
||||
- **Complete TDD workspace management** with validated Python library architecture
|
||||
- **Issue-driven development** with proven Gitea API integration
|
||||
- **AI-assisted test generation** framework for automated TDD workflows (validated)
|
||||
- **Test coverage assessment system** with accurate requirement extraction and gap analysis
|
||||
- **Workspace lifecycle management** from issue creation to test integration
|
||||
- **CLI interface** (`tddai_cli.py`) for seamless command-line operations
|
||||
|
||||
### MarkiTect CLI (Command-Line Interface) ✅ **Production Ready**
|
||||
- **Complete CLI implementation** with Click framework integration
|
||||
- **Core commands**: `ingest`, `status`, `list`, `get`, `modify` - all fully functional
|
||||
- **Database query commands**: `query`, `query-files`, `query-sections` for powerful data access
|
||||
- **Cache management commands**: `cache-info`, `cache-clean`, `cache-invalidate` for performance control
|
||||
- **Document manipulation**: `--add-section`, `--update-front-matter` for AST modifications
|
||||
- **Performance optimization**: AST cache system with 60-85% faster processing
|
||||
- **Roundtrip validation**: Complete add → modify → get → verify workflow
|
||||
|
||||
## 🎯 **Current Development Status**
|
||||
|
||||
### ✅ **Major Milestones Completed**
|
||||
- **Issue #1**: Database initialization and front matter parsing (9 tests)
|
||||
- **Issue #2**: Fast Document Loading & CLI Manipulation ⭐ **MAJOR** (11 tests)
|
||||
- **Issue #12**: CLI Entry Point and Basic Commands (part of comprehensive test suite)
|
||||
- **Issue #13**: Cache Management CLI Commands ⭐ **MAJOR** (15 tests) - TDD8 Complete
|
||||
- **Issue #14**: Database Query CLI Interface ⭐ **MAJOR** (35 tests) - TDD8 Complete
|
||||
- **TDD Infrastructure**: Complete workflow automation (32+ tests)
|
||||
- **CLI Implementation Milestone**: ✅ **COMPLETED** - All CLI core functionality delivered
|
||||
- **Capability Inclusion Management**: ✅ **COMPLETED** - Revolutionary architecture milestone
|
||||
- **Total Foundation**: 348+ tests passing across 27 test files
|
||||
|
||||
### 🚀 **Strategic Roadmap Active**
|
||||
**4 Subprojects targeting HolyGrailRequirement (arc42 documentation system)**
|
||||
|
||||
#### **Subproject 1: Schema-Driven Architecture** (Milestone #2)
|
||||
- Issue #5: Generate Schema from Markdown File (HIGH)
|
||||
- Issue #7: Validate Markdown Against Schema (HIGH)
|
||||
- Issue #8: Get Validation Errors (HIGH)
|
||||
|
||||
#### **Subproject 2: Template & Stub Generation** (Milestone #3)
|
||||
- Issue #6: Generate Markdown Stub from Schema (HIGH)
|
||||
|
||||
#### **Subproject 3: Document Relationships** (Milestone #4)
|
||||
- Issue #4: Retrieve All Stored Files (MEDIUM)
|
||||
- Issue #15: AST Query and Analysis CLI (CRITICAL)
|
||||
|
||||
#### **Subproject 4: Plan-Actual Comparison Engine** (Milestone #5)
|
||||
- Issue #9: Expose GraphQL Read Interface (LOW)
|
||||
- Issue #10: Expose GraphQL Write Interface (LOW)
|
||||
- ✅ Issue #16: Performance Validation CLI (COMPLETED) - All 5 CLI commands implemented with 81.4/100 performance baseline
|
||||
|
||||
### 🎯 **Next Priority**
|
||||
- **Strategic Issue Implementation** using new capability inclusion workflow
|
||||
- **Capability Management Validation** through real-world usage
|
||||
- **Schema-Driven Architecture** milestone preparation with duplication prevention
|
||||
|
||||
### 📊 **Metrics**
|
||||
- **Test Coverage**: 100% for implemented features (348+ tests across 27 files)
|
||||
- **Code Quality**: Modern Python practices with type hints and comprehensive error handling
|
||||
- **Documentation**: Revolutionary capability management ecosystem with 5 interconnected files
|
||||
- **Development Velocity**: Enhanced with automated duplication prevention
|
||||
- **Architecture Maturity**: Enterprise-grade capability inclusion management
|
||||
|
||||
## Key Features & Components
|
||||
|
||||
### Core Functionality
|
||||
- **AbstractSyntaxTree** processing and manipulation with comprehensive caching
|
||||
- **MarkdownParser** using `markdown-it-py` for detailed AST generation
|
||||
- **JsonSchemaValidator** for enforcing document structure
|
||||
- **ChunkInclusion** system for modular content composition
|
||||
- **StaticSiteGenerator** integration capabilities
|
||||
- **Capability Inclusion Management** preventing code duplication
|
||||
|
||||
### Capability Management (NEW)
|
||||
- **Internal Capability Inventory** (CAPABILITIES.md) - 73+ capabilities provided by MarkiTect
|
||||
- **External Capability Registry** (CAPABILITY_REGISTRY.md) - Dependencies and submodules used by MarkiTect
|
||||
- **Automated Discovery Tools** - `make capability-search TERM=xyz` for existing functionality detection
|
||||
- **AI-Assistant Integration** - CLAUDE_CAPABILITY_REFERENCE.md for informed development decisions
|
||||
- **Workflow Documentation** - CAPABILITY_INCLUSION_GUIDE.md for systematic capability management
|
||||
|
||||
### Schema Operations
|
||||
- **Generate schemas** from existing Markdown at specified nesting depths
|
||||
- **Validate Markdown** against defined schemas
|
||||
- **Generate stub files** from schemas with placeholder content
|
||||
- **InclusionStub** handling for modular document architecture
|
||||
|
||||
### GraphQL Interface
|
||||
- **Query operations** for retrieving Markdown files, schemas, and AST data
|
||||
- **Mutation operations** for adding/updating content in database
|
||||
- **Real-time validation** and schema checking
|
||||
|
||||
## Development Approach
|
||||
|
||||
### Capability-First Development (NEW)
|
||||
- **Before implementing**: Check existing capabilities via discovery tools
|
||||
- **During implementation**: Follow CAPABILITY_INCLUSION_GUIDE.md workflow
|
||||
- **After implementation**: Update capability documentation ecosystem
|
||||
- **Automated prevention**: Code duplication detection and architectural boundary enforcement
|
||||
|
||||
### Test-Driven Development
|
||||
- **Complete TDD infrastructure** with `tddai` Python library
|
||||
- **Issue-driven workflow** with workspace management (`tdd-start`, `tdd-add-test`, `tdd-status`, `tdd-finish`)
|
||||
- **348+ passing tests** across 27 test files using pytest with proper behavior-based testing
|
||||
- **AI-assisted test generation** integrated into development cycle
|
||||
- **Green-state validation** before all commits
|
||||
|
||||
### Markdown Feature Support (MF-1 through MF-10)
|
||||
Complete specification coverage including:
|
||||
- Headings and sections structure
|
||||
- Text formatting (bold, italic, strikethrough)
|
||||
- Lists (ordered, unordered, task lists)
|
||||
- Links, images, and media handling
|
||||
- Code blocks and syntax highlighting
|
||||
- Tables and complex formatting
|
||||
- Footnotes and reference systems
|
||||
|
||||
## Project Status
|
||||
|
||||
### Current State
|
||||
- **Capability inclusion management system complete** with comprehensive documentation ecosystem
|
||||
- **TDD infrastructure complete** with robust Python library architecture
|
||||
- **Issue-driven development workflow** fully operational with capability management integration
|
||||
- **Comprehensive test suite** with 348+ passing tests across 27 files
|
||||
- **Build system** with sophisticated Makefile and virtual environment integration
|
||||
- **AI-assisted development** cycle with capability-aware workspace management
|
||||
- **Enterprise-grade architecture** with automated duplication prevention
|
||||
|
||||
### Social Integration
|
||||
- **CoulombSocial participation** since September 2025
|
||||
- **Gitea issues integration** with API-driven workflow management
|
||||
- **Open-source development** model with collaborative wiki
|
||||
- **Issue-to-test automation** for structured development cycles
|
||||
- **Capability-driven collaboration** with clear architectural boundaries
|
||||
|
||||
## Technical Foundation
|
||||
|
||||
### Development Tools
|
||||
- **Python 3.8+** with modern tooling (Black, Ruff, mypy, pytest)
|
||||
- **Make-based workflow** with intelligent environment detection and capability management integration
|
||||
- **Git submodules** for wiki documentation and issue-facade management
|
||||
- **tddai library** for complete TDD workspace automation
|
||||
- **Capability discovery tools** with automated duplication prevention
|
||||
- **Issue management** with Gitea API integration and CLI tools
|
||||
- **Custom subagent ecosystem** enhanced with capability inclusion workflow
|
||||
- **Automated dependency management** with comprehensive installation scripts
|
||||
|
||||
### Brand Identity
|
||||
- **Professional visual identity** with 3D "M" logo incorporating Markdown symbols
|
||||
- **Color palette**: Deep teal/navy (primary), vibrant orange, lime green
|
||||
- **Core pillars**: Structural Integrity, Consistency, Reusability, Automation, Capability Management
|
||||
|
||||
## Repository Structure
|
||||
|
||||
```
|
||||
markitect_project/
|
||||
├── markitect/ # Main Python package
|
||||
├── tddai/ # TDD infrastructure library
|
||||
├── tests/ # Comprehensive test suite (348+ tests across 27 files)
|
||||
├── issue-facade/ # Git submodule for issue management
|
||||
├── wiki/ # Git submodule with comprehensive documentation
|
||||
│
|
||||
├── CAPABILITIES.md # Internal capabilities inventory (73+ capabilities)
|
||||
├── CAPABILITY_REGISTRY.md # External capabilities registry
|
||||
├── CAPABILITY_INCLUSION_GUIDE.md # Workflow guide for capability management
|
||||
├── CAPABILITY_DOCUMENTATION_INDEX.md # Navigation hub for capability docs
|
||||
├── CLAUDE_CAPABILITY_REFERENCE.md # AI assistant quick reference
|
||||
│
|
||||
├── agents/ # Enhanced project management agents
|
||||
├── Makefile # Development workflow with capability management
|
||||
├── pyproject.toml # Python package configuration
|
||||
├── NEXT.md # Next session priorities and strategy
|
||||
├── history/ProjectDiary.md # Development milestone tracking
|
||||
└── README.md # Project overview with capability links
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. **Environment Setup:**
|
||||
```bash
|
||||
sudo ./install-depends.sh # Install system dependencies (Ubuntu 24.04)
|
||||
./install-pip.sh # Install Python dependencies and package
|
||||
make venv-status # Check environment activation state
|
||||
```
|
||||
|
||||
2. **Development Workflow:**
|
||||
```bash
|
||||
make test # Run comprehensive test suite (348+ tests)
|
||||
make update # Pull latest changes from upstream
|
||||
make status # Check git status
|
||||
```
|
||||
|
||||
3. **Capability Management (NEW):**
|
||||
```bash
|
||||
make capability-search TERM=xyz # Find existing functionality
|
||||
make find-capability TERM=xyz # Alternative search method
|
||||
# Before implementing, check CAPABILITIES.md and CAPABILITY_REGISTRY.md
|
||||
```
|
||||
|
||||
4. **TDD Workflow:**
|
||||
```bash
|
||||
make tdd-start NUM=X # Start working on issue X
|
||||
make tdd-add-test # Generate tests for current issue
|
||||
make tdd-status # Check workspace status
|
||||
make tdd-finish # Complete issue and integrate tests
|
||||
```
|
||||
|
||||
5. **Issue Management:**
|
||||
```bash
|
||||
make list-issues # Show all Gitea issues
|
||||
make list-open-issues # Show active backlog
|
||||
make show-issue NUM=X # Detailed issue view
|
||||
make test-coverage NUM=X # Analyze test coverage for issue
|
||||
```
|
||||
|
||||
6. **Building:**
|
||||
```bash
|
||||
make build # Build the package
|
||||
make clean # Clean build artifacts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
MarkiTect represents a significant evolution toward treating documentation as **structured, validatable, and reusable data** rather than simple text files, with robust tooling for large-scale content management, automation, and **enterprise-grade capability inclusion management** that prevents code duplication and ensures architectural clarity.
|
||||
|
||||
> **Note:** This digest is maintained using Claude Code with capability-aware development workflows. Run `make update-digest` to refresh with latest project information.
|
||||
@@ -1,646 +0,0 @@
|
||||
"""
|
||||
Gitea repository implementation with async HTTP client.
|
||||
|
||||
Provides high-performance, reliable access to Gitea API with connection pooling,
|
||||
retry mechanisms, and proper error handling.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from infrastructure.logging import get_logger
|
||||
from typing import List, Optional, Dict, Any
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import aiohttp
|
||||
|
||||
from domain.issues.models import Issue, Label, IssueState
|
||||
from domain.projects.models import Project, Milestone, ProjectState
|
||||
from infrastructure.repositories.interfaces import IssueRepository, ProjectRepository
|
||||
from infrastructure.connection_manager import ConnectionManager, retry_with_backoff, RetryConfig
|
||||
from infrastructure.exceptions import (
|
||||
ErrorContext, OperationType, GiteaApiError, NetworkError,
|
||||
ResourceNotFoundError, ValidationError, ConcurrencyError
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GiteaIssueRepository(IssueRepository):
|
||||
"""
|
||||
Gitea implementation of IssueRepository using async HTTP client.
|
||||
|
||||
Provides efficient access to Gitea issues API with connection pooling,
|
||||
automatic retries, and proper error handling.
|
||||
"""
|
||||
|
||||
def __init__(self, connection_manager: ConnectionManager, retry_config: Optional[RetryConfig] = None):
|
||||
self.connection_manager = connection_manager
|
||||
self.retry_config = retry_config or RetryConfig()
|
||||
self.repo_owner = None
|
||||
self.repo_name = None
|
||||
|
||||
def set_repo_info(self, repo_owner: str, repo_name: str):
|
||||
"""Set repository owner and name for API endpoints."""
|
||||
self.repo_owner = repo_owner
|
||||
self.repo_name = repo_name
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def get_issue(self, issue_number: int, context: Optional[ErrorContext] = None) -> Issue:
|
||||
"""Retrieve an issue by its number from Gitea API."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_issue_{issue_number}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="Issue",
|
||||
resource_id=str(issue_number)
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
if not self.repo_owner or not self.repo_name:
|
||||
raise ValidationError("repo_info", None, "Repository owner and name must be set", context)
|
||||
|
||||
endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}/issues/{issue_number}"
|
||||
async with session.get(endpoint) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
return self._map_api_issue_to_domain(data)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting issue {issue_number}: {e}")
|
||||
raise NetworkError(f"get issue {issue_number}", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def get_issues(
|
||||
self,
|
||||
project_id: Optional[str] = None,
|
||||
state: Optional[str] = None,
|
||||
labels: Optional[List[str]] = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> List[Issue]:
|
||||
"""Retrieve multiple issues with filtering and pagination."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_issues_{project_id or 'all'}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="Issue",
|
||||
metadata={
|
||||
"project_id": project_id,
|
||||
"state": state,
|
||||
"labels": labels,
|
||||
"limit": limit,
|
||||
"offset": offset
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
# Build query parameters
|
||||
params = {
|
||||
"limit": limit,
|
||||
"page": (offset // limit) + 1 # Gitea uses 1-based pagination
|
||||
}
|
||||
|
||||
if state:
|
||||
params["state"] = state
|
||||
|
||||
if labels:
|
||||
params["labels"] = ",".join(labels)
|
||||
|
||||
if not self.repo_owner or not self.repo_name:
|
||||
raise ValidationError("repo_info", None, "Repository owner and name must be set", context)
|
||||
|
||||
endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}/issues"
|
||||
async with session.get(endpoint, params=params) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
return [self._map_api_issue_to_domain(issue_data) for issue_data in data]
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting issues: {e}")
|
||||
raise NetworkError("get issues", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def create_issue(
|
||||
self,
|
||||
title: str,
|
||||
body: str,
|
||||
labels: Optional[List[str]] = None,
|
||||
assignees: Optional[List[str]] = None,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> Issue:
|
||||
"""Create a new issue via Gitea API."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"create_issue_{title[:50]}",
|
||||
operation_type=OperationType.WRITE,
|
||||
resource_type="Issue",
|
||||
request_data={
|
||||
"title": title,
|
||||
"body": body,
|
||||
"labels": labels,
|
||||
"assignees": assignees
|
||||
}
|
||||
)
|
||||
|
||||
# Validate input
|
||||
if not title or not title.strip():
|
||||
raise ValidationError("title", title, "Title cannot be empty", context)
|
||||
|
||||
if len(title) > 255:
|
||||
raise ValidationError("title", title, "Title cannot exceed 255 characters", context)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
# Prepare request payload
|
||||
payload = {
|
||||
"title": title.strip(),
|
||||
"body": body or ""
|
||||
}
|
||||
|
||||
if labels:
|
||||
payload["labels"] = labels
|
||||
|
||||
if assignees:
|
||||
payload["assignees"] = assignees
|
||||
|
||||
if not self.repo_owner or not self.repo_name:
|
||||
raise ValidationError("repo_info", None, "Repository owner and name must be set", context)
|
||||
|
||||
endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}/issues"
|
||||
async with session.post(endpoint, json=payload) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
created_issue = self._map_api_issue_to_domain(data)
|
||||
|
||||
logger.info(f"Created issue #{created_issue.number}: {title}")
|
||||
return created_issue
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error creating issue '{title}': {e}")
|
||||
raise NetworkError(f"create issue '{title}'", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def update_issue(
|
||||
self,
|
||||
issue_number: int,
|
||||
title: Optional[str] = None,
|
||||
body: Optional[str] = None,
|
||||
state: Optional[str] = None,
|
||||
labels: Optional[List[str]] = None,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> Issue:
|
||||
"""Update an existing issue via Gitea API."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"update_issue_{issue_number}",
|
||||
operation_type=OperationType.UPDATE,
|
||||
resource_type="Issue",
|
||||
resource_id=str(issue_number),
|
||||
request_data={
|
||||
"title": title,
|
||||
"body": body,
|
||||
"state": state,
|
||||
"labels": labels
|
||||
}
|
||||
)
|
||||
|
||||
# Validate input
|
||||
if title is not None:
|
||||
if not title.strip():
|
||||
raise ValidationError("title", title, "Title cannot be empty", context)
|
||||
if len(title) > 255:
|
||||
raise ValidationError("title", title, "Title cannot exceed 255 characters", context)
|
||||
|
||||
if state is not None and state not in ["open", "closed"]:
|
||||
raise ValidationError("state", state, "State must be 'open' or 'closed'", context)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
# First, get current issue to check for concurrent modifications
|
||||
current_issue = await self.get_issue(issue_number, context)
|
||||
|
||||
# Prepare update payload
|
||||
payload = {}
|
||||
|
||||
if title is not None:
|
||||
payload["title"] = title.strip()
|
||||
|
||||
if body is not None:
|
||||
payload["body"] = body
|
||||
|
||||
if state is not None:
|
||||
payload["state"] = state
|
||||
|
||||
if labels is not None:
|
||||
payload["labels"] = labels
|
||||
|
||||
# Only update if there are changes
|
||||
if not payload:
|
||||
return current_issue
|
||||
|
||||
if not self.repo_owner or not self.repo_name:
|
||||
raise ValidationError("repo_info", None, "Repository owner and name must be set", context)
|
||||
|
||||
endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}/issues/{issue_number}"
|
||||
async with session.patch(endpoint, json=payload) as response:
|
||||
# Handle potential concurrent modification
|
||||
if response.status == 409:
|
||||
raise ConcurrencyError("Issue", str(issue_number), context)
|
||||
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
updated_issue = self._map_api_issue_to_domain(data)
|
||||
|
||||
logger.info(f"Updated issue #{issue_number}")
|
||||
return updated_issue
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error updating issue {issue_number}: {e}")
|
||||
raise NetworkError(f"update issue {issue_number}", e, context)
|
||||
|
||||
async def get_issue_project_info(
|
||||
self,
|
||||
issue_number: int,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get project-related information for an issue."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_issue_project_info_{issue_number}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="ProjectInfo",
|
||||
resource_id=str(issue_number)
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
# Get issue details first
|
||||
issue = await self.get_issue(issue_number, context)
|
||||
|
||||
# Get repository information
|
||||
if not self.repo_owner or not self.repo_name:
|
||||
raise ValidationError("repo_info", None, "Repository owner and name must be set", context)
|
||||
|
||||
repo_endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}"
|
||||
async with session.get(repo_endpoint) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
repo_data = await response.json()
|
||||
|
||||
# Get project boards if available
|
||||
project_info = {
|
||||
"repository": repo_data,
|
||||
"kanban_columns": ["Todo", "In Progress", "Review", "Done"], # Default columns
|
||||
"issue": {
|
||||
"number": issue.number,
|
||||
"title": issue.title,
|
||||
"state": issue.state.value,
|
||||
"labels": [label.name for label in issue.labels]
|
||||
}
|
||||
}
|
||||
|
||||
# Try to get actual project boards
|
||||
try:
|
||||
projects_endpoint = f"/api/v1/repos/{self.repo_owner}/{self.repo_name}/projects"
|
||||
async with session.get(projects_endpoint) as projects_response:
|
||||
if projects_response.status == 200:
|
||||
projects_data = await projects_response.json()
|
||||
if projects_data:
|
||||
# Use first project's columns if available
|
||||
project_info["projects"] = projects_data
|
||||
except Exception:
|
||||
# Projects API might not be available, use defaults
|
||||
pass
|
||||
|
||||
return project_info
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting project info for issue {issue_number}: {e}")
|
||||
raise NetworkError(f"get project info for issue {issue_number}", e, context)
|
||||
|
||||
def _map_api_issue_to_domain(self, api_data: Dict[str, Any]) -> Issue:
|
||||
"""Map Gitea API issue data to domain Issue object."""
|
||||
# Map labels
|
||||
labels = []
|
||||
if "labels" in api_data:
|
||||
for label_data in api_data["labels"]:
|
||||
label = Label(
|
||||
name=label_data["name"],
|
||||
color=label_data.get("color", ""),
|
||||
description=label_data.get("description", "")
|
||||
)
|
||||
labels.append(label)
|
||||
|
||||
# Map state
|
||||
state_value = api_data.get("state", "open")
|
||||
issue_state = IssueState.OPEN if state_value == "open" else IssueState.CLOSED
|
||||
|
||||
# Parse dates
|
||||
created_at = datetime.fromisoformat(api_data["created_at"].replace("Z", "+00:00"))
|
||||
updated_at = datetime.fromisoformat(api_data["updated_at"].replace("Z", "+00:00"))
|
||||
|
||||
closed_at = None
|
||||
if api_data.get("closed_at"):
|
||||
closed_at = datetime.fromisoformat(api_data["closed_at"].replace("Z", "+00:00"))
|
||||
|
||||
return Issue(
|
||||
number=api_data["number"],
|
||||
title=api_data["title"],
|
||||
state=issue_state,
|
||||
labels=labels,
|
||||
created_at=created_at,
|
||||
updated_at=updated_at,
|
||||
milestone=api_data.get("milestone", {}).get("title") if api_data.get("milestone") else None,
|
||||
assignee=api_data.get("assignees", [{}])[0].get("login") if api_data.get("assignees") else None,
|
||||
closed_at=closed_at
|
||||
)
|
||||
|
||||
async def _handle_response_errors(self, response: aiohttp.ClientResponse, context: ErrorContext):
|
||||
"""Handle HTTP response errors and convert to appropriate exceptions."""
|
||||
if response.status == 200 or response.status == 201:
|
||||
return
|
||||
|
||||
response_text = await response.text()
|
||||
|
||||
if response.status == 404:
|
||||
resource_id = context.resource_id or "unknown"
|
||||
raise ResourceNotFoundError(context.resource_type, resource_id, context)
|
||||
|
||||
elif response.status == 401:
|
||||
raise GiteaApiError(
|
||||
response.status,
|
||||
"Authentication failed - check API token",
|
||||
str(response.url),
|
||||
context
|
||||
)
|
||||
|
||||
elif response.status == 403:
|
||||
raise GiteaApiError(
|
||||
response.status,
|
||||
"Access forbidden - check API permissions",
|
||||
str(response.url),
|
||||
context
|
||||
)
|
||||
|
||||
elif response.status == 409:
|
||||
# Conflict - usually concurrent modification
|
||||
raise ConcurrencyError(context.resource_type, context.resource_id or "unknown", context)
|
||||
|
||||
elif response.status == 422:
|
||||
# Validation error
|
||||
try:
|
||||
error_data = await response.json()
|
||||
error_message = error_data.get("message", response_text)
|
||||
except:
|
||||
error_message = response_text
|
||||
|
||||
raise ValidationError("request", None, error_message, context)
|
||||
|
||||
elif response.status >= 500:
|
||||
raise GiteaApiError(
|
||||
response.status,
|
||||
f"Server error: {response_text}",
|
||||
str(response.url),
|
||||
context
|
||||
)
|
||||
|
||||
else:
|
||||
raise GiteaApiError(
|
||||
response.status,
|
||||
response_text,
|
||||
str(response.url),
|
||||
context
|
||||
)
|
||||
|
||||
|
||||
class GiteaProjectRepository(ProjectRepository):
|
||||
"""
|
||||
Gitea implementation of ProjectRepository.
|
||||
|
||||
Provides access to project and milestone information via Gitea API.
|
||||
"""
|
||||
|
||||
def __init__(self, connection_manager: ConnectionManager, retry_config: Optional[RetryConfig] = None):
|
||||
self.connection_manager = connection_manager
|
||||
self.retry_config = retry_config or RetryConfig()
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def get_project(self, project_id: str, context: Optional[ErrorContext] = None) -> Project:
|
||||
"""Retrieve a project by its ID from Gitea API."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_project_{project_id}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="Project",
|
||||
resource_id=project_id
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
async with session.get(f"/api/v1/repos/projects/{project_id}") as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
return self._map_api_project_to_domain(data)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting project {project_id}: {e}")
|
||||
raise NetworkError(f"get project {project_id}", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def get_projects(
|
||||
self,
|
||||
organization: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> List[Project]:
|
||||
"""Retrieve multiple projects with pagination."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_projects_{organization or 'all'}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="Project",
|
||||
metadata={
|
||||
"organization": organization,
|
||||
"limit": limit,
|
||||
"offset": offset
|
||||
}
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
params = {
|
||||
"limit": limit,
|
||||
"page": (offset // limit) + 1
|
||||
}
|
||||
|
||||
endpoint = "/api/v1/repos/projects"
|
||||
if organization:
|
||||
endpoint = f"/api/v1/orgs/{organization}/projects"
|
||||
|
||||
async with session.get(endpoint, params=params) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
return [self._map_api_project_to_domain(project_data) for project_data in data]
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting projects: {e}")
|
||||
raise NetworkError("get projects", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def get_milestones(
|
||||
self,
|
||||
project_id: str,
|
||||
state: Optional[str] = None,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> List[Milestone]:
|
||||
"""Retrieve milestones for a project."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"get_milestones_{project_id}",
|
||||
operation_type=OperationType.READ,
|
||||
resource_type="Milestone",
|
||||
metadata={"project_id": project_id, "state": state}
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
params = {}
|
||||
if state:
|
||||
params["state"] = state
|
||||
|
||||
# Note: This would need repo info from GiteaIssueRepository, but for now use general endpoint
|
||||
async with session.get("/api/v1/repos/milestones", params=params) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
return [self._map_api_milestone_to_domain(milestone_data) for milestone_data in data]
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error getting milestones for project {project_id}: {e}")
|
||||
raise NetworkError(f"get milestones for project {project_id}", e, context)
|
||||
|
||||
@retry_with_backoff(RetryConfig())
|
||||
async def create_milestone(
|
||||
self,
|
||||
project_id: str,
|
||||
title: str,
|
||||
description: str,
|
||||
due_date: Optional[str] = None,
|
||||
context: Optional[ErrorContext] = None
|
||||
) -> Milestone:
|
||||
"""Create a new milestone for a project."""
|
||||
if context is None:
|
||||
context = ErrorContext(
|
||||
operation_id=f"create_milestone_{title[:50]}",
|
||||
operation_type=OperationType.WRITE,
|
||||
resource_type="Milestone",
|
||||
request_data={
|
||||
"project_id": project_id,
|
||||
"title": title,
|
||||
"description": description,
|
||||
"due_date": due_date
|
||||
}
|
||||
)
|
||||
|
||||
# Validate input
|
||||
if not title or not title.strip():
|
||||
raise ValidationError("title", title, "Milestone title cannot be empty", context)
|
||||
|
||||
try:
|
||||
session = await self.connection_manager.get_http_session()
|
||||
|
||||
payload = {
|
||||
"title": title.strip(),
|
||||
"description": description or ""
|
||||
}
|
||||
|
||||
if due_date:
|
||||
payload["due_on"] = due_date
|
||||
|
||||
# Note: This would need repo info from GiteaIssueRepository, but for now use general endpoint
|
||||
async with session.post("/api/v1/repos/milestones", json=payload) as response:
|
||||
await self._handle_response_errors(response, context)
|
||||
|
||||
data = await response.json()
|
||||
created_milestone = self._map_api_milestone_to_domain(data)
|
||||
|
||||
logger.info(f"Created milestone: {title}")
|
||||
return created_milestone
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"Network error creating milestone '{title}': {e}")
|
||||
raise NetworkError(f"create milestone '{title}'", e, context)
|
||||
|
||||
def _map_api_project_to_domain(self, api_data: Dict[str, Any]) -> Project:
|
||||
"""Map Gitea API project data to domain Project object."""
|
||||
# For now, create a basic project since Gitea projects API might be limited
|
||||
created_at = datetime.fromisoformat(api_data.get("created_at", datetime.now(timezone.utc).isoformat()).replace("Z", "+00:00"))
|
||||
updated_at = datetime.fromisoformat(api_data.get("updated_at", datetime.now(timezone.utc).isoformat()).replace("Z", "+00:00"))
|
||||
|
||||
return Project(
|
||||
id=str(api_data.get("id", 0)),
|
||||
name=api_data.get("title", api_data.get("name", "Unknown Project")),
|
||||
description=api_data.get("body", api_data.get("description", "")),
|
||||
state=ProjectState.ACTIVE, # Default to active
|
||||
milestones=[], # Will be populated separately
|
||||
created_at=created_at,
|
||||
updated_at=updated_at
|
||||
)
|
||||
|
||||
def _map_api_milestone_to_domain(self, api_data: Dict[str, Any]) -> Milestone:
|
||||
"""Map Gitea API milestone data to domain Milestone object."""
|
||||
created_at = datetime.fromisoformat(api_data["created_at"].replace("Z", "+00:00"))
|
||||
updated_at = datetime.fromisoformat(api_data["updated_at"].replace("Z", "+00:00"))
|
||||
|
||||
due_date = None
|
||||
if api_data.get("due_on"):
|
||||
due_date = datetime.fromisoformat(api_data["due_on"].replace("Z", "+00:00"))
|
||||
|
||||
return Milestone(
|
||||
id=api_data["id"],
|
||||
title=api_data["title"],
|
||||
description=api_data.get("description", ""),
|
||||
state=api_data.get("state", "open"),
|
||||
open_issues=api_data.get("open_issues", 0),
|
||||
closed_issues=api_data.get("closed_issues", 0),
|
||||
due_date=due_date,
|
||||
created_at=created_at,
|
||||
updated_at=updated_at
|
||||
)
|
||||
|
||||
async def _handle_response_errors(self, response: aiohttp.ClientResponse, context: ErrorContext):
|
||||
"""Handle HTTP response errors and convert to appropriate exceptions."""
|
||||
# Reuse the same error handling logic from GiteaIssueRepository
|
||||
if response.status == 200 or response.status == 201:
|
||||
return
|
||||
|
||||
response_text = await response.text()
|
||||
|
||||
if response.status == 404:
|
||||
resource_id = context.resource_id or "unknown"
|
||||
raise ResourceNotFoundError(context.resource_type, resource_id, context)
|
||||
|
||||
elif response.status >= 400:
|
||||
raise GiteaApiError(
|
||||
response.status,
|
||||
response_text,
|
||||
str(response.url),
|
||||
context
|
||||
)
|
||||
@@ -11,7 +11,7 @@ from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Base version from pyproject.toml
|
||||
__version__ = "0.2.0"
|
||||
__version__ = "0.4.0"
|
||||
|
||||
def get_git_commit_hash() -> Optional[str]:
|
||||
"""Get the current git commit hash if available."""
|
||||
|
||||
@@ -64,8 +64,10 @@ class AssetManager:
|
||||
assets_config.get('storage_path', DEFAULT_ASSETS_DIR)
|
||||
).resolve()
|
||||
|
||||
# Default registry path should be relative to storage_path, not cwd
|
||||
default_registry_path = self.storage_path.parent / DEFAULT_REGISTRY_FILENAME
|
||||
self.registry_path = Path(
|
||||
assets_config.get('registry_path', DEFAULT_REGISTRY_FILENAME)
|
||||
assets_config.get('registry_path', default_registry_path)
|
||||
).resolve()
|
||||
|
||||
self.database_path = Path(
|
||||
|
||||
@@ -109,8 +109,6 @@ from .schema_generator import SchemaGenerator
|
||||
from .schema_validator import SchemaValidator
|
||||
from .exceptions import FileNotFoundError, InvalidDepthError, SchemaValidationError, InvalidSchemaError
|
||||
|
||||
# Issue management commands - also available via dedicated 'issue' CLI or 'tddai' CLI
|
||||
from .issues.commands import issues_group
|
||||
|
||||
# Global options for CLI configuration
|
||||
pass_config = click.make_pass_decorator(dict, ensure=True)
|
||||
@@ -6184,23 +6182,12 @@ cli.add_command(wishlist_group)
|
||||
|
||||
|
||||
# Register issue management commands
|
||||
cli.add_command(issues_group)
|
||||
|
||||
# Register issue activity tracking commands
|
||||
from markitect.issues.activity_commands import activity as activity_group
|
||||
cli.add_command(activity_group)
|
||||
|
||||
# Register worktime tracking commands
|
||||
from markitect.finance.worktime_commands import worktime as worktime_group
|
||||
cli.add_command(worktime_group)
|
||||
|
||||
# Register day wrap-up commands
|
||||
from markitect.finance.day_wrapup_commands import wrapup as wrapup_group
|
||||
cli.add_command(wrapup_group)
|
||||
|
||||
# Register issue wrap-up commands
|
||||
from markitect.issues.issue_wrapup_commands import issue_wrapup as issue_wrapup_group
|
||||
cli.add_command(issue_wrapup_group)
|
||||
|
||||
|
||||
# Query Paradigm Commands - Issue #62
|
||||
|
||||
@@ -574,35 +574,35 @@ class DocumentManager:
|
||||
const sections = content.querySelectorAll('.markitect-section-editable');
|
||||
let reconstructed = '';
|
||||
|
||||
sections.forEach(section => {
|
||||
sections.forEach(section => {{
|
||||
const tagName = section.tagName.toLowerCase();
|
||||
const text = section.textContent.trim();
|
||||
|
||||
if (tagName.startsWith('h')) {
|
||||
if (tagName.startsWith('h')) {{
|
||||
const level = parseInt(tagName.charAt(1));
|
||||
reconstructed += '#'.repeat(level) + ' ' + text + '\n\n';
|
||||
} else if (tagName === 'p') {
|
||||
reconstructed += text + '\n\n';
|
||||
} else if (tagName === 'blockquote') {
|
||||
reconstructed += '> ' + text + '\n\n';
|
||||
} else if (tagName === 'pre') {
|
||||
reconstructed += '```\n' + text + '\n```\n\n';
|
||||
} else if (tagName === 'ul') {
|
||||
reconstructed += '#'.repeat(level) + ' ' + text + '\\n\\n';
|
||||
}} else if (tagName === 'p') {{
|
||||
reconstructed += text + '\\n\\n';
|
||||
}} else if (tagName === 'blockquote') {{
|
||||
reconstructed += '> ' + text + '\\n\\n';
|
||||
}} else if (tagName === 'pre') {{
|
||||
reconstructed += '```\\n' + text + '\\n```\\n\\n';
|
||||
}} else if (tagName === 'ul') {{
|
||||
const items = section.querySelectorAll('li');
|
||||
items.forEach(item => {
|
||||
reconstructed += '- ' + item.textContent.trim() + '\n';
|
||||
});
|
||||
reconstructed += '\n';
|
||||
} else if (tagName === 'ol') {
|
||||
items.forEach(item => {{
|
||||
reconstructed += '- ' + item.textContent.trim() + '\\n';
|
||||
}});
|
||||
reconstructed += '\\n';
|
||||
}} else if (tagName === 'ol') {{
|
||||
const items = section.querySelectorAll('li');
|
||||
items.forEach((item, index) => {
|
||||
reconstructed += `${index + 1}. ` + item.textContent.trim() + '\n';
|
||||
});
|
||||
reconstructed += '\n';
|
||||
} else {
|
||||
reconstructed += text + '\n\n';
|
||||
}
|
||||
});
|
||||
items.forEach((item, index) => {{
|
||||
reconstructed += (index + 1) + '. ' + item.textContent.trim() + '\\n';
|
||||
}});
|
||||
reconstructed += '\\n';
|
||||
}} else {{
|
||||
reconstructed += text + '\\n\\n';
|
||||
}}
|
||||
}});
|
||||
|
||||
return reconstructed.trim();
|
||||
}
|
||||
@@ -617,9 +617,82 @@ class DocumentManager:
|
||||
# Edit mode status and error reporting section
|
||||
edit_mode_html = ""
|
||||
if edit_mode:
|
||||
# Get version info for header
|
||||
try:
|
||||
import markitect
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
# Get base version
|
||||
version = "0.3.0" # fallback
|
||||
try:
|
||||
from importlib.metadata import version as get_version
|
||||
version = get_version('markitect')
|
||||
except:
|
||||
pass
|
||||
|
||||
# Get git commit with timestamp and local changes info
|
||||
git_info = ""
|
||||
try:
|
||||
repo_path = Path(__file__).parent.parent
|
||||
|
||||
# Get commit hash and timestamp
|
||||
result = subprocess.run(['git', 'rev-parse', '--short', 'HEAD'],
|
||||
capture_output=True, text=True, cwd=repo_path)
|
||||
if result.returncode == 0:
|
||||
commit_hash = result.stdout.strip()
|
||||
|
||||
# Get commit timestamp
|
||||
timestamp_result = subprocess.run(['git', 'show', '-s', '--format=%ci', 'HEAD'],
|
||||
capture_output=True, text=True, cwd=repo_path)
|
||||
commit_time = ""
|
||||
if timestamp_result.returncode == 0:
|
||||
from datetime import datetime
|
||||
# Parse git timestamp and format it nicely
|
||||
git_time = timestamp_result.stdout.strip()
|
||||
try:
|
||||
dt = datetime.fromisoformat(git_time.replace(' +', '+'))
|
||||
commit_time = f" ({dt.strftime('%Y-%m-%d %H:%M')})"
|
||||
except:
|
||||
pass
|
||||
|
||||
git_info = f"+{commit_hash}{commit_time}"
|
||||
|
||||
# Check for uncommitted changes
|
||||
status_result = subprocess.run(['git', 'status', '--porcelain'],
|
||||
capture_output=True, text=True, cwd=repo_path)
|
||||
if status_result.returncode == 0 and status_result.stdout.strip():
|
||||
# Get timestamp of most recent uncommitted change
|
||||
import os
|
||||
import glob
|
||||
|
||||
latest_change = 0
|
||||
for line in status_result.stdout.strip().split('\n'):
|
||||
if line.strip():
|
||||
# Extract filename (skip first 3 chars which are status indicators)
|
||||
filename = line[3:].strip()
|
||||
try:
|
||||
file_path = repo_path / filename
|
||||
if file_path.exists():
|
||||
mtime = os.path.getmtime(file_path)
|
||||
latest_change = max(latest_change, mtime)
|
||||
except:
|
||||
pass
|
||||
|
||||
if latest_change > 0:
|
||||
change_dt = datetime.fromtimestamp(latest_change)
|
||||
git_info += f" including local changes until {change_dt.strftime('%Y-%m-%d %H:%M')}"
|
||||
|
||||
except:
|
||||
pass
|
||||
|
||||
version_info = f"{version}{git_info}"
|
||||
except:
|
||||
version_info = "0.3.0"
|
||||
|
||||
edit_mode_html = f"""
|
||||
<div id="markitect-status" style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 12px; margin-bottom: 20px; font-family: monospace; font-size: 14px;">
|
||||
<div style="font-weight: bold; color: #1976d2;">📝 Markitect Edit Mode</div>
|
||||
<div style="font-weight: bold; color: #1976d2;">📝 Markitect Edit Mode <span style="font-weight: normal; color: #666;">v{version_info}</span></div>
|
||||
<div id="status-message" style="margin-top: 8px;">Loading edit capabilities...</div>
|
||||
<div id="error-details" style="display: none; background: #ffebee; border: 1px solid #f44336; padding: 8px; margin-top: 8px; border-radius: 4px;">
|
||||
<div style="font-weight: bold; color: #c62828;">❌ Edit Mode Failed</div>
|
||||
@@ -659,20 +732,56 @@ class DocumentManager:
|
||||
// Define editor class first (if in edit mode)
|
||||
{editor_scripts if edit_mode else ''}
|
||||
|
||||
// Error reporting utility
|
||||
function reportEditModeError(errorMsg, technicalDetails) {{
|
||||
// Enhanced error reporting utility
|
||||
function reportEditModeError(errorMsg, technicalDetails, errorType = 'error') {{
|
||||
const statusDiv = document.getElementById('markitect-status');
|
||||
const errorDiv = document.getElementById('error-details');
|
||||
const errorText = document.getElementById('error-text');
|
||||
const statusMsg = document.getElementById('status-message');
|
||||
const browserInfo = document.getElementById('browser-info');
|
||||
|
||||
if (statusMsg) statusMsg.textContent = 'Edit mode unavailable - content displayed in read-only mode';
|
||||
// Log to console for debugging
|
||||
console.error('[MarkiTect Edit Mode Error]', errorMsg, technicalDetails);
|
||||
|
||||
// Create error report object
|
||||
const errorReport = {{
|
||||
timestamp: new Date().toISOString(),
|
||||
error: errorMsg,
|
||||
details: technicalDetails,
|
||||
type: errorType,
|
||||
userAgent: navigator.userAgent,
|
||||
url: window.location.href,
|
||||
markdownContent: typeof markdownContent !== 'undefined' ? markdownContent.length + ' chars' : 'unavailable'
|
||||
}};
|
||||
|
||||
// Store error for potential reporting
|
||||
if (!window.markitectErrors) window.markitectErrors = [];
|
||||
window.markitectErrors.push(errorReport);
|
||||
|
||||
// Update UI
|
||||
if (statusMsg) {{
|
||||
const statusText = errorType === 'warning'
|
||||
? 'Edit mode partially available - some features may not work'
|
||||
: 'Edit mode unavailable - content displayed in read-only mode';
|
||||
statusMsg.textContent = statusText;
|
||||
}}
|
||||
|
||||
if (errorDiv) errorDiv.style.display = 'block';
|
||||
if (errorText) errorText.textContent = errorMsg + (technicalDetails ? ' (' + technicalDetails + ')' : '');
|
||||
if (errorText) {{
|
||||
const fullError = errorMsg + (technicalDetails ? ' (' + technicalDetails + ')' : '');
|
||||
errorText.textContent = fullError;
|
||||
}}
|
||||
if (browserInfo) browserInfo.textContent = navigator.userAgent.split(' ').slice(-2).join(' ');
|
||||
|
||||
// Auto-hide warnings after 10 seconds
|
||||
if (errorType === 'warning' && errorDiv) {{
|
||||
setTimeout(() => {{
|
||||
errorDiv.style.display = 'none';
|
||||
}}, 10000);
|
||||
}}
|
||||
}}
|
||||
|
||||
|
||||
// Status update utility
|
||||
function updateStatus(message, isError = false) {{
|
||||
const statusMsg = document.getElementById('status-message');
|
||||
|
||||
@@ -1,566 +0,0 @@
|
||||
"""
|
||||
Cost Allocation Engine for MarkiTect Issue Cost Distribution.
|
||||
|
||||
This module implements the core allocation engine that distributes operational
|
||||
costs across active issues using the defined algorithm from Issue #88.
|
||||
|
||||
The engine handles:
|
||||
- Equal distribution of costs across active issues in a period
|
||||
- Loss carried forward when no active issues exist
|
||||
- Transaction audit trail creation
|
||||
- Edge case handling and validation
|
||||
- Integration with period management and activity tracking
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import List, Dict, Any, Optional, Tuple
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
from .models import FinanceModels
|
||||
from .cost_manager import CostItemManager
|
||||
from .period_manager import PeriodManager, Period, PeriodStatus
|
||||
from ..issues.activity_tracker import IssueActivityTracker, ActivityType
|
||||
|
||||
|
||||
class AllocationStatus(Enum):
|
||||
"""Status enumeration for allocation operations."""
|
||||
SUCCESS = "success"
|
||||
NO_ACTIVE_ISSUES = "no_active_issues"
|
||||
NO_COSTS_TO_ALLOCATE = "no_costs_to_allocate"
|
||||
PERIOD_CLOSED = "period_closed"
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
@dataclass
|
||||
class AllocationResult:
|
||||
"""Result of a cost allocation operation."""
|
||||
status: AllocationStatus
|
||||
period_id: int
|
||||
total_costs: Decimal = Decimal('0.00')
|
||||
active_issues: List[int] = None
|
||||
cost_per_issue: Decimal = Decimal('0.00')
|
||||
allocations_created: int = 0
|
||||
transactions_created: int = 0
|
||||
loss_carried_forward: Decimal = Decimal('0.00')
|
||||
message: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
if self.active_issues is None:
|
||||
self.active_issues = []
|
||||
|
||||
|
||||
@dataclass
|
||||
class IssueAllocation:
|
||||
"""Represents a cost allocation to a specific issue."""
|
||||
issue_id: int
|
||||
allocated_amount: Decimal
|
||||
allocation_date: date
|
||||
period_id: int
|
||||
transaction_id: Optional[int] = None
|
||||
|
||||
|
||||
class TransactionManager:
|
||||
"""Manages cost transaction audit trails for allocations."""
|
||||
|
||||
def __init__(self, db_path: str):
|
||||
"""
|
||||
Initialize transaction manager.
|
||||
|
||||
Args:
|
||||
db_path: Path to the SQLite database
|
||||
"""
|
||||
self.db_path = db_path
|
||||
self.finance_models = FinanceModels(db_path)
|
||||
|
||||
def create_allocation_transaction(
|
||||
self,
|
||||
period_id: int,
|
||||
amount: Decimal,
|
||||
issue_id: int,
|
||||
transaction_date: date,
|
||||
description: str
|
||||
) -> int:
|
||||
"""
|
||||
Create a cost allocation transaction record.
|
||||
|
||||
Args:
|
||||
period_id: ID of the cost period
|
||||
amount: Amount allocated to the issue
|
||||
issue_id: ID of the issue receiving allocation
|
||||
transaction_date: Date of the transaction
|
||||
description: Description of the allocation
|
||||
|
||||
Returns:
|
||||
ID of the created transaction
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO cost_transactions
|
||||
(period_id, transaction_type, amount_eur, issue_id,
|
||||
transaction_date, description)
|
||||
VALUES (?, 'cost_allocated', ?, ?, ?, ?)
|
||||
''', (period_id, float(amount), issue_id, transaction_date.isoformat() if hasattr(transaction_date, 'isoformat') else transaction_date, description))
|
||||
|
||||
return cursor.lastrowid
|
||||
|
||||
def create_loss_forward_transaction(
|
||||
self,
|
||||
from_period_id: int,
|
||||
to_period_id: int,
|
||||
amount: Decimal,
|
||||
transaction_date: date,
|
||||
description: str
|
||||
) -> int:
|
||||
"""
|
||||
Create a loss carried forward transaction.
|
||||
|
||||
Args:
|
||||
from_period_id: Source period ID
|
||||
to_period_id: Destination period ID
|
||||
amount: Amount being carried forward
|
||||
transaction_date: Date of the transaction
|
||||
description: Description of the carry forward
|
||||
|
||||
Returns:
|
||||
ID of the created transaction
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO cost_transactions
|
||||
(period_id, transaction_type, amount_eur, transaction_date, description)
|
||||
VALUES (?, 'loss_forward', ?, ?, ?)
|
||||
''', (to_period_id, float(amount), transaction_date.isoformat() if hasattr(transaction_date, 'isoformat') else transaction_date, description))
|
||||
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
class AllocationEngine:
|
||||
"""
|
||||
Core cost allocation engine for distributing operational costs to active issues.
|
||||
|
||||
Implements the algorithm defined in Issue #88:
|
||||
1. Calculate total costs for the period (monthly + one-time + carried forward)
|
||||
2. Identify active issues (created/modified during period)
|
||||
3. Distribute costs equally among active issues
|
||||
4. Handle edge cases (no active issues -> carry forward loss)
|
||||
5. Create audit trail transactions
|
||||
6. Update period statistics
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "markitect.db"):
|
||||
"""
|
||||
Initialize the allocation engine.
|
||||
|
||||
Args:
|
||||
db_path: Path to the SQLite database
|
||||
"""
|
||||
self.db_path = db_path
|
||||
self.finance_models = FinanceModels(db_path)
|
||||
self.cost_manager = CostItemManager(db_path)
|
||||
self.period_manager = PeriodManager(db_path)
|
||||
self.activity_tracker = IssueActivityTracker(db_path)
|
||||
self.transaction_manager = TransactionManager(db_path)
|
||||
|
||||
# Ensure database schema is initialized
|
||||
self.finance_models.initialize_finance_schema()
|
||||
|
||||
def allocate_period_costs(self, period_id: int) -> AllocationResult:
|
||||
"""
|
||||
Allocate costs for a specific period to active issues.
|
||||
|
||||
Args:
|
||||
period_id: ID of the period to process
|
||||
|
||||
Returns:
|
||||
AllocationResult with operation details and status
|
||||
"""
|
||||
try:
|
||||
# Get period details
|
||||
period = self._get_period(period_id)
|
||||
if not period:
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.ERROR,
|
||||
period_id=period_id,
|
||||
message=f"Period {period_id} not found"
|
||||
)
|
||||
|
||||
# Check if period is already closed
|
||||
if period.status == PeriodStatus.CLOSED.value:
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.PERIOD_CLOSED,
|
||||
period_id=period_id,
|
||||
message=f"Period {period_id} is already closed"
|
||||
)
|
||||
|
||||
# Set period status to calculating
|
||||
self._update_period_status(period_id, PeriodStatus.CALCULATING)
|
||||
|
||||
# Step 1: Calculate total costs for period
|
||||
total_costs = self._calculate_period_total_costs(period)
|
||||
|
||||
if total_costs == Decimal('0.00'):
|
||||
self._update_period_status(period_id, PeriodStatus.CLOSED)
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.NO_COSTS_TO_ALLOCATE,
|
||||
period_id=period_id,
|
||||
total_costs=total_costs,
|
||||
message="No costs to allocate for this period"
|
||||
)
|
||||
|
||||
# Step 2: Identify active issues for the period
|
||||
active_issues = self._get_active_issues_for_period(period)
|
||||
|
||||
if not active_issues:
|
||||
# No active issues - carry forward loss to next period
|
||||
next_period_id = self._get_or_create_next_period(period)
|
||||
if next_period_id:
|
||||
self._carry_forward_loss(period_id, next_period_id, total_costs)
|
||||
|
||||
# Update period and close
|
||||
self._update_period_totals(period_id, total_costs, 0, Decimal('0.00'), total_costs)
|
||||
self._update_period_status(period_id, PeriodStatus.CLOSED)
|
||||
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.NO_ACTIVE_ISSUES,
|
||||
period_id=period_id,
|
||||
total_costs=total_costs,
|
||||
active_issues=[],
|
||||
loss_carried_forward=total_costs,
|
||||
message=f"No active issues found. Carried forward €{total_costs:.2f} to next period"
|
||||
)
|
||||
|
||||
# Step 3: Calculate cost per issue (equal distribution)
|
||||
cost_per_issue = total_costs / len(active_issues)
|
||||
|
||||
# Step 4: Create allocations and transactions
|
||||
allocations_created = 0
|
||||
transactions_created = 0
|
||||
allocation_date = date.today()
|
||||
|
||||
for issue_id in active_issues:
|
||||
# Create allocation record
|
||||
allocation_id = self._create_issue_allocation(
|
||||
issue_id, period_id, cost_per_issue, allocation_date
|
||||
)
|
||||
|
||||
if allocation_id:
|
||||
allocations_created += 1
|
||||
|
||||
# Create audit transaction
|
||||
transaction_id = self.transaction_manager.create_allocation_transaction(
|
||||
period_id=period_id,
|
||||
amount=cost_per_issue,
|
||||
issue_id=issue_id,
|
||||
transaction_date=allocation_date,
|
||||
description=f"Cost allocation for period {period.period_start} to {period.period_end}"
|
||||
)
|
||||
|
||||
if transaction_id:
|
||||
transactions_created += 1
|
||||
# Link transaction to allocation
|
||||
self._update_allocation_transaction_id(allocation_id, transaction_id)
|
||||
|
||||
# Step 5: Update period totals
|
||||
self._update_period_totals(
|
||||
period_id, total_costs, len(active_issues), cost_per_issue, Decimal('0.00')
|
||||
)
|
||||
|
||||
# Step 6: Close the period
|
||||
self._update_period_status(period_id, PeriodStatus.CLOSED)
|
||||
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.SUCCESS,
|
||||
period_id=period_id,
|
||||
total_costs=total_costs,
|
||||
active_issues=active_issues,
|
||||
cost_per_issue=cost_per_issue,
|
||||
allocations_created=allocations_created,
|
||||
transactions_created=transactions_created,
|
||||
message=f"Successfully allocated €{total_costs:.2f} across {len(active_issues)} issues"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
# Reset period status on error
|
||||
self._update_period_status(period_id, PeriodStatus.OPEN)
|
||||
return AllocationResult(
|
||||
status=AllocationStatus.ERROR,
|
||||
period_id=period_id,
|
||||
message=f"Allocation failed: {str(e)}"
|
||||
)
|
||||
|
||||
def get_issue_allocations(self, issue_id: int) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get all cost allocations for a specific issue.
|
||||
|
||||
Args:
|
||||
issue_id: ID of the issue
|
||||
|
||||
Returns:
|
||||
List of allocation records
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
ica.id,
|
||||
ica.issue_id,
|
||||
ica.period_id,
|
||||
ica.allocated_amount,
|
||||
ica.allocation_date,
|
||||
ica.transaction_id,
|
||||
cp.period_start,
|
||||
cp.period_end,
|
||||
cp.period_type
|
||||
FROM issue_cost_allocations ica
|
||||
JOIN cost_periods cp ON ica.period_id = cp.id
|
||||
WHERE ica.issue_id = ?
|
||||
ORDER BY ica.allocation_date DESC
|
||||
''', (issue_id,))
|
||||
|
||||
rows = cursor.fetchall()
|
||||
allocations = []
|
||||
|
||||
for row in rows:
|
||||
allocation = {
|
||||
'id': row[0],
|
||||
'issue_id': row[1],
|
||||
'period_id': row[2],
|
||||
'allocated_amount': float(row[3]),
|
||||
'allocation_date': row[4],
|
||||
'transaction_id': row[5],
|
||||
'period_start': row[6],
|
||||
'period_end': row[7],
|
||||
'period_type': row[8]
|
||||
}
|
||||
allocations.append(allocation)
|
||||
|
||||
return allocations
|
||||
|
||||
def get_period_allocations(self, period_id: int) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Get all allocations for a specific period.
|
||||
|
||||
Args:
|
||||
period_id: ID of the period
|
||||
|
||||
Returns:
|
||||
List of allocation records
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
SELECT
|
||||
ica.id,
|
||||
ica.issue_id,
|
||||
ica.allocated_amount,
|
||||
ica.allocation_date,
|
||||
ica.transaction_id
|
||||
FROM issue_cost_allocations ica
|
||||
WHERE ica.period_id = ?
|
||||
ORDER BY ica.issue_id
|
||||
''', (period_id,))
|
||||
|
||||
rows = cursor.fetchall()
|
||||
allocations = []
|
||||
|
||||
for row in rows:
|
||||
allocation = {
|
||||
'id': row[0],
|
||||
'issue_id': row[1],
|
||||
'allocated_amount': float(row[2]),
|
||||
'allocation_date': row[3],
|
||||
'transaction_id': row[4]
|
||||
}
|
||||
allocations.append(allocation)
|
||||
|
||||
return allocations
|
||||
|
||||
def reverse_allocation(self, allocation_id: int) -> bool:
|
||||
"""
|
||||
Reverse a cost allocation (for corrections).
|
||||
|
||||
Args:
|
||||
allocation_id: ID of the allocation to reverse
|
||||
|
||||
Returns:
|
||||
True if successful, False otherwise
|
||||
"""
|
||||
try:
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Get allocation details
|
||||
cursor.execute('''
|
||||
SELECT issue_id, period_id, allocated_amount, transaction_id
|
||||
FROM issue_cost_allocations
|
||||
WHERE id = ?
|
||||
''', (allocation_id,))
|
||||
|
||||
result = cursor.fetchone()
|
||||
if not result:
|
||||
return False
|
||||
|
||||
issue_id, period_id, amount, transaction_id = result
|
||||
|
||||
# Create reversal transaction using adjustment type (allows negative amounts)
|
||||
with self.finance_models.get_connection() as conn2:
|
||||
cursor2 = conn2.cursor()
|
||||
cursor2.execute('''
|
||||
INSERT INTO cost_transactions
|
||||
(period_id, transaction_type, amount_eur, issue_id,
|
||||
transaction_date, description)
|
||||
VALUES (?, 'adjustment', ?, ?, ?, ?)
|
||||
''', (period_id, float(-amount), issue_id, date.today().isoformat(), f"Reversal of allocation #{allocation_id}"))
|
||||
|
||||
reversal_transaction_id = cursor2.lastrowid
|
||||
|
||||
# Only delete if reversal transaction was created successfully
|
||||
if reversal_transaction_id:
|
||||
cursor.execute('DELETE FROM issue_cost_allocations WHERE id = ?', (allocation_id,))
|
||||
return cursor.rowcount > 0
|
||||
else:
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
# Log the exception for debugging in tests
|
||||
print(f"Reversal failed with exception: {e}")
|
||||
return False
|
||||
|
||||
def _get_period(self, period_id: int) -> Optional[Period]:
|
||||
"""Get period details by ID."""
|
||||
period_data = self.period_manager.get_period_by_id(period_id)
|
||||
if not period_data:
|
||||
return None
|
||||
|
||||
# Convert dict to Period object
|
||||
return Period(
|
||||
id=period_data['id'],
|
||||
period_start=datetime.strptime(period_data['period_start'], '%Y-%m-%d').date() if period_data['period_start'] else None,
|
||||
period_end=datetime.strptime(period_data['period_end'], '%Y-%m-%d').date() if period_data['period_end'] else None,
|
||||
period_type=period_data['period_type'],
|
||||
status=period_data['status'],
|
||||
total_costs=Decimal(str(period_data['total_costs'])),
|
||||
active_issues_count=period_data['active_issues_count'],
|
||||
cost_per_issue=Decimal(str(period_data['cost_per_issue'])),
|
||||
loss_carried_forward=Decimal(str(period_data['loss_carried_forward'] or 0))
|
||||
)
|
||||
|
||||
def _update_period_status(self, period_id: int, status: PeriodStatus):
|
||||
"""Update period status."""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
'UPDATE cost_periods SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
|
||||
(status.value, period_id)
|
||||
)
|
||||
|
||||
def _calculate_period_total_costs(self, period: Period) -> Decimal:
|
||||
"""Calculate total costs for a period including carried forward amounts."""
|
||||
calculations = self.cost_manager.calculate_period_costs(
|
||||
period.period_start, period.period_end
|
||||
)
|
||||
|
||||
period_costs = calculations['total_period']
|
||||
carried_forward = period.loss_carried_forward or Decimal('0.00')
|
||||
|
||||
return Decimal(str(period_costs)) + carried_forward
|
||||
|
||||
def _get_active_issues_for_period(self, period: Period) -> List[int]:
|
||||
"""Get list of active issue IDs for a period."""
|
||||
activities = self.activity_tracker.get_activities_by_period(
|
||||
period.id,
|
||||
activity_types=[
|
||||
ActivityType.CREATED,
|
||||
ActivityType.MODIFIED,
|
||||
ActivityType.COMMENTED,
|
||||
ActivityType.STATUS_CHANGED
|
||||
]
|
||||
)
|
||||
|
||||
# Get unique issue IDs
|
||||
active_issues = list(set(activity.issue_id for activity in activities))
|
||||
return active_issues
|
||||
|
||||
def _get_or_create_next_period(self, current_period: Period) -> Optional[int]:
|
||||
"""Get or create the next period for loss carry forward."""
|
||||
# For now, return None - next period creation will be handled separately
|
||||
# This is a placeholder for future automatic period creation
|
||||
return None
|
||||
|
||||
def _carry_forward_loss(self, from_period_id: int, to_period_id: int, amount: Decimal):
|
||||
"""Carry forward loss to next period."""
|
||||
# Update the destination period's carried forward amount
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE cost_periods
|
||||
SET loss_carried_forward = loss_carried_forward + ?
|
||||
WHERE id = ?
|
||||
''', (float(amount), to_period_id))
|
||||
|
||||
# Create audit transaction
|
||||
self.transaction_manager.create_loss_forward_transaction(
|
||||
from_period_id=from_period_id,
|
||||
to_period_id=to_period_id,
|
||||
amount=amount,
|
||||
transaction_date=date.today(),
|
||||
description=f"Loss carried forward from period {from_period_id}"
|
||||
)
|
||||
|
||||
def _create_issue_allocation(
|
||||
self, issue_id: int, period_id: int, amount: Decimal, allocation_date: date
|
||||
) -> Optional[int]:
|
||||
"""Create an issue cost allocation record."""
|
||||
try:
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO issue_cost_allocations
|
||||
(issue_id, period_id, allocated_amount, allocation_date)
|
||||
VALUES (?, ?, ?, ?)
|
||||
''', (issue_id, period_id, float(amount), allocation_date.isoformat() if hasattr(allocation_date, 'isoformat') else allocation_date))
|
||||
|
||||
return cursor.lastrowid
|
||||
except sqlite3.IntegrityError:
|
||||
# Allocation already exists for this issue/period
|
||||
return None
|
||||
|
||||
def _update_allocation_transaction_id(self, allocation_id: int, transaction_id: int):
|
||||
"""Link allocation to its audit transaction."""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE issue_cost_allocations
|
||||
SET transaction_id = ?
|
||||
WHERE id = ?
|
||||
''', (transaction_id, allocation_id))
|
||||
|
||||
def _update_period_totals(
|
||||
self,
|
||||
period_id: int,
|
||||
total_costs: Decimal,
|
||||
active_issues_count: int,
|
||||
cost_per_issue: Decimal,
|
||||
loss_carried_forward: Decimal
|
||||
):
|
||||
"""Update period summary statistics."""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE cost_periods
|
||||
SET total_costs = ?,
|
||||
active_issues_count = ?,
|
||||
cost_per_issue = ?,
|
||||
loss_carried_forward = ?,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
''', (float(total_costs), active_issues_count, float(cost_per_issue), float(loss_carried_forward), period_id))
|
||||
@@ -1,507 +0,0 @@
|
||||
"""
|
||||
Single Command Day Wrap-Up functionality.
|
||||
|
||||
This module provides a comprehensive end-of-day command that consolidates
|
||||
daily work summaries, activity tracking, cost distribution, and reporting
|
||||
into a single convenient command.
|
||||
"""
|
||||
|
||||
import click
|
||||
from datetime import datetime, date, timedelta
|
||||
from typing import Optional, Dict, Any, List
|
||||
from decimal import Decimal
|
||||
from tabulate import tabulate
|
||||
import json
|
||||
|
||||
from .worktime_tracker import WorktimeTracker
|
||||
from ..issues.activity_tracker import IssueActivityTracker
|
||||
from .session_tracker import SessionCostTracker
|
||||
|
||||
|
||||
class DayWrapUpService:
|
||||
"""Service for comprehensive day wrap-up functionality."""
|
||||
|
||||
def __init__(self, db_path: str = "markitect.db"):
|
||||
"""Initialize the day wrap-up service."""
|
||||
self.db_path = db_path
|
||||
self.worktime_tracker = WorktimeTracker(db_path)
|
||||
self.activity_tracker = IssueActivityTracker(db_path)
|
||||
self.session_tracker = SessionCostTracker(db_path)
|
||||
|
||||
def generate_daily_summary(self, target_date: date) -> Dict[str, Any]:
|
||||
"""
|
||||
Generate comprehensive daily summary.
|
||||
|
||||
Args:
|
||||
target_date: Date to generate summary for
|
||||
|
||||
Returns:
|
||||
Dictionary containing complete daily summary
|
||||
"""
|
||||
summary = {
|
||||
'date': target_date,
|
||||
'worktime': self._get_worktime_summary(target_date),
|
||||
'activities': self._get_activity_summary(target_date),
|
||||
'costs': self._get_cost_summary(target_date),
|
||||
'recommendations': []
|
||||
}
|
||||
|
||||
# Add recommendations based on data
|
||||
summary['recommendations'] = self._generate_recommendations(summary)
|
||||
|
||||
return summary
|
||||
|
||||
def _get_worktime_summary(self, target_date: date) -> Dict[str, Any]:
|
||||
"""Get worktime summary for the date."""
|
||||
daily_summary = self.worktime_tracker.get_daily_summary(target_date)
|
||||
|
||||
if not daily_summary:
|
||||
return {
|
||||
'total_minutes': 0,
|
||||
'total_hours': 0.0,
|
||||
'issues_worked': 0,
|
||||
'entries': [],
|
||||
'cost_allocated': None,
|
||||
'cost_per_minute': None
|
||||
}
|
||||
|
||||
# Get issue breakdown
|
||||
issue_breakdown = {}
|
||||
for entry in daily_summary.entries:
|
||||
if entry.issue_id not in issue_breakdown:
|
||||
issue_breakdown[entry.issue_id] = {
|
||||
'minutes': 0,
|
||||
'entries': 0,
|
||||
'descriptions': []
|
||||
}
|
||||
issue_breakdown[entry.issue_id]['minutes'] += entry.duration_minutes
|
||||
issue_breakdown[entry.issue_id]['entries'] += 1
|
||||
if entry.description:
|
||||
issue_breakdown[entry.issue_id]['descriptions'].append(entry.description)
|
||||
|
||||
return {
|
||||
'total_minutes': daily_summary.total_minutes,
|
||||
'total_hours': daily_summary.total_minutes / 60,
|
||||
'issues_worked': daily_summary.issue_count,
|
||||
'entries': len(daily_summary.entries),
|
||||
'issue_breakdown': issue_breakdown,
|
||||
'cost_allocated': float(daily_summary.total_cost_allocated) if daily_summary.total_cost_allocated else None,
|
||||
'cost_per_minute': float(daily_summary.cost_per_minute) if daily_summary.cost_per_minute else None
|
||||
}
|
||||
|
||||
def _get_activity_summary(self, target_date: date) -> Dict[str, Any]:
|
||||
"""Get activity summary for the date."""
|
||||
summary = self.activity_tracker.get_activity_summary(
|
||||
start_date=target_date,
|
||||
end_date=target_date
|
||||
)
|
||||
|
||||
# Get detailed activities for the day
|
||||
activities = []
|
||||
if summary['total_activities'] > 0:
|
||||
# Get activities by checking each issue that had activity
|
||||
with self.activity_tracker.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT issue_id, activity_type, activity_details, created_at
|
||||
FROM issue_activity_log
|
||||
WHERE activity_date = ?
|
||||
ORDER BY created_at DESC
|
||||
''', (target_date.isoformat() if hasattr(target_date, 'isoformat') else target_date,))
|
||||
|
||||
for row in cursor.fetchall():
|
||||
activities.append({
|
||||
'issue_id': row[0],
|
||||
'activity_type': row[1],
|
||||
'details': row[2],
|
||||
'created_at': row[3]
|
||||
})
|
||||
|
||||
return {
|
||||
'total_activities': summary['total_activities'],
|
||||
'unique_issues': summary['unique_issues'],
|
||||
'activities_by_type': summary['activities_by_type'],
|
||||
'activities': activities
|
||||
}
|
||||
|
||||
def _get_cost_summary(self, target_date: date) -> Dict[str, Any]:
|
||||
"""Get cost summary for the date."""
|
||||
# Get session costs from cost notes for the day
|
||||
cost_summary = self.session_tracker.get_issue_costs_summary()
|
||||
|
||||
# Filter for today's costs (this is approximate - would need better filtering in real implementation)
|
||||
daily_costs = 0.0
|
||||
issue_costs = {}
|
||||
|
||||
# Get worktime cost distribution if available
|
||||
with self.worktime_tracker.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT issue_id, cost_allocated
|
||||
FROM worktime_cost_distributions
|
||||
WHERE work_date = ?
|
||||
''', (target_date.isoformat() if hasattr(target_date, 'isoformat') else target_date,))
|
||||
|
||||
for row in cursor.fetchall():
|
||||
issue_id, cost = row
|
||||
issue_costs[issue_id] = cost
|
||||
daily_costs += cost
|
||||
|
||||
return {
|
||||
'daily_total': daily_costs,
|
||||
'issue_costs': issue_costs,
|
||||
'has_cost_allocation': len(issue_costs) > 0
|
||||
}
|
||||
|
||||
def _generate_recommendations(self, summary: Dict[str, Any]) -> List[str]:
|
||||
"""Generate recommendations based on daily summary."""
|
||||
recommendations = []
|
||||
|
||||
# Worktime recommendations
|
||||
worktime = summary['worktime']
|
||||
if worktime['total_minutes'] == 0:
|
||||
recommendations.append("⚠️ No worktime logged for today. Consider logging time spent on issues.")
|
||||
elif worktime['total_hours'] < 4:
|
||||
recommendations.append("⏰ Low worktime logged today. Is this accurate or should more time be added?")
|
||||
elif worktime['total_hours'] > 10:
|
||||
recommendations.append("🔥 High worktime logged today. Make sure to take breaks!")
|
||||
|
||||
# Activity recommendations
|
||||
activities = summary['activities']
|
||||
if activities['total_activities'] == 0:
|
||||
recommendations.append("📝 No issue activities logged today. Consider what issues you worked on.")
|
||||
elif activities['unique_issues'] > 5:
|
||||
recommendations.append("🤹 Many issues worked on today. Consider focusing on fewer issues for better productivity.")
|
||||
|
||||
# Cost recommendations
|
||||
costs = summary['costs']
|
||||
if worktime['total_minutes'] > 0 and not costs['has_cost_allocation']:
|
||||
recommendations.append("💰 Time logged but no costs distributed. Run cost distribution to allocate daily expenses.")
|
||||
|
||||
return recommendations
|
||||
|
||||
def perform_auto_estimation(self, target_date: date, total_hours: float = 8.0) -> Dict[str, Any]:
|
||||
"""
|
||||
Perform automatic worktime estimation if no time is logged.
|
||||
|
||||
Args:
|
||||
target_date: Date to estimate for
|
||||
total_hours: Total hours to distribute
|
||||
|
||||
Returns:
|
||||
Estimation results
|
||||
"""
|
||||
# Check if any time is already logged
|
||||
summary = self.worktime_tracker.get_daily_summary(target_date)
|
||||
if summary and summary.total_minutes > 0:
|
||||
return {
|
||||
'estimated': False,
|
||||
'reason': 'Time already logged for this date',
|
||||
'existing_minutes': summary.total_minutes
|
||||
}
|
||||
|
||||
# Get active issues for the day from activity log
|
||||
with self.activity_tracker.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT DISTINCT issue_id
|
||||
FROM issue_activity_log
|
||||
WHERE activity_date = ?
|
||||
''', (target_date.isoformat() if hasattr(target_date, 'isoformat') else target_date,))
|
||||
active_issues = [row[0] for row in cursor.fetchall()]
|
||||
|
||||
if not active_issues:
|
||||
return {
|
||||
'estimated': False,
|
||||
'reason': 'No active issues found for this date',
|
||||
'active_issues': []
|
||||
}
|
||||
|
||||
# Perform estimation
|
||||
estimation_result = self.worktime_tracker.estimate_daily_worktime(
|
||||
work_date=target_date,
|
||||
total_hours=total_hours,
|
||||
issues=active_issues,
|
||||
distribution_method="activity_based"
|
||||
)
|
||||
|
||||
return {
|
||||
'estimated': True,
|
||||
'estimation_result': estimation_result
|
||||
}
|
||||
|
||||
def distribute_daily_costs(self, target_date: date, daily_cost: Decimal) -> Dict[str, Any]:
|
||||
"""
|
||||
Distribute daily costs based on worktime allocation.
|
||||
|
||||
Args:
|
||||
target_date: Date to distribute costs for
|
||||
daily_cost: Total daily cost to distribute
|
||||
|
||||
Returns:
|
||||
Distribution results
|
||||
"""
|
||||
return self.worktime_tracker.distribute_daily_costs(
|
||||
work_date=target_date,
|
||||
total_daily_cost=daily_cost
|
||||
)
|
||||
|
||||
|
||||
@click.group()
|
||||
def wrapup():
|
||||
"""Day wrap-up commands for end-of-day summaries and automation."""
|
||||
pass
|
||||
|
||||
|
||||
@wrapup.command()
|
||||
@click.argument('date', type=click.DateTime(formats=['%Y-%m-%d']), required=False)
|
||||
@click.option('--auto-estimate', is_flag=True,
|
||||
help='Automatically estimate worktime if none logged')
|
||||
@click.option('--estimate-hours', type=float, default=8.0,
|
||||
help='Hours to estimate (used with --auto-estimate)')
|
||||
@click.option('--distribute-cost', type=float,
|
||||
help='Daily cost to distribute (€)')
|
||||
@click.option('--format', 'output_format', type=click.Choice(['summary', 'detailed', 'json']),
|
||||
default='summary', help='Output format')
|
||||
def daily(date: Optional[datetime], auto_estimate: bool, estimate_hours: float,
|
||||
distribute_cost: Optional[float], output_format: str):
|
||||
"""Generate comprehensive daily wrap-up summary.
|
||||
|
||||
If no date is provided, uses today's date.
|
||||
"""
|
||||
from datetime import date as date_module
|
||||
target_date = date.date() if date else date_module.today()
|
||||
service = DayWrapUpService()
|
||||
|
||||
try:
|
||||
# Auto-estimate worktime if requested
|
||||
if auto_estimate:
|
||||
click.echo(f"🤖 Auto-estimating worktime for {target_date}...")
|
||||
estimation = service.perform_auto_estimation(target_date, estimate_hours)
|
||||
|
||||
if estimation['estimated']:
|
||||
result = estimation['estimation_result']
|
||||
click.echo(f"✅ Estimated {estimate_hours}h across {result['issues_count']} issues")
|
||||
else:
|
||||
click.echo(f"ℹ️ {estimation['reason']}")
|
||||
|
||||
# Distribute costs if requested
|
||||
if distribute_cost:
|
||||
click.echo(f"💰 Distributing €{distribute_cost:.2f} for {target_date}...")
|
||||
distribution = service.distribute_daily_costs(target_date, Decimal(str(distribute_cost)))
|
||||
|
||||
if 'message' in distribution:
|
||||
click.echo(f"⚠️ {distribution['message']}")
|
||||
else:
|
||||
click.echo(f"✅ Distributed €{distribute_cost:.2f} across {distribution['issues_count']} issues")
|
||||
|
||||
# Generate summary
|
||||
summary = service.generate_daily_summary(target_date)
|
||||
|
||||
if output_format == 'json':
|
||||
# Convert date to string for JSON serialization
|
||||
summary['date'] = summary['date'].isoformat()
|
||||
click.echo(json.dumps(summary, indent=2))
|
||||
return
|
||||
|
||||
# Display summary
|
||||
_display_daily_summary(summary, output_format)
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error generating daily wrap-up: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@wrapup.command()
|
||||
@click.argument('start_date', type=click.DateTime(formats=['%Y-%m-%d']))
|
||||
@click.argument('end_date', type=click.DateTime(formats=['%Y-%m-%d']))
|
||||
@click.option('--format', 'output_format', type=click.Choice(['summary', 'json']),
|
||||
default='summary', help='Output format')
|
||||
def period(start_date: datetime, end_date: datetime, output_format: str):
|
||||
"""Generate wrap-up summary for a date range."""
|
||||
service = DayWrapUpService()
|
||||
|
||||
try:
|
||||
# Get worktime report for period
|
||||
worktime_report = service.worktime_tracker.get_worktime_report(
|
||||
start_date=start_date.date(),
|
||||
end_date=end_date.date()
|
||||
)
|
||||
|
||||
# Get activity summary for period
|
||||
activity_summary = service.activity_tracker.get_activity_summary(
|
||||
start_date=start_date.date(),
|
||||
end_date=end_date.date()
|
||||
)
|
||||
|
||||
period_summary = {
|
||||
'period': f"{start_date.date()} to {end_date.date()}",
|
||||
'worktime': worktime_report,
|
||||
'activities': activity_summary
|
||||
}
|
||||
|
||||
if output_format == 'json':
|
||||
click.echo(json.dumps(period_summary, indent=2))
|
||||
else:
|
||||
_display_period_summary(period_summary)
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error generating period wrap-up: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@wrapup.command()
|
||||
@click.argument('date', type=click.DateTime(formats=['%Y-%m-%d']), required=False)
|
||||
@click.option('--hours', type=float, default=8.0, help='Total hours worked')
|
||||
@click.option('--method', type=click.Choice(['equal', 'activity_based']),
|
||||
default='activity_based', help='Estimation method')
|
||||
def estimate(date: Optional[datetime], hours: float, method: str):
|
||||
"""Estimate and log worktime for a day based on issue activities."""
|
||||
from datetime import date as date_module
|
||||
target_date = date.date() if date else date_module.today()
|
||||
service = DayWrapUpService()
|
||||
|
||||
try:
|
||||
estimation = service.perform_auto_estimation(target_date, hours)
|
||||
|
||||
if not estimation['estimated']:
|
||||
click.echo(f"⚠️ {estimation['reason']}")
|
||||
return
|
||||
|
||||
result = estimation['estimation_result']
|
||||
click.echo(f"✅ Estimated worktime for {target_date}")
|
||||
click.echo(f"Total Hours: {hours}h")
|
||||
click.echo(f"Distribution Method: {method}")
|
||||
click.echo(f"Issues: {result['issues_count']}")
|
||||
|
||||
# Show breakdown
|
||||
headers = ['Issue', 'Time', 'Percentage']
|
||||
rows = []
|
||||
total_minutes = result['total_minutes']
|
||||
|
||||
for issue_id, minutes in result['issue_estimates'].items():
|
||||
percentage = (minutes / total_minutes) * 100
|
||||
hours_mins = f"{minutes//60}h{minutes%60}m" if minutes >= 60 else f"{minutes}m"
|
||||
rows.append([f"#{issue_id}", hours_mins, f"{percentage:.1f}%"])
|
||||
|
||||
click.echo("\nEstimated Time Distribution:")
|
||||
click.echo(tabulate(rows, headers=headers, tablefmt='grid'))
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error estimating worktime: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
def _display_daily_summary(summary: Dict[str, Any], format_type: str):
|
||||
"""Display daily summary in formatted output."""
|
||||
date_str = summary['date']
|
||||
worktime = summary['worktime']
|
||||
activities = summary['activities']
|
||||
costs = summary['costs']
|
||||
recommendations = summary['recommendations']
|
||||
|
||||
click.echo(f"\n📊 Daily Wrap-Up for {date_str}")
|
||||
click.echo("=" * 50)
|
||||
|
||||
# Worktime section
|
||||
click.echo(f"\n⏰ WORKTIME SUMMARY")
|
||||
if worktime['total_minutes'] > 0:
|
||||
hours = int(worktime['total_hours'])
|
||||
minutes = int((worktime['total_hours'] - hours) * 60)
|
||||
click.echo(f"Total Time: {hours}h {minutes}m ({worktime['total_minutes']} minutes)")
|
||||
click.echo(f"Issues Worked: {worktime['issues_worked']}")
|
||||
click.echo(f"Time Entries: {worktime['entries']}")
|
||||
|
||||
if worktime['cost_allocated']:
|
||||
click.echo(f"Cost Allocated: €{worktime['cost_allocated']:.2f}")
|
||||
click.echo(f"Cost per Minute: €{worktime['cost_per_minute']:.4f}")
|
||||
|
||||
if format_type == 'detailed' and worktime['issue_breakdown']:
|
||||
click.echo("\nTime by Issue:")
|
||||
headers = ['Issue', 'Time', 'Entries', 'Percentage']
|
||||
rows = []
|
||||
|
||||
for issue_id, data in worktime['issue_breakdown'].items():
|
||||
percentage = (data['minutes'] / worktime['total_minutes']) * 100
|
||||
time_str = f"{data['minutes']//60}h{data['minutes']%60}m" if data['minutes'] >= 60 else f"{data['minutes']}m"
|
||||
rows.append([f"#{issue_id}", time_str, data['entries'], f"{percentage:.1f}%"])
|
||||
|
||||
click.echo(tabulate(rows, headers=headers, tablefmt='grid'))
|
||||
else:
|
||||
click.echo("No worktime logged today")
|
||||
|
||||
# Activities section
|
||||
click.echo(f"\n📝 ACTIVITIES SUMMARY")
|
||||
if activities['total_activities'] > 0:
|
||||
click.echo(f"Total Activities: {activities['total_activities']}")
|
||||
click.echo(f"Issues with Activity: {activities['unique_issues']}")
|
||||
|
||||
if activities['activities_by_type']:
|
||||
click.echo("\nActivity Breakdown:")
|
||||
for activity_type, count in activities['activities_by_type'].items():
|
||||
click.echo(f" {activity_type.title()}: {count}")
|
||||
|
||||
if format_type == 'detailed' and activities['activities']:
|
||||
click.echo("\nRecent Activities:")
|
||||
for activity in activities['activities'][:5]: # Show last 5
|
||||
details = f" - {activity['details']}" if activity['details'] else ""
|
||||
click.echo(f" #{activity['issue_id']}: {activity['activity_type']}{details}")
|
||||
else:
|
||||
click.echo("No activities logged today")
|
||||
|
||||
# Costs section
|
||||
click.echo(f"\n💰 COST SUMMARY")
|
||||
if costs['has_cost_allocation']:
|
||||
click.echo(f"Daily Total: €{costs['daily_total']:.2f}")
|
||||
click.echo("Cost Allocation:")
|
||||
for issue_id, cost in costs['issue_costs'].items():
|
||||
click.echo(f" Issue #{issue_id}: €{cost:.2f}")
|
||||
else:
|
||||
click.echo("No cost allocation for today")
|
||||
|
||||
# Recommendations section
|
||||
if recommendations:
|
||||
click.echo(f"\n💡 RECOMMENDATIONS")
|
||||
for rec in recommendations:
|
||||
click.echo(f" {rec}")
|
||||
|
||||
click.echo()
|
||||
|
||||
|
||||
def _display_period_summary(summary: Dict[str, Any]):
|
||||
"""Display period summary in formatted output."""
|
||||
click.echo(f"\n📈 Period Wrap-Up: {summary['period']}")
|
||||
click.echo("=" * 60)
|
||||
|
||||
worktime = summary['worktime']
|
||||
activities = summary['activities']
|
||||
|
||||
# Worktime summary
|
||||
click.echo(f"\n⏰ WORKTIME OVERVIEW")
|
||||
click.echo(f"Total Time: {worktime['total_time']['hours']}h {worktime['total_time']['minutes']}m")
|
||||
click.echo(f"Total Entries: {worktime['total_entries']}")
|
||||
click.echo(f"Unique Issues: {worktime['unique_issues']}")
|
||||
click.echo(f"Unique Dates: {worktime['unique_dates']}")
|
||||
|
||||
if worktime['unique_dates'] > 0:
|
||||
avg_minutes = worktime['average_minutes_per_day']
|
||||
avg_hours = int(avg_minutes // 60)
|
||||
avg_mins = int(avg_minutes % 60)
|
||||
click.echo(f"Average per Day: {avg_hours}h {avg_mins}m")
|
||||
|
||||
# Activities summary
|
||||
click.echo(f"\n📝 ACTIVITIES OVERVIEW")
|
||||
click.echo(f"Total Activities: {activities['total_activities']}")
|
||||
click.echo(f"Unique Issues: {activities['unique_issues']}")
|
||||
|
||||
if activities['activities_by_type']:
|
||||
click.echo("\nActivity Types:")
|
||||
for activity_type, count in activities['activities_by_type'].items():
|
||||
percentage = (count / activities['total_activities']) * 100
|
||||
click.echo(f" {activity_type.title()}: {count} ({percentage:.1f}%)")
|
||||
|
||||
click.echo()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
wrapup()
|
||||
0
markitect/finance/tests/__init__.py
Normal file
0
markitect/finance/tests/__init__.py
Normal file
0
markitect/graphql/tests/__init__.py
Normal file
0
markitect/graphql/tests/__init__.py
Normal file
@@ -1,7 +0,0 @@
|
||||
"""
|
||||
Issue management module for MarkiTect.
|
||||
|
||||
Provides unified CLI interface for issue management with pluggable backend support.
|
||||
"""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@@ -1,271 +0,0 @@
|
||||
"""
|
||||
CLI commands for issue activity tracking.
|
||||
|
||||
This module provides command-line interface for logging, viewing, and managing
|
||||
issue activities for cost allocation and project management purposes.
|
||||
"""
|
||||
|
||||
import click
|
||||
from datetime import datetime, date
|
||||
from typing import List, Optional
|
||||
from tabulate import tabulate
|
||||
|
||||
from markitect.issues.activity_tracker import IssueActivityTracker, ActivityType, IssueActivity
|
||||
|
||||
|
||||
@click.group()
|
||||
def activity():
|
||||
"""Issue activity tracking commands."""
|
||||
pass
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.argument('issue_id', type=int)
|
||||
@click.argument('activity_type', type=click.Choice([at.value for at in ActivityType]))
|
||||
@click.option('--date', '-d', type=click.DateTime(formats=['%Y-%m-%d']),
|
||||
help='Activity date (defaults to today)')
|
||||
@click.option('--details', '-m', help='Activity details/message')
|
||||
@click.option('--period-id', type=int, help='Cost period ID for allocation')
|
||||
def log(issue_id: int, activity_type: str, date: Optional[datetime],
|
||||
details: Optional[str], period_id: Optional[int]):
|
||||
"""Log an activity for an issue."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
activity_date = date.date() if date else None
|
||||
activity_enum = ActivityType(activity_type)
|
||||
|
||||
try:
|
||||
activity_id = tracker.log_activity(
|
||||
issue_id=issue_id,
|
||||
activity_type=activity_enum,
|
||||
activity_date=activity_date,
|
||||
activity_details=details,
|
||||
period_id=period_id
|
||||
)
|
||||
|
||||
click.echo(f"✅ Logged {activity_type} activity for issue #{issue_id} (ID: {activity_id})")
|
||||
|
||||
if details:
|
||||
click.echo(f" Details: {details}")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error logging activity: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.argument('issue_id', type=int)
|
||||
@click.option('--limit', '-l', type=int, default=20, help='Maximum number of activities to show')
|
||||
@click.option('--offset', type=int, default=0, help='Number of activities to skip')
|
||||
@click.option('--format', 'output_format', type=click.Choice(['table', 'json']),
|
||||
default='table', help='Output format')
|
||||
def show(issue_id: int, limit: int, offset: int, output_format: str):
|
||||
"""Show activities for a specific issue."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
try:
|
||||
activities = tracker.get_issue_activities(issue_id, limit=limit, offset=offset)
|
||||
|
||||
if not activities:
|
||||
click.echo(f"📝 No activities found for issue #{issue_id}")
|
||||
return
|
||||
|
||||
if output_format == 'json':
|
||||
import json
|
||||
activity_data = [activity.to_dict() for activity in activities]
|
||||
click.echo(json.dumps(activity_data, indent=2))
|
||||
|
||||
else:
|
||||
# Table format
|
||||
click.echo(f"\n📋 Activities for Issue #{issue_id}\n")
|
||||
|
||||
headers = ['ID', 'Type', 'Date', 'Period', 'Details', 'Logged']
|
||||
rows = []
|
||||
|
||||
for activity in activities:
|
||||
rows.append([
|
||||
activity.id,
|
||||
activity.activity_type_display,
|
||||
activity.formatted_date,
|
||||
activity.period_id or 'N/A',
|
||||
activity.truncated_details,
|
||||
activity.formatted_datetime
|
||||
])
|
||||
|
||||
click.echo(tabulate(rows, headers=headers, tablefmt='grid'))
|
||||
|
||||
if len(activities) == limit:
|
||||
click.echo(f"\n💡 Showing {limit} most recent activities. Use --limit and --offset for pagination.")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error retrieving activities: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.option('--period-id', type=int, help='Filter by cost period ID')
|
||||
@click.option('--activity-type', type=click.Choice([at.value for at in ActivityType]),
|
||||
multiple=True, help='Filter by activity types (can specify multiple)')
|
||||
@click.option('--format', 'output_format', type=click.Choice(['table', 'json']),
|
||||
default='table', help='Output format')
|
||||
def list(period_id: Optional[int], activity_type: List[str], output_format: str):
|
||||
"""List activities across issues."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
try:
|
||||
if period_id:
|
||||
activity_types = [ActivityType(at) for at in activity_type] if activity_type else None
|
||||
activities = tracker.get_activities_by_period(period_id, activity_types)
|
||||
title = f"Activities for Period #{period_id}"
|
||||
else:
|
||||
# For now, show recent activities across all issues (could be enhanced)
|
||||
click.echo("❌ Currently only period-based listing is supported. Use --period-id option.")
|
||||
return
|
||||
|
||||
if not activities:
|
||||
click.echo(f"📝 No activities found for the specified criteria")
|
||||
return
|
||||
|
||||
if output_format == 'json':
|
||||
import json
|
||||
activity_data = [activity.to_dict() for activity in activities]
|
||||
click.echo(json.dumps(activity_data, indent=2))
|
||||
|
||||
else:
|
||||
# Table format
|
||||
click.echo(f"\n📊 {title}\n")
|
||||
|
||||
headers = ['ID', 'Issue', 'Type', 'Date', 'Details']
|
||||
rows = []
|
||||
|
||||
for activity in activities:
|
||||
rows.append([
|
||||
activity.id,
|
||||
f"#{activity.issue_id}",
|
||||
activity.activity_type.value.title(),
|
||||
activity.activity_date.strftime('%Y-%m-%d') if activity.activity_date else 'N/A',
|
||||
(activity.activity_details[:50] + '...') if activity.activity_details and len(activity.activity_details) > 50 else (activity.activity_details or '')
|
||||
])
|
||||
|
||||
click.echo(tabulate(rows, headers=headers, tablefmt='grid'))
|
||||
click.echo(f"\n📈 Total: {len(activities)} activities")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error retrieving activities: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.option('--issue-id', type=int, help='Filter by specific issue ID')
|
||||
@click.option('--start-date', type=click.DateTime(formats=['%Y-%m-%d']),
|
||||
help='Start date for summary period')
|
||||
@click.option('--end-date', type=click.DateTime(formats=['%Y-%m-%d']),
|
||||
help='End date for summary period')
|
||||
def summary(issue_id: Optional[int], start_date: Optional[datetime],
|
||||
end_date: Optional[datetime]):
|
||||
"""Show activity summary statistics."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
try:
|
||||
summary_data = tracker.get_activity_summary(
|
||||
issue_id=issue_id,
|
||||
start_date=start_date.date() if start_date else None,
|
||||
end_date=end_date.date() if end_date else None
|
||||
)
|
||||
|
||||
click.echo("\n📊 Issue Activity Summary\n")
|
||||
|
||||
# Basic stats
|
||||
click.echo(f"Total Activities: {summary_data['total_activities']}")
|
||||
click.echo(f"Unique Issues: {summary_data['unique_issues']}")
|
||||
|
||||
# Date range
|
||||
date_range = summary_data['date_range']
|
||||
if date_range['start'] and date_range['end']:
|
||||
click.echo(f"Date Range: {date_range['start']} to {date_range['end']}")
|
||||
elif date_range['start']:
|
||||
click.echo(f"Since: {date_range['start']}")
|
||||
|
||||
# Activity breakdown
|
||||
if summary_data['activities_by_type']:
|
||||
click.echo("\nActivity Breakdown:")
|
||||
for activity_type, count in summary_data['activities_by_type'].items():
|
||||
percentage = (count / summary_data['total_activities']) * 100
|
||||
click.echo(f" {activity_type.title()}: {count} ({percentage:.1f}%)")
|
||||
|
||||
# Filters applied
|
||||
filters = summary_data['filters']
|
||||
applied_filters = []
|
||||
if filters['issue_id']:
|
||||
applied_filters.append(f"Issue #{filters['issue_id']}")
|
||||
if filters['start_date']:
|
||||
applied_filters.append(f"From {filters['start_date']}")
|
||||
if filters['end_date']:
|
||||
applied_filters.append(f"Until {filters['end_date']}")
|
||||
|
||||
if applied_filters:
|
||||
click.echo(f"\nFilters Applied: {', '.join(applied_filters)}")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error generating summary: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.argument('activity_id', type=int)
|
||||
@click.confirmation_option(prompt='Are you sure you want to delete this activity?')
|
||||
def delete(activity_id: int):
|
||||
"""Delete an activity record."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
try:
|
||||
if tracker.delete_activity(activity_id):
|
||||
click.echo(f"✅ Deleted activity #{activity_id}")
|
||||
else:
|
||||
click.echo(f"❌ Activity #{activity_id} not found")
|
||||
raise click.Abort()
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error deleting activity: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@activity.command()
|
||||
@click.argument('file_path', type=click.Path(exists=True))
|
||||
@click.option('--format', 'input_format', type=click.Choice(['json', 'csv']),
|
||||
default='json', help='Input file format')
|
||||
def import_activities(file_path: str, input_format: str):
|
||||
"""Import activities from a file."""
|
||||
tracker = IssueActivityTracker()
|
||||
|
||||
try:
|
||||
if input_format == 'json':
|
||||
import json
|
||||
with open(file_path, 'r') as f:
|
||||
activities = json.load(f)
|
||||
|
||||
elif input_format == 'csv':
|
||||
import csv
|
||||
activities = []
|
||||
with open(file_path, 'r') as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
activity = {
|
||||
'issue_id': int(row['issue_id']),
|
||||
'activity_type': row['activity_type'],
|
||||
'activity_date': datetime.strptime(row['activity_date'], '%Y-%m-%d').date() if row.get('activity_date') else None,
|
||||
'activity_details': row.get('activity_details'),
|
||||
'period_id': int(row['period_id']) if row.get('period_id') else None
|
||||
}
|
||||
activities.append(activity)
|
||||
|
||||
activity_ids = tracker.bulk_log_activities(activities)
|
||||
click.echo(f"✅ Successfully imported {len(activity_ids)} activities")
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error importing activities: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
activity()
|
||||
@@ -1,417 +0,0 @@
|
||||
"""
|
||||
Issue Activity Tracking Service
|
||||
|
||||
This module provides comprehensive issue activity tracking functionality,
|
||||
building on the existing database infrastructure to log and retrieve
|
||||
issue activities for cost allocation and project management.
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
from datetime import datetime, date
|
||||
from typing import List, Dict, Any, Optional
|
||||
from dataclasses import dataclass, asdict
|
||||
from enum import Enum
|
||||
|
||||
from markitect.finance.models import FinanceModels
|
||||
|
||||
|
||||
class ActivityType(Enum):
|
||||
"""Enumeration of supported issue activity types."""
|
||||
CREATED = "created"
|
||||
MODIFIED = "modified"
|
||||
CLOSED = "closed"
|
||||
REOPENED = "reopened"
|
||||
COMMENTED = "commented"
|
||||
STATUS_CHANGED = "status_changed"
|
||||
|
||||
|
||||
@dataclass
|
||||
class IssueActivity:
|
||||
"""Data class representing an issue activity record with convenient methods."""
|
||||
id: Optional[int] = None
|
||||
issue_id: int = None
|
||||
activity_type: ActivityType = None
|
||||
activity_date: date = None
|
||||
period_id: Optional[int] = None
|
||||
activity_details: Optional[str] = None
|
||||
created_at: Optional[datetime] = None
|
||||
|
||||
@property
|
||||
def activity_type_value(self) -> str:
|
||||
"""Get the string value of the activity type."""
|
||||
return self.activity_type.value if self.activity_type else ''
|
||||
|
||||
@property
|
||||
def activity_type_display(self) -> str:
|
||||
"""Get the display-friendly activity type."""
|
||||
return self.activity_type_value.replace('_', ' ').title()
|
||||
|
||||
@property
|
||||
def formatted_date(self) -> str:
|
||||
"""Get formatted activity date string."""
|
||||
return self.activity_date.strftime('%Y-%m-%d') if self.activity_date else 'N/A'
|
||||
|
||||
@property
|
||||
def formatted_datetime(self) -> str:
|
||||
"""Get formatted created datetime string."""
|
||||
return self.created_at.strftime('%Y-%m-%d %H:%M') if self.created_at else 'N/A'
|
||||
|
||||
@property
|
||||
def truncated_details(self) -> str:
|
||||
"""Get truncated activity details for display (max 40 chars)."""
|
||||
if not self.activity_details:
|
||||
return ''
|
||||
return (self.activity_details[:40] + '...') if len(self.activity_details) > 40 else self.activity_details
|
||||
|
||||
def contains_keyword(self, keyword: str, case_sensitive: bool = False) -> bool:
|
||||
"""Check if activity contains a keyword in type or details."""
|
||||
search_text = f"{self.activity_type_value} {self.activity_details or ''}".strip()
|
||||
if not case_sensitive:
|
||||
search_text = search_text.lower()
|
||||
keyword = keyword.lower()
|
||||
return keyword in search_text
|
||||
|
||||
def has_implementation_activity(self) -> bool:
|
||||
"""Check if this activity indicates implementation work."""
|
||||
return (self.contains_keyword('implement') or
|
||||
self.contains_keyword('code') or
|
||||
self.contains_keyword('develop'))
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Convert to dictionary representation."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'issue_id': self.issue_id,
|
||||
'activity_type': self.activity_type_value,
|
||||
'activity_date': self.activity_date.isoformat() if self.activity_date else None,
|
||||
'period_id': self.period_id,
|
||||
'activity_details': self.activity_details,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None
|
||||
}
|
||||
|
||||
|
||||
class IssueActivityTracker:
|
||||
"""
|
||||
Service for tracking and managing issue activities.
|
||||
|
||||
Provides functionality to log issue activities, retrieve activity history,
|
||||
and generate activity reports for cost allocation and project management.
|
||||
"""
|
||||
|
||||
def __init__(self, db_path: str = "markitect.db"):
|
||||
"""
|
||||
Initialize the issue activity tracker.
|
||||
|
||||
Args:
|
||||
db_path: Path to the SQLite database file
|
||||
"""
|
||||
self.db_path = db_path
|
||||
self.finance_models = FinanceModels(db_path)
|
||||
self._ensure_schema()
|
||||
|
||||
def _ensure_schema(self):
|
||||
"""Ensure the database schema is properly initialized."""
|
||||
self.finance_models.initialize_finance_schema()
|
||||
|
||||
def log_activity(
|
||||
self,
|
||||
issue_id: int,
|
||||
activity_type: ActivityType,
|
||||
activity_date: Optional[date] = None,
|
||||
activity_details: Optional[str] = None,
|
||||
period_id: Optional[int] = None
|
||||
) -> int:
|
||||
"""
|
||||
Log an issue activity.
|
||||
|
||||
Args:
|
||||
issue_id: ID of the issue
|
||||
activity_type: Type of activity performed
|
||||
activity_date: Date when activity occurred (defaults to today)
|
||||
activity_details: Additional details about the activity
|
||||
period_id: Optional period ID for cost allocation
|
||||
|
||||
Returns:
|
||||
ID of the created activity record
|
||||
|
||||
Raises:
|
||||
sqlite3.Error: If database operation fails
|
||||
"""
|
||||
if activity_date is None:
|
||||
activity_date = date.today()
|
||||
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# If period_id is not provided, try to get the current period
|
||||
if period_id is None:
|
||||
cursor.execute('''
|
||||
SELECT id FROM cost_periods
|
||||
WHERE ? BETWEEN period_start AND period_end
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
''', (activity_date.isoformat(),))
|
||||
result = cursor.fetchone()
|
||||
if result:
|
||||
period_id = result[0]
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO issue_activity_log
|
||||
(issue_id, activity_type, activity_date, period_id, activity_details)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (issue_id, activity_type.value, activity_date.isoformat(), period_id, activity_details))
|
||||
|
||||
return cursor.lastrowid
|
||||
|
||||
def get_issue_activities(
|
||||
self,
|
||||
issue_id: int,
|
||||
limit: Optional[int] = None,
|
||||
offset: int = 0
|
||||
) -> List[IssueActivity]:
|
||||
"""
|
||||
Get activities for a specific issue.
|
||||
|
||||
Args:
|
||||
issue_id: ID of the issue
|
||||
limit: Maximum number of activities to return
|
||||
offset: Number of activities to skip
|
||||
|
||||
Returns:
|
||||
List of issue activities, ordered by activity date (most recent first)
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
query = '''
|
||||
SELECT id, issue_id, activity_type, activity_date,
|
||||
period_id, activity_details, created_at
|
||||
FROM issue_activity_log
|
||||
WHERE issue_id = ?
|
||||
ORDER BY activity_date DESC, created_at DESC
|
||||
'''
|
||||
params = [issue_id]
|
||||
|
||||
if limit:
|
||||
query += ' LIMIT ? OFFSET ?'
|
||||
params.extend([limit, offset])
|
||||
|
||||
cursor.execute(query, params)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
activities = []
|
||||
for row in rows:
|
||||
activity = IssueActivity(
|
||||
id=row[0],
|
||||
issue_id=row[1],
|
||||
activity_type=ActivityType(row[2]),
|
||||
activity_date=datetime.strptime(row[3], '%Y-%m-%d').date() if row[3] else None,
|
||||
period_id=row[4],
|
||||
activity_details=row[5],
|
||||
created_at=datetime.fromisoformat(row[6]) if row[6] else None
|
||||
)
|
||||
activities.append(activity)
|
||||
|
||||
return activities
|
||||
|
||||
def get_activities_by_period(
|
||||
self,
|
||||
period_id: int,
|
||||
activity_types: Optional[List[ActivityType]] = None
|
||||
) -> List[IssueActivity]:
|
||||
"""
|
||||
Get all activities within a specific cost period.
|
||||
|
||||
Args:
|
||||
period_id: ID of the cost period
|
||||
activity_types: Optional list of activity types to filter by
|
||||
|
||||
Returns:
|
||||
List of issue activities within the period
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
query = '''
|
||||
SELECT id, issue_id, activity_type, activity_date,
|
||||
period_id, activity_details, created_at
|
||||
FROM issue_activity_log
|
||||
WHERE period_id = ?
|
||||
'''
|
||||
params = [period_id]
|
||||
|
||||
if activity_types:
|
||||
placeholders = ','.join(['?' for _ in activity_types])
|
||||
query += f' AND activity_type IN ({placeholders})'
|
||||
params.extend([at.value for at in activity_types])
|
||||
|
||||
query += ' ORDER BY activity_date DESC, created_at DESC'
|
||||
|
||||
cursor.execute(query, params)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
activities = []
|
||||
for row in rows:
|
||||
activity = IssueActivity(
|
||||
id=row[0],
|
||||
issue_id=row[1],
|
||||
activity_type=ActivityType(row[2]),
|
||||
activity_date=datetime.strptime(row[3], '%Y-%m-%d').date() if row[3] else None,
|
||||
period_id=row[4],
|
||||
activity_details=row[5],
|
||||
created_at=datetime.fromisoformat(row[6]) if row[6] else None
|
||||
)
|
||||
activities.append(activity)
|
||||
|
||||
return activities
|
||||
|
||||
def get_activity_summary(
|
||||
self,
|
||||
issue_id: Optional[int] = None,
|
||||
start_date: Optional[date] = None,
|
||||
end_date: Optional[date] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get activity summary statistics.
|
||||
|
||||
Args:
|
||||
issue_id: Optional issue ID to filter by
|
||||
start_date: Optional start date filter
|
||||
end_date: Optional end date filter
|
||||
|
||||
Returns:
|
||||
Dictionary containing activity summary statistics
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Build base query
|
||||
base_conditions = []
|
||||
params = []
|
||||
|
||||
if issue_id:
|
||||
base_conditions.append('issue_id = ?')
|
||||
params.append(issue_id)
|
||||
|
||||
if start_date:
|
||||
base_conditions.append('activity_date >= ?')
|
||||
params.append(start_date.isoformat() if hasattr(start_date, 'isoformat') else start_date)
|
||||
|
||||
if end_date:
|
||||
base_conditions.append('activity_date <= ?')
|
||||
params.append(end_date.isoformat() if hasattr(end_date, 'isoformat') else end_date)
|
||||
|
||||
where_clause = ' AND '.join(base_conditions) if base_conditions else '1=1'
|
||||
|
||||
# Get total activity count
|
||||
cursor.execute(f'''
|
||||
SELECT COUNT(*) FROM issue_activity_log WHERE {where_clause}
|
||||
''', params)
|
||||
total_activities = cursor.fetchone()[0]
|
||||
|
||||
# Get activity count by type
|
||||
cursor.execute(f'''
|
||||
SELECT activity_type, COUNT(*)
|
||||
FROM issue_activity_log
|
||||
WHERE {where_clause}
|
||||
GROUP BY activity_type
|
||||
ORDER BY COUNT(*) DESC
|
||||
''', params)
|
||||
activities_by_type = dict(cursor.fetchall())
|
||||
|
||||
# Get unique issues count
|
||||
cursor.execute(f'''
|
||||
SELECT COUNT(DISTINCT issue_id)
|
||||
FROM issue_activity_log
|
||||
WHERE {where_clause}
|
||||
''', params)
|
||||
unique_issues = cursor.fetchone()[0]
|
||||
|
||||
# Get date range
|
||||
cursor.execute(f'''
|
||||
SELECT MIN(activity_date), MAX(activity_date)
|
||||
FROM issue_activity_log
|
||||
WHERE {where_clause}
|
||||
''', params)
|
||||
date_range = cursor.fetchone()
|
||||
|
||||
return {
|
||||
'total_activities': total_activities,
|
||||
'activities_by_type': activities_by_type,
|
||||
'unique_issues': unique_issues,
|
||||
'date_range': {
|
||||
'start': date_range[0] if date_range[0] else None,
|
||||
'end': date_range[1] if date_range[1] else None
|
||||
},
|
||||
'filters': {
|
||||
'issue_id': issue_id,
|
||||
'start_date': start_date.isoformat() if start_date else None,
|
||||
'end_date': end_date.isoformat() if end_date else None
|
||||
}
|
||||
}
|
||||
|
||||
def delete_activity(self, activity_id: int) -> bool:
|
||||
"""
|
||||
Delete an activity record.
|
||||
|
||||
Args:
|
||||
activity_id: ID of the activity to delete
|
||||
|
||||
Returns:
|
||||
True if activity was deleted, False if not found
|
||||
"""
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM issue_activity_log WHERE id = ?', (activity_id,))
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def bulk_log_activities(self, activities: List[Dict[str, Any]]) -> List[int]:
|
||||
"""
|
||||
Log multiple activities in a single transaction.
|
||||
|
||||
Args:
|
||||
activities: List of activity dictionaries with keys:
|
||||
issue_id, activity_type, activity_date (optional),
|
||||
activity_details (optional), period_id (optional)
|
||||
|
||||
Returns:
|
||||
List of created activity IDs
|
||||
|
||||
Raises:
|
||||
ValueError: If activity data is invalid
|
||||
sqlite3.Error: If database operation fails
|
||||
"""
|
||||
activity_ids = []
|
||||
|
||||
with self.finance_models.get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
for activity_data in activities:
|
||||
if 'issue_id' not in activity_data or 'activity_type' not in activity_data:
|
||||
raise ValueError("Each activity must have 'issue_id' and 'activity_type'")
|
||||
|
||||
issue_id = activity_data['issue_id']
|
||||
activity_type = ActivityType(activity_data['activity_type'])
|
||||
activity_date = activity_data.get('activity_date', date.today())
|
||||
activity_details = activity_data.get('activity_details')
|
||||
period_id = activity_data.get('period_id')
|
||||
|
||||
# Auto-determine period if not provided
|
||||
if period_id is None:
|
||||
cursor.execute('''
|
||||
SELECT id FROM cost_periods
|
||||
WHERE ? BETWEEN period_start AND period_end
|
||||
ORDER BY created_at DESC LIMIT 1
|
||||
''', (activity_date.isoformat() if hasattr(activity_date, 'isoformat') else activity_date,))
|
||||
result = cursor.fetchone()
|
||||
if result:
|
||||
period_id = result[0]
|
||||
|
||||
cursor.execute('''
|
||||
INSERT INTO issue_activity_log
|
||||
(issue_id, activity_type, activity_date, period_id, activity_details)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
''', (issue_id, activity_type.value, activity_date.isoformat() if hasattr(activity_date, 'isoformat') else activity_date, period_id, activity_details))
|
||||
|
||||
activity_ids.append(cursor.lastrowid)
|
||||
|
||||
return activity_ids
|
||||
@@ -1,109 +0,0 @@
|
||||
"""
|
||||
Abstract base class for issue management backends.
|
||||
|
||||
This module defines the interface that all issue management backends must implement.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import List, Optional, Dict, Any
|
||||
import sys
|
||||
from pathlib import Path
|
||||
# Add project root to path so domain module can be imported
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
if str(project_root) not in sys.path:
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from domain.issues.models import Issue
|
||||
|
||||
|
||||
class IssueBackend(ABC):
|
||||
"""Abstract base class for issue management backends."""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]):
|
||||
"""Initialize backend with configuration."""
|
||||
self.config = config
|
||||
|
||||
@abstractmethod
|
||||
def list_issues(self, state: Optional[str] = None) -> List[Issue]:
|
||||
"""
|
||||
List issues with optional state filter.
|
||||
|
||||
Args:
|
||||
state: Filter by state ('open', 'closed', 'all', or None for all)
|
||||
|
||||
Returns:
|
||||
List of Issue objects
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_issue(self, issue_id: str) -> Issue:
|
||||
"""
|
||||
Get specific issue by ID.
|
||||
|
||||
Args:
|
||||
issue_id: The issue identifier
|
||||
|
||||
Returns:
|
||||
Issue object
|
||||
|
||||
Raises:
|
||||
Exception: If issue not found
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def create_issue(self, title: str, body: str, **kwargs) -> Issue:
|
||||
"""
|
||||
Create new issue.
|
||||
|
||||
Args:
|
||||
title: Issue title
|
||||
body: Issue body/description
|
||||
**kwargs: Additional issue properties (labels, assignees, etc.)
|
||||
|
||||
Returns:
|
||||
Created Issue object
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def add_comment(self, issue_id: str, comment: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Add comment to issue.
|
||||
|
||||
Args:
|
||||
issue_id: The issue identifier
|
||||
comment: Comment text
|
||||
|
||||
Returns:
|
||||
Comment metadata (id, timestamp, etc.)
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def close_issue(self, issue_id: str) -> Issue:
|
||||
"""
|
||||
Close issue.
|
||||
|
||||
Args:
|
||||
issue_id: The issue identifier
|
||||
|
||||
Returns:
|
||||
Updated Issue object with closed state
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def update_issue(self, issue_id: str, **kwargs) -> Issue:
|
||||
"""
|
||||
Update issue properties.
|
||||
|
||||
Args:
|
||||
issue_id: The issue identifier
|
||||
**kwargs: Properties to update (title, body, state, etc.)
|
||||
|
||||
Returns:
|
||||
Updated Issue object
|
||||
"""
|
||||
pass
|
||||
@@ -1,165 +0,0 @@
|
||||
"""
|
||||
CLI commands for issue management.
|
||||
|
||||
This module provides Click commands for the unified issue management interface.
|
||||
"""
|
||||
|
||||
import click
|
||||
from typing import Optional
|
||||
|
||||
from .manager import IssuePluginManager
|
||||
from .exceptions import PluginNotFoundError, ConfigurationError
|
||||
from cli.presenters.views import IssueView
|
||||
|
||||
|
||||
@click.group()
|
||||
def issues():
|
||||
"""Issue management with multiple backend support."""
|
||||
pass
|
||||
|
||||
|
||||
@issues.command()
|
||||
@click.option('--state', type=click.Choice(['open', 'closed', 'all']), default='all',
|
||||
help='Filter issues by state')
|
||||
@click.option('--backend', help='Override configured backend')
|
||||
def list(state: str, backend: Optional[str]):
|
||||
"""List issues from configured backend."""
|
||||
try:
|
||||
manager = IssuePluginManager()
|
||||
backend_instance = manager.get_backend(backend)
|
||||
issues_list = backend_instance.list_issues(state=state)
|
||||
|
||||
if state == 'open':
|
||||
IssueView.show_open_issues(issues_list)
|
||||
else:
|
||||
IssueView.show_list(issues_list, f"Issues ({state})")
|
||||
|
||||
except (PluginNotFoundError, ConfigurationError) as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"Unexpected error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@issues.command()
|
||||
@click.argument('issue_id')
|
||||
@click.option('--backend', help='Override configured backend')
|
||||
def show(issue_id: str, backend: Optional[str]):
|
||||
"""Show details of a specific issue."""
|
||||
try:
|
||||
manager = IssuePluginManager()
|
||||
backend_instance = manager.get_backend(backend)
|
||||
issue = backend_instance.get_issue(issue_id)
|
||||
|
||||
# Convert issue to dict for display
|
||||
issue_data = {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': getattr(issue, '_body', ''),
|
||||
'state': issue.state.value if hasattr(issue.state, 'value') else str(issue.state),
|
||||
'created_at': issue.created_at,
|
||||
'updated_at': getattr(issue, 'updated_at', issue.created_at),
|
||||
'labels': [label.name if hasattr(label, 'name') else str(label) for label in issue.labels],
|
||||
'assignees': getattr(issue, 'assignees', []) or [],
|
||||
'assignee': getattr(issue, 'assignee', None),
|
||||
'milestone': getattr(issue, 'milestone', None),
|
||||
'html_url': getattr(issue, 'html_url', ''),
|
||||
'state_label': getattr(issue, 'state_label', issue.state.value if hasattr(issue.state, 'value') else str(issue.state)),
|
||||
'priority_label': getattr(issue, 'priority_label', 'Normal'),
|
||||
'type_labels': getattr(issue, 'type_labels', []),
|
||||
'other_labels': getattr(issue, 'other_labels', []),
|
||||
'kanban_column': getattr(issue, 'kanban_column', 'To Do')
|
||||
}
|
||||
|
||||
IssueView.show_issue_details(issue_data)
|
||||
|
||||
except FileNotFoundError:
|
||||
click.echo(f"Error: Issue {issue_id} not found", err=True)
|
||||
raise click.Abort()
|
||||
except (PluginNotFoundError, ConfigurationError) as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"Unexpected error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@issues.command()
|
||||
@click.argument('title')
|
||||
@click.argument('body')
|
||||
@click.option('--backend', help='Override configured backend')
|
||||
def create(title: str, body: str, backend: Optional[str]):
|
||||
"""Create a new issue."""
|
||||
try:
|
||||
manager = IssuePluginManager()
|
||||
backend_instance = manager.get_backend(backend)
|
||||
issue = backend_instance.create_issue(title, body)
|
||||
|
||||
# Convert issue to dict for display
|
||||
result = {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'state': issue.state.value if hasattr(issue.state, 'value') else str(issue.state)
|
||||
}
|
||||
|
||||
IssueView.show_creation_success(result, "issue")
|
||||
click.echo(f"Issue #{issue.number} created successfully")
|
||||
|
||||
except (PluginNotFoundError, ConfigurationError) as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"Unexpected error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@issues.command()
|
||||
@click.argument('issue_id')
|
||||
@click.argument('comment')
|
||||
@click.option('--backend', help='Override configured backend')
|
||||
def comment(issue_id: str, comment: str, backend: Optional[str]):
|
||||
"""Add a comment to an issue."""
|
||||
try:
|
||||
manager = IssuePluginManager()
|
||||
backend_instance = manager.get_backend(backend)
|
||||
result = backend_instance.add_comment(issue_id, comment)
|
||||
|
||||
click.echo(f"Comment added to issue #{issue_id}")
|
||||
|
||||
except ValueError as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except (PluginNotFoundError, ConfigurationError) as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"Unexpected error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
@issues.command()
|
||||
@click.argument('issue_id')
|
||||
@click.option('--backend', help='Override configured backend')
|
||||
def close(issue_id: str, backend: Optional[str]):
|
||||
"""Close an issue."""
|
||||
try:
|
||||
manager = IssuePluginManager()
|
||||
backend_instance = manager.get_backend(backend)
|
||||
issue = backend_instance.close_issue(issue_id)
|
||||
|
||||
click.echo(f"Issue #{issue_id} closed successfully")
|
||||
|
||||
except FileNotFoundError:
|
||||
click.echo(f"Error: Issue {issue_id} not found", err=True)
|
||||
raise click.Abort()
|
||||
except (PluginNotFoundError, ConfigurationError) as e:
|
||||
click.echo(f"Error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
except Exception as e:
|
||||
click.echo(f"Unexpected error: {e}", err=True)
|
||||
raise click.Abort()
|
||||
|
||||
|
||||
# Make issues_group available for import
|
||||
issues_group = issues
|
||||
@@ -1,18 +0,0 @@
|
||||
"""
|
||||
Exceptions for the issue management module.
|
||||
"""
|
||||
|
||||
|
||||
class IssuePluginError(Exception):
|
||||
"""Base exception for issue plugin errors."""
|
||||
pass
|
||||
|
||||
|
||||
class PluginNotFoundError(IssuePluginError):
|
||||
"""Raised when a requested plugin is not found."""
|
||||
pass
|
||||
|
||||
|
||||
class ConfigurationError(IssuePluginError):
|
||||
"""Raised when there's a configuration error."""
|
||||
pass
|
||||
@@ -1,600 +0,0 @@
|
||||
"""
|
||||
Single Command Issue Wrap-Up functionality.
|
||||
|
||||
This module provides comprehensive issue completion automation including:
|
||||
- Requirement validation and verification
|
||||
- Test execution and validation
|
||||
- Cost note creation and database updates
|
||||
- Git operations (add, commit with cost notes)
|
||||
- Comprehensive completion summary
|
||||
|
||||
The system automates the entire issue closure workflow in a single command.
|
||||
"""
|
||||
|
||||
import click
|
||||
import subprocess
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime, date
|
||||
from typing import Optional, Dict, Any, List
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from tabulate import tabulate
|
||||
|
||||
from ..finance.worktime_tracker import WorktimeTracker
|
||||
from ..finance.session_tracker import SessionCostTracker
|
||||
from ..finance.cost_manager import CostItemManager
|
||||
from .activity_tracker import IssueActivityTracker
|
||||
from .manager import IssuePluginManager
|
||||
|
||||
|
||||
class IssueWrapUpService:
|
||||
"""Service for comprehensive issue wrap-up functionality."""
|
||||
|
||||
def __init__(self, db_path: str = "markitect.db"):
|
||||
"""Initialize the issue wrap-up service."""
|
||||
self.db_path = db_path
|
||||
self.worktime_tracker = WorktimeTracker(db_path)
|
||||
self.activity_tracker = IssueActivityTracker(db_path)
|
||||
self.session_tracker = SessionCostTracker(db_path)
|
||||
self.cost_manager = CostItemManager(db_path)
|
||||
self.issue_manager = IssuePluginManager()
|
||||
|
||||
def wrap_up_issue(self, issue_number: int, force: bool = False) -> Dict[str, Any]:
|
||||
"""
|
||||
Perform comprehensive issue wrap-up.
|
||||
|
||||
Args:
|
||||
issue_number: Issue number to wrap up
|
||||
force: Skip validation checks if True
|
||||
|
||||
Returns:
|
||||
Dictionary containing wrap-up results
|
||||
"""
|
||||
wrap_up_results = {
|
||||
'issue_number': issue_number,
|
||||
'timestamp': datetime.now(),
|
||||
'steps': {}
|
||||
}
|
||||
|
||||
# Step 1: Get issue details
|
||||
click.echo(f"🔍 Retrieving issue #{issue_number} details...")
|
||||
issue_details = self._get_issue_details(issue_number)
|
||||
wrap_up_results['issue_details'] = issue_details
|
||||
wrap_up_results['steps']['issue_retrieval'] = {'success': bool(issue_details)}
|
||||
|
||||
if not issue_details and not force:
|
||||
wrap_up_results['steps']['issue_retrieval']['error'] = "Issue not found"
|
||||
return wrap_up_results
|
||||
|
||||
# Step 2: Review requirements (placeholder - would need issue analysis)
|
||||
click.echo("📋 Reviewing requirements...")
|
||||
req_check = self._review_requirements(issue_number, issue_details, force)
|
||||
wrap_up_results['steps']['requirement_review'] = req_check
|
||||
|
||||
# Step 3: Run associated tests
|
||||
click.echo("🧪 Running associated tests...")
|
||||
test_results = self._run_issue_tests(issue_number, force)
|
||||
wrap_up_results['steps']['test_execution'] = test_results
|
||||
|
||||
# Step 4: Run full test suite
|
||||
click.echo("🔬 Running full test suite...")
|
||||
full_test_results = self._run_full_tests(force)
|
||||
wrap_up_results['steps']['full_test_execution'] = full_test_results
|
||||
|
||||
# Step 5: Calculate and update costs
|
||||
click.echo("💰 Calculating and updating costs...")
|
||||
cost_results = self._update_cost_tracking(issue_number, issue_details)
|
||||
wrap_up_results['steps']['cost_tracking'] = cost_results
|
||||
|
||||
# Step 6: Create/update cost note
|
||||
click.echo("📄 Creating/updating cost note...")
|
||||
cost_note_results = self._create_cost_note(issue_number, issue_details, cost_results)
|
||||
wrap_up_results['steps']['cost_note'] = cost_note_results
|
||||
|
||||
# Step 7: Git operations
|
||||
click.echo("📦 Adding and committing changes...")
|
||||
git_results = self._git_operations(issue_number, issue_details)
|
||||
wrap_up_results['steps']['git_operations'] = git_results
|
||||
|
||||
# Step 8: Close issue
|
||||
click.echo("🔒 Closing issue...")
|
||||
closure_results = self._close_issue(issue_number)
|
||||
wrap_up_results['steps']['issue_closure'] = closure_results
|
||||
|
||||
return wrap_up_results
|
||||
|
||||
def _get_issue_details(self, issue_number: int) -> Optional[Dict[str, Any]]:
|
||||
"""Retrieve issue details from the backend."""
|
||||
try:
|
||||
backend = self.issue_manager.get_backend()
|
||||
# This would call the actual backend API
|
||||
# For now, simulate with basic info
|
||||
return {
|
||||
'number': issue_number,
|
||||
'title': f"Issue #{issue_number}",
|
||||
'status': 'open',
|
||||
'description': 'Issue description would be retrieved from backend'
|
||||
}
|
||||
except Exception as e:
|
||||
return None
|
||||
|
||||
def _review_requirements(self, issue_number: int, issue_details: Optional[Dict], force: bool) -> Dict[str, Any]:
|
||||
"""Review that requirements have been met."""
|
||||
if force:
|
||||
return {'success': True, 'forced': True}
|
||||
|
||||
# This would implement actual requirement checking logic
|
||||
# For now, check if there are recent activities
|
||||
activities = self.activity_tracker.get_issue_activities(
|
||||
issue_id=issue_number,
|
||||
limit=10
|
||||
)
|
||||
|
||||
has_implementation = any(
|
||||
activity.has_implementation_activity()
|
||||
for activity in activities
|
||||
)
|
||||
|
||||
return {
|
||||
'success': has_implementation or len(activities) > 0,
|
||||
'activities_count': len(activities),
|
||||
'has_implementation_activity': has_implementation
|
||||
}
|
||||
|
||||
def _run_issue_tests(self, issue_number: int, force: bool) -> Dict[str, Any]:
|
||||
"""Run tests associated with the issue."""
|
||||
test_files = [
|
||||
f"tests/test_issue_{issue_number}_*.py",
|
||||
f"tests/test_issue_{issue_number}.py"
|
||||
]
|
||||
|
||||
results = {
|
||||
'success': True,
|
||||
'test_files': [],
|
||||
'output': []
|
||||
}
|
||||
|
||||
for test_pattern in test_files:
|
||||
# Check if test files exist
|
||||
test_files_found = list(Path('.').glob(test_pattern))
|
||||
|
||||
for test_file in test_files_found:
|
||||
results['test_files'].append(str(test_file))
|
||||
|
||||
try:
|
||||
if force:
|
||||
results['output'].append(f"FORCED: Skipping test execution for {test_file}")
|
||||
continue
|
||||
|
||||
# Run the specific test
|
||||
cmd = ['.venv/bin/python', '-m', 'pytest', str(test_file), '-v']
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd='.')
|
||||
|
||||
results['output'].append({
|
||||
'file': str(test_file),
|
||||
'returncode': result.returncode,
|
||||
'stdout': result.stdout,
|
||||
'stderr': result.stderr
|
||||
})
|
||||
|
||||
if result.returncode != 0:
|
||||
results['success'] = False
|
||||
|
||||
except Exception as e:
|
||||
results['success'] = False
|
||||
results['output'].append({
|
||||
'file': str(test_file),
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
if not results['test_files']:
|
||||
results['output'].append(f"No specific test files found for issue #{issue_number}")
|
||||
|
||||
return results
|
||||
|
||||
def _run_full_tests(self, force: bool) -> Dict[str, Any]:
|
||||
"""Run the full test suite to ensure no regressions."""
|
||||
if force:
|
||||
return {
|
||||
'success': True,
|
||||
'forced': True,
|
||||
'output': 'FORCED: Skipped full test suite execution'
|
||||
}
|
||||
|
||||
try:
|
||||
# Try to determine the test command from Makefile or common patterns
|
||||
test_commands = [
|
||||
['make', 'test'],
|
||||
['.venv/bin/python', '-m', 'pytest', '-v'],
|
||||
['python', '-m', 'pytest', '-v'],
|
||||
['pytest', '-v']
|
||||
]
|
||||
|
||||
for cmd in test_commands:
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd='.', timeout=300)
|
||||
return {
|
||||
'success': result.returncode == 0,
|
||||
'command': ' '.join(cmd),
|
||||
'returncode': result.returncode,
|
||||
'stdout': result.stdout,
|
||||
'stderr': result.stderr
|
||||
}
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
continue
|
||||
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'No suitable test command found'
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def _update_cost_tracking(self, issue_number: int, issue_details: Optional[Dict]) -> Dict[str, Any]:
|
||||
"""Calculate and register time and cost data in database."""
|
||||
try:
|
||||
# Get activity data
|
||||
activities = self.activity_tracker.get_issue_activities(issue_id=issue_number)
|
||||
|
||||
# Get session cost data - method may not exist
|
||||
session_costs = []
|
||||
try:
|
||||
if hasattr(self.session_tracker, 'get_issue_costs'):
|
||||
session_costs = self.session_tracker.get_issue_costs(issue_number)
|
||||
elif hasattr(self.session_tracker, 'get_costs_for_issue'):
|
||||
session_costs = self.session_tracker.get_costs_for_issue(issue_number)
|
||||
except Exception:
|
||||
# If session cost tracking fails, continue with empty list
|
||||
session_costs = []
|
||||
|
||||
# Try to get worktime data - method name may vary
|
||||
total_minutes = 0
|
||||
try:
|
||||
# Try different possible methods for getting worktime data
|
||||
if hasattr(self.worktime_tracker, 'get_issue_summary'):
|
||||
worktime_summary = self.worktime_tracker.get_issue_summary(issue_number)
|
||||
total_minutes = worktime_summary.get('total_minutes', 0) if worktime_summary else 0
|
||||
elif hasattr(self.worktime_tracker, 'get_issue_worktime'):
|
||||
worktime_data = self.worktime_tracker.get_issue_worktime(issue_number)
|
||||
total_minutes = worktime_data.get('total_minutes', 0) if worktime_data else 0
|
||||
# If no specific method available, try to calculate from entries
|
||||
elif hasattr(self.worktime_tracker, 'get_entries'):
|
||||
entries = self.worktime_tracker.get_entries()
|
||||
total_minutes = sum(
|
||||
entry.duration_minutes for entry in entries
|
||||
if hasattr(entry, 'issue_id') and entry.issue_id == issue_number
|
||||
)
|
||||
except Exception:
|
||||
# If worktime tracking fails, continue with 0
|
||||
total_minutes = 0
|
||||
|
||||
# Calculate totals
|
||||
total_cost = sum(cost.get('cost_eur', 0) for cost in session_costs)
|
||||
|
||||
cost_data = {
|
||||
'issue_number': issue_number,
|
||||
'total_minutes': total_minutes,
|
||||
'total_hours': total_minutes / 60 if total_minutes else 0,
|
||||
'total_cost_eur': total_cost,
|
||||
'activity_count': len(activities),
|
||||
'session_count': len(session_costs)
|
||||
}
|
||||
|
||||
# This would register in a centralized cost tracking system
|
||||
# For now, just return the calculated data
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'cost_data': cost_data
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def _create_cost_note(self, issue_number: int, issue_details: Optional[Dict], cost_results: Dict) -> Dict[str, Any]:
|
||||
"""Create or update cost note for the issue."""
|
||||
try:
|
||||
cost_data = cost_results.get('cost_data', {})
|
||||
|
||||
# Create cost note content
|
||||
cost_note_content = self._generate_cost_note_content(
|
||||
issue_number, issue_details, cost_data
|
||||
)
|
||||
|
||||
# Write cost note file
|
||||
cost_note_path = Path(f"cost_notes/issue_{issue_number}_cost_{date.today().isoformat()}.md")
|
||||
cost_note_path.parent.mkdir(exist_ok=True)
|
||||
|
||||
with open(cost_note_path, 'w') as f:
|
||||
f.write(cost_note_content)
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'cost_note_path': str(cost_note_path)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def _generate_cost_note_content(self, issue_number: int, issue_details: Optional[Dict], cost_data: Dict) -> str:
|
||||
"""Generate cost note content."""
|
||||
title = issue_details.get('title', f'Issue #{issue_number}') if issue_details else f'Issue #{issue_number}'
|
||||
|
||||
total_cost_eur = cost_data.get('total_cost_eur', 0)
|
||||
total_cost_usd = total_cost_eur / 0.92 if total_cost_eur else 0 # Approximate conversion
|
||||
|
||||
content = f"""---
|
||||
note_type: "issue_cost_tracking"
|
||||
issue_id: {issue_number}
|
||||
issue_title: "{title}"
|
||||
session_date: "{date.today().isoformat()}"
|
||||
claude_model: "claude-sonnet-4"
|
||||
total_cost_eur: {total_cost_eur:.4f}
|
||||
total_cost_usd: {total_cost_usd:.3f}
|
||||
total_minutes: {cost_data.get('total_minutes', 0)}
|
||||
implementation_time_minutes: {cost_data.get('total_minutes', 0)}
|
||||
generated_at: "{datetime.now().isoformat()}"
|
||||
---
|
||||
|
||||
# Issue #{issue_number} Implementation Cost
|
||||
**Issue**: {title}
|
||||
**Date**: {date.today().isoformat()}
|
||||
**Claude Model**: claude-sonnet-4
|
||||
|
||||
## Cost Summary
|
||||
- **Total Cost**: €{total_cost_eur:.4f} (${total_cost_usd:.4f} USD)
|
||||
- **Implementation Time**: {cost_data.get('total_hours', 0):.1f} hours ({cost_data.get('total_minutes', 0)} minutes)
|
||||
- **Activities Tracked**: {cost_data.get('activity_count', 0)} activities
|
||||
- **Sessions**: {cost_data.get('session_count', 0)} cost sessions
|
||||
|
||||
## Implementation Summary
|
||||
Issue #{issue_number} "{title}" has been completed and wrapped up through automated process.
|
||||
|
||||
## Cost Allocation
|
||||
This cost has been allocated to issue #{issue_number} implementation.
|
||||
|
||||
## Notes
|
||||
- Currency conversion rate: 1 USD = 0.920 EUR
|
||||
- Pricing based on claude-sonnet-4 rates as of {date.today().isoformat()}
|
||||
- Implementation time includes design, coding, testing, and validation
|
||||
|
||||
<!--
|
||||
contentmatter:
|
||||
{{
|
||||
"cost_tracking": {{
|
||||
"issue": {{
|
||||
"id": {issue_number},
|
||||
"title": "{title}",
|
||||
"completion_date": "{date.today().isoformat()}",
|
||||
"implementation_time_minutes": {cost_data.get('total_minutes', 0)},
|
||||
"status": "completed"
|
||||
}},
|
||||
"costs": {{
|
||||
"total_cost_usd": {total_cost_usd:.4f},
|
||||
"total_cost_eur": {total_cost_eur:.4f},
|
||||
"conversion_rate": 0.92
|
||||
}},
|
||||
"tracking": {{
|
||||
"activity_count": {cost_data.get('activity_count', 0)},
|
||||
"session_count": {cost_data.get('session_count', 0)}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
-->
|
||||
"""
|
||||
return content
|
||||
|
||||
def _git_operations(self, issue_number: int, issue_details: Optional[Dict]) -> Dict[str, Any]:
|
||||
"""Perform git add and commit operations."""
|
||||
try:
|
||||
# Add all changes including cost notes
|
||||
result_add = subprocess.run(['git', 'add', '.'], capture_output=True, text=True)
|
||||
|
||||
if result_add.returncode != 0:
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Git add failed: {result_add.stderr}'
|
||||
}
|
||||
|
||||
# Create commit message
|
||||
title = issue_details.get('title', f'Issue #{issue_number}') if issue_details else f'Issue #{issue_number}'
|
||||
commit_message = f"""feat: complete issue #{issue_number} - {title}
|
||||
|
||||
Automated issue wrap-up including:
|
||||
- Implementation completion verification
|
||||
- Test execution and validation
|
||||
- Cost tracking and note generation
|
||||
- Repository state commit
|
||||
|
||||
🤖 Generated with [Claude Code](https://claude.ai/code)
|
||||
|
||||
Co-Authored-By: Claude <noreply@anthropic.com>"""
|
||||
|
||||
# Commit changes
|
||||
result_commit = subprocess.run(
|
||||
['git', 'commit', '-m', commit_message],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
|
||||
return {
|
||||
'success': result_commit.returncode == 0,
|
||||
'add_output': result_add.stdout,
|
||||
'commit_output': result_commit.stdout,
|
||||
'commit_error': result_commit.stderr if result_commit.returncode != 0 else None
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def _close_issue(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Close the issue using the issue management system."""
|
||||
try:
|
||||
# Log closing activity
|
||||
self.activity_tracker.log_activity(
|
||||
issue_id=issue_number,
|
||||
activity_type="close",
|
||||
description=f"Issue #{issue_number} completed via automated wrap-up process"
|
||||
)
|
||||
|
||||
# Try to close via make command (most reliable method)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['make', 'close-issue', f'NUM={issue_number}'],
|
||||
capture_output=True, text=True, cwd='.'
|
||||
)
|
||||
|
||||
return {
|
||||
'success': result.returncode == 0,
|
||||
'method': 'make',
|
||||
'output': result.stdout,
|
||||
'error': result.stderr if result.returncode != 0 else None
|
||||
}
|
||||
|
||||
except Exception:
|
||||
# Fallback to direct backend call
|
||||
try:
|
||||
backend = self.issue_manager.get_backend()
|
||||
# This would call backend.close_issue(issue_number)
|
||||
return {
|
||||
'success': False,
|
||||
'method': 'backend',
|
||||
'error': 'Backend closure not implemented'
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'method': 'backend',
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
def format_summary(self, results: Dict[str, Any]) -> str:
|
||||
"""Format wrap-up results as a readable summary."""
|
||||
issue_num = results['issue_number']
|
||||
timestamp = results['timestamp'].strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
summary = [
|
||||
f"\n🎉 Issue #{issue_num} Wrap-Up Complete",
|
||||
f"📅 Completed: {timestamp}",
|
||||
"=" * 50
|
||||
]
|
||||
|
||||
# Step-by-step results
|
||||
steps = results.get('steps', {})
|
||||
step_names = {
|
||||
'issue_retrieval': '🔍 Issue Retrieval',
|
||||
'requirement_review': '📋 Requirement Review',
|
||||
'test_execution': '🧪 Associated Tests',
|
||||
'full_test_execution': '🔬 Full Test Suite',
|
||||
'cost_tracking': '💰 Cost Tracking',
|
||||
'cost_note': '📄 Cost Note',
|
||||
'git_operations': '📦 Git Operations',
|
||||
'issue_closure': '🔒 Issue Closure'
|
||||
}
|
||||
|
||||
for step_key, step_name in step_names.items():
|
||||
if step_key in steps:
|
||||
step_result = steps[step_key]
|
||||
success = step_result.get('success', False)
|
||||
status = "✅ SUCCESS" if success else "❌ FAILED"
|
||||
summary.append(f"{step_name}: {status}")
|
||||
|
||||
if not success and 'error' in step_result:
|
||||
summary.append(f" Error: {step_result['error']}")
|
||||
|
||||
# Cost information
|
||||
if 'cost_tracking' in steps and steps['cost_tracking'].get('success'):
|
||||
cost_data = steps['cost_tracking'].get('cost_data', {})
|
||||
if cost_data:
|
||||
summary.extend([
|
||||
"",
|
||||
"💰 Cost Summary:",
|
||||
f" Time: {cost_data.get('total_hours', 0):.1f} hours",
|
||||
f" Cost: €{cost_data.get('total_cost_eur', 0):.4f}",
|
||||
f" Activities: {cost_data.get('activity_count', 0)}"
|
||||
])
|
||||
|
||||
# Overall status
|
||||
all_critical_success = all(
|
||||
steps.get(step, {}).get('success', False)
|
||||
for step in ['test_execution', 'full_test_execution', 'git_operations']
|
||||
)
|
||||
|
||||
summary.extend([
|
||||
"",
|
||||
"🎯 Overall Status:",
|
||||
"✅ SUCCESS - Issue wrap-up completed successfully!" if all_critical_success
|
||||
else "⚠️ PARTIAL - Some steps had issues, please review above"
|
||||
])
|
||||
|
||||
return "\n".join(summary)
|
||||
|
||||
|
||||
@click.group()
|
||||
def issue_wrapup():
|
||||
"""Issue wrap-up commands for comprehensive issue completion."""
|
||||
pass
|
||||
|
||||
|
||||
@issue_wrapup.command()
|
||||
@click.argument('issue_number', type=int)
|
||||
@click.option('--force', is_flag=True, help='Skip validation checks and force completion')
|
||||
@click.option('--format', 'output_format', type=click.Choice(['summary', 'detailed', 'json']),
|
||||
default='summary', help='Output format')
|
||||
def complete(issue_number: int, force: bool, output_format: str):
|
||||
"""Complete comprehensive wrap-up for an issue.
|
||||
|
||||
Performs all steps needed to properly close an issue:
|
||||
- Verifies requirements have been met
|
||||
- Runs associated tests and full test suite
|
||||
- Calculates and updates cost tracking
|
||||
- Creates/updates cost notes
|
||||
- Commits changes to repository
|
||||
- Closes the issue
|
||||
- Provides completion summary
|
||||
"""
|
||||
service = IssueWrapUpService()
|
||||
|
||||
try:
|
||||
results = service.wrap_up_issue(issue_number, force=force)
|
||||
|
||||
if output_format == 'json':
|
||||
# Convert datetime objects to strings for JSON serialization
|
||||
json_results = json.loads(json.dumps(results, default=str))
|
||||
click.echo(json.dumps(json_results, indent=2))
|
||||
elif output_format == 'detailed':
|
||||
click.echo(service.format_summary(results))
|
||||
# Add detailed step information
|
||||
for step_name, step_data in results.get('steps', {}).items():
|
||||
if 'output' in step_data:
|
||||
click.echo(f"\n--- {step_name.title()} Details ---")
|
||||
click.echo(json.dumps(step_data['output'], indent=2, default=str))
|
||||
else: # summary
|
||||
click.echo(service.format_summary(results))
|
||||
|
||||
except Exception as e:
|
||||
click.echo(f"❌ Error during issue wrap-up: {str(e)}", err=True)
|
||||
raise click.ClickException(f"Issue wrap-up failed: {str(e)}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
issue_wrapup()
|
||||
@@ -1,151 +0,0 @@
|
||||
"""
|
||||
Plugin manager for issue backends.
|
||||
|
||||
This module handles discovery, loading, and configuration of issue management backends.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Type, Optional
|
||||
|
||||
from .base import IssueBackend
|
||||
from .exceptions import PluginNotFoundError, ConfigurationError
|
||||
|
||||
|
||||
class IssuePluginManager:
|
||||
"""Manages issue backend plugins and configuration."""
|
||||
|
||||
def __init__(self, config_path: Optional[str] = None):
|
||||
"""
|
||||
Initialize plugin manager.
|
||||
|
||||
Args:
|
||||
config_path: Optional path to configuration file
|
||||
"""
|
||||
self.config = self._load_config(config_path)
|
||||
self.plugins = self._discover_plugins()
|
||||
|
||||
def get_backend(self, backend_name: Optional[str] = None) -> IssueBackend:
|
||||
"""
|
||||
Get configured backend instance.
|
||||
|
||||
Args:
|
||||
backend_name: Backend name to use, or None for default
|
||||
|
||||
Returns:
|
||||
IssueBackend instance
|
||||
|
||||
Raises:
|
||||
PluginNotFoundError: If backend not found
|
||||
"""
|
||||
backend_name = backend_name or self.config.get('default_backend', 'gitea')
|
||||
|
||||
plugin_class = self.plugins.get(backend_name)
|
||||
if not plugin_class:
|
||||
raise PluginNotFoundError(f"Unknown backend: {backend_name}")
|
||||
|
||||
backend_config = self.config.get('backends', {}).get(backend_name, {})
|
||||
return plugin_class(backend_config)
|
||||
|
||||
def _load_config(self, config_path: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Load configuration from file or return defaults.
|
||||
|
||||
Args:
|
||||
config_path: Path to configuration file
|
||||
|
||||
Returns:
|
||||
Configuration dictionary
|
||||
"""
|
||||
from config.manager import UnifiedConfigManager
|
||||
|
||||
# Get main markitect configuration to extract API token and settings
|
||||
try:
|
||||
config_manager = UnifiedConfigManager()
|
||||
markitect_config = config_manager.get_config()
|
||||
main_config = markitect_config.__dict__ if hasattr(markitect_config, '__dict__') else {}
|
||||
except Exception:
|
||||
main_config = {}
|
||||
|
||||
if config_path is None:
|
||||
config_path = Path('.markitect/config/issues.yml')
|
||||
else:
|
||||
config_path = Path(config_path)
|
||||
|
||||
# Extract configuration from main markitect config
|
||||
gitea_url = main_config.get('gitea_url', 'http://92.205.130.254:32166')
|
||||
api_token = main_config.get('api_token', '')
|
||||
repo_owner = main_config.get('repo_owner', 'coulomb')
|
||||
repo_name = main_config.get('repo_name', 'markitect_project')
|
||||
|
||||
# Default configuration using main config values
|
||||
default_config = {
|
||||
'default_backend': 'gitea',
|
||||
'backends': {
|
||||
'gitea': {
|
||||
'url': gitea_url,
|
||||
'token': api_token,
|
||||
'repo_owner': repo_owner,
|
||||
'repo_name': repo_name,
|
||||
'repo': f'{repo_owner}/{repo_name}'
|
||||
},
|
||||
'local': {
|
||||
'directory': '.markitect/issues',
|
||||
'auto_git': True
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if not config_path.exists():
|
||||
return default_config
|
||||
|
||||
try:
|
||||
with open(config_path, 'r') as f:
|
||||
config = yaml.safe_load(f) or {}
|
||||
|
||||
# Merge with defaults
|
||||
merged_config = default_config.copy()
|
||||
merged_config.update(config)
|
||||
|
||||
# Ensure gitea backend has token from main config if not overridden
|
||||
if 'backends' in merged_config and 'gitea' in merged_config['backends']:
|
||||
gitea_config = merged_config['backends']['gitea']
|
||||
if not gitea_config.get('token'):
|
||||
gitea_config['token'] = api_token
|
||||
if not gitea_config.get('repo_owner'):
|
||||
gitea_config['repo_owner'] = repo_owner
|
||||
if not gitea_config.get('repo_name'):
|
||||
gitea_config['repo_name'] = repo_name
|
||||
|
||||
return merged_config
|
||||
except Exception:
|
||||
# Return defaults if config loading fails
|
||||
return default_config
|
||||
|
||||
def _discover_plugins(self) -> Dict[str, Type[IssueBackend]]:
|
||||
"""
|
||||
Discover available backend plugins.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping backend names to plugin classes
|
||||
"""
|
||||
plugins = {}
|
||||
|
||||
# Try to import known plugins
|
||||
plugin_modules = [
|
||||
('gitea', 'markitect.issues.plugins.gitea', 'GiteaPlugin'),
|
||||
('local', 'markitect.issues.plugins.local', 'LocalPlugin'),
|
||||
]
|
||||
|
||||
for name, module_path, class_name in plugin_modules:
|
||||
try:
|
||||
module = importlib.import_module(module_path)
|
||||
plugin_class = getattr(module, class_name)
|
||||
if issubclass(plugin_class, IssueBackend):
|
||||
plugins[name] = plugin_class
|
||||
except (ImportError, AttributeError):
|
||||
# Plugin not available, skip
|
||||
continue
|
||||
|
||||
return plugins
|
||||
@@ -1,5 +0,0 @@
|
||||
"""
|
||||
Issue management plugins.
|
||||
|
||||
This package contains backend implementations for different issue management systems.
|
||||
"""
|
||||
@@ -1,102 +0,0 @@
|
||||
"""
|
||||
Gitea backend plugin for issue management.
|
||||
|
||||
This plugin integrates with existing GiteaIssueRepository infrastructure.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
from ..base import IssueBackend
|
||||
from domain.issues.models import Issue
|
||||
from infrastructure.repositories.gitea_repository import GiteaIssueRepository
|
||||
from infrastructure.connection_manager import ConnectionManager, DataSourceConfig
|
||||
|
||||
|
||||
class GiteaPlugin(IssueBackend):
|
||||
"""Gitea backend plugin using existing repository infrastructure."""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]):
|
||||
"""Initialize Gitea plugin with configuration."""
|
||||
super().__init__(config)
|
||||
|
||||
# Store repo info for API endpoints
|
||||
self.repo_owner = config.get('repo_owner', 'coulomb')
|
||||
self.repo_name = config.get('repo_name', 'markitect_project')
|
||||
self.repo_full_name = f"{self.repo_owner}/{self.repo_name}"
|
||||
|
||||
# Create connection manager with configuration
|
||||
datasource_config = DataSourceConfig(
|
||||
gitea_base_url=config.get('url', 'http://92.205.130.254:32166'),
|
||||
gitea_token=config.get('token', ''),
|
||||
database_path=config.get('database_path', 'markitect.db')
|
||||
)
|
||||
connection_manager = ConnectionManager(datasource_config)
|
||||
|
||||
# Create repository with repo info
|
||||
self.repository = GiteaIssueRepository(connection_manager)
|
||||
self.repository.set_repo_info(self.repo_owner, self.repo_name)
|
||||
|
||||
def list_issues(self, state: Optional[str] = None) -> List[Issue]:
|
||||
"""List issues from Gitea."""
|
||||
return asyncio.run(self._list_issues_async(state))
|
||||
|
||||
async def _list_issues_async(self, state: Optional[str] = None) -> List[Issue]:
|
||||
"""Async implementation of list_issues."""
|
||||
if state == 'all' or state is None:
|
||||
state = None # Repository expects None for all issues
|
||||
return await self.repository.get_issues(state=state)
|
||||
|
||||
def get_issue(self, issue_id: str) -> Issue:
|
||||
"""Get specific issue from Gitea."""
|
||||
return asyncio.run(self._get_issue_async(issue_id))
|
||||
|
||||
async def _get_issue_async(self, issue_id: str) -> Issue:
|
||||
"""Async implementation of get_issue."""
|
||||
issue_number = int(issue_id)
|
||||
return await self.repository.get_issue(issue_number)
|
||||
|
||||
def create_issue(self, title: str, body: str, **kwargs) -> Issue:
|
||||
"""Create new issue in Gitea."""
|
||||
return asyncio.run(self._create_issue_async(title, body, **kwargs))
|
||||
|
||||
async def _create_issue_async(self, title: str, body: str, **kwargs) -> Issue:
|
||||
"""Async implementation of create_issue."""
|
||||
return await self.repository.create_issue(title=title, body=body, **kwargs)
|
||||
|
||||
def add_comment(self, issue_id: str, comment: str) -> Dict[str, Any]:
|
||||
"""Add comment to Gitea issue."""
|
||||
return asyncio.run(self._add_comment_async(issue_id, comment))
|
||||
|
||||
async def _add_comment_async(self, issue_id: str, comment: str) -> Dict[str, Any]:
|
||||
"""Async implementation of add_comment."""
|
||||
if not comment.strip():
|
||||
raise ValueError("Comment cannot be empty")
|
||||
if not issue_id.strip():
|
||||
raise ValueError("Issue ID cannot be empty")
|
||||
|
||||
# For now, return mock comment data
|
||||
# This will be implemented when comment support is added to repository
|
||||
return {
|
||||
'id': 'comment_123',
|
||||
'body': comment,
|
||||
'issue_id': issue_id
|
||||
}
|
||||
|
||||
def close_issue(self, issue_id: str) -> Issue:
|
||||
"""Close issue in Gitea."""
|
||||
return asyncio.run(self._close_issue_async(issue_id))
|
||||
|
||||
async def _close_issue_async(self, issue_id: str) -> Issue:
|
||||
"""Async implementation of close_issue."""
|
||||
issue_number = int(issue_id)
|
||||
return await self.repository.update_issue(issue_number, state='closed')
|
||||
|
||||
def update_issue(self, issue_id: str, **kwargs) -> Issue:
|
||||
"""Update issue in Gitea."""
|
||||
return asyncio.run(self._update_issue_async(issue_id, **kwargs))
|
||||
|
||||
async def _update_issue_async(self, issue_id: str, **kwargs) -> Issue:
|
||||
"""Async implementation of update_issue."""
|
||||
issue_number = int(issue_id)
|
||||
return await self.repository.update_issue(issue_number, **kwargs)
|
||||
@@ -1,300 +0,0 @@
|
||||
"""
|
||||
Local file backend plugin for issue management.
|
||||
|
||||
This plugin provides offline issue management using markdown files with YAML frontmatter.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import yaml
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Dict, Any
|
||||
|
||||
from ..base import IssueBackend
|
||||
from domain.issues.models import Issue, IssueState, Label
|
||||
|
||||
|
||||
class LocalPlugin(IssueBackend):
|
||||
"""Local file-based backend plugin."""
|
||||
|
||||
def __init__(self, config: Dict[str, Any]):
|
||||
"""Initialize local plugin with configuration."""
|
||||
super().__init__(config)
|
||||
|
||||
self.issues_dir = Path(config.get('directory', '.markitect/issues'))
|
||||
self.auto_git = config.get('auto_git', True)
|
||||
|
||||
self._setup_directory_structure()
|
||||
self._load_local_config()
|
||||
|
||||
def _setup_directory_structure(self):
|
||||
"""Create necessary directory structure."""
|
||||
self.issues_dir.mkdir(parents=True, exist_ok=True)
|
||||
(self.issues_dir / 'open').mkdir(exist_ok=True)
|
||||
(self.issues_dir / 'closed').mkdir(exist_ok=True)
|
||||
|
||||
def _load_local_config(self):
|
||||
"""Load or create local configuration."""
|
||||
config_file = self.issues_dir / 'config.yml'
|
||||
|
||||
if config_file.exists():
|
||||
with open(config_file, 'r') as f:
|
||||
self.local_config = yaml.safe_load(f) or {}
|
||||
else:
|
||||
self.local_config = {'next_issue_number': self.config.get('numbering_start', 1)}
|
||||
self._save_local_config()
|
||||
|
||||
def _save_local_config(self):
|
||||
"""Save local configuration."""
|
||||
config_file = self.issues_dir / 'config.yml'
|
||||
with open(config_file, 'w') as f:
|
||||
yaml.dump(self.local_config, f, default_flow_style=False)
|
||||
|
||||
def list_issues(self, state: Optional[str] = None) -> List[Issue]:
|
||||
"""List issues from local files."""
|
||||
issues = []
|
||||
|
||||
if state == 'open' or state is None or state == 'all':
|
||||
issues.extend(self._read_issues_from_directory(self.issues_dir / 'open'))
|
||||
|
||||
if state == 'closed' or state is None or state == 'all':
|
||||
issues.extend(self._read_issues_from_directory(self.issues_dir / 'closed'))
|
||||
|
||||
# Sort by issue number
|
||||
issues.sort(key=lambda x: x.number)
|
||||
return issues
|
||||
|
||||
def _read_issues_from_directory(self, directory: Path) -> List[Issue]:
|
||||
"""Read all issues from a directory."""
|
||||
issues = []
|
||||
|
||||
if not directory.exists():
|
||||
return issues
|
||||
|
||||
for file_path in directory.glob('*.md'):
|
||||
try:
|
||||
issue = self._read_issue_file(file_path)
|
||||
issues.append(issue)
|
||||
except Exception:
|
||||
# Skip malformed files
|
||||
continue
|
||||
|
||||
return issues
|
||||
|
||||
def _read_issue_file(self, file_path: Path) -> Issue:
|
||||
"""Read issue from markdown file with YAML frontmatter."""
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# Split frontmatter and body
|
||||
if content.startswith('---\n'):
|
||||
try:
|
||||
parts = content.split('---\n', 2)
|
||||
if len(parts) >= 3:
|
||||
frontmatter = yaml.safe_load(parts[1])
|
||||
body = parts[2].strip()
|
||||
else:
|
||||
frontmatter = {}
|
||||
body = content
|
||||
except yaml.YAMLError:
|
||||
raise yaml.YAMLError(f"Invalid YAML in {file_path}")
|
||||
else:
|
||||
frontmatter = {}
|
||||
body = content
|
||||
|
||||
# Convert string labels to Label objects
|
||||
label_objects = []
|
||||
for label in frontmatter.get('labels', []):
|
||||
if isinstance(label, str):
|
||||
label_objects.append(Label(name=label))
|
||||
else:
|
||||
label_objects.append(label)
|
||||
|
||||
# Map state string to IssueState enum
|
||||
state_str = frontmatter.get('state', 'open')
|
||||
issue_state = IssueState.OPEN if state_str == 'open' else IssueState.CLOSED
|
||||
|
||||
# Create Issue object
|
||||
issue = Issue(
|
||||
number=frontmatter.get('number', 0),
|
||||
title=frontmatter.get('title', ''),
|
||||
state=issue_state,
|
||||
labels=label_objects,
|
||||
created_at=datetime.fromisoformat(frontmatter.get('created_at', datetime.now().isoformat())),
|
||||
updated_at=datetime.fromisoformat(frontmatter.get('updated_at', datetime.now().isoformat())),
|
||||
assignee=frontmatter.get('assignee'),
|
||||
milestone=frontmatter.get('milestone')
|
||||
)
|
||||
|
||||
# Store body separately since domain model doesn't have it
|
||||
issue._body = body
|
||||
|
||||
return issue
|
||||
|
||||
def get_issue(self, issue_id: str) -> Issue:
|
||||
"""Get specific issue by ID."""
|
||||
file_path = self._find_issue_file(issue_id)
|
||||
if not file_path:
|
||||
raise FileNotFoundError(f"Issue {issue_id} not found")
|
||||
|
||||
return self._read_issue_file(file_path)
|
||||
|
||||
def _find_issue_file(self, issue_id: str) -> Optional[Path]:
|
||||
"""Find issue file in open or closed directories."""
|
||||
# Convert issue_id to 3-digit format to match filename pattern
|
||||
issue_num = f"{int(issue_id):03d}"
|
||||
pattern = f"{issue_num}-*.md"
|
||||
|
||||
# Search in open directory
|
||||
for file_path in (self.issues_dir / 'open').glob(pattern):
|
||||
return file_path
|
||||
|
||||
# Search in closed directory
|
||||
for file_path in (self.issues_dir / 'closed').glob(pattern):
|
||||
return file_path
|
||||
|
||||
return None
|
||||
|
||||
def create_issue(self, title: str, body: str, **kwargs) -> Issue:
|
||||
"""Create new issue as local file."""
|
||||
issue_number = self.local_config.get('next_issue_number', 1)
|
||||
|
||||
# Convert string labels to Label objects
|
||||
label_objects = []
|
||||
for label in kwargs.get('labels', []):
|
||||
if isinstance(label, str):
|
||||
label_objects.append(Label(name=label))
|
||||
else:
|
||||
label_objects.append(label)
|
||||
|
||||
# Create Issue object
|
||||
issue = Issue(
|
||||
number=issue_number,
|
||||
title=title,
|
||||
state=IssueState.OPEN,
|
||||
labels=label_objects,
|
||||
created_at=datetime.now(),
|
||||
updated_at=datetime.now(),
|
||||
assignee=kwargs.get('assignee'),
|
||||
milestone=kwargs.get('milestone')
|
||||
)
|
||||
|
||||
# Store body separately since domain model doesn't have it
|
||||
issue._body = body # Temporary storage for body content
|
||||
|
||||
# Write to file
|
||||
self._write_issue_file(issue, self.issues_dir / 'open')
|
||||
|
||||
# Update counter
|
||||
self.local_config['next_issue_number'] = issue_number + 1
|
||||
self._save_local_config()
|
||||
|
||||
# Git integration
|
||||
if self.auto_git:
|
||||
self._git_add_and_commit(f"Create issue #{issue_number}: {title}")
|
||||
|
||||
return issue
|
||||
|
||||
def _write_issue_file(self, issue: Issue, directory: Path):
|
||||
"""Write issue to markdown file with YAML frontmatter."""
|
||||
filename = self._generate_filename(issue)
|
||||
file_path = directory / filename
|
||||
|
||||
# Convert Label objects to strings for YAML
|
||||
label_names = [label.name for label in issue.labels]
|
||||
|
||||
# Prepare frontmatter
|
||||
frontmatter = {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'state': issue.state.value,
|
||||
'created_at': issue.created_at.isoformat(),
|
||||
'updated_at': issue.updated_at.isoformat(),
|
||||
'labels': label_names,
|
||||
'assignee': issue.assignee,
|
||||
'milestone': issue.milestone
|
||||
}
|
||||
|
||||
# Write file
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
f.write('---\n')
|
||||
yaml.dump(frontmatter, f, default_flow_style=False)
|
||||
f.write('---\n\n')
|
||||
f.write(getattr(issue, '_body', ''))
|
||||
|
||||
def _generate_filename(self, issue: Issue) -> str:
|
||||
"""Generate safe filename from issue."""
|
||||
# Sanitize title for filename
|
||||
safe_title = re.sub(r'[^\w\s-]', '', issue.title.lower())
|
||||
safe_title = re.sub(r'[\s_-]+', '-', safe_title)
|
||||
safe_title = safe_title.strip('-')[:50] # Limit length
|
||||
|
||||
return f"{issue.number:03d}-{safe_title}.md"
|
||||
|
||||
def add_comment(self, issue_id: str, comment: str) -> Dict[str, Any]:
|
||||
"""Add comment to local issue file."""
|
||||
if not comment.strip():
|
||||
raise ValueError("Comment cannot be empty")
|
||||
if not issue_id.strip():
|
||||
raise ValueError("Issue ID cannot be empty")
|
||||
|
||||
# For now, return mock comment data
|
||||
# Full implementation would append to issue file
|
||||
return {
|
||||
'id': f"comment_{datetime.now().timestamp()}",
|
||||
'body': comment,
|
||||
'timestamp': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
def close_issue(self, issue_id: str) -> Issue:
|
||||
"""Close issue by moving to closed directory."""
|
||||
return self.update_issue(issue_id, state=IssueState.CLOSED)
|
||||
|
||||
def update_issue(self, issue_id: str, **kwargs) -> Issue:
|
||||
"""Update issue properties."""
|
||||
file_path = self._find_issue_file(issue_id)
|
||||
if not file_path:
|
||||
raise FileNotFoundError(f"Issue {issue_id} not found")
|
||||
|
||||
# Read current issue
|
||||
issue = self._read_issue_file(file_path)
|
||||
|
||||
# Update properties
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(issue, key):
|
||||
setattr(issue, key, value)
|
||||
|
||||
# Handle state change (move file if needed)
|
||||
old_state = 'open' if 'open' in str(file_path) else 'closed'
|
||||
new_state_obj = kwargs.get('state', issue.state)
|
||||
new_state = new_state_obj.value if hasattr(new_state_obj, 'value') else str(new_state_obj)
|
||||
|
||||
if new_state != old_state:
|
||||
# Remove old file
|
||||
file_path.unlink()
|
||||
|
||||
# Write to new directory
|
||||
new_directory = self.issues_dir / new_state
|
||||
self._write_issue_file(issue, new_directory)
|
||||
else:
|
||||
# Update existing file
|
||||
self._write_issue_file(issue, file_path.parent)
|
||||
|
||||
# Git integration
|
||||
if self.auto_git:
|
||||
self._git_add_and_commit(f"Update issue #{issue.number}")
|
||||
|
||||
return issue
|
||||
|
||||
def _git_add_and_commit(self, message: str):
|
||||
"""Add and commit changes to git."""
|
||||
try:
|
||||
subprocess.run(['git', 'add', str(self.issues_dir)],
|
||||
cwd='.', check=True, capture_output=True)
|
||||
subprocess.run(['git', 'commit', '-m', message],
|
||||
cwd='.', check=True, capture_output=True)
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
# Git not available or not a git repo, ignore
|
||||
pass
|
||||
@@ -1533,7 +1533,7 @@ def md_ingest_command(ctx, file_path):
|
||||
doc_manager = DocumentManager(config.get('db_manager'))
|
||||
|
||||
# Process the file
|
||||
result = doc_manager.ingest_file(file_path)
|
||||
result = doc_manager.ingest_file(Path(file_path))
|
||||
|
||||
if config.get('verbose', False):
|
||||
click.echo(f"Processing results:")
|
||||
@@ -2980,4 +2980,6 @@ class FilenameDecoder:
|
||||
|
||||
def decode_batch(self, filenames):
|
||||
"""Process multiple filenames in batch."""
|
||||
return [self.decode(filename) for filename in filenames]
|
||||
return [self.decode(filename) for filename in filenames]
|
||||
|
||||
|
||||
|
||||
0
markitect/plugins/tests/__init__.py
Normal file
0
markitect/plugins/tests/__init__.py
Normal file
0
markitect/query_paradigms/tests/__init__.py
Normal file
0
markitect/query_paradigms/tests/__init__.py
Normal file
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "markitect"
|
||||
version = "0.2.0"
|
||||
version = "0.4.0"
|
||||
description = "Advanced Markdown engine for structured content"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
"""
|
||||
Issue service - business logic for issue operations.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from tddai import IssueFetcher, TddaiError
|
||||
from tddai.issue_creator import IssueCreator
|
||||
from gitea.models import Issue, Priority
|
||||
|
||||
|
||||
class IssueService:
|
||||
"""Service for issue operations."""
|
||||
|
||||
def __init__(self):
|
||||
self.issue_fetcher = IssueFetcher()
|
||||
self.issue_creator = IssueCreator()
|
||||
|
||||
def get_issue(self, issue_number: int) -> Issue:
|
||||
"""Get a specific issue by number."""
|
||||
return self.issue_fetcher.fetch_issue(issue_number)
|
||||
|
||||
def list_issues(self, state: str = "all") -> List[Issue]:
|
||||
"""List issues with optional state filter."""
|
||||
return self.issue_fetcher.fetch_issues(state)
|
||||
|
||||
def list_open_issues(self) -> List[Issue]:
|
||||
"""List only open issues."""
|
||||
return self.issue_fetcher.fetch_open_issues()
|
||||
|
||||
def create_issue(self, title: str, body: str, **kwargs) -> Dict[str, Any]:
|
||||
"""Create a new issue."""
|
||||
return self.issue_creator.create_issue(title, body, **kwargs)
|
||||
|
||||
def create_enhancement_issue(self, title: str, use_case: str,
|
||||
technical_requirements: str = "",
|
||||
acceptance_criteria: Optional[List[str]] = None,
|
||||
dependencies: Optional[List[str]] = None,
|
||||
priority: str = "Medium") -> Dict[str, Any]:
|
||||
"""Create a structured enhancement issue."""
|
||||
return self.issue_creator.create_enhancement_issue(
|
||||
title, use_case, technical_requirements,
|
||||
acceptance_criteria, dependencies, priority
|
||||
)
|
||||
|
||||
def create_from_template(self, template_file: str, **kwargs) -> Dict[str, Any]:
|
||||
"""Create issue from template file."""
|
||||
return self.issue_creator.create_from_template(template_file, **kwargs)
|
||||
|
||||
def close_issue(self, issue_number: int, comment: str = "") -> Dict[str, Any]:
|
||||
"""Close an issue with optional comment."""
|
||||
from gitea import GiteaClient, GiteaConfig
|
||||
from tddai.config import get_config
|
||||
import os
|
||||
|
||||
# Get config and create Gitea client
|
||||
config = get_config()
|
||||
gitea_config = GiteaConfig.from_tddai_config(config)
|
||||
auth_token = os.getenv('GITEA_API_TOKEN')
|
||||
if auth_token:
|
||||
gitea_config.auth_token = auth_token
|
||||
|
||||
gitea_client = GiteaClient(gitea_config)
|
||||
|
||||
# Close the issue
|
||||
issue = gitea_client.issues.close(issue_number)
|
||||
|
||||
# If comment provided, add it (this would need API support for comments)
|
||||
# For now, we'll just close the issue
|
||||
|
||||
# Convert to dict format for consistency
|
||||
return gitea_client.issues.to_dict(issue)
|
||||
|
||||
def get_issue_details(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Get comprehensive issue details for display purposes."""
|
||||
issue = self.get_issue(issue_number)
|
||||
|
||||
# Get additional project management information
|
||||
from tddai.project_manager import ProjectManager
|
||||
project_mgr = ProjectManager()
|
||||
|
||||
# Get detailed issue data via API for milestone and project information
|
||||
from tddai.config import get_config
|
||||
config = get_config()
|
||||
issue_url = f"{config.issues_api_url}/{issue_number}"
|
||||
detailed_issue = project_mgr._make_api_call('GET', issue_url)
|
||||
|
||||
# Process labels
|
||||
labels = detailed_issue.get('labels', [])
|
||||
state_labels = [l['name'] for l in labels if l['name'].startswith('status:')]
|
||||
priority_labels = [l['name'] for l in labels if l['name'].startswith('priority:')]
|
||||
type_labels = [l['name'] for l in labels if l['name'].startswith('type:')]
|
||||
other_labels = [l['name'] for l in labels if not any(l['name'].startswith(p) for p in ['status:', 'priority:', 'type:'])]
|
||||
|
||||
# Determine project column/state
|
||||
if detailed_issue.get('state') == 'closed':
|
||||
if any(l['name'] == 'status:done' for l in labels):
|
||||
column = "Done"
|
||||
else:
|
||||
column = "Closed"
|
||||
else:
|
||||
state_labels = [l['name'] for l in labels if l['name'].startswith('status:')]
|
||||
if state_labels:
|
||||
state = state_labels[0].replace('status:', '')
|
||||
column_map = {
|
||||
'todo': 'Todo',
|
||||
'active': 'Active',
|
||||
'review': 'Review',
|
||||
'blocked': 'Blocked'
|
||||
}
|
||||
column = column_map.get(state, 'Todo')
|
||||
else:
|
||||
column = "Todo"
|
||||
|
||||
return {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': issue.body,
|
||||
'state': issue.state,
|
||||
'created_at': issue.created_at,
|
||||
'updated_at': issue.updated_at,
|
||||
'html_url': issue.html_url,
|
||||
'assignee': issue.assignee.login if issue.assignee else None,
|
||||
'milestone': detailed_issue.get('milestone'),
|
||||
'state_label': state_labels[0].replace('status:', '').title() if state_labels else "No state label",
|
||||
'priority_label': priority_labels[0].replace('priority:', '').title() if priority_labels else "No priority set",
|
||||
'type_labels': [l.replace('type:', '').title() for l in type_labels],
|
||||
'other_labels': other_labels,
|
||||
'kanban_column': column
|
||||
}
|
||||
|
||||
def get_issue_summary(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Get issue summary for display purposes."""
|
||||
issue = self.get_issue(issue_number)
|
||||
|
||||
return {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': issue.body,
|
||||
'state': issue.state,
|
||||
'priority': issue.priority,
|
||||
'status': issue.status,
|
||||
'created_at': issue.created_at,
|
||||
'updated_at': issue.updated_at,
|
||||
'html_url': issue.html_url,
|
||||
'assignee': issue.assignee.login if issue.assignee else None,
|
||||
'labels': [label.name for label in issue.labels],
|
||||
'has_milestone': issue.milestone is not None,
|
||||
'milestone_title': issue.milestone.title if issue.milestone else None
|
||||
}
|
||||
|
||||
def analyze_coverage(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Analyze test coverage for a specific issue.
|
||||
|
||||
Args:
|
||||
issue_number: The issue number to analyze
|
||||
|
||||
Returns:
|
||||
Coverage analysis data for the issue
|
||||
|
||||
Raises:
|
||||
IssueError: When coverage analysis fails
|
||||
"""
|
||||
from tddai.coverage_analyzer import CoverageAnalyzer
|
||||
|
||||
analyzer = CoverageAnalyzer()
|
||||
assessment = analyzer.analyze_issue_coverage(issue_number)
|
||||
|
||||
return {
|
||||
'issue_number': assessment.issue_number,
|
||||
'issue_title': assessment.issue_title,
|
||||
'coverage_percentage': assessment.coverage_percentage,
|
||||
'requirements': assessment.requirements,
|
||||
'existing_tests': assessment.existing_tests,
|
||||
'coverage_gaps': assessment.coverage_gaps,
|
||||
'recommendations': assessment.recommendations
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
"""
|
||||
Project service - business logic for project management operations.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
from tddai.project_manager import ProjectManager, ProjectState, Priority, Milestone, Label
|
||||
from tddai import TddaiError
|
||||
|
||||
|
||||
class ProjectService:
|
||||
"""Service for project management operations."""
|
||||
|
||||
def __init__(self):
|
||||
self.project_manager = ProjectManager()
|
||||
|
||||
def setup_project_management(self) -> None:
|
||||
"""Setup project management labels and structure."""
|
||||
self.project_manager.ensure_project_labels()
|
||||
|
||||
def create_milestone(self, title: str, description: str = "", due_date: Optional[str] = None) -> Milestone:
|
||||
"""Create a new milestone (project)."""
|
||||
return self.project_manager.create_milestone(title, description, due_date)
|
||||
|
||||
def list_milestones(self, state: str = "open") -> List[Milestone]:
|
||||
"""List milestones."""
|
||||
return self.project_manager.list_milestones(state)
|
||||
|
||||
def list_labels(self) -> List[Label]:
|
||||
"""List repository labels."""
|
||||
return self.project_manager.list_labels()
|
||||
|
||||
def set_issue_state(self, issue_number: int, state_name: str) -> Dict[str, Any]:
|
||||
"""Set issue project state."""
|
||||
# Convert string to ProjectState enum
|
||||
state_map = {
|
||||
'todo': ProjectState.TODO,
|
||||
'active': ProjectState.ACTIVE,
|
||||
'review': ProjectState.REVIEW,
|
||||
'done': ProjectState.DONE,
|
||||
'blocked': ProjectState.BLOCKED
|
||||
}
|
||||
|
||||
if state_name not in state_map:
|
||||
raise TddaiError(f"Invalid state '{state_name}'. Valid states: {list(state_map.keys())}")
|
||||
|
||||
project_state = state_map[state_name]
|
||||
return self.project_manager.set_issue_state(issue_number, project_state)
|
||||
|
||||
def set_issue_priority(self, issue_number: int, priority_name: str) -> Dict[str, Any]:
|
||||
"""Set issue priority."""
|
||||
# Convert string to Priority enum
|
||||
priority_map = {
|
||||
'low': Priority.LOW,
|
||||
'medium': Priority.MEDIUM,
|
||||
'high': Priority.HIGH,
|
||||
'critical': Priority.CRITICAL
|
||||
}
|
||||
|
||||
if priority_name not in priority_map:
|
||||
raise TddaiError(f"Invalid priority '{priority_name}'. Valid priorities: {list(priority_map.keys())}")
|
||||
|
||||
priority_level = priority_map[priority_name]
|
||||
return self.project_manager.set_issue_priority(issue_number, priority_level)
|
||||
|
||||
def move_issue_to_done(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Move issue to done state and close it."""
|
||||
return self.project_manager.move_issue_to_done(issue_number)
|
||||
|
||||
def assign_issue_to_milestone(self, issue_number: int, milestone_id: int) -> Dict[str, Any]:
|
||||
"""Assign issue to a milestone."""
|
||||
return self.project_manager.assign_issue_to_milestone(issue_number, milestone_id)
|
||||
|
||||
def get_project_overview(self) -> Dict[str, Any]:
|
||||
"""Get project management overview."""
|
||||
return self.project_manager.get_project_overview()
|
||||
@@ -1,116 +0,0 @@
|
||||
"""
|
||||
Workspace service - business logic for TDD workspace operations.
|
||||
"""
|
||||
|
||||
from typing import Optional, Dict, Any
|
||||
from pathlib import Path
|
||||
|
||||
from tddai import WorkspaceManager, IssueFetcher, WorkspaceStatus, TddaiError
|
||||
|
||||
|
||||
class WorkspaceInfo:
|
||||
"""Value object for workspace information."""
|
||||
|
||||
def __init__(self, status: WorkspaceStatus, workspace=None):
|
||||
self.status = status
|
||||
self.workspace = workspace
|
||||
|
||||
@property
|
||||
def is_clean(self) -> bool:
|
||||
return self.status == WorkspaceStatus.CLEAN
|
||||
|
||||
@property
|
||||
def is_dirty(self) -> bool:
|
||||
return self.status == WorkspaceStatus.DIRTY
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
return self.status == WorkspaceStatus.ACTIVE
|
||||
|
||||
def get_test_files(self) -> list:
|
||||
"""Get list of test files in workspace."""
|
||||
if not self.workspace or not self.workspace.tests_dir.exists():
|
||||
return []
|
||||
return list(self.workspace.tests_dir.glob("*.py"))
|
||||
|
||||
|
||||
class WorkspaceService:
|
||||
"""Service for workspace operations."""
|
||||
|
||||
def __init__(self):
|
||||
self.workspace_manager = WorkspaceManager()
|
||||
self.issue_fetcher = IssueFetcher()
|
||||
|
||||
def get_workspace_info(self) -> WorkspaceInfo:
|
||||
"""Get current workspace information."""
|
||||
status = self.workspace_manager.get_status()
|
||||
workspace = None
|
||||
|
||||
if status == WorkspaceStatus.ACTIVE:
|
||||
workspace = self.workspace_manager.get_current_workspace()
|
||||
|
||||
return WorkspaceInfo(status, workspace)
|
||||
|
||||
def start_issue_workspace(self, issue_number: int) -> WorkspaceInfo:
|
||||
"""Start working on an issue.
|
||||
|
||||
Returns:
|
||||
WorkspaceInfo with the created workspace
|
||||
|
||||
Raises:
|
||||
TddaiError: If workspace already active or issue cannot be fetched
|
||||
"""
|
||||
# Check if workspace already active
|
||||
current_info = self.get_workspace_info()
|
||||
if current_info.is_active:
|
||||
raise TddaiError(f"Already working on issue #{current_info.workspace.issue_number}")
|
||||
|
||||
# Fetch issue data
|
||||
issue_data = self.issue_fetcher.get_issue_data_dict(issue_number)
|
||||
|
||||
# Create workspace
|
||||
workspace = self.workspace_manager.create_workspace(issue_data)
|
||||
return WorkspaceInfo(WorkspaceStatus.ACTIVE, workspace)
|
||||
|
||||
def finish_current_workspace(self) -> Optional[int]:
|
||||
"""Finish current workspace and return the issue number.
|
||||
|
||||
Returns:
|
||||
Issue number that was finished, or None if no active workspace
|
||||
|
||||
Raises:
|
||||
TddaiError: If workspace operations fail
|
||||
"""
|
||||
current_info = self.get_workspace_info()
|
||||
if not current_info.is_active:
|
||||
return None
|
||||
|
||||
issue_number = current_info.workspace.issue_number
|
||||
self.workspace_manager.finish_workspace()
|
||||
return issue_number
|
||||
|
||||
def get_workspace_summary(self) -> Dict[str, Any]:
|
||||
"""Get workspace summary for display purposes."""
|
||||
info = self.get_workspace_info()
|
||||
|
||||
summary = {
|
||||
'status': info.status,
|
||||
'active': info.is_active,
|
||||
'clean': info.is_clean,
|
||||
'dirty': info.is_dirty
|
||||
}
|
||||
|
||||
if info.workspace:
|
||||
test_files = info.get_test_files()
|
||||
summary.update({
|
||||
'issue_number': info.workspace.issue_number,
|
||||
'issue_title': info.workspace.issue_title,
|
||||
'issue_state': info.workspace.issue_state,
|
||||
'workspace_dir': str(info.workspace.workspace_dir),
|
||||
'test_count': len(test_files),
|
||||
'test_files': [f.name for f in test_files],
|
||||
'requirements_file': str(info.workspace.requirements_file),
|
||||
'test_plan_file': str(info.workspace.test_plan_file)
|
||||
})
|
||||
|
||||
return summary
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash
|
||||
# TDDAi environment setup for MarkiTect project
|
||||
# Source this file to configure tddai for this specific project
|
||||
|
||||
export TDDAI_WORKSPACE_DIR=.markitect_workspace
|
||||
export TDDAI_GITEA_URL=http://92.205.130.254:32166
|
||||
export TDDAI_REPO_OWNER=coulomb
|
||||
export TDDAI_REPO_NAME=markitect_project
|
||||
|
||||
echo "✅ TDDAi configured for MarkiTect project"
|
||||
echo " Workspace: $TDDAI_WORKSPACE_DIR"
|
||||
echo " Repository: $TDDAI_REPO_OWNER/$TDDAI_REPO_NAME"
|
||||
echo " URL: $TDDAI_GITEA_URL"
|
||||
@@ -1,37 +0,0 @@
|
||||
"""
|
||||
tddai - Test-Driven Development with AI Support
|
||||
|
||||
A Python library for managing issue-driven TDD workflows with AI assistance.
|
||||
Provides workspace management, test generation, and issue integration.
|
||||
"""
|
||||
|
||||
from .workspace import WorkspaceManager, Workspace, WorkspaceStatus
|
||||
from .issue_fetcher import IssueFetcher, Issue
|
||||
from .issue_creator import IssueCreator
|
||||
from .project_manager import ProjectManager, ProjectState, Priority
|
||||
from .test_generator import TestGenerator
|
||||
from .coverage_analyzer import CoverageAnalyzer, CoverageAssessment, TestRequirement, CoverageGap
|
||||
from .exceptions import TddaiError, WorkspaceError, IssueError, ConfigurationError, TestGenerationError
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__all__ = [
|
||||
"WorkspaceManager",
|
||||
"Workspace",
|
||||
"WorkspaceStatus",
|
||||
"IssueFetcher",
|
||||
"Issue",
|
||||
"IssueCreator",
|
||||
"ProjectManager",
|
||||
"ProjectState",
|
||||
"Priority",
|
||||
"TestGenerator",
|
||||
"CoverageAnalyzer",
|
||||
"CoverageAssessment",
|
||||
"TestRequirement",
|
||||
"CoverageGap",
|
||||
"TddaiError",
|
||||
"WorkspaceError",
|
||||
"IssueError",
|
||||
"ConfigurationError",
|
||||
"TestGenerationError",
|
||||
]
|
||||
171
tddai/config.py
171
tddai/config.py
@@ -1,171 +0,0 @@
|
||||
"""
|
||||
Configuration management for tddai.
|
||||
|
||||
DEPRECATED: This module is kept for backward compatibility only.
|
||||
New code should use the unified configuration system in the `config` module.
|
||||
|
||||
The tddai framework is project-agnostic and can be configured per project
|
||||
via environment variables:
|
||||
|
||||
- TDDAI_WORKSPACE_DIR: Workspace directory name (default: .tddai_workspace)
|
||||
- TDDAI_GITEA_URL: Git platform URL
|
||||
- TDDAI_REPO_OWNER: Repository owner/organization
|
||||
- TDDAI_REPO_NAME: Repository name
|
||||
|
||||
Example .env file for a project:
|
||||
```
|
||||
TDDAI_WORKSPACE_DIR=.myproject_workspace
|
||||
TDDAI_GITEA_URL=https://github.com
|
||||
TDDAI_REPO_OWNER=myusername
|
||||
TDDAI_REPO_NAME=myproject
|
||||
```
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .exceptions import ConfigurationError
|
||||
|
||||
# Import unified configuration system
|
||||
try:
|
||||
from config import get_tddai_config as _get_unified_tddai_config
|
||||
_UNIFIED_CONFIG_AVAILABLE = True
|
||||
except ImportError:
|
||||
_UNIFIED_CONFIG_AVAILABLE = False
|
||||
|
||||
|
||||
def load_dotenv_file(env_file: Path) -> None:
|
||||
"""Load environment variables from a .env file.
|
||||
|
||||
DEPRECATED: Use config.loaders.load_env_file() instead.
|
||||
"""
|
||||
if not env_file.exists():
|
||||
return
|
||||
|
||||
with open(env_file, 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#') and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
os.environ.setdefault(key.strip(), value.strip())
|
||||
|
||||
|
||||
@dataclass
|
||||
class TddaiConfig:
|
||||
"""Configuration settings for tddai.
|
||||
|
||||
DEPRECATED: Use config.TddaiConfigCompat instead.
|
||||
"""
|
||||
|
||||
# Workspace settings
|
||||
workspace_dir: Path = Path(".tddai_workspace")
|
||||
current_issue_file: str = "current_issue.json"
|
||||
|
||||
# Git repository settings (must be configured per project)
|
||||
gitea_url: str = ""
|
||||
repo_owner: str = ""
|
||||
repo_name: str = ""
|
||||
|
||||
# Test settings
|
||||
tests_dir: Path = Path("tests")
|
||||
test_file_pattern: str = "test_issue_{issue_num}_{scenario}.py"
|
||||
|
||||
# AI settings
|
||||
claude_code_command: str = "claude"
|
||||
|
||||
@property
|
||||
def issues_api_url(self) -> str:
|
||||
"""Get the full issues API URL."""
|
||||
return f"{self.gitea_url}/api/v1/repos/{self.repo_owner}/{self.repo_name}/issues"
|
||||
|
||||
@property
|
||||
def current_issue_path(self) -> Path:
|
||||
"""Get the path to current issue file."""
|
||||
return self.workspace_dir / self.current_issue_file
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> "TddaiConfig":
|
||||
"""Create config from environment variables and .env files."""
|
||||
# Auto-load .env.tddai file if it exists
|
||||
env_file = Path(".env.tddai")
|
||||
load_dotenv_file(env_file)
|
||||
|
||||
config = cls()
|
||||
|
||||
# Override with environment variables if present
|
||||
gitea_url = os.getenv("TDDAI_GITEA_URL")
|
||||
if gitea_url:
|
||||
config.gitea_url = gitea_url
|
||||
|
||||
repo_owner = os.getenv("TDDAI_REPO_OWNER")
|
||||
if repo_owner:
|
||||
config.repo_owner = repo_owner
|
||||
|
||||
repo_name = os.getenv("TDDAI_REPO_NAME")
|
||||
if repo_name:
|
||||
config.repo_name = repo_name
|
||||
|
||||
workspace_dir = os.getenv("TDDAI_WORKSPACE_DIR")
|
||||
if workspace_dir:
|
||||
config.workspace_dir = Path(workspace_dir)
|
||||
|
||||
return config
|
||||
|
||||
def validate(self) -> None:
|
||||
"""Validate configuration settings."""
|
||||
if not self.gitea_url:
|
||||
raise ConfigurationError("gitea_url cannot be empty")
|
||||
|
||||
if not self.repo_owner:
|
||||
raise ConfigurationError("repo_owner cannot be empty")
|
||||
|
||||
if not self.repo_name:
|
||||
raise ConfigurationError("repo_name cannot be empty")
|
||||
|
||||
|
||||
# Global config instance
|
||||
_config: Optional[TddaiConfig] = None
|
||||
|
||||
|
||||
def get_config() -> TddaiConfig:
|
||||
"""Get the global configuration instance.
|
||||
|
||||
DEPRECATED: Use config.get_tddai_config() instead for new code.
|
||||
This function maintains backward compatibility.
|
||||
"""
|
||||
global _config
|
||||
if _config is None:
|
||||
if _UNIFIED_CONFIG_AVAILABLE:
|
||||
# Use unified configuration system if available
|
||||
try:
|
||||
unified_config = _get_unified_tddai_config()
|
||||
_config = TddaiConfig(
|
||||
workspace_dir=unified_config.workspace_dir,
|
||||
gitea_url=unified_config.gitea_url,
|
||||
repo_owner=unified_config.repo_owner,
|
||||
repo_name=unified_config.repo_name,
|
||||
tests_dir=unified_config.tests_dir,
|
||||
test_file_pattern=unified_config.test_file_pattern,
|
||||
claude_code_command=unified_config.claude_code_command
|
||||
)
|
||||
return _config
|
||||
except Exception:
|
||||
# Fall back to legacy behavior if unified config fails
|
||||
pass
|
||||
|
||||
# Legacy fallback
|
||||
_config = TddaiConfig.from_environment()
|
||||
_config.validate()
|
||||
return _config
|
||||
|
||||
|
||||
def set_config(config: TddaiConfig) -> None:
|
||||
"""Set the global configuration instance.
|
||||
|
||||
DEPRECATED: Use the unified configuration system instead.
|
||||
"""
|
||||
global _config
|
||||
config.validate()
|
||||
_config = config
|
||||
@@ -1,430 +0,0 @@
|
||||
"""
|
||||
Test coverage analyzer for issues.
|
||||
|
||||
This module analyzes issues and existing tests to identify gaps in functional test coverage.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Set, Tuple, Optional
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .issue_fetcher import IssueFetcher
|
||||
from .config import get_config
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestRequirement:
|
||||
"""Represents a test requirement extracted from an issue."""
|
||||
category: str
|
||||
description: str
|
||||
priority: str # "critical", "important", "nice-to-have"
|
||||
keywords: List[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExistingTest:
|
||||
"""Represents an existing test file and its coverage."""
|
||||
file_path: Path
|
||||
test_methods: List[str]
|
||||
coverage_keywords: Set[str]
|
||||
related_issue: Optional[int] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoverageGap:
|
||||
"""Represents a gap in test coverage."""
|
||||
requirement: TestRequirement
|
||||
suggested_test_name: str
|
||||
suggested_test_file: str
|
||||
example_test: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoverageAssessment:
|
||||
"""Complete coverage assessment for an issue."""
|
||||
issue_number: int
|
||||
issue_title: str
|
||||
requirements: List[TestRequirement]
|
||||
existing_tests: List[ExistingTest]
|
||||
coverage_gaps: List[CoverageGap]
|
||||
coverage_percentage: float
|
||||
recommendations: List[str]
|
||||
|
||||
|
||||
class CoverageAnalyzer:
|
||||
"""Analyzes test coverage for issues."""
|
||||
|
||||
def __init__(self, config=None):
|
||||
self.config = config or get_config()
|
||||
self.issue_fetcher = IssueFetcher(self.config)
|
||||
|
||||
def analyze_issue_coverage(self, issue_number: int) -> CoverageAssessment:
|
||||
"""Analyze test coverage for a specific issue."""
|
||||
# Fetch issue details
|
||||
issue_data = self.issue_fetcher.fetch_issue(issue_number)
|
||||
|
||||
# Extract test requirements from issue
|
||||
requirements = self._extract_requirements(issue_data)
|
||||
|
||||
# Find existing tests
|
||||
existing_tests = self._find_existing_tests(issue_number)
|
||||
|
||||
# Identify coverage gaps
|
||||
coverage_gaps = self._identify_gaps(requirements, existing_tests)
|
||||
|
||||
# Calculate coverage percentage
|
||||
coverage_percentage = self._calculate_coverage(requirements, existing_tests)
|
||||
|
||||
# Generate recommendations
|
||||
recommendations = self._generate_recommendations(issue_data, coverage_gaps)
|
||||
|
||||
return CoverageAssessment(
|
||||
issue_number=issue_number,
|
||||
issue_title=issue_data.title if hasattr(issue_data, 'title') else issue_data.get('title', ''),
|
||||
requirements=requirements,
|
||||
existing_tests=existing_tests,
|
||||
coverage_gaps=coverage_gaps,
|
||||
coverage_percentage=coverage_percentage,
|
||||
recommendations=recommendations
|
||||
)
|
||||
|
||||
def _extract_requirements(self, issue_data) -> List[TestRequirement]:
|
||||
"""Extract test requirements from issue description."""
|
||||
requirements = []
|
||||
|
||||
# Handle both dict and Issue object
|
||||
if hasattr(issue_data, 'body'):
|
||||
description = issue_data.body + ' ' + issue_data.title
|
||||
else:
|
||||
description = issue_data.get('body', '') + ' ' + issue_data.get('title', '')
|
||||
|
||||
# Define requirement patterns with priorities
|
||||
requirement_patterns = [
|
||||
# Critical functionality patterns
|
||||
(r'user can\s+([^.]+)', 'critical', 'user_functionality'),
|
||||
(r'must\s+([^.]+)', 'critical', 'requirement'),
|
||||
(r'should\s+([^.]+)', 'important', 'requirement'),
|
||||
(r'example:\s*([^.]+)', 'important', 'example_scenario'),
|
||||
|
||||
# API/Interface patterns
|
||||
(r'(create|generate|parse|validate|convert|process)\s+([^.]+)', 'critical', 'core_function'),
|
||||
(r'(read|store|save|load|retrieve|fetch)\s+([^.]+)', 'critical', 'data_operation'),
|
||||
(r'(input|output|parameter|argument):\s*([^.]+)', 'important', 'io_validation'),
|
||||
(r'(returns?|outputs?)\s+([^.]+)', 'important', 'output_validation'),
|
||||
|
||||
# Data operations - common in simple issues
|
||||
(r'(file|database|storage|content)\s+([^.]+)', 'important', 'data_handling'),
|
||||
(r'(schema|json|markdown|ast)\s+([^.]+)', 'important', 'format_handling'),
|
||||
|
||||
# Error handling patterns
|
||||
(r'(error|exception|fail|invalid)\s+([^.]+)', 'important', 'error_handling'),
|
||||
(r'edge case:\s*([^.]+)', 'important', 'edge_case'),
|
||||
|
||||
# Performance/behavior patterns
|
||||
(r'(performance|speed|memory|optimization)\s+([^.]+)', 'nice-to-have', 'performance'),
|
||||
(r'(depth|level|nesting)\s+([^.]+)', 'important', 'structural'),
|
||||
]
|
||||
|
||||
# Extract requirements based on patterns
|
||||
for pattern, priority, category in requirement_patterns:
|
||||
matches = re.finditer(pattern, description, re.IGNORECASE)
|
||||
for match in matches:
|
||||
requirement_text = match.group(1) if match.groups() else match.group(0)
|
||||
keywords = self._extract_keywords(requirement_text)
|
||||
|
||||
requirements.append(TestRequirement(
|
||||
category=category,
|
||||
description=requirement_text.strip(),
|
||||
priority=priority,
|
||||
keywords=keywords
|
||||
))
|
||||
|
||||
# Add enhanced requirements if few found (especially for simple issues)
|
||||
if len(requirements) <= 2:
|
||||
title = issue_data.title if hasattr(issue_data, 'title') else issue_data.get('title', '')
|
||||
|
||||
# Extract more detailed requirements from title
|
||||
title_words = title.lower().split()
|
||||
|
||||
# Add basic functionality requirement
|
||||
requirements.append(TestRequirement(
|
||||
category='basic_functionality',
|
||||
description=f'Basic functionality: {title}',
|
||||
priority='critical',
|
||||
keywords=self._extract_keywords(title)
|
||||
))
|
||||
|
||||
# Add specific requirements based on title analysis
|
||||
if any(word in title_words for word in ['read', 'load', 'fetch', 'get']):
|
||||
requirements.append(TestRequirement(
|
||||
category='input_validation',
|
||||
description='Input validation and file reading',
|
||||
priority='critical',
|
||||
keywords=['read', 'input', 'validation', 'file']
|
||||
))
|
||||
|
||||
if any(word in title_words for word in ['store', 'save', 'write', 'database']):
|
||||
requirements.append(TestRequirement(
|
||||
category='storage_operation',
|
||||
description='Data storage and persistence',
|
||||
priority='critical',
|
||||
keywords=['store', 'save', 'database', 'persistence']
|
||||
))
|
||||
|
||||
if any(word in title_words for word in ['schema', 'json', 'format']):
|
||||
requirements.append(TestRequirement(
|
||||
category='format_handling',
|
||||
description='Schema/format validation and processing',
|
||||
priority='important',
|
||||
keywords=['schema', 'json', 'format', 'validation']
|
||||
))
|
||||
|
||||
# Add error handling requirement for all functionality
|
||||
requirements.append(TestRequirement(
|
||||
category='error_handling',
|
||||
description='Error handling and edge cases',
|
||||
priority='important',
|
||||
keywords=['error', 'exception', 'validation', 'edge']
|
||||
))
|
||||
|
||||
return requirements
|
||||
|
||||
def _extract_keywords(self, text: str) -> List[str]:
|
||||
"""Extract relevant keywords from text."""
|
||||
# Common technical keywords
|
||||
keywords = []
|
||||
text_lower = text.lower()
|
||||
|
||||
# Extract nouns and verbs that are likely important
|
||||
important_patterns = [
|
||||
r'\b(schema|json|markdown|ast|parse|generate|create|validate|convert|transform)\b',
|
||||
r'\b(file|document|content|structure|element|heading|list|depth|level)\b',
|
||||
r'\b(input|output|parameter|argument|result|data|format)\b',
|
||||
r'\b(error|exception|validation|check|verify|ensure)\b'
|
||||
]
|
||||
|
||||
for pattern in important_patterns:
|
||||
matches = re.findall(pattern, text_lower)
|
||||
keywords.extend(matches)
|
||||
|
||||
return list(set(keywords)) # Remove duplicates
|
||||
|
||||
def _find_existing_tests(self, issue_number: int) -> List[ExistingTest]:
|
||||
"""Find existing tests related to the issue."""
|
||||
existing_tests = []
|
||||
tests_dir = Path('tests')
|
||||
|
||||
if not tests_dir.exists():
|
||||
return existing_tests
|
||||
|
||||
# Find tests that mention the issue number
|
||||
issue_patterns = [
|
||||
f'test_issue_{issue_number}',
|
||||
f'issue_{issue_number}',
|
||||
f'#{issue_number}',
|
||||
f'issue {issue_number}'
|
||||
]
|
||||
|
||||
for test_file in tests_dir.glob('test_*.py'):
|
||||
try:
|
||||
content = test_file.read_text()
|
||||
test_methods = self._extract_test_methods(content)
|
||||
coverage_keywords = self._extract_coverage_keywords(content)
|
||||
|
||||
# Check if this test file is related to the issue
|
||||
related_issue = None
|
||||
for pattern in issue_patterns:
|
||||
if pattern in content.lower():
|
||||
related_issue = issue_number
|
||||
break
|
||||
|
||||
existing_tests.append(ExistingTest(
|
||||
file_path=test_file,
|
||||
test_methods=test_methods,
|
||||
coverage_keywords=coverage_keywords,
|
||||
related_issue=related_issue
|
||||
))
|
||||
except (OSError, IOError, UnicodeDecodeError) as e:
|
||||
# Skip files that can't be read due to file system or encoding issues
|
||||
# Log the issue but continue processing other files
|
||||
from infrastructure.logging import get_logger
|
||||
logger = get_logger(__name__)
|
||||
logger.warning(
|
||||
f"Could not read test file {test_file}: {e}"
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
# Unexpected errors should be logged but not silently ignored
|
||||
from infrastructure.logging import get_logger
|
||||
logger = get_logger(__name__)
|
||||
logger.error(
|
||||
f"Unexpected error processing test file {test_file}: {e}",
|
||||
exc_info=True
|
||||
)
|
||||
continue
|
||||
|
||||
return existing_tests
|
||||
|
||||
def _extract_test_methods(self, content: str) -> List[str]:
|
||||
"""Extract test method names from test file content."""
|
||||
pattern = r'def\s+(test_[a-zA-Z_0-9]+)\s*\('
|
||||
return re.findall(pattern, content)
|
||||
|
||||
def _extract_coverage_keywords(self, content: str) -> Set[str]:
|
||||
"""Extract keywords that indicate what functionality is being tested."""
|
||||
keywords = set()
|
||||
content_lower = content.lower()
|
||||
|
||||
# Extract from test method names and docstrings
|
||||
test_patterns = [
|
||||
r'def\s+test_([a-zA-Z_0-9]+)',
|
||||
r'"""([^"]+)"""',
|
||||
r"'''([^']+)'''",
|
||||
r'#\s*([^\n]+)'
|
||||
]
|
||||
|
||||
for pattern in test_patterns:
|
||||
matches = re.findall(pattern, content_lower)
|
||||
for match in matches:
|
||||
keywords.update(self._extract_keywords(match))
|
||||
|
||||
return keywords
|
||||
|
||||
def _identify_gaps(self, requirements: List[TestRequirement],
|
||||
existing_tests: List[ExistingTest]) -> List[CoverageGap]:
|
||||
"""Identify gaps between requirements and existing tests."""
|
||||
gaps = []
|
||||
|
||||
# Get all covered keywords from existing tests
|
||||
covered_keywords = set()
|
||||
for test in existing_tests:
|
||||
covered_keywords.update(test.coverage_keywords)
|
||||
|
||||
for requirement in requirements:
|
||||
# Check if requirement is covered by existing tests
|
||||
requirement_keywords = set(requirement.keywords)
|
||||
|
||||
if requirement_keywords:
|
||||
coverage_overlap = requirement_keywords.intersection(covered_keywords)
|
||||
# If less than 50% of keywords are covered, consider it a gap
|
||||
coverage_ratio = len(coverage_overlap) / len(requirement_keywords)
|
||||
|
||||
if coverage_ratio < 0.5:
|
||||
gap = self._create_coverage_gap(requirement)
|
||||
gaps.append(gap)
|
||||
else:
|
||||
# If no keywords could be extracted, always consider it a gap
|
||||
# (This prevents false positives where we can't determine coverage)
|
||||
gap = self._create_coverage_gap(requirement)
|
||||
gaps.append(gap)
|
||||
|
||||
return gaps
|
||||
|
||||
def _create_coverage_gap(self, requirement: TestRequirement) -> CoverageGap:
|
||||
"""Create a coverage gap with suggestions."""
|
||||
# Generate suggested test name
|
||||
category_clean = requirement.category.replace('_', ' ').title().replace(' ', '')
|
||||
suggested_name = f"test_{requirement.category}"
|
||||
|
||||
# Generate suggested file name
|
||||
suggested_file = f"tests/test_{requirement.category}.py"
|
||||
|
||||
# Generate example test
|
||||
example_test = self._generate_example_test(requirement)
|
||||
|
||||
return CoverageGap(
|
||||
requirement=requirement,
|
||||
suggested_test_name=suggested_name,
|
||||
suggested_test_file=suggested_file,
|
||||
example_test=example_test
|
||||
)
|
||||
|
||||
def _generate_example_test(self, requirement: TestRequirement) -> str:
|
||||
"""Generate an example test for a requirement."""
|
||||
method_name = f"test_{requirement.category}"
|
||||
|
||||
return f'''def {method_name}(self):
|
||||
"""Test {requirement.description}."""
|
||||
# Arrange
|
||||
# TODO: Set up test data for {requirement.description}
|
||||
|
||||
# Act
|
||||
# TODO: Execute the functionality: {requirement.description}
|
||||
|
||||
# Assert
|
||||
# TODO: Verify the expected behavior
|
||||
assert True # Replace with actual assertions'''
|
||||
|
||||
def _calculate_coverage(self, requirements: List[TestRequirement],
|
||||
existing_tests: List[ExistingTest]) -> float:
|
||||
"""Calculate coverage percentage."""
|
||||
if not requirements:
|
||||
return 100.0
|
||||
|
||||
covered_requirements = 0
|
||||
total_requirements = len(requirements)
|
||||
|
||||
# Get all covered keywords
|
||||
covered_keywords = set()
|
||||
issue_related_tests = []
|
||||
for test in existing_tests:
|
||||
if test.related_issue: # Only count tests specifically for this issue
|
||||
covered_keywords.update(test.coverage_keywords)
|
||||
issue_related_tests.append(test)
|
||||
|
||||
# If no issue-specific tests found, coverage should be 0%
|
||||
if not issue_related_tests:
|
||||
return 0.0
|
||||
|
||||
# Check coverage for each requirement
|
||||
for requirement in requirements:
|
||||
requirement_keywords = set(requirement.keywords)
|
||||
|
||||
if requirement_keywords:
|
||||
# Need actual keyword overlap for coverage
|
||||
coverage_ratio = len(requirement_keywords.intersection(covered_keywords)) / len(requirement_keywords)
|
||||
if coverage_ratio >= 0.5: # Consider 50%+ keyword coverage as "covered"
|
||||
covered_requirements += 1
|
||||
else:
|
||||
# If no keywords extracted, this requirement is NOT covered
|
||||
# (This prevents false positives for untested functionality)
|
||||
pass
|
||||
|
||||
return (covered_requirements / total_requirements) * 100 if total_requirements > 0 else 0.0
|
||||
|
||||
def _generate_recommendations(self, issue_data: Dict, gaps: List[CoverageGap]) -> List[str]:
|
||||
"""Generate recommendations for improving test coverage."""
|
||||
recommendations = []
|
||||
|
||||
if not gaps:
|
||||
recommendations.append("✅ Good test coverage! All major requirements appear to be tested.")
|
||||
return recommendations
|
||||
|
||||
# Prioritize recommendations by requirement priority
|
||||
critical_gaps = [g for g in gaps if g.requirement.priority == 'critical']
|
||||
important_gaps = [g for g in gaps if g.requirement.priority == 'important']
|
||||
nice_gaps = [g for g in gaps if g.requirement.priority == 'nice-to-have']
|
||||
|
||||
if critical_gaps:
|
||||
recommendations.append(f"🚨 CRITICAL: {len(critical_gaps)} critical requirements lack test coverage")
|
||||
for gap in critical_gaps:
|
||||
recommendations.append(f" - Add test for: {gap.requirement.description}")
|
||||
|
||||
if important_gaps:
|
||||
recommendations.append(f"⚠️ IMPORTANT: {len(important_gaps)} important requirements need tests")
|
||||
for gap in important_gaps[:3]: # Show top 3
|
||||
recommendations.append(f" - Test needed: {gap.requirement.description}")
|
||||
|
||||
if nice_gaps:
|
||||
recommendations.append(f"💡 ENHANCEMENT: {len(nice_gaps)} additional tests would improve coverage")
|
||||
|
||||
# Add specific recommendations
|
||||
recommendations.append("📝 Recommended actions:")
|
||||
issue_num = issue_data.number if hasattr(issue_data, 'number') else issue_data.get('number', 'X')
|
||||
recommendations.append(f" 1. Use 'make tdd-start NUM={issue_num}' to create workspace")
|
||||
recommendations.append(" 2. Use 'make tdd-add-test' to generate missing tests")
|
||||
recommendations.append(" 3. Focus on critical requirements first")
|
||||
|
||||
return recommendations
|
||||
@@ -1,28 +0,0 @@
|
||||
"""
|
||||
Custom exceptions for tddai library.
|
||||
"""
|
||||
|
||||
|
||||
class TddaiError(Exception):
|
||||
"""Base exception for all tddai errors."""
|
||||
pass
|
||||
|
||||
|
||||
class WorkspaceError(TddaiError):
|
||||
"""Raised when workspace operations fail."""
|
||||
pass
|
||||
|
||||
|
||||
class IssueError(TddaiError):
|
||||
"""Raised when issue operations fail."""
|
||||
pass
|
||||
|
||||
|
||||
class ConfigurationError(TddaiError):
|
||||
"""Raised when configuration is invalid."""
|
||||
pass
|
||||
|
||||
|
||||
class TestGenerationError(TddaiError):
|
||||
"""Raised when test generation fails."""
|
||||
pass
|
||||
@@ -1,180 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
TDDAi Issue Closer
|
||||
|
||||
A dedicated module for closing issues in the selected issue tracking backend.
|
||||
Provides both programmatic API and CLI functionality for easy issue closure.
|
||||
|
||||
This module integrates with the existing tddai framework and provides:
|
||||
- Simple programmatic interface for closing issues
|
||||
- Command-line utility for manual issue closure
|
||||
- Integration with existing issue tracking backends
|
||||
- Proper error handling and user feedback
|
||||
"""
|
||||
|
||||
import sys
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Add project root to path for imports
|
||||
project_root = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from cli import CLIFramework
|
||||
from services import IssueService
|
||||
from tddai import TddaiError
|
||||
|
||||
|
||||
class IssueCloser:
|
||||
"""Dedicated class for closing issues with the configured backend."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the issue closer with CLI framework."""
|
||||
self.cli = CLIFramework()
|
||||
self.service = IssueService()
|
||||
|
||||
def close_issue(self, issue_number: int, comment: str = "") -> bool:
|
||||
"""
|
||||
Close an issue with optional comment.
|
||||
|
||||
Args:
|
||||
issue_number: The issue number to close
|
||||
comment: Optional closing comment
|
||||
|
||||
Returns:
|
||||
bool: True if issue was closed successfully, False otherwise
|
||||
"""
|
||||
try:
|
||||
self.cli.close_issue(issue_number, comment)
|
||||
return True
|
||||
except TddaiError as e:
|
||||
print(f"Error closing issue #{issue_number}: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"Unexpected error closing issue #{issue_number}: {e}")
|
||||
return False
|
||||
|
||||
def close_with_completion_message(self, issue_number: int, completed_work: str) -> bool:
|
||||
"""
|
||||
Close an issue with a standardized completion message.
|
||||
|
||||
Args:
|
||||
issue_number: The issue number to close
|
||||
completed_work: Description of what was completed
|
||||
|
||||
Returns:
|
||||
bool: True if issue was closed successfully, False otherwise
|
||||
"""
|
||||
completion_comment = f"✅ Completed: {completed_work}"
|
||||
return self.close_issue(issue_number, completion_comment)
|
||||
|
||||
def close_multiple_issues(self, issue_numbers: list, comment: str = "") -> dict:
|
||||
"""
|
||||
Close multiple issues with the same comment.
|
||||
|
||||
Args:
|
||||
issue_numbers: List of issue numbers to close
|
||||
comment: Comment to add to all issues
|
||||
|
||||
Returns:
|
||||
dict: Results with 'successful' and 'failed' lists
|
||||
"""
|
||||
results = {'successful': [], 'failed': []}
|
||||
|
||||
for issue_num in issue_numbers:
|
||||
if self.close_issue(issue_num, comment):
|
||||
results['successful'].append(issue_num)
|
||||
else:
|
||||
results['failed'].append(issue_num)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def main():
|
||||
"""Command-line interface for the issue closer."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="TDDAi Issue Closer - Close issues in the configured tracking backend",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
python3 issue_closer.py 42 # Close issue #42
|
||||
python3 issue_closer.py 42 -c "Fixed the bug" # Close with comment
|
||||
python3 issue_closer.py 42 -w "All tests passing" # Close with completion message
|
||||
python3 issue_closer.py 42 43 44 # Close multiple issues
|
||||
python3 issue_closer.py 42 43 -c "Batch closure" # Close multiple with comment
|
||||
|
||||
Integration with existing tddai CLI:
|
||||
python3 tddai_cli.py close-issue 42 --comment "Done" # Alternative method
|
||||
"""
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'issue_numbers',
|
||||
type=int,
|
||||
nargs='+',
|
||||
help='Issue number(s) to close'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-c', '--comment',
|
||||
type=str,
|
||||
default='',
|
||||
help='Optional closing comment'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-w', '--work-completed',
|
||||
type=str,
|
||||
help='Description of completed work (creates standardized completion message)'
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
'-v', '--verbose',
|
||||
action='store_true',
|
||||
help='Enable verbose output'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Initialize issue closer
|
||||
closer = IssueCloser()
|
||||
|
||||
# Determine which closing method to use
|
||||
if args.work_completed:
|
||||
comment = f"✅ Completed: {args.work_completed}"
|
||||
else:
|
||||
comment = args.comment
|
||||
|
||||
# Handle single or multiple issues
|
||||
if len(args.issue_numbers) == 1:
|
||||
issue_num = args.issue_numbers[0]
|
||||
if args.verbose:
|
||||
print(f"Closing issue #{issue_num}...")
|
||||
if comment:
|
||||
print(f"Comment: {comment}")
|
||||
|
||||
success = closer.close_issue(issue_num, comment)
|
||||
sys.exit(0 if success else 1)
|
||||
|
||||
else:
|
||||
# Multiple issues
|
||||
if args.verbose:
|
||||
print(f"Closing {len(args.issue_numbers)} issues...")
|
||||
if comment:
|
||||
print(f"Comment: {comment}")
|
||||
|
||||
results = closer.close_multiple_issues(args.issue_numbers, comment)
|
||||
|
||||
if results['successful']:
|
||||
print(f"✅ Successfully closed: {results['successful']}")
|
||||
|
||||
if results['failed']:
|
||||
print(f"❌ Failed to close: {results['failed']}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"✅ All {len(args.issue_numbers)} issues closed successfully!")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,211 +0,0 @@
|
||||
"""
|
||||
Issue creation using the Gitea facade.
|
||||
|
||||
This module now acts as an adapter to the new gitea package,
|
||||
maintaining backwards compatibility while using the cleaner API.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional, List
|
||||
|
||||
from gitea import GiteaClient, GiteaConfig, Priority
|
||||
from .config import get_config
|
||||
from .exceptions import IssueError
|
||||
|
||||
|
||||
class IssueCreator:
|
||||
"""Creates new issues using the Gitea facade."""
|
||||
|
||||
def __init__(self, config=None, auth_token=None):
|
||||
self.config = config or get_config()
|
||||
self.auth_token = auth_token or os.getenv('GITEA_API_TOKEN')
|
||||
|
||||
# Create Gitea client from tddai config
|
||||
gitea_config = GiteaConfig.from_tddai_config(self.config)
|
||||
if self.auth_token:
|
||||
gitea_config.auth_token = self.auth_token
|
||||
self.gitea_client = GiteaClient(gitea_config)
|
||||
|
||||
def create_issue(self, title: str, body: str, **kwargs) -> Dict[str, Any]:
|
||||
"""Create a new issue via POST operation.
|
||||
|
||||
Args:
|
||||
title: Issue title (required)
|
||||
body: Issue description/body (required)
|
||||
**kwargs: Optional fields (assignees, milestone, labels, etc.)
|
||||
|
||||
Returns:
|
||||
Dict containing created issue data including issue number
|
||||
|
||||
Raises:
|
||||
IssueError: If creation fails
|
||||
"""
|
||||
# Validate input
|
||||
if not title or not title.strip():
|
||||
raise IssueError("Issue title cannot be empty")
|
||||
|
||||
try:
|
||||
issue = self.gitea_client.issues.create(
|
||||
title=title,
|
||||
body=body,
|
||||
assignees=kwargs.get('assignees', []),
|
||||
milestone=kwargs.get('milestone'),
|
||||
labels=kwargs.get('labels', [])
|
||||
)
|
||||
|
||||
# Convert back to dict format for backwards compatibility
|
||||
return {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': issue.body,
|
||||
'state': issue.state,
|
||||
'html_url': issue.html_url,
|
||||
'created_at': issue.created_at.isoformat(),
|
||||
'updated_at': issue.updated_at.isoformat(),
|
||||
'assignee': {'login': issue.assignee.login} if issue.assignee else None,
|
||||
'labels': [{'name': label.name} for label in issue.labels]
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to create issue: {e}")
|
||||
|
||||
def create_enhancement_issue(self, title: str, use_case: str,
|
||||
technical_requirements: str = "",
|
||||
acceptance_criteria: Optional[List[str]] = None,
|
||||
dependencies: Optional[List[str]] = None,
|
||||
priority: str = "Medium") -> Dict[str, Any]:
|
||||
"""Create an enhancement issue with structured format.
|
||||
|
||||
Args:
|
||||
title: Issue title
|
||||
use_case: UseCase description
|
||||
technical_requirements: Technical implementation details
|
||||
acceptance_criteria: List of acceptance criteria
|
||||
dependencies: List of dependency descriptions
|
||||
priority: Priority level (High, Medium, Low)
|
||||
|
||||
Returns:
|
||||
Dict containing created issue data
|
||||
"""
|
||||
# Build structured body
|
||||
body_parts = [f"UseCase: {use_case}"]
|
||||
|
||||
if technical_requirements:
|
||||
body_parts.extend([
|
||||
"",
|
||||
"Technical Requirements:",
|
||||
technical_requirements
|
||||
])
|
||||
|
||||
if acceptance_criteria:
|
||||
body_parts.extend([
|
||||
"",
|
||||
"Acceptance Criteria:"
|
||||
])
|
||||
for criterion in acceptance_criteria:
|
||||
body_parts.append(f"- [ ] {criterion}")
|
||||
|
||||
if dependencies:
|
||||
body_parts.extend([
|
||||
"",
|
||||
"Dependencies:"
|
||||
])
|
||||
for dep in dependencies:
|
||||
body_parts.append(f"- {dep}")
|
||||
|
||||
body = "\n".join(body_parts)
|
||||
|
||||
# Create with enhancement label
|
||||
return self.create_issue(
|
||||
title=title,
|
||||
body=body,
|
||||
labels=[priority.lower(), "enhancement"]
|
||||
)
|
||||
|
||||
def create_bug_issue(self, title: str, description: str,
|
||||
steps_to_reproduce: Optional[List[str]] = None,
|
||||
expected_behavior: str = "",
|
||||
actual_behavior: str = "",
|
||||
environment: str = "") -> Dict[str, Any]:
|
||||
"""Create a bug issue with structured format.
|
||||
|
||||
Args:
|
||||
title: Bug title
|
||||
description: Bug description
|
||||
steps_to_reproduce: List of reproduction steps
|
||||
expected_behavior: What should happen
|
||||
actual_behavior: What actually happens
|
||||
environment: Environment details
|
||||
|
||||
Returns:
|
||||
Dict containing created issue data
|
||||
"""
|
||||
body_parts = [description]
|
||||
|
||||
if steps_to_reproduce:
|
||||
body_parts.extend([
|
||||
"",
|
||||
"Steps to Reproduce:"
|
||||
])
|
||||
for i, step in enumerate(steps_to_reproduce, 1):
|
||||
body_parts.append(f"{i}. {step}")
|
||||
|
||||
if expected_behavior:
|
||||
body_parts.extend([
|
||||
"",
|
||||
f"Expected Behavior: {expected_behavior}"
|
||||
])
|
||||
|
||||
if actual_behavior:
|
||||
body_parts.extend([
|
||||
"",
|
||||
f"Actual Behavior: {actual_behavior}"
|
||||
])
|
||||
|
||||
if environment:
|
||||
body_parts.extend([
|
||||
"",
|
||||
f"Environment: {environment}"
|
||||
])
|
||||
|
||||
body = "\n".join(body_parts)
|
||||
|
||||
# Create with bug label
|
||||
return self.create_issue(
|
||||
title=title,
|
||||
body=body,
|
||||
labels=["bug"]
|
||||
)
|
||||
|
||||
def create_from_template(self, template_file: str, **template_vars) -> Dict[str, Any]:
|
||||
"""Create issue from a template file.
|
||||
|
||||
Args:
|
||||
template_file: Path to template file
|
||||
**template_vars: Variables to substitute in template
|
||||
|
||||
Returns:
|
||||
Dict containing created issue data
|
||||
"""
|
||||
try:
|
||||
with open(template_file, 'r') as f:
|
||||
template_content = f.read()
|
||||
|
||||
# Simple template variable substitution
|
||||
for key, value in template_vars.items():
|
||||
template_content = template_content.replace(f"{{{key}}}", str(value))
|
||||
|
||||
# Extract title (first line) and body (rest)
|
||||
lines = template_content.strip().split('\n')
|
||||
if not lines or (len(lines) == 1 and not lines[0].strip()):
|
||||
raise IssueError("Template file is empty")
|
||||
|
||||
title = lines[0].replace('Title: ', '').strip()
|
||||
body = '\n'.join(lines[1:]).strip()
|
||||
|
||||
return self.create_issue(title=title, body=body)
|
||||
|
||||
except FileNotFoundError:
|
||||
raise IssueError(f"Template file not found: {template_file}")
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to process template: {e}")
|
||||
@@ -1,92 +0,0 @@
|
||||
"""
|
||||
Issue fetching using the Gitea facade.
|
||||
|
||||
This module now acts as an adapter to the new gitea package,
|
||||
maintaining backwards compatibility while using the cleaner API.
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
|
||||
from gitea import GiteaClient, Issue as GiteaIssue, GiteaConfig
|
||||
from gitea.exceptions import GiteaError, GiteaNotFoundError, GiteaAuthError, GiteaApiError
|
||||
from .config import get_config
|
||||
from .exceptions import IssueError
|
||||
|
||||
# Re-export Issue for backwards compatibility
|
||||
Issue = GiteaIssue
|
||||
|
||||
|
||||
class IssueFetcher:
|
||||
"""Fetches issues using the Gitea facade."""
|
||||
|
||||
def __init__(self, config=None):
|
||||
self.config = config or get_config()
|
||||
|
||||
# Create Gitea client from tddai config
|
||||
gitea_config = GiteaConfig.from_tddai_config(self.config)
|
||||
self.gitea_client = GiteaClient(gitea_config)
|
||||
|
||||
def fetch_issue(self, issue_number: int) -> Issue:
|
||||
"""Fetch a specific issue by number.
|
||||
|
||||
Raises:
|
||||
IssueError: When issue cannot be fetched (with specific context)
|
||||
"""
|
||||
try:
|
||||
return self.gitea_client.issues.get(issue_number)
|
||||
except GiteaNotFoundError as e:
|
||||
raise IssueError(f"Issue #{issue_number} not found") from e
|
||||
except GiteaAuthError as e:
|
||||
raise IssueError(f"Authentication failed when fetching issue #{issue_number}") from e
|
||||
except GiteaApiError as e:
|
||||
raise IssueError(f"API error fetching issue #{issue_number}: {e}") from e
|
||||
except GiteaError as e:
|
||||
raise IssueError(f"Gitea error fetching issue #{issue_number}: {e}") from e
|
||||
|
||||
def fetch_issues(self, state: str = "all") -> List[Issue]:
|
||||
"""Fetch all issues with optional state filter.
|
||||
|
||||
Args:
|
||||
state: Issue state filter ("all", "open", "closed")
|
||||
|
||||
Raises:
|
||||
IssueError: When issues cannot be fetched (with specific context)
|
||||
"""
|
||||
try:
|
||||
return self.gitea_client.issues.list(state=state)
|
||||
except GiteaAuthError as e:
|
||||
raise IssueError("Authentication failed when fetching issues") from e
|
||||
except GiteaApiError as e:
|
||||
raise IssueError(f"API error fetching issues with state '{state}': {e}") from e
|
||||
except GiteaError as e:
|
||||
raise IssueError(f"Gitea error fetching issues: {e}") from e
|
||||
|
||||
def fetch_open_issues(self) -> List[Issue]:
|
||||
"""Fetch only open issues.
|
||||
|
||||
Raises:
|
||||
IssueError: When open issues cannot be fetched (with specific context)
|
||||
"""
|
||||
try:
|
||||
return self.gitea_client.issues.list_open()
|
||||
except GiteaAuthError as e:
|
||||
raise IssueError("Authentication failed when fetching open issues") from e
|
||||
except GiteaApiError as e:
|
||||
raise IssueError(f"API error fetching open issues: {e}") from e
|
||||
except GiteaError as e:
|
||||
raise IssueError(f"Gitea error fetching open issues: {e}") from e
|
||||
|
||||
def get_issue_data_dict(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Get issue data as dictionary for workspace creation."""
|
||||
issue = self.fetch_issue(issue_number)
|
||||
return {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': issue.body,
|
||||
'state': issue.state,
|
||||
'created_at': issue.created_at.isoformat(),
|
||||
'updated_at': issue.updated_at.isoformat(),
|
||||
'html_url': issue.html_url,
|
||||
'assignee': {'login': issue.assignee.login} if issue.assignee else None,
|
||||
'labels': [{'name': label.name} for label in issue.labels]
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
"""
|
||||
Issue writing using the Gitea integration facade.
|
||||
|
||||
This module now acts as an adapter to the new gitea package,
|
||||
maintaining backwards compatibility while using the cleaner API.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from gitea import GiteaClient, GiteaConfig
|
||||
from .config import get_config
|
||||
from .exceptions import IssueError
|
||||
|
||||
|
||||
class IssueWriter:
|
||||
"""Writes issue updates using the Gitea integration facade."""
|
||||
|
||||
def __init__(self, config=None, auth_token=None):
|
||||
self.config = config or get_config()
|
||||
self.auth_token = auth_token or os.getenv('GITEA_API_TOKEN')
|
||||
|
||||
# Create Gitea client from tddai config
|
||||
gitea_config = GiteaConfig.from_tddai_config(self.config)
|
||||
if self.auth_token:
|
||||
gitea_config.auth_token = self.auth_token
|
||||
self.gitea_client = GiteaClient(gitea_config)
|
||||
|
||||
def update_issue(self, issue_number: int, update_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Update an issue via the gitea integration."""
|
||||
if not self.auth_token:
|
||||
raise IssueError("Authentication token required for issue updates")
|
||||
|
||||
try:
|
||||
issue = self.gitea_client.issues.update(issue_number, **update_data)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to update issue #{issue_number}: {e}")
|
||||
|
||||
def update_issue_title(self, issue_number: int, new_title: str) -> Dict[str, Any]:
|
||||
"""Update only the title of an issue."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.update_title(issue_number, new_title)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to update issue title #{issue_number}: {e}")
|
||||
|
||||
def update_issue_body(self, issue_number: int, new_body: str) -> Dict[str, Any]:
|
||||
"""Update only the body of an issue."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.update_body(issue_number, new_body)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to update issue body #{issue_number}: {e}")
|
||||
|
||||
def update_issue_state(self, issue_number: int, new_state: str) -> Dict[str, Any]:
|
||||
"""Update only the state of an issue (open/closed)."""
|
||||
if new_state not in ['open', 'closed']:
|
||||
raise IssueError(f"Invalid state '{new_state}'. Must be 'open' or 'closed'")
|
||||
|
||||
try:
|
||||
if new_state == 'closed':
|
||||
issue = self.gitea_client.issues.close(issue_number)
|
||||
else:
|
||||
issue = self.gitea_client.issues.reopen(issue_number)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to update issue state #{issue_number}: {e}")
|
||||
|
||||
def close_issue(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Close an issue."""
|
||||
return self.update_issue_state(issue_number, 'closed')
|
||||
|
||||
def reopen_issue(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Reopen a closed issue."""
|
||||
return self.update_issue_state(issue_number, 'open')
|
||||
|
||||
def assign_to_milestone(self, issue_number: int, milestone_id: int) -> Dict[str, Any]:
|
||||
"""Assign issue to a milestone (project)."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.assign_to_milestone(issue_number, milestone_id)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to assign issue #{issue_number} to milestone: {e}")
|
||||
|
||||
def remove_from_milestone(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Remove issue from its current milestone."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.remove_from_milestone(issue_number)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to remove issue #{issue_number} from milestone: {e}")
|
||||
|
||||
def update_labels(self, issue_number: int, labels: list) -> Dict[str, Any]:
|
||||
"""Update issue labels completely."""
|
||||
if not self.auth_token:
|
||||
raise IssueError("Authentication token required for label updates")
|
||||
|
||||
try:
|
||||
issue = self.gitea_client.issues.set_labels(issue_number, labels)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to update labels for issue #{issue_number}: {e}")
|
||||
|
||||
def add_labels(self, issue_number: int, new_labels: list) -> Dict[str, Any]:
|
||||
"""Add labels to issue (preserving existing labels)."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.add_labels(issue_number, new_labels)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to add labels to issue #{issue_number}: {e}")
|
||||
|
||||
def remove_labels(self, issue_number: int, labels_to_remove: list) -> Dict[str, Any]:
|
||||
"""Remove specific labels from issue."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.remove_labels(issue_number, labels_to_remove)
|
||||
return self.gitea_client.issues.to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to remove labels from issue #{issue_number}: {e}")
|
||||
@@ -1,244 +0,0 @@
|
||||
"""
|
||||
Project management functionality using the Gitea facade.
|
||||
|
||||
This module now acts as an adapter to the new gitea package,
|
||||
maintaining backwards compatibility while using the cleaner API.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
from gitea import GiteaClient, GiteaConfig
|
||||
from gitea.models import ProjectState, Priority, Milestone as GiteaMilestone, Label as GiteaLabel
|
||||
from gitea.exceptions import GiteaError, GiteaNotFoundError, GiteaAuthError, GiteaApiError
|
||||
from .config import get_config
|
||||
from .exceptions import IssueError
|
||||
|
||||
# Re-export for backwards compatibility
|
||||
Milestone = GiteaMilestone
|
||||
Label = GiteaLabel
|
||||
|
||||
|
||||
class ProjectManager:
|
||||
"""Manages project organization using the Gitea facade."""
|
||||
|
||||
def __init__(self, config=None, auth_token=None):
|
||||
self.config = config or get_config()
|
||||
self.auth_token = auth_token or os.getenv('GITEA_API_TOKEN')
|
||||
|
||||
# Create Gitea client from tddai config
|
||||
gitea_config = GiteaConfig.from_tddai_config(self.config)
|
||||
if self.auth_token:
|
||||
gitea_config.auth_token = self.auth_token
|
||||
self.gitea_client = GiteaClient(gitea_config)
|
||||
|
||||
def _make_api_call(self, method: str, url: str, data: Dict[str, Any] = None) -> Dict[str, Any]:
|
||||
"""Make authenticated API call to Gitea (kept for backwards compatibility).
|
||||
|
||||
Args:
|
||||
method: HTTP method (GET, POST, etc.)
|
||||
url: API endpoint URL
|
||||
data: Optional request data
|
||||
|
||||
Raises:
|
||||
IssueError: When API call fails (with specific context)
|
||||
"""
|
||||
# This method is kept for backwards compatibility but now delegates to the gitea client
|
||||
# For new code, use the gitea_client directly
|
||||
try:
|
||||
if method == 'GET' and 'issues' in url and url.endswith('/issues'):
|
||||
issues = self.gitea_client.issues.list()
|
||||
return [self._issue_to_dict(issue) for issue in issues]
|
||||
elif method == 'GET' and '/issues/' in url and not url.endswith('/labels'):
|
||||
issue_number = int(url.split('/issues/')[-1])
|
||||
issue = self.gitea_client.issues.get(issue_number)
|
||||
return self._issue_to_dict(issue)
|
||||
else:
|
||||
raise IssueError(f"Legacy API call not supported: {method} {url}")
|
||||
except GiteaNotFoundError as e:
|
||||
raise IssueError(f"Resource not found for {method} {url}") from e
|
||||
except GiteaAuthError as e:
|
||||
raise IssueError(f"Authentication failed for {method} {url}") from e
|
||||
except GiteaApiError as e:
|
||||
raise IssueError(f"API error for {method} {url}: {e}") from e
|
||||
except GiteaError as e:
|
||||
raise IssueError(f"Gitea error for {method} {url}: {e}") from e
|
||||
except (ValueError, IndexError) as e:
|
||||
raise IssueError(f"Invalid URL format for {method} {url}") from e
|
||||
|
||||
def _issue_to_dict(self, issue) -> Dict[str, Any]:
|
||||
"""Convert Issue object to dict for backwards compatibility."""
|
||||
return {
|
||||
'number': issue.number,
|
||||
'title': issue.title,
|
||||
'body': issue.body,
|
||||
'state': issue.state,
|
||||
'html_url': issue.html_url,
|
||||
'created_at': issue.created_at.isoformat(),
|
||||
'updated_at': issue.updated_at.isoformat(),
|
||||
'assignee': {'login': issue.assignee.login} if issue.assignee else None,
|
||||
'labels': [{'name': label.name, 'color': label.color} for label in issue.labels]
|
||||
}
|
||||
|
||||
# Milestone Management (Projects)
|
||||
|
||||
def create_milestone(self, title: str, description: str = "", due_date: Optional[str] = None) -> Milestone:
|
||||
"""Create a new milestone (project)."""
|
||||
try:
|
||||
return self.gitea_client.milestones.create(title, description, due_date)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to create milestone: {e}")
|
||||
|
||||
def list_milestones(self, state: str = "open") -> List[Milestone]:
|
||||
"""List all milestones (projects)."""
|
||||
try:
|
||||
if state == "all":
|
||||
return self.gitea_client.milestones.list()
|
||||
elif state == "open":
|
||||
return self.gitea_client.milestones.list_open()
|
||||
elif state == "closed":
|
||||
return self.gitea_client.milestones.list_closed()
|
||||
else:
|
||||
return self.gitea_client.milestones.list(state)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to list milestones: {e}")
|
||||
|
||||
def update_milestone(self, milestone_id: int, **kwargs) -> Milestone:
|
||||
"""Update milestone details."""
|
||||
url = f"{self.config.gitea_url}/api/v1/repos/{self.config.repo_owner}/{self.config.repo_name}/milestones/{milestone_id}"
|
||||
|
||||
# Only include fields that can be updated
|
||||
valid_fields = ['title', 'description', 'state', 'due_on']
|
||||
data = {k: v for k, v in kwargs.items() if k in valid_fields}
|
||||
|
||||
response = self._make_api_call('PATCH', url, data)
|
||||
|
||||
return Milestone(
|
||||
id=response['id'],
|
||||
title=response['title'],
|
||||
description=response.get('description', ''),
|
||||
state=response['state'],
|
||||
open_issues=response['open_issues'],
|
||||
closed_issues=response['closed_issues'],
|
||||
due_on=response.get('due_on')
|
||||
)
|
||||
|
||||
def close_milestone(self, milestone_id: int) -> Milestone:
|
||||
"""Close a milestone (complete project)."""
|
||||
return self.update_milestone(milestone_id, state='closed')
|
||||
|
||||
# Label Management (States & Priority)
|
||||
|
||||
def create_label(self, name: str, color: str, description: str = "") -> Label:
|
||||
"""Create a new label."""
|
||||
url = f"{self.config.gitea_url}/api/v1/repos/{self.config.repo_owner}/{self.config.repo_name}/labels"
|
||||
|
||||
data = {
|
||||
'name': name,
|
||||
'color': color,
|
||||
'description': description
|
||||
}
|
||||
|
||||
response = self._make_api_call('POST', url, data)
|
||||
|
||||
return Label(
|
||||
id=response['id'],
|
||||
name=response['name'],
|
||||
color=response['color'],
|
||||
description=response.get('description', '')
|
||||
)
|
||||
|
||||
def list_labels(self) -> List[Label]:
|
||||
"""List all repository labels."""
|
||||
url = f"{self.config.gitea_url}/api/v1/repos/{self.config.repo_owner}/{self.config.repo_name}/labels"
|
||||
|
||||
response = self._make_api_call('GET', url)
|
||||
|
||||
return [
|
||||
Label(
|
||||
id=l['id'],
|
||||
name=l['name'],
|
||||
color=l['color'],
|
||||
description=l.get('description', '')
|
||||
)
|
||||
for l in response
|
||||
]
|
||||
|
||||
def ensure_project_labels(self) -> None:
|
||||
"""Ensure all required project management labels exist."""
|
||||
try:
|
||||
self.gitea_client.labels.ensure_project_labels()
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to ensure project labels: {e}")
|
||||
|
||||
def list_labels(self) -> List[Label]:
|
||||
"""List all repository labels."""
|
||||
try:
|
||||
return self.gitea_client.labels.list()
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to list labels: {e}")
|
||||
|
||||
def create_label(self, name: str, color: str, description: str = "") -> Label:
|
||||
"""Create a new label."""
|
||||
try:
|
||||
return self.gitea_client.labels.create(name, color, description)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to create label: {e}")
|
||||
|
||||
# Project Management Operations
|
||||
|
||||
def assign_issue_to_milestone(self, issue_number: int, milestone_id: int) -> Dict[str, Any]:
|
||||
"""Assign issue to a milestone (project)."""
|
||||
url = f"{self.config.issues_api_url}/{issue_number}"
|
||||
|
||||
data = {'milestone': milestone_id}
|
||||
return self._make_api_call('PATCH', url, data)
|
||||
|
||||
def set_issue_state(self, issue_number: int, state: ProjectState) -> Dict[str, Any]:
|
||||
"""Set issue project state using labels."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.set_status(issue_number, state)
|
||||
return self._issue_to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to set issue state: {e}")
|
||||
|
||||
def set_issue_priority(self, issue_number: int, priority: Priority) -> Dict[str, Any]:
|
||||
"""Set issue priority using labels."""
|
||||
try:
|
||||
issue = self.gitea_client.issues.set_priority(issue_number, priority)
|
||||
return self._issue_to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to set issue priority: {e}")
|
||||
|
||||
def move_issue_to_done(self, issue_number: int) -> Dict[str, Any]:
|
||||
"""Move issue to done state and close it."""
|
||||
try:
|
||||
# Set state to done
|
||||
self.set_issue_state(issue_number, ProjectState.DONE)
|
||||
|
||||
# Close the issue
|
||||
issue = self.gitea_client.issues.close(issue_number)
|
||||
return self._issue_to_dict(issue)
|
||||
except Exception as e:
|
||||
raise IssueError(f"Failed to move issue to done: {e}")
|
||||
|
||||
def get_project_overview(self) -> Dict[str, Any]:
|
||||
"""Get overview of project status."""
|
||||
milestones = self.list_milestones("all")
|
||||
labels = self.list_labels()
|
||||
|
||||
# Count issues by state
|
||||
state_counts = {}
|
||||
for state in ProjectState:
|
||||
state_counts[state.value] = 0
|
||||
|
||||
# This would require fetching all issues to count by labels
|
||||
# For now, return milestone overview
|
||||
|
||||
return {
|
||||
'milestones': len(milestones),
|
||||
'active_projects': len([m for m in milestones if m.state == 'open']),
|
||||
'completed_projects': len([m for m in milestones if m.state == 'closed']),
|
||||
'total_labels': len(labels),
|
||||
'project_management_ready': len([l for l in labels if l.name.startswith('status:')]) > 0
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
"""
|
||||
Test generation with AI assistance.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from .config import get_config
|
||||
from .workspace import WorkspaceManager
|
||||
from .exceptions import TestGenerationError
|
||||
|
||||
|
||||
class TestGenerator:
|
||||
"""Generates tests using AI assistance."""
|
||||
|
||||
def __init__(self, config=None):
|
||||
self.config = config or get_config()
|
||||
self.workspace_manager = WorkspaceManager(config)
|
||||
|
||||
def generate_test(self, scenario_name: str, test_description: str) -> Path:
|
||||
"""Generate a test file for the current workspace issue."""
|
||||
workspace = self.workspace_manager.get_current_workspace()
|
||||
if not workspace:
|
||||
raise TestGenerationError("No active workspace found")
|
||||
|
||||
# Create test file name
|
||||
test_filename = self.config.test_file_pattern.format(
|
||||
issue_num=workspace.issue_number,
|
||||
scenario=scenario_name.lower().replace(' ', '_').replace('-', '_')
|
||||
)
|
||||
test_file_path = workspace.tests_dir / test_filename
|
||||
|
||||
# Generate test prompt
|
||||
prompt = self._create_test_prompt(workspace, scenario_name, test_description)
|
||||
|
||||
# Use Claude Code to generate the test
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
|
||||
f.write(prompt)
|
||||
prompt_file = Path(f.name)
|
||||
|
||||
result = subprocess.run(
|
||||
[self.config.claude_code_command, '--file', str(prompt_file)],
|
||||
cwd=workspace.workspace_dir,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
|
||||
prompt_file.unlink() # Clean up temp file
|
||||
|
||||
if result.returncode != 0:
|
||||
raise TestGenerationError(f"Claude Code failed: {result.stderr}")
|
||||
|
||||
# Extract Python code from Claude's response
|
||||
test_content = self._extract_test_code(result.stdout)
|
||||
|
||||
# Write test file
|
||||
test_file_path.write_text(test_content)
|
||||
|
||||
# Update test plan
|
||||
self._update_test_plan(workspace, scenario_name, test_filename)
|
||||
|
||||
return test_file_path
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise TestGenerationError(f"Failed to generate test: {e}")
|
||||
except Exception as e:
|
||||
raise TestGenerationError(f"Test generation error: {e}")
|
||||
|
||||
def _create_test_prompt(self, workspace, scenario_name: str, test_description: str) -> str:
|
||||
"""Create prompt for Claude Code to generate test."""
|
||||
return f"""# Test Generation Request
|
||||
|
||||
## Context
|
||||
- Issue #{workspace.issue_number}: {workspace.issue_title}
|
||||
- Scenario: {scenario_name}
|
||||
|
||||
## Issue Description
|
||||
{workspace.issue_body}
|
||||
|
||||
## Test Requirements
|
||||
{test_description}
|
||||
|
||||
## Instructions
|
||||
Please generate a comprehensive Python test file that:
|
||||
|
||||
1. Tests the behavior described in the scenario
|
||||
2. Follows pytest conventions
|
||||
3. Includes proper docstrings and comments
|
||||
4. Tests both positive and negative cases
|
||||
5. Uses meaningful test method names
|
||||
6. Includes appropriate assertions
|
||||
|
||||
The test should focus on behavior verification rather than implementation details.
|
||||
|
||||
## Expected Output
|
||||
Please provide only the Python test code without any additional explanation.
|
||||
The code should be ready to save as `{self.config.test_file_pattern.format(issue_num=workspace.issue_number, scenario=scenario_name.lower().replace(' ', '_'))}`
|
||||
"""
|
||||
|
||||
def _extract_test_code(self, claude_response: str) -> str:
|
||||
"""Extract Python test code from Claude's response."""
|
||||
lines = claude_response.split('\n')
|
||||
code_lines = []
|
||||
in_code_block = False
|
||||
|
||||
for line in lines:
|
||||
if line.strip().startswith('```python'):
|
||||
in_code_block = True
|
||||
continue
|
||||
elif line.strip() == '```' and in_code_block:
|
||||
break
|
||||
elif in_code_block:
|
||||
code_lines.append(line)
|
||||
|
||||
if not code_lines:
|
||||
# If no code block found, assume entire response is code
|
||||
return claude_response.strip()
|
||||
|
||||
return '\n'.join(code_lines)
|
||||
|
||||
def _update_test_plan(self, workspace, scenario_name: str, test_filename: str) -> None:
|
||||
"""Update the test plan with the new test."""
|
||||
test_plan_content = workspace.test_plan_file.read_text()
|
||||
|
||||
# Add test to the generated tests section
|
||||
new_entry = f"- [x] {scenario_name} (`{test_filename}`)"
|
||||
|
||||
if "### Generated Tests" in test_plan_content:
|
||||
# Add to existing generated tests section
|
||||
lines = test_plan_content.split('\n')
|
||||
for i, line in enumerate(lines):
|
||||
if line.strip() == "Tests generated for this workspace will be listed here as they are created.":
|
||||
lines[i] = new_entry
|
||||
break
|
||||
elif line.startswith("- [") and "Generated Tests" in lines[max(0, i-5):i]:
|
||||
lines.insert(i, new_entry)
|
||||
break
|
||||
else:
|
||||
# Add at the end of generated tests section
|
||||
for i, line in enumerate(lines):
|
||||
if "### Generated Tests" in line:
|
||||
# Find next section or end
|
||||
j = i + 1
|
||||
while j < len(lines) and not lines[j].startswith('##'):
|
||||
j += 1
|
||||
lines.insert(j, new_entry)
|
||||
break
|
||||
|
||||
workspace.test_plan_file.write_text('\n'.join(lines))
|
||||
|
||||
def list_generated_tests(self) -> list:
|
||||
"""List all generated tests for the current workspace."""
|
||||
workspace = self.workspace_manager.get_current_workspace()
|
||||
if not workspace:
|
||||
return []
|
||||
|
||||
if not workspace.tests_dir.exists():
|
||||
return []
|
||||
|
||||
return list(workspace.tests_dir.glob("*.py"))
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user