# Changelog

All notable changes to this project 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).

## [0.7.0] - 2026-01-28

### Added
- **Bug Fix pattern** — New pattern for fixing broken functionality
  - Keywords: fix, bug, broken, crash, error, regression
  - systems_base: 0.5 (usually single-system fixes)
  - Includes error_handling modifier by default
  - Probe questions for reproduction and root cause
  - Intent scaffold with success criteria for regression testing
  - Lower confidence threshold (65%) to match simple "Fix X" directives
- **Refactor pattern** — New pattern for implementation replacement
  - Keywords: replace, rewrite, swap, substitute, refactor
  - systems_base: 1.0 (moderate complexity)
  - No default modifiers (clean refactors)
  - Probe questions for replacement strategy
  - Intent scaffold emphasizing behavior preservation
- **File extension detection** — Single-file changes cap systems at 1
  - Detects 20+ common extensions: .ts, .tsx, .js, .jsx, .py, .java, .go, .rs, etc.
  - Example: "Fix bug in handler.ts" → 1 system (even with multiple signals)
  - Multiple files detected correctly: "Fix handler.ts and validator.ts" → 2 systems
  - Prevents over-decomposition of targeted file changes
  - More accurate complexity assessment for bug fixes
- **Intent validation** — Optional validation of intent completeness
  - `validate_intent` flag: warns if intent contains TODOs (non-blocking)
  - `require_complete_intent` flag: errors if intent contains TODOs (strict)
  - Checks goal, success_criteria, constraints, out_of_scope fields
  - Validates fields are non-empty (not just TODO-free)
  - Pattern-matched directives pass validation automatically
  - Encourages use of recognized patterns or manual intent editing
- **Enhanced task template** — Context reminders and alignment checks
  - Context Files section at top with checklist:
    * Review manifest.yaml for root intent
    * Check siblings.yaml for coordination
    * Review ancestry chain if at depth > 0
  - Expanded Alignment Check section (required before COMPLETE):
    * Root Goal fulfillment verification
    * Success Criteria satisfaction check
    * Constraints adherence validation
    * Scope boundaries verification
    * Required alignment summary field

### Fixed
- **CRITICAL: Pattern collision resolution** — Highest confidence pattern now wins
  - Previously: First pattern >= 80% won (order-dependent)
  - Now: All patterns collected, sorted by confidence, highest returned
  - Example: "Replace authentication with OAuth" now correctly matches Refactor over Authentication
  - Added `return_all_matches` parameter for debugging pattern collisions
- **CRITICAL: Multiple file detection** — Multi-file directives no longer cap at 1 system
  - Previously: `re.search()` found first file and stopped
  - Now: `re.findall()` detects all file mentions
  - Single file: caps at 1 system
  - Multiple files: uses max(base_count, file_count), capped at 6 systems
- **CRITICAL: Bug Fix pattern matching** — Simple "Fix X" directives now match
  - Lowered confidence threshold from 80% to 65%
  - Added +15% confidence boost when specific file mentioned
  - No longer requires "area" component coverage for match
  - Example: "Fix workspace scanning in CleaveWorkspaceView.ts" → 75% confidence match
- **HIGH: Empty directive validation** — Empty and whitespace-only directives now rejected
  - `assess_directive("")` raises ValueError with clear message
  - Fail-fast before any pattern matching
- **System count capping** — All code paths now consistently cap at 6 systems
  - Prevents over-decomposition on large-scale changes
  - Applied to both single-file and multi-file detection paths

### Changed
- Pattern library expanded from 7 to 9 patterns (Bug Fix, Refactor added)
- Task template now ~70 lines (from ~50) with enhanced guidance
- estimate_systems() now file-aware for single-file and multi-file directives
- init_workspace() accepts new validation flags
- match_pattern() now collects all matches and returns highest confidence

### Test Results
- 581 tests passing (up from 547)
- 34 new tests added (patterns, file detection, validation, collision resolution)
- 100% pass rate, no regressions

## [0.6.5] - 2026-01-28

### Added
- **Comprehensive .cloven.md reports** — Enhanced reports with all workspace metrics
  - **Executive Summary**: Quick stats (status, tasks, conflicts, accuracy)
  - **Directive & Intent**: Full goal, success criteria, constraints, out-of-scope
  - **Ancestry Context**: Tree position (depth, node ID, budget), parent chain
  - **Task Details**: Full summaries from each task (not just counts)
  - **Verification Evidence**: Commands, outputs, coverage, edge cases tested
  - **Decisions & Interfaces**: All architectural decisions and APIs published
  - **Assumptions**: What was assumed true during execution
  - **Telemetry**: Access patterns, cache hits/misses, fast-path usage
  - **GitHub Issue Template**: Ready-to-paste markdown for direct issue creation
  - Data sources: manifest.yaml, siblings.yaml, metrics.yaml, merge.md, review.md
  - All workspace artifacts included in single comprehensive report

