Compare commits

...
203 Commits
Author SHA1 Message Date
asepharyana 8ecc588a3e feat(best_practice): add code quality scanning and commit message validation
- Implemented a code quality scanner that checks for common clean-code violations in Rust source files, including missing documentation, usage of `.unwrap()` in production code, and commented-out code.
- Introduced a commit message validator that follows the Conventional Commits specification, ensuring proper formatting and providing suggestions for invalid messages.
- Created a unified BestPracticeEngine to encapsulate the functionalities of skills, architecture audits, code quality checks, and commit message validation.
- Added tests for both the code quality scanner and commit message validator to ensure reliability and correctness.
2026-07-21 07:21:22 +07:00
asepharyana 55677dd671 feat: Add SOLID principles and TDD reference documentation
- Created solid.md to document the SOLID principles for clean code practices.
- Created tdd.md to outline Test Driven Development principles and practices.
- Added kana-rust-backend-best-practice.md as a reference guide for building a Rust backend using Axum and SeaORM.
- Established push-flow-convention.md to enforce pre-commit and pre-push hooks with versioning rules.
- Introduced AGENTS.md to provide guidance on best practices and available commands for Kilo.
- Configured kilo.json to include new skills and agents for enhanced functionality.
- Added lefthook.yml for managing git hooks to ensure code quality and adherence to conventions.
2026-07-21 07:10:17 +07:00
asepharyana d615090dcd feat: centralize default constants and refactor overlay enter handling in TUI 2026-07-21 07:00:15 +07:00
asepharyana 8c58faf292 feat(tui): introduce comprehensive state management for TUI interface
- Add AppStateRest as the central state struct for managing TUI state.
- Implement InputState for handling user input, autocomplete, and history.
- Create MiscState to manage overlays, notifications, and editor state.
- Introduce ScrollState for viewport scrolling functionality.
- Develop TranscriptCache for efficient message rendering in the chat pane.
- Implement SimpleAgent and SimpleWorkflowEngine for agent lifecycle management.
- Add helper functions for managing effort levels and token counting.
- Organize state-related modules for better maintainability and clarity.
2026-07-21 06:42:53 +07:00
asepharyana 802346f909 Refactor subagent and workflow domain models; migrate access tiers and events to domain module
- Moved `AccessTier` and `SubagentEvent` enums to `zesdex_domain::subagent`.
- Consolidated workflow-related types into `zesdex_domain::workflow`.
- Updated references across the codebase to use the new domain models.
- Refactored tool execution logic to utilize a new `ToolExecutor` trait.
- Enhanced `AgentTurnService` to handle tool calls and events more effectively.
- Adjusted API handlers and state management to align with new domain structure.
2026-07-21 06:42:53 +07:00
semantic-release-bot 552bc5bc63 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Bug Fixes