### Fixed
- **CRITICAL: Circular import** — Module load failure resolved
  - `_get_version()` function with function-level import breaks circular dependency
  - Returns "unknown" gracefully if import fails
- **HIGH: None value handling** — Reports no longer show "None" strings
  - All numeric fields use `or 0` pattern (file_count, interface_count, systems_count, telemetry)
  - Depth, remaining_budget, coord_depth handle None values correctly
- **HIGH: Input validation** — Added required keys check for aggregated dict
  - Raises ValueError with clear message if keys missing
  - Validates all required fields before proceeding
- **HIGH: Children string formatting** — Malformed manifest no longer crashes
  - Type checking with isinstance() filters non-dict items
  - Provides defaults for missing id/label fields
- **MEDIUM: YAML parsing errors** — Added try/except for all YAML reads
  - Logs warnings on parse failure, continues with empty dict
  - Covers manifest.yaml, siblings.yaml, metrics.yaml
- **MEDIUM: String slicing safety** — Pre-converts to string, checks length
  - Applied to output and reasoning fields
  - No redundant .get() calls or conversions
- **MEDIUM: GitHub template formatting** — Clean markdown checklist
  - No empty strings or blank lines in output
  - Properly built next_steps list

### Changed
- Dynamic version from `__version__` instead of hardcoded string
- Enhanced error handling with logging throughout report module
- Improved None-safety patterns across all data fields

### Test Results
- Test fixtures updated with complete data structures
- New tests for intent, ancestry, telemetry, GitHub template sections
- Integration tests updated with full manifests

## [0.6.4] - 2026-01-28

### Added
- **Automatic workspace naming** — Workspaces are now auto-generated with unique names
  based on the directive to prevent collisions when running multiple cleave sessions.
  - Example: `cleave init -d "Add JWT auth"` → `.cleave-add-jwt-auth/`
  - Collision detection with numeric suffixes (`.cleave-add-jwt-auth-2/`)
  - `generate_workspace_name()` function slugifies directives (40 char max)
  - CLI `--output` parameter now defaults to None (auto-generate)
  - Explicit `--output` still works for manual override
  - Returns `workspace` key in created dict for display

### Changed
- `init_workspace()` `output_dir` parameter now accepts `None` for auto-generation
- CLI help text updated to reflect auto-naming behavior

### Test Results
- 547 tests passing, 0 skipped, 0 warnings (up from 537)

## [0.6.3] - 2026-01-28

### Fixed
- **PerfMetrics double-start guard** — `start()` is now a no-op when already streaming,
  preventing mid-flight counter resets from duplicate calls.
- **`ru_maxrss` label corrected** — Display shows `RSS` instead of `MB`; docstring
  clarified the value is the kernel's last reported RSS, not a tracked peak.
- **TODO warning resilience** — `cmd_reunify` manifest check uses `- TODO:` prefix
  scan instead of a single hard-coded string, surviving template wording changes.
- **`test_conflicts.py` assertions strengthened** — Three previously comment-only tests
  now have concrete assertions (same-sibling no-contradiction, assumption_violation
  detection, missing-file return type).

### Test Results
- 537 tests passing, 0 skipped, 0 warnings

## [0.6.2] - 2026-01-28

### Fixed
- **Verification parser anchored to section** - `parse_task_result()` now isolates the
  `**Verification:**` block before searching for Command/Output/Edge cases fields.
  Stray occurrences of "Output:" in Summary or Alignment sections no longer pollute
  verification evidence. Six of nine tasks across prior cleave runs had real verification
  data that was silently discarded by the old document-wide regexes.
- **SYSTEM_SIGNALS false positives eliminated** - Removed broad-match keywords that
  inflated system counts on legitimate directives: `"command"` (matched "command pattern"),
  `"service"` (matched "customer service"), `"model"` (matched "ML model"), `"serial"`
  (matched "serial port"). Replaced with precise signals: `"subcommand"`, `"argparse"`,
  `"click"`, `"microservice"`, `"orm"`, `"serializ"`.
- **asyncio.iscoroutinefunction deprecation** - Replaced with `inspect.iscoroutinefunction`
  in retry.py (Python 3.16 removal warning).

### Added
- **Live TUI performance metrics** - `PerfMetrics` widget displays latency, token count,
  tokens/sec, and memory usage during streaming responses. Integrates into ChatPanel
  streaming lifecycle. stdlib only (`time.perf_counter`, `resource`).
- **Success criteria warnings** - `cleave init` warns when no pattern matched and
  success criteria are TODO placeholders. `cleave reunify` warns when verification
  coverage is 0 or manifest has unresolved TODO criteria.