* add .releaserc.json for semantic-release configuration ([047d718](https://github.com/asepharyana/zesdex/commit/047d7183d72adaa0dd1a18a7f92b22d67d5aa85f))

### Features

* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* implement Component trait for modular UI components and refactor TUI views to use it ([d59713d](https://github.com/asepharyana/zesdex/commit/d59713d3e3aa4325f9753bbddd068654e442f6ef))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 23:11:52 +00:00
asepharyana d59713d3e3 feat: implement Component trait for modular UI components and refactor TUI views to use it 2026-07-21 06:08:00 +07:00
semantic-release-bot 6ab532018a chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Bug Fixes

* add .releaserc.json for semantic-release configuration ([047d718](https://github.com/asepharyana/zesdex/commit/047d7183d72adaa0dd1a18a7f92b22d67d5aa85f))

### Features

* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 10:48:37 +00:00
asepharyana 047d7183d7 fix: add .releaserc.json for semantic-release configuration
- Configure branches, plugins, and release workflow for Rust project
- Fixes Release workflow failing with 'tag already exists'
2026-07-20 17:44:33 +07:00
semantic-release-bot 4d85e5144b chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 10:36:16 +00:00
asepharyana dcc8c3ee42 feat: enhance context gathering in auto-review engine and agent runner 2026-07-20 17:32:31 +07:00
semantic-release-bot 289c58ef36 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 10:29:23 +00:00
asepharyana 094eb4b8ba feat: refactor auto-review engine to use spawn_subagent for improved thread handling 2026-07-20 17:25:23 +07:00
asepharyana dd7825b481 refactor: streamline agent turn handling and background review process 2026-07-20 17:25:23 +07:00
semantic-release-bot 4c186b62d4 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 10:03:25 +00:00
asepharyana fef3c925cd feat: add semantic search tool for code symbol indexing and searching
- Implemented a new tool for semantic code search that indexes Rust code symbols (functions, structs, enums, traits, modules) and allows searching by name, concept, or meaning.
- Introduced a symbol index structure with methods for rebuilding the index and searching symbols.
- Added regex patterns for extracting various code symbols from Rust source files.
- Implemented scoring logic for search results based on exact matches, prefix matches, and context relevance.
- Created a web search tool that interacts with a SearXNG instance to fetch documentation and API information based on user queries.
- Added a diff preview overlay for rendering git diff output with color-coded additions and deletions in a TUI interface.
2026-07-20 16:59:27 +07:00
semantic-release-bot 785ae19757 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 09:42:13 +00:00
asepharyana 873f870e23 feat(agent): add AI summarization for conversation history compacting 2026-07-20 16:38:21 +07:00
semantic-release-bot 54927f692f chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 09:33:26 +00:00
asepharyana efcd191f96 feat(agent): implement agent execution engine and turn handling with background processing 2026-07-20 16:29:39 +07:00
semantic-release-bot 2e8a4f2443 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 09:20:09 +00:00
asepharyana 2f5f62ab09 feat(tui): add rich context information including active jobs, README snippet, and recent git history 2026-07-20 16:16:26 +07:00
asepharyana 919435eb84 feat(tui): integrate rich context builder into agent turn process 2026-07-20 16:16:26 +07:00
asepharyana bed9f8cff6 feat(tui): enhance system prompt with workspace structure information 2026-07-20 16:16:26 +07:00
asepharyana 6c7995f5f5 feat(llm): increase max retries for streaming requests from 3 to 10
refactor(shell): remove unused debug logging from tracing imports
2026-07-20 16:16:26 +07:00
asepharyana 7ea226509c feat(llm): improve UTF-8 handling in response processing to prevent infinite loops
feat(shell): enhance output capturing by using threads for stdout and stderr
feat(tui): update usage widget to display token counts and provider/model information
refactor(tui): simplify status bar rendering by removing unnecessary token calculations
2026-07-20 16:16:26 +07:00
semantic-release-bot 6bef4a3f82 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 08:57:39 +00:00
asepharyana 16494d4b1e Enhance logging and documentation across utility tools and TUI overlays
- Added tracing instrumentation and improved logging messages in the Pong, Todofinish, and Todowrite tools for better debugging and monitoring.
- Enhanced documentation comments for clarity on tool functionalities and workflows.
- Implemented tracing in WorkflowRun, NoteFinding, ReadFindings, and HiveMind tools to track execution phases and findings.
- Updated TUI overlays (e.g., Bash, Clear Confirm, Editor, Effort Level, Help, Key Input, Learning, Loading, MCP, Model Selector, Plan, Quit Confirm, Rewind, Settings, Todo, Usage) with debug logging to capture rendering details.
- Improved the status bar and workflow panel rendering with additional debug information.
- Added tracing to various utility functions to facilitate better performance monitoring and error tracking.
2026-07-20 15:53:43 +07:00
semantic-release-bot f84dfb8476 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
2026-07-20 08:25:10 +00:00
asepharyana 07b217cf4a feat(tui): enhance agent turn handling by grouping parameters and improving message management 2026-07-20 15:21:23 +07:00
asepharyana 9bfb95d795 feat(llm): improve tool call handling by dynamically resizing tool_calls and updating arguments 2026-07-20 14:58:39 +07:00
asepharyana 285dbb14cc feat(tui): add support for reasoning in chat messages and update transcript handling 2026-07-20 14:56:03 +07:00
asepharyana cac6626586 feat(tui): implement streaming support for LLM responses and update transcript handling 2026-07-20 14:51:16 +07:00
asepharyana 5a373d1031 feat(tui): update system message for clarity and conciseness in tool usage instructions 2026-07-20 14:47:55 +07:00
asepharyana fe2e916937 feat: add test_load and test_parse binaries for configuration loading and parsing 2026-07-20 14:47:55 +07:00
asepharyana 66ac4dbf02 feat: remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide 2026-07-20 14:47:55 +07:00
semantic-release-bot 44c3dd1239 chore(release): 1.18.0 [skip ci]
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)

### Features

* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
2026-07-20 06:56:23 +00:00
asepharyana 87abe8c335 feat(tui): optimize performance by caching display lines and token counts, and improve action handling 2026-07-20 13:52:20 +07:00
asepharyana 148ba4e07b feat(mcp): enhance MCP server registration with error handling and improve transport process management
refactor: update various tools for better error handling and path resolution
fix: improve markdown rendering and input display in TUI
2026-07-20 13:12:04 +07:00
semantic-release-bot 89ee213454 chore(release): 1.17.0 [skip ci]
# [1.17.0](https://github.com/asepharyana/zesdex/compare/v1.16.1...v1.17.0) (2026-07-20)

### Features

* **token:** add refresh token verification to TokenService ([a046519](https://github.com/asepharyana/zesdex/commit/a04651905f4afd562b516c839449a2c813ce6627))
2026-07-20 05:30:00 +00:00
asepharyana a04651905f feat(token): add refresh token verification to TokenService
feat(bootstrap): create temporary settings and config files to prevent data loss

refactor(edit_log): switch from Vec to VecDeque for efficient memory management

fix(gateway): ensure store directories are created before starting the API server

refactor(bgbash): implement a global singleton for BashControl

feat(auth): enhance session authentication middleware to use SessionRepository

fix(edit_log_repo): update to use VecDeque for in-memory edit log storage

fix(memory_repo): add newline escaping for frontmatter fields

fix(session_lock_repo): improve error handling for lock file operations

fix(bash_tools): prevent path traversal in job_id argument

refactor(delete): enforce empty directory deletion in file system tools

fix(edit): optimize string replacement to only replace the first occurrence

fix(git_cred): improve credential management with piped input to git commands

feat(git_operator): add safety filter to block destructive git operations

fix(shell): register background jobs in Bash control

feat(spawn): add access tier specification for pipeline stages

refactor(hive_mind): run directives concurrently for improved performance

fix(auth): update refresh token verification in the refresh handler

fix(chat): optimize LLM client usage based on model matching

fix(conversations): enhance message deletion to target specific indices

feat(api): add JWT authentication middleware for all API routes

fix(state): implement refresh token verification in JwtTokenService

fix(daemon): improve usage tracking with saturating addition

fix(tui): handle compacted messages in the TUI state management
2026-07-20 12:26:10 +07:00
semantic-release-bot 600ea041ef chore(release): 1.16.1 [skip ci]
## [1.16.1](https://github.com/asepharyana/zesdex/compare/v1.16.0...v1.16.1) (2026-07-20)
2026-07-20 05:06:27 +00:00
asepharyana 1ec2aa136a refactor: improve code readability and consistency across multiple files 2026-07-20 12:02:50 +07:00
semantic-release-bot 4ced6681c2 chore(release): 1.16.0 [skip ci]
# [1.16.0](https://github.com/asepharyana/zesdex/compare/v1.15.2...v1.16.0) (2026-07-20)

### Features

* **tui:** add usage overlay and sidebar for displaying usage statistics and tasks ([da2ed6d](https://github.com/asepharyana/zesdex/commit/da2ed6da25953b823354cc5deaa7b404b7b13cb0))
* **tui:** enhance agent turn with tool descriptions and sanitize arguments ([08e2f99](https://github.com/asepharyana/zesdex/commit/08e2f9998d3693e4cd57225491359c762d03f1d9))
* **tui:** implement agent turn engine for background processing and enhance input handling ([792695b](https://github.com/asepharyana/zesdex/commit/792695b65a393cfc54efe353480b7831e91544b5))
2026-07-20 04:33:19 +00:00
asepharyana 08e2f9998d feat(tui): enhance agent turn with tool descriptions and sanitize arguments 2026-07-20 11:29:33 +07:00
asepharyana 792695b65a feat(tui): implement agent turn engine for background processing and enhance input handling 2026-07-20 10:55:09 +07:00
asepharyana da2ed6da25 feat(tui): add usage overlay and sidebar for displaying usage statistics and tasks
feat(tui): implement status bar with connection and turn state indicators
feat(tui): create workflow panel for agent status and progress visualization
feat(web): introduce web frontend interface with static file serving
feat(ws): add WebSocket interface for real-time communication and session management
2026-07-20 09:04:57 +07:00
asepharyana bceba665c0 refactor: remove unused tracing imports across multiple files 2026-07-20 07:02:55 +07:00
asepharyana 714b4617dd Refactor CMS and IAM modules: restructure presentation and command layers
- Removed HTTP adapter module from CMS infrastructure.
- Updated CMS infrastructure module to exclude HTTP.
- Introduced presentation layer in CMS with DTOs and handlers for REST API.
- Added command types for CMS domain operations to encapsulate input data.
- Created typed error handling for CMS presentation layer.
- Implemented handlers for CMS REST API endpoints.
- Removed HTTP DTOs and handlers from IAM infrastructure.
- Introduced command types for IAM domain operations.
- Created presentation layer in IAM with DTOs and handlers for OAuth flow.
- Implemented typed error handling for IAM presentation layer.
2026-07-20 06:53:01 +07:00
asepharyana e9a8e93c83 Refactor session ID handling and improve error management
- Introduced `SessionId` newtype for validated session identifiers, ensuring safety against path traversal attacks.
- Updated session repository methods to accept `SessionId` instead of raw strings, enhancing type safety.
- Removed redundant error handling in repository methods by leveraging the new `Error` type from `zesdex_utils`.
- Simplified atomic JSON write operations by eliminating unnecessary error conversions.
- Enhanced integer casting with a new `CastOr` trait for safer narrowing conversions.
- Removed deprecated error handling code and consolidated error types across the codebase.
- Updated HTTP handlers to utilize the new session ID validation, improving overall robustness.
2026-07-20 06:39:30 +07:00
asepharyana ab1a54b72e Refactor error handling in IAM and CMS crates
- Introduced `RepositoryError` and `ServiceError` enums in both IAM and CMS domains for better error management.
- Updated domain traits and services to return specific error types instead of `anyhow::Result`.
- Enhanced session and OAuth repository implementations to handle errors more explicitly.
- Refactored session service methods to return `Result<T, ServiceError>` for improved error handling.
- Updated HTTP handlers to utilize the new error types.
- Modified password hashing functions to run in a blocking context using `tokio::task::spawn_blocking`.
- Added tests for new error handling mechanisms and async password functions.
2026-07-20 06:14:23 +07:00
asepharyana 5aaedbf787 docs: tambah doc comment, logging, dan inline comments di semua 255 file
Meliputi:
- File-level //! doc comment: tujuan file, alur kerja, komponen utama
- Function-level /// doc comment: apa, parameter, return, flow, edge cases
- Struct/enum/trait /// doc comment: peran, field docs
- Tracing logging (tracing::info!/debug!/trace!/warn!/error!) di setiap fungsi
- Inline comments untuk variable dan branching logic penting
- Seluruh 8 crates di workspace: zesdex-backend, zesdex-cms, zesdex-entities,
  zesdex-iam, zesdex-infra, zesdex-ipc, zesdex-middleware, zesdex-utils
- Build: 0 errors, 242/242 tests passed
2026-07-19 17:05:47 +07:00
semantic-release-bot 6680795ce7 chore(release): 1.15.2 [skip ci]
## [1.15.2](https://github.com/asepharyana/zesdex/compare/v1.15.1...v1.15.2) (2026-07-17)

### Bug Fixes

* correct jitter range to ±25% and fix abort.rs doc — review findings ([9b6e51d](https://github.com/asepharyana/zesdex/commit/9b6e51dc677cc4b798532f1e63335785f2f7bbbf))
2026-07-17 20:21:33 +00:00
asepharyana 9b6e51dc67 fix: correct jitter range to ±25% and fix abort.rs doc — review findings 2026-07-18 03:18:27 +07:00
asepharyana 40524f930f refactor: use mark_dirty() helper di input.rs, DRY 22 lokasi 2026-07-18 03:18:27 +07:00
asepharyana 086cb86f0d refactor: extract is_aborted helpers, DRY 16 call sites 2026-07-18 03:18:27 +07:00
asepharyana ff47bffe0c refactor: reuse is_auth_error from provider.rs, DRY backend retry logic 2026-07-18 03:18:27 +07:00
asepharyana 431c8d3b89 refactor: unify 3 backoff implementations into shared helper 2026-07-18 03:18:27 +07:00
asepharyanaandClaude Opus 4.8 e32501ee59 refactor: extract session_id extraction helper, DRY auth.rs
Extract duplicated session ID extraction + validation logic from
SessionAuthMiddleware::call() and require_session() into two shared
helper functions: extract_session_id and validate_and_build_identity.

Removes ~60 lines of duplicated code while preserving behavior:
- Both call sites now rely on the same extraction/validation path
- User-Agent default remains empty string (existing behavior unchanged)
- Error response format (401 with header/validation messages) unchanged

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 03:18:27 +07:00
asepharyanaandClaude Opus 4.8 7d8487cefb refactor: consolidate #![allow(clippy::cast_*)] to crate roots
Add the cast-allow block to zesdex-entities/src/lib.rs and
zesdex-utils/src/lib.rs (which lacked it), then remove from
65 sub-files across all 8 crates. Build and all 223 tests
continue to pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 03:18:27 +07:00
asepharyanaandClaude Opus 4.8 4cd38c9291 refactor: extract write_json_atomic helper, DRY 8 call sites
Move the crash-safe write-then-rename pattern into
zesdex-utils::write_json_atomic and apply it across:

- zesdex-cms: app_config_repo, conversation_repo, settings_repo
- zesdex-iam: oauth_repo, session_repo
- zesdex-entities: Conversation::save_conversation, Session::save

Excluded (non-JSON format):
- rewind_blob_repo (binary blob)
- memory_repo (markdown + frontmatter, not JSON)
- session_lock (PID string, not JSON)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 03:18:27 +07:00
asepharyanaandClaude Opus 4.8 9a6ab62562 refactor: DRY cleanup — extract shared helpers, remove duplication across tools, LSP, overlays, and runtime
Eliminate ~500 lines of duplicate code across 31 files by extracting
shared functions, helpers, and consolidating repeated patterns.

Highlights:
- Toast helpers (toast_info/success/warning/error) on AppStateRest
- push_event() helper for turn-event queue (19 callers consolidated)
- log_write_edit_tool() shared fn (turn.rs + engine.rs ~50 lines saved)
- resolve_api_key() shared fn (spawn.rs + provider.rs)
- LSP call_positional() helper on LspClient
- lsp_cursor_params() shared schema for 4 tool files
-overlay_block() helper for consistent overlay title/border styling
- cycle_selected_index(), path_not_found/a_directory() helpers
- mark_dirty(), save_settings() on AppStateRest
- Remove redundant Err(e) => Err(e) arms in LSP tools
- Consolidate generate_workspace_tree (turn.rs → workspace.rs)
- Simplify background-review wrapper args in auto/mod.rs

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 03:18:27 +07:00
asepharyana b02754acd2 refactor: implement retry logic with exponential backoff and jitter for subagent and provider calls 2026-07-18 03:18:27 +07:00
semantic-release-bot b3c5b2a57b chore(release): 1.15.1 [skip ci]
## [1.15.1](https://github.com/asepharyana/zesdex/compare/v1.15.0...v1.15.1) (2026-07-17)
2026-07-17 03:32:34 +00:00
asepharyana 796bb09c5b refactor: enhance message shaping with progressive summarization and improved handling of dropped messages 2026-07-17 10:29:52 +07:00
asepharyana 5aad7e1eb1 refactor: streamline token counting and message shaping logic 2026-07-17 10:29:52 +07:00
semantic-release-bot 0dfde96f81 chore(release): 1.15.0 [skip ci]
# [1.15.0](https://github.com/asepharyana/zesdex/compare/v1.14.0...v1.15.0) (2026-07-17)

### Bug Fixes

* **cms:** perbaiki serde default hive_mind_node_timeout_ms & toleransi parse gagal di Settings ([6d41ffc](https://github.com/asepharyana/zesdex/commit/6d41ffc587f6f8de5bb4757c7eb8d69077831057))
* **cms:** satukan ChatMessage/Role Conversation dengan tipe kanonik zesdex-entities ([b272858](https://github.com/asepharyana/zesdex/commit/b272858edbe36af0b2eca119ff5b132de8dadce9))
* **iam:** redirect_uri dinamis + validasi CSRF state di OAuthServiceImpl ([be278f8](https://github.com/asepharyana/zesdex/commit/be278f8b1c2bc1295368e49c38622ef2bc3ed9ee))
* **iam:** set permission 0600 pada file token OAuth ([f2d97fb](https://github.com/asepharyana/zesdex/commit/f2d97fb17dcf4f52123da89532d7964ed8f8124c))
* **middleware:** jangan percaya header X-Forwarded-For/X-Real-IP secara default di rate limiter ([4dc4f80](https://github.com/asepharyana/zesdex/commit/4dc4f80fa344d894c2ce62f75d239847cd13001a))

### Features

* **cms:** implement RewindBlobRepository for managing binary blobs ([22dd6fd](https://github.com/asepharyana/zesdex/commit/22dd6fdda7d0c8eabfce296bbad53587204c69fa))
* **iam:** implementasikan FileSystemSessionLockRepository (sebelumnya belum ada implementasi) ([ff6a749](https://github.com/asepharyana/zesdex/commit/ff6a749c1149d890173922fbff76facef50a93b0))
* **iam:** port LoopbackServer OAuth callback listener dari zesdex-backend ([910aa5e](https://github.com/asepharyana/zesdex/commit/910aa5e071911f158609c4dd8985f776d8d9235f))
* **iam:** tambahkan CSPRNG (OsRng) untuk token state/PKCE ([5ede65f](https://github.com/asepharyana/zesdex/commit/5ede65f454b08303f588754a208dca0c37d3ce34))
2026-07-17 02:20:51 +00:00
asepharyana 9a67137954 refactor: massive codebase restructuring — naming, splitting, DRY
Crate renames:
  - zesdex-entities::seaorm → domain (misleading name, no SeaORM used)
  - zesdex-dto → merged into zesdex-entities (100% re-exports)
  - zesdex-libs → zesdex-infra (vague name)

Module renames:
  - app/harness → guard (misleading: safety gatekeeper, not test harness)
  - runtime/commands → action_dispatch (name clashed with controller/command)
  - resources → prompts (embedded prompt text, not general resources)
  - tool/seqthink → sequential_think (unreadable abbreviation)
  - msglog/query → insert (module only inserts, never queries)

Dead code removal:
  - app/mode/help.rs (orphaned — not declared in mod.rs)
  - app/mode/loading.rs (orphaned — not declared in mod.rs)

File splitting (71 new files, avg ~115 lines/file):
  - app/runtime/actions/: 1→8 files (was 2030 lines)
  - view/overlays/: 1→16 files (was 1167 lines)
  - tool/lsp/: 1→8 per-tool files (was 909 lines)
  - main.rs: 1→5 files (session, daemon, attach, event_loop)
  - workflow/engine + hive_mind: 2→10 files
  - subagent/engine + auto: 2→9 files
  - lsp/provisioner: 1→5 files
  - review/: 1→6 files
  - guard/: 1→2 files (extracted patterns)
  - state/misc: 1→3 files (input, scroll)
  - mcp/: 1→3 files (transport, adapter)
  - stream/json_repair extracted from turn.rs

DRY:
  - Pattern constants (STUB_PATTERNS etc) in guard/patterns shared with subagent
  - 3 near-identical background spawners → 1 generic + thin wrappers
  - Shared spawn_subagent_with_drain() extracted
  - Shared create_session() in main
  - write_osc52 deduplicated

Bug fixes:
  - archive_message(): sess.db → db (wrong variable name)
  - execute_one_tool(): wrong parameter name
  - check_credential_read() function was missing (restored from test expectations)
2026-07-17 09:08:41 +07:00
asepharyana 1f0ae9f551 Refactor and clean up code across multiple modules
- Simplified token type assignment in OAuth service.
- Removed unused session_lock module and re-exported Session from zesdex_entities.
- Cleaned up session entity by removing unnecessary comments and code.
- Consolidated session handling in HTTP handlers for better readability.
- Improved formatting and readability in OAuth repository tests.
- Enhanced session lock repository with clearer match statements.
- Streamlined session repository error handling.
- Refined RNG tests for better clarity.
- Adjusted module visibility and organization in lib.rs.
- Updated IPC client and connection code for better error handling and clarity.
- Improved frame handling in IPC for better readability.
- Organized module imports and added test utilities for IPC.
- Enhanced database connection error handling.
- Simplified JWT token creation error handling.
- Improved password verification error handling.
- Cleaned up state management code for better readability.
- Refactored middleware for session authentication and rate limiting.
- Simplified clipboard utility for better error handling.
- Enhanced logging initialization for better error reporting.
- Improved pagination utility with clearer method annotations.
- Cleaned up sanitization functions for filenames and paths.
- Enhanced slug generation functions for better clarity and usability.
2026-07-17 09:08:41 +07:00
asepharyana 22dd6fdda7 feat(cms): implement RewindBlobRepository for managing binary blobs 2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 b272858edb fix(cms): satukan ChatMessage/Role Conversation dengan tipe kanonik zesdex-entities
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 3f79b283e2 chore: hapus entitas settings/app_config/memory/edit_log lama di zesdex-entities yang sudah digantikan zesdex-cms
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 9618ef413b refactor(backend): alihkan EditLog ke zesdex-cms JsonlEditLogRepository
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 0ad3b0e539 refactor(backend): alihkan Memory ke zesdex-cms MarkdownMemoryRepository
Ganti semua pemanggilan Memory::read/write/remove/list di zesdex-backend
dengan MarkdownMemoryRepository dari zesdex-cms. Hapus re-export
model::memory yang sudah tidak dipakai.

Method mapping: read -> load, write -> save, remove -> delete, list -> list.
Import trait MemoryRepository untuk method resolution.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 dc9fd4dbd1 refactor(backend): alihkan AppConfig ke zesdex-cms JsonAppConfigRepository
Semua pemanggilan AppConfig::load() diganti dengan
JsonAppConfigRepository + AppConfigRepository trait.
Re-export model::app_config dihapus dari model/mod.rs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 8e6acc30d5 refactor(backend): alihkan Settings ke zesdex-cms JsonSettingsRepository
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 6d41ffc587 fix(cms): perbaiki serde default hive_mind_node_timeout_ms & toleransi parse gagal di Settings
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 f51a32569f chore: hapus implementasi OAuth/session lama yang sudah digantikan zesdex-iam
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 add6845edf refactor(backend): alihkan manajemen session ke zesdex-iam (SessionRepository/SessionLockRepository)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 4ab812d93b refactor(backend): alihkan run_oauth_flow ke zesdex-iam OAuthServiceImpl
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 ff6a749c11 feat(iam): implementasikan FileSystemSessionLockRepository (sebelumnya belum ada implementasi)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 f2d97fb17d fix(iam): set permission 0600 pada file token OAuth
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 be278f8b1c fix(iam): redirect_uri dinamis + validasi CSRF state di OAuthServiceImpl
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 910aa5e071 feat(iam): port LoopbackServer OAuth callback listener dari zesdex-backend
Duplikasi verbatim dari crates/zesdex-backend/src/service/oauth/loopback.rs
ke zesdex-iam untuk sentralisasi primitif OAuth.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyana 5ede65f454 feat(iam): tambahkan CSPRNG (OsRng) untuk token state/PKCE 2026-07-17 09:08:41 +07:00
asepharyanaandClaude Sonnet 5 4dc4f80fa3 fix(middleware): jangan percaya header X-Forwarded-For/X-Real-IP secara default di rate limiter
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-17 09:08:41 +07:00
asepharyana 3401d63063 docs(shell): perbaiki doc comment shell_filter yang menyesatkan soal credential-read 2026-07-17 09:08:41 +07:00
asepharyana be0a9582bb refactor: migrate monolithic crate to Cargo Workspace with Clean Architecture
Transform the single binary crate into a 9-crate workspace monorepo:

- Root Cargo.toml as [workspace] manager with resolver = "2"
- zesdex-entities: Domain entity types (session, settings, store, message, etc.)
- zesdex-utils: Pure utility functions (error, logger, pagination, slug, clipboard)
- zesdex-dto: Data Transfer Objects for LLM provider API communication
- zesdex-ipc: Unix-socket IPC layer (client/server/framing/protocol)
- zesdex-iam: Identity & Access Management (Clean Architecture: domain/application/infrastructure)
- zesdex-cms: Content Management (Clean Architecture: domain/application/infrastructure)
- zesdex-middleware: HTTP middleware (Auth, CORS, Rate Limiting)
- zesdex-libs: Composition root (AppContext, DB init, JWT, Argon2)
- zesdex-backend: Main binary entry point + seed/migrate binaries
- DevOps: Dockerfile, docker-compose, Nix (flake/shell/default), CI/CD updates
- Remove dead root src/ and src-misc/ directories

All crate re-exports maintain backward compatibility with original
crate::model::*, crate::dto::*, crate::ipc::* module paths.
Feature crates enforce strict layer separation: domain -> application
-> infrastructure with generic trait-based dependency injection.
2026-07-17 09:08:41 +07:00
semantic-release-bot 86cc412395 chore(release): 1.14.0 [skip ci]
# [1.14.0](https://github.com/asepharyana/zesdex/compare/v1.13.0...v1.14.0) (2026-07-16)

### Bug Fixes

* **context:** batasi squash_log ke tool bash saja ([7d99cd6](https://github.com/asepharyana/zesdex/commit/7d99cd66187b3fafb2ddeb19d8e8aa7db139df64))
* **context:** perbaiki fixture test shaping agar men-drop pesan lama ([8bb697a](https://github.com/asepharyana/zesdex/commit/8bb697a53fe89c9d00f709df33ccbd7944482f07))
* **plan:** perbaiki bug entropy gate dan fixture test squash.rs ([ceb8479](https://github.com/asepharyana/zesdex/commit/ceb84790bb741352b2b3416cda4bdbc6b42767c9))
* **plan:** perbaiki fixture test array-cutoff squash_json ([7ffdf44](https://github.com/asepharyana/zesdex/commit/7ffdf441355cda0972b849bc9b475d3de8f39843))
* **plan:** perbaiki fixture test shaping agar benar-benar men-drop pesan ([3a6e32d](https://github.com/asepharyana/zesdex/commit/3a6e32d8f3f0dd47d2c5ff63ab0c184b0ee4a6bc))
* **plan:** perkuat fixture test log agar benar-benar uji squash_log ([682007a](https://github.com/asepharyana/zesdex/commit/682007a2507f209c2378796442d4bc879516191a))

### Features

* **context:** tambah context::dedup untuk hasil tool yang berulang ([12a03fd](https://github.com/asepharyana/zesdex/commit/12a03fd3d1123c7a88289e44064537a71b9f574b))
* **context:** tambah context::shaping (port dari shortsend) ([e080d9f](https://github.com/asepharyana/zesdex/commit/e080d9fc6b7daf2ab37fb242d03a3f64e8629acc))
* **context:** tambah context::squash untuk kompresi hasil tool ([ea0b498](https://github.com/asepharyana/zesdex/commit/ea0b4988299894e4588d851ebc91704a9e73bc73))
* **context:** tambah context::tokens dengan tiktoken-rs ([c219b6e](https://github.com/asepharyana/zesdex/commit/c219b6ec58ddad4770e491a48bbe1b6e3d0c8884))
* **context:** tambah context::window::resolve ([059ca8e](https://github.com/asepharyana/zesdex/commit/059ca8ea246768dbec06ae5336433853e4276cec))
* **runtime:** kompres hasil tool lewat squash sebelum masuk context ([96084f7](https://github.com/asepharyana/zesdex/commit/96084f74621636a72c209388580d0ebbb335d198))
* **settings:** tambah mode ringkas opsional (concise_output) ([d6de973](https://github.com/asepharyana/zesdex/commit/d6de9735aba7745f5f57a8e7a5e625613c1a2569))
2026-07-16 01:01:45 +00:00
asepharyana 1afca97c1b refactor(subagent): remove unused step parameter from SubagentEvent 2026-07-16 07:58:34 +07:00
asepharyana a00aa9bec8 Refactor view modules for improved readability and consistency
- Updated markdown rendering logic to use more concise methods for obtaining vector lengths.
- Changed review status display to use the correct flag from settings.
- Cleaned up sidebar rendering code for better formatting and readability.
- Enhanced status bar rendering with improved string formatting and consistent style application.
- Refined workflow panel rendering, ensuring consistent style usage and improved readability.
- Added architecture overview and detailed documentation for backend, data, dependencies, and frontend structures.
2026-07-16 07:56:11 +07:00
asepharyanaandClaude Sonnet 5 7d99cd6618 fix(context): batasi squash_log ke tool bash saja
Ditemukan reviewer whole-branch final: looks_log_shaped murni berbasis
konten (>=3 baris berpola error/warn/fail), jadi hasil grep/search yang
match ke kode error-handling ikut lolos ambang itu -- padahal
squash_log punya cap keras 20 error + 10 warning tanpa budget byte,
diam-diam membuang match yang sah di luar cap itu. Sekarang hanya tool
bash (penghasil log sungguhan) yang boleh lewat squash_log; tool lain
yang kebetulan konten-nya mirip log jatuh ke squash_generic yang lebih
longgar (head/tail + budget byte). Tambah test regresi yang membedakan
kedua jalur lewat retensi baris terakhir.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:56:11 +07:00
asepharyana e075eb7acc style(context): bersihkan warning clippy pedantic di squash.rs dan dedup.rs
Perbaikan gaya murni (format! di-append ke String -> write!, syntax
perbandingan yang lebih jelas, backtick di doc comment) tanpa
mengubah perilaku -- semua test tetap hijau.
2026-07-16 07:56:11 +07:00
asepharyana d6de9735ab feat(settings): tambah mode ringkas opsional (concise_output)
Off by default, diaktifkan lewat settings.json (belum ada UI toggle —
sama seperti review_enabled/session_archive_enabled/lsp_auto_provision
yang juga cuma bisa diedit manual hari ini). Saat aktif, system prompt
diberi instruksi menulis ringkas, dengan pengecualian eksplisit untuk
konfirmasi operasi destruktif dan peringatan keamanan yang tetap harus
detail penuh.
2026-07-16 07:56:11 +07:00
asepharyana 85d16ebe97 refactor(status): pakai context::tokens dan context::window
Status bar sekarang memakai penghitungan token yang sama persis dengan
compaction (bukan heuristik /4 terpisah), dan selalu menampilkan angka
context window nyata alih-alih '?' saat model role tidak override
context_window secara eksplisit — konsisten dengan fallback yang
sudah dipakai compaction sendiri.
2026-07-16 07:56:11 +07:00
asepharyana 96084f7462 feat(runtime): kompres hasil tool lewat squash sebelum masuk context
Salinan yang dikirim ke UI (TurnEvent::ToolResult) tetap utuh; hanya
salinan yang masuk riwayat percakapan (dikirim ke LLM) yang dikompres,
supaya user tetap melihat output tool apa adanya.
2026-07-16 07:56:11 +07:00
asepharyanaandClaude Sonnet 5 82c024a854 docs(runtime): perbarui doc comment run_agent_turn yang basi
Masih menyebut shortsend padahal modul itu sudah dihapus dan diganti
context::dedup/context::shaping di commit sebelumnya.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:56:11 +07:00
asepharyana 78e402cf14 refactor(runtime): pindah ke context::, perbaiki asimetri /compact manual
Loop auto-compaction sekarang selalu menjalankan dedup tiap iterasi
lalu shaping lewat context::, menggantikan shortsend:: yang dihapus.

Action::Compact tadinya berjalan sinkron dan selalu client: None,
sehingga hasil compact manual tidak pernah diringkas LLM (beda dengan
compaction otomatis di tengah turn). Sekarang /compact jalan di
thread background seperti spawn_turn, sehingga bisa memanggil LLM
untuk meringkas riwayat yang dibuang — perilaku manual dan otomatis
jadi setara.

Ekstrak resolve_llm_client_config() dari spawn_turn supaya logika
resolusi api_key/model/base_url tidak dua kali.
2026-07-16 07:56:11 +07:00
asepharyanaandClaude Sonnet 5 3a6e32d8f3 fix(plan): perbaiki fixture test shaping agar benar-benar men-drop pesan
Ditemukan implementer Task 5: fixture pesan pendek (~8 token nyata
lewat tiktoken untuk 20 pesan = ~160 token) tidak pernah melebihi
target 700 token (70% dari max_wire_tokens=1000), jadi force=true pun
tidak pernah men-drop satu pesan pun -- test placeholder-summary dan
keeps-most-recent lulus secara vakum tanpa benar-benar menguji jalur
drop. Diverifikasi ulang dengan context::tokens::count_tokens nyata:
fixture baru (20 pesan ~49 token = ~980 token total) melebihi target
700 dengan nyaman.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:55:48 +07:00
asepharyana e080d9fc6b feat(context): tambah context::shaping (port dari shortsend)
Perilaku should_shape/shape_messages tidak berubah, hanya sumber
penghitungan token yang sekarang lewat context::tokens (tiktoken-rs)
menggantikan heuristik char/3 bawaannya sendiri.
2026-07-16 07:55:48 +07:00
asepharyana ea0b498829 feat(context): tambah context::squash untuk kompresi hasil tool
Kompresi per-jenis-konten (JSON: pertahankan struktur & value pendek/
entropi tinggi, buang value panjang bertele-tele; log: simpan baris
error/warning berskor tertinggi + konteks sekitarnya; generic: potong
importance-ranked) untuk hasil tool di atas 1.5KB. Tool read dikecualikan
total karena isinya harus tetap byte-exact untuk edit selanjutnya.
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 682007a250 fix(plan): perkuat fixture test log agar benar-benar uji squash_log
Ditemukan lewat trace manual (bukan implementer): fixture lama cuma
punya 1 baris berpola error, di bawah ambang looks_log_shaped (>=3),
jadi tanpa sadar selalu jatuh ke squash_generic -- test tetap lulus
tapi tidak pernah menguji logika scoring/windowing squash_log sama
sekali. Tambah baris error/warning lagi supaya jalur squash_log
benar-benar terpakai.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 7ffdf44135 fix(plan): perbaiki fixture test array-cutoff squash_json
Ditemukan implementer Task 4 (percobaan kedua, lagi-lagi BLOCKED
sebelum commit apapun): test sebelumnya memakai string sama yang
panjang+entropi-rendah di semua 4 elemen array, jadi elemen index
0-2 pun ikut ter-elide oleh aturan panjang/entropi normal -- tidak
benar-benar menguji efek posisi array. Ganti fixture pakai string
berbentuk UUID (tanpa spasi, entropi tinggi) yang lolos aturan normal
di posisi manapun, supaya index 3 yang di-force-elide walau
identifier-shaped benar-benar membuktikan aturan "past index 3
regardless of length/entropy".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 ceb84790bb fix(plan): perbaiki bug entropy gate dan fixture test squash.rs
Ditemukan implementer Task 4 sebelum commit apapun (BLOCKED, bukan
kode salah): entropi Shannon mentah per-karakter tidak membedakan
prosa dari identifier acak — prosa berulang skor ~3.89 bit/char,
lebih tinggi dari UUID (~3.39). Tambah syarat "tanpa spasi" sebelum
cek entropi (meniru pre-filter headroom sendiri), turunkan ambang ke
3.0 pada skala mentah. Fixture test array JSON juga diperbesar
(repeat 5 -> 8) karena sebelumnya tidak pernah melewati SQUASH_FLOOR_BYTES
yang diasumsikan test itu sendiri.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 12a03fd3d1 feat(context): tambah context::dedup untuk hasil tool yang berulang
Panggilan tool read-only (read, grep, glob, dst) dengan argumen persis
sama menyisakan satu salinan penuh saja di context; entri lama diganti
placeholder tapi tool-call-nya sendiri tetap terlihat di riwayat. Tool
bersifat mutasi (write/edit/bash/dll) tidak pernah disentuh.

Jadikan tool_scope::READ_TOOLS pub supaya jadi satu-satunya sumber
klasifikasi read-only, dipakai ulang bukan didaftar dua kali.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 059ca8ea24 feat(context): tambah context::window::resolve
Satukan tiga salinan logika resolusi context_window (Action::Compact,
spawn_turn, status bar) yang sempat melenceng satu sama lain.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyana c219b6ec58 feat(context): tambah context::tokens dengan tiktoken-rs
Ganti tiga heuristik char-count (/3 di shortsend, /4 di loop turn, /4
di status bar) yang saling tidak konsisten dengan satu BPE tokenizer
nyata. tiktoken-rs membundel vocab lewat include_str! saat build, jadi
tidak ada akses jaringan saat runtime.
2026-07-16 07:49:43 +07:00
asepharyana 8bb697a53f fix(context): perbaiki fixture test shaping agar men-drop pesan lama
Fixture pendek sebelumnya (~8 token nyata per pesan lewat tiktoken)
tidak pernah melebihi target 700 token, jadi shape_messages tidak
pernah men-drop satu pesan pun -- satu test gagal, satu test lain
lulus secara vakum. Pakai fixture lebih panjang (~49 token/pesan)
yang diverifikasi melebihi target dengan nyaman.
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 75e9cadcd5 docs(plans): tambah plan implementasi rombak context & compaction
9 task: tokens.rs (tiktoken-rs), window.rs, dedup.rs, squash.rs,
shaping.rs (port shortsend), gabungan cutover+fix /compact manual,
wiring squash, status bar, dan mode ringkas opsional. Setiap task
diverifikasi dengan cargo build/test nyata, bukan -D warnings (yang
sudah merah di main karena warning pre-existing di file lain).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 c4e1d7c2b2 docs(specs): hapus facade prepare(), panggil modul context langsung
Facade cuma dipakai generically oleh satu caller (Action::Compact);
auto-loop tetap butuh kontrol per-stage sendiri. Selaras dengan prinsip
"No DI" di CLAUDE.md. dedup::collapse juga diubah mengembalikan
(Vec<ChatMessage>, bool) supaya caller tahu ada perubahan tanpa perlu
ChatMessage: PartialEq.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 da39033e81 docs(specs): kecualikan tool read dari squash
Ditemukan saat menulis plan: kompresi JSON pada hasil read akan merusak
byte-exactness yang dibutuhkan untuk edit selanjutnya jika file yang
dibaca kebetulan berformat JSON (package.json, tsconfig.json, dst).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
asepharyanaandClaude Sonnet 5 f62ac3f688 docs(specs): tambah desain rombak context & compaction
Rencana pengganti shortsend.rs dengan modul context/ (dedup, squash,
shaping, tokens, window) plus mode ringkas opsional, disusun dari studi
teknik rtk-ai/rtk, headroomlabs-ai/headroom, dan JuliusBrussee/caveman
(ide saja, tanpa menyalin kode).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 07:49:43 +07:00
semantic-release-bot aaab953d8a chore(release): 1.13.0 [skip ci]
# [1.13.0](https://github.com/asepharyana/zesdex/compare/v1.12.0...v1.13.0) (2026-07-14)

### Bug Fixes

* correct test assertion in dim_false_plain_text_has_no_color ([8d77e45](https://github.com/asepharyana/zesdex/commit/8d77e4565c2e3ca49058022c71e8277bdd790312))
* Remove orphaned span_text helper function from markdown test module ([199028f](https://github.com/asepharyana/zesdex/commit/199028fa2eb6056dad2bdf0753554939c153a163))
* **state:** cegah panic saat select mention dengan cursor stale ([dcfc5b9](https://github.com/asepharyana/zesdex/commit/dcfc5b9ec0d35f4c66b1648ded00f4f1279e0413))
* **state:** jangan bangun mention index di mode attach ([e0d0860](https://github.com/asepharyana/zesdex/commit/e0d0860d7ba0ab6a4c9b9f1562f6a767a6424d99))

### Features

* Deteksi trigger [@mention](https://github.com/mention) dan Tab-cycle di input handler ([2eebedf](https://github.com/asepharyana/zesdex/commit/2eebedfea56c7d4827f94a2739dbb5fa006e3069))
* **ipc:** dukung Ctrl+Y clipboard copy di mode daemon/attach ([472162d](https://github.com/asepharyana/zesdex/commit/472162d135478666913a888a68867e635e50d14a))
* Judul dropdown autocomplete mengikuti jenisnya (Commands vs Files) ([7f2509e](https://github.com/asepharyana/zesdex/commit/7f2509ecd2688495545333debee0c81016b28641))
* **state:** Alirkan mention_index lewat ToolCtx dan AppStateRest, bangun index di background thread ([93be92a](https://github.com/asepharyana/zesdex/commit/93be92a5fb8644c9020478c49421585ade2d0fd1))
* Tambah Ctrl+Y untuk menyalin pesan assistant terakhir ([d93bdba](https://github.com/asepharyana/zesdex/commit/d93bdba59b7dd14b4a76dc91c6b7f70a3c0f721c))
* Tambah field pending_clipboard_copy di MiscState ([3b6abd9](https://github.com/asepharyana/zesdex/commit/3b6abd920ea92329ebcf888c3bb50470675c4152))
* Tambah helper truncate_diff untuk membatasi panjang diff ([5dd835f](https://github.com/asepharyana/zesdex/commit/5dd835ff244a138bb5f1a8dbfd7cf252c2671e5e))
* Tambah MentionIndex, AutocompleteKind, dan deteksi [@mention](https://github.com/mention) di InputState ([95cae8f](https://github.com/asepharyana/zesdex/commit/95cae8fd8a8ce737ba60c3ac8bea77f4c2e14b1a))
* Tambah write_osc52 dan salin ke clipboard di mode single-process ([71b1613](https://github.com/asepharyana/zesdex/commit/71b1613d8467cfcb2383b3fce153a25c7883ac3d))
* Tambahkan file baru ke mention_index saat tool write membuatnya ([930961b](https://github.com/asepharyana/zesdex/commit/930961bd85701ab8906b8d81095e46d3635a951d))
* Tampilkan unified diff pada hasil tool edit ([c3c0ef6](https://github.com/asepharyana/zesdex/commit/c3c0ef632a605d8bf32712049035e4fc814af9d5))
* Tampilkan unified diff saat tool write menimpa file yang sudah ada ([2bb8e6f](https://github.com/asepharyana/zesdex/commit/2bb8e6f2555eac01baf2311d41811afad4aa3041))
* **view:** Tambah parameter dim dan pewarnaan baris diff di markdown renderer ([683715c](https://github.com/asepharyana/zesdex/commit/683715cd7af77d87a2ae3834360bb6f7a4388bd0))
2026-07-14 23:39:22 +00:00
asepharyana e0d0860d7b fix(state): jangan bangun mention index di mode attach
AppStateRest::new() men-spawn thread ignore::Walk untuk mention_index
tanpa syarat, padahal mode --attach cuma dipakai untuk render lokal —
handle_key dan logika mention berjalan di sisi daemon lewat IPC, jadi
index di client attach tidak pernah dipakai. Ini bikin setiap
--attach melakukan full workspace walk (sampai 50.000 entry) sia-sia.

Pindahkan thread-spawn itu ke method terpisah
spawn_mention_index_build(), dipanggil eksplisit dari
run_single_process() dan run_daemon() setelah AppStateRest::new(),
tapi sengaja tidak dipanggil dari run_attach().
2026-07-15 06:32:57 +07:00
asepharyana dcfc5b9ec0 fix(state): cegah panic saat select mention dengan cursor stale
Cursor bisa berpindah (Left/Right) tanpa menutup dropdown mention,
sehingga mention_start jadi stale relatif ke cursor saat Enter
ditekan. select_autocomplete() lalu memanggil replace_range dengan
start > end dan panic (crash seluruh TUI, termasuk daemon). Tambah
guard: jika cursor < mention_start atau mention_start > buffer.len(),
tutup dropdown dan kembalikan false alih-alih menyambung range yang
tidak valid. Tambah regression test yang mereproduksi skenario ini.
2026-07-15 06:32:57 +07:00
asepharyana 472162d135 feat(ipc): dukung Ctrl+Y clipboard copy di mode daemon/attach
Tambah DaemonFrame::ClipboardCopy(String) supaya daemon bisa
mengirim teks pending_clipboard_copy ke attach client, yang
kemudian menulis sekuens OSC52 ke stdout-nya sendiri (bukan
stdout daemon yang tidak dimiliki terminal user).
2026-07-15 06:32:57 +07:00
asepharyana 71b1613d84 feat: Tambah write_osc52 dan salin ke clipboard di mode single-process 2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 d93bdba59b feat: Tambah Ctrl+Y untuk menyalin pesan assistant terakhir
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyana 3b6abd920e feat: Tambah field pending_clipboard_copy di MiscState 2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 7f2509ecd2 feat: Judul dropdown autocomplete mengikuti jenisnya (Commands vs Files)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 2eebedfea5 feat: Deteksi trigger @mention dan Tab-cycle di input handler
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 930961bd85 feat: Tambahkan file baru ke mention_index saat tool write membuatnya
Ketika write tool membuat file baru (bukan overwrite), path file
sekarang di-push ke mention_index untuk autocomplete @file mention.

- Capture file existence status sebelum write
- Push ke mention_index hanya untuk genuinely new files
- Add 2 tests: one untuk new file push, one untuk overwrite non-duplication

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyana 93be92a5fb feat(state): Alirkan mention_index lewat ToolCtx dan AppStateRest, bangun index di background thread
Menambahkan field mention_index: MentionIndex ke ToolCtx/ToolCtxBuilder dan
AppStateRest, mengikuti pola dir_cache yang sudah ada. AppStateRest::new()
sekarang men-spawn thread background yang men-walk setiap workspace root
via ignore::Walk, membangun daftar path file (dengan prefix [N] untuk root
selain yang pertama) dan mengisi mention_index — data ini yang akan dipakai
fitur autocomplete @file-mention.
2026-07-15 06:32:57 +07:00
asepharyana 95cae8fd8a feat: Tambah MentionIndex, AutocompleteKind, dan deteksi @mention di InputState
Menambahkan MentionIndex (indeks path file thread-safe untuk fitur
autocomplete @file-mention), enum AutocompleteKind untuk membedakan
dropdown slash-command dan file-mention, serta method baru pada
InputState: mention_query_at_cursor untuk deteksi token @mention di
posisi cursor, dan open_mention_autocomplete untuk fuzzy-match file
via nucleo-matcher. select_autocomplete kini kind-aware: menyisipkan
path file ke posisi mention alih-alih mengganti seluruh buffer.
2026-07-15 06:32:57 +07:00
asepharyana 5c413cf9a3 chore: Tambah dependency nucleo-matcher untuk fuzzy file matching 2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 c386030573 refactor: Pakai parameter dim render_markdown, hapus override style manual di chat
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 199028fa2e fix: Remove orphaned span_text helper function from markdown test module
The span_text function in src/view/markdown.rs's test module was no longer
called after the dim_false_plain_text_has_no_color test was fixed. With the
crate's dead_code = "deny" lint enabled, this unused function caused a compile
error. Removed it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 8d77e4565c fix: correct test assertion in dim_false_plain_text_has_no_color
The first assertion was checking span_text() which concatenates all spans
including trailing paragraph-end newlines, making the test guaranteed to fail.
Changed to check spans[0].content directly to verify the text span itself
contains 'hello world' with no color applied when dim=false.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyana 683715cd7a feat(view): Tambah parameter dim dan pewarnaan baris diff di markdown renderer
Tambahkan helper apply_dim dan diff_line_style, ubah signature
render_markdown untuk menerima flag dim, serta deteksi fence bahasa
diff sehingga baris +/-/@@ tetap berwarna meskipun pesan sedang
dirender dim (tampilan tool-output).
2026-07-15 06:32:57 +07:00
asepharyana 2bb8e6f255 feat: Tampilkan unified diff saat tool write menimpa file yang sudah ada 2026-07-15 06:32:57 +07:00
asepharyana c3c0ef632a feat: Tampilkan unified diff pada hasil tool edit 2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 5dd835ff24 feat: Tambah helper truncate_diff untuk membatasi panjang diff
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyanaandClaude Sonnet 5 0a24903eb0 chore: Tambah dependency similar untuk diff computation
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-15 06:32:57 +07:00
asepharyana de8e3703f2 docs: Perbaiki perintah cargo test --lib jadi cargo test (crate ini tanpa lib target) 2026-07-15 06:32:57 +07:00
asepharyana b7fc335bf5 docs: Tambah implementation plan untuk diff view, @mention, dan clipboard copy 2026-07-15 06:28:49 +07:00
asepharyana 821622e80d docs: Tambah spec desain clipboard copy via OSC52 2026-07-15 06:28:49 +07:00
asepharyana 8fbc51534d docs: Tambah spec desain fuzzy @file-mention autocomplete 2026-07-15 06:28:49 +07:00
asepharyana 3f284cbb9a docs: Tambah spec desain diff view untuk tool edit/write 2026-07-15 06:28:49 +07:00
semantic-release-bot 54484ed137 chore(release): 1.12.0 [skip ci]
# [1.12.0](https://github.com/asepharyana/zesdex/compare/v1.11.0...v1.12.0) (2026-07-14)

### Features

* Add mouse capture functionality to terminal and enhance markdown rendering with table support ([4428e8b](https://github.com/asepharyana/zesdex/commit/4428e8bc01c196415ac408a42f57305227a79760))
* Improve markdown rendering with enhanced line wrapping and indentation for code blocks ([b2e848d](https://github.com/asepharyana/zesdex/commit/b2e848d124e726c4d8b644d473e518398fab1dea))
2026-07-14 21:40:13 +00:00
asepharyana 9bf5236680 refactor: Remove obsolete documentation files and unused test for mouse functionality 2026-07-15 04:36:00 +07:00
asepharyana 4428e8bc01 feat: Add mouse capture functionality to terminal and enhance markdown rendering with table support 2026-07-15 04:36:00 +07:00
asepharyana b2e848d124 feat: Improve markdown rendering with enhanced line wrapping and indentation for code blocks 2026-07-15 04:36:00 +07:00
semantic-release-bot 3020a0431c chore(release): 1.11.0 [skip ci]
# [1.11.0](https://github.com/asepharyana/zesdex/compare/v1.10.0...v1.11.0) (2026-07-14)

### Features

* Enhance subagent tool output handling and clarify workflow directives ([6fbe1e2](https://github.com/asepharyana/zesdex/commit/6fbe1e2d1dc790ba2509803b3ab3a848d5b2a63b))
* Enhance token usage tracking and improve chat UI with emojis ([188e7cc](https://github.com/asepharyana/zesdex/commit/188e7cc9a9233140a5e4953e3f3ff66682914e42))
2026-07-14 20:43:21 +00:00
asepharyana 6fbe1e2d1d feat: Enhance subagent tool output handling and clarify workflow directives 2026-07-15 03:39:15 +07:00
asepharyana 9ba9a5048b refactor: Remove workflow-related commands and overlays from the application 2026-07-15 03:39:15 +07:00
asepharyana 188e7cc9a9 feat: Enhance token usage tracking and improve chat UI with emojis 2026-07-15 03:39:15 +07:00
semantic-release-bot 1a6a0c628e chore(release): 1.10.0 [skip ci]
# [1.10.0](https://github.com/asepharyana/zesdex/compare/v1.9.0...v1.10.0) (2026-07-14)

### Bug Fixes

* align format strings in sidebar Usage widget ([98615ca](https://github.com/asepharyana/zesdex/commit/98615ca5b9d896331a5a6d9af91035aca1f5e9d5))
* use {:>6}: for aligned colons in sidebar Usage widget ([f87ab13](https://github.com/asepharyana/zesdex/commit/f87ab133f1953633f66e21b9eaf7c4eb41291ccd))

### Features

* Implement lesson generation feature and update status display ([1c08b8e](https://github.com/asepharyana/zesdex/commit/1c08b8e4e9c3bb1318535a74c9812beb976df315))
2026-07-14 20:16:30 +00:00
asepharyana 1c08b8e4e9 feat: Implement lesson generation feature and update status display
- Added functionality to generate lessons based on code reviews, including prompts and instructions for the reviewer.
- Updated the `.gitignore` to exclude lesson documentation files.
- Removed the `/lesson` command from the help menu and command parsing.
- Enhanced the status bar to display a message when a lesson is being generated.
- Introduced a new `lesson_running` state to track lesson generation progress.
- Updated various components to handle the new lesson generation workflow, including subagent events and token usage tracking.
2026-07-15 03:11:55 +07:00
asepharyana f87ab133f1 fix: use {:>6}: for aligned colons in sidebar Usage widget
Colons are now at column 9 for all five lines (labels right-aligned
in 6-char field). Values start at column 10. Leading zeros retained
for minutes/seconds via {:02}.

   total: 0 tok
    main: 0 tok
   learn: 0 tok
   calls: 0
    time: 0h 06m 46s
2026-07-15 03:11:55 +07:00
asepharyana 98615ca5b9 fix: align format strings in sidebar Usage widget
All five lines now use consistent label-first '  {:<7} {}' pattern
with aligned colons (column 9) and values (column 10). Elapsed time
uses {:02} leading zeros for minutes/seconds.

Fixes malformed output where some lines used number-first order
('{} tok total') while others used label-first ('main: {} tok'),
causing visual misalignment in the ~28-char-wide sidebar column.
2026-07-15 03:11:55 +07:00
semantic-release-bot 5e6d6deeab chore(release): 1.9.0 [skip ci]
# [1.9.0](https://github.com/asepharyana/zesdex/compare/v1.8.0...v1.9.0) (2026-07-14)

### Bug Fixes

* **workflow:** import Color style for improved agent state rendering ([472c597](https://github.com/asepharyana/zesdex/commit/472c597c5e4ab12808a6bcd1899628bc7ab77186))

### Features

* **agent:** refine cognitive cycle plan with structured phases for exploration, planning, and execution ([c5253b2](https://github.com/asepharyana/zesdex/commit/c5253b2ca359d4dbed9445e04f1dec1a6bb37e8f))
* **subagent:** add progress event handling and formatting for subagent execution ([558908a](https://github.com/asepharyana/zesdex/commit/558908aef216e61a0a108083fbac5e02c31501dc))
* **subagent:** emit reasoning text as progress in StepCompleted events ([97aa75f](https://github.com/asepharyana/zesdex/commit/97aa75f2da37aee5fc7a0626fc396988f089fff2))
* **subagent:** include tool call arguments in ToolResult events and progress formatting ([a8adfcb](https://github.com/asepharyana/zesdex/commit/a8adfcbf6dc5411e977f22ac6b6ba023f563d7c9))
2026-07-14 19:29:20 +00:00
asepharyana c5253b2ca3 feat(agent): refine cognitive cycle plan with structured phases for exploration, planning, and execution 2026-07-15 02:25:15 +07:00
asepharyana a8adfcbf6d feat(subagent): include tool call arguments in ToolResult events and progress formatting 2026-07-15 02:25:15 +07:00
asepharyana 558908aef2 feat(subagent): add progress event handling and formatting for subagent execution 2026-07-15 02:25:15 +07:00
asepharyana 472c597c5e fix(workflow): import Color style for improved agent state rendering 2026-07-15 02:25:15 +07:00
asepharyana 97aa75f2da feat(subagent): emit reasoning text as progress in StepCompleted events 2026-07-15 02:25:15 +07:00
semantic-release-bot dfceb8acac chore(release): 1.8.0 [skip ci]
# [1.8.0](https://github.com/asepharyana/zesdex/compare/v1.7.0...v1.8.0) (2026-07-14)

### Features

* **tools:** require reason argument for delete and git_operator tools ([c6ab063](https://github.com/asepharyana/zesdex/commit/c6ab063c211fb858fd0e155883b9c47b345f0f8a))
2026-07-14 19:05:45 +00:00
asepharyana c6ab063c21 feat(tools): require reason argument for delete and git_operator tools 2026-07-15 02:01:24 +07:00
semantic-release-bot 2af8432ce4 chore(release): 1.7.0 [skip ci]
# [1.7.0](https://github.com/asepharyana/zesdex/compare/v1.6.0...v1.7.0) (2026-07-14)

### Bug Fixes

* **prompt:** perbarui system prompt dari CEO/company ke model hive-mind ([d392c4a](https://github.com/asepharyana/zesdex/commit/d392c4aa00154aae5a0f36db615f05adc385fdb5))
* **runtime:** add check for unconfigured provider to prevent misleading API errors ([181b512](https://github.com/asepharyana/zesdex/commit/181b5128ac1fba47627bf7b377358c782e3481b7))

### Features

* **install:** add installation script for building and symlinking the binary ([4eba9d0](https://github.com/asepharyana/zesdex/commit/4eba9d0a2fbe42b0383eaf872eaeace18cc59a92))
* **protocol:** add Paste request type for bracketed-paste events ([b92dab9](https://github.com/asepharyana/zesdex/commit/b92dab97e6efe1fd6f7c23b28310610c653a57b0))
* **provider:** enhance Claude provider configuration to support environment variable fallback ([4b16bc3](https://github.com/asepharyana/zesdex/commit/4b16bc31125018ad3d3e46706881596a226f5352))
* **runtime:** implement JSON repair function for truncated tool-call arguments ([e13f040](https://github.com/asepharyana/zesdex/commit/e13f04083313f3544bdb1a76b5ecd535ecf59e4f))
* **stream:** add method to detect incomplete tool calls and handle parsing errors ([732d603](https://github.com/asepharyana/zesdex/commit/732d6039dc23bc8ec323bc4f91be9a7131a61ef6))
2026-07-14 18:59:09 +00:00
asepharyana b92dab97e6 feat(protocol): add Paste request type for bracketed-paste events
feat(engine): summarize agent completion progress in UI notifications

feat(main): enable and disable bracketed paste support in terminal

fix(app_config): store API key from file as fallback for Claude provider

refactor(workflow): remove unnecessary card separator in workflow panel
2026-07-15 01:54:36 +07:00
asepharyana e13f040833 feat(runtime): implement JSON repair function for truncated tool-call arguments 2026-07-15 01:42:15 +07:00
asepharyana 4b16bc3112 feat(provider): enhance Claude provider configuration to support environment variable fallback 2026-07-15 01:06:36 +07:00
asepharyana 181b5128ac fix(runtime): add check for unconfigured provider to prevent misleading API errors 2026-07-15 00:59:32 +07:00
asepharyana 732d6039dc feat(stream): add method to detect incomplete tool calls and handle parsing errors 2026-07-15 00:49:50 +07:00
asepharyana 4eba9d0a2f feat(install): add installation script for building and symlinking the binary 2026-07-15 00:25:53 +07:00
asepharyana 7fccc16a54 refactor(engine, hive_mind): update terminology from 'agents' to 'drones' and enhance logging for clarity 2026-07-15 00:24:49 +07:00
asepharyana b5e3dfe4b1 refactor(hive_mind): enhance documentation for clarity and consistency in terminology 2026-07-15 00:22:59 +07:00
asepharyana 519be7559b refactor(prompts): update reviewer prompts to align with Hive's directive and contamination protocols 2026-07-15 00:20:41 +07:00
asepharyanaandClaude Sonnet 5 d392c4aa00 fix(prompt): perbarui system prompt dari CEO/company ke model hive-mind
src-misc/system-prompt.txt masih memakai framing lama "Zesdex Corp
CEO / 5 divisi" dan mereferensikan tool run_company_pipeline yang
sudah tidak ada, tertinggal saat commit 25f084f merombak arsitektur
ke hive-mind (CLAUDE.md, README.md, dan implementasi workflow_run
sudah diupdate saat itu, tapi file prompt utama ini terlewat).
Akibatnya AI membalas dengan persona CEO/company, bukan Core
Intelligence/hive-mind seperti didokumentasikan di README.md.

- system-prompt.txt: tulis ulang total ke model Core Intelligence /
  cognitive cycle plan / processing node / access tier, konsisten
  dengan CLAUDE.md dan tool hive_mind yang sebenarnya.
- system-tools.txt: tambah entri hive_mind dan read_findings yang
  sebelumnya tidak ada sama sekali di daftar tool.
- workflow.rs: perbaiki sisa teks "divisions/subagents" di deskripsi
  tool read_findings jadi "nodes/subagents".

Diverifikasi live: AI sekarang memperkenalkan diri sebagai "Core
Intelligence of Zesdex ... modeled as a hive-mind" alih-alih CEO.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:55:49 +07:00
semantic-release-bot 340ae2fde2 chore(release): 1.6.0 [skip ci]
# [1.6.0](https://github.com/asepharyana/zesdex/compare/v1.5.0...v1.6.0) (2026-07-14)

### Bug Fixes

* perbaiki 5 warning clippy pre-existing (base untuk TUI overhaul) ([6b58977](https://github.com/asepharyana/zesdex/commit/6b58977875f809f19cc2d7bb9b2a7dd057d0229e))
* **tui:** perbaiki isi overlay Todo dan Usage jadi tampilan detail nyata ([aaea300](https://github.com/asepharyana/zesdex/commit/aaea300699f7e76cdc689e225e7c4c3bc164e8d4))
* **tui:** perbaiki potensi terpotongnya baris token di widget Usage sidebar ([7fd55fa](https://github.com/asepharyana/zesdex/commit/7fd55fa86dfe8f9a4581f02fa9220cd5d1ba600c))
* **tui:** perbaiki rendering multi-baris pada pesan Tool ([2f1a4d8](https://github.com/asepharyana/zesdex/commit/2f1a4d85a1fdc9cbfb81912a3206c057ad9d1ed5))

### Features

* **tui:** ganti palet warna ke Tokyo Night ([7a9cb7b](https://github.com/asepharyana/zesdex/commit/7a9cb7bf342367c81fb4a1568675e46f132a8afc))
* **tui:** rombak rendering chat jadi format log rapat ([e34708a](https://github.com/asepharyana/zesdex/commit/e34708a3191bef63d191e76dee39a58a33e4ad5f))
* **tui:** tambah command /todo dan /usage untuk buka overlay ([aa2b6ac](https://github.com/asepharyana/zesdex/commit/aa2b6acb95f8518950b8b7d9c3c9e10968936162))
* **tui:** tambah dan pasang sidebar dashboard permanen ([31c01cd](https://github.com/asepharyana/zesdex/commit/31c01cdf1df6827c3a949820378c8b85ebcfdf87))
2026-07-14 16:45:55 +00:00
asepharyana 1010e44b22 Implement new feature for user authentication and improve error handling 2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 b355c9928e style(tui): hapus emoji dekoratif dari judul overlay
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 aaea300699 fix(tui): perbaiki isi overlay Todo dan Usage jadi tampilan detail nyata
Overlay Todo sebelumnya menampilkan jumlah pesan yang tidak relevan,
bukan isi task list. Overlay Usage sekarang pakai compute_usage_summary
yang sama dengan widget sidebar (DRY, angka konsisten).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 7fd55fa86d fix(tui): perbaiki potensi terpotongnya baris token di widget Usage sidebar
Baris pertama widget Usage sebelumnya bisa melebihi lebar kolom sidebar
(30 kolom) pada sesi dengan jumlah token besar, menyebabkan teks
terpotong diam-diam tanpa wrap. Sekarang dipecah jadi beberapa baris
pendek yang aman di lebar berapa pun yang realistis.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 31c01cdf1d feat(tui): tambah dan pasang sidebar dashboard permanen
Sidebar kanan permanen (Workflow/Tasks/Usage) menggantikan panel todo
ad-hoc yang lama. Widget baca state yang sudah ada, tidak ada perubahan
skema AppStateRest.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 aa2b6acb95 feat(tui): tambah command /todo dan /usage untuk buka overlay
Overlay Todo dan Usage sebelumnya tidak punya trigger sama sekali di
jalur interaksi normal (cuma bisa lewat restore snapshot sesi) --
sekarang mengikuti pola /workflow yang sudah ada.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 2f1a4d85a1 fix(tui): perbaiki rendering multi-baris pada pesan Tool
Konten Tool sebelumnya didorong sebagai satu Span tanpa split newline,
sehingga output tool multi-baris (stdout bash, hasil grep, diff)
tampil sebagai karakter \n literal alih-alih baris terpisah. Sekarang
mengikuti pola render_markdown + split_spans_into_lines yang sama
dengan role lain.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 e34708a319 feat(tui): rombak rendering chat jadi format log rapat
markdown.rs juga disesuaikan: indentasi paragraf/heading bawaannya
dilepas supaya tidak bentrok dengan indent PREFIX_WIDTH di chat.rs
(baris pertama vs baris wrap lanjutan jadi sejajar).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 6b58977875 fix: perbaiki 5 warning clippy pre-existing (base untuk TUI overhaul)
unnested_or_patterns, collapsible_if, items_after_statements, dan
case_sensitive_file_extension_comparisons di auto.rs, engine.rs, dan
actions/mod.rs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 7a9cb7bf34 feat(tui): ganti palet warna ke Tokyo Night
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
asepharyanaandClaude Sonnet 5 04e7ff9380 docs: tambah spec desain rombak TUI (Multi-Pane Dashboard, Tokyo Night)
Spec brainstorming untuk rombak total src/view + src/controller: layout
Multi-Pane Dashboard dengan sidebar Workflow/Tasks/Usage, palet Tokyo
Night, dan format chat inline rapat.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 23:41:53 +07:00
semantic-release-bot 7070c96460 chore(release): 1.5.0 [skip ci]
# [1.5.0](https://github.com/asepharyana/zesdex/compare/v1.4.0...v1.5.0) (2026-07-14)

### Bug Fixes

* **hive-mind:** ganti gerbang pipeline berbasis jumlah pesan dengan deteksi konvergensi sebelumnya ([5498088](https://github.com/asepharyana/zesdex/commit/5498088532314f8dbc005d5e8058c0170ca92320))
* **hive-mind:** gunakan flag SessionRuntime sebagai sinyal konvergensi otoritatif ([28e763a](https://github.com/asepharyana/zesdex/commit/28e763a695f56adfbecd4efb14edbde13bbd63dc))
* **hive-mind:** hapus penulisan docs/runs ganda dan sambungkan abort_flag ke tool hive_mind manual ([a125f5d](https://github.com/asepharyana/zesdex/commit/a125f5d4400b0c417ba4049e67480bd18479e90b))
* **hive-mind:** tambah timeout per-node dan jamin dokumentasi convergence tetap tertulis saat sintesis gagal ([b1c0265](https://github.com/asepharyana/zesdex/commit/b1c0265e8cdf9278664e64f77fbde4ec8c22fcfd))
* **subagent:** panic-proof overlap guards and update stale docs ([e023f2c](https://github.com/asepharyana/zesdex/commit/e023f2c5a8f036d89e925bb9ceec253343476a74))
* **subagent:** perbaiki filter is_production_code berbasis substring dan tambah pembatalan/anti-tumpang-tindih pada background review ([1039f67](https://github.com/asepharyana/zesdex/commit/1039f67c12749c6b2c93e3ab7037feded8ab01c6))
* **tui:** perbaiki roster workflow yang tidak pernah ter-reset karena substring "started" tidak pernah cocok ([fdd62f8](https://github.com/asepharyana/zesdex/commit/fdd62f830330b5b3e2b4f9fcc7274daf7f7842a5))

### Features

* **settings:** tambah hive_mind_node_timeout_ms dengan fallback serde default ([e2878a3](https://github.com/asepharyana/zesdex/commit/e2878a3d83f171aa181ac29ca689828e0cb1408f))
* **tool:** tambah abort_flag ke ToolCtx dan sambungkan dari session state ([79e2bfc](https://github.com/asepharyana/zesdex/commit/79e2bfcc9ca67424ca2b34a5652d3c2bb93291bf))
2026-07-14 03:59:10 +00:00
asepharyanaandClaude Sonnet 5 28e763a695 fix(hive-mind): gunakan flag SessionRuntime sebagai sinyal konvergensi otoritatif
Pesan sistem bertanda [Hive-Mind Consensus] hanya di-push ke variabel lokal
run_agent_turn dan diarsipkan ke SQLite, tidak pernah masuk ke
rt.messages lewat TurnEvent — sehingga hive_mind_already_ran selalu
memindai daftar pesan yang kosong dan gerbang "converge sekali per sesi"
tidak pernah aktif. Tambahkan SessionRuntime.hive_mind_converged yang
diset dari event TurnEvent::SystemNote { kind: "hive_mind_converged" }
setelah konvergensi selesai, disalurkan lewat TurnCtx, dan dijadikan
sinyal utama di run_agent_turn (pemindaian pesan lama tetap sebagai
fallback defensif).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 3e6f9a6a5f test(subagent): tambah pengujian invarian read⊆write⊆full pada tool_scope
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 e023f2c5a8 fix(subagent): panic-proof overlap guards and update stale docs
RunningGuard resets TEST_GEN_RUNNING/ARCH_REVIEW_RUNNING/SECURITY_REVIEW_RUNNING
via Drop so a subagent panic can no longer wedge that review kind disabled
for the rest of the process. Doc comments on run_subagent_with_retry and the
three spawn_background_* / spawn_all_background functions now describe the
abort_flag and overlap-guard behavior added in Task 7.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 1039f67c12 fix(subagent): perbaiki filter is_production_code berbasis substring dan tambah pembatalan/anti-tumpang-tindih pada background review
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 fdd62f8303 fix(tui): perbaiki roster workflow yang tidak pernah ter-reset karena substring "started" tidak pernah cocok
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 5498088532 fix(hive-mind): ganti gerbang pipeline berbasis jumlah pesan dengan deteksi konvergensi sebelumnya
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 a125f5d440 fix(hive-mind): hapus penulisan docs/runs ganda dan sambungkan abort_flag ke tool hive_mind manual
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 79e2bfcc9c feat(tool): tambah abort_flag ke ToolCtx dan sambungkan dari session state
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 b1c0265e8c fix(hive-mind): tambah timeout per-node dan jamin dokumentasi convergence tetap tertulis saat sintesis gagal
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 e2878a3d83 feat(settings): tambah hive_mind_node_timeout_ms dengan fallback serde default
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
asepharyanaandClaude Sonnet 5 6790fe481b docs: tambah rencana implementasi perbaikan hive-mind dan subagent
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-14 10:55:05 +07:00
semantic-release-bot d0c7fe4096 chore(release): 1.4.0 [skip ci]
# [1.4.0](https://github.com/asepharyana/zesdex/compare/v1.3.0...v1.4.0) (2026-07-14)

### Features

* **hive-mind:** implement multi-agent orchestration with cognitive cycles ([25f084f](https://github.com/asepharyana/zesdex/commit/25f084f9dbb5047c5c91aedcb582d35f4ff95395))
2026-07-14 01:16:53 +00:00
asepharyana 25f084f9db feat(hive-mind): implement multi-agent orchestration with cognitive cycles
- Introduced a new hive-mind architecture that allows the Core Intelligence to issue directives to anonymous processing nodes.
- Each node executes its directive and merges output into a collective state, visible to all nodes in real-time.
- Added support for dynamic cognitive cycles, enabling flexible task management.
- Implemented documentation generation for hive-mind runs, ensuring a durable record of decisions and actions.
- Refactored existing company pipeline tools to align with the new hive-mind structure, replacing division-specific prompts with a more generalized approach.
- Updated workflow rendering to accommodate hive-mind nodes and their system-assigned designations.
- Enhanced error handling and validation for cognitive cycle plans.
2026-07-14 08:12:43 +07:00
semantic-release-bot b1e0dcae14 chore(release): 1.3.0 [skip ci]
# [1.3.0](https://github.com/asepharyana/zesdex/compare/v1.2.0...v1.3.0) (2026-07-13)

### Features

* enhance edit logging in subagent execution and streamline edit tracking in run_agent_turn ([c60fadb](https://github.com/asepharyana/zesdex/commit/c60fadb88ae63788a5bbe3c3443e2ce826e5778f))
2026-07-13 07:51:20 +00:00
asepharyana c60fadb88a feat: enhance edit logging in subagent execution and streamline edit tracking in run_agent_turn 2026-07-13 14:47:03 +07:00
semantic-release-bot 4a297669b4 chore(release): 1.2.0 [skip ci]
# [1.2.0](https://github.com/asepharyana/zesdex/compare/v1.1.0...v1.2.0) (2026-07-13)

### Features

* enhance responsiveness by implementing abort checks in streaming API calls ([0d6f558](https://github.com/asepharyana/zesdex/commit/0d6f558b2bd0282a7a1695f7680ab1d1c6142579))
* refactor agent step limits and enhance workflow orchestration with new findings tool ([3b660e0](https://github.com/asepharyana/zesdex/commit/3b660e09a87f3e982db94f48d2282ddb63116341))
* remove pipeline command and refactor workflow execution to use custom specialists ([00e2913](https://github.com/asepharyana/zesdex/commit/00e29139c53c5fed4c13b0493297dd9da984460c))
* update overlay handling in apply_action and remove mouse capture from terminal execution ([2e351cc](https://github.com/asepharyana/zesdex/commit/2e351ccf6930ff4823f55b581308222229fe6684))
* update README and documentation for new tools and features ([1d50b94](https://github.com/asepharyana/zesdex/commit/1d50b94eec1ed82dfc40d43d41bd01aeb79edfe1))
2026-07-13 07:43:49 +00:00
asepharyana 2e351ccf69 feat: update overlay handling in apply_action and remove mouse capture from terminal execution 2026-07-13 14:39:39 +07:00
asepharyana 1d50b94eec feat: update README and documentation for new tools and features
- Updated README.md to reflect the addition of 3 new built-in tools, bringing the total to 37.
- Revised architecture documentation to indicate the increase in tool count.
- Enhanced backend documentation with updated line counts for various modules.
- Modified data documentation to change edit log format from JSON to JSONL.
- Updated dependencies documentation to reflect version upgrades for several crates.
- Improved prompts for auto-reviewer, division implementer, planner, tester, and quality reviewer to enforce stricter coding standards regarding linter bypasses.
- Refactored code in various modules to improve clarity and performance, including updates to error handling and tool execution logic.
- Added comprehensive tests for IPC frame serialization and deserialization.
2026-07-13 14:39:39 +07:00
asepharyana 00e29139c5 feat: remove pipeline command and refactor workflow execution to use custom specialists 2026-07-13 14:39:39 +07:00
asepharyana 3b660e09a8 feat: refactor agent step limits and enhance workflow orchestration with new findings tool 2026-07-13 14:39:39 +07:00
asepharyana 0d6f558b2b feat: enhance responsiveness by implementing abort checks in streaming API calls 2026-07-13 14:39:39 +07:00
457 changed files with 32463 additions and 20395 deletions
+94
View File
@@ -0,0 +1,94 @@
---
name: commit-and-push
description: Enforce Conventional Commits specification for all commit messages and push workflows
---
# Commit and Push Rule
All commits MUST follow the [Conventional Commits v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/) specification. No exceptions.
## Commit Message Format
```
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
```
## Types
| Type | When to use |
|------|-------------|
| `feat` | New feature — correlates with `MINOR` in semver |
| `fix` | Bug fix — correlates with `PATCH` in semver |
| `chore` | Maintenance, deps, config — no production code change |
| `docs` | Documentation only |
| `style` | Formatting, whitespace — no logic change |
| `refactor` | Code restructure — no feature or fix |
| `perf` | Performance improvement |
| `test` | Adding or correcting tests |
| `build` | Build system or external dependency changes |
| `ci` | CI configuration and scripts |
| `revert` | Reverts a previous commit |
## Breaking Changes
Append `!` after type/scope to indicate a breaking change. This correlates with `MAJOR` in semver.
```
feat(api)!: remove deprecated /v1/users endpoint
BREAKING CHANGE: /v1/users has been removed. Use /v2/users instead.
```
A `BREAKING CHANGE:` footer can also be used in the commit body.
## Rules
1. Type is ALWAYS lowercase.
2. Description is imperative mood ("add", not "added" or "adds").
3. Description is lowercase, no trailing period.
4. Keep subject line under 72 characters.
5. Scope is optional but recommended for `feat` and `fix` — use the affected module name.
6. One logical change per commit. If a commit spans multiple types, split into multiple commits.
7. Body wraps at 72 characters. Use it to explain **why**, not **what**.
8. Footer uses `git trailer` format (e.g., `BREAKING CHANGE:`, `Reviewed-by:`, `Refs:`).
## Lefthook Hooks
Every commit and push MUST go through Lefthook's `pre-commit` and `pre-push` hooks. Hooks are the gatekeeper — if they fail, the commit/push does not happen.
1. `pre-commit` runs lint-staged on staged files. Commit is blocked until lint-staged passes.
2. `pre-push` runs lint-staged diff check and version bump. Push is blocked until both pass.
3. If a hook fails, **fix the root cause**. Do not work around it.
## Push
1. Every push MUST pass pre-commit and pre-push hooks (see `push-flow-convention` skill).
2. **NEVER use `--no-verify`** to bypass hooks. No exceptions. No "just this once." If hooks fail, fix the issue and retry.
3. **NEVER use `git commit --no-verify`**. If pre-commit fails, fix linting/formatting and restage.
4. **NEVER use `git push --no-verify`**. If pre-push fails, fix the failing check and push again.
5. Commit message quality is enforced — reject vague messages like "fix stuff", "update", "wip", "misc".
6. If Lefthook is not installed, run `pnpm exec lefthook install` before committing. Do not commit without hooks registered.
7. **NEVER add `Co-Authored-By` trailers for AI tools** (e.g., `Co-Authored-By: Claude Code <noreply@anthropic.com>`). Commits are authored by humans only. No AI attribution in commit messages.
8. **NEVER stage all files in one commit** (`git add .` or `git add -A` then commit). Group related changes into separate, focused commits. Each commit = one logical change. If a feature touches auth + billing, split into separate commits per module.
9. Stage files deliberately by name (`git add src/auth/login.ts src/auth/types.ts`). Review what's staged before committing (`git status`, `git diff --cached`).
## Examples
```
feat(auth): add google oauth sign-in
fix(cart): correct total calculation when discount is zero
chore: update eslint config
docs: add setup guide to README
refactor(billing): extract invoice calculation to service layer
test(users): add unit tests for avatar upload
perf(api): cache user profile queries
feat(api)!: change response format for /orders endpoint
```
## Reference
Full specification: [conventionalcommits.org/en/v1.0.0](https://www.conventionalcommits.org/en/v1.0.0/)
+58
View File
@@ -0,0 +1,58 @@
---
name: docs-folder
description: Route non-hexagonal files to docs/ folder to keep domain architecture clean
---
# Docs Folder Rule
Any file that does not fit the hexagonal architecture design pattern MUST live in the `docs/` folder. The source tree stays clean — only hexagonal-compliant code belongs in `src/`.
## Hexagonal Architecture Recap
```
src/
├── domain/ # Pure business logic, entities, value objects, ports (interfaces)
├── application/ # Use cases, orchestration, input/output ports
├── infrastructure/ # Adapters — DB, HTTP clients, messaging, external APIs
└── interfaces/ # Controllers, routes, CLI, resolvers (driving adapters)
```
Only code that fits one of these layers belongs in the source tree.
## What goes in `docs/`
| Item | Why it's not hexagonal |
|------|----------------------|
| Architecture decision records (ADRs) | Documentation, not code |
| API documentation / OpenAPI specs | Reference material |
| Database diagrams / ERDs | Design artifacts |
| Flowcharts / sequence diagrams | Visual documentation |
| Meeting notes / technical decisions | Project context |
| Onboarding guides | People documentation |
| RFC / proposal documents | Decision records |
| Scratch files / experiments | Not production code |
| Third-party integration guides | Reference material |
| Deployment runbooks | Ops documentation |
| Configuration examples / templates | Not domain logic |
| Migration guides / upgrade notes | Process documentation |
## Structure
```
docs/
├── adr/ # Architecture Decision Records
├── api/ # API specs, OpenAPI/Swagger files
├── diagrams/ # ERDs, flowcharts, sequence diagrams
├── guides/ # Onboarding, deployment, migration guides
├── rfcs/ # Proposals and RFCs
└── notes/ # Meeting notes, scratch, experiments
```
## Non-negotiables
1. NEVER put documentation files in `src/` — they pollute the domain.
2. NEVER put scratch code, experiments, or spikes in `src/` — use `docs/notes/` or a separate branch.
3. NEVER put config examples or templates in `src/` — use `docs/` or project root.
4. If a file doesn't implement a port, adapter, use case, or entity — it doesn't belong in `src/`.
5. Keep `docs/` organized by category, not by date or author.
6. README at project root is fine — detailed docs go in `docs/`.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,144 @@
# Clean Architecture
When to load this reference: when structuring a new service or module, drawing boundaries between components, deciding what a microservice should own, untangling framework coupling, reviewing a system for testability and longevity, or choosing a top-level folder structure.
Clean Architecture is Uncle Bob's synthesis of Hexagonal Architecture (Alistair Cockburn), Onion Architecture (Jeffrey Palermo), DCI (Coplien & Reenskaug), and BCE (Ivar Jacobson, *Object-Oriented Software Engineering*, 1992). They differ in detail but agree on one goal: **separation of concerns by layering**, with business rules isolated from delivery mechanisms.
The foundational insight comes from Jacobson: **architectures are structures that support the use cases of the system.** Not frameworks. Not databases. Not UIs. Use cases.
---
## What a Clean Architecture Produces
A system that is:
1. **Independent of frameworks.** Frameworks are tools, not constraints.
2. **Testable.** Business rules tested without UI, DB, web server, or any external element.
3. **Independent of UI.** The UI can be replaced (web → console → CLI → TUI) without touching business rules.
4. **Independent of database.** Swap PostgreSQL for MongoDB, ClickHouse, or in-memory without rewriting domain logic.
5. **Independent of any external agency.** The core business rules know nothing about the outside world.
**The database is a detail.** So is the web. So is the framework. These are the most common sources of architectural rot because developers mistake them for foundations.
> "The database is merely an IO device. It happens to provide some useful tools for sorting, querying, and reporting but those are ancillary to the system architecture." — *A Little Architecture* (2016)
---
## The Dependency Rule
The one rule that makes everything else work:
> **Source code dependencies point only inward, toward higher-level policy.**
- Nothing in an inner layer may name anything from an outer layer — no function, class, variable, or data format.
- Data formats convenient for the outer layer (ORM row struct, JSON DTO) must not leak inward.
- Control flow may cross boundaries in either direction, but *source dependencies* point only inward. The Dependency Inversion Principle (see [solid.md](solid.md)) is the mechanism that makes this possible when control flow runs outward.
When this rule is obeyed, external details — databases, frameworks, UIs — become replaceable plugins.
---
## The Four Concentric Layers
Schematic. You may need more or fewer for a given system, but the Dependency Rule always applies.
### 1. Entities (innermost)
Encapsulate **enterprise-wide** business rules. An entity can be a class with methods or a data structure plus functions — style choice.
- Entities know nothing about applications, use cases, frameworks, or anything outside.
- For single applications (no "enterprise"), these are your core business objects.
- These are the least affected by operational change. Changes to page navigation, auth mechanisms, or DB schemas must not reach here.
### 2. Use Cases
Encapsulate **application-specific** business rules. Use cases orchestrate entities to accomplish the application's goals.
- A use case directs entities; it does not contain enterprise-wide rules itself.
- Changes to the application's *behavior* land here. Changes to externalities do not.
- Simple request/response data structures (not entities) flow in and out.
### 3. Interface Adapters
Convert data between the format convenient for use cases/entities and the format convenient for external agencies.
- MVC's Controllers, Presenters, and Views live here.
- All SQL lives here (if the database is SQL). Nothing inside knows about SQL.
- DTOs are translated into domain types and back here.
### 4. Frameworks and Drivers (outermost)
The web framework, the database, the message broker, the file system. Glue code only — you do not write much application logic here. Details live here because details change, and the outer ring is where change is cheap.
---
## Crossing Boundaries
When control flow needs to run outward — a use case needs to call a presenter — a direct call violates the Dependency Rule (the inner layer names something in the outer layer).
**Solution: the Dependency Inversion Principle.** The use case calls an interface (an "output port") defined in its own layer. The outer-layer presenter implements that interface. Control flows outward; source dependencies point inward. Same pattern works for repositories, gateways, any outward call.
---
## What Crosses Boundaries
Only **simple data structures** cross boundaries:
- Plain structs or Data Transfer Objects.
- Primitive arguments in function calls.
- Maps/dictionaries, when appropriate.
Never pass Entity objects or ORM row objects across boundaries — that couples layers. Translate to the format most convenient for the inner circle at every boundary crossing.
---
## Screaming Architecture
From the 2011 blog post of the same name. The top-level layout of a project should *scream* what the system does, not what framework it uses.
**The blueprint metaphor.** Imagine looking at the blueprints of a building. A single-family residence: front entrance, foyer, living room, dining room, kitchen. A library: grand entrance, check-in clerks, reading areas, galleries of bookshelves. A shopping mall: corridors, store bays, parking lots. You can tell what kind of building it is before you see any sign.
What does *your* application architecture scream?
**Bad top-level:** `controllers/`, `models/`, `views/`, `services/`. Tells you the system uses MVC. Tells you nothing about what the system is for.
**Good top-level:** `billing/`, `shipping/`, `catalog/`, `fraud_detection/`. Now you know what the system does.
**Why it matters:** A good architecture lets you defer decisions about Rails, Spring, Hibernate, Tomcat, MySQL, or React until much later in the project. A framework-centric top-level locks those decisions in day one, and also makes the code base mute about its own purpose. The web is a *delivery mechanism*; the database is a *detail*. Neither should dominate your system structure.
If a stranger cannot tell from the directory structure whether they are looking at an e-commerce platform or a hospital records system, the architecture is failing at the highest level.
---
## Component Principles
Once modules are organized, they group into **components** — independently deployable units (libraries, services, jars, crates). Two sets of principles govern them.
### Component Cohesion
- **REP — Reuse/Release Equivalence Principle.** The unit of reuse is the unit of release.
- **CCP — Common Closure Principle.** Group together classes that change for the same reasons at the same times. (SRP at component scale.)
- **CRP — Common Reuse Principle.** Classes used together belong together; classes not used together don't. (ISP at component scale.)
These three pull in different directions — the **tension diagram** is a triangle and component design is an ongoing balance. Early-stage projects lean toward REP+CCP (ship quickly, include more); mature, widely-reused components shift toward CRP (exclude what clients don't need).
### Component Coupling
- **ADP — Acyclic Dependencies Principle.** The dependency graph among components must have no cycles. Break cycles with DIP or by extracting a new component both sides depend on.
- **SDP — Stable Dependencies Principle.** Depend in the direction of stability.
- **SAP — Stable Abstractions Principle.** Stable components should be abstract; volatile components should be concrete.
---
## Applying This in Practice
- **"NO DB" and "NO Web" are valid starting positions.** Business rules should be expressible, testable, and useful before either is chosen.
- **Frameworks are tools, not partners.** Wrap them. Keep `import django` or `import axum::Router` out of the core. (Uncle Bob's 2014 "Framework Bound" is a full rant on this.)
- **Not every project needs four full circles.** Small projects may collapse Entities and Use Cases into one layer. The Dependency Rule still applies whatever the count.
- **The seams matter most.** Architecture lives at the boundaries between components. Defend them at every review — once they rot, replacing a dependency stops being a weekend task and becomes a six-month project.
- **Dialog from *A Little Architecture* (2016).** An aspiring architect says they want to make decisions about databases, frameworks, and webservers. Uncle Bob's response: "Oh. Well, then you don't want to become a Software Architect after all." The architect's job is to make decisions that let you **defer** the irrelevant decisions.
---
## Architecture and Agility
From "The Scatology of Agile Architecture" (2009): Agile does *not* mean no up-front architecture. The myth that you evolve architecture from zero is, in Uncle Bob's words, "horse shit." Good teams do enough architecture up front to get the seams right, then let the details emerge inside those seams. See [craft.md](craft.md) for more on this.
@@ -0,0 +1,135 @@
# The Craftsmanship Ethic
When to load this reference: when the task raises questions of professional judgment — estimation, deadline pressure, sloppy code accumulating, pairing, saying no to bad requests, or when the user invokes "technical debt" or "mess" or "craftsmanship."
The behaviors in *Clean Code* and *Clean Architecture* are not ends in themselves. They are instrumental to a larger ethic that Uncle Bob has been refining since the early 2000s: the software craftsmanship movement, which evolved into the Programmer's Oath (see [oath.md](oath.md)) and the 2022 book *Clean Craftsmanship*. This reference captures the non-code parts of that ethic that still materially affect how Claude should behave when writing or reviewing code.
---
## Clean Code Is a Practice, Not a Destination
From many posts, consolidated:
- Every function is an opportunity to practice. You don't reach "clean" and stop.
- The **Boy Scout Rule** is the daily discipline: leave each module cleaner than you found it, even if just by renaming one variable.
- "The only way to go fast is to go well." Dirty code does not trade speed for quality; it trades illusory short-term speed for enormous long-term slowness. This is the Productivity Roller-Coaster: feel fast for weeks, slow to a crawl over months.
- From *Going Fast*: "Fast" is a property you get by being disciplined, not by skipping discipline.
- From *Speed Kills*: conversely, the illusion that you can get fast by cutting corners almost always kills a project.
---
## A Mess Is Not Technical Debt
**This distinction matters.** People conflate them, and the conflation is a way to make sloppiness sound respectable.
**Ward Cunningham's Technical Debt (the original, 1992):** a **deliberate, considered** engineering trade-off when a schedule or learning situation justifies using a suboptimal design temporarily. You know what the right design is; you are choosing the wrong one now, *with intent*, and you will fix it later. Example: initial website uses server-rendered pages because there's no time to build an Ajax framework.
**A Mess:** bad code written by someone who did not do the work to understand the problem, did not refactor, did not test, did not think. It is not "debt" because it was never a considered choice — it is just poor craftsmanship.
From "A Mess is not a Technical Debt" (2009): calling a mess "technical debt" launders bad craftsmanship as if it were responsible engineering. It is not. When refusing to ship a mess, do not accept the framing that "we're just taking on some debt." Debt is deliberate; a mess is sloppy.
**Fowler's four quadrants of debt** (prudent/imprudent × deliberate/inadvertent) are a better map:
- Deliberate+prudent: the original Cunningham case ("we must ship now, we'll fix X next sprint").
- Deliberate+imprudent: "we don't have time for design" (toxic, not actually debt).
- Inadvertent+prudent: "now I know how we should have done it" (honest learning).
- Inadvertent+imprudent: plain-old-mess masquerading as debt.
---
## Saying No
From "Saying No!" (2009) and elaborated in *The Clean Coder*: professionals have an obligation to refuse impossible or unethical demands.
- When a manager asks for something that cannot be done correctly in the time allowed, the professional answer is "no, but here's what I can do," not "yes" followed by silent quality compromise.
- "Yes and then failing to deliver" is worse than "no" — the manager loses the ability to plan around reality.
- Professionals push back on their own estimates. If pressure makes you shorten a number you believe, you have stopped being the expert the organization pays you to be.
Applied to Claude: when a user asks for something that cannot be done well under the stated constraints (skip the tests, skip the error handling, ship something that will crash), the right response includes the pushback. Offer what you *can* deliver cleanly, not a degraded version of what was asked for.
---
## Honest Estimates
From "Why is Estimating so Hard?" (2012) and related posts:
- Estimates are **probability distributions, not numbers.** Give a range: optimistic, nominal, pessimistic. Three-point estimates are honest; single-point estimates almost always compress uncertainty.
- "I don't know yet, let me do a spike" is a professional answer. "I'll have it by Friday" said under duress without real confidence is not.
- An estimate is not a commitment; commitments come from negotiating after estimates are honestly given.
---
## On Documentation
**Martin's First Law of Documentation** (from *Agile Software Development: PPP*): "Produce no document unless its need is immediate and significant."
This is often misread as "Agile means no documentation." It does not. From the butunclebob.com wiki:
> "Agile Development is NOT development without documentation. Rejecting documentation in the name of 'Agility' is a flawed religious behavior. It is just as flawed as uncritically accepting the production of dozens of different documents."
Documentation, like any engineering activity, is prioritized by ROI. Create documents that more than pay back the effort to produce them. Skip documents written because policy requires them but no one will read them.
What counts as documentation:
- API docs (rustdoc, TSDoc, javadoc) — high value, close to code.
- Architecture decision records (ADRs) — capture *why* decisions were made.
- Onboarding / how-to guides — pay back every time a new person joins.
- Specs for important flows — pay back every time a flow breaks.
What does not:
- Status reports that recapitulate information already in the tracker.
- Design documents written after implementation that no one will read.
- Comments that restate the code.
---
## Pairing Guidelines
From "Pairing Guidelines" (2021) and earlier posts:
- Pairing is a **tool**, not a religion. Use it when it works; don't when it doesn't.
- Mature agile teams pair maybe 5070% of the time, not 100%.
- Some problems require "time, focus, and silence" to study before attacking. Pairing on those is worse than solo.
- Pair at the start of a story to align direction; solo for deep-focus passages; reunite to review.
- The strategy "separate the syntax issues from the semantic issues" is a useful pattern when stuck as a pair — refactor the mechanical noise (parsing, config, regex) into a helper module so the core algorithm can be reasoned about on its own.
---
## Shipping Under Pressure
From "AgilePeopleStillDontGetIt" (2006) and "We must ship now and deal with consequences" (2009):
- "It is completely unacceptable to release code that you aren't sure works. Either make sure it works, or don't ship it. Period."
- "A feature that crashes is much worse than a feature that doesn't exist. A feature that doesn't exist will defer revenue. A feature that crashes makes enemies out of customers."
- "Our customers interpret features as promises. When we release a feature we are promising that it works. When it crashes we have broken that promise."
- "Shipping untested software is shipping something unfinished and your customers will force you to finish it. The pressure will be higher at orders of magnitude if you finish it AFTER you have shipped it."
Applied to Claude: when asked to ship quickly and drop tests, the honest response is that the tests aren't slowing you down; they are the only way to ship correctly. "Going fast" without tests produces code that will return tenfold in debugging and firefighting over the next weeks.
---
## Professionalism Is Not Rigid Formalism
From "Why the sea is boiling hot" (2009) — the closing statement of Uncle Bob's 2009 Rails Conf keynote:
> "Professionalism does not mean rigid formalism. Professionalism does not mean adhering to bureaucracy. Professionalism is **honor**. Professionalism is being honest with yourself and disciplined in the way you work. Professionalism is not letting fear take over."
Honor and discipline. Not process for its own sake. The rules in this skill are tools for being disciplined; they are not a rulebook to hide behind.
---
## The Tricky Bit
From "The Tricky Bit" (2010): a British MP flew the Concorde and complained to the designer that going supersonic "didn't feel any different at all." The designer beamed: "Yes, that was the tricky bit."
Clean code, good architecture, solid tests — when they are working, the reader doesn't notice. The absence of friction is the product. Code that *announces* how clever it is, how much architecture it has, how sophisticated its patterns are, is usually the opposite of clean. The goal is invisibility — the reader moves through the code and feels nothing but understanding.
---
## When Claude Should Invoke Any of This
- **User wants to skip tests "just this once":** reference the "A Mess is not Debt" framing and the shipping-under-pressure material.
- **User wants a speculative number instead of a range:** offer a range and explain why.
- **User wants you to document something they won't read:** suggest the minimum viable doc that pays its way.
- **User wants a "quick fix" that you can see will rot the module:** explain the Boy Scout Rule cost — a quick fix that makes the code worse is a negative-value change even at zero time cost.
- **User says "we're doing Agile, we don't write documentation":** redirect to Martin's First Law and the "it's about ROI" framing.
The oath ([oath.md](oath.md)) captures the promises. This file captures the attitude and the vocabulary for navigating the hard conversations where craft meets pressure.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,161 @@
# Programming Paradigms
When to load this reference: when choosing between procedural and OO style, writing code in a functional language, refactoring switch statements, handling persistence, or when the user asks about OO vs FP, design patterns, or Clean Code's chapter on objects and data structures.
Uncle Bob's reductionist framing of the three paradigms is a powerful lens for reasoning about code shape. Each paradigm imposes **discipline** by **taking something away** from the programmer.
---
## The Three Paradigms
Each paradigm is defined by what it *forbids*, not by what it enables. This is Dijkstra-style reasoning: fewer primitives mean fewer ways to be wrong.
### Structured Programming
- **Forbids:** `goto` (direct transfer of control).
- **Provides:** Sequence, Selection (if/else), Iteration (while). Dijkstra proved any algorithm can be expressed with just these three.
- **Why:** Dijkstra's 1968 letter "Go To Statement Considered Harmful." Unrestricted `goto` makes programs impossible to reason about. Restricted control flow is provably correct for sequence, selection, iteration; not provably correct with arbitrary `goto`.
- **Status today:** Won so completely that most developers don't even realize they're using it. Modern languages don't have `goto` (or discourage it).
### Object-Oriented Programming
- **Forbids:** Raw function pointers / indirect transfer of control through unmanaged pointers.
- **Provides:** Polymorphism. The language manages the function pointers for you.
- **Why:** Raw function pointers (as in C) are correct but fragile — every caller must follow conventions every time. Polymorphism provides the same runtime capability through a disciplined mechanism: objects carry their own dispatch table, set up once when the object is created.
- **The reductionist core:** OO = polymorphism. Encapsulation, methods-bound-to-data, and simple inheritance exist in C and Pascal too. **What OO uniquely gives you is convenient polymorphism.** "OO without polymorphism is not OO."
### Functional Programming
- **Forbids:** Assignment / mutation of state.
- **Provides:** Referential transparency. Same inputs → same outputs, always, everywhere.
- **Why:** Shared mutable state is the source of most concurrency bugs and most "action at a distance" reasoning failures. Forbidding it means state changes are explicit and localized.
- **The reductionist core:** FP = referential transparency. Higher-order functions exist in OO languages too (Smalltalk, etc.). What FP uniquely gives you is the guarantee that a function call cannot change anything you didn't pass to it.
### Why "Three Paradigms" Matters
These are **orthogonal**, not competing. Each removes a different freedom:
| Paradigm | Discipline on | Mechanism |
|---|---|---|
| Structured | Direct transfer of control | No `goto` |
| OO | Indirect transfer of control | Polymorphism |
| FP | Assignment | Referential transparency |
A language can (and modern ones often do) impose all three disciplines at once. You can write OO code functionally, and you can apply SOLID inside a functional program.
---
## OO and FP Are Orthogonal, Not Exclusive
From Uncle Bob's 2014 and 2018 "FP vs OO" posts:
> "The principles of software design still apply, regardless of your programming style. The fact that you've decided to use a language that doesn't have an assignment operator does not mean that you can ignore the Single Responsibility Principle; or that the Open Closed Principle is somehow automatic."
And from his 2023 *Functional Classes* post: "Should you subdivide a functional program into classes the way you would an object oriented program? Yes. You should. Because the rules don't change just because you've chosen to use immutable data structures."
**A class, reductively:** "A group of cohesive and narrowly defined functions that operate on an encapsulated data structure. The functions may, or may not, be polymorphically deployed." This definition works in Clojure, Haskell, Rust, Java, TypeScript, Python.
**The design principles transcend paradigm:**
- SRP applies in Clojure (group functions by actor).
- OCP applies in Haskell (use abstraction, add type class instances).
- DIP applies anywhere there are modules.
- A "class" in the sense above is a cohesive namespace of related functions plus the data they operate on.
---
## Data/Object Anti-Symmetry
From Chapter 6 of *Clean Code* and elaborated in the 2019 blog post "Classes vs. Data Structures."
**Two definitions that complement each other:**
- **Object:** A set of functions that operate on **implied** data. Data exists but is hidden. Callers see only functions.
- **Data structure:** A set of data elements operated on by **implied** functions. Data is exposed. Functions exist but are not specified by the structure.
They are **diametric opposites**. You cannot fully be both.
### Consequences
- **DTOs are data structures, not objects.**
- **Database tables are data structures, not objects.**
- **"ORM" is a misnomer.** There is no mapping between database tables and objects. ORMs map tables to data structures. (This is not pedantic; it explains why ORMs have the smells they do.)
- **Polymorphism is the marker of objects.** When `shape.area()` dispatches dynamically to the Circle or Square implementation, you are doing OO. When `area(shape)` is a free function with `match shape { Circle => …, Square => … }`, you are doing procedural work.
### The Four Symmetry Rules
These tell you when to choose each style.
| | Add new FUNCTION | Add new TYPE |
|---|---|---|
| **Classes (OO)** | **Hard** — change every class | **Easy** — add one class |
| **Data structures (procedural)** | **Easy** — add one function | **Hard** — change every function |
**Choose by expected axis of change:**
- If you expect more new functions than new types → procedural style with data structures + functions (e.g., visitor pattern, pattern matching over enums, Clojure-style).
- If you expect more new types than new functions → OO style with classes and polymorphism.
- The **Visitor pattern** is procedural-style behavior over OO data — it bridges the two.
**In Rust specifically:** enums with `match` are procedural by this taxonomy (add a variant → every match must handle it); traits with implementations are OO (add an impl → no existing code changes). Neither is wrong; choose by axis of change. If new variants are rare and new operations are common, the enum wins. If new types are common, the trait wins.
---
## Polymorphism and if-else-switch
From "if-else-switch" (2021). A very common refactor:
**The pattern.** When you see an if/else chain or switch that branches by type or by "kind," replace it with:
1. A base class or interface with one method per case.
2. Concrete implementations, one per branch.
3. A **factory** that creates the right implementation based on the discriminator (this is where the if/else/switch ends up, condensed into one place).
4. The business logic calls the interface, never the discriminator.
**Runtime characteristics are identical.** If/else does a procedural lookup, switch uses a compiler-built jump table, polymorphic dispatch uses a vtable — similar performance.
**What you gain:**
- The high-level business code no longer transitively depends on every low-level case.
- Each case is its own named method, not an indented block within a branch.
- New cases = new classes (OCP).
- Independent deployment becomes possible: the high-level module and each implementation can live in separate components.
**When not to apply:** if the switch is small, stable, and not type-based (e.g., processing a small enum of flags in one place), leaving it as a switch is fine. The rule is "factor out switches on *type*," not "destroy every conditional."
---
## The Tell-Don't-Ask Style
Alan Kay's original OO conception: objects as cells in a biological system.
> "Neurons are tellers, not askers. Hormones are tellers, not askers. In biological systems, communication was half-duplex."
Instead of:
```
if account.getBalance() < amount:
throw InsufficientFunds
account.setBalance(account.getBalance() - amount)
```
Say:
```
account.withdraw(amount) // account decides if it can, and how
```
The caller stops interrogating state and deciding. The object owns the decision. This is what Law of Demeter is a weak shadow of — the deeper principle is that state should not leak out of objects.
---
## Loops and State Machines
From the 2020 "Loopy" post. Any program with nested loops can be refactored step-by-step into a Turing-style finite state machine, with tests passing at every step. This is a useful mental exercise: a nested loop is a state machine that a programmer wrote too compactly.
Practical takeaway: when a loop body is getting complex, consider extracting an explicit state (enum of states) and transitioning between them. Reads better than four nested `if`s; generalizes better; easier to test.
---
## Applying This in Practice
- **Default to OO + polymorphism** for business logic where types vary (entities, strategies, handlers). Polymorphism is the mechanism behind DIP, OCP, and Clean Architecture boundaries.
- **Default to data structures + free functions** for values, messages, and records that flow through the system. DTOs, events, API payloads, DB rows.
- **Keep the two species apart.** A "hybrid" that has both public fields and rich behavior usually gets the worst of both worlds.
- **FP is not an exception to SOLID.** Cohesion, SRP, DIP all still apply; you express them with namespaces, protocols, or type classes instead of classes.
File diff suppressed because one or more lines are too long
+177
View File
@@ -0,0 +1,177 @@
# Test Driven Development
When to load this reference: when writing new tests, reviewing tests, debugging brittle tests, dealing with legacy code that resists testing, or deciding on a testing strategy for a module.
Tests are the safety net that makes fearless refactoring possible. Without that net, every change is a gamble; with it, every change can be confident. Tests are also the most precise, executable documentation a system will ever have.
**Michael Feathers's definition of legacy code:** *Legacy code is code without tests.* Uncle Bob adopted this definition and it underpins the TDD practice.
---
## The Three Laws of TDD
1. **You are not allowed to write any production code unless it is to make a failing unit test pass.**
2. **You are not allowed to write any more of a unit test than is sufficient to fail — and compilation failures are failures.**
3. **You are not allowed to write any more production code than is sufficient to pass the one failing unit test.**
The loop is measured in seconds, not minutes. Write a line or two of test, see it fail, write a line or two of production, see it pass, repeat. This is the **nano-cycle**.
**Why these rules:**
- **Debugging time plummets** — you were never more than 60 seconds away from working code.
- **Tests are automatic documentation** that cannot fall out of sync with the system.
- **Design improves** because code written to be testable is naturally decoupled.
- **Refactoring becomes fearless** because the net catches regressions instantly.
This is double-entry bookkeeping for software. Every behavior is stated twice — once in the test, once in the code — and they must agree.
---
## F.I.R.S.T. — Clean Tests
Clean tests are:
- **Fast.** Slow tests will stop being run. If a suite takes 10 minutes, people will commit without running it. 15-minute CI feedback is too slow for the TDD loop.
- **Independent.** No test depends on another. Any test can run alone, in any order.
- **Repeatable.** Same result in every environment — laptop, CI, staging. If a test depends on the network, wall clock, or shared database, it is flaky and must be fixed.
- **Self-validating.** Pass or fail. No manual inspection.
- **Timely.** Written *just before* the production code they cover — not "when we have time."
Test code is first-class. Hold it to the same clarity bar as production code. When tests rot, production code rots.
---
## Canonical Test Definitions (First-Class Tests, 2017)
The industry has been sloppy about what "unit," "integration," "acceptance," etc. mean. Uncle Bob's proposed taxonomy:
- **Unit Test.** Written by a programmer, for a programmer. Ensures production code does what the programmer expected. Sometimes called **programmer test** or **micro-test**.
- **Acceptance Test.** Written by the business (or a BA/QA representing the business). Ensures production code does what the business expects. Sometimes called **customer test**.
- **Integration Test.** Written by architects or technical leads. Ensures a sub-assembly of system components operates correctly. **These are plumbing tests, not business-rule tests** — rules are already verified by unit and acceptance tests.
- **System Test.** An integration test for the whole integrated system.
- **Micro-test** (Mike Hill / @GeePawHill). A unit test at very small scope — tests a single function or small group.
- **Functional Test.** A unit test at larger scope, with mocks for slow components.
> "Integration tests do not test business rules. Those rules have already been tested, once by programmer (unit) tests, and again by customer (acceptance) tests. Integration tests test the plumbing and choreography of the components." — Uncle Bob (Twitter, 2019)
**Implication for Claude when writing tests:** Know which kind of test you are writing and don't couple it to the wrong kind. If you're asked to "add tests" for a pure function, write unit/micro tests. If you're asked to "test the API works end-to-end," that's integration/system. Don't test business rules in an integration test — the rules should already have unit tests.
---
## Test Structure
Use one of these structures; be consistent.
- **Arrange / Act / Assert** — set up context, perform action, check result.
- **Given / When / Then** — same thing in BDD vocabulary.
- **Build / Operate / Check** — same thing, different vocabulary.
One *concept* per test. Often one assertion, but "one concept" is the real rule — several assertions verifying the same behavior are fine.
### Test Naming
Name the test for what it verifies about behavior, not for the method. `returns_empty_list_when_given_empty_input` beats `test_filter_1`. If the name runs long, the test is probably doing more than one thing.
---
## Test Doubles — The Hierarchy
Adapted from Gerard Meszaros's *xUnit Patterns*, with Uncle Bob's gloss. Each is a degree of sophistication above the last.
- **Dummy.** Passed around but never used. Fills a parameter slot.
- **Stub.** Returns canned answers. No logic.
- **Spy.** A stub that records the calls it received.
- **Mock.** A spy with expectations built in: set up *before* the act, verified *after*. Fails if expected interactions didn't happen.
- **Fake.** A working implementation with production-unfit shortcuts — e.g., in-memory repo that stands in for a real database.
Pick the lowest-sophistication double that does the job. A mock where a stub would suffice adds coupling and fragility.
**Uncle Bob hand-rolls most of his Java mocks** ("Manual Mocking," 2009) rather than using mockito, to keep explicit control over ceremony. This is a taste preference, not a rule, but his reasoning (less magic, clearer test code) is worth knowing.
---
## Chicago vs. London (State-ism vs. Mockism)
Two schools of TDD.
- **Chicago / Classical / State-ist.** Test behavior through state. Exercise the object, assert on its final state (or collaborators' state). Minimal mocking. Less coupled to implementation detail.
- **London / Mockist.** Test behavior through interactions. Mock collaborators; assert on calls. More explicit about collaboration but more coupled to it.
**Practical guidance:** Use Chicago for value objects, algorithms, internal logic. Use London at **boundaries** — where the code coordinates external collaborators. Never mock what you own when you could exercise it directly; mock (or fake) what you do not own when the real thing would make the test slow or flaky.
---
## Fragile Tests
Tests that break without a real regression are worse than no tests — they train developers to ignore the suite. Known causes:
- **Interface sensitivity.** Tests break because a signature changed, not behavior. Often a sign of excessive mocking.
- **Behavior sensitivity.** Tests break because an unrelated behavior changed. A sign of poor isolation.
- **Data sensitivity.** Tests break because shared fixtures changed. Fix by making tests own their data.
- **Context sensitivity.** Tests pass locally, fail in CI. Remove environmental coupling: clock, network, filesystem, time zone.
- **Over-specification.** Tests assert on more than the behavior under test — internal call order, private fields, log output. Assert on what the *user of the code* would observe.
A fragile test is a design signal — usually a missing abstraction, a leaky boundary, or an over-eager mock.
"Skilled TDDers understand that neither micro-tests, nor functional tests, nor acceptance tests should be coupled to the implementation of the system." — *First-Class Tests* (2017)
---
## As Tests Get More Specific, Code Gets More Generic
Uncle Bob's formulation (2009): tests are specifications. As you add tests, the specifications grow more specific. To satisfy them all, the production code must grow more *generic*. This is the inverse relationship that drives TDD-induced good design — the code gets pushed toward abstractions that cover many cases rather than one.
---
## The Transformation Priority Premise (TPP)
When making a failing test pass, there is a natural ordering of changes, simpler before more complex. Prefer earlier transformations when more than one would work:
1. `{} → nil` — no code → returning nil
2. `nil → constant` — return a constant
3. `constant → variable` — replace constant with a variable
4. `statement → statements` — add another statement
5. `unconditional → if` — introduce a branch
6. `scalar → array` — move from a single value to a collection
7. `array → container` — move to a richer collection type
8. `statement → recursion` — replace a statement with recursion
9. `if → while` — replace a branch with iteration
10. `expression → function` — extract a function
11. `variable → assignment` — introduce mutation
Using lower-priority transformations earlier creates needless complexity; using higher-priority ones later often indicates a design that could be simpler. TPP is a tiebreaker, not a law — but it usually guides tests toward algorithms that generalize cleanly.
---
## The Cycles of TDD
TDD operates at multiple time scales simultaneously. Working at only one scale produces bad software.
- **Seconds (Red-Green-Refactor).** The nano-cycle.
- **Minutes (Specific-to-Generic).** Tests grow more specific; code grows more generic.
- **Tens of minutes (Boundary).** Periodically step back and ask whether the module is still well-factored. Extract. Rename. Regroup.
- **Hours (Architecture).** Once a day or so, step back further: are the component boundaries still correct? Does the Dependency Rule still hold?
- **Days (Acceptance).** Acceptance tests (at the feature/use-case level) close the loop with the business.
Skipping the larger cycles is the most common failure mode. Red-Green-Refactor religiously, but never step back to reconsider architecture, and you end up with a suite of fine-grained tests wrapped around a tangled ball of mud.
---
## Testing Across Architectural Boundaries
- **The test boundary** is a first-class part of architecture. Tests live outside the system they test.
- **Do not couple tests to UI frameworks or databases.** If a test needs a browser to exercise a use case, the boundary between use case and UI is broken.
- **Legacy code strategy** (Feathers). Find a seam — a place where behavior can be varied without modifying code. Write a characterization test at that seam to pin down current behavior. Refactor behind the pin. Repeat.
Uncle Bob's position on test placement: "Don't test through UIs. Don't test through web servers. Test as close to the code as you can." — *Testing Like the TSA* (2017)
---
## Common Pitfalls
- **Writing tests after the fact.** Produces tests that confirm whatever the code happens to do, including the bugs. Much lower value than TDD.
- **Slow test suites.** If any unit test takes more than a fraction of a second, isolate it. Keep the unit suite fast and run integration tests separately.
- **Mocking what you own.** Prefer real objects for your own code.
- **Testing implementation details.** Refactors then break tests without any real regression, and people conclude "TDD gets in the way of refactoring." It doesn't — the tests were just wrong.
- **Skipping refactor.** Red-Green-… is not TDD. The third step is where design emerges.
- **Over-coverage religion.** Uncle Bob's ratio for some project types: 20% test-first, 80% test-after is acceptable for controllers/models/views (per *Testing Like the TSA*, 2017). The three laws are guidance for the hottest logic in the system, not dogma for every trivial accessor.
+47
View File
@@ -0,0 +1,47 @@
---
name: commit-convention
description: Conventional Commits format and version-bump rules for this repo (Bahasa Indonesia commit style). Use when creating a git commit in zesdex.
---
# Commit Convention
Gunakan **Conventional Commits** untuk semua commit. Format:
```
<type>(<scope>): <description>
```
**Type & efek ke versi:**
| Type | Bump | Kapan pakai |
|-------------|-------|------------------------------------------|
| `feat` | minor | Fitur baru |
| `fix` | patch | Perbaikan bug |
| `chore` | patch | Maintenance, update deps, dll |
| `docs` | patch | Perubahan dokumentasi/comment |
| `refactor` | patch | Refactor kode tanpa perubahan fungsional |
| `test` | patch | Nambah/ubah test |
| `style` | patch | Formatting, whitespace, lint |
| `perf` | patch | Optimasi performa |
| `ci` | patch | Perubahan CI/CD |
**Catatan:**
- **Semua type menghasilkan release** (patch minimal). Tidak ada commit yang "skip release".
- Tambahkan `BREAKING CHANGE:` di body commit untuk bump **major**.
- **Scope** opsional, tapi direkomendasikan (misal `feat(agent):`, `fix(ipc):`).
### Contoh
```
feat(tool): add batch file delete
chore: bump reqwest to 0.12
refactor(harness): flatten guard pipeline
fix(ipc): reconnect loop on socket timeout
docs: add architecture diagram to README
BREAKING CHANGE: IPC frame header changed from 4-byte to 8-byte length
```
@@ -0,0 +1,449 @@
---
name: kana-rust-backend-best-practice
description: Reference guide for building a Rust clean-architecture backend with Axum, SeaORM, Argon2, JWT, and sea-orm-migration. Use when scaffolding a new Rust service, adding a feature (domain + use-case + repository + handler), or reviewing Rust code against the axum-clean-architecture reference layout.
---
# Axum Clean Architecture Skill
Reference stack (see `../axum-clean-architecture`):
| Layer | Tech |
|---|---|
| HTTP framework | Axum 0.8 |
| ORM | SeaORM 1.1 (PostgreSQL via sqlx + rustls) |
| Migrations | sea-orm-migration |
| Auth | Argon2 (password hashing) + jsonwebtoken (JWT) |
| Validation | zod-rs (schema-driven, mirrors Zod) |
| Pagination | paginator-rs + paginator-sea-orm + paginator-axum |
| Observability | tracing + tracing-subscriber |
| Middleware | tower-http (CORS, TraceLayer) |
| Runtime | Tokio (full features) |
| Error handling | anyhow (app-level), typed domain errors |
---
## 0. Workspace layout
```
axum-clean-architecture/
├── Cargo.toml # workspace, resolver = "3"
├── apps/
│ ├── iam/ # core domain library (lib crate)
│ │ └── src/
│ │ ├── domain/ # entities, repository traits, domain errors
│ │ ├── application/ # use cases + port traits
│ │ ├── infrastructure/ # SeaORM repos + auth services
│ │ └── presentation/ # Axum handlers, DTOs, middleware, state
│ ├── gateway/ # binary — assembles router, runs server
│ └── bootstrap/ # binary — seeds permissions/roles/admin
├── .config/ # AppServer, database/env helpers
└── .migrations/ # sea-orm-migration crate
```
The `iam` app is a **library crate**. `gateway` and `bootstrap` depend on it.
---
## 1. Dependency rules (strictly enforced)
```
presentation → application → domain
infrastructure → domain (implements domain traits)
presentation → infrastructure (only to wire AppState)
```
- Domain has **zero** external crate dependencies beyond `uuid`, `chrono`.
- Use cases depend only on port traits — never on concrete infrastructure types.
- Presentation instantiates use cases from `AppState` on every request; use cases are not stored.
---
## 2. Domain layer
### Entity pattern
Plain Rust structs — no derives beyond what domain logic needs. No ORM annotations.
```rust
// domain/user/entity.rs
pub struct User {
pub id: Uuid,
pub email: String,
pub password_hash: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub struct NewUser {
pub id: Uuid,
pub email: String,
pub password_hash: String,
}
#[derive(Default)]
pub struct UserPatch {
pub email: Option<String>,
pub password_hash: Option<String>,
}
```
### Repository trait pattern
Use `impl Future` in trait methods (Rust 2024 edition, no `async_trait` needed).
Always `Send + Sync` on the trait.
```rust
// domain/user/repository.rs
pub trait UserRepository: Send + Sync {
fn find_by_id(&self, id: Uuid)
-> impl Future<Output = Result<Option<User>, RepositoryError>> + Send;
fn find_by_email(&self, email: &str)
-> impl Future<Output = Result<Option<User>, RepositoryError>> + Send;
fn create(&self, user: NewUser)
-> impl Future<Output = Result<User, RepositoryError>> + Send;
fn update(&self, id: Uuid, patch: UserPatch)
-> impl Future<Output = Result<User, RepositoryError>> + Send;
fn delete(&self, id: Uuid)
-> impl Future<Output = Result<(), RepositoryError>> + Send;
fn list(&self, params: &PaginationParams)
-> impl Future<Output = Result<PaginatorResponse<User>, RepositoryError>> + Send;
}
```
### Shared RepositoryError (lives in domain)
```rust
pub enum RepositoryError {
NotFound,
Conflict(String),
Database(String),
}
```
### Domain errors
Per-aggregate. `AuthError` lives in `domain/auth/errors.rs`:
```rust
pub enum AuthError {
InvalidCredentials,
EmailAlreadyExists,
UserNotFound,
PasswordHashFailed(String),
PasswordVerificationFailed(String),
TokenGenerationFailed(String),
InvalidToken(String),
RepositoryError(String),
}
```
---
## 3. Application layer
### Port traits (interfaces for external services)
```rust
// application/auth/ports/password.rs
pub trait PasswordService: Send + Sync {
fn hash(&self, password: &str)
-> impl Future<Output = Result<String, PasswordError>> + Send;
fn verify(&self, password: &str, hash: &str)
-> impl Future<Output = Result<bool, PasswordError>> + Send;
}
```
```rust
// application/auth/ports/token.rs
pub trait TokenService: Send + Sync {
fn generate_auth_tokens(&self, sub: &str)
-> impl Future<Output = Result<(String, String), TokenError>> + Send;
fn verify_access_token(&self, token: &str)
-> Result<String, TokenError>;
}
```
### Use case pattern
Generic over port traits and repository traits. Constructed in the handler, not stored.
```rust
// application/user/use_cases/create.rs
pub struct CreateUserCommand { pub email: String, pub password: String }
pub struct CreateUserUseCase<P, R> {
password_service: P,
user_repository: R,
}
impl<P: PasswordService, R: UserRepository> CreateUserUseCase<P, R> {
pub fn new(password_service: P, user_repository: R) -> Self { ... }
pub async fn execute(&self, cmd: CreateUserCommand) -> Result<User, AuthError> {
// 1. guard: check uniqueness
// 2. hash password via port
// 3. create domain entity with Uuid::new_v4()
// 4. persist via repository
// 5. log + return
info!(user_id = %user.id, "user created");
Ok(user)
}
}
```
### Use case naming convention
| File | Struct | Command/Query |
|---|---|---|
| `create.rs` | `CreateXxxUseCase` | `CreateXxxCommand` |
| `update.rs` | `UpdateXxxUseCase` | `UpdateXxxCommand` |
| `delete.rs` | `DeleteXxxUseCase` | `DeleteXxxCommand` |
| `detail.rs` | `XxxDetailUseCase` | `XxxDetailQuery` |
| `list.rs` | `ListXxxsUseCase` | takes `&PaginationParams` |
---
## 4. Infrastructure layer
### SeaORM repository implementation
```rust
// infrastructure/repository/user.rs
#[derive(Clone)]
pub struct SeaOrmUserRepository { db: DatabaseConnection }
// Convert ORM Model → domain entity here (not in domain)
impl From<Model> for User { ... }
// Map DbErr → RepositoryError
fn map_db_err(e: DbErr) -> RepositoryError {
match e {
DbErr::RecordNotFound(_) => RepositoryError::NotFound,
other => { error!(error = %other, "database operation failed"); RepositoryError::Database(other.to_string()) }
}
}
impl UserRepository for SeaOrmUserRepository {
async fn create(&self, user: NewUser) -> Result<User, RepositoryError> {
let model = ActiveModel {
id: Set(user.id),
email: Set(user.email),
password_hash: Set(user.password_hash),
created_at: Set(now),
updated_at: Set(now),
};
let inserted = model.insert(&self.db).await.map_err(|e| match e {
DbErr::Exec(ref msg) | DbErr::Query(ref msg)
if msg.to_string().contains("unique") =>
RepositoryError::Conflict("email already exists".into()),
other => RepositoryError::Database(other.to_string()),
})?;
Ok(User::from(inserted))
}
}
```
Pagination uses `paginator-sea-orm`:
```rust
let response = UserEntity::find()
.paginate_with(&self.db, params)
.await
.map_err(|e| RepositoryError::Database(e.to_string()))?;
let mapped: Vec<User> = response.data.into_iter().map(User::from).collect();
Ok(PaginatorResponse { data: mapped, meta: response.meta })
```
### Auth services
- `Argon2PasswordService`: uses `spawn_blocking` for CPU-bound hashing, `SaltString::generate(OsRng)`.
- `JwtTokenService`: stores `secret: Vec<u8>`, generates separate access/refresh tokens with a `type` claim. `verify_access_token` checks `claims.token_type == "access"`.
### SeaORM entities (ORM models)
Live in `infrastructure/repository/entities/`. One file per table. Junction tables (`user_role`, `role_permission`) have composite primary keys. Timestamps use `DateTimeWithTimeZone`.
---
## 5. Presentation layer
### AppState
Concrete types only — no trait objects. Cheap to clone because `DatabaseConnection` is internally Arc-backed.
```rust
#[derive(Clone)]
pub struct AppState {
pub password_service: Argon2PasswordService,
pub token_service: JwtTokenService,
pub user_repository: SeaOrmUserRepository,
pub role_repository: SeaOrmRoleRepository,
pub permission_repository: SeaOrmPermissionRepository,
}
```
Injected via `Extension(state)` on every handler. Use cases are constructed inside handlers.
### AppError
```rust
pub enum AppError { BadRequest(String), Unauthorized, Forbidden, NotFound, Conflict(String), Internal(String) }
impl IntoResponse for AppError { /* maps to HTTP status + JSON { "error": "..." } */ }
impl From<AuthError> for AppError { ... }
impl From<RepositoryError> for AppError { ... }
impl From<TokenError> for AppError { ... }
```
Internal errors are logged with `tracing::error!` before returning a generic 500 message.
### Handler pattern
```rust
#[instrument(skip_all, fields(actor = %actor.id, email = %req.email))]
pub async fn create(
Extension(state): Extension<AppState>,
Extension(actor): Extension<AuthenticatedUser>,
Json(req): Json<CreateUserRequest>,
) -> Result<(StatusCode, Json<UserResponse>), AppError> {
let use_case = CreateUserUseCase::new(
state.password_service.clone(),
state.user_repository.clone(),
);
let user = use_case.execute(req.into()).await?;
Ok((StatusCode::CREATED, Json(user.into())))
}
```
Rules:
- Always `#[instrument(skip_all, fields(...))]` on every handler.
- Use `?` to propagate `AppError` (via `From` impls).
- `201 CREATED` for `POST`, `204 NO_CONTENT` for `DELETE`, `200 OK` for everything else.
- Pagination handlers return `PaginatedJson<Dto>` via `paginator-axum`.
### DTO pattern
```rust
#[derive(Debug, Serialize, Deserialize, ZodSchema)]
pub struct CreateUserRequest {
#[zod(email)]
pub email: String,
#[zod(min_length(8), max_length(128))]
pub password: String,
}
impl From<CreateUserRequest> for CreateUserCommand { ... }
#[derive(Debug, Serialize)]
pub struct UserResponse { pub id: Uuid, pub email: String, pub created_at: DateTime<Utc>, pub updated_at: DateTime<Utc> }
impl From<User> for UserResponse { ... }
```
- Request structs: `Deserialize + ZodSchema`. Use `#[zod(...)]` for field-level validation.
- Response structs: `Serialize` only. Never expose `password_hash`.
- Conversions: `impl From<Request> for Command` and `impl From<DomainEntity> for Response`.
### Middleware
**Auth middleware** (`presentation/middleware/auth.rs`):
- Extracts `Bearer <token>` from `Authorization` header.
- Calls `state.token_service.verify_access_token(token)`.
- Inserts `AuthenticatedUser { id: Uuid }` into request extensions.
**Permission check** (`presentation/middleware/permission.rs`):
- Called inline from handlers: `ensure_permission(&state, &actor, "users:write").await?`.
- Queries `permission_repository.find_for_user(actor.id)` and checks by name.
### Router assembly
```rust
pub fn build_router(state: AppState) -> Router {
Router::new()
.nest("/auth", auth::router())
.nest("/me", me::router())
.nest("/users", user::router())
.nest("/roles", role::router())
.nest("/permissions", permission::router())
.layer(Extension(state))
}
```
Gateway nests the IAM router at `/api/v1/iam` and adds a health check at `/`.
---
## 6. Migrations (sea-orm-migration)
```rust
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.create_table(
Table::create()
.table(Users::Table)
.if_not_exists()
.col(ColumnDef::new(Users::Id).uuid().not_null().primary_key())
.col(ColumnDef::new(Users::Email).string().not_null().unique_key())
...
.to_owned(),
).await
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager.drop_table(Table::drop().table(Users::Table).to_owned()).await
}
}
#[derive(DeriveIden)]
pub enum Users { Table, Id, Email, PasswordHash, CreatedAt, UpdatedAt }
```
Naming convention: `m{YYYYMMDD}_{6-digit-seq}_{description}.rs`, e.g. `m20260413_000001_create_users.rs`.
---
## 7. Bootstrap pattern
A separate `bootstrap` binary seeds idempotent system data (permissions, roles, admin user):
```rust
// Check existence before inserting — fully idempotent
if permission_repo.find_by_name("rbac:manage").await?.is_none() {
permission_repo.create(...).await?;
}
```
Standard permissions:
- `rbac:manage`, `users:read`, `users:write`, `roles:read`, `roles:write`, `permissions:read`, `permissions:write`
---
## 8. Adding a new aggregate (checklist)
1. **Domain**: `domain/{name}/entity.rs` (entity + NewXxx + XxxPatch), `domain/{name}/repository.rs` (trait + errors), `domain/{name}/errors.rs` if needed.
2. **Application**: `application/{name}/mod.rs`, `application/{name}/use_cases/{create,update,delete,detail,list}.rs`.
3. **Infrastructure entity**: `infrastructure/repository/entities/{name}.rs` (SeaORM model).
4. **Infrastructure repo**: `infrastructure/repository/{name}.rs` (`From<Model>`, `impl XxxRepository for SeaOrmXxxRepository`).
5. **Add to AppState**: `{name}_repository: SeaOrmXxxRepository`.
6. **Presentation DTO**: `presentation/{name}/dto.rs` (Request + Response with `From` impls).
7. **Presentation handlers**: `presentation/{name}/handlers.rs` (`#[instrument]`, construct use case, return DTO).
8. **Presentation router**: `presentation/{name}/mod.rs` (define routes with `axum_route_macro` or `Router::new().route(...)`).
9. **Nest in `build_router`**.
10. **Migration**: new file in `.migrations/src/` following naming convention.
11. **Bootstrap**: seed any required initial data.
---
## 9. Key conventions
- Edition **2024** — use `impl Future` in traits, not `#[async_trait]`.
- All timestamps are `DateTime<Utc>` in domain; `DateTimeWithTimeZone` in SeaORM models; convert with `.with_timezone(&Utc)`.
- UUIDs generated with `Uuid::new_v4()` in the use case, not the repository.
- Unique-constraint conflicts detected via string match on `DbErr::Exec`/`DbErr::Query` containing `"unique"` — map to `RepositoryError::Conflict`.
- `tracing::instrument` on every handler; log user/actor IDs as structured fields.
- `warn!` for expected failures (wrong password, permission denied), `error!` for unexpected DB errors.
- Response structs never expose internal fields (`password_hash`, internal IDs from junction tables).
@@ -0,0 +1,107 @@
---
name: push-flow-convention
description: Enforce pre-commit/pre-push hooks, lint-staged checks, and semver version bump on every push
---
# Push Flow Convention
Every repository MUST enforce the same pre-commit, pre-push, and versioning flow. No push lands without hooks, lint-staged, and a version bump.
## Required Setup
### 1. Lefthook (pre-commit + pre-push)
> **Always use [Lefthook](https://lefthook.dev/) for git hooks. Never use husky.**
Install once per repo:
```bash
pnpm add -D lefthook lint-staged
pnpm exec lefthook install
```
Create `lefthook.yml` in project root:
```yaml
pre-commit:
commands:
lint-staged:
run: pnpm exec lint-staged
pre-push:
commands:
lint-staged:
run: pnpm exec lint-staged --diff="origin/{push_remote_branch}...HEAD"
bump:
run: pnpm run bump
```
### 2. lint-staged
Declared in `package.json`. Runs ONLY on staged files so commits stay fast.
```json
{
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml,yaml}": [
"prettier --write"
]
}
}
```
### 3. Version bump script
`package.json` MUST expose a `bump` script used by `pre-push`:
```json
{
"scripts": {
"bump": "node scripts/bump-version.mjs"
}
}
```
The script inspects the diff between the current branch and its upstream, applies the semver rule below, and writes the new version back to `package.json`. Commit the bump before pushing (amend the previous commit or create a `chore: adjust package.json version (bump)` commit — see `commit-convention`).
## Semver Rules (applied on every push)
The bump is based on the changes in the commits being pushed:
| Change size / kind | Bump |
|--------------------|------|
| `< 5` changed files across pushed commits | **patch** (`x.y.Z`) |
| `>= 5` changed files across pushed commits | **minor** (`x.Y.0`) |
| New feature OR new behaviour (any `feat:` commit) | **major** (`X.0.0`) |
Rules in order of precedence:
1. If ANY commit being pushed is a `feat(...)`**major** bump.
2. Otherwise, count files changed (`git diff --name-only origin/<branch>...HEAD | wc -l`):
- fewer than 5 → **patch**
- 5 or more → **minor**
The `feat` rule always wins — a new feature is always a major bump regardless of file count.
## Non-negotiables
1. NEVER push without pre-commit and pre-push hooks installed.
2. NEVER bypass hooks with `--no-verify` — if a hook fails, fix the root cause.
3. NEVER push without a version bump. Every push = new version.
4. The bump commit MUST use the `chore: adjust package.json version (bump)` message (see `commit-convention`).
5. lint-staged MUST run on every commit. A green lint-staged is a prerequisite for the commit to be created.
6. If `pnpm` is not the package manager, substitute with `npm` or `yarn` but keep the same flow.
## Quick verification checklist
Before declaring the push flow set up, confirm:
- [ ] `lefthook.yml` exists with `pre-commit` and `pre-push` hooks
- [ ] `pnpm exec lefthook install` has been run (hooks registered in `.git/hooks/`)
- [ ] `package.json` has a `lint-staged` block
- [ ] `package.json` has a `bump` script
- [ ] A dry-run commit triggers lint-staged
- [ ] A dry-run push triggers the version bump
+6 -6
View File
@@ -21,11 +21,11 @@ jobs:
with:
components: clippy
- name: Build
run: cargo build --release
- name: Build workspace
run: cargo build --release --workspace
- name: Test
run: cargo test
- name: Test workspace
run: cargo test --workspace
- name: Clippy
run: cargo clippy -- -D warnings
- name: Clippy workspace
run: cargo clippy --workspace -- -D warnings
+2 -2
View File
@@ -20,10 +20,10 @@ jobs:
uses: actions-rust-lang/setup-rust-toolchain@v1
- name: Build
run: cargo build --release
run: cargo build --release --workspace
- name: Test
run: cargo test
run: cargo test --workspace
release:
name: Semantic Release
+4 -1
View File
@@ -3,4 +3,7 @@ target/
.claude/settings.local.json
node_modules/
package.json
package-lock.json
package-lock.json
.superpowers/
docs/lesson/
.kilo/
+18
View File
@@ -0,0 +1,18 @@
{
"branches": ["main"],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/changelog",
["@semantic-release/exec", {
"prepareCmd": "sed -i 's/^version = \"[^\"]*\"/version = \"${nextRelease.version}\"/' Cargo.toml && cargo check"
}],
["@semantic-release/git", {
"assets": ["Cargo.toml", "CHANGELOG.md"],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}],
["@semantic-release/github", {
"assets": []
}]
]
}
+38
View File
@@ -0,0 +1,38 @@
# AGENTS.md
This file provides guidance to Kilo when working with code in the zesdex repository.
## Best Practice Conventions
Zesdex follows Kana Engineering Best Practices:
1. **Clean Architecture** — Strict domain/application/infrastructure/presentation layering.
- Domain has ZERO framework dependencies.
- Application depends only on domain.
- Infrastructure implements domain traits.
- DTOs cross layer boundaries, NOT entities.
2. **Clean Code** — Functions under ~40 lines, one level of abstraction per function, descriptive names, no flag arguments, no commented-out code.
3. **Documentation** — Every pub fn, struct, enum, and trait needs a doc comment (///) explaining what, flow, why, and return value.
4. **Commit Convention** — Conventional Commits in Bahasa Indonesia: `feat(scope):`, `fix(scope):`, `chore:`, `docs:`.
5. **Error Handling**`anyhow::Result` and `anyhow::bail!` throughout. Log with `tracing` (never stderr).
6. **Testing**`#[cfg(test)] mod tests` blocks inline in production files. Tests are F.I.R.S.T. (Fast, Independent, Repeatable, Self-validating, Timely).
7. **No Compiler Bypasses** — Never use `#[allow(...)]`, `#[expect(...)]`, or `#[allow(dead_code)]`. Fix the underlying code.
8. **Boy Scout Rule** — Leave every module cleaner than you found it.
## Available Agents
- `@rust-engineer` — Rust clean architecture specialist (subagent).
- `@code-reviewer` — Code review specialist (subagent).
## Available Commands
- `/check` — Run cargo check, clippy, and tests.
- `/audit` — Code quality audit against clean-architecture best practices.
- `/doc` — Generate or update doc comments.
+460
View File
@@ -1,3 +1,463 @@
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Bug Fixes
* add .releaserc.json for semantic-release configuration ([047d718](https://github.com/asepharyana/zesdex/commit/047d7183d72adaa0dd1a18a7f92b22d67d5aa85f))
### Features
* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* implement Component trait for modular UI components and refactor TUI views to use it ([d59713d](https://github.com/asepharyana/zesdex/commit/d59713d3e3aa4325f9753bbddd068654e442f6ef))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Bug Fixes
* add .releaserc.json for semantic-release configuration ([047d718](https://github.com/asepharyana/zesdex/commit/047d7183d72adaa0dd1a18a7f92b22d67d5aa85f))
### Features
* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* enhance context gathering in auto-review engine and agent runner ([dcc8c3e](https://github.com/asepharyana/zesdex/commit/dcc8c3ee42ef568843e04143048d799bc0882288))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* refactor auto-review engine to use spawn_subagent for improved thread handling ([094eb4b](https://github.com/asepharyana/zesdex/commit/094eb4b8baa5abd878dcf5b611cf615955bc79eb))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add semantic search tool for code symbol indexing and searching ([fef3c92](https://github.com/asepharyana/zesdex/commit/fef3c925cd02e1d76e2d990cc6fa4e4cba64fab0))
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** add AI summarization for conversation history compacting ([873f870](https://github.com/asepharyana/zesdex/commit/873f870e233dd0d2c6f0cce935f83fb8ce373505))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **agent:** implement agent execution engine and turn handling with background processing ([efcd191](https://github.com/asepharyana/zesdex/commit/efcd191f9698023944f9096a86c1efa47e412b6b))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **llm:** improve UTF-8 handling in response processing to prevent infinite loops ([7ea2265](https://github.com/asepharyana/zesdex/commit/7ea226509c8e11ee1bab21d216e0413715988fb9))
* **llm:** increase max retries for streaming requests from 3 to 10 ([6c7995f](https://github.com/asepharyana/zesdex/commit/6c7995f5f5481c48ccd449e72d9563425fdcb837))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add rich context information including active jobs, README snippet, and recent git history ([2f5f62a](https://github.com/asepharyana/zesdex/commit/2f5f62ab097614d8b0c7a3e5c7bd364cd479e0aa))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** enhance system prompt with workspace structure information ([bed9f8c](https://github.com/asepharyana/zesdex/commit/bed9f8cff60711c4db998c8f10f32f8e210ae410))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** integrate rich context builder into agent turn process ([919435e](https://github.com/asepharyana/zesdex/commit/919435eb84f9a41a0637052a5dc1234b410714f8))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* add test_load and test_parse binaries for configuration loading and parsing ([fe2e916](https://github.com/asepharyana/zesdex/commit/fe2e9169371bf7a3cc9391d8467d47fc2258ad1f))
* **llm:** improve tool call handling by dynamically resizing tool_calls and updating arguments ([9bfb95d](https://github.com/asepharyana/zesdex/commit/9bfb95d795d6c7cc10cfcb907642bba7b8bb7f19))
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* remove obsolete design documents for clipboard OSC52, diff view, file mention, context compaction, and add development guide ([66ac4db](https://github.com/asepharyana/zesdex/commit/66ac4dbf027820697f4303264666b5f63a0b31d4))
* **tui:** add support for reasoning in chat messages and update transcript handling ([285dbb1](https://github.com/asepharyana/zesdex/commit/285dbb14cccb1c261134c1fcb6c30ef1ed02bb55))
* **tui:** enhance agent turn handling by grouping parameters and improving message management ([07b217c](https://github.com/asepharyana/zesdex/commit/07b217cf4a81b99c63101512932935246fcbc7ae))
* **tui:** implement streaming support for LLM responses and update transcript handling ([cac6626](https://github.com/asepharyana/zesdex/commit/cac662658651ae092cffddfc88f39a775afef942))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
* **tui:** update system message for clarity and conciseness in tool usage instructions ([5a373d1](https://github.com/asepharyana/zesdex/commit/5a373d1031b476970bd45804a65c7455be99e78d))
# [1.18.0](https://github.com/asepharyana/zesdex/compare/v1.17.0...v1.18.0) (2026-07-20)
### Features
* **mcp:** enhance MCP server registration with error handling and improve transport process management ([148ba4e](https://github.com/asepharyana/zesdex/commit/148ba4e07b424736c6b4824c5786c0c7c9cbf0a1))
* **tui:** optimize performance by caching display lines and token counts, and improve action handling ([87abe8c](https://github.com/asepharyana/zesdex/commit/87abe8c3358ac17196df93d19169901a856850d3))
# [1.17.0](https://github.com/asepharyana/zesdex/compare/v1.16.1...v1.17.0) (2026-07-20)
### Features
* **token:** add refresh token verification to TokenService ([a046519](https://github.com/asepharyana/zesdex/commit/a04651905f4afd562b516c839449a2c813ce6627))
## [1.16.1](https://github.com/asepharyana/zesdex/compare/v1.16.0...v1.16.1) (2026-07-20)
# [1.16.0](https://github.com/asepharyana/zesdex/compare/v1.15.2...v1.16.0) (2026-07-20)
### Features
* **tui:** add usage overlay and sidebar for displaying usage statistics and tasks ([da2ed6d](https://github.com/asepharyana/zesdex/commit/da2ed6da25953b823354cc5deaa7b404b7b13cb0))
* **tui:** enhance agent turn with tool descriptions and sanitize arguments ([08e2f99](https://github.com/asepharyana/zesdex/commit/08e2f9998d3693e4cd57225491359c762d03f1d9))
* **tui:** implement agent turn engine for background processing and enhance input handling ([792695b](https://github.com/asepharyana/zesdex/commit/792695b65a393cfc54efe353480b7831e91544b5))
## [1.15.2](https://github.com/asepharyana/zesdex/compare/v1.15.1...v1.15.2) (2026-07-17)
### Bug Fixes
* correct jitter range to ±25% and fix abort.rs doc — review findings ([9b6e51d](https://github.com/asepharyana/zesdex/commit/9b6e51dc677cc4b798532f1e63335785f2f7bbbf))
## [1.15.1](https://github.com/asepharyana/zesdex/compare/v1.15.0...v1.15.1) (2026-07-17)
# [1.15.0](https://github.com/asepharyana/zesdex/compare/v1.14.0...v1.15.0) (2026-07-17)
### Bug Fixes
* **cms:** perbaiki serde default hive_mind_node_timeout_ms & toleransi parse gagal di Settings ([6d41ffc](https://github.com/asepharyana/zesdex/commit/6d41ffc587f6f8de5bb4757c7eb8d69077831057))
* **cms:** satukan ChatMessage/Role Conversation dengan tipe kanonik zesdex-entities ([b272858](https://github.com/asepharyana/zesdex/commit/b272858edbe36af0b2eca119ff5b132de8dadce9))
* **iam:** redirect_uri dinamis + validasi CSRF state di OAuthServiceImpl ([be278f8](https://github.com/asepharyana/zesdex/commit/be278f8b1c2bc1295368e49c38622ef2bc3ed9ee))
* **iam:** set permission 0600 pada file token OAuth ([f2d97fb](https://github.com/asepharyana/zesdex/commit/f2d97fb17dcf4f52123da89532d7964ed8f8124c))
* **middleware:** jangan percaya header X-Forwarded-For/X-Real-IP secara default di rate limiter ([4dc4f80](https://github.com/asepharyana/zesdex/commit/4dc4f80fa344d894c2ce62f75d239847cd13001a))
### Features
* **cms:** implement RewindBlobRepository for managing binary blobs ([22dd6fd](https://github.com/asepharyana/zesdex/commit/22dd6fdda7d0c8eabfce296bbad53587204c69fa))
* **iam:** implementasikan FileSystemSessionLockRepository (sebelumnya belum ada implementasi) ([ff6a749](https://github.com/asepharyana/zesdex/commit/ff6a749c1149d890173922fbff76facef50a93b0))
* **iam:** port LoopbackServer OAuth callback listener dari zesdex-backend ([910aa5e](https://github.com/asepharyana/zesdex/commit/910aa5e071911f158609c4dd8985f776d8d9235f))
* **iam:** tambahkan CSPRNG (OsRng) untuk token state/PKCE ([5ede65f](https://github.com/asepharyana/zesdex/commit/5ede65f454b08303f588754a208dca0c37d3ce34))
# [1.14.0](https://github.com/asepharyana/zesdex/compare/v1.13.0...v1.14.0) (2026-07-16)
### Bug Fixes
* **context:** batasi squash_log ke tool bash saja ([7d99cd6](https://github.com/asepharyana/zesdex/commit/7d99cd66187b3fafb2ddeb19d8e8aa7db139df64))
* **context:** perbaiki fixture test shaping agar men-drop pesan lama ([8bb697a](https://github.com/asepharyana/zesdex/commit/8bb697a53fe89c9d00f709df33ccbd7944482f07))
* **plan:** perbaiki bug entropy gate dan fixture test squash.rs ([ceb8479](https://github.com/asepharyana/zesdex/commit/ceb84790bb741352b2b3416cda4bdbc6b42767c9))
* **plan:** perbaiki fixture test array-cutoff squash_json ([7ffdf44](https://github.com/asepharyana/zesdex/commit/7ffdf441355cda0972b849bc9b475d3de8f39843))
* **plan:** perbaiki fixture test shaping agar benar-benar men-drop pesan ([3a6e32d](https://github.com/asepharyana/zesdex/commit/3a6e32d8f3f0dd47d2c5ff63ab0c184b0ee4a6bc))
* **plan:** perkuat fixture test log agar benar-benar uji squash_log ([682007a](https://github.com/asepharyana/zesdex/commit/682007a2507f209c2378796442d4bc879516191a))
### Features
* **context:** tambah context::dedup untuk hasil tool yang berulang ([12a03fd](https://github.com/asepharyana/zesdex/commit/12a03fd3d1123c7a88289e44064537a71b9f574b))
* **context:** tambah context::shaping (port dari shortsend) ([e080d9f](https://github.com/asepharyana/zesdex/commit/e080d9fc6b7daf2ab37fb242d03a3f64e8629acc))
* **context:** tambah context::squash untuk kompresi hasil tool ([ea0b498](https://github.com/asepharyana/zesdex/commit/ea0b4988299894e4588d851ebc91704a9e73bc73))
* **context:** tambah context::tokens dengan tiktoken-rs ([c219b6e](https://github.com/asepharyana/zesdex/commit/c219b6ec58ddad4770e491a48bbe1b6e3d0c8884))
* **context:** tambah context::window::resolve ([059ca8e](https://github.com/asepharyana/zesdex/commit/059ca8ea246768dbec06ae5336433853e4276cec))
* **runtime:** kompres hasil tool lewat squash sebelum masuk context ([96084f7](https://github.com/asepharyana/zesdex/commit/96084f74621636a72c209388580d0ebbb335d198))
* **settings:** tambah mode ringkas opsional (concise_output) ([d6de973](https://github.com/asepharyana/zesdex/commit/d6de9735aba7745f5f57a8e7a5e625613c1a2569))
# [1.13.0](https://github.com/asepharyana/zesdex/compare/v1.12.0...v1.13.0) (2026-07-14)
### Bug Fixes
* correct test assertion in dim_false_plain_text_has_no_color ([8d77e45](https://github.com/asepharyana/zesdex/commit/8d77e4565c2e3ca49058022c71e8277bdd790312))
* Remove orphaned span_text helper function from markdown test module ([199028f](https://github.com/asepharyana/zesdex/commit/199028fa2eb6056dad2bdf0753554939c153a163))
* **state:** cegah panic saat select mention dengan cursor stale ([dcfc5b9](https://github.com/asepharyana/zesdex/commit/dcfc5b9ec0d35f4c66b1648ded00f4f1279e0413))
* **state:** jangan bangun mention index di mode attach ([e0d0860](https://github.com/asepharyana/zesdex/commit/e0d0860d7ba0ab6a4c9b9f1562f6a767a6424d99))
### Features
* Deteksi trigger [@mention](https://github.com/mention) dan Tab-cycle di input handler ([2eebedf](https://github.com/asepharyana/zesdex/commit/2eebedfea56c7d4827f94a2739dbb5fa006e3069))
* **ipc:** dukung Ctrl+Y clipboard copy di mode daemon/attach ([472162d](https://github.com/asepharyana/zesdex/commit/472162d135478666913a888a68867e635e50d14a))
* Judul dropdown autocomplete mengikuti jenisnya (Commands vs Files) ([7f2509e](https://github.com/asepharyana/zesdex/commit/7f2509ecd2688495545333debee0c81016b28641))
* **state:** Alirkan mention_index lewat ToolCtx dan AppStateRest, bangun index di background thread ([93be92a](https://github.com/asepharyana/zesdex/commit/93be92a5fb8644c9020478c49421585ade2d0fd1))
* Tambah Ctrl+Y untuk menyalin pesan assistant terakhir ([d93bdba](https://github.com/asepharyana/zesdex/commit/d93bdba59b7dd14b4a76dc91c6b7f70a3c0f721c))
* Tambah field pending_clipboard_copy di MiscState ([3b6abd9](https://github.com/asepharyana/zesdex/commit/3b6abd920ea92329ebcf888c3bb50470675c4152))
* Tambah helper truncate_diff untuk membatasi panjang diff ([5dd835f](https://github.com/asepharyana/zesdex/commit/5dd835ff244a138bb5f1a8dbfd7cf252c2671e5e))
* Tambah MentionIndex, AutocompleteKind, dan deteksi [@mention](https://github.com/mention) di InputState ([95cae8f](https://github.com/asepharyana/zesdex/commit/95cae8fd8a8ce737ba60c3ac8bea77f4c2e14b1a))
* Tambah write_osc52 dan salin ke clipboard di mode single-process ([71b1613](https://github.com/asepharyana/zesdex/commit/71b1613d8467cfcb2383b3fce153a25c7883ac3d))
* Tambahkan file baru ke mention_index saat tool write membuatnya ([930961b](https://github.com/asepharyana/zesdex/commit/930961bd85701ab8906b8d81095e46d3635a951d))
* Tampilkan unified diff pada hasil tool edit ([c3c0ef6](https://github.com/asepharyana/zesdex/commit/c3c0ef632a605d8bf32712049035e4fc814af9d5))
* Tampilkan unified diff saat tool write menimpa file yang sudah ada ([2bb8e6f](https://github.com/asepharyana/zesdex/commit/2bb8e6f2555eac01baf2311d41811afad4aa3041))
* **view:** Tambah parameter dim dan pewarnaan baris diff di markdown renderer ([683715c](https://github.com/asepharyana/zesdex/commit/683715cd7af77d87a2ae3834360bb6f7a4388bd0))
# [1.12.0](https://github.com/asepharyana/zesdex/compare/v1.11.0...v1.12.0) (2026-07-14)
### Features
* Add mouse capture functionality to terminal and enhance markdown rendering with table support ([4428e8b](https://github.com/asepharyana/zesdex/commit/4428e8bc01c196415ac408a42f57305227a79760))
* Improve markdown rendering with enhanced line wrapping and indentation for code blocks ([b2e848d](https://github.com/asepharyana/zesdex/commit/b2e848d124e726c4d8b644d473e518398fab1dea))
# [1.11.0](https://github.com/asepharyana/zesdex/compare/v1.10.0...v1.11.0) (2026-07-14)
### Features
* Enhance subagent tool output handling and clarify workflow directives ([6fbe1e2](https://github.com/asepharyana/zesdex/commit/6fbe1e2d1dc790ba2509803b3ab3a848d5b2a63b))
* Enhance token usage tracking and improve chat UI with emojis ([188e7cc](https://github.com/asepharyana/zesdex/commit/188e7cc9a9233140a5e4953e3f3ff66682914e42))
# [1.10.0](https://github.com/asepharyana/zesdex/compare/v1.9.0...v1.10.0) (2026-07-14)
### Bug Fixes
* align format strings in sidebar Usage widget ([98615ca](https://github.com/asepharyana/zesdex/commit/98615ca5b9d896331a5a6d9af91035aca1f5e9d5))
* use {:>6}: for aligned colons in sidebar Usage widget ([f87ab13](https://github.com/asepharyana/zesdex/commit/f87ab133f1953633f66e21b9eaf7c4eb41291ccd))
### Features
* Implement lesson generation feature and update status display ([1c08b8e](https://github.com/asepharyana/zesdex/commit/1c08b8e4e9c3bb1318535a74c9812beb976df315))
# [1.9.0](https://github.com/asepharyana/zesdex/compare/v1.8.0...v1.9.0) (2026-07-14)
### Bug Fixes
* **workflow:** import Color style for improved agent state rendering ([472c597](https://github.com/asepharyana/zesdex/commit/472c597c5e4ab12808a6bcd1899628bc7ab77186))
### Features
* **agent:** refine cognitive cycle plan with structured phases for exploration, planning, and execution ([c5253b2](https://github.com/asepharyana/zesdex/commit/c5253b2ca359d4dbed9445e04f1dec1a6bb37e8f))
* **subagent:** add progress event handling and formatting for subagent execution ([558908a](https://github.com/asepharyana/zesdex/commit/558908aef216e61a0a108083fbac5e02c31501dc))
* **subagent:** emit reasoning text as progress in StepCompleted events ([97aa75f](https://github.com/asepharyana/zesdex/commit/97aa75f2da37aee5fc7a0626fc396988f089fff2))
* **subagent:** include tool call arguments in ToolResult events and progress formatting ([a8adfcb](https://github.com/asepharyana/zesdex/commit/a8adfcbf6dc5411e977f22ac6b6ba023f563d7c9))
# [1.8.0](https://github.com/asepharyana/zesdex/compare/v1.7.0...v1.8.0) (2026-07-14)
### Features
* **tools:** require reason argument for delete and git_operator tools ([c6ab063](https://github.com/asepharyana/zesdex/commit/c6ab063c211fb858fd0e155883b9c47b345f0f8a))
# [1.7.0](https://github.com/asepharyana/zesdex/compare/v1.6.0...v1.7.0) (2026-07-14)
### Bug Fixes
* **prompt:** perbarui system prompt dari CEO/company ke model hive-mind ([d392c4a](https://github.com/asepharyana/zesdex/commit/d392c4aa00154aae5a0f36db615f05adc385fdb5))
* **runtime:** add check for unconfigured provider to prevent misleading API errors ([181b512](https://github.com/asepharyana/zesdex/commit/181b5128ac1fba47627bf7b377358c782e3481b7))
### Features
* **install:** add installation script for building and symlinking the binary ([4eba9d0](https://github.com/asepharyana/zesdex/commit/4eba9d0a2fbe42b0383eaf872eaeace18cc59a92))
* **protocol:** add Paste request type for bracketed-paste events ([b92dab9](https://github.com/asepharyana/zesdex/commit/b92dab97e6efe1fd6f7c23b28310610c653a57b0))
* **provider:** enhance Claude provider configuration to support environment variable fallback ([4b16bc3](https://github.com/asepharyana/zesdex/commit/4b16bc31125018ad3d3e46706881596a226f5352))
* **runtime:** implement JSON repair function for truncated tool-call arguments ([e13f040](https://github.com/asepharyana/zesdex/commit/e13f04083313f3544bdb1a76b5ecd535ecf59e4f))
* **stream:** add method to detect incomplete tool calls and handle parsing errors ([732d603](https://github.com/asepharyana/zesdex/commit/732d6039dc23bc8ec323bc4f91be9a7131a61ef6))
# [1.6.0](https://github.com/asepharyana/zesdex/compare/v1.5.0...v1.6.0) (2026-07-14)
### Bug Fixes
* perbaiki 5 warning clippy pre-existing (base untuk TUI overhaul) ([6b58977](https://github.com/asepharyana/zesdex/commit/6b58977875f809f19cc2d7bb9b2a7dd057d0229e))
* **tui:** perbaiki isi overlay Todo dan Usage jadi tampilan detail nyata ([aaea300](https://github.com/asepharyana/zesdex/commit/aaea300699f7e76cdc689e225e7c4c3bc164e8d4))
* **tui:** perbaiki potensi terpotongnya baris token di widget Usage sidebar ([7fd55fa](https://github.com/asepharyana/zesdex/commit/7fd55fa86dfe8f9a4581f02fa9220cd5d1ba600c))
* **tui:** perbaiki rendering multi-baris pada pesan Tool ([2f1a4d8](https://github.com/asepharyana/zesdex/commit/2f1a4d85a1fdc9cbfb81912a3206c057ad9d1ed5))
### Features
* **tui:** ganti palet warna ke Tokyo Night ([7a9cb7b](https://github.com/asepharyana/zesdex/commit/7a9cb7bf342367c81fb4a1568675e46f132a8afc))
* **tui:** rombak rendering chat jadi format log rapat ([e34708a](https://github.com/asepharyana/zesdex/commit/e34708a3191bef63d191e76dee39a58a33e4ad5f))
* **tui:** tambah command /todo dan /usage untuk buka overlay ([aa2b6ac](https://github.com/asepharyana/zesdex/commit/aa2b6acb95f8518950b8b7d9c3c9e10968936162))
* **tui:** tambah dan pasang sidebar dashboard permanen ([31c01cd](https://github.com/asepharyana/zesdex/commit/31c01cdf1df6827c3a949820378c8b85ebcfdf87))
# [1.5.0](https://github.com/asepharyana/zesdex/compare/v1.4.0...v1.5.0) (2026-07-14)
### Bug Fixes
* **hive-mind:** ganti gerbang pipeline berbasis jumlah pesan dengan deteksi konvergensi sebelumnya ([5498088](https://github.com/asepharyana/zesdex/commit/5498088532314f8dbc005d5e8058c0170ca92320))
* **hive-mind:** gunakan flag SessionRuntime sebagai sinyal konvergensi otoritatif ([28e763a](https://github.com/asepharyana/zesdex/commit/28e763a695f56adfbecd4efb14edbde13bbd63dc))
* **hive-mind:** hapus penulisan docs/runs ganda dan sambungkan abort_flag ke tool hive_mind manual ([a125f5d](https://github.com/asepharyana/zesdex/commit/a125f5d4400b0c417ba4049e67480bd18479e90b))
* **hive-mind:** tambah timeout per-node dan jamin dokumentasi convergence tetap tertulis saat sintesis gagal ([b1c0265](https://github.com/asepharyana/zesdex/commit/b1c0265e8cdf9278664e64f77fbde4ec8c22fcfd))
* **subagent:** panic-proof overlap guards and update stale docs ([e023f2c](https://github.com/asepharyana/zesdex/commit/e023f2c5a8f036d89e925bb9ceec253343476a74))
* **subagent:** perbaiki filter is_production_code berbasis substring dan tambah pembatalan/anti-tumpang-tindih pada background review ([1039f67](https://github.com/asepharyana/zesdex/commit/1039f67c12749c6b2c93e3ab7037feded8ab01c6))
* **tui:** perbaiki roster workflow yang tidak pernah ter-reset karena substring "started" tidak pernah cocok ([fdd62f8](https://github.com/asepharyana/zesdex/commit/fdd62f830330b5b3e2b4f9fcc7274daf7f7842a5))
### Features
* **settings:** tambah hive_mind_node_timeout_ms dengan fallback serde default ([e2878a3](https://github.com/asepharyana/zesdex/commit/e2878a3d83f171aa181ac29ca689828e0cb1408f))
* **tool:** tambah abort_flag ke ToolCtx dan sambungkan dari session state ([79e2bfc](https://github.com/asepharyana/zesdex/commit/79e2bfcc9ca67424ca2b34a5652d3c2bb93291bf))
# [1.4.0](https://github.com/asepharyana/zesdex/compare/v1.3.0...v1.4.0) (2026-07-14)
### Features
* **hive-mind:** implement multi-agent orchestration with cognitive cycles ([25f084f](https://github.com/asepharyana/zesdex/commit/25f084f9dbb5047c5c91aedcb582d35f4ff95395))
# [1.3.0](https://github.com/asepharyana/zesdex/compare/v1.2.0...v1.3.0) (2026-07-13)
### Features
* enhance edit logging in subagent execution and streamline edit tracking in run_agent_turn ([c60fadb](https://github.com/asepharyana/zesdex/commit/c60fadb88ae63788a5bbe3c3443e2ce826e5778f))
# [1.2.0](https://github.com/asepharyana/zesdex/compare/v1.1.0...v1.2.0) (2026-07-13)
### Features
* enhance responsiveness by implementing abort checks in streaming API calls ([0d6f558](https://github.com/asepharyana/zesdex/commit/0d6f558b2bd0282a7a1695f7680ab1d1c6142579))
* refactor agent step limits and enhance workflow orchestration with new findings tool ([3b660e0](https://github.com/asepharyana/zesdex/commit/3b660e09a87f3e982db94f48d2282ddb63116341))
* remove pipeline command and refactor workflow execution to use custom specialists ([00e2913](https://github.com/asepharyana/zesdex/commit/00e29139c53c5fed4c13b0493297dd9da984460c))
* update overlay handling in apply_action and remove mouse capture from terminal execution ([2e351cc](https://github.com/asepharyana/zesdex/commit/2e351ccf6930ff4823f55b581308222229fe6684))
* update README and documentation for new tools and features ([1d50b94](https://github.com/asepharyana/zesdex/commit/1d50b94eec1ed82dfc40d43d41bd01aeb79edfe1))
# [1.1.0](https://github.com/asepharyana/zesdex/compare/v1.0.4...v1.1.0) (2026-07-13)
+73 -86
View File
@@ -2,42 +2,13 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build & Test
```bash
# Build (debug)
cargo build
# Release build
cargo build --release
# Run all tests
cargo test
# Run a single test
cargo test test_name
# Lint
cargo clippy
# Lint with warnings-as-errors
cargo clippy -- -D warnings
```
Test modules are located inline in production files (not a separate `tests/` dir):
- `src/app/harness.rs` — guard/verdict parsing tests
- `src/app/runtime/stream/mod.rs` — SSE parser tests
- `src/model/memory.rs` — memory CRUD + slugify tests
- `src/model/editlog.rs` — edit log append/reload tests
- `src/tool/fs/helpers.rs` — tool argument extraction tests
Tests use `#[cfg(test)] mod tests` blocks. There are 37 unit tests total.
Tests use `#[cfg(test)] mod tests` blocks inline in production files (not a separate `tests/` dir).
Tracing output goes to `~/.local/share/zesdex/zesdex.log`. Set `RUST_LOG=debug` for verbose logging.
## Architecture Overview
Zesdex is an autonomous AI coding agent with a TUI — an OpenAI/Anthropic-compatible LLM client wrapped in a tool-use harness with 28 built-in tools.
Zesdex is an autonomous AI coding agent with a TUI — an OpenAI/Anthropic-compatible LLM client wrapped in a tool-use harness with 37 built-in tools.
Detailed architecture documentation is in `docs/CODEMAPS/`:
@@ -49,23 +20,7 @@ Detailed architecture documentation is in `docs/CODEMAPS/`:
| [`docs/CODEMAPS/data.md`](docs/CODEMAPS/data.md) | Persistence, SQLite msglog, memory files, settings/config |
| [`docs/CODEMAPS/dependencies.md`](docs/CODEMAPS/dependencies.md) | 23 Rust crates, 5 external services |
### Entry Points
`src/main.rs` — three modes:
- **Single-process** (default): TUI + agent loop in one process
- **Daemon** (`--daemon`): background Unix socket server, handles LLM calls
- **Attach** (`--attach <id>`): TUI-only client that connects to a daemon
### Core Flow
```
Controller (key input → Action) → Event Loop → LLM stream → Tool execution → State mutation → TUI render
│ │ │
│ src/controller/input.rs │ src/app/runtime/actions/ │ src/tool/
└── maps keys to Action enum │── dispatches Action::* └── 28 tool impls
│ matching on Action variant
│── applies state mutations
```
`docs/runs/` holds an auto-generated audit trail: one markdown file per hive-mind convergence (see below), written deterministically by `app::workflow::docs::write_hive_mind_convergence` — not hand-maintained like `docs/CODEMAPS/`.
### Key Patterns
@@ -75,63 +30,94 @@ Controller (key input → Action) → Event Loop → LLM stream → Tool executi
- **Error handling**`anyhow::Result` and `anyhow::bail!` throughout. No custom error types.
- **Static strings** — MCP tool descriptions use `Box::leak` + `OnceLock` cache.
- **Tools**`trait Tool { fn name() -> &str, fn run() -> Result<String> }`, 28 impls, gated by `Harness`.
- **Shell safety**`tool/shell_filter/` blocks credential leaks and destructive git commands.
- **Shell safety**`tool/shell_filter/` blocks destructive git commands (`shell_filter::git::check_git_destructive`, called from `tool/shell.rs::Bash::run`). It also contains a `check_credential_read` detector for credential-file reads, but that one is intentionally NOT wired into `Bash::run` today — see the doc comment on `Bash::run` for why.
### Company Pipeline (Division Architecture)
### Hive-Mind Orchestration (Machine Intelligence)
- **5 divisions** in `src/app/subagent/division.rs`: Strategy, Engineering, Quality, Security, Documentation.
- **Pipeline orchestrator** in `src/app/workflow/company.rs`: two modes:
- `run_company_pipeline()` — full 5-division pipeline
- `run_company_pipeline_quick()` — 3-division (Strategy → Engineering → Quality)
- **Auto-CEO trigger** in `run_agent_turn()` (`actions/mod.rs`): detects complex requests via `is_complex_request()` heuristics, auto-delegates to pipeline.
- **Override** via `/pipeline full|quick|skip` sets `MiscState::pipeline_override`, consumed on next turn.
- **Live division progress** in TUI panel (`view/workflow.rs`): shows division name + current tool via `AgentStatus::progress`.
- **A single Core Intelligence spawning anonymous processing nodes.** The Core Intelligence (main agent) compiles a cognitive cycle plan per task: an ordered list of cycles, each cycle a set of processing nodes that run in parallel. Each node's sole identity is its directive (what to do) and an access tier. Cycle count and nodes-per-cycle are entirely Core-Intelligence output.
- **Access tiers** in `src/app/subagent/division.rs` (`tool_scope` module): tool access is granted per node via one of three tiers (`read` / `write` / `full`, see `tool_scope::tools_for`) picked by the Core Intelligence based on what each node's directive actually needs.
- **Orchestrator** in `src/app/workflow/hive_mind.rs`: `run_hive_mind()` executes a `CognitiveCyclePlan { cycles: Vec<Vec<NodeDirective>> }` cycle-by-cycle. Node IDs are system-assigned coordinates (e.g. `"Node-0-1"`).
- **Continuous collective state, not phase-boundary sync**: `engine::execute_primitive`'s `ScopedAgent` arm merges each node's complete output into the shared collective-state channel the instant that node finishes — not after its whole parallel cohort completes — so sibling/later nodes see it in real time.
- **Consensus synthesis, not a per-node summary**: after all cycles complete, `synthesize_consensus()` spawns one final read-only node whose sole directive is to reconcile the entire collective state into a single consensus assessment — a real reasoning pass, not string concatenation, since node outputs can overlap or conflict.
- **Auto-trigger** in `run_agent_turn()` (`actions/mod.rs`): `is_complex_request()` heuristics decide only whether to ask the Core Intelligence to compile a plan at all — the plan's shape is fully dynamic.
- **`hive_mind` tool** (`src/tool/workflow.rs`) is the manual entry point: the calling LLM supplies its own `cycles` array of `{directive, access}` directly.
- **Guaranteed documentation**: after every convergence, `src/app/workflow/docs.rs::write_hive_mind_convergence()` deterministically (not an LLM step, not skippable) writes every node's full output plus the final consensus to `docs/runs/<timestamp>-<slug>.md`.
- **Live node progress** in TUI panel (`view/workflow.rs`): shows node designation + current tool via `AgentStatus::progress`.
- **Auto inline review** after each edit: `src/app/subagent/auto.rs``spawn_quick_review()` injects verdict back into LLM conversation.
- **Background subagents** (test-gen, arch-review, security-review) fire asynchronously at turn end via `TurnEvent::SystemNote`.
- **Background subagents** (test-gen, arch-review, security-review) fire asynchronously at turn end via `TurnEvent::SystemNote`, retrying once on failure and escalating to a blocking (`ESCALATED:`-prefixed, `ToastKind::Error`) notice if the retry also fails.
## Commit Convention
---
Gunakan **Conventional Commits** untuk semua commit. Format:
## Best Practices (Kana Engineering Standards)
This project follows Kana Engineering Best Practices. The following skills are loaded and enforced:
| Skill | Location | Purpose |
|-------|----------|---------|
| `clean-code` | `.claude/skills/clean-code/SKILL.md` | Clean Code principles (naming, functions, classes, comments) |
| `commit-convention` | `.claude/skills/commit-convention/SKILL.md` | Conventional Commits (Bahasa Indonesia) |
| `push-flow-convention` | `.claude/skills/push-flow-convention/SKILL.md` | Pre-commit/pre-push hooks via lefthook |
| `kana-rust-backend-best-practice` | `.claude/skills/kana-rust-backend-best-practice/SKILL.md` | Rust clean-architecture patterns (Axum, SeaORM, etc.) |
### Layering Rules
```
<type>(<scope>): <description>
domain/ → application/ → infrastructure/ → interfaces/ → gateway/
(inward) (outward)
```
**Type & efek ke versi:**
- **Domain** (Layer 0): Pure entities, value objects, repository/service traits. ZERO external framework deps.
- **Application** (Layer 1): Use-case services (one per file), port traits. Depends ONLY on domain.
- **Infrastructure** (Layer 2): Concrete implementations of domain traits (SQLite, JSON files, LLM clients, LSP servers, MCP).
- **Interfaces** (Layer 3): Presentation adapters — TUI (ratatui), API (Axum), WebSocket, daemon, gRPC, web.
- **Gateway**: Composition root — the only place that wires all layers together.
| Type | Bump | Kapan pakai |
|-------------|-------|------------------------------------------|
| `feat` | minor | Fitur baru |
| `fix` | patch | Perbaikan bug |
| `chore` | patch | Maintenance, update deps, dll |
| `docs` | patch | Perubahan dokumentasi/comment |
| `refactor` | patch | Refactor kode tanpa perubahan fungsional |
| `test` | patch | Nambah/ubah test |
| `style` | patch | Formatting, whitespace, lint |
| `perf` | patch | Optimasi performa |
| `ci` | patch | Perubahan CI/CD |
**Critical:** Domain must NEVER import application, infrastructure, or interfaces. Application must NEVER import infrastructure or interfaces.
**Catatan:**
- **Semua type menghasilkan release** (patch minimal). Tidak ada commit yang "skip release".
- Tambahkan `BREAKING CHANGE:` di body commit untuk bump **major**.
- **Scope** opsional, tapi direkomendasikan (misal `feat(agent):`, `fix(ipc):`).
### Commit Convention (Bahasa Indonesia)
### Contoh
All commits follow Conventional Commits in Bahasa Indonesia:
```
feat(tool): add batch file delete
chore: bump reqwest to 0.12
refactor(harness): flatten guard pipeline
fix(ipc): reconnect loop on socket timeout
chore: bump reqwest to 0.13
docs: add architecture diagram to README
BREAKING CHANGE: IPC frame header changed from 4-byte to 8-byte length
refactor(harness): flatten guard pipeline
```
Types: `feat`, `fix`, `chore`, `docs`, `refactor`, `test`, `style`, `perf`, `ci`. All types produce a release (patch minimum). Add `BREAKING CHANGE:` for major bumps.
### Clean Code Principles
- **Functions under ~40 lines**, one level of abstraction, extracted till you drop.
- **No flag arguments** — split `render(true)` into `renderForSuite()` / `renderForSingleTest()`.
- **Command-Query Separation** — function either does or answers, never both.
- **No switch/if-else on type** — replace with factory + polymorphism.
- **No null returns** — use `Option<T>` or empty collections.
- **No magic numbers** — extract named constants.
- **DRY** — no duplication.
- **Tell, Don't Ask** — don't fetch state then decide; tell the object to work.
- **Boy Scout Rule** — leave every module cleaner than you found it.
### Error Handling
- `anyhow::Result` and `anyhow::bail!` throughout (except domain layer typed errors).
- `tracing::warn!` / `tracing::error!` for logging. NEVER stderr (corrupts TUI).
- Never `.unwrap()` or `.expect()` in production code — use `?` or proper error handling.
- Log expected failures at `warn!`, unexpected errors at `error!`.
### Testing
- `#[cfg(test)] mod tests` blocks inline in production files.
- Tests are F.I.R.S.T. — Fast, Independent, Repeatable, Self-validating, Timely.
- Use `Result<()>` as test return type for `?` propagation.
- Mock at boundaries only; prefer fakes for owned abstractions.
### Compiler Bypasses
NEVER use `#[allow(...)]`, `#[expect(...)]`, or `#[allow(dead_code)]`. Fix the underlying code instead.
## Code Documentation
Every function, struct, enum, trait, module, and significant code block must have a doc comment (`///` or `//!`) that explains:
@@ -167,3 +153,4 @@ Rules:
- Non-trivial private functions (≥10 lines) need a doc comment
- Write the comment above the code it documents (not inline in the body)
- Update comments when code behavior changes — stale docs are worse than no docs
- NEVER use compiler/linter bypass annotations or attributes (such as `#[allow(clippy::too_many_lines, clippy::too_many_arguments, clippy::ref_option)]`, `#[allow(dead_code)]`, etc.) to silence warnings or skip linter checks. Always fix the underlying code issues instead.
Generated
+690 -17
View File
File diff suppressed because it is too large Load Diff
+67 -33
View File
@@ -1,11 +1,25 @@
[package]
name = "zesdex"
version = "1.1.0"
[workspace]
resolver = "2"
members = [
"apps/domain",
"apps/application",
"apps/infrastructure",
"apps/interfaces/tui",
"apps/interfaces/api",
"apps/interfaces/daemon",
"apps/interfaces/ws",
"apps/interfaces/grpc",
"apps/interfaces/web",
"apps/gateway",
"apps/bootstrap",
]
[workspace.package]
version = "1.18.0"
edition = "2021"
authors = ["asepharyana <superaseph@gmail.com>"]
# Treat all warnings as errors, set strict clippy levels
[lints.rust]
[workspace.lints.rust]
unused = "deny"
dead_code = "deny"
unreachable_code = "deny"
@@ -17,46 +31,66 @@ deprecated = "deny"
trivial_casts = "deny"
trivial_numeric_casts = "deny"
[lints.clippy]
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -2 }
[dependencies]
ratatui = "0.30.2"
crossterm = "0.29"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "signal"] }
reqwest = { version = "0.13", features = ["json", "stream", "blocking", "native-tls-vendored", "form"] }
dom_smoothie = "0.18.0"
fast_html2md = "0.0.62"
scraper = "0.27.0"
url = "2"
percent-encoding = "2"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yaml_ng = "0.10"
anyhow = "1"
include_dir = "0.7"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "v5"] }
dirs = "6"
futures-util = "0.3"
pulldown-cmark = { version = "0.13", default-features = false }
syntect = { version = "5", default-features = false, features = ["default-fancy"] }
anyhow = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "net", "io-util", "signal"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
reqwest = { version = "0.13", features = ["json", "stream", "blocking", "native-tls-vendored", "form"] }
ratatui = "0.30.2"
crossterm = "0.29"
rusqlite = { version = "0.40", features = ["bundled"] }
ignore = "0.4"
regex = "1"
globset = "0.4"
infer = "0.19"
thiserror = "1"
base64 = "0.22"
sha2 = "0.11"
hex = "0.4"
libc = "0.2"
dirs = "6"
regex = "1"
globset = "0.4"
ignore = "0.4"
nucleo-matcher = "0.3"
futures-util = "0.3"
rmcp = { version = "2.2", default-features = false, features = ["client", "transport-child-process", "transport-streamable-http-client-reqwest", "macros"] }
tracing = "0.1"
chrono = { version = "0.4", features = ["serde"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
webbrowser = "1"
lsp-types = "0.97"
tiktoken-rs = "0.12"
similar = "3"
syntect = { version = "5", default-features = false, features = ["default-fancy"] }
pulldown-cmark = { version = "0.13", default-features = false }
infer = "0.19"
webbrowser = "1"
url = "2"
percent-encoding = "2"
dom_smoothie = "0.18.0"
fast_html2md = "0.0.62"
scraper = "0.27.0"
include_dir = "0.7"
axum = { version = "0.8", features = ["macros"] }
tower = "0.5"
tower-http = { version = "0.6", features = ["cors", "limit"] }
argon2 = "0.5"
jsonwebtoken = "9"
clap = { version = "4", features = ["derive"] }
rand_core = { version = "0.6", features = ["getrandom"] }
[[bin]]
name = "zesdex"
path = "src/main.rs"
# Clean-architecture workspace crate references
zesdex-domain = { path = "apps/domain" }
zesdex-application = { path = "apps/application" }
zesdex-infrastructure = { path = "apps/infrastructure" }
zesdex-tui = { path = "apps/interfaces/tui" }
zesdex-api = { path = "apps/interfaces/api" }
zesdex-daemon = { path = "apps/interfaces/daemon" }
zesdex-ws = { path = "apps/interfaces/ws" }
zesdex-grpc = { path = "apps/interfaces/grpc" }
zesdex-web = { path = "apps/interfaces/web" }
zesdex-gateway = { path = "apps/gateway" }
zesdex-bootstrap = { path = "apps/bootstrap" }
+30
View File
@@ -0,0 +1,30 @@
# syntax=docker/dockerfile:1
# Zesdex — Multi-stage Docker build
# ===================================
# Stage 1: Build with Rust toolchain
FROM rust:1.85-slim-bookworm AS builder
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libsqlite3-dev && \
rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY . .
# Build with release profile (treats warnings as errors via lints)
RUN cargo build --release -p zesdex-backend --bin zesdex
# Stage 2: Minimal runtime image
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates libsqlite3-0 && \
rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/zesdex /usr/local/bin/zesdex
ENV ZESDEX_DATA_DIR=/data
VOLUME ["/data"]
ENTRYPOINT ["/usr/local/bin/zesdex"]
+192 -321
View File
@@ -1,379 +1,250 @@
# Zesdex
# Zesdex — Autonomous AI Coding Agent
> Autonomous AI coding agent in a terminal-based TUI.
Zesdex is an autonomous AI coding agent with a Terminal UI (TUI). It acts as an
OpenAI/Anthropic-compatible LLM client wrapped in a tool-use harness with **37
built-in tools** — file operations, git, shell execution, LSP integration, MCP,
subagent orchestration, and more.
Zesdex is a Rust-powered AI assistant that operates directly in your terminal via a rich TUI interface. It combines large language model intelligence with a comprehensive set of tools to explore, understand, and modify codebases autonomously — with built-in guardrails at every layer.
```
┌──────────────────────────────────────────────────────────────┐
│ Mode Selector │
│ TUI (default) ─── Daemon ─── Attach ─── API ─── WS/gRPC/Web │
└──────────────────────────────────────────────────────────────┘
```
---
## Features
## Quick Start
### Core
```bash
# Run the TUI (default mode)
cargo run
- **TUI Interface** — Full-screen terminal UI with chat panel, input bar, and status bar built with [ratatui](https://github.com/ratatui-org/ratatui) and [crossterm](https://github.com/crossterm-rs/crossterm).
- **Daemon Architecture** — Run as a background daemon with client attach/detach via Unix domain sockets. The daemon processes state; clients only render.
- **IPC Protocol** — Bidirectional state synchronization between daemon and client processes with diff-based updates.
- **Provider Agnostic** — Configurable AI model providers with dynamic model selection, per-role temperature/token limits, and API key management.
# Run the REST API server
cargo run -- --api --api-port 8080
### Tool System (34 built-in tools)
# Run in daemon mode (background + IPC)
cargo run -- --daemon
| Category | Tools |
|----------|-------|
| **Filesystem** | `read`, `write`, `edit`, `delete` |
| **Search** | `grep` (recursive text), `glob` (file patterns) |
| **Shell** | `bash`, `bash_output`, `bash_kill` |
| **Git** | `git_operator`, `git_worktree`, `git_cred` |
| **Memory** | `remember`, `recall`, `forget` |
| **Planning** | `plan_enter`, `plan_ready`, `seqthink` |
| **Workflow** | `workflow_run`, `note_finding`, `company_pipeline` |
| **Utility** | `cd`, `dir_list`, `dir_cache_update`, `pong`, `todowrite`, `todofinish` |
| **LSP** | `lsp_connect`, `lsp_diagnostics`, `lsp_hover`, `lsp_completion`, `lsp_definition`, `lsp_references`, `lsp_disconnect` |
# Attach TUI to a running daemon session
cargo run -- --attach <session-id>
### Intelligence
# Seed initial data (first run)
cargo run --bin bootstrap
```
- **Company Pipeline** — Autonomous agent orchestration modeled as a company with specialized divisions. The CEO (main agent) automatically delegates work to 5 divisions in sequence:
### Prerequisites
```
Strategy → Engineering → Quality → Security → Documentation
```
- **Rust** 1.81+ (edition 2021)
- **Linux** or **macOS** (Unix domain sockets required for daemon mode)
- An **API key** for an OpenAI/Anthropic-compatible LLM provider (set via
settings or environment variable)
Each division has a dedicated role, toolset, and system prompt. Controlled via `/pipeline full|quick|skip`.
---
- **Workflow Engine** — Orchestrate complex multi-step tasks with parallel sub-agents, pipelines, and phased execution. Spawn independent workers that share findings in real-time.
- **Self-Learning** — Persistent memory system that stores lessons, references, and project knowledge across sessions. Memories include provenance tracking, lifecycle management, and scope isolation.
- **Self-Review** — Review subagents trigger automatically after each code edit (inline) and at turn completion (background). Three types: code quality, architecture, and security.
- **Self-Healing** — On build/test failures, spawns a sub-agent with the error context to autonomously fix issues before reporting them to the user.
- **MCP Support** — [Model Context Protocol](https://modelcontextprotocol.io/) integration for connecting to external AI tool servers.
- **Sequential Thinking** — Chain-of-thought reasoning tool for step-by-step problem decomposition.
- **Session Locking** — Prevents multiple processes from operating on the same session directory.
## Modes
### Session Management
- Multiple concurrent sessions with history, rewind, and transcript persistence.
- Per-session edit logs with full change tracking.
- Session archival and summary generation.
| Flag | Mode | Description |
|------|------|-------------|
| *(none)* | **TUI** | Full terminal UI with chat, overlays, and agent loop in one process |
| `--daemon` | **Daemon** | Background daemon with IPC socket; clients attach separately |
| `--attach <id>` | **Attach** | Connect TUI to an existing daemon session via Unix socket |
| `--api` | **REST API** | HTTP server with session management and chat endpoints |
| `--ws` | **WebSocket** | WebSocket server for real-time communication |
| `--grpc` | **gRPC** | gRPC server for programmatic access |
| `--web` | **Web** | Serves the web frontend |
| `--api-port`, `--ws-port`, `--grpc-port`, `--web-port` | *(ports)* | Configure server ports (defaults: 8080, 8081, 50051, 3000) |
---
## Architecture
### Clean Architecture Layering
```
src/
├── main.rs # Entry point: single-process, daemon, or attach mode
├── resources.rs # Embedded resources (help text, system prompts)
├── app/
├── state/ # AppStateRest — immutable-rest state model
│ │ ├── rest.rs # Core state struct
├── types.rs # Overlay, Toast, Origin enums
│ │ ├── snapshot.rs # State snapshots for IPC
│ │ ├── diff.rs # Diff-based state synchronization
│ │ ├── runtime.rs # Runtime state mutations
│ │ └── misc.rs # DirCache and miscellaneous state helpers
├── runtime/ # Action dispatch and event loop
│ │ ├── actions/ # Action enum and apply_action reducer
│ │ ── stream/ # LLM streaming and tool execution
│ │ │ └── tools/ # Tool harness integration
│ │ │ └── turn.rs # Turn orchestration
│ │ ├── event_loop/ # Main event loop and shortsend
│ │ ├── commands.rs # Slash command dispatch
│ │ └── shortsend.rs # Short-lived async send helper
│ ├── mode/ # UI modes and overlays (13 modes)
│ │ ├── bash.rs # Bash panel mode
│ │ ├── editor.rs # Multi-line editor mode
│ │ ├── effort.rs # Effort level selector
│ │ ├── help.rs # Help overlay
│ │ ├── key_input.rs # Raw key input mode
│ │ ├── loading.rs # Loading spinner overlay
│ │ ├── mcp.rs # MCP server management
│ │ ├── quit_confirm.rs # Quit confirmation dialog
│ │ ├── rewind.rs # Session rewind mode
│ │ ├── settings.rs # Settings panel
│ │ ├── todo.rs # Task list overlay
│ │ └── workflow.rs # Workflow visualization
│ ├── harness.rs # Tool harness for agent execution
│ ├── workflow/ # Workflow engine
│ │ ├── script.rs # Workflow script DSL
│ │ ├── engine.rs # Workflow executor
│ │ └── company.rs # Company pipeline orchestrator
│ ├── mcp/ # MCP client manager
│ │ └── manager.rs # MCP server lifecycle and tool exposure
│ ├── subagent/ # Sub-agent management
│ │ ├── spawn.rs # AgentDefinition and spawning
│ │ ├── engine.rs # Sub-agent event loop
│ │ ├── context.rs # Context construction for sub-agents
│ │ └── event.rs # Progress event types
│ ├── bgbash/ # Background bash job management
│ │ ├── job.rs # Background job handle
│ │ └── control.rs # Bash control (bg/fg/kill)
│ ├── lsp/ # LSP client management
│ │ ├── client.rs # LSP client connection wrapper
│ │ └── provisioner.rs # Auto-provisioning of LSP servers
│ └── review/ # Self-review quality system
├── controller/
│ ├── input.rs # Key event → Action mapping
│ └── command.rs # Slash command parser
├── dto/
│ ├── chat/ # Message, ToolCall, Role types
│ │ ├── message.rs # Chat message types
│ │ ├── tool.rs # Tool call/result types
│ │ └── mod.rs
│ └── provider/ # AI provider request/response/usage types
│ ├── request.rs # Provider request schema
│ ├── response.rs # Provider response schema
│ └── usage.rs # Token usage tracking
├── ipc/
│ ├── protocol.rs # ClientRequest, DaemonFrame, StatePayload
│ ├── server.rs # Unix socket server
│ ├── client.rs # Unix socket client
│ ├── conn.rs # Framed connection
│ ├── frame.rs # Length-prefixed frame encoding
│ ├── snapshot.rs # State snapshot serialization
│ └── diff.rs # Binary diff for state sync
├── model/
│ ├── store.rs # File-based storage (~/.config/zesdex/)
│ ├── session.rs # Session CRUD and listing
│ ├── settings.rs # User settings (provider, model, tokens)
│ ├── app_config.rs # Provider definitions and model roles
│ ├── memory.rs # Persistent memory with frontmatter
│ ├── editlog.rs # Edit history tracking
│ ├── msglog/ # Message log (SQLite-backed)
│ │ ├── schema.rs # SQLite schema
│ │ ├── query.rs # Query helpers
│ │ ├── blobs.rs # Large blob storage
│ │ └── summary.rs # Session summarization
│ ├── agent_def/ # Agent definitions (builtin, global, session)
│ │ ├── builtin.rs # Built-in agent profiles
│ │ ├── global.rs # Global agent config
│ │ └── session.rs # Per-session agent config
│ ├── conversation.rs # Conversation helpers
│ └── session_lock.rs # Flock-based session locking
├── service/
│ ├── provider.rs # AI provider abstraction
│ └── oauth/ # OAuth PKCE flow with loopback server
│ ├── loopback.rs # Local HTTP server for OAuth redirect
│ ├── manager.rs # OAuth token manager
│ ├── pkce.rs # PKCE code challenge/verifier
│ └── mod.rs
├── tool/ # 34 tool implementations
│ ├── fs/ # read, write, edit, delete
│ │ ├── read.rs
│ │ ├── write.rs
│ │ ├── edit.rs
│ │ ├── delete.rs
│ │ └── helpers.rs # Path resolution and validation
│ ├── search.rs # grep, glob
│ ├── shell.rs # bash
│ ├── bash_tools.rs # bash_output, bash_kill
│ ├── git_operator.rs # git operations
│ ├── git_worktree.rs # git worktree management
│ ├── git_cred.rs # git credential store/get/erase
│ ├── memory/ # remember, forget, recall
│ │ ├── remember.rs
│ │ ├── forget.rs
│ │ └── recall.rs
│ ├── plan.rs # plan_enter, plan_ready
│ ├── seqthink.rs # Sequential thinking
│ ├── workflow.rs # workflow_run, note_finding
│ ├── utility/ # cd, dir_list, dir_cache_update, pong, todowrite, todofinish
│ │ ├── cd.rs
│ │ ├── dir_list.rs
│ │ ├── dir_cache_update.rs
│ │ ├── pong.rs
│ │ ├── todowrite.rs
│ │ └── todofinish.rs
│ ├── lsp/ # LSP tools (connect, diagnostics, hover, etc.)
│ │ └── mod.rs
│ └── shell_filter/ # Shell output filtering (credentials, git)
│ ├── credentials.rs
│ ├── git.rs
│ └── mod.rs
└── view/ # TUI rendering
├── chat.rs # Chat transcript with markdown
├── markdown.rs # Markdown → ratatui spans
├── status.rs # Status bar
├── theme.rs # Color scheme
└── workflow.rs # Workflow visualization
apps/
├── domain/ # Pure entities, value objects, repository/service traits
# Zero framework deps — only serde + chrono + uuid
├── application/ # Use-case services (auth, sessions, conversations, memory)
│ # Depends only on domain-layer trait interfaces
├── infrastructure/ # All I/O: LLM client, IPC, persistence, LSP, MCP, tools
# Implements domain/application port interfaces
└── interfaces/ # Entry points
├── tui/ # Ratatui terminal UI
├── api/ # Axum REST API
├── daemon/ # Unix socket daemon + client
├── ws/ # WebSocket server
├── grpc/ # gRPC server
── web/ # Web frontend (static file server)
```
---
### Tool System
## Usage
37 tools across 9 categories:
```bash
# Run in single-process mode (default)
zesdex
| Category | Tools |
|----------|-------|
| **File System** | `read`, `write`, `edit`, `delete`, `dir_list`, `dir_cache_update` |
| **Shell** | `bash`, `bash_interactive`, `bash_kill`, `bash_output` |
| **Git** | `git_operator`, `git_cred`, `git_worktree` |
| **Search** | `search`, `grep`, `glob`, `semantic_search` |
| **LSP** | `lsp_connect`, `lsp_hover`, `lsp_completion`, `lsp_definition`, `lsp_references`, `lsp_diagnostics`, `lsp_disconnect` |
| **Memory** | `remember`, `recall`, `forget` |
| **Workflow** | `spawn_agents`, `spawn_pipeline`, `plan`, `sequential_think`, `hive_mind` |
| **Utility** | `todo_write`, `todo_finish`, `pong`, `cd` |
| **Background** | Background bash jobs with `cancel/status/list` |
# Run as a background daemon
zesdex --daemon
# Attach to a running daemon session
zesdex --attach <session-id>
# Set log level
RUST_LOG=debug zesdex
```
### Key Bindings
| Binding | Action |
|---------|--------|
| `Ctrl+Q` | Quit |
| `Ctrl+H` | Help overlay |
| `Ctrl+P` | Settings overlay |
| `Ctrl+B` | Bash panel |
| `Ctrl+S` | Session hub |
| `Ctrl+T` | Task list |
| `Ctrl+W` | Workflow view |
| `Ctrl+K` | Key input mode |
| `Esc` | Cancel / back |
| `Tab` | Autocomplete |
| `↑/↓` | History / navigation |
| `Scroll` | Mouse scroll in chat |
### Slash Commands
| Command | Description |
|---------|-------------|
| `/help` | Show help |
| `/clear` | Clear transcript |
| `/model` | Select AI model provider |
| `/pipeline` | Show current pipeline mode |
| `/pipeline full` | Force full company pipeline (5 divisions) on next request |
| `/pipeline quick` | Force quick pipeline (3 divisions) on next request |
| `/pipeline skip` | Skip pipeline — handle next request directly |
| `/exit` | Exit application |
| `/settings` | Open settings |
| `Any text` | Sent to the AI assistant as a prompt |
---
## Configuration
All configuration lives in `~/.config/zesdex/` (or platform equivalent via the `dirs` crate).
| File | Purpose |
|------|---------|
| `settings.json` | Provider selection, model, temperature, max tokens, review settings, workflow concurrency |
| `app_config.json` | AI provider definitions (name, API base URL, auth type, default model) |
| `memory/` | Persistent lesson and reference storage (Markdown with YAML frontmatter) |
| `sessions/` | Per-session transcripts, edit logs, and activity data |
| `run/` | Unix domain sockets for daemon mode |
### Provider Configuration
Providers are defined in `app_config.json`:
```json
{
"providers": {
"my-provider": {
"api_base": "https://api.example.com/v1",
"api_key_env": "MY_API_KEY",
"default_model": "model-name"
}
},
"model_roles": {
"default": {
"provider": "my-provider",
"model": "model-name",
"max_tokens": 8192,
"temperature": 0.7
}
},
"default_provider": "my-provider",
"default_model": "model-name"
Each tool implements the `Tool` trait:
```rust
pub trait Tool: Send + Sync {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn parameters(&self) -> Value;
fn run(&self, ctx: &ToolCtx, args: &Value) -> Result<String>;
}
```
### Settings
### Hive Mind Orchestration
Key settings in `settings.json`:
The multi-agent orchestration system compiles a **cognitive cycle plan** per
task — ordered cycles of parallel processing nodes. Each node has a directive
and an **access tier** (`read` / `write` / `full`). Node outputs merge into a
shared collective state in real time, and a final **consensus synthesis**
produces the unified result.
| Setting | Default | Description |
|---------|---------|-------------|
| `review_enabled` | `true` | Enable self-review after tool execution |
| `review_max_lessons_per_run` | `5` | Max lessons loaded per review cycle |
| `adaptive_review_max_skip` | `3` | Consecutive passes before skipping review |
| `verify_command` | `null` | Optional command to verify changes |
| `workflow_max_concurrency` | `5` | Max parallel sub-agents in workflows |
| `session_archive_enabled` | `true` | Auto-archive completed sessions |
- **Auto-trigger**: Complex requests automatically use the hive mind
- **Manual entry**: The `hive_mind` tool lets the LLM specify cycles explicitly
- **Live progress**: TUI panel shows each node's status and current tool
- **Guaranteed docs**: Every convergence writes to `docs/runs/`
### IPC Protocol (Daemon Mode)
```
┌──────────┐ Unix socket ┌──────────┐
│ Client │ ◄──────────────► │ Daemon │
│ (TUI) │ length-prefixed│ │
└──────────┘ serde_json └──────────┘
Frame format: [4-byte BE length][JSON payload]
```
The daemon holds `AppStateRest` and drives the agent loop. Clients are stateless
renderers that receive full state snapshots after each action.
---
## Installation
## Built-in Features
### Prerequisites
| Feature | Description |
|---------|-------------|
| **LLM Provider** | OpenAI/Anthropic-compatible API (streaming + non-streaming) with automatic retry and fallback |
| **Tool Harness** | Safety-gated tool execution with graduated review checks |
| **Subagents** | Auto-inline review, background test-gen, arch-review, security-review |
| **OAuth 2.0** | PKCE flow for LLM provider authentication |
| **MCP** | Model Context Protocol server management (stdio + HTTP transport) |
| **LSP** | Language Server Protocol integration (completion, hover, diagnostics, references) |
| **Session Mgmt** | SQLite-persisted sessions with lock-based concurrency control |
| **Memory** | File-based memory system with frontmatter metadata |
| **Edit Log** | Append-only edit history with configurable retention |
| **Rate Limiting** | Sliding-window per-client rate limiter |
| **JWT Auth** | HS256 JWT access/refresh tokens (API mode) |
| **Password Auth** | Argon2 password hashing with pepper |
| **OAuth Loopback** | Localhost HTTP server for OAuth redirect capture |
| **Background Jobs** | Long-running shell jobs with cancellation and output collection |
| **Settings** | JSON-persisted settings with hot-reload |
- **Rust** 2021 edition toolchain ([rustup](https://rustup.rs/))
---
### Build from Source
## TUI Overlays
16 overlays accessible from the terminal UI:
| Overlay | Purpose |
|---------|---------|
| Chat Input | Main input bar with autocomplete |
| Bash Panel | Interactive shell panel |
| File Editor | Built-in file editor |
| Effort Selector | LLM reasoning effort selector |
| Help | Keybindings reference |
| Key Input | Custom key binding configuration |
| Learning | Lesson viewer |
| Loading | Generating spinner |
| MCP Manager | MCP server management |
| Model Selector | LLM model picker |
| Quit Confirm | Exit confirmation dialog |
| Rewind | Message/history rewind |
| Settings | Settings panel |
| Todo | Task/TODO list |
| Usage | Token usage statistics |
| Workflow | Hive-mind node progress |
---
## Data & Persistence
All data lives under the platform's data directory (`~/.local/share/zesdex/`):
```bash
git clone <repository-url>
cd zesdex
cargo build --release
./target/release/zesdex
```
~/.local/share/zesdex/
├── settings.json # User settings (provider, model, keys)
├── app_config.json # Provider definitions (endpoints, env vars)
├── sessions/ # Chat sessions (one subdirectory per session)
│ └── <uuid>/
│ ├── session.json # Session metadata
│ ├── messages.jsonl # Message log
│ └── .lock # Session lock file
└── memories/ # Memory files with frontmatter metadata
└── *.md
```
---
## Development
### Commit Convention
```bash
# Build all crates
cargo build
Project ini menggunakan **Conventional Commits** untuk otomatis menentukan versi rilis (melalui semantic-release).
# Run all unit tests (8 tests across 11 crates)
cargo test
Format:
```
<type>(<scope>): <description>
# Run clippy linting
cargo clippy --all-targets
[optional body]
[optional footer]
# Run with verbose logging
RUST_LOG=debug cargo run
```
**`<type>` — menentukan bump version:**
### Workspace Crates
| Type | Bump | Keterangan |
|-------------|---------|-------------------------------------------|
| `feat` | minor | Fitur baru |
| `fix` | patch | Perbaikan bug |
| `chore` | patch | Tugas maintenance, refactor ringan |
| `docs` | patch | Perubahan dokumentasi |
| `refactor` | patch | Refactor kode (tanpa perubahan fungsional)|
| `test` | patch | Penambahan atau perbaikan test |
| `style` | patch | Perubahan formatting, whitespace, dll |
| `perf` | patch | Optimasi performa |
| `ci` | patch | Perubahan CI/CD |
| Crate | Path | Layer |
|-------|------|-------|
| `zesdex-domain` | `apps/domain/` | Pure domain entities & traits |
| `zesdex-application` | `apps/application/` | Use-case services |
| `zesdex-infrastructure` | `apps/infrastructure/` | All I/O & tool implementations |
| `zesdex-tui` | `apps/interfaces/tui/` | Ratatui terminal interface |
| `zesdex-api` | `apps/interfaces/api/` | Axum REST API |
| `zesdex-daemon` | `apps/interfaces/daemon/` | Unix socket daemon |
| `zesdex-ws` | `apps/interfaces/ws/` | WebSocket server |
| `zesdex-grpc` | `apps/interfaces/grpc/` | gRPC server |
| `zesdex-web` | `apps/interfaces/web/` | Web frontend |
| `zesdex-gateway` | `apps/gateway/` | CLI entry point & dispatcher |
| `zesdex-bootstrap` | `apps/bootstrap/` | Initial data seeder |
**`BREAKING CHANGE`** pada body commit → **major** (apa pun typenya).
### Code Map
Contoh:
```
feat(agent): add workspace-aware file search
Detailed architecture documentation is in `docs/CODEMAPS/`:
Implement context-aware search scoped to current workspace directory.
BREAKING CHANGE: search results now filter by workspace scope.
```
```
fix(ipc): handle partial frame on unix socket reconnect
```
```
chore: update rustls to 0.23
```
### Release Workflow
Push ke branch `main` akan memicu:
1. **CI**`cargo build --release` + `cargo test`
2. **Semantic Release** — analisis commit → update `Cargo.toml` + `CHANGELOG.md` → git tag → GitHub Release dengan binary
| File | Covers |
|------|--------|
| `docs/CODEMAPS/architecture.md` | System layout, process modes, data flow |
| `docs/CODEMAPS/backend.md` | Provider, OAuth, IPC, workflow engine, MCP, LSP, review |
| `docs/CODEMAPS/frontend.md` | TUI render pipeline, 16 overlays, toasts, input handling |
| `docs/CODEMAPS/data.md` | Persistence, SQLite msglog, memory files, settings/config |
| `docs/CODEMAPS/dependencies.md` | All Rust crates and external services |
---
## License
See [LICENSE](LICENSE) for details.
See `CHANGELOG.md` for release history.
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "zesdex-application"
version.workspace = true
edition.workspace = true
authors.workspace = true
# Application layer — port traits (interfaces), use cases, DTOs.
# Depends ONLY on domain. Application services orchestrate domain objects
# through port traits without knowing concrete implementations.
[dependencies]
zesdex-domain = { path = "../domain" }
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
uuid.workspace = true
anyhow.workspace = true
tracing.workspace = true
tokio.workspace = true
base64.workspace = true
sha2.workspace = true
url.workspace = true
+25
View File
@@ -0,0 +1,25 @@
use anyhow::Result;
use std::future::Future;
use zesdex_domain::agent::AgentTurnParams;
/// Interface for dispatching tool calls to their concrete implementations.
pub trait ToolExecutor: Send + Sync {
/// Execute a tool call asynchronously.
fn execute(
&self,
tool_name: &str,
args: &serde_json::Value,
) -> impl Future<Output = Result<String>> + Send;
}
/// Service for running agent turns asynchronously.
pub trait AgentTurnService: Send + Sync {
/// Run a full agent turn loop asynchronously.
fn run_turn(
&self,
params: AgentTurnParams,
) -> impl Future<Output = Result<()>> + Send;
}
pub mod turn_service;
+298
View File
@@ -0,0 +1,298 @@
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use tracing::{debug, info, warn};
use zesdex_domain::agent::{AgentTurnParams, TurnEvent};
use zesdex_domain::core::{ChatMessage, StreamEvent, ToolDef};
use zesdex_domain::main_agent_prompt;
use crate::ports::ProviderService;
use super::ToolExecutor;
/// Maximum tool-call iterations per agent turn before forcing termination.
const MAX_TURN_ITERATIONS: u32 = 50;
// ---------------------------------------------------------------------------
// Helper: push a TurnEvent onto the shared queue.
// ---------------------------------------------------------------------------
fn push_event(queue: &Arc<Mutex<VecDeque<TurnEvent>>>, event: TurnEvent) {
if let Ok(mut q) = queue.lock() {
q.push_back(event);
}
}
// ---------------------------------------------------------------------------
// Helper: stream-event callback that forwards tokens to the turn-event queue
// and checks the abort flag on each emission.
// ---------------------------------------------------------------------------
fn make_stream_callback(
abort: &Arc<AtomicBool>,
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
) -> Box<dyn FnMut(&StreamEvent) -> bool + Send> {
let abort_clone = Arc::clone(abort);
let events_clone = Arc::clone(turn_events);
Box::new(move |event: &StreamEvent| -> bool {
if abort_clone.load(Ordering::SeqCst) {
return false;
}
match event {
StreamEvent::Token(s) => {
push_event(&events_clone, TurnEvent::StreamToken(s.clone()));
}
StreamEvent::Reasoning(s) => {
push_event(&events_clone, TurnEvent::StreamReasoning(s.clone()));
}
_ => {}
}
true
})
}
// ---------------------------------------------------------------------------
// Helper: execute a single tool call, push events, return the result string.
// ---------------------------------------------------------------------------
async fn execute_tool_call<T: ToolExecutor>(
tool_executor: &T,
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
tc: &zesdex_domain::core::ToolCall,
) -> String {
let name = &tc.function.name;
let args = zesdex_domain::core::tool_call::sanitize_tool_arguments(&tc.function.arguments);
debug!("executing tool: {name}");
let output = match tool_executor.execute(name, &args).await {
Ok(o) => o,
Err(e) => format!("Error: {e}"),
};
let is_error = output.starts_with("Error:");
push_event(
turn_events,
TurnEvent::ToolResult {
tool_call_id: tc.id.clone(),
tool_name: name.clone(),
output: output.clone(),
is_error,
path: None,
},
);
output
}
// ---------------------------------------------------------------------------
// Helper: emit usage event from optional LLM response metadata.
// ---------------------------------------------------------------------------
fn emit_usage(turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>, usage: Option<(u64, u64)>) {
if let Some((tokens_in, tokens_out)) = usage {
push_event(
turn_events,
TurnEvent::Usage {
tokens_in,
tokens_out,
},
);
}
}
// ---------------------------------------------------------------------------
// Service implementation
// ---------------------------------------------------------------------------
/// Service implementation for executing an agent turn asynchronously.
pub struct AgentTurnServiceImpl<P: ProviderService, T: ToolExecutor> {
provider: Arc<P>,
tool_executor: Arc<T>,
tool_defs: Vec<ToolDef>,
}
impl<P: ProviderService, T: ToolExecutor> AgentTurnServiceImpl<P, T> {
pub fn new(provider: Arc<P>, tool_executor: Arc<T>, tool_defs: Vec<ToolDef>) -> Self {
Self {
provider,
tool_executor,
tool_defs,
}
}
/// Execute a single LLM call with the current message list, handling
/// streaming events and error reporting.
async fn call_llm(
&self,
messages: &[ChatMessage],
abort: &Arc<AtomicBool>,
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
) -> Result<(ChatMessage, Option<(u64, u64)>), String> {
let on_event = make_stream_callback(abort, turn_events);
self.provider
.chat_stream(
messages,
Some(self.tool_defs.clone()),
Some(4096),
Some(0.7),
on_event,
)
.await
.map_err(|e| format!("LLM error: {e}"))
}
}
impl<P: ProviderService, T: ToolExecutor> super::AgentTurnService for AgentTurnServiceImpl<P, T> {
async fn run_turn(&self, mut params: AgentTurnParams) -> anyhow::Result<()> {
info!(
"Starting async agent turn with {} messages (model: {})",
params.messages.len(),
params.model
);
// Insert system prompt at position 0 once and keep it there for the
// entire turn, avoiding per-iteration clones of the full message list.
// It is removed before emitting the Compacted event so persistence
// does not store the prompt redundantly.
params.messages.insert(0, ChatMessage::system(main_agent_prompt()));
let original_count = params.messages.len();
for iteration in 0..MAX_TURN_ITERATIONS {
// ── Check abort flag ────────────────────────────────────────
if params.abort.load(Ordering::SeqCst) {
params.abort.store(false, Ordering::SeqCst);
push_event(
&params.turn_events,
TurnEvent::SystemNote {
kind: "info".into(),
message: "Turn aborted by user".into(),
},
);
break;
}
debug!("agent turn iteration {iteration}");
// ── Stream start + call LLM ─────────────────────────────────
push_event(&params.turn_events, TurnEvent::StreamStart);
// Uses params.messages directly (sys_msg[0] already in place
// from the insert above) — no per-iteration clone needed.
let result = self
.call_llm(&params.messages, &params.abort, &params.turn_events)
.await;
match result {
Ok((assistant_msg, usage)) => {
let content = assistant_msg.content.clone().unwrap_or_default();
let tool_calls = assistant_msg.tool_calls.clone().unwrap_or_default();
push_event(
&params.turn_events,
TurnEvent::StreamDone(assistant_msg.clone()),
);
emit_usage(&params.turn_events, usage);
// ── No tool calls → assistant is done ──────────────
if tool_calls.is_empty() {
params.messages.push(ChatMessage::assistant(Some(content)));
break;
}
params.messages.push(assistant_msg);
// ── Execute each tool call ──────────────────────────
for tc in &tool_calls {
let output =
execute_tool_call(self.tool_executor.as_ref(), &params.turn_events, tc).await;
params
.messages
.push(ChatMessage::tool(tc.id.clone(), output));
}
}
Err(e) => {
warn!("{e}");
push_event(
&params.turn_events,
TurnEvent::Error(e),
);
break;
}
}
}
// Remove the synthetic sys_msg before shipping events to the TUI
// so the transcript shows only the actual user/assistant/tool exchange.
let compacted: Vec<ChatMessage> = params.messages.drain(original_count - 1..).collect();
push_event(
&params.turn_events,
TurnEvent::Compacted(compacted),
);
push_event(&params.turn_events, TurnEvent::Done);
params.in_flight.store(false, Ordering::SeqCst);
Ok(())
}
}
// ---------------------------------------------------------------------------
// Conversation compaction
// ---------------------------------------------------------------------------
/// Maximum number of recent messages to preserve during compaction.
const COMPACT_KEEP_TAIL: usize = 6;
/// Compacts conversation history using AI summarisation.
///
/// Flow: if the message count exceeds `KEEP_TAIL + 2`, the oldest messages
/// are drained and summarised by the LLM. The summary is inserted as a
/// system message at the head of the remaining history.
pub async fn compact_messages_with_ai<P: ProviderService>(
messages: &mut Vec<ChatMessage>,
provider: &P,
) -> anyhow::Result<()> {
if messages.len() <= COMPACT_KEEP_TAIL + 2 {
return Ok(()); // Not enough messages to compact
}
let split_idx = messages.len() - COMPACT_KEEP_TAIL;
let evicted: Vec<_> = messages.drain(..split_idx).collect();
let mut summary_prompt = vec![
ChatMessage::system(zesdex_domain::compaction_prompt()),
];
summary_prompt.extend(evicted);
summary_prompt.push(ChatMessage::user(
"Please summarise our previous conversation above for context continuity.".to_string(),
));
match provider.chat(&summary_prompt, None, Some(1024), Some(0.3)).await {
Ok((summary_msg, _)) => {
let summary_text = summary_msg
.content
.unwrap_or_else(|| "Previous context summarised.".to_string());
let summary_node = ChatMessage::system(format!(
"[AI Summary of Previous Conversation]\n{}",
summary_text.trim()
));
messages.insert(0, summary_node);
Ok(())
}
Err(e) => {
warn!("AI summarisation failed during compact, falling back to simple notice: {e}");
messages.insert(
0,
ChatMessage::system(
"[Earlier conversation messages compacted to save context window]".to_string(),
),
);
Ok(())
}
}
}
+16
View File
@@ -0,0 +1,16 @@
//! Auth use-case implementations.
//!
//! Contains concrete service types that implement the domain's
//! authentication and session management traits by coordinating
//! injected repository and port dependencies.
//!
//! # Use Cases
//!
//! - [`oauth_service`] — `OAuthUseCase`: OAuth 2.0 authorization-code + PKCE flow
//! - [`session_service`] — `SessionServiceImpl`: session CRUD lifecycle
pub mod oauth_service;
pub mod session_service;
pub use oauth_service::{OAuthFlowStore, OAuthUseCase, TokenExchanger};
pub use session_service::SessionServiceImpl;
+250
View File
@@ -0,0 +1,250 @@
//! OAuth 2.0 authorization-code + PKCE flow use-case.
//!
//! `OAuthUseCase` orchestrates the standard PKCE-enhanced OAuth flow:
//!
//! 1. **`start_flow`** — generates a cryptographic PKCE code verifier,
//! derives its S256 challenge, creates a CSRF state token, persists
//! the verifier + state via `OAuthFlowStore`, and builds an
//! authorization URL with all required parameters.
//! 2. **`complete_flow`** — validates the returned `state` against the
//! stored value (CSRF check), reads the stored verifier, delegates
//! the token-code exchange to an injected `TokenExchanger`, and
//! persists the resulting `OAuthToken` via `OAuthRepository`.
//! 3. **`get_token`** — loads the stored OAuth token (if any).
//!
//! # Portability
//!
//! The service is generic over three injected dependencies:
//! - `R: OAuthRepository` — token persistence
//! - `S: OAuthFlowStore` — ephemeral flow state (verifier + CSRF state)
//! - `E: TokenExchanger` — the HTTP token-endpoint exchange
//!
//! This keeps all I/O and protocol-level concerns abstracted behind
//! port traits; the service itself contains only orchestration logic.
use std::path::PathBuf;
use tracing;
use zesdex_domain::auth::{OAuthConfig, OAuthRepository, OAuthToken, ServiceError};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use sha2::{Digest, Sha256};
// ---------------------------------------------------------------------------
// Port traits (defined here because they are specific to this use-case)
// ---------------------------------------------------------------------------
/// Persistence contract for ephemeral OAuth flow state.
///
/// Between `start_flow` and `complete_flow` the verifier and CSRF state
/// must survive across process boundaries (the user opens a browser, the
/// provider redirects back to a loopback listener on the next invocation).
///
/// Implementors store key-value pairs to disk or another durable medium
/// and clear them after a successful (or failed) flow completion.
pub trait OAuthFlowStore: Send + Sync {
/// Persist the PKCE code verifier and CSRF state token.
fn save_flow_state(
&self,
verifier: &str,
state: &str,
) -> Result<(), ServiceError>;
/// Load the stored PKCE code verifier.
fn load_verifier(&self) -> Result<String, ServiceError>;
/// Load the stored CSRF state token.
fn load_state(&self) -> Result<String, ServiceError>;
/// Clear stored flow state (verifier + state).
fn clear(&self) -> Result<(), ServiceError>;
}
/// Abstraction for exchanging an authorization code for tokens.
///
/// Implementors handle the HTTP POST to the provider's token endpoint
/// with the appropriate form-encoded parameters, parse the JSON
/// response, and return the extracted `OAuthToken`.
pub trait TokenExchanger: Send + Sync {
/// Exchange an authorization code for an access token.
///
/// ## Parameters
/// - `token_url` — the provider's token endpoint URL
/// - `client_id` — OAuth client identifier
/// - `client_secret` — optional client secret
/// - `redirect_uri` — must match the URI used in `start_flow`
/// - `code` — the authorization code from the provider's redirect
/// - `code_verifier` — the PKCE verifier from `start_flow`
fn exchange_code(
&self,
token_url: &str,
client_id: &str,
client_secret: Option<&str>,
redirect_uri: &str,
code: &str,
code_verifier: &str,
) -> Result<OAuthToken, ServiceError>;
}
// ---------------------------------------------------------------------------
// PKCE helpers
// ---------------------------------------------------------------------------
/// Generate a PKCE code-verifier and its S256 code-challenge.
///
/// Uses 32 cryptographically random bytes, base64url-encoded (no padding)
/// for the verifier, then SHA-256 hashes the verifier and base64url-encodes
/// the digest for the challenge. This satisfies the PKCE `S256` method
/// which requires a minimum verifier length of 43 characters.
fn generate_pkce_pair() -> (String, String) {
// 32 random bytes → 43 base64url chars (well above the 43-char PKCE
// minimum).
let mut bytes = [0u8; 32];
bytes[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
bytes[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
let verifier = URL_SAFE_NO_PAD.encode(bytes);
let challenge = {
let mut hasher = Sha256::new();
hasher.update(verifier.as_bytes());
URL_SAFE_NO_PAD.encode(hasher.finalize())
};
(verifier, challenge)
}
/// Generate a random CSRF state token (UUID-based, 36 chars).
fn generate_state_token() -> String {
uuid::Uuid::new_v4().to_string()
}
// ---------------------------------------------------------------------------
// Service
// ---------------------------------------------------------------------------
/// Concrete OAuth flow use-case.
///
/// Generic over three dependencies:
/// - `R` — token persistence (`OAuthRepository`)
/// - `S` — flow-state persistence (`OAuthFlowStore`)
/// - `E` — token-endpoint HTTP exchange (`TokenExchanger`)
pub struct OAuthUseCase<R, S, E> {
/// Repository for persisting / loading OAuth tokens.
pub token_repo: R,
/// Store for ephemeral flow state (verifier + CSRF state).
pub flow_store: S,
/// Token-endpoint HTTP exchanger.
pub token_exchanger: E,
/// File path for the token JSON file.
pub token_path: PathBuf,
}
impl<R: OAuthRepository, S: OAuthFlowStore, E: TokenExchanger> OAuthUseCase<R, S, E> {
/// Create a new OAuth use-case.
pub fn new(
token_repo: R,
flow_store: S,
token_exchanger: E,
token_path: PathBuf,
) -> Self {
OAuthUseCase {
token_repo,
flow_store,
token_exchanger,
token_path,
}
}
}
impl<R: OAuthRepository, S: OAuthFlowStore, E: TokenExchanger>
zesdex_domain::auth::OAuthService for OAuthUseCase<R, S, E>
{
fn start_flow(
&self,
config: &OAuthConfig,
redirect_uri: &str,
) -> Result<(String, String), ServiceError> {
if config.auth_url.is_empty() {
return Err(ServiceError::InvalidConfig(
"OAuth auth_url is empty".to_string(),
));
}
let (verifier, challenge) = generate_pkce_pair();
let state = generate_state_token();
// Persist verifier + state so `complete_flow` can retrieve them.
self.flow_store.save_flow_state(&verifier, &state)?;
tracing::debug!(
auth_url = %config.auth_url,
redirect_uri = %redirect_uri,
state_len = state.len(),
"starting OAuth flow",
);
let mut url = url::Url::parse(&config.auth_url)
.map_err(|e| {
ServiceError::InvalidConfig(format!(
"invalid auth_url '{}': {e}",
config.auth_url
))
})?;
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", &config.client_id)
.append_pair("redirect_uri", redirect_uri)
.append_pair("scope", &config.scopes.join(" "))
.append_pair("state", &state)
.append_pair("code_challenge_method", "S256")
.append_pair("code_challenge", &challenge);
Ok((url.to_string(), state))
}
fn complete_flow(
&self,
config: &OAuthConfig,
redirect_uri: &str,
code: &str,
state: &str,
) -> Result<OAuthToken, ServiceError> {
// CSRF check: validate the returned state against the stored value.
let expected_state = self.flow_store.load_state()?;
if expected_state != state {
return Err(ServiceError::StateMismatch);
}
// Read the PKCE verifier that was saved in `start_flow`.
let verifier = self.flow_store.load_verifier()?;
tracing::debug!(
token_url = %config.token_url,
code_len = code.len(),
"completing OAuth flow — exchanging code for token",
);
// Delegate the HTTP token exchange to the injected exchanger.
let token = self.token_exchanger.exchange_code(
&config.token_url,
&config.client_id,
config.client_secret.as_deref(),
redirect_uri,
code,
&verifier,
)?;
// Persist the token and clean up flow state.
self.token_repo.save_token(&self.token_path, &token)?;
let _ = self.flow_store.clear();
Ok(token)
}
fn get_token(&self) -> Result<Option<OAuthToken>, ServiceError> {
self.token_repo
.load_token(&self.token_path)
.map_err(ServiceError::Repository)
}
}
@@ -0,0 +1,89 @@
//! Session management use-case.
//!
//! `SessionServiceImpl` implements [`SessionService`] from the domain
//! layer by delegating CRUD operations to injected repository traits.
//!
//! # Flow
//!
//! - **`create_session`** — generates a UUID v4 id, creates a `Session`
//! entity with the given title, persists via `SessionRepository`.
//! - **`list_all`** — delegates to `SessionRepository::list_sessions`.
//! - **`archive_session`** — loads session, sets `archived = true`,
//! persists the updated entity.
//!
//! # Generics
//!
//! - `R: SessionRepository` — session CRUD persistence
//! - `L: SessionLockRepository` — session lock acquire/release
use std::path::PathBuf;
use tracing;
use uuid::Uuid;
use zesdex_domain::auth::{
ServiceError, Session, SessionId, SessionLockRepository, SessionRepository,
};
/// Concrete session service backed by injected repository implementations.
pub struct SessionServiceImpl<R: SessionRepository, L: SessionLockRepository> {
/// Repository for session CRUD operations.
pub session_repo: R,
/// Repository for session lock acquire/release.
pub lock_repo: L,
/// Base data directory passed to repository methods.
pub base_dir: PathBuf,
}
impl<R: SessionRepository, L: SessionLockRepository> SessionServiceImpl<R, L> {
/// Create a new session service with the given repositories and base
/// data directory.
pub fn new(session_repo: R, lock_repo: L, base_dir: PathBuf) -> Self {
SessionServiceImpl {
session_repo,
lock_repo,
base_dir,
}
}
}
impl<R: SessionRepository, L: SessionLockRepository>
zesdex_domain::auth::SessionService for SessionServiceImpl<R, L>
{
fn create_session(&self, title: &str) -> Result<Session, ServiceError> {
let id = SessionId::new(&Uuid::new_v4().to_string())
.map_err(ServiceError::Other)?;
let title_owned = if title.is_empty() {
"New Session".to_string()
} else {
title.to_string()
};
let session = Session::new(id.into_string(), title_owned);
tracing::debug!(session_id = %session.id, title = %session.title, "creating new session");
self.session_repo
.save_session(&self.base_dir, &session)?;
Ok(session)
}
fn list_all(&self) -> Result<Vec<Session>, ServiceError> {
tracing::debug!("listing all sessions");
self.session_repo
.list_sessions(&self.base_dir)
.map_err(ServiceError::Repository)
}
fn archive_session(&self, id: SessionId) -> Result<(), ServiceError> {
tracing::debug!(session_id = %id, "archiving session");
let mut session = self
.session_repo
.load_session(&self.base_dir, &id)?;
session.archived = true;
let millis = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis();
session.updated_at = i64::try_from(millis).unwrap_or(i64::MAX);
self.session_repo
.save_session(&self.base_dir, &session)?;
Ok(())
}
}
@@ -0,0 +1,72 @@
//! Conversation use-case implementation.
//!
//! `ConversationServiceImpl` implements [`ConversationService`] from the
//! domain layer. It is generic over `R: ConversationRepository`, delegating
//! all persistence to that adapter.
//!
//! # Flow
//!
//! Each method computes the session directory from the session ID, then
//! delegates the actual I/O to the injected `repo`. Error context is
//! added at this layer to identify which session caused the failure.
use std::path::PathBuf;
use tracing;
use zesdex_domain::cms::{Conversation, ConversationRepository, ServiceError};
use zesdex_domain::core::ChatMessage;
/// Service implementation for conversation CRUD operations.
///
/// Generic over `R: ConversationRepository` so the persistence layer
/// can be swapped without changing business logic.
pub struct ConversationServiceImpl<R> {
pub repo: R,
/// Base directory containing session subdirectories.
pub sessions_dir: PathBuf,
}
impl<R: ConversationRepository> ConversationServiceImpl<R> {
/// Create a new service with the given repository and sessions directory.
pub fn new(repo: R, sessions_dir: impl Into<PathBuf>) -> Self {
tracing::debug!("creating ConversationServiceImpl");
Self {
repo,
sessions_dir: sessions_dir.into(),
}
}
/// Compute the session directory for a given session id.
fn session_dir(&self, session_id: &str) -> PathBuf {
self.sessions_dir.join(session_id)
}
}
impl<R: ConversationRepository> zesdex_domain::cms::ConversationService
for ConversationServiceImpl<R>
{
fn load_conversation(&self, session_id: &str) -> Result<Conversation, ServiceError> {
tracing::debug!("loading conversation for session {session_id}");
let dir = self.session_dir(session_id);
self.repo.load(&dir).map_err(ServiceError::Repository)
}
fn save_conversation(&self, conv: &Conversation) -> Result<(), ServiceError> {
tracing::debug!("saving conversation for session {}", conv.session_id);
let dir = self.session_dir(&conv.session_id);
self.repo.save(&dir, conv)?;
Ok(())
}
fn add_message(
&self,
conv: &mut Conversation,
msg: ChatMessage,
) -> Result<(), ServiceError> {
tracing::debug!("adding message to session {}", conv.session_id);
conv.push(msg);
let dir = self.session_dir(&conv.session_id);
self.repo.save(&dir, conv)?;
Ok(())
}
}
@@ -0,0 +1,59 @@
//! Memory use-case implementation.
//!
//! `MemoryServiceImpl` implements [`MemoryService`] from the domain
//! layer. It is generic over `R: MemoryRepository`, delegating all
//! persistence to that adapter.
//!
//! # Flow
//!
//! Each method delegates to the injected `repo` with the configured
//! `memory_dir`. Error context is added at this layer to identify which
//! memory operation failed.
use std::path::PathBuf;
use tracing;
use zesdex_domain::cms::{Memory, MemoryRepository, ServiceError};
/// Service implementation for memory CRUD operations.
///
/// Generic over `R: MemoryRepository` so the persistence layer can be
/// swapped without changing business logic.
pub struct MemoryServiceImpl<R> {
pub repo: R,
/// Base directory for memory storage files.
pub memory_dir: PathBuf,
}
impl<R: MemoryRepository> MemoryServiceImpl<R> {
/// Create a new service with the given repository and memory directory.
pub fn new(repo: R, memory_dir: impl Into<PathBuf>) -> Self {
tracing::debug!("creating MemoryServiceImpl");
Self {
repo,
memory_dir: memory_dir.into(),
}
}
}
impl<R: MemoryRepository> zesdex_domain::cms::MemoryService for MemoryServiceImpl<R> {
fn list_memories(&self) -> Result<Vec<String>, ServiceError> {
tracing::debug!("listing memories from {:?}", self.memory_dir);
self.repo
.list(&self.memory_dir)
.map_err(ServiceError::Repository)
}
fn save_memory(&self, memory: &Memory) -> Result<(), ServiceError> {
tracing::debug!("saving memory '{}'", memory.name);
self.repo.save(&self.memory_dir, memory)?;
Ok(())
}
fn delete_memory(&self, name: &str) -> Result<(), ServiceError> {
tracing::debug!("deleting memory '{name}'");
self.repo
.delete(&self.memory_dir, name)
.map_err(ServiceError::Repository)
}
}
+18
View File
@@ -0,0 +1,18 @@
//! CMS use-case implementations.
//!
//! Contains concrete service types that implement the domain's CMS
//! service traits by coordinating injected repository dependencies.
//!
//! # Use Cases
//!
//! - [`conversation_service`] — `ConversationServiceImpl`: conversation CRUD
//! - [`memory_service`] — `MemoryServiceImpl`: long-term memory management
//! - [`settings_service`] — `SettingsServiceImpl`: settings & app-config management
pub mod conversation_service;
pub mod memory_service;
pub mod settings_service;
pub use conversation_service::ConversationServiceImpl;
pub use memory_service::MemoryServiceImpl;
pub use settings_service::SettingsServiceImpl;
@@ -0,0 +1,76 @@
//! Settings and app-config use-case implementation.
//!
//! `SettingsServiceImpl` implements [`SettingsService`] from the domain
//! layer. It is generic over `S: SettingsRepository` and `C: AppConfigRepository`,
//! delegating persistence to those adapters.
//!
//! # Flow
//!
//! Each method delegates to the appropriate injected repository with the
//! configured `base_dir`. The `update_provider` method coordinates between
//! both repositories: load app config → mutate provider map → save app config.
use std::path::PathBuf;
use tracing;
use zesdex_domain::cms::{
AppConfig, AppConfigRepository, ProviderConfig, ServiceError, Settings,
SettingsRepository,
};
/// Service implementation for settings and app-config operations.
///
/// Generic over `S: SettingsRepository` and `C: AppConfigRepository` so
/// the persistence layer can be swapped without changing business logic.
pub struct SettingsServiceImpl<S, C> {
pub settings_repo: S,
pub app_config_repo: C,
pub base_dir: PathBuf,
}
impl<S: SettingsRepository, C: AppConfigRepository> SettingsServiceImpl<S, C> {
/// Create a new service with the given repositories and base directory.
pub fn new(
settings_repo: S,
app_config_repo: C,
base_dir: impl Into<PathBuf>,
) -> Self {
tracing::debug!("creating SettingsServiceImpl");
Self {
settings_repo,
app_config_repo,
base_dir: base_dir.into(),
}
}
}
impl<S: SettingsRepository, C: AppConfigRepository>
zesdex_domain::cms::SettingsService for SettingsServiceImpl<S, C>
{
fn load_settings(&self) -> Result<Settings, ServiceError> {
tracing::debug!("loading settings");
self.settings_repo
.load(&self.base_dir)
.map_err(ServiceError::Repository)
}
fn save_settings(&self, settings: &Settings) -> Result<(), ServiceError> {
tracing::debug!("saving settings");
self.settings_repo.save(&self.base_dir, settings)?;
Ok(())
}
fn update_provider(
&self,
name: &str,
config: &ProviderConfig,
) -> Result<(), ServiceError> {
tracing::debug!("updating provider '{name}'");
let mut app_config: AppConfig = self.app_config_repo.load(&self.base_dir)?;
app_config
.providers
.insert(name.to_string(), config.clone());
self.app_config_repo.save(&self.base_dir, &app_config)?;
Ok(())
}
}
+54
View File
@@ -0,0 +1,54 @@
//! # Zesdex Application Layer
//!
//! Defines port traits (interfaces) and use-case implementations for the
//! Zesdex application. This crate depends **only** on the domain crate;
//! it has no knowledge of infrastructure or interface adapters.
//!
//! ## Architecture
//!
//! ```text
//! apps/application/src/
//! ├── lib.rs — crate root, re-exports
//! ├── ports/ — Port traits (interfaces to external services)
//! │ ├── provider.rs -- ProviderService (LLM chat completion)
//! │ ├── password.rs -- PasswordService (hash / verify)
//! │ ├── token.rs -- TokenService (JWT create / verify)
//! │ └── authentication.rs -- AuthService (combined auth)
//! ├── auth/ — Auth use-cases
//! │ ├── oauth_service.rs -- OAuth 2.0 PKCE flow
//! │ └── session_service.rs -- Session CRUD lifecycle
//! └── cms/ — CMS use-cases
//! ├── conversation_service.rs -- Conversation CRUD
//! ├── memory_service.rs -- Long-term memory management
//! └── settings_service.rs -- Settings & app-config management
//! ```
//!
//! ## Key Design Principle
//!
//! Application services are generic over their repository/port dependencies.
//! Concrete implementations are injected at the composition root, keeping
//! the use-case logic independent of any specific persistence or infrastructure
//! technology.
pub mod auth;
pub mod cms;
pub mod ports;
pub mod agent;
// Re-export port traits for ergonomic access.
pub use ports::*;
// Re-export auth use-cases.
pub use auth::{
oauth_service::{OAuthFlowStore, OAuthUseCase, TokenExchanger},
session_service::SessionServiceImpl,
};
// Re-export CMS use-cases.
pub use cms::{
conversation_service::ConversationServiceImpl,
memory_service::MemoryServiceImpl,
settings_service::SettingsServiceImpl,
};
pub use agent::{AgentTurnService, ToolExecutor, turn_service::{AgentTurnServiceImpl, compact_messages_with_ai}};
@@ -0,0 +1,35 @@
//! AuthService port — combined authentication operations.
//!
//! Defines a high-level authentication trait that composes password
//! verification and token generation into a single use-case boundary.
//! Implementations delegate to the injected `PasswordService` and
//! `TokenService` adapters.
use anyhow::Result;
use std::future::Future;
/// High-level authentication service combining password verification
/// and token issuance (login flow).
///
/// # Flow
///
/// 1. **`authenticate`** — verify a subject's password against a stored hash.
/// 2. **`issue_tokens`** — generate an access + refresh token pair for a subject.
///
/// Implementations are generic over `PasswordService` and `TokenService`
/// port traits.
pub trait AuthService: Send + Sync {
/// Authenticate a user by verifying a password against a stored hash.
///
/// Returns `true` if the password matches, `false` otherwise.
fn authenticate(
&self,
password: &str,
hash: &str,
) -> impl Future<Output = Result<bool>> + Send;
/// Issue a new access + refresh token pair for the given subject.
///
/// Returns `(access_token, refresh_token)`.
fn issue_tokens(&self, sub: &str) -> Result<(String, String)>;
}
+22
View File
@@ -0,0 +1,22 @@
//! Port traits — interfaces for external / infrastructure services.
//!
//! These traits define the boundaries between the application layer and
//! the outside world. Infrastructure adapters implement these traits;
//! the application layer depends only on the trait definitions.
//!
//! # Ports
//!
//! - [`provider`] — `ProviderService`: LLM chat completion (streaming + non-streaming)
//! - [`password`] — `PasswordService`: password hashing and verification
//! - [`token`] — `TokenService`: JWT access/refresh token generation and verification
//! - [`authentication`] — `AuthService`: combined authentication operations
pub mod authentication;
pub mod password;
pub mod provider;
pub mod token;
pub use authentication::AuthService;
pub use password::PasswordService;
pub use provider::ProviderService;
pub use token::TokenService;
+24
View File
@@ -0,0 +1,24 @@
//! PasswordService port — password hashing and verification abstraction.
//!
//! Defines the trait that password-hashing adapters (argon2, bcrypt, etc.)
//! implement. The application layer depends only on this trait, never on
//! a concrete hashing library.
use anyhow::Result;
use std::future::Future;
/// Abstraction for password hashing and verification.
///
/// Implementors handle the actual hashing algorithm (argon2, bcrypt, etc.)
/// and parameter selection. The trait is `Send + Sync` for use in async
/// service layers.
pub trait PasswordService: Send + Sync {
/// Hash a plaintext password and return the encoded hash string
/// (suitable for storage in a credential store).
fn hash(&self, password: &str) -> impl Future<Output = Result<String>> + Send;
/// Verify a plaintext password against a previously-hashed string.
///
/// Returns `true` if the password matches the hash, `false` otherwise.
fn verify(&self, password: &str, hash: &str) -> impl Future<Output = Result<bool>> + Send;
}
+56
View File
@@ -0,0 +1,56 @@
//! ProviderService port — LLM chat completion provider abstraction.
//!
//! Defines the trait that HTTP-based provider clients (OpenAI, Anthropic,
//! etc.) implement. Supports both non-streaming and SSE-streaming chat
//! completion requests.
//!
//! # Flow
//!
//! 1. Caller builds a message list and optional tool definitions.
//! 2. `chat` sends a non-streaming request and returns the full response.
//! 3. `chat_stream` sends a streaming request and invokes `on_event` for
//! each parsed `StreamEvent` as it arrives, then returns the assembled
//! message and usage.
use anyhow::Result;
use std::future::Future;
use zesdex_domain::core::{ChatMessage, StreamEvent, ToolDef};
/// Abstraction for an LLM provider chat-completion service.
///
/// Both methods accept a message list, optional tool definitions, and
/// generation parameters. Implementors handle authentication, HTTP
/// transport, retry logic, and response parsing internally.
///
/// # Send + Sync
///
/// This trait is `Send + Sync` so it can be shared across async tasks
/// and injected into service structs that require thread safety.
pub trait ProviderService: Send + Sync {
/// Send a non-streaming chat completion request.
///
/// Returns the assistant's `ChatMessage` and optional token usage
/// `(prompt_tokens, completion_tokens)`.
fn chat(
&self,
messages: &[ChatMessage],
tools: Option<Vec<ToolDef>>,
max_tokens: Option<u32>,
temperature: Option<f32>,
) -> impl Future<Output = Result<(ChatMessage, Option<(u64, u64)>)>> + Send;
/// Send a streaming chat completion request.
///
/// `on_event` is called for every parsed SSE event and returns `false`
/// to signal abort (caller cancellation). Returns the fully assembled
/// assistant message and optional usage once the stream completes.
fn chat_stream(
&self,
messages: &[ChatMessage],
tools: Option<Vec<ToolDef>>,
max_tokens: Option<u32>,
temperature: Option<f32>,
on_event: Box<dyn FnMut(&StreamEvent) -> bool + Send>,
) -> impl Future<Output = Result<(ChatMessage, Option<(u64, u64)>)>> + Send;
}
+32
View File
@@ -0,0 +1,32 @@
//! TokenService port — JWT access and refresh token abstraction.
//!
//! Defines the trait that JWT adapter implementations provide. Covers
//! token generation (pair of access + refresh tokens) and access token
//! verification (returns the subject claim).
use anyhow::Result;
/// Abstraction for JWT-based token generation and verification.
///
/// Implementors handle signing key management, token serialisation,
/// and expiry validation. The trait is `Send + Sync` for use across
/// thread boundaries.
pub trait TokenService: Send + Sync {
/// Generate an access + refresh token pair for the given subject
/// identifier.
///
/// Returns `(access_token, refresh_token)`.
fn generate_tokens(&self, sub: &str) -> Result<(String, String)>;
/// Verify an access token and return the embedded subject claim.
///
/// Returns `Err` if the token is expired, malformed, or has an
/// invalid signature.
fn verify_access_token(&self, token: &str) -> Result<String>;
/// Verify a refresh token and return the embedded subject claim.
///
/// Returns `Err` if the token is expired, malformed, or has an
/// invalid signature.
fn verify_refresh_token(&self, token: &str) -> Result<String>;
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "zesdex-bootstrap"
version.workspace = true
edition.workspace = true
authors.workspace = true
# Bootstrap binary — seeds initial system data (permissions, roles,
# admin user) idempotently. Run once after first deployment.
[[bin]]
name = "bootstrap"
path = "src/main.rs"
[dependencies]
zesdex-domain = { path = "../domain" }
zesdex-application = { path = "../application" }
zesdex-infrastructure = { path = "../infrastructure" }
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
uuid.workspace = true
anyhow.workspace = true
tokio.workspace = true
tracing.workspace = true
dirs.workspace = true
+2
View File
@@ -0,0 +1,2 @@
//! Bootstrap library — shared utilities for the bootstrap binary.
//! The main entry point is in `main.rs`.
+44
View File
@@ -0,0 +1,44 @@
//! Bootstrap binary — seeds initial system data idempotently.
//!
//! Creates default permissions, roles, and admin user if they don't
//! already exist. Run once after first deployment.
//!
//! Usage: cargo run --bin bootstrap
fn main() -> anyhow::Result<()> {
println!("Zesdex Bootstrap — seeding initial data...");
let store = zesdex_domain::core::Store::new();
store.ensure_dirs()?;
// Seed default settings if not present
let settings_path = store.base_dir.join("settings.json");
if !settings_path.exists() {
let settings = zesdex_domain::cms::Settings::default();
let content = serde_json::to_string_pretty(&settings)?;
let tmp = store.base_dir.join("settings.json.tmp");
std::fs::write(&tmp, &content)?;
std::fs::File::open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &settings_path)?;
println!(" ✓ Default settings created");
} else {
println!(" · Settings already exist, skipping");
}
// Seed default app config if not present
let config_path = store.base_dir.join("app_config.json");
if !config_path.exists() {
let config = zesdex_domain::cms::AppConfig::default();
let content = serde_json::to_string_pretty(&config)?;
let tmp = store.base_dir.join("app_config.json.tmp");
std::fs::write(&tmp, &content)?;
std::fs::File::open(&tmp)?.sync_all()?;
std::fs::rename(&tmp, &config_path)?;
println!(" ✓ Default app_config created");
} else {
println!(" · App config already exists, skipping");
}
println!("Bootstrap complete.");
Ok(())
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "zesdex-domain"
version.workspace = true
edition.workspace = true
authors.workspace = true
# Domain layer — PURE entities, value objects, repository/service traits.
# Zero framework dependencies. Only serde for serialization, chrono for
# timestamps, uuid for identity.
[dependencies]
serde.workspace = true
serde_json.workspace = true
chrono.workspace = true
uuid.workspace = true
base64.workspace = true
sha2.workspace = true
url.workspace = true
libc.workspace = true
anyhow.workspace = true
tracing.workspace = true
+34
View File
@@ -0,0 +1,34 @@
//! Shared default constants used across the application.
//!
//! Centralising these values eliminates the hardcoded-string duplication
//! that existed when every call site provided its own inline fallback.
//! Consumers should reference these constants rather than repeating
//! the string literals.
/// Default LLM provider API base URL.
pub const DEFAULT_API_BASE: &str = "https://opencode.ai/zen/v1";
/// Default LLM model identifier.
pub const DEFAULT_MODEL: &str = "deepseek-v4-flash-free";
/// Fallback JWT secret used only when `JWT_SECRET` env var is unset.
/// In production this MUST be configured via environment variable.
pub const FALLBACK_JWT_SECRET: &str = "dev-secret";
/// Default context window size (128k tokens).
pub const DEFAULT_CONTEXT_WINDOW: usize = 256_000;
/// Maximum tool-call iterations per agent turn.
pub const MAX_TOOL_ITERATIONS: u32 = 50;
/// Maximum subagent tool-call iterations.
pub const MAX_SUBAGENT_ITERATIONS: u32 = 25;
/// Default LLM request max tokens.
pub const DEFAULT_MAX_TOKENS: u32 = 4096;
/// Default temperature for the main agent.
pub const DEFAULT_TEMPERATURE: f64 = 0.7;
/// Default temperature for compaction / summary calls.
pub const DEFAULT_COMPACT_TEMPERATURE: f64 = 0.3;
+260
View File
@@ -0,0 +1,260 @@
//! Domain types for agent lifecycle: turn events, session runtime, progress
//! reporting, prompts, and the agent-turn parameter bundle.
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::core::{ChatMessage, ToolCallResult, UsageStats};
pub mod defaults;
pub mod prompt;
pub mod progress;
/// Which kind of caller (main agent vs. subagent vs. reviewer) is
/// invoking a tool, used to scope permissions and tag log/output paths.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum Origin {
/// The main agent turn loop.
Main,
/// A spawned subagent (test-gen, arch-review, security-review, etc.).
SubAgent,
/// The auto-inline review step after an edit.
Reviewer,
}
impl Origin {
/// Short string tag for this origin, used in filenames and logs.
pub fn tag(self) -> String {
match self {
Origin::Main => "main",
Origin::SubAgent => "subagent",
Origin::Reviewer => "reviewer",
}
.to_string()
}
}
/// Severity/category of a toast notification, used to pick its color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ToastKind {
Info,
Success,
Warning,
Error,
Lesson,
}
/// A transient status message shown in the TUI, auto-dismissed after `lifetime_ms`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Toast {
pub kind: ToastKind,
pub message: String,
pub created_at: i64,
pub lifetime_ms: u64,
}
impl Toast {
/// Create a toast with a default 5-second lifetime, stamped with now.
pub fn new(kind: ToastKind, message: String) -> Self {
Toast {
kind,
message,
created_at: chrono::Utc::now().timestamp_millis(),
lifetime_ms: 5000,
}
}
/// Whether this toast's lifetime has elapsed as of `now_ms`.
pub fn expired(&self, now_ms: i64) -> bool {
let lifetime = self.lifetime_ms as i64;
now_ms - self.created_at > lifetime
}
}
/// Agent status for workflow engine progress tracking.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AgentStatus {
Pending,
Running,
Completed,
Failed(String),
Cancelled,
}
impl std::fmt::Display for AgentStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AgentStatus::Pending => write!(f, "pending"),
AgentStatus::Running => write!(f, "running"),
AgentStatus::Completed => write!(f, "completed"),
AgentStatus::Failed(msg) => write!(f, "failed: {msg}"),
AgentStatus::Cancelled => write!(f, "cancelled"),
}
}
}
/// Events emitted onto the turn-event queue while an agent turn runs,
/// consumed by the event loop to update state and drive re-renders.
#[derive(Debug, Clone)]
pub enum TurnEvent {
AssistantMessage(ChatMessage),
ToolResult {
tool_call_id: String,
tool_name: String,
output: String,
is_error: bool,
path: Option<String>,
},
SystemNote {
kind: String,
message: String,
},
StreamStart,
StreamToken(String),
StreamReasoning(String),
StreamDone(ChatMessage),
Usage {
tokens_in: u64,
tokens_out: u64,
},
ReviewUsage {
tokens_in: u64,
tokens_out: u64,
},
Compacted(Vec<ChatMessage>),
Error(String),
Done,
WorkflowAgentUpdate {
agent_id: String,
agent_name: String,
status: AgentStatus,
},
TodoUpdate(String),
PlanUpdate(String),
/// Structured progress report from a subagent or workflow node,
/// carrying the current tool name and optional step counters.
AgentProgress(crate::agent::progress::AgentProgress),
}
/// How a pending tool call should be executed when the turn resumes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExecutionModel {
Inline,
Deferred,
AsyncTokio,
}
/// A tool call awaiting execution, along with which execution model
/// (inline, deferred, async) it should run under.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingTool {
pub tool_name: String,
pub args: serde_json::Value,
pub execution_model: ExecutionModel,
}
/// Reference to a background bash job tracked in session state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BashJobRef {
pub id: String,
pub command: String,
pub started_at: i64,
pub running: bool,
}
/// Tracks counts of learned patterns by outcome and lifecycle stage.
#[derive(Debug, Clone, Default)]
pub struct LessonStats {
/// Total number of lessons tracked.
pub total: u32,
/// User-initiated lessons.
pub user: u32,
/// Feedback-driven lessons.
pub feedback: u32,
/// Project-scoped lessons.
pub project: u32,
/// Reference-scoped lessons.
pub reference: u32,
/// Currently active lessons.
pub active: u32,
/// Stale (outdated) lessons.
pub stale: u32,
/// Contradicted lessons.
pub contradicted: u32,
/// Human-authored lessons.
pub human: u32,
/// Verified lessons.
pub verified: u32,
/// Unverified lessons.
pub unverified: u32,
}
/// Per-session runtime state: message history, pending tool queue,
/// background bash jobs, lesson/review counters.
#[derive(Debug, Clone)]
pub struct SessionRuntime {
pub messages: Vec<ChatMessage>,
pub tool_call_results: Vec<ToolCallResult>,
pub pending_tool_queue: Vec<PendingTool>,
pub bash_jobs: Vec<BashJobRef>,
pub subagent_queue: usize,
pub edit_count: u32,
pub consecutive_empty_reviews: u32,
pub session_start: i64,
/// Aggregated lesson statistics.
pub lessons: LessonStats,
pub review_count: u32,
pub session_dir: PathBuf,
pub usage: UsageStats,
pub hive_mind_converged: bool,
}
impl SessionRuntime {
pub fn new(session_dir: PathBuf) -> Self {
SessionRuntime {
messages: Vec::new(),
tool_call_results: Vec::new(),
pending_tool_queue: Vec::new(),
bash_jobs: Vec::new(),
subagent_queue: 0,
edit_count: 0,
consecutive_empty_reviews: 0,
session_start: chrono::Utc::now().timestamp_millis(),
lessons: LessonStats::default(),
review_count: 0,
session_dir,
usage: UsageStats::default(),
hive_mind_converged: false,
}
}
pub fn push_message(&mut self, msg: ChatMessage) {
self.messages.push(msg);
}
}
/// Simple ASCII progress display for a long-running operation.
#[derive(Debug, Clone)]
pub struct ProgressState {
pub current: u64,
pub total: u64,
pub message: String,
pub start_time: i64,
}
use std::collections::VecDeque;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
/// Owned parameters required to spawn and execute an agent turn.
pub struct AgentTurnParams {
pub messages: Vec<ChatMessage>,
pub session_dir: PathBuf,
pub workspace_roots: Vec<PathBuf>,
pub turn_events: Arc<Mutex<VecDeque<TurnEvent>>>,
pub in_flight: Arc<AtomicBool>,
pub abort: Arc<AtomicBool>,
pub api_key: String,
pub model: String,
pub api_base: Option<String>,
}
+81
View File
@@ -0,0 +1,81 @@
//! Progress reporting types for long-running agent and subagent operations.
//!
//! These types are emitted onto the turn-event queue to drive the TUI's
//! spinner, progress bar, and agent-status sidebar. They are pure domain
//! types with no I/O or framework dependency.
use crate::agent::AgentStatus;
/// Describes progress within a single subagent or workflow-node execution.
///
/// Emitted as a `TurnEvent::AgentProgress` so the UI can show which tool
/// the subagent is currently invoking, or which step it has reached.
#[derive(Debug, Clone)]
pub struct AgentProgress {
/// Unique identifier for this agent (e.g. `"Node-0-1"`, `"auto-review"`).
pub agent_id: String,
/// Human-readable display name shown in the TUI sidebar.
pub agent_name: String,
/// Current lifecycle status.
pub status: AgentStatus,
/// Optional description of the current tool or step being executed.
/// Set to `None` when the agent is not actively executing a tool.
pub current_tool: Option<String>,
/// Optional progress range: (completed_steps, total_steps).
/// When `None`, the agent shows an indeterminate spinner.
pub steps: Option<(u32, u32)>,
}
impl AgentProgress {
/// Mark this agent as running with an optional tool name.
pub fn running(
agent_id: impl Into<String>,
agent_name: impl Into<String>,
current_tool: Option<String>,
) -> Self {
AgentProgress {
agent_id: agent_id.into(),
agent_name: agent_name.into(),
status: AgentStatus::Running,
current_tool,
steps: None,
}
}
/// Mark this agent as pending (queued but not yet started).
pub fn pending(agent_id: impl Into<String>, agent_name: impl Into<String>) -> Self {
AgentProgress {
agent_id: agent_id.into(),
agent_name: agent_name.into(),
status: AgentStatus::Pending,
current_tool: None,
steps: None,
}
}
/// Mark this agent as completed successfully.
pub fn completed(agent_id: impl Into<String>, agent_name: impl Into<String>) -> Self {
AgentProgress {
agent_id: agent_id.into(),
agent_name: agent_name.into(),
status: AgentStatus::Completed,
current_tool: None,
steps: None,
}
}
/// Mark this agent as failed with an error message.
pub fn failed(
agent_id: impl Into<String>,
agent_name: impl Into<String>,
error: String,
) -> Self {
AgentProgress {
agent_id: agent_id.into(),
agent_name: agent_name.into(),
status: AgentStatus::Failed(error),
current_tool: None,
steps: None,
}
}
}
+92
View File
@@ -0,0 +1,92 @@
//! System prompts and directive templates for agent and subagent turns.
//!
//! Centralising all prompt text here keeps the core turn logic free of
//! hardcoded prose, making prompts easier to maintain, review, and localise.
//!
//! # Flow
//! The application layer's `AgentTurnServiceImpl` calls `main_agent_prompt()`
//! to construct the system message at the start of each turn. Subagent and
//! review prompts are provided by their respective modules.
/// Build the main-agent system prompt.
///
/// The prompt establishes the agent's identity as Zesdex, an AI coding
/// assistant, and defines the priority hierarchy that governs tool selection:
///
/// 1. **Workflow first** — `workflow_run` / `hive_mind` for complex tasks
/// 2. **Planning & TODOs** — `plan_enter` / `todowrite` for structural work
/// 3. **Reasoning** — `seq_think` for deep analysis
/// 4. **Tool execution** — direct tools for simple actions
pub fn main_agent_prompt() -> String {
"\
You are Zesdex, an AI coding assistant. You have access to various tools \
via native function calling to help the user.
CRITICAL DIRECTIVES & PRIORITY HIERARCHY:
1. WORKFLOW FIRST: For any multi-step, complex, or non-trivial task, \
you MUST prioritise using `workflow_run` (to construct and execute a \
multi-phase YAML workflow) or `hive_mind` (to orchestrate parallel \
autonomous agents). Workflows are your primary strategy.
2. PLANNING & TODOS: Use `plan_enter` to establish high-level \
architectural plans and `todowrite` to maintain granular task checklists.
3. REASONING: Use `seq_think` for deep step-by-step analysis.
4. TOOL EXECUTION: Execute individual tools (file edits, terminal commands) \
within or guided by your workflows. If an error occurs, analyse and fix it.
Respond conversationally, concisely, and helpfully."
.to_string()
}
/// Build a subagent directive prompt.
///
/// The directive is embedded in a system message that also communicates the
/// current working directory and workspace root so the subagent can resolve
/// paths correctly.
pub fn subagent_directive(directive: &str, cwd: &str, ws_root: &str) -> String {
format!(
"\
You are a focused subagent.
Current directory (PWD): {cwd}
Workspace root: {ws_root}
Your directive:
{directive}
Complete the directive autonomously using the tools available to you. \
Return your final answer when done."
)
}
/// Build a conversation-compaction prompt.
///
/// The LLM is asked to produce a concise bulleted summary of the key
/// requests, decisions, tools executed, and files modified.
pub fn compaction_prompt() -> String {
"\
You are a helpful assistant summarising conversation history. \
Provide a concise summary of the key user requests, decisions, tools \
executed, and modified files. Format as a clear bulleted list."
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn main_prompt_is_non_empty() {
let prompt = main_agent_prompt();
assert!(!prompt.is_empty());
assert!(prompt.contains("Zesdex"));
assert!(prompt.contains("WORKFLOW FIRST"));
}
#[test]
fn subagent_directive_includes_directive_text() {
let prompt = subagent_directive("test directive", "/home", "/home/project");
assert!(prompt.contains("test directive"));
assert!(prompt.contains("/home"));
assert!(prompt.contains("/home/project"));
}
}
+30
View File
@@ -0,0 +1,30 @@
//! Command types for IAM domain operations.
//!
//! Following the `NewXxx` / command pattern from clean architecture,
//! these types encapsulate the input data for create/update operations
//! on domain entities. They decouple presentation DTOs from the entity
//! mutation surface and provide a clear boundary for validation.
/// Command to create a new session.
///
/// Carries only the data needed to construct a session entity — the
/// service generates the UUID and timestamp internally.
#[derive(Debug, Clone)]
pub struct NewSession {
/// Human-readable session title.
pub title: String,
}
impl From<String> for NewSession {
fn from(title: String) -> Self {
Self { title }
}
}
impl From<&str> for NewSession {
fn from(title: &str) -> Self {
Self {
title: title.to_string(),
}
}
}
+62
View File
@@ -0,0 +1,62 @@
//! Domain error types for the IAM (auth) module.
//!
//! Typed error enums replace `anyhow::Result` in domain traits and
//! application services, enabling callers to match on specific error
//! variants (e.g. `NotFound` vs `Conflict`) rather than string-checking.
//!
//! # Components
//!
//! - [`RepositoryError`] — persistence-layer errors (not found, conflict, I/O)
//! - [`ServiceError`] — use-case / orchestration errors (config, state
//! mismatch, provider failures)
use std::fmt;
use crate::error::DomainError;
/// Shared repository error type for IAM persistence operations.
pub type RepositoryError = DomainError;
/// Errors from service / use-case operations in the IAM domain.
#[derive(Debug)]
pub enum ServiceError {
/// A repository operation failed.
Repository(DomainError),
/// The provided configuration is invalid.
InvalidConfig(String),
/// OAuth state mismatch — possible CSRF attack.
StateMismatch,
/// The OAuth provider returned an error.
OAuthProvider(String),
/// A generic error with a message.
Other(String),
}
impl From<DomainError> for ServiceError {
fn from(err: DomainError) -> Self {
ServiceError::Repository(err)
}
}
impl fmt::Display for ServiceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServiceError::Repository(err) => write!(f, "repository error: {err}"),
ServiceError::InvalidConfig(msg) => write!(f, "invalid configuration: {msg}"),
ServiceError::StateMismatch => {
write!(f, "OAuth state mismatch — possible CSRF attack")
}
ServiceError::OAuthProvider(msg) => write!(f, "OAuth provider error: {msg}"),
ServiceError::Other(msg) => write!(f, "{msg}"),
}
}
}
impl std::error::Error for ServiceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ServiceError::Repository(err) => Some(err),
_ => None,
}
}
}

Some files were not shown because too many files have changed in this diff Show More