- **Signal-based systems estimation** - `estimate_systems()` replaces hardcoded `systems=2`
  fallback with 13 architectural boundary signal categories. Directives that previously
  assessed at a flat complexity=3.0 now get differentiated scores.

### Test Results
- 536 tests passing, 0 skipped, 0 warnings

## [0.6.0] - 2026-01-28

### Added
- **Performance Monitoring** - `@timed` and `@memory_profiled` decorators for core operations
  - Instrumented assess_directive, reunify_workspace, probe_codebase
  - Analytics module with trend analysis and regression detection
  - `cleave analytics` CLI command (JSON, YAML, Markdown, Prometheus export)
  - Benchmark suite for assessment speed and file I/O
- **Theme System** - 5 built-in TUI themes with runtime switching
  - retro-purple (default), cyberpunk-green, solarized-dark, nord, high-contrast
  - Theme registry and loader infrastructure
  - `t` keybinding to cycle themes in TUI
- **Retry Logic** - Exponential backoff retry decorator (async/sync)
  - `retry_on_network_errors()` and `retry_on_file_errors()` convenience wrappers
- **Plugin Security** - AST-based static analysis for backend plugins
  - Detects eval, exec, subprocess, unauthorized file/network access
  - Plugin discovery from ~/.cleave/backends/
- **Integration Tests** - 53 tests for TUI and probe modules
- **Backend Auth Validation** - Credential format and endpoint connectivity checks
- **Settings Validation** - Enum validation, type checking, actionable error messages
- **Comprehensive Documentation**
  - Architecture docs (overview, backend interface, assessment pipeline)
  - User guides (getting started, TUI usage, advanced patterns, contributing)
  - CALF format specification
  - Plugin system guide with examples
- **Parallel Agent Development** - Documented in CLAUDE.md

### Fixed
- TUI `current_theme` property conflict with Textual App base class
- Theme application using unavailable Textual Stylesheet API
- Probe integration test path matching (full path vs basename)

### Test Results
- 504 tests passing, 5 skipped (pending RichLog API adaptation)
- 21 deprecation warnings in retry.py (asyncio.iscoroutinefunction)

## [0.5.1] - 2026-01-27

### Fixed
- **Critical**: Added `__main__.py` for proper `python -m cleave` execution
- **Critical**: Fixed 6 test failures in report module due to parameter mismatch in `_generate_calibration_insight()`
  - Tests now use `systems_count` (int) instead of `systems_detected` (list)
  - Tests mock settings to use workspace naming mode for backwards compatibility
- CLI `config set` command now supports `backend` parameter with validation
- Test suite now passes cleanly (310/310 tests)

### Added
- Backend selection via `cleave config set backend <backend>` with validation
  - Valid backends: `claude`, `ollama`, `openai`, `vllm`, `llamacpp`

### Documentation
- Comprehensive CHANGELOG entry for v0.5.0 documenting all features and limitations
- TUI installation instructions in README with keyboard shortcuts
- Backend configuration guide in README
- Settings management examples

### Changed
- CLI validation now includes backend selection

This patch release addresses critical issues identified in the adversarial review of v0.5.0, ensuring the package works correctly after installation.

## [0.5.0] - 2026-01-27

### Added
- **Interactive Terminal UI** - Full TUI implementation with retro CRT purple theme
  - Textual-based terminal interface for task decomposition
  - Claude Agent SDK integration with live streaming
  - Multi-line chat input with history navigation (Up/Down arrows)
  - Session management with persistent history
  - CALF file support for directive management
  - Tool use display with syntax highlighting
  - Session export to markdown
  - Keyboard shortcuts: Ctrl+L (clear), Escape (cancel), Shift+Enter (newline)
- **Intelligent Assessment Infrastructure**
  - `probe` module: Socratic interrogation with codebase-aware questions
  - `metrics` module: Feedback loop for tracking assessment accuracy
  - `report` module: Session reports with calibration insights (`.cloven.md`)
  - `settings` module: Configuration management via `~/.cleave/settings.yaml`
  - `file_utils` module: Atomic file write operations
- **Backend Abstraction Layer** (preparation for multi-model support)
  - Abstract `Backend` interface for LLM providers
  - `ClaudeBackend` implementation wrapping Claude Agent SDK
  - `OpenAICompatBackend` for Ollama, vLLM, llama.cpp, OpenAI
  - Backend configuration in settings with per-backend options
- **New CLI Commands**
  - `cleave tui [directory]` - Launch interactive TUI
  - `cleave probe --directive "..."` - Pre-decomposition codebase interrogation
  - `cleave metrics --workspace .` - View assessment accuracy and calibration
  - `cleave config show|set|path` - Manage settings
- **Enhanced Core Modules**
  - Assessment: Added `probe_questions` to all 7 patterns for context-aware interrogation
  - Reunify: Auto-extract effort metrics from task results, generate `.cloven.md` reports
  - Conflicts: Enhanced 4-step conflict detection with file overlap analysis
  - Workspace: Simplified task file generation
  - Permissions: Enhanced permission inference
- **Optional Dependencies** for flexible installation
  - `[tui]` - TUI with Claude backend (Textual + Claude SDK)
  - `[claude]` - Claude SDK only
  - `[local]` - Local inference via OpenAI-compatible APIs
  - `[tui-local]` - TUI with local inference only (no Claude SDK)
  - `[full]` - All features
- **Comprehensive Test Suite** - 48 test files covering all modules
- **Visual Theme** - Retro CRT aesthetic with purple accents (#a855f7), heavy borders, ASCII art

### Changed
- Version bumped to 0.5.0 reflecting major feature additions
- Report naming now configurable via settings (`descriptor`, `timestamp`, or `workspace`)
- Backend selection prepared for multi-model support (Claude, Ollama, vLLM, llama.cpp)

### Fixed
- History property conflict in TextArea (renamed to `input_history`)

### Installation
```bash
pip install styrene-cleave[tui]      # TUI with Claude backend
pip install styrene-cleave[full]     # All features
pip install styrene-cleave           # Core only (no TUI)
```

### Limitations
- TUI requires optional dependencies (`textual>=0.47.0`)
- Backend authentication only checks credential file existence, not validity
- No integration tests for TUI end-to-end functionality
- Multi-model backend support prepared but not fully tested with local models

### Documentation
- Added comprehensive PR documentation (#1)
- TUI keyboard shortcuts and usage documented in release notes

## [0.3.0] - 2026-01-26

### Added
- **Windows 11 cross-platform compatibility** - Full support for Windows 11 operations
- **Version tracking for directory copies** - Automatic detection and update of stale installations
- **Long path validation** - Pre-validation for Windows MAX_PATH (260 char) limit with helpful errors
- **Symlink fallback mechanism** - Graceful fallback to directory copy when symlink privileges unavailable
- **Partial copy cleanup** - Automatic cleanup of failed partial directory copies
- **MCP dependency checking** - Programmatic validation for Sequential Thinking MCP server requirement
- Comprehensive Windows compatibility test suite (12 new tests)
- `WINDOWS_COMPAT.md` documentation for cross-platform considerations

### Fixed
- **Critical**: Path separator bug causing "Path escapes home directory" error on Windows
- **Critical**: Stale directory copies not updating after package upgrades
- **Critical**: Partial file remnants after failed copy operations
- **High**: Missing validation for Windows long path support
- Cross-platform path comparison now uses `Path.is_relative_to()` instead of string concatenation

### Changed
- `InstallResult` dataclass now includes `used_copy` field to track installation method
- `install_skill()` function now validates path length before attempting installation
- Directory copy installations now include `.version` file for upgrade tracking

### Security
- Enhanced path traversal protection with cross-platform path resolution

## [0.2.0] - 2026-01-25

### Added
- Initial public release
- `cleave install-skill` command for skill installation
- Automatic skill discovery via symlink to `~/.claude/skills/`
- Support for editable installs and various package managers (pip, pipx, poetry)

## [0.1.0] - 2026-01-24

### Added
- Initial development release
- Core task decomposition functionality
- Complexity assessment with fast-path pattern matching
- Workspace initialization and management
- Reunification with conflict detection
- Adaptive interrogation system
- Permission inference for fire-and-forget execution
- TDD workflow support

[0.7.0]: https://github.com/styrene-lab/cleave/compare/v0.6.5...v0.7.0
[0.6.5]: https://github.com/styrene-lab/cleave/compare/v0.6.4...v0.6.5
[0.6.4]: https://github.com/styrene-lab/cleave/compare/v0.6.3...v0.6.4
[0.6.3]: https://github.com/styrene-lab/cleave/compare/v0.6.2...v0.6.3
[0.6.2]: https://github.com/styrene-lab/cleave/compare/v0.6.0...v0.6.2
[0.6.0]: https://github.com/styrene-lab/cleave/compare/v0.5.1...v0.6.0
[0.5.1]: https://github.com/styrene-lab/cleave/compare/v0.5.0...v0.5.1
[0.5.0]: https://github.com/styrene-lab/cleave/compare/v0.3.0...v0.5.0
[0.3.0]: https://github.com/styrene-lab/cleave/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/styrene-lab/cleave/compare/v0.1.0...v0.2.0
[0.1.0]: https://github.com/styrene-lab/cleave/releases/tag/v0.1.0
