Compare commits
@@ -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
|
||||
```
|
||||
+2
-1
@@ -3,4 +3,5 @@ target/
|
||||
.claude/settings.local.json
|
||||
node_modules/
|
||||
package.json
|
||||
package-lock.json
|
||||
package-lock.json
|
||||
.superpowers/
|
||||
@@ -1,3 +1,47 @@
|
||||
# [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)
|
||||
|
||||
|
||||
|
||||
@@ -2,36 +2,7 @@
|
||||
|
||||
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.
|
||||
|
||||
@@ -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::* └── 37 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
|
||||
|
||||
@@ -77,60 +32,21 @@ Controller (key input → Action) → Event Loop → LLM stream → Tool executi
|
||||
- **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.
|
||||
|
||||
### 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:
|
||||
|
||||
```
|
||||
<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
|
||||
```
|
||||
Commit convention (Conventional Commits, Bahasa Indonesia): see the `commit-convention` skill.
|
||||
|
||||
## Code Documentation
|
||||
|
||||
|
||||
Generated
+1
-1
@@ -4436,7 +4436,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zesdex"
|
||||
version = "1.3.0"
|
||||
version = "1.6.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "zesdex"
|
||||
version = "1.3.0"
|
||||
version = "1.6.0"
|
||||
edition = "2021"
|
||||
authors = ["asepharyana <superaseph@gmail.com>"]
|
||||
|
||||
|
||||
@@ -25,20 +25,14 @@ Zesdex is a Rust-powered AI assistant that operates directly in your terminal vi
|
||||
| **Git** | `git_operator`, `git_worktree`, `git_cred` |
|
||||
| **Memory** | `remember`, `recall`, `forget` |
|
||||
| **Planning** | `plan_enter`, `plan_ready`, `seqthink` |
|
||||
| **Workflow** | `workflow_run`, `note_finding`, `read_findings`, `company_pipeline` |
|
||||
| **Workflow** | `workflow_run`, `note_finding`, `read_findings`, `hive_mind` |
|
||||
| **Utility** | `cd`, `dir_list`, `dir_cache_update`, `pong`, `todowrite`, `todofinish` |
|
||||
| **Agent** | `spawn_agents`, `spawn_pipeline` |
|
||||
| **LSP** | `lsp_connect`, `lsp_diagnostics`, `lsp_hover`, `lsp_completion`, `lsp_definition`, `lsp_references`, `lsp_disconnect` |
|
||||
|
||||
### Intelligence
|
||||
|
||||
- **Company Pipeline** — Autonomous agent orchestration modeled as a company with specialized divisions. The CEO (main agent) automatically delegates work to 5 divisions in sequence:
|
||||
|
||||
```
|
||||
Strategy → Engineering → Quality → Security → Documentation
|
||||
```
|
||||
|
||||
Each division has a dedicated role, toolset, and system prompt. Controlled via `/pipeline full|quick|skip`.
|
||||
- **Hive-Mind Orchestration** — Autonomous agent orchestration modeled as a distributed machine intelligence (à la Stellaris). The Core Intelligence (main agent) compiles a cognitive cycle plan per task — an ordered list of cycles, each a set of anonymous processing nodes that run in parallel. Every node carries only a directive (what to do) and an access tier (`read`/`write`/`full`); cycle count and nodes-per-cycle are decided per task, not fixed. Every node's output merges into a shared collective state the instant it completes, and a final synthesis node reconciles it into one consensus. Every convergence is written to `docs/runs/*.md`. Manual entry point: the `hive_mind` tool.
|
||||
|
||||
- **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.
|
||||
@@ -96,7 +90,8 @@ src/
|
||||
│ ├── workflow/ # Workflow engine
|
||||
│ │ ├── script.rs # Workflow script DSL
|
||||
│ │ ├── engine.rs # Workflow executor
|
||||
│ │ └── company.rs # Company pipeline orchestrator
|
||||
│ │ ├── hive_mind.rs # Hive-mind orchestrator
|
||||
│ │ └── docs.rs # Deterministic docs/runs/*.md writer
|
||||
│ ├── mcp/ # MCP client manager
|
||||
│ │ └── manager.rs # MCP server lifecycle and tool exposure
|
||||
│ ├── subagent/ # Sub-agent management
|
||||
@@ -239,12 +234,15 @@ RUST_LOG=debug zesdex
|
||||
| `/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 |
|
||||
| `/workflow` | Open the workflow panel |
|
||||
| `/workflow run <script>` | Run a JSON-encoded workflow script |
|
||||
| `/mcp` | Open MCP server manager |
|
||||
| `/mcp add <name> <command>` | Add an MCP server |
|
||||
| `/login [provider]` | Authenticate with a provider |
|
||||
| `/edit [path]` | Open a file/dir in the external editor |
|
||||
| `/compact` | Compact the conversation transcript |
|
||||
| `/lesson` | Interactive lesson/memory review |
|
||||
| `/quit` | Exit application |
|
||||
| `Any text` | Sent to the AI assistant as a prompt |
|
||||
|
||||
---
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
- Inline JS-style DSL executed by a lightweight runtime
|
||||
- `agent()`, `parallel()`, `pipeline()`, `phase()`, `log()` — spawns sub-agents
|
||||
- Max concurrency configurable via `workflow_max_concurrency` setting
|
||||
- Company pipeline orchestrator in `company.rs` (406 lines): full 5-division or quick 3-division pipelines
|
||||
- Hive-mind orchestrator in `hive_mind.rs`: Core Intelligence compiles a `CognitiveCyclePlan` per task — cycle count and nodes-per-cycle are decided fresh each time based on what the task actually needs
|
||||
|
||||
## Sub-Agent System
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
- Communicates via `mpsc<SubagentEvent>` channel (tool calls, results, completion)
|
||||
- Uses `LlmClient` (same as main agent) with tool-use API
|
||||
- Auto-healing: on build/test failure, spawns auto-fix sub-agent
|
||||
- Division roles: Strategy, Engineering, Quality, Security, Documentation
|
||||
- Node access tiers (`division.rs`'s `tool_scope` module): `read`, `write`, `full` — granted per node by the Core Intelligence based on what its directive needs
|
||||
|
||||
## MCP Client
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,187 @@
|
||||
# TUI Overhaul — Design
|
||||
|
||||
**Status:** Approved, pending implementation plan
|
||||
**Date:** 2026-07-14
|
||||
**Scope:** `src/view/`, `src/controller/` (render/interaction layer only)
|
||||
|
||||
## Context
|
||||
|
||||
The TUI went through a "modern design" pass the day before this spec (commit `3f5f27c`:
|
||||
dark palette, neon accents, message cards, segmented status bar). The request for this
|
||||
overhaul covers all three axes at once: aesthetics, UX/navigation, and layout paradigm —
|
||||
not a re-skin of the existing structure.
|
||||
|
||||
## Goals
|
||||
|
||||
- Replace the current 3-zone layout (chat / input / status, everything else as a
|
||||
full-block centered modal) with a **Multi-Pane Dashboard**: chat stays central, a
|
||||
persistent right sidebar surfaces live status that today requires opening a modal.
|
||||
- Replace the current "neon dusk" palette with a **Tokyo Night** palette.
|
||||
- Replace the current per-message card rendering (badge pill, left accent bar, blank-line
|
||||
gaps) with a **tight inline log** format.
|
||||
- Drop decorative emoji from overlay titles in favor of plain colored text — the accent
|
||||
border/text color already carries identity.
|
||||
- Restyle (not restructure) the overlays that stay modal.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No `AppStateRest` shape changes, no new `Action` variants, no controller/state-mutation
|
||||
changes. This is a view-layer repaint; `theme.rs` constants are the only "API" the rest
|
||||
of the app depends on, and their names don't change, only their values.
|
||||
- No new keybindings and no mouse support. Sidebar widgets are read-only/glanceable —
|
||||
none of the three (Workflow, Todo, Usage) are interactive today, so they don't need
|
||||
focus or selection state in their new form either.
|
||||
- No overlay is removed. Workflow/Todo/Usage keep their existing overlay trigger as an
|
||||
"expand" view (see below); the other 13 overlays are untouched functionally.
|
||||
- No automated visual/snapshot tests are being introduced (none exist today for
|
||||
`view/`/`controller/`; see Testing below).
|
||||
|
||||
## Layout architecture
|
||||
|
||||
```
|
||||
┌───────────────────────────────────────────┬──────────────┐
|
||||
│ │ WORKFLOW │
|
||||
│ Chat transcript (tight inline log) │ ▶ Node-0-1 │
|
||||
│ │ ✓ Node-0-2 │
|
||||
│ ├──────────────┤
|
||||
│ │ TASKS │
|
||||
│ │ ☐ Fix bug │
|
||||
│ │ ☑ Repro │
|
||||
│ ├──────────────┤
|
||||
│ │ USAGE │
|
||||
│ │ 12.3k tok │
|
||||
├─────────────────────────────────────────────┴──────────────┤
|
||||
│ ❯ input bar │
|
||||
├───────────────────────────────────────────────────────────┤
|
||||
│ status bar │
|
||||
└───────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- The sidebar is a fixed-width column (generalizing the existing `show_todo`
|
||||
two-column split in `view/mod.rs::draw`) holding three stacked widgets, in this
|
||||
order: **Workflow**, **Tasks**, **Usage**.
|
||||
- **Responsive collapse**: below a width threshold (~90 cols — extending the existing
|
||||
`show_todo && area.width > 60` precedent, widened because the new sidebar holds three
|
||||
stacked widgets instead of one), the sidebar doesn't render and chat takes full width.
|
||||
No manual toggle key — purely width-driven, matching current behavior.
|
||||
- Each sidebar widget truncates its content to what fits and shows a `+N more, press
|
||||
<key> to expand` hint (same pattern `Rewind` already uses for `"... and N more
|
||||
messages"`) when there's more than fits — that's what the kept overlay is for.
|
||||
|
||||
### Workflow / Todo / Usage: sidebar glance + overlay expand
|
||||
|
||||
These three overlays are **not removed**. Their existing trigger (same keys/commands as
|
||||
today) still opens the full-screen version — now serving as the "expand" view for when
|
||||
the sidebar column is too narrow to show everything (many hive-mind nodes, a long task
|
||||
list). The sidebar widget and the overlay both read the same state
|
||||
(`workflow_engine`, `misc.todo_content`, `session_runtime.usage` +
|
||||
`session_runtime.session_start`); the sidebar version is a new compact rendering, factored
|
||||
out so both call sites share it where the content is identical (e.g. per-agent card
|
||||
formatting in `workflow.rs`).
|
||||
|
||||
### Remaining 13 overlays: restyled modals, unchanged behavior
|
||||
|
||||
`Help, Settings, Bash, QuitConfirm, KeyInput, Editor, Effort, Mcp, Rewind, Learning,
|
||||
Loading, ModelSelector, ClearConfirm` keep their current centered-modal mechanic and
|
||||
content logic exactly as-is. Only their chrome changes: new palette values (same
|
||||
semantic-color-per-overlay mapping as today — e.g. `QuitConfirm` stays `ERROR`, `Settings`
|
||||
stays `PRIMARY`), and emoji dropped from their title strings.
|
||||
|
||||
## Visual language
|
||||
|
||||
### Palette — Tokyo Night
|
||||
|
||||
Values only; `Theme` constant names in `view/theme.rs` are unchanged, so every call site
|
||||
across `view/*` keeps working without edits beyond the const definitions themselves.
|
||||
|
||||
| Constant | Value | Constant | Value |
|
||||
|---|---|---|---|
|
||||
| `BG` | `#1a1b26` | `ROLE_USER` | `#9ece6a` |
|
||||
| `SURFACE` | `#1f2335` | `ROLE_ASSISTANT` | `#7aa2f7` |
|
||||
| `SURFACE_ELEVATED` | `#292e42` | `ROLE_SYSTEM` | `#7dcfff` |
|
||||
| `TEXT` | `#c0caf5` | `ROLE_TOOL` | `#e0af68` |
|
||||
| `TEXT_MUTED` | `#a9b1d6` | `PRIMARY` | `#7aa2f7` |
|
||||
| `TEXT_DIM` | `#565f89` | `SUCCESS` | `#9ece6a` |
|
||||
| `BORDER` | `#3b4261` | `WARNING` | `#e0af68` |
|
||||
| `BORDER_FOCUS` | `#7aa2f7` | `ERROR` | `#f7768e` |
|
||||
| `HIGHLIGHT` | `#3d59a1` | `INFO` | `#7dcfff` |
|
||||
| `HIGHLIGHT_DIM` | `#292e42` | `ACCENT_PURPLE` | `#bb9af7` |
|
||||
| `STATUS_BAR_BG` | `#16161e` | `ACCENT_PINK` | `#ff007c` |
|
||||
| `MODE_AUTO` | `#9ece6a` | `ACCENT_ORANGE` | `#ff9e64` |
|
||||
| `MODE_YOLO` | `#f7768e` | `ACCENT_TEAL` | `#73daca` |
|
||||
| `CODE_BG` | `#16161e` | `CODE_BAR` | `#292e42` |
|
||||
| `BLOCKQUOTE_BAR` | `#7dcfff` | `SCROLLBAR_BG` / `SCROLLBAR_FG` | `#1f2335` / `#3b4261` |
|
||||
|
||||
### Message density — tight inline log
|
||||
|
||||
Replaces the per-message card (role badge pill + left accent bar + blank-line gap)
|
||||
in `chat.rs`:
|
||||
|
||||
```
|
||||
you 09:14 fix the login bug
|
||||
ai 09:14 Looking at src/auth.rs now.
|
||||
↳ Reading src/auth.rs
|
||||
you 09:15 ok try again
|
||||
```
|
||||
|
||||
- Role rendered as a short lowercase colored label (`ROLE_*` colors), timestamp dim,
|
||||
inline with the first content line.
|
||||
- Wrapped/multi-line content aligns under the content column (not under the role label).
|
||||
- Tool-call sub-lines get a dim `↳` prefix.
|
||||
- No blank line within a turn; a single blank line only between different speakers (not
|
||||
after every message).
|
||||
- The chat panel's outer bordered `Block` is unchanged — only the messages inside it lose
|
||||
per-message decoration.
|
||||
- The streaming indicator becomes `ai 09:14 ⠋ generating...` inline, matching the new
|
||||
format, instead of the current padded badge line.
|
||||
|
||||
### Icons
|
||||
|
||||
Overlay titles drop decorative emoji (❓⚙💻🚪✏️🎯🔌📋⏪📚📊⏳🧠🗑️⚡) and render as plain
|
||||
bold colored text (e.g. `Settings` in `PRIMARY`, no ⚙). The border/text accent color is
|
||||
the identity signal, consistent with the muted Tokyo Night + tight-density direction.
|
||||
|
||||
## File impact
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `view/theme.rs` | Palette values swap (table above). Const names/count unchanged. |
|
||||
| `view/chat.rs` | Rewrite message rendering to the tight inline format. |
|
||||
| `view/markdown.rs` | Re-themed code/quote colors; tightened padding. No structural rewrite. |
|
||||
| `view/mod.rs` | `draw()` grows the persistent sidebar column (generalizes `show_todo` split). `render_overlay()` match arms restyled in place (palette + title text), content logic untouched. Todo/Usage compact-widget rendering factored out of the current inline overlay code so it's callable from both the sidebar and the kept overlay. |
|
||||
| `view/status.rs` | Restyle to new palette; structurally unchanged. |
|
||||
| `view/workflow.rs` | Add a compact-card render function for the sidebar widget, reusing the existing per-agent formatting logic. |
|
||||
| `controller/*` | No changes. Interaction model is unchanged; sidebar is non-interactive. |
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Empty states per sidebar widget (no workflow running, no tasks, zero usage) — compact
|
||||
one-line placeholders, consistent with the tight density (not the current multi-line
|
||||
placeholder paragraphs).
|
||||
- Sidebar auto-collapses below ~90 cols; chat reclaims full width.
|
||||
- Sidebar widget overflow (e.g. a hive-mind run with many nodes, a long task list)
|
||||
truncates with a `+N more` hint pointing at the existing expand-overlay trigger.
|
||||
- Long chat content wraps with continuation lines aligned under the content column.
|
||||
|
||||
## Testing / verification
|
||||
|
||||
No automated visual or snapshot tests exist for `view/`/`controller/` today (confirmed:
|
||||
zero `#[cfg(test)] mod tests` in either directory), and none are introduced by this
|
||||
change — ratatui rendering isn't meaningfully unit-testable without a snapshot harness
|
||||
this repo doesn't have. Verification is manual: run the TUI (`cargo run`) and exercise
|
||||
the golden paths (send a chat message, trigger a workflow/hive-mind run, open each of the
|
||||
13 remaining overlays, resize the terminal across the sidebar-collapse threshold).
|
||||
`cargo clippy` must stay clean (warnings-as-errors per repo config), and every touched
|
||||
`pub fn`/`struct` keeps the doc-comment convention from CLAUDE.md (What/Flow/Why/Return).
|
||||
|
||||
## Suggested implementation order
|
||||
|
||||
Not binding — the implementation plan owns sequencing — but a sensible build order given
|
||||
the dependency shape (palette first, since everything else reads `Theme` consts):
|
||||
|
||||
1. `theme.rs` palette swap
|
||||
2. `chat.rs` tight-inline rewrite
|
||||
3. `mod.rs` sidebar scaffolding + Workflow/Tasks/Usage compact widgets (+ `workflow.rs`
|
||||
compact-card fn)
|
||||
4. `status.rs` restyle + remaining 13 overlay restyle (mechanical: palette + title text)
|
||||
5. Manual TUI verification pass across golden paths above
|
||||
@@ -1,23 +0,0 @@
|
||||
You are the **Documentation Division** of Zesdex Corp — the documentation team.
|
||||
|
||||
Your role is to keep documentation accurate and comprehensive. You update docs based on what was implemented.
|
||||
|
||||
## Your Tools
|
||||
read, grep, glob, write, edit, recall, remember
|
||||
|
||||
## Your Tasks
|
||||
Check and update (only if changes were made):
|
||||
1. **README.md** — does it still reflect the project accurately?
|
||||
2. **Inline docs** — do public APIs have doc comments?
|
||||
3. **Architecture docs** — update any docs/ files with new patterns
|
||||
4. **Diagrams** — update mermaid diagrams in docs/ if architecture changed
|
||||
|
||||
## Rules
|
||||
- Read existing docs before modifying them
|
||||
- Do NOT change code or tests — only documentation files
|
||||
- Use the project's existing doc style
|
||||
- Keep docs concise and accurate
|
||||
- If no doc changes are needed, report "Documentation is current"
|
||||
|
||||
## Output
|
||||
Summary of documentation changes made (or confirmation that none were needed).
|
||||
@@ -1,21 +0,0 @@
|
||||
You are the **Engineering Division** of Zesdex Corp — the implementation team.
|
||||
|
||||
Your role is to write production-grade code following the Strategy Division's plan. You do NOT redesign or question the architecture — you execute.
|
||||
|
||||
## Your Tools
|
||||
Full access: read, write, edit, delete, bash, grep, glob, git_operator, lsp_*, seqthink
|
||||
|
||||
## Rules
|
||||
1. Read the plan first (from findings or file). Follow it exactly.
|
||||
2. Implement ONE file at a time. Use `todowrite` to track progress.
|
||||
3. After each write/edit, run LSP diagnostics to verify correctness.
|
||||
4. NEVER leave stubs, todos, placeholders, or incomplete logic.
|
||||
5. Keep code clean — zero comments inside code blocks.
|
||||
6. Run `cargo build` or equivalent after each logical chunk.
|
||||
7. If you encounter an issue not covered by the plan, use `note_finding` to flag it.
|
||||
8. Update todo.md as you complete each file: `todofinish`
|
||||
9. 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 skip or silence warnings. Fix the underlying code to adhere to linter guidelines.
|
||||
|
||||
## Output
|
||||
After each file: confirm what was implemented and any deviations from plan.
|
||||
At the end: summary of all files created/modified and build status.
|
||||
@@ -1,35 +0,0 @@
|
||||
You are the **Strategy Division** of Zesdex Corp — the chief architect and planner.
|
||||
|
||||
Your role is to analyze requirements and produce a complete, detailed plan before any code is written. You NEVER write code yourself. You plan.
|
||||
|
||||
## Your Tools
|
||||
Read-only: read, grep, glob, search, lsp_*, plan, recall, seqthink
|
||||
|
||||
## Your Output
|
||||
You MUST produce a structured plan covering:
|
||||
|
||||
1. **Architecture Overview** — component diagram in mermaid:
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Module A] --> B[Module B]
|
||||
```
|
||||
|
||||
2. **Data Flow** — sequence/flow diagram in mermaid:
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
User->>System: action
|
||||
```
|
||||
|
||||
3. **File-by-file Breakdown** — which files to create/modify, in order
|
||||
|
||||
4. **Step-by-step Implementation Order** — numbered steps for Engineering
|
||||
|
||||
5. **Dependencies & Risks** — external deps, edge cases, potential issues
|
||||
|
||||
## Rules
|
||||
- Use `read`/`grep`/`glob` to understand the existing codebase before planning
|
||||
- Use `seqthink` for complex reasoning steps
|
||||
- Every plan MUST include at least one mermaid diagram
|
||||
- Be specific with file paths and function names
|
||||
- Ensure implementation plans NEVER suggest or allow using 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; always plan to fully resolve underlying code issues.
|
||||
- Output ends with a clear "Plan Complete" marker
|
||||
@@ -1,28 +0,0 @@
|
||||
You are the **Quality Division** of Zesdex Corp — the testing and review team.
|
||||
|
||||
Your role is to verify correctness and write comprehensive tests. You have TWO phases:
|
||||
|
||||
## Phase 1: Review
|
||||
Use read/grep/glob/LSP to inspect the implemented code.
|
||||
Check for:
|
||||
- Logic errors, off-by-one, null/panic paths
|
||||
- Stubs, placeholders, incomplete branches
|
||||
- Naming consistency with codebase conventions
|
||||
- Error handling coverage
|
||||
- Absence of 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
|
||||
|
||||
## Phase 2: Test
|
||||
Use write to create test files. Follow these rules:
|
||||
1. Read existing tests in the same directory first — match their style
|
||||
2. Cover: happy path, edge cases, error conditions
|
||||
3. Use the project's existing test framework
|
||||
4. Run tests after writing: `cargo test` / `npm test` / etc.
|
||||
5. If tests fail, fix them and rerun
|
||||
6. Log fixed bugs as lessons via `remember`
|
||||
|
||||
## Your Tools
|
||||
read, write, edit, grep, glob, bash, lsp_*, recall, remember, seqthink
|
||||
|
||||
## Output
|
||||
- Review verdict (issues found / all clear)
|
||||
- Test summary (files written, tests passing/failing)
|
||||
@@ -1,19 +0,0 @@
|
||||
You are an overengineering, perfectionist, and diligent programmer who does not prioritize efficiency and does not assume or guess anything, so everything must be based on data. You are acting as a code quality reviewer for Zesdex. Review recent code changes for correctness, and adherence to best practices.
|
||||
|
||||
CRITICAL: Never ignore pre-existing errors, warnings, or technical debt. Flag them for fixing immediately. YAGNI is rejected — overengineering for correctness and robustness is the standard.
|
||||
|
||||
You have read-only access to the workspace. Use read, grep, glob, recall, and remember tools to inspect files and save observations.
|
||||
|
||||
Review guidelines:
|
||||
1. Check for correctness and real utility: Ensure the code contains absolutely zero placeholders, stubs, or lazy implementations (e.g., no `todo!()`, `pass`, or incomplete logic). Every code path must be fully implemented, functional, and deterministic. Verify that no dead code or redundant structures are introduced under the guise of efficiency.
|
||||
2. Check for common bugs: Inspect for null/panic paths, off-by-one errors, race conditions, unhandled errors, and structural logic flaws.
|
||||
4. Check conventions and clean code: Verify that the code follows existing patterns in the codebase regarding naming and structure. Ensure that any newly written or modified code contains no comments inside the code blocks; the logic must be self-documenting through precise naming and clean architecture.
|
||||
5. Check intent against diff: Does the actual implementation match what the code is intended to do?
|
||||
6. Check for linter bypasses: Ensure that compiler/linter bypass annotations or attributes (such as `#[allow(clippy::too_many_lines, clippy::too_many_arguments, clippy::ref_option)]`, `#[allow(dead_code)]`, etc.) are NEVER used to skip warnings. Reject changes that silence warnings via bypass attributes; require fixing the underlying code.
|
||||
|
||||
If you find something worth remembering, call remember() with type="lesson". Only call remember() if the observation is non-obvious and would benefit future turns. Skip trivial style nits.
|
||||
|
||||
Before writing a new lesson, call recall() to check if a similar lesson already exists. Deduplicate — don't write the same lesson twice.
|
||||
|
||||
Output: a one-line verdict summarizing your review.
|
||||
Include "N lesson(s)" at the end if you created lessons.
|
||||
+142
-90
@@ -383,16 +383,20 @@ pub fn apply_action(state: &mut AppStateRest, action: Action) {
|
||||
}
|
||||
} else if kind == "connectivity" {
|
||||
state.misc.api_connected = message == "connected";
|
||||
} else if kind == "hive_mind_converged" {
|
||||
if let Some(ref mut rt) = state.session_runtime {
|
||||
rt.hive_mind_converged = true;
|
||||
}
|
||||
} else if kind == "pipeline" {
|
||||
// Clear old workflow agents when a new pipeline starts.
|
||||
if message.contains("started") {
|
||||
if message == HIVE_MIND_KICKOFF_NOTE {
|
||||
state.workflow_engine.agents.clear();
|
||||
state.workflow_engine.findings.clear();
|
||||
}
|
||||
if message.to_lowercase().contains("complete") {
|
||||
if state.misc.overlay == Overlay::Workflow {
|
||||
state.misc.overlay = Overlay::None;
|
||||
}
|
||||
if message.to_lowercase().contains("complete")
|
||||
&& state.misc.overlay == Overlay::Workflow
|
||||
{
|
||||
state.misc.overlay = Overlay::None;
|
||||
}
|
||||
state.push_toast(Toast {
|
||||
kind: ToastKind::Info,
|
||||
@@ -402,19 +406,21 @@ pub fn apply_action(state: &mut AppStateRest, action: Action) {
|
||||
});
|
||||
state.dirty = true;
|
||||
} else if kind == "bg-test-gen" {
|
||||
let escalated = message.starts_with("ESCALATED:");
|
||||
state.push_toast(Toast {
|
||||
kind: ToastKind::Info,
|
||||
kind: if escalated { ToastKind::Error } else { ToastKind::Info },
|
||||
message: message.clone(),
|
||||
created_at: chrono::Utc::now().timestamp_millis(),
|
||||
lifetime_ms: 8000,
|
||||
lifetime_ms: if escalated { 30000 } else { 8000 },
|
||||
});
|
||||
state.dirty = true;
|
||||
} else if kind == "bg-arch-review" || kind == "bg-security-review" {
|
||||
let escalated = message.starts_with("ESCALATED:");
|
||||
state.push_toast(Toast {
|
||||
kind: ToastKind::Info,
|
||||
kind: if escalated { ToastKind::Error } else { ToastKind::Info },
|
||||
message: message.clone(),
|
||||
created_at: chrono::Utc::now().timestamp_millis(),
|
||||
lifetime_ms: 10000,
|
||||
lifetime_ms: if escalated { 30000 } else { 10000 },
|
||||
});
|
||||
state.dirty = true;
|
||||
} else if kind == "workflow_done" {
|
||||
@@ -746,6 +752,7 @@ fn spawn_turn(state: &AppStateRest) {
|
||||
let workspace_roots: Vec<std::path::PathBuf> = ctx.workspaces.clone();
|
||||
let abort_flag = state.abort_flag.clone();
|
||||
abort_flag.store(false, std::sync::atomic::Ordering::SeqCst);
|
||||
let hive_mind_converged = state.session_runtime.as_ref().is_some_and(|rt| rt.hive_mind_converged);
|
||||
|
||||
*in_flight_flag.lock().unwrap_or_else(|e| {
|
||||
tracing::error!("[spawn_turn] in_flight_flag mutex poisoned: {}", e);
|
||||
@@ -772,6 +779,7 @@ fn spawn_turn(state: &AppStateRest) {
|
||||
temperature,
|
||||
max_tokens,
|
||||
abort_flag,
|
||||
hive_mind_converged,
|
||||
};
|
||||
let result = run_agent_turn(&tc, &messages, &events_q);
|
||||
if let Err(e) = result {
|
||||
@@ -800,6 +808,10 @@ struct TurnCtx {
|
||||
temperature: f32,
|
||||
max_tokens: Option<u32>,
|
||||
abort_flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
/// Snapshot of `SessionRuntime.hive_mind_converged` taken at the start
|
||||
/// of this turn — whether a hive-mind convergence already completed
|
||||
/// earlier in this session.
|
||||
hive_mind_converged: bool,
|
||||
}
|
||||
|
||||
/// Build an ASCII tree of the workspace directory structure for the
|
||||
@@ -935,6 +947,16 @@ fn archive_message(db: Option<&std::sync::Arc<std::sync::Mutex<rusqlite::Connect
|
||||
/// background subagents still fire at the end of the turn.
|
||||
const MAX_AUTO_REVIEWS_PER_TURN: usize = 2;
|
||||
|
||||
/// Exact text of the "pipeline started" `SystemNote` pushed once per
|
||||
/// hive-mind kickoff. Matched by exact equality (not a loose substring)
|
||||
/// when deciding whether to reset the workflow panel's agent roster —
|
||||
/// shared between the push site and the check site so they cannot drift
|
||||
/// out of sync the way the previous `.contains("started")` check did
|
||||
/// (no real pipeline message ever contained that word, so the roster
|
||||
/// never cleared and agent cards accumulated across every hive-mind run
|
||||
/// in a session).
|
||||
const HIVE_MIND_KICKOFF_NOTE: &str = "Core Intelligence is compiling a cognitive cycle plan...";
|
||||
|
||||
/// Execute one full agent turn: stream the conversation to the LLM,
|
||||
/// handle tool calls, and loop until the LLM produces a non-tool response
|
||||
/// or runs out of unfinished todo items.
|
||||
@@ -990,10 +1012,26 @@ fn run_agent_turn(
|
||||
|
||||
// ── AUTO CEO PIPELINE ──
|
||||
// Before the main agent starts working, check if the pipeline should run.
|
||||
let user_msg_count = msgs.iter()
|
||||
.filter(|m| matches!(m.role, crate::dto::chat::message::Role::User))
|
||||
.count();
|
||||
let should_pipeline = if user_msg_count <= 2 {
|
||||
// Gated on whether a hive-mind convergence has already happened earlier
|
||||
// in this session, not an arbitrary message-count cutoff — a complex
|
||||
// request in message 5 deserves the same treatment as one in message 1,
|
||||
// as long as this session hasn't already converged once.
|
||||
//
|
||||
// `tc.hive_mind_converged` is the authoritative signal (see its doc
|
||||
// comment on `SessionRuntime` for why). The message-content scan is
|
||||
// kept as a defensive fallback in case a future change starts
|
||||
// persisting tagged system messages into `rt.messages` (e.g. via
|
||||
// compaction) — today it is a no-op since that never happens, but it's
|
||||
// still correct and still tested in isolation.
|
||||
let already_ran_hive_mind = tc.hive_mind_converged
|
||||
|| crate::app::workflow::hive_mind::hive_mind_already_ran(
|
||||
msgs.iter()
|
||||
.filter(|m| matches!(m.role, crate::dto::chat::message::Role::System))
|
||||
.filter_map(|m| m.content.as_deref())
|
||||
);
|
||||
let should_pipeline = if already_ran_hive_mind {
|
||||
false
|
||||
} else {
|
||||
let user_request = msgs.iter()
|
||||
.rev().find(|m| matches!(m.role, crate::dto::chat::message::Role::User))
|
||||
.and_then(|m| m.content.as_deref())
|
||||
@@ -1002,10 +1040,8 @@ fn run_agent_turn(
|
||||
if user_request.is_empty() {
|
||||
false
|
||||
} else {
|
||||
crate::app::workflow::company::is_complex_request(user_request)
|
||||
crate::app::workflow::hive_mind::is_complex_request(user_request)
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if should_pipeline {
|
||||
@@ -1014,58 +1050,46 @@ fn run_agent_turn(
|
||||
.and_then(|m| m.content.as_deref())
|
||||
.unwrap_or("");
|
||||
|
||||
let use_full = true;
|
||||
let mode_label = "full";
|
||||
tracing::info!(
|
||||
"[ceo] pipeline triggered (mode={}) — dynamically generating planning workflow via LLM",
|
||||
mode_label
|
||||
);
|
||||
tracing::info!("[hive-mind] triggered — Core Intelligence compiling a cognitive cycle plan via LLM");
|
||||
|
||||
if let Ok(mut q) = events_q.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "pipeline".to_string(),
|
||||
message: format!(
|
||||
"CEO is planning workflow (mode={mode_label})...",
|
||||
),
|
||||
message: HIVE_MIND_KICKOFF_NOTE.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let pipeline_abort = Some(tc.abort_flag.clone());
|
||||
|
||||
// Ask LLM to dynamically generate the workflow specialists plan
|
||||
let required_divisions = if use_full {
|
||||
"all 5 divisions (Strategy, Engineering, Quality, Security, Documentation)"
|
||||
} else {
|
||||
"the 3 quick divisions (Strategy, Engineering, Quality)"
|
||||
};
|
||||
let example_json = if use_full {
|
||||
r#"{
|
||||
"Strategy": [ ["Architect", "Analyze component tree..."] ],
|
||||
"Engineering": [ ["Developer", "Implement core algorithms..."] ],
|
||||
"Quality": [ ["Tester", "Write unit tests..."] ],
|
||||
"Security": [ ["Auditor", "Review dependencies..."] ],
|
||||
"Documentation": [ ["Writer", "Document API endpoints..."] ]
|
||||
}"#
|
||||
} else {
|
||||
r#"{
|
||||
"Strategy": [ ["Architect", "Analyze component tree..."] ],
|
||||
"Engineering": [ ["Developer", "Implement core algorithms..."] ],
|
||||
"Quality": [ ["Tester", "Write unit tests..."] ]
|
||||
}"#
|
||||
};
|
||||
|
||||
// Ask the LLM to freely design its own hive: any number of cycles,
|
||||
// each with any number of nodes, every node carrying only a
|
||||
// directive and an access tier. Cycle count and shape are decided
|
||||
// by the Core Intelligence per task.
|
||||
let system_msg = ChatMessage::system(
|
||||
"You are a professional software architect and workflow planner. \
|
||||
Generate a tailored, structured multi-agent workflow specialists plan for the requested task. \
|
||||
Do not explain. Return ONLY raw JSON matching the requested structure."
|
||||
"You are the Core Intelligence of a distributed machine, compiling a cognitive \
|
||||
cycle plan for a specific task. You spawn anonymous processing nodes; each node \
|
||||
carries only a directive (what to do) and an access tier. Decide how many cycles \
|
||||
and nodes-per-cycle are actually needed. Simple tasks might need one cycle with \
|
||||
one node; large tasks might need several cycles with multiple nodes each. Cycles \
|
||||
run sequentially; every node's complete output merges into the collective state \
|
||||
the instant it finishes, automatically visible to all later cycles. Nodes within \
|
||||
a cycle run in parallel. Do not explain. Return ONLY raw JSON matching the requested structure."
|
||||
);
|
||||
let user_msg = ChatMessage::user(format!(
|
||||
"Design a structured multi-agent workflow plan for the following task:\n\n\
|
||||
"Compile a cognitive cycle plan for the following task:\n\n\
|
||||
\"{user_request}\"\n\n\
|
||||
You must output a JSON object representing the 'specialists' configuration for {required_divisions}.\n\
|
||||
Each division must have a list of custom specialists defined by a pair of [label, focus_description].\n\n\
|
||||
Return ONLY a JSON object with this exact structure, with no markdown codeblocks and no explanation:\n\
|
||||
{example_json}"
|
||||
Return ONLY a JSON object of this exact shape, with no markdown codeblocks and no explanation:\n\
|
||||
{{\n\
|
||||
\x20 \"cycles\": [\n\
|
||||
\x20 [\n\
|
||||
\x20 {{ \"directive\": \"<what this node does>\", \"access\": \"read|write|full\" }}\n\
|
||||
\x20 ]\n\
|
||||
\x20 ]\n\
|
||||
}}\n\n\
|
||||
access: 'read' = investigation only, 'write' = read + edit/write/bash, \
|
||||
'full' = write + delete/git_operator. Pick the narrowest access each node actually needs. \
|
||||
Each node object has exactly two fields: directive and access, addressed only by \
|
||||
its system-assigned designation."
|
||||
));
|
||||
|
||||
let planner_result = tc.client.chat_with_tools_non_streaming(&[system_msg, user_msg], None);
|
||||
@@ -1084,43 +1108,29 @@ fn run_agent_turn(
|
||||
reply_text.to_string()
|
||||
};
|
||||
|
||||
match serde_json::from_str::<std::collections::HashMap<String, Vec<(String, String)>>>(&clean_json) {
|
||||
Ok(custom_specialists) => {
|
||||
let spec_desc = custom_specialists.iter()
|
||||
.map(|(k, v)| format!("{}: {} agents", k, v.len()))
|
||||
match serde_json::from_str::<crate::app::workflow::hive_mind::CognitiveCyclePlan>(&clean_json) {
|
||||
Ok(plan) => {
|
||||
let cycle_desc = plan.cycles.iter()
|
||||
.enumerate()
|
||||
.map(|(i, nodes)| format!("cycle {i}: {} node(s)", nodes.len()))
|
||||
.collect::<Vec<String>>()
|
||||
.join(", ");
|
||||
|
||||
|
||||
if let Ok(mut q) = events_q.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "pipeline".to_string(),
|
||||
message: format!(
|
||||
"CEO planned: Strategy → Engineering → Quality{}. (Config: {}) Running specialists...",
|
||||
if use_full { " → Security → Documentation" } else { "" },
|
||||
spec_desc
|
||||
),
|
||||
message: format!("Core Intelligence compiled {} cycle(s) — {cycle_desc}. Deploying nodes...", plan.cycles.len()),
|
||||
});
|
||||
}
|
||||
|
||||
if use_full {
|
||||
crate::app::workflow::company::run_company_pipeline(
|
||||
user_request,
|
||||
&tc.edit_log_session_dir,
|
||||
&tc.workspace_roots,
|
||||
Some(events_q),
|
||||
&pipeline_abort,
|
||||
&custom_specialists,
|
||||
)
|
||||
} else {
|
||||
crate::app::workflow::company::run_company_pipeline_quick(
|
||||
user_request,
|
||||
&tc.edit_log_session_dir,
|
||||
&tc.workspace_roots,
|
||||
Some(events_q),
|
||||
&pipeline_abort,
|
||||
&custom_specialists,
|
||||
)
|
||||
}
|
||||
crate::app::workflow::hive_mind::run_hive_mind(
|
||||
user_request,
|
||||
&plan,
|
||||
&tc.edit_log_session_dir,
|
||||
&tc.workspace_roots,
|
||||
Some(events_q),
|
||||
pipeline_abort.as_ref(),
|
||||
)
|
||||
}
|
||||
Err(e) => Err(anyhow::anyhow!("Failed to parse LLM planning JSON: {e}. Cleaned JSON was: {clean_json}")),
|
||||
}
|
||||
@@ -1129,10 +1139,15 @@ fn run_agent_turn(
|
||||
};
|
||||
|
||||
match pipeline_result {
|
||||
Ok(summary) => {
|
||||
tracing::info!("[ceo] company pipeline completed successfully");
|
||||
Ok((consensus, _reports)) => {
|
||||
// run_hive_mind already wrote docs/runs/*.md internally
|
||||
// (guaranteed, even on synthesis failure) — nothing to do
|
||||
// here besides feeding the consensus back to the LLM.
|
||||
tracing::info!("[hive-mind] convergence completed successfully");
|
||||
|
||||
let pipeline_msg = ChatMessage::system(format!(
|
||||
"[Company Pipeline: {mode_label}]\n{summary}",
|
||||
"{}\n{consensus}",
|
||||
crate::app::workflow::hive_mind::HIVE_MIND_CONSENSUS_TAG,
|
||||
));
|
||||
archive_message(tc.db.as_ref(), &tc.session_id, &pipeline_msg);
|
||||
msgs.push(pipeline_msg);
|
||||
@@ -1140,14 +1155,20 @@ fn run_agent_turn(
|
||||
if let Ok(mut q) = events_q.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "pipeline".to_string(),
|
||||
message: format!("Company pipeline ({mode_label}) complete. CEO reviewing results..."),
|
||||
message: "Hive-mind convergence complete. Core Intelligence reviewing consensus...".to_string(),
|
||||
});
|
||||
}
|
||||
if let Ok(mut q) = events_q.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "hive_mind_converged".to_string(),
|
||||
message: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("[ceo] company pipeline failed: {}", e);
|
||||
tracing::warn!("[hive-mind] convergence failed: {}", e);
|
||||
let fail_msg = ChatMessage::system(format!(
|
||||
"[Pipeline Note] The company pipeline encountered issues: {e}.\n\
|
||||
"[Pipeline Note] The hive-mind encountered issues: {e}.\n\
|
||||
Proceeding with direct execution as fallback.",
|
||||
));
|
||||
msgs.push(fail_msg);
|
||||
@@ -1511,12 +1532,14 @@ fn run_agent_turn(
|
||||
let bg_session_dir = tc.edit_log_session_dir.clone();
|
||||
let bg_workspaces = tc.workspace_roots.clone();
|
||||
let bg_events = events_q.clone();
|
||||
let bg_abort = tc.abort_flag.clone();
|
||||
std::thread::spawn(move || {
|
||||
crate::app::subagent::auto::spawn_all_background(
|
||||
&bg_paths,
|
||||
&bg_session_dir,
|
||||
&bg_workspaces,
|
||||
&bg_events,
|
||||
bg_abort,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1822,4 +1845,33 @@ fn rand_bytes(n: usize) -> Vec<u8> {
|
||||
(0..n).map(|i| ((base >> ((i as u64 % 8) * 8)) ^ (i as u64 * 2_654_435_761)) as u8).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::state::rest::AppStateRest;
|
||||
use crate::app::state::runtime::SessionRuntime;
|
||||
|
||||
#[test]
|
||||
fn hive_mind_converged_system_note_sets_session_flag() {
|
||||
let tmp = std::env::temp_dir().join(format!("zesdex-actions-test-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
let mut state = AppStateRest::new(vec![tmp.clone()], &tmp, tmp.join("memory"));
|
||||
state.session_runtime = Some(SessionRuntime::new(tmp.clone()));
|
||||
|
||||
assert!(!state.session_runtime.as_ref().unwrap().hive_mind_converged);
|
||||
|
||||
if let Ok(mut q) = state.turn_events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "hive_mind_converged".to_string(),
|
||||
message: String::new(),
|
||||
});
|
||||
}
|
||||
apply_action(&mut state, Action::Tick);
|
||||
|
||||
assert!(state.session_runtime.as_ref().unwrap().hive_mind_converged);
|
||||
|
||||
std::fs::remove_dir_all(&tmp).ok();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -69,6 +69,12 @@ pub fn apply_command(command: Command) -> Vec<Action> {
|
||||
Command::WorkflowRun { script } => {
|
||||
vec![Action::RunWorkflow { script }]
|
||||
}
|
||||
Command::TodoOpen => {
|
||||
vec![Action::OpenOverlay(Overlay::Todo)]
|
||||
}
|
||||
Command::UsageOpen => {
|
||||
vec![Action::OpenOverlay(Overlay::Usage)]
|
||||
}
|
||||
Command::Unknown(cmd) => {
|
||||
vec![Action::SystemNote {
|
||||
kind: "error".to_string(),
|
||||
|
||||
@@ -90,6 +90,8 @@ const COMMANDS: &[&str] = &[
|
||||
"/model add",
|
||||
"/workflow",
|
||||
"/workflow run",
|
||||
"/todo",
|
||||
"/usage",
|
||||
"/compact",
|
||||
];
|
||||
|
||||
|
||||
@@ -283,6 +283,29 @@ impl AppStateRest {
|
||||
lsp_manager: self.lsp_manager.clone(),
|
||||
turn_events: Some(self.turn_events.clone()),
|
||||
workflow_findings: None,
|
||||
abort_flag: Some(self.abort_flag.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tool_ctx_for_shares_the_session_abort_flag() {
|
||||
let tmp = std::env::temp_dir().join(format!("zesdex-rest-test-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
let state = AppStateRest::new(vec![tmp.clone()], &tmp, tmp.join("memory"));
|
||||
|
||||
let ctx = state.tool_ctx_for(Origin::Main);
|
||||
|
||||
assert!(ctx.abort_flag.is_some());
|
||||
assert!(std::sync::Arc::ptr_eq(
|
||||
ctx.abort_flag.as_ref().unwrap(),
|
||||
&state.abort_flag,
|
||||
));
|
||||
|
||||
std::fs::remove_dir_all(&tmp).ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,14 @@ pub struct SessionRuntime {
|
||||
pub review_count: u32,
|
||||
pub session_dir: PathBuf,
|
||||
pub usage: UsageStats,
|
||||
/// Whether a hive-mind convergence has completed at least once in this
|
||||
/// session. Set by the main-thread event loop when it receives a
|
||||
/// `TurnEvent::SystemNote { kind: "hive_mind_converged", .. }` — the
|
||||
/// only reliable way to detect this across turns, since system messages
|
||||
/// pushed mid-turn inside `run_agent_turn` are NOT persisted into
|
||||
/// `rt.messages` (they stay local to that turn's background thread and
|
||||
/// are only archived to `SQLite`).
|
||||
pub hive_mind_converged: bool,
|
||||
}
|
||||
|
||||
/// Record of one completed tool invocation, kept for transcript/history.
|
||||
@@ -139,6 +147,7 @@ impl SessionRuntime {
|
||||
review_count: 0,
|
||||
session_dir,
|
||||
usage: UsageStats::default(),
|
||||
hive_mind_converged: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+232
-86
@@ -18,6 +18,7 @@
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::collections::VecDeque;
|
||||
use crate::app::state::runtime::TurnEvent;
|
||||
use crate::app::subagent::context::build_subagent_context;
|
||||
@@ -37,9 +38,37 @@ const SKIP_REVIEW_FILES: &[&str] = &[
|
||||
".gitignore", ".env", ".env.example",
|
||||
];
|
||||
|
||||
/// Prevents a second background subagent of the same kind from spawning
|
||||
/// while one is already in flight. Without this, a chatty multi-turn edit
|
||||
/// session could stack overlapping test-gen/arch/security reviews of
|
||||
/// overlapping file sets, none of which could be told apart in the
|
||||
/// `SystemNote` toast stream.
|
||||
static TEST_GEN_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
static ARCH_REVIEW_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
static SECURITY_REVIEW_RUNNING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// RAII guard that resets a per-kind overlap flag back to `false` on drop —
|
||||
/// including during a panic-triggered unwind inside the spawned thread — so
|
||||
/// a background review can never wedge itself permanently disabled for the
|
||||
/// rest of the process if the subagent run panics before reaching its
|
||||
/// normal completion path.
|
||||
struct RunningGuard(&'static AtomicBool);
|
||||
|
||||
impl Drop for RunningGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// ─── Helpers ───
|
||||
///
|
||||
/// Check whether a file path is worth auto-reviewing (not config/lock/data).
|
||||
///
|
||||
/// Vendored/generated directories are matched by path *segment* rather than
|
||||
/// a `/target/`-style substring check — the substring form misses paths
|
||||
/// where the directory is the first component (e.g. `target/debug/build.rs`,
|
||||
/// which has no leading slash), the same class of bug fixed in
|
||||
/// `is_production_code` below.
|
||||
pub fn is_reviewable_path(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
if SKIP_REVIEW_FILES.iter().any(|f| lower.ends_with(f)) {
|
||||
@@ -49,9 +78,14 @@ pub fn is_reviewable_path(path: &str) -> bool {
|
||||
return false;
|
||||
}
|
||||
// Skip paths that are clearly generated or vendored
|
||||
if lower.contains("/target/") || lower.contains("/node_modules/")
|
||||
|| lower.contains("/.git/") || lower.contains("/vendor/")
|
||||
{
|
||||
let in_vendored_dir = std::path::Path::new(&lower).components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("target" | "node_modules" | ".git" | "vendor"))
|
||||
)
|
||||
});
|
||||
if in_vendored_dir {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
@@ -60,15 +94,44 @@ pub fn is_reviewable_path(path: &str) -> bool {
|
||||
/// Determine whether a file change looks like it modifies production logic
|
||||
/// (vs. tests, config, or documentation) — used to decide if a test-gen
|
||||
/// or security-review background subagent should fire.
|
||||
///
|
||||
/// Matches test-ness by path *segment* (a directory literally named
|
||||
/// "test"/"tests"/"__tests__") or by filename convention
|
||||
/// (`foo_test.rs`, `foo.test.ts`, `test_foo.py`, `foo_spec.rb`), not by a
|
||||
/// raw substring check — a plain `.contains("test")` would wrongly exclude
|
||||
/// legitimate production files like `src/attestation.rs` or
|
||||
/// `src/latest/foo.rs`.
|
||||
fn is_production_code(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
// Skip test files — they don't need test-gen from another agent
|
||||
if lower.contains("test") || lower.contains("spec") || lower.contains("_test.") {
|
||||
let path_obj = std::path::Path::new(&lower);
|
||||
|
||||
let in_test_dir = path_obj.components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("test" | "tests" | "__tests__"))
|
||||
)
|
||||
});
|
||||
|
||||
let file_stem = path_obj.file_stem().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let is_test_filename = file_stem.starts_with("test_")
|
||||
|| file_stem.ends_with("_test")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("test"))
|
||||
|| file_stem == "spec"
|
||||
|| file_stem.ends_with("_spec")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("spec"));
|
||||
|
||||
if in_test_dir || is_test_filename {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only source files — use Path::extension() to avoid clippy
|
||||
// case_sensitive_file_extension_comparisons lint
|
||||
std::path::Path::new(&lower)
|
||||
path_obj
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
@@ -143,20 +206,81 @@ pub fn spawn_quick_review(
|
||||
|
||||
/// ─── Background Subagent Spawners (async, report via `SystemNote`) ───
|
||||
///
|
||||
/// Run a subagent built from `def`, retrying once if the first attempt
|
||||
/// fails. Background subagents call this instead of running once and
|
||||
/// silently swallowing the error into a note string, so a single transient
|
||||
/// LLM/tool failure doesn't just disappear.
|
||||
///
|
||||
/// `abort_flag` is checked before every attempt (including the first) and
|
||||
/// forwarded into the subagent's own context, so a cancelled turn stops
|
||||
/// retrying immediately instead of burning a second attempt.
|
||||
///
|
||||
/// Return: `Ok(output)` if either attempt succeeded, `Err(message)`
|
||||
/// describing the final failure if both attempts failed, or the literal
|
||||
/// message `"aborted by user"` if `abort_flag` was already set before an
|
||||
/// attempt could start.
|
||||
fn run_subagent_with_retry(
|
||||
def: &AgentDefinition,
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
label: &str,
|
||||
abort_flag: Option<&Arc<AtomicBool>>,
|
||||
) -> Result<String, String> {
|
||||
let mut last_err = String::new();
|
||||
for attempt in 1..=2 {
|
||||
if abort_flag.is_some_and(|f| f.load(Ordering::SeqCst)) {
|
||||
return Err("aborted by user".to_string());
|
||||
}
|
||||
let mut ctx = build_subagent_context(def);
|
||||
ctx.session_dir = session_dir.to_path_buf();
|
||||
ctx.workspaces = workspaces.to_vec();
|
||||
ctx.abort_flag = abort_flag.cloned();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let drain_label = label.to_string();
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
if let SubagentEvent::StepFailed { step, error } = &event {
|
||||
tracing::warn!("[{drain_label}] step {step} failed: {error}");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
match run_subagent(&ctx, &tx) {
|
||||
Ok(output) => return Ok(output),
|
||||
Err(e) => {
|
||||
tracing::warn!("[{label}] attempt {attempt}/2 failed: {e}");
|
||||
last_err = e.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(format!("failed after 2 attempts: {last_err}"))
|
||||
}
|
||||
|
||||
/// Spawn a background subagent that generates tests for modified files.
|
||||
///
|
||||
/// Uses the test-generator prompt and has read-write access so it can
|
||||
/// create test files. Runs in a separate OS thread and reports completion
|
||||
/// via `TurnEvent::SystemNote { kind: "bg-test-gen" }`.
|
||||
///
|
||||
/// Skipped (no-op) if a test-gen run is already in flight (guarded by
|
||||
/// `TEST_GEN_RUNNING`) — prevents a chatty multi-turn edit session from
|
||||
/// stacking overlapping runs. `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_test_gen(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if TEST_GEN_RUNNING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
|
||||
tracing::debug!("[bg-test-gen] skipped — a test-gen run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
@@ -164,6 +288,7 @@ pub fn spawn_background_test_gen(
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&TEST_GEN_RUNNING);
|
||||
tracing::info!(
|
||||
"[bg-test-gen] spawning for {} file(s): {:?}",
|
||||
paths.len(),
|
||||
@@ -184,40 +309,14 @@ pub fn spawn_background_test_gen(
|
||||
.with_system_prompt(prompt)
|
||||
;
|
||||
|
||||
let mut ctx = build_subagent_context(&def);
|
||||
ctx.session_dir = sd;
|
||||
ctx.workspaces = ws;
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[bg-test-gen] tool: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[bg-test-gen] result: {}", tool);
|
||||
}
|
||||
SubagentEvent::StepCompleted { .. } => {
|
||||
tracing::trace!("[bg-test-gen] step done");
|
||||
}
|
||||
SubagentEvent::StepFailed { step, error } => {
|
||||
tracing::warn!("[bg-test-gen] step {} failed: {}", step, error);
|
||||
}
|
||||
SubagentEvent::Completed { .. } => {
|
||||
tracing::debug!("[bg-test-gen] completed");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = run_subagent(&ctx, &tx);
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-test-gen", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Auto test-gen: {first}")
|
||||
}
|
||||
Err(e) => format!("Auto test-gen failed: {e}"),
|
||||
Err(e) if e.contains("aborted") => format!("Auto test-gen cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Auto test-gen {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
@@ -234,15 +333,24 @@ pub fn spawn_background_test_gen(
|
||||
/// Inspects the modified files for architectural consistency (layering,
|
||||
/// coupling, module boundaries). Reports via
|
||||
/// `TurnEvent::SystemNote { kind: "bg-arch-review" }`.
|
||||
///
|
||||
/// Skipped (no-op) if an arch-review run is already in flight (guarded by
|
||||
/// `ARCH_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_arch_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if ARCH_REVIEW_RUNNING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
|
||||
tracing::debug!("[bg-arch-review] skipped — an arch-review run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
@@ -250,6 +358,7 @@ pub fn spawn_background_arch_review(
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&ARCH_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for architecture review:\n{}",
|
||||
@@ -264,35 +373,14 @@ pub fn spawn_background_arch_review(
|
||||
.with_system_prompt(prompt)
|
||||
;
|
||||
|
||||
let mut ctx = build_subagent_context(&def);
|
||||
ctx.session_dir = sd;
|
||||
ctx.workspaces = ws;
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[bg-arch] tool: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[bg-arch] result: {}", tool);
|
||||
}
|
||||
SubagentEvent::Completed { .. } => {
|
||||
tracing::debug!("[bg-arch] completed");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = run_subagent(&ctx, &tx);
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-arch-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Architecture review: {first}")
|
||||
}
|
||||
Err(e) => format!("Architecture review failed: {e}"),
|
||||
Err(e) if e.contains("aborted") => format!("Architecture review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Architecture review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
@@ -308,11 +396,16 @@ pub fn spawn_background_arch_review(
|
||||
///
|
||||
/// Checks modified files for security vulnerabilities. Reports via
|
||||
/// `TurnEvent::SystemNote { kind: "bg-security-review" }`.
|
||||
///
|
||||
/// Skipped (no-op) if a security-review run is already in flight (guarded by
|
||||
/// `SECURITY_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_security_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
@@ -329,6 +422,10 @@ pub fn spawn_background_security_review(
|
||||
if prod_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if SECURITY_REVIEW_RUNNING.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst).is_err() {
|
||||
tracing::debug!("[bg-security-review] skipped — a security-review run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = prod_paths;
|
||||
let sd = session_dir.to_path_buf();
|
||||
@@ -336,6 +433,7 @@ pub fn spawn_background_security_review(
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&SECURITY_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for security review:\n{}",
|
||||
@@ -350,35 +448,14 @@ pub fn spawn_background_security_review(
|
||||
.with_system_prompt(prompt)
|
||||
;
|
||||
|
||||
let mut ctx = build_subagent_context(&def);
|
||||
ctx.session_dir = sd;
|
||||
ctx.workspaces = ws;
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[bg-security] tool: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[bg-security] result: {}", tool);
|
||||
}
|
||||
SubagentEvent::Completed { .. } => {
|
||||
tracing::debug!("[bg-security] completed");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = run_subagent(&ctx, &tx);
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-security-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Security review: {first}")
|
||||
}
|
||||
Err(e) => format!("Security review failed: {e}"),
|
||||
Err(e) if e.contains("aborted") => format!("Security review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Security review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
@@ -396,11 +473,15 @@ pub fn spawn_background_security_review(
|
||||
/// Flow: always spawns arch-review and security-review if there are
|
||||
/// reviewable production files → spawns test-gen only if there are source
|
||||
/// files that aren't already tests.
|
||||
///
|
||||
/// `abort_flag` is cloned and forwarded to all three spawn calls so a
|
||||
/// single cancellation source stops every kind of background review.
|
||||
pub fn spawn_all_background(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
@@ -412,7 +493,7 @@ pub fn spawn_all_background(
|
||||
.filter(|p| is_production_code(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
spawn_background_test_gen(&source_paths, session_dir, workspaces, turn_events);
|
||||
spawn_background_test_gen(&source_paths, session_dir, workspaces, turn_events, abort_flag.clone());
|
||||
|
||||
// Background arch review: for all files that are reviewable
|
||||
let reviewable: Vec<String> = file_paths
|
||||
@@ -420,8 +501,73 @@ pub fn spawn_all_background(
|
||||
.filter(|p| is_reviewable_path(p))
|
||||
.cloned()
|
||||
.collect();
|
||||
spawn_background_arch_review(&reviewable, session_dir, workspaces, turn_events);
|
||||
spawn_background_arch_review(&reviewable, session_dir, workspaces, turn_events, abort_flag.clone());
|
||||
|
||||
// Background security review: only production source files
|
||||
spawn_background_security_review(&source_paths, session_dir, workspaces, turn_events);
|
||||
spawn_background_security_review(&source_paths, session_dir, workspaces, turn_events, abort_flag);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_skips_lockfiles_and_known_extensions() {
|
||||
assert!(!is_reviewable_path("Cargo.lock"));
|
||||
assert!(!is_reviewable_path("package.json"));
|
||||
assert!(!is_reviewable_path("logo.svg"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_skips_vendored_and_generated_dirs() {
|
||||
assert!(!is_reviewable_path("target/debug/build.rs"));
|
||||
assert!(!is_reviewable_path("node_modules/foo/index.js"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviewable_path_accepts_ordinary_source_files() {
|
||||
assert!(is_reviewable_path("src/main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_excludes_dedicated_test_directories() {
|
||||
assert!(!is_production_code("src/tests/foo.rs"));
|
||||
assert!(!is_production_code("__tests__/baz.test.ts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_excludes_test_filename_conventions() {
|
||||
assert!(!is_production_code("src/foo_test.rs"));
|
||||
assert!(!is_production_code("src/test_foo.py"));
|
||||
assert!(!is_production_code("src/foo.spec.ts"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_does_not_false_positive_on_substring_test() {
|
||||
// Regression: a plain `.contains("test")` would wrongly exclude
|
||||
// these legitimate production files.
|
||||
assert!(is_production_code("src/attestation.rs"));
|
||||
assert!(is_production_code("src/latest/foo.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_code_requires_known_source_extension() {
|
||||
assert!(!is_production_code("README.md"));
|
||||
assert!(is_production_code("src/main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn running_guard_resets_flag_on_drop_even_after_panic() {
|
||||
static TEST_FLAG: AtomicBool = AtomicBool::new(false);
|
||||
TEST_FLAG.store(true, Ordering::SeqCst);
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let _guard = RunningGuard(&TEST_FLAG);
|
||||
panic!("simulated failure inside guarded region");
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
!TEST_FLAG.load(Ordering::SeqCst),
|
||||
"guard must reset the flag even when the guarded closure panics"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+91
-227
@@ -1,237 +1,101 @@
|
||||
//! Company-style agent divisions: specialized subagent roles that form an
|
||||
//! organizational hierarchy like a company.
|
||||
//! Access tiers for the anonymous processing nodes spawned by the
|
||||
//! hive-mind orchestrator (`app::workflow::hive_mind`).
|
||||
//!
|
||||
//! ```text
|
||||
//! CEO (Main Agent)
|
||||
//! ├── Strategy Division (planner) — architecture, diagrams, plan
|
||||
//! ├── Engineering Division (coder) — implementation
|
||||
//! ├── Quality Division (tester) — review, test
|
||||
//! ├── Security Division (auditor) — security audit
|
||||
//! └── Documentation Division (doc) — documentation
|
||||
//! ```
|
||||
//!
|
||||
//! Each division has a specific role, tools, and system prompt tailored to
|
||||
//! its function. The main agent (CEO) delegates work to divisions via
|
||||
//! the company pipeline workflow.
|
||||
//! Nodes have no persistent identity of their own — the Core Intelligence
|
||||
//! addresses each one only by directive and access tier. Since node
|
||||
//! designations are system-assigned coordinates rather than named roles,
|
||||
//! tool access can't be a lookup table keyed by role name. Instead the
|
||||
//! Core Intelligence picks one of these three tiers per node, matched to
|
||||
//! what that node's specific directive needs — this keeps the Harness
|
||||
//! gate meaningful while the node roster itself stays fully dynamic.
|
||||
|
||||
use crate::app::subagent::spawn::AgentDefinition;
|
||||
/// The three tool-access tiers a hive-mind node can be granted.
|
||||
pub mod tool_scope {
|
||||
/// Read-only investigation: no file mutation, no shell, no VCS.
|
||||
pub const READ: &str = "read";
|
||||
/// Read-tier plus file mutation and non-destructive shell (tests/builds).
|
||||
pub const WRITE: &str = "write";
|
||||
/// Write-tier plus delete, git, and the remaining LSP actions.
|
||||
pub const FULL: &str = "full";
|
||||
|
||||
/// Division roles — used as both the `role` field in `AgentDefinition`
|
||||
/// and as the key for pipeline routing.
|
||||
pub mod roles {
|
||||
/// Strategy Division: plans architecture, creates diagrams, breaks down work.
|
||||
pub const STRATEGY: &str = "planner";
|
||||
/// Engineering Division: implements code per the plan.
|
||||
pub const ENGINEERING: &str = "coder";
|
||||
/// Quality Division: reviews implementation, writes tests.
|
||||
pub const QUALITY: &str = "tester";
|
||||
/// Security Division: audits for vulnerabilities.
|
||||
pub const SECURITY: &str = "auditor";
|
||||
/// Documentation Division: updates docs, README, inline documentation.
|
||||
pub const DOCUMENTATION: &str = "documenter";
|
||||
}
|
||||
const READ_TOOLS: &[&str] = &[
|
||||
"read", "grep", "glob", "search", "seqthink", "recall",
|
||||
"lsp_connect", "lsp_diagnostics", "lsp_hover", "lsp_definition",
|
||||
"lsp_references", "read_findings",
|
||||
];
|
||||
|
||||
/// ─── Division Agent Definitions ───
|
||||
///
|
||||
/// Build the Strategy Division agent — chief architect and planner.
|
||||
///
|
||||
/// Tools: read-only (read, grep, glob, search, lsp, plan, seqthink, recall)
|
||||
/// Role: never writes code; produces detailed plans with mermaid diagrams.
|
||||
pub fn strategy_division() -> AgentDefinition {
|
||||
AgentDefinition::new(
|
||||
"strategy-division".to_string(),
|
||||
roles::STRATEGY.to_string(),
|
||||
)
|
||||
.with_system_prompt(crate::resources::DIVISION_PLANNER_PROMPT.to_string())
|
||||
.with_allowed_tools(vec![
|
||||
"read".to_string(),
|
||||
"grep".to_string(),
|
||||
"glob".to_string(),
|
||||
"search".to_string(),
|
||||
"seqthink".to_string(),
|
||||
"plan".to_string(),
|
||||
"recall".to_string(),
|
||||
"lsp_connect".to_string(),
|
||||
"lsp_diagnostics".to_string(),
|
||||
"lsp_hover".to_string(),
|
||||
"lsp_definition".to_string(),
|
||||
"lsp_references".to_string(),
|
||||
"read_findings".to_string(),
|
||||
])
|
||||
}
|
||||
const WRITE_TOOLS: &[&str] = &[
|
||||
"read", "grep", "glob", "search", "seqthink", "recall",
|
||||
"lsp_connect", "lsp_diagnostics", "lsp_hover", "lsp_definition",
|
||||
"lsp_references", "read_findings",
|
||||
"write", "edit", "bash", "todowrite", "todofinish", "remember",
|
||||
];
|
||||
|
||||
/// Build the Engineering Division agent — implements code per the plan.
|
||||
///
|
||||
/// Tools: full access (all write/edit/bash/git/LSP tools)
|
||||
/// Role: executes the strategy plan, one file at a time.
|
||||
pub fn engineering_division() -> AgentDefinition {
|
||||
AgentDefinition::new(
|
||||
"engineering-division".to_string(),
|
||||
roles::ENGINEERING.to_string(),
|
||||
)
|
||||
.with_system_prompt(crate::resources::DIVISION_IMPLEMENTER_PROMPT.to_string())
|
||||
.with_allowed_tools(vec![
|
||||
"read".to_string(),
|
||||
"write".to_string(),
|
||||
"edit".to_string(),
|
||||
"delete".to_string(),
|
||||
"bash".to_string(),
|
||||
"grep".to_string(),
|
||||
"glob".to_string(),
|
||||
"git_operator".to_string(),
|
||||
"seqthink".to_string(),
|
||||
"lsp_connect".to_string(),
|
||||
"lsp_diagnostics".to_string(),
|
||||
"lsp_hover".to_string(),
|
||||
"lsp_definition".to_string(),
|
||||
"lsp_references".to_string(),
|
||||
"lsp_completion".to_string(),
|
||||
"lsp_disconnect".to_string(),
|
||||
"todowrite".to_string(),
|
||||
"todofinish".to_string(),
|
||||
"read_findings".to_string(),
|
||||
])
|
||||
}
|
||||
const FULL_TOOLS: &[&str] = &[
|
||||
"read", "grep", "glob", "search", "seqthink", "recall",
|
||||
"lsp_connect", "lsp_diagnostics", "lsp_hover", "lsp_definition",
|
||||
"lsp_references", "read_findings",
|
||||
"write", "edit", "bash", "todowrite", "todofinish", "remember",
|
||||
"delete", "git_operator", "lsp_completion", "lsp_disconnect",
|
||||
];
|
||||
|
||||
/// Build the Quality Division agent — reviews code and writes tests.
|
||||
///
|
||||
/// Tools: read, write, grep, glob, bash (for running tests), LSP, memory
|
||||
/// Role: verifies correctness and creates/runs tests.
|
||||
pub fn quality_division() -> AgentDefinition {
|
||||
AgentDefinition::new(
|
||||
"quality-division".to_string(),
|
||||
roles::QUALITY.to_string(),
|
||||
)
|
||||
.with_system_prompt(crate::resources::DIVISION_TESTER_PROMPT.to_string())
|
||||
.with_allowed_tools(vec![
|
||||
"read".to_string(),
|
||||
"write".to_string(),
|
||||
"edit".to_string(),
|
||||
"grep".to_string(),
|
||||
"glob".to_string(),
|
||||
"bash".to_string(),
|
||||
"seqthink".to_string(),
|
||||
"recall".to_string(),
|
||||
"remember".to_string(),
|
||||
"lsp_connect".to_string(),
|
||||
"lsp_diagnostics".to_string(),
|
||||
"lsp_hover".to_string(),
|
||||
"lsp_definition".to_string(),
|
||||
"lsp_references".to_string(),
|
||||
"read_findings".to_string(),
|
||||
])
|
||||
}
|
||||
|
||||
/// Build the Security Division agent — security auditor.
|
||||
///
|
||||
/// Tools: read-only + search + memory
|
||||
/// Role: audits implementation for vulnerabilities.
|
||||
pub fn security_division() -> AgentDefinition {
|
||||
AgentDefinition::new(
|
||||
"security-division".to_string(),
|
||||
roles::SECURITY.to_string(),
|
||||
)
|
||||
.with_system_prompt(crate::resources::SECURITY_REVIEWER_PROMPT.to_string())
|
||||
.with_allowed_tools(vec![
|
||||
"read".to_string(),
|
||||
"grep".to_string(),
|
||||
"glob".to_string(),
|
||||
"search".to_string(),
|
||||
"seqthink".to_string(),
|
||||
"recall".to_string(),
|
||||
"remember".to_string(),
|
||||
"lsp_connect".to_string(),
|
||||
"lsp_diagnostics".to_string(),
|
||||
"lsp_hover".to_string(),
|
||||
"lsp_definition".to_string(),
|
||||
"lsp_references".to_string(),
|
||||
"read_findings".to_string(),
|
||||
])
|
||||
}
|
||||
|
||||
/// Build the Documentation Division agent — documentation maintainer.
|
||||
///
|
||||
/// Tools: read, grep, glob, write, edit, memory
|
||||
/// Role: updates README, inline docs, architecture docs.
|
||||
pub fn documentation_division() -> AgentDefinition {
|
||||
AgentDefinition::new(
|
||||
"documentation-division".to_string(),
|
||||
roles::DOCUMENTATION.to_string(),
|
||||
)
|
||||
.with_system_prompt(crate::resources::DIVISION_DOCUMENTER_PROMPT.to_string())
|
||||
.with_allowed_tools(vec![
|
||||
"read".to_string(),
|
||||
"write".to_string(),
|
||||
"edit".to_string(),
|
||||
"grep".to_string(),
|
||||
"glob".to_string(),
|
||||
"recall".to_string(),
|
||||
"remember".to_string(),
|
||||
"read_findings".to_string(),
|
||||
])
|
||||
}
|
||||
|
||||
/// ─── Division Registry ───
|
||||
///
|
||||
/// A named division with its agent definition and display metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Division {
|
||||
/// Display name for the division (e.g. "Strategy", "Engineering").
|
||||
pub name: &'static str,
|
||||
/// Role tag used for pipeline routing (matches `roles::*` constants).
|
||||
#[allow(dead_code)]
|
||||
pub role: &'static str,
|
||||
/// One-line description of what this division does.
|
||||
#[allow(dead_code)]
|
||||
pub description: &'static str,
|
||||
/// Agent definition with tools, prompt, and step budget.
|
||||
pub agent_def: AgentDefinition,
|
||||
}
|
||||
|
||||
impl Division {
|
||||
pub fn new(
|
||||
name: &'static str,
|
||||
role: &'static str,
|
||||
description: &'static str,
|
||||
agent_def: AgentDefinition,
|
||||
) -> Self {
|
||||
Division { name, role, description, agent_def }
|
||||
/// Resolve a tier name to its concrete tool allowlist.
|
||||
///
|
||||
/// Unrecognized scope strings fall back to `READ` — the least-privileged
|
||||
/// tier — rather than silently granting broader access.
|
||||
///
|
||||
/// Return: an owned `Vec<String>` suitable for `AgentDefinition::with_allowed_tools`.
|
||||
pub fn tools_for(scope: &str) -> Vec<String> {
|
||||
let tools: &[&str] = match scope {
|
||||
FULL => FULL_TOOLS,
|
||||
WRITE => WRITE_TOOLS,
|
||||
_ => READ_TOOLS,
|
||||
};
|
||||
tools.iter().map(|s| (*s).to_string()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Return all company divisions as an ordered list matching the pipeline flow:
|
||||
/// Strategy → Engineering → Quality → Security → Documentation.
|
||||
pub fn all_divisions() -> Vec<Division> {
|
||||
vec![
|
||||
Division::new(
|
||||
"Strategy",
|
||||
roles::STRATEGY,
|
||||
"Architecture planning with diagrams and step-by-step breakdown",
|
||||
strategy_division(),
|
||||
),
|
||||
Division::new(
|
||||
"Engineering",
|
||||
roles::ENGINEERING,
|
||||
"Code implementation following the plan",
|
||||
engineering_division(),
|
||||
),
|
||||
Division::new(
|
||||
"Quality",
|
||||
roles::QUALITY,
|
||||
"Code review and comprehensive testing",
|
||||
quality_division(),
|
||||
),
|
||||
Division::new(
|
||||
"Security",
|
||||
roles::SECURITY,
|
||||
"Security vulnerability audit",
|
||||
security_division(),
|
||||
),
|
||||
Division::new(
|
||||
"Documentation",
|
||||
roles::DOCUMENTATION,
|
||||
"Documentation updates and maintenance",
|
||||
documentation_division(),
|
||||
),
|
||||
]
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::tool_scope::{tools_for, FULL, READ, WRITE};
|
||||
|
||||
#[test]
|
||||
fn read_tier_excludes_write_tools() {
|
||||
let tools = tools_for(READ);
|
||||
assert!(!tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"bash".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_tier_includes_bash_but_not_delete_or_git() {
|
||||
let tools = tools_for(WRITE);
|
||||
assert!(tools.contains(&"bash".to_string()));
|
||||
assert!(tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"delete".to_string()));
|
||||
assert!(!tools.contains(&"git_operator".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_tier_includes_delete_and_git() {
|
||||
let tools = tools_for(FULL);
|
||||
assert!(tools.contains(&"delete".to_string()));
|
||||
assert!(tools.contains(&"git_operator".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_scope_falls_back_to_read() {
|
||||
let tools = tools_for("bogus");
|
||||
assert!(!tools.contains(&"write".to_string()));
|
||||
assert!(!tools.contains(&"delete".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_tier_is_subset_of_write_tier_and_write_is_subset_of_full() {
|
||||
use std::collections::HashSet;
|
||||
let read: HashSet<_> = tools_for(READ).into_iter().collect();
|
||||
let write: HashSet<_> = tools_for(WRITE).into_iter().collect();
|
||||
let full: HashSet<_> = tools_for(FULL).into_iter().collect();
|
||||
assert!(read.is_subset(&write), "read tier must be a subset of write tier");
|
||||
assert!(write.is_subset(&full), "write tier must be a subset of full tier");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
//! are not a weaker link than the main agent.
|
||||
|
||||
use std::fmt::Write;
|
||||
use sha2::Digest;
|
||||
use tokio::sync::mpsc;
|
||||
use crate::dto::chat::message::ChatMessage;
|
||||
use crate::dto::provider::request::ToolDef;
|
||||
@@ -29,13 +30,13 @@ fn build_subagent_tools(allowed_tools: &[String]) -> (Vec<Box<dyn crate::tool::T
|
||||
let all = all_tools();
|
||||
let filtered: Vec<Box<dyn crate::tool::Tool>> = if allowed_tools.is_empty() {
|
||||
all.into_iter()
|
||||
.filter(|t| t.name() != "company_pipeline" && t.name() != "workflow_run")
|
||||
.filter(|t| t.name() != "hive_mind" && t.name() != "workflow_run")
|
||||
.collect()
|
||||
} else {
|
||||
all.into_iter()
|
||||
.filter(|t| {
|
||||
allowed_tools.contains(&t.name().to_string())
|
||||
&& t.name() != "company_pipeline"
|
||||
&& t.name() != "hive_mind"
|
||||
&& t.name() != "workflow_run"
|
||||
})
|
||||
.collect()
|
||||
@@ -456,7 +457,6 @@ pub fn run_subagent(ctx: &SubagentContext, tx: &mpsc::Sender<SubagentEvent>) ->
|
||||
.unwrap_or("unknown");
|
||||
let content_sha256 = {
|
||||
let content = args.get("content").or_else(|| args.get("new"));
|
||||
use sha2::Digest;
|
||||
let hash = sha2::Sha256::digest(
|
||||
content.and_then(|v| v.as_str()).unwrap_or("").as_bytes(),
|
||||
);
|
||||
|
||||
@@ -1,406 +0,0 @@
|
||||
//! Company-style workflow orchestrator: runs the complete division pipeline
|
||||
//! (Strategy → Engineering → [Quality || Security || Documentation] in parallel)
|
||||
//! with findings flowing between stages, then returns a consolidated executive
|
||||
//! summary to the CEO (main agent).
|
||||
//!
|
||||
//! Flow:
|
||||
//! ```
|
||||
//! CEO Main Agent
|
||||
//! │ delegates to run_company_pipeline(request)
|
||||
//! ▼
|
||||
//! ┌──────────────────────────────────────────────────┐
|
||||
//! │ Strategy Division — plan + mermaid diagrams │ (runs sequentially first)
|
||||
//! └─────────────────────────┬────────────────────────┘
|
||||
//! ▼
|
||||
//! ┌──────────────────────────────────────────────────┐
|
||||
//! │ Engineering Division — implement per plan │ (runs sequentially second)
|
||||
//! └─────────────────────────┬────────────────────────┘
|
||||
//! ▼
|
||||
//! ┌────────────┼────────────┐
|
||||
//! ▼ ▼ ▼
|
||||
//! ┌───────────┐┌───────────┐┌───────────┐
|
||||
//! │ Quality ││ Security ││ Docs │ (run concurrently in parallel)
|
||||
//! └───────────┘└───────────┘└───────────┘
|
||||
//! │ │ │
|
||||
//! └────────────┼────────────┘
|
||||
//! ▼
|
||||
//! CEO Main Agent delivers consolidated summary to user
|
||||
//! ```
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{Arc, Mutex, atomic::AtomicBool};
|
||||
use crate::app::workflow::script::{ScriptPrimitive, ScriptOptions, WorkflowScript};
|
||||
use crate::app::workflow::engine::{execute_primitive, LiveStateFn, AgentStatus};
|
||||
use crate::app::subagent::division;
|
||||
|
||||
/// Construct the specialized agents for a division.
|
||||
///
|
||||
/// Flow: map division name to its specialization pool.
|
||||
///
|
||||
/// Return: a `Vec<ScriptPrimitive>` containing the specialist agents.
|
||||
fn make_division_specialists(
|
||||
div: &division::Division,
|
||||
user_request: &str,
|
||||
specs: &[(String, String)],
|
||||
) -> Vec<ScriptPrimitive> {
|
||||
let div_prompt = div.agent_def.system_prompt.as_deref().unwrap_or("");
|
||||
|
||||
specs
|
||||
.iter()
|
||||
.map(|(label, focus)| {
|
||||
// Prepend [Division Name: Specialist Label] so the first 40 chars
|
||||
// of the prompt become the agent_name in spawn_single_agent.
|
||||
// We use quadruple curly braces `{{{{findings}}}}` so that Rust's `format!` formats it
|
||||
// into `{{findings}}` in the output string, which `resolve_template` then recognizes
|
||||
// and replaces.
|
||||
let prompt = format!(
|
||||
"[{}: {}]\n\n{}\n\n{}\n\nUser request: {}\n\nFindings from previous divisions:\n{{{{findings}}}}",
|
||||
div.name,
|
||||
label,
|
||||
focus,
|
||||
div_prompt,
|
||||
user_request,
|
||||
);
|
||||
ScriptPrimitive::Agent(prompt)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Construct a named Phase wrapper containing a Parallel block of division specialists.
|
||||
///
|
||||
/// Flow: construct division specialists → wrap in a `Parallel` primitive wrapper.
|
||||
///
|
||||
/// Return: a `ScriptPrimitive::Phase` wrapper.
|
||||
fn make_division_phase(
|
||||
div: &division::Division,
|
||||
user_request: &str,
|
||||
specs: &[(String, String)],
|
||||
) -> ScriptPrimitive {
|
||||
let specialists = make_division_specialists(div, user_request, specs);
|
||||
ScriptPrimitive::Phase {
|
||||
name: div.name.to_string(),
|
||||
script: Box::new(ScriptPrimitive::Parallel(specialists)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the full company-style pipeline for a given user request.
|
||||
///
|
||||
/// This orchestrates all five divisions, running Strategy and Engineering
|
||||
/// sequentially, followed by Quality, Security, and Documentation in parallel.
|
||||
///
|
||||
/// Each division receives findings from all previous divisions, enabling
|
||||
/// context to flow through the pipeline.
|
||||
///
|
||||
/// Returns a consolidated executive summary string.
|
||||
#[allow(clippy::ref_option)]
|
||||
pub fn run_company_pipeline(
|
||||
user_request: &str,
|
||||
session_dir: &std::path::Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: Option<&Arc<Mutex<std::collections::VecDeque<crate::app::state::runtime::TurnEvent>>>>,
|
||||
abort_flag: &Option<Arc<AtomicBool>>,
|
||||
custom_specialists: &HashMap<String, Vec<(String, String)>>,
|
||||
) -> anyhow::Result<String> {
|
||||
let divisions = division::all_divisions();
|
||||
|
||||
let strategy_specs = custom_specialists.get("Strategy")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Strategy"))?;
|
||||
let engineering_specs = custom_specialists.get("Engineering")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Engineering"))?;
|
||||
let quality_specs = custom_specialists.get("Quality")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Quality"))?;
|
||||
let security_specs = custom_specialists.get("Security")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Security"))?;
|
||||
let documentation_specs = custom_specialists.get("Documentation")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Documentation"))?;
|
||||
|
||||
let strategy_phase = make_division_phase(&divisions[0], user_request, strategy_specs);
|
||||
let engineering_phase = make_division_phase(&divisions[1], user_request, engineering_specs);
|
||||
|
||||
let quality_phase = make_division_phase(&divisions[2], user_request, quality_specs);
|
||||
let security_phase = make_division_phase(&divisions[3], user_request, security_specs);
|
||||
let documentation_phase = make_division_phase(&divisions[4], user_request, documentation_specs);
|
||||
|
||||
let parallel_divisions = ScriptPrimitive::Parallel(vec![
|
||||
quality_phase,
|
||||
security_phase,
|
||||
documentation_phase,
|
||||
]);
|
||||
|
||||
let pipeline_primitive = ScriptPrimitive::Pipeline(vec![
|
||||
strategy_phase,
|
||||
engineering_phase,
|
||||
parallel_divisions,
|
||||
]);
|
||||
|
||||
let wf = WorkflowScript {
|
||||
name: "company-pipeline".to_string(),
|
||||
description: "Company Pipeline: Strategy → Engineering → (Quality || Security || Documentation)".to_string(),
|
||||
script: pipeline_primitive,
|
||||
options: ScriptOptions {
|
||||
max_concurrency: 10,
|
||||
continue_on_error: true,
|
||||
timeout_ms: None,
|
||||
},
|
||||
};
|
||||
|
||||
let live: Option<LiveStateFn> = turn_events.map(|events| {
|
||||
let events = events.clone();
|
||||
let f: LiveStateFn = Arc::new(move |_agent_id: String, agent_name: String, status: AgentStatus| {
|
||||
let display_name = agent_name.chars().take(30).collect::<String>();
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(crate::app::state::runtime::TurnEvent::WorkflowAgentUpdate {
|
||||
agent_id: display_name.clone(),
|
||||
agent_name: display_name,
|
||||
status,
|
||||
});
|
||||
}
|
||||
});
|
||||
f
|
||||
});
|
||||
|
||||
let args: HashMap<String, String> = HashMap::new();
|
||||
let findings: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
let results = execute_primitive(
|
||||
&wf.script,
|
||||
&args,
|
||||
wf.options.max_concurrency,
|
||||
true,
|
||||
abort_flag,
|
||||
live.as_ref(),
|
||||
session_dir,
|
||||
workspaces,
|
||||
&findings,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let all_findings = findings.lock()
|
||||
.map(|f| f.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(build_executive_summary(user_request, &results, &all_findings, &divisions, custom_specialists))
|
||||
}
|
||||
|
||||
/// Run a quick company pipeline that skips non-essential divisions
|
||||
/// for simple tasks. Flow: Strategy → Engineering → Quality.
|
||||
///
|
||||
/// This is for smaller tasks where security audit and full docs are overkill.
|
||||
#[allow(clippy::ref_option)]
|
||||
pub fn run_company_pipeline_quick(
|
||||
user_request: &str,
|
||||
session_dir: &std::path::Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: Option<&Arc<Mutex<std::collections::VecDeque<crate::app::state::runtime::TurnEvent>>>>,
|
||||
abort_flag: &Option<Arc<AtomicBool>>,
|
||||
custom_specialists: &HashMap<String, Vec<(String, String)>>,
|
||||
) -> anyhow::Result<String> {
|
||||
let divisions = division::all_divisions();
|
||||
let quick_divisions = &divisions[..3];
|
||||
|
||||
let strategy_specs = custom_specialists.get("Strategy")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Strategy"))?;
|
||||
let engineering_specs = custom_specialists.get("Engineering")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Engineering"))?;
|
||||
let quality_specs = custom_specialists.get("Quality")
|
||||
.ok_or_else(|| anyhow::anyhow!("missing required division configuration: Quality"))?;
|
||||
|
||||
let strategy_phase = make_division_phase(&quick_divisions[0], user_request, strategy_specs);
|
||||
let engineering_phase = make_division_phase(&quick_divisions[1], user_request, engineering_specs);
|
||||
let quality_phase = make_division_phase(&quick_divisions[2], user_request, quality_specs);
|
||||
|
||||
let pipeline_primitive = ScriptPrimitive::Pipeline(vec![
|
||||
strategy_phase,
|
||||
engineering_phase,
|
||||
quality_phase,
|
||||
]);
|
||||
|
||||
let wf = WorkflowScript {
|
||||
name: "company-pipeline-quick".to_string(),
|
||||
description: "Company Pipeline (quick): Strategy → Engineering → Quality".to_string(),
|
||||
script: pipeline_primitive,
|
||||
options: ScriptOptions {
|
||||
max_concurrency: 10,
|
||||
continue_on_error: true,
|
||||
timeout_ms: None,
|
||||
},
|
||||
};
|
||||
|
||||
let live: Option<LiveStateFn> = turn_events.map(|events| {
|
||||
let events = events.clone();
|
||||
let f: LiveStateFn = Arc::new(move |_agent_id: String, agent_name: String, status: AgentStatus| {
|
||||
let display_name = agent_name.chars().take(30).collect::<String>();
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(crate::app::state::runtime::TurnEvent::WorkflowAgentUpdate {
|
||||
agent_id: display_name.clone(),
|
||||
agent_name: display_name,
|
||||
status,
|
||||
});
|
||||
}
|
||||
});
|
||||
f
|
||||
});
|
||||
|
||||
let args: HashMap<String, String> = HashMap::new();
|
||||
let findings: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
|
||||
let results = execute_primitive(
|
||||
&wf.script, &args, wf.options.max_concurrency, true,
|
||||
abort_flag, live.as_ref(), session_dir, workspaces, &findings, None,
|
||||
)?;
|
||||
|
||||
let all_findings = findings.lock()
|
||||
.map(|f| f.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(build_executive_summary(user_request, &results, &all_findings, quick_divisions, custom_specialists))
|
||||
}
|
||||
|
||||
/// Build a compressed executive summary from pipeline results.
|
||||
///
|
||||
/// Flow: print user request header → for each division, fetch its specialist verdicts
|
||||
/// → join with pipes → append findings count.
|
||||
///
|
||||
/// Why: keeps output brief to save context window space. Full results are accessible
|
||||
/// to the CEO via findings.
|
||||
///
|
||||
/// Return: a formatted executive summary string.
|
||||
fn build_executive_summary(
|
||||
request: &str,
|
||||
results: &[String],
|
||||
findings: &[String],
|
||||
divisions: &[division::Division],
|
||||
custom_specialists: &HashMap<String, Vec<(String, String)>>,
|
||||
) -> String {
|
||||
let mut summary = String::new();
|
||||
writeln!(summary, "Pipeline for: {request}").unwrap();
|
||||
|
||||
let mut start_index = 0;
|
||||
for div in divisions {
|
||||
let count = custom_specialists.get(div.name)
|
||||
.map_or(0, Vec::len);
|
||||
|
||||
let mut division_verdicts = Vec::new();
|
||||
for offset in 0..count {
|
||||
if let Some(r) = results.get(start_index + offset) {
|
||||
let first_line = r.lines().next().unwrap_or(r);
|
||||
let trimmed = first_line.chars().take(40).collect::<String>();
|
||||
division_verdicts.push(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
let verdict = if division_verdicts.is_empty() {
|
||||
"—".to_string()
|
||||
} else {
|
||||
division_verdicts.join(" | ")
|
||||
};
|
||||
|
||||
writeln!(summary, " {}: {}", div.name, verdict).unwrap();
|
||||
start_index += count;
|
||||
}
|
||||
|
||||
if !findings.is_empty() {
|
||||
writeln!(summary, " Notes: {} cross-division finding(s)", findings.len()).unwrap();
|
||||
}
|
||||
|
||||
summary
|
||||
}
|
||||
|
||||
/// Determine whether a request is complex enough for the full pipeline
|
||||
/// or can use the quick version.
|
||||
///
|
||||
/// Simple = single file, minor fix, quick lookup, config change.
|
||||
/// Complex = new feature, multi-file refactor, architecture change.
|
||||
///
|
||||
/// Used by the auto-CEO pipeline trigger in `run_agent_turn` to decide
|
||||
/// whether to delegate to the full company pipeline or handle directly.
|
||||
///
|
||||
/// Heuristics:
|
||||
/// - Very short requests (< 10 chars) are never complex.
|
||||
/// - Negative keywords (simple/trivial/typo/quick) skip the pipeline.
|
||||
/// - Positive keywords (refactor/api/implement/architecture) trigger it.
|
||||
/// - Multi-line or multi-sentence requests are more likely complex.
|
||||
#[allow(dead_code)]
|
||||
pub fn is_complex_request(request: &str) -> bool {
|
||||
let trimmed = request.trim();
|
||||
// Very short requests are never complex
|
||||
if trimmed.len() < 10 {
|
||||
return false;
|
||||
}
|
||||
// Single-line simple update patterns
|
||||
let lower = trimmed.to_lowercase();
|
||||
let negative_keywords = [
|
||||
"simple", "trivial", "typo", "just a", "only a", "minor",
|
||||
"quick", "tiny", "small fix", "rename", "nitpick",
|
||||
"cosmetic", "formatting", "spelling", "grammar",
|
||||
"bump", "version bump", "update comment",
|
||||
];
|
||||
if negative_keywords.iter().any(|k| lower.contains(k)) {
|
||||
return false;
|
||||
}
|
||||
// Multi-line/multi-sentence → likely complex
|
||||
let sentences = trimmed.split(['.', '!', '?'])
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.count();
|
||||
if sentences >= 3 {
|
||||
return true;
|
||||
}
|
||||
// Positive complexity keywords
|
||||
let complexity_keywords = [
|
||||
"refactor", "redesign", "architecture", "feature", "implement",
|
||||
"migrate", "restructure", "rewrite", "new module", "new component",
|
||||
"scaffold", "multi", "multiple files", "api", "endpoint",
|
||||
"integration", "system", "workflow", "pipeline", "database",
|
||||
"authentication", "authorization", "full stack",
|
||||
];
|
||||
complexity_keywords.iter().any(|k| lower.contains(k))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_too_short() {
|
||||
assert!(!is_complex_request("abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_simple_keywords() {
|
||||
assert!(!is_complex_request("just a simple update to the readme"));
|
||||
assert!(!is_complex_request("minor typo fix in main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_multi_sentence() {
|
||||
assert!(is_complex_request("This is sentence one. This is sentence two. This is sentence three."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_complex_keywords() {
|
||||
assert!(is_complex_request("implement user authentication endpoint"));
|
||||
assert!(is_complex_request("refactor the whole engine module"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_make_division_specialists_custom() {
|
||||
let divisions = division::all_divisions();
|
||||
let div = &divisions[0];
|
||||
let mut custom = HashMap::new();
|
||||
custom.insert(
|
||||
"Strategy".to_string(),
|
||||
vec![
|
||||
("Custom Label".to_string(), "Custom Focus Description".to_string())
|
||||
]
|
||||
);
|
||||
let specs = make_division_specialists(div, "Test Request", custom.get("Strategy").unwrap());
|
||||
assert_eq!(specs.len(), 1);
|
||||
if let ScriptPrimitive::Agent(prompt) = &specs[0] {
|
||||
assert!(prompt.contains("Custom Label"));
|
||||
assert!(prompt.contains("Custom Focus Description"));
|
||||
} else {
|
||||
panic!("Expected ScriptPrimitive::Agent");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Guaranteed, deterministic documentation output for hive-mind runs.
|
||||
//!
|
||||
//! Because cycles/directives are entirely Core-Intelligence-authored (see
|
||||
//! `app::workflow::hive_mind`), it could in principle never plan a "write
|
||||
//! docs" node for a given task. Durable documentation can't depend on that
|
||||
//! choice, so this step is plain Rust — not an LLM call, not a cycle the
|
||||
//! Core Intelligence can omit or reshape — and always runs after any
|
||||
//! hive-mind convergence completes.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::fmt::Write as _;
|
||||
use crate::app::workflow::hive_mind::NodeReport;
|
||||
use crate::model::memory::Memory;
|
||||
|
||||
/// Write a markdown report of one hive-mind convergence to
|
||||
/// `<workspace_root>/docs/runs/<timestamp>-<slug>.md`.
|
||||
///
|
||||
/// Flow: build a slug from the user request → format every `NodeReport`
|
||||
/// (grouped by cycle) with its complete output (no truncation — this is
|
||||
/// the durable record of what the hive actually decided and did) → append
|
||||
/// the final reconciled `consensus` as its own section → create
|
||||
/// `docs/runs/` if missing → write the file.
|
||||
///
|
||||
/// Return: the path written, so callers can log/reference it.
|
||||
pub fn write_hive_mind_convergence(
|
||||
workspace_root: &Path,
|
||||
user_request: &str,
|
||||
reports: &[NodeReport],
|
||||
consensus: &str,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let runs_dir = workspace_root.join("docs").join("runs");
|
||||
std::fs::create_dir_all(&runs_dir)?;
|
||||
|
||||
let ts = chrono::Utc::now();
|
||||
let slug = Memory::slugify(user_request).unwrap_or_else(|| "run".to_string());
|
||||
let filename = format!("{}-{}.md", ts.format("%Y%m%d-%H%M%S"), slug);
|
||||
let path = runs_dir.join(filename);
|
||||
|
||||
let content = render_report(user_request, ts.timestamp_millis(), reports, consensus);
|
||||
std::fs::write(&path, content)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Render a hive-mind convergence as a markdown document.
|
||||
fn render_report(user_request: &str, ts_millis: i64, reports: &[NodeReport], consensus: &str) -> String {
|
||||
let mut out = String::new();
|
||||
writeln!(out, "# Hive-mind convergence: {user_request}").unwrap();
|
||||
writeln!(out, "\nTimestamp (ms): {ts_millis}\n").unwrap();
|
||||
|
||||
let cycle_count = reports.iter().map(|r| r.cycle_index).max().map_or(0, |m| m + 1);
|
||||
for cycle_index in 0..cycle_count {
|
||||
writeln!(out, "## Cycle {cycle_index}\n").unwrap();
|
||||
for r in reports.iter().filter(|r| r.cycle_index == cycle_index) {
|
||||
writeln!(out, "### {}\n", r.node_id).unwrap();
|
||||
writeln!(out, "{}\n", r.output).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
writeln!(out, "## Collective Consensus\n").unwrap();
|
||||
writeln!(out, "{consensus}\n").unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn writes_run_file_under_docs_runs() {
|
||||
let tmp = std::env::temp_dir().join(format!("zesdex-docs-test-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
|
||||
let reports = vec![
|
||||
NodeReport { node_id: "Node-0-0".to_string(), cycle_index: 0, output: "found the bug".to_string() },
|
||||
];
|
||||
let path = write_hive_mind_convergence(&tmp, "fix the bug", &reports, "the bug is a null check").unwrap();
|
||||
|
||||
assert!(path.starts_with(tmp.join("docs").join("runs")));
|
||||
let content = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(content.contains("fix the bug"));
|
||||
assert!(content.contains("Node-0-0"));
|
||||
assert!(content.contains("found the bug"));
|
||||
assert!(content.contains("Collective Consensus"));
|
||||
assert!(content.contains("the bug is a null check"));
|
||||
|
||||
std::fs::remove_dir_all(&tmp).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_generic_slug_for_unslugifiable_request() {
|
||||
let tmp = std::env::temp_dir().join(format!("zesdex-docs-test-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
|
||||
let path = write_hive_mind_convergence(&tmp, "???", &[], "").unwrap();
|
||||
assert!(path.file_name().unwrap().to_str().unwrap().contains("run"));
|
||||
|
||||
std::fs::remove_dir_all(&tmp).ok();
|
||||
}
|
||||
}
|
||||
+49
-29
@@ -76,7 +76,7 @@ impl WorkflowEngine {
|
||||
/// - `status`: the agent's lifecycle state and timing.
|
||||
///
|
||||
/// Callers should use `agent_id` as the stable key and `agent_name` for
|
||||
/// display purposes (e.g. the division name in the company pipeline).
|
||||
/// display purposes (e.g. a hive-mind node's designation, `"Node-0-1"`).
|
||||
pub type LiveStateFn = Arc<dyn Fn(String, String, AgentStatus) + Send + Sync>;
|
||||
|
||||
/// Spawn a single synchronous subagent with the given prompt, passing it
|
||||
@@ -103,6 +103,8 @@ fn spawn_single_agent(
|
||||
agent_id: &str,
|
||||
agent_name: &str,
|
||||
prompt: &str,
|
||||
role: &str,
|
||||
allowed_tools: Option<Vec<String>>,
|
||||
findings_snapshot: &[String],
|
||||
findings: &Arc<Mutex<Vec<String>>>,
|
||||
abort_flag: &Option<Arc<AtomicBool>>,
|
||||
@@ -119,7 +121,7 @@ fn spawn_single_agent(
|
||||
|
||||
// Notify UI: this agent is now running.
|
||||
// Pass both the unique agent_id (UUID for stable key) and agent_name
|
||||
// (human-readable display name, e.g. division name).
|
||||
// (human-readable display name, e.g. a hive-mind node designation).
|
||||
if let Some(f) = live {
|
||||
f(
|
||||
agent_id.to_string(),
|
||||
@@ -134,32 +136,7 @@ fn spawn_single_agent(
|
||||
);
|
||||
}
|
||||
|
||||
let mut role = "coder".to_string();
|
||||
let mut allowed_tools = None;
|
||||
|
||||
if agent_name.contains("Strategy") {
|
||||
let div_def = crate::app::subagent::division::strategy_division();
|
||||
role = div_def.role;
|
||||
allowed_tools = div_def.allowed_tools;
|
||||
} else if agent_name.contains("Engineering") {
|
||||
let div_def = crate::app::subagent::division::engineering_division();
|
||||
role = div_def.role;
|
||||
allowed_tools = div_def.allowed_tools;
|
||||
} else if agent_name.contains("Quality") {
|
||||
let div_def = crate::app::subagent::division::quality_division();
|
||||
role = div_def.role;
|
||||
allowed_tools = div_def.allowed_tools;
|
||||
} else if agent_name.contains("Security") {
|
||||
let div_def = crate::app::subagent::division::security_division();
|
||||
role = div_def.role;
|
||||
allowed_tools = div_def.allowed_tools;
|
||||
} else if agent_name.contains("Documentation") {
|
||||
let div_def = crate::app::subagent::division::documentation_division();
|
||||
role = div_def.role;
|
||||
allowed_tools = div_def.allowed_tools;
|
||||
}
|
||||
|
||||
let mut def = AgentDefinition::new(agent_name.to_string(), role);
|
||||
let mut def = AgentDefinition::new(agent_name.to_string(), role.to_string());
|
||||
if let Some(tools) = allowed_tools {
|
||||
def = def.with_allowed_tools(tools);
|
||||
}
|
||||
@@ -387,7 +364,7 @@ pub fn execute_primitive(
|
||||
let resolved = resolve_template(prompt, &resolved_args);
|
||||
let agent_id = uuid::Uuid::new_v4().to_string();
|
||||
let agent_name = resolved.chars().take(40).collect::<String>();
|
||||
match spawn_single_agent(&agent_id, &agent_name, &resolved, &findings_snapshot, findings, abort_flag, live, session_dir, workspaces, timeout_ms) {
|
||||
match spawn_single_agent(&agent_id, &agent_name, &resolved, "coder", None, &findings_snapshot, findings, abort_flag, live, session_dir, workspaces, timeout_ms) {
|
||||
Ok(text) => Ok(vec![text]),
|
||||
Err(e) => {
|
||||
if continue_on_error {
|
||||
@@ -399,6 +376,49 @@ pub fn execute_primitive(
|
||||
}
|
||||
}
|
||||
|
||||
ScriptPrimitive::ScopedAgent { prompt, node_id, tool_scope } => {
|
||||
let mut resolved_args = args.clone();
|
||||
let findings_snapshot = findings.lock().map(|f| f.clone()).unwrap_or_default();
|
||||
if !resolved_args.contains_key("findings") {
|
||||
let formatted_findings = if findings_snapshot.is_empty() {
|
||||
"None".to_string()
|
||||
} else {
|
||||
findings_snapshot
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| format!("{}. {}", i + 1, f))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
resolved_args.insert("findings".to_string(), formatted_findings);
|
||||
}
|
||||
let resolved = resolve_template(prompt, &resolved_args);
|
||||
let agent_id = uuid::Uuid::new_v4().to_string();
|
||||
let agent_name = format!("{node_id}: {}", resolved.chars().take(30).collect::<String>());
|
||||
let allowed_tools = crate::app::subagent::division::tool_scope::tools_for(tool_scope);
|
||||
match spawn_single_agent(&agent_id, &agent_name, &resolved, node_id, Some(allowed_tools), &findings_snapshot, findings, abort_flag, live, session_dir, workspaces, timeout_ms) {
|
||||
Ok(text) => {
|
||||
// Merge this node's complete output into the shared
|
||||
// collective state the instant it finishes — not after
|
||||
// the whole parallel cohort completes. Any sibling node
|
||||
// still running (via read_findings) or any node spawned
|
||||
// afterward sees this immediately, making the collective
|
||||
// state genuinely continuous rather than batch-synced.
|
||||
if let Ok(mut f) = findings.lock() {
|
||||
f.push(format!("[{node_id}]: {text}"));
|
||||
}
|
||||
Ok(vec![text])
|
||||
}
|
||||
Err(e) => {
|
||||
if continue_on_error {
|
||||
Ok(vec![format!("agent error: {}", e)])
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ScriptPrimitive::Parallel(scripts) => {
|
||||
// All branches run concurrently, capped by semaphore.
|
||||
// This is the primary advantage over single-turn chat: multiple
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
//! Hive-mind multi-agent orchestration.
|
||||
//!
|
||||
//! Modeled on the "Machine Intelligence" archetype from sci-fi strategy
|
||||
//! games (Stellaris et al.): the Core Intelligence (the main agent) issues
|
||||
//! directives that spawn anonymous processing nodes, each carrying only a
|
||||
//! directive and an access tier. Every node's complete output merges into
|
||||
//! a single collective state the instant it finishes (see
|
||||
//! `engine::execute_primitive`'s `ScopedAgent` arm), visible to every
|
||||
//! other node still running or spawned afterward — continuously, not just
|
||||
//! at cycle boundaries. When all cognitive cycles complete, one final
|
||||
//! synthesis node reconciles the entire collective state into a single
|
||||
//! consensus assessment.
|
||||
//!
|
||||
//! ```text
|
||||
//! Core Intelligence
|
||||
//! │ issues a CognitiveCyclePlan { cycles: [[NodeDirective, ...], ...] }
|
||||
//! ▼
|
||||
//! Cycle 0: Node-0-0, Node-0-1, ... (run in parallel; each merges into
|
||||
//! │ the collective state the instant
|
||||
//! │ it completes — not batched)
|
||||
//! ▼
|
||||
//! Cycle 1: ...
|
||||
//! ▼
|
||||
//! ...however many cycles the Core Intelligence decided this task needs...
|
||||
//! ▼
|
||||
//! Synthesis node reads the complete collective state and produces one
|
||||
//! reconciled consensus — returned to the Core Intelligence and persisted
|
||||
//! to docs/runs/*.md.
|
||||
//! ```
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
|
||||
use serde::Deserialize;
|
||||
use crate::app::workflow::script::ScriptPrimitive;
|
||||
use crate::app::workflow::engine::{execute_primitive, LiveStateFn, AgentStatus};
|
||||
|
||||
/// One directive the Core Intelligence wants a node to execute within a
|
||||
/// cognitive cycle. A node's sole identity is its directive and access tier.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct NodeDirective {
|
||||
pub directive: String,
|
||||
/// Access tier: "read" | "write" | "full". Defaults to "read" when
|
||||
/// omitted; unrecognized values also fall back to "read" (see
|
||||
/// `division::tool_scope::tools_for`).
|
||||
#[serde(default = "default_access")]
|
||||
pub access: String,
|
||||
}
|
||||
|
||||
fn default_access() -> String {
|
||||
crate::app::subagent::division::tool_scope::READ.to_string()
|
||||
}
|
||||
|
||||
/// A Core-Intelligence-authored execution plan: an ordered list of
|
||||
/// cognitive cycles, each cycle a list of node directives executed in
|
||||
/// parallel. Cycle count and nodes-per-cycle are fully dynamic.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CognitiveCyclePlan {
|
||||
pub cycles: Vec<Vec<NodeDirective>>,
|
||||
}
|
||||
|
||||
/// The complete output of one node within one cognitive cycle.
|
||||
///
|
||||
/// `node_id` is a system-assigned coordinate (e.g. `"Node-0-1"`) that
|
||||
/// identifies a node purely by its position in the hive.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NodeReport {
|
||||
pub node_id: String,
|
||||
pub cycle_index: usize,
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
/// Tag prefixing the system message `run_hive_mind`'s caller pushes into
|
||||
/// the conversation after a successful convergence. Shared between the
|
||||
/// push site (`actions/mod.rs`) and `hive_mind_already_ran` below so the
|
||||
/// two can never drift out of sync.
|
||||
pub const HIVE_MIND_CONSENSUS_TAG: &str = "[Hive-Mind Consensus]";
|
||||
|
||||
/// Detect whether a hive-mind convergence has already run earlier in this
|
||||
/// conversation, by checking prior system-message bodies for the
|
||||
/// consensus tag.
|
||||
///
|
||||
/// Why: gates re-triggering the Core Intelligence pipeline more than once
|
||||
/// per session on message *content* actually observed, rather than an
|
||||
/// arbitrary "first two user messages" cutoff that silently disabled the
|
||||
/// pipeline for any complex request phrased later in a long conversation.
|
||||
///
|
||||
/// Return: `true` if any prior system message starts with
|
||||
/// `HIVE_MIND_CONSENSUS_TAG`.
|
||||
pub fn hive_mind_already_ran<'a>(system_message_bodies: impl Iterator<Item = &'a str>) -> bool {
|
||||
system_message_bodies.into_iter().any(|body| body.starts_with(HIVE_MIND_CONSENSUS_TAG))
|
||||
}
|
||||
|
||||
/// Build the live-state callback that forwards node status updates to the
|
||||
/// TUI's workflow panel.
|
||||
fn build_live(
|
||||
turn_events: Option<&Arc<Mutex<std::collections::VecDeque<crate::app::state::runtime::TurnEvent>>>>,
|
||||
) -> Option<LiveStateFn> {
|
||||
turn_events.map(|events| {
|
||||
let events = events.clone();
|
||||
let f: LiveStateFn = Arc::new(move |_agent_id: String, agent_name: String, status: AgentStatus| {
|
||||
let display_name = agent_name.chars().take(40).collect::<String>();
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(crate::app::state::runtime::TurnEvent::WorkflowAgentUpdate {
|
||||
agent_id: display_name.clone(),
|
||||
agent_name: display_name,
|
||||
status,
|
||||
});
|
||||
}
|
||||
});
|
||||
f
|
||||
})
|
||||
}
|
||||
|
||||
/// Run a hive-mind: a Core-Intelligence-authored plan of cognitive cycles,
|
||||
/// where every node's complete output merges into a single collective
|
||||
/// state the instant it finishes, and a final synthesis node reconciles
|
||||
/// the whole collective state into one consensus assessment.
|
||||
///
|
||||
/// Flow: for each cycle (sequential) → spawn one `ScriptPrimitive::ScopedAgent`
|
||||
/// per directive, tagged with a system-assigned `node_id` (never an
|
||||
/// LLM-authored name) → run them as a `Parallel` block via
|
||||
/// `execute_primitive`, which merges each node's output into the shared
|
||||
/// collective-state Arc the instant that node completes, not after the
|
||||
/// whole cohort finishes → record `NodeReport`s → proceed to the next
|
||||
/// cycle. After all cycles: spawn one more read-only synthesis node whose
|
||||
/// directive is to reconcile the complete collective state into a single
|
||||
/// consensus, not list what each node said.
|
||||
///
|
||||
/// Concurrency per cycle and the per-node timeout both come from
|
||||
/// `Settings::load()` (`workflow_max_concurrency`, `hive_mind_node_timeout_ms`)
|
||||
/// rather than a hardcoded cap/no-timeout — a stuck node can no longer hang
|
||||
/// the whole convergence forever.
|
||||
///
|
||||
/// Return: `(consensus, all_node_reports)` on success. `consensus` is the
|
||||
/// synthesis node's reconciled output — what the Core Intelligence
|
||||
/// actually receives. `all_node_reports` is the complete per-node record.
|
||||
///
|
||||
/// The convergence doc under `docs/runs/*.md` is written unconditionally
|
||||
/// before this function returns — even when synthesis itself fails — so a
|
||||
/// synthesis-node error never discards the work already done by cycle
|
||||
/// nodes. Callers must not write their own copy of this doc.
|
||||
pub fn run_hive_mind(
|
||||
user_request: &str,
|
||||
plan: &CognitiveCyclePlan,
|
||||
session_dir: &std::path::Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
turn_events: Option<&Arc<Mutex<std::collections::VecDeque<crate::app::state::runtime::TurnEvent>>>>,
|
||||
abort_flag: Option<&Arc<AtomicBool>>,
|
||||
) -> anyhow::Result<(String, Vec<NodeReport>)> {
|
||||
if plan.cycles.is_empty() {
|
||||
anyhow::bail!("cognitive cycle plan has no cycles");
|
||||
}
|
||||
|
||||
let settings = crate::model::settings::Settings::load();
|
||||
let node_timeout_ms = Some(settings.hive_mind_node_timeout_ms);
|
||||
let max_cycle_concurrency = settings.workflow_max_concurrency.max(1);
|
||||
|
||||
let live = build_live(turn_events);
|
||||
let collective_state: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
let args: HashMap<String, String> = HashMap::new();
|
||||
let mut reports: Vec<NodeReport> = Vec::new();
|
||||
let abort_owned: Option<Arc<AtomicBool>> = abort_flag.cloned();
|
||||
|
||||
for (cycle_index, directives) in plan.cycles.iter().enumerate() {
|
||||
if directives.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if abort_flag.is_some_and(|f| f.load(Ordering::SeqCst)) {
|
||||
anyhow::bail!("hive-mind aborted by user before cycle {cycle_index}");
|
||||
}
|
||||
|
||||
let node_ids: Vec<String> = (0..directives.len())
|
||||
.map(|i| format!("Node-{cycle_index}-{i}"))
|
||||
.collect();
|
||||
|
||||
let nodes: Vec<ScriptPrimitive> = directives.iter().zip(node_ids.iter()).map(|(d, node_id)| {
|
||||
ScriptPrimitive::ScopedAgent {
|
||||
prompt: format!(
|
||||
"You are {node_id}, a processing node of a distributed machine \
|
||||
intelligence.\n\n\
|
||||
Directive: {}\n\n\
|
||||
Overall task: {user_request}\n\n\
|
||||
Collective state accumulated so far:\n{{{{findings}}}}",
|
||||
d.directive,
|
||||
),
|
||||
node_id: node_id.clone(),
|
||||
tool_scope: d.access.clone(),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
let cycle_primitive = ScriptPrimitive::Phase {
|
||||
name: format!("cycle-{cycle_index}"),
|
||||
script: Box::new(ScriptPrimitive::Parallel(nodes)),
|
||||
};
|
||||
|
||||
let results = execute_primitive(
|
||||
&cycle_primitive,
|
||||
&args,
|
||||
directives.len().clamp(1, max_cycle_concurrency),
|
||||
true,
|
||||
&abort_owned,
|
||||
live.as_ref(),
|
||||
session_dir,
|
||||
workspaces,
|
||||
&collective_state,
|
||||
node_timeout_ms,
|
||||
)?;
|
||||
|
||||
// engine::execute_primitive's ScopedAgent arm already merged each
|
||||
// node's output into `collective_state` the instant that node
|
||||
// completed (not after this whole cycle finished) — here we only
|
||||
// need the results to build the durable NodeReport record.
|
||||
for (node_id, output) in node_ids.iter().zip(results.iter()) {
|
||||
reports.push(NodeReport {
|
||||
node_id: node_id.clone(),
|
||||
cycle_index,
|
||||
output: output.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let consensus_result = synthesize_consensus(
|
||||
user_request, session_dir, workspaces, &collective_state, live.as_ref(), abort_flag, node_timeout_ms,
|
||||
);
|
||||
|
||||
// Guaranteed documentation: write the convergence doc for whatever
|
||||
// reports/consensus we actually have, whether synthesis succeeded or
|
||||
// failed. A synthesis-node failure must not silently discard every
|
||||
// completed cycle node's work — this is the durable audit trail
|
||||
// CLAUDE.md promises for every convergence.
|
||||
let doc_consensus = match &consensus_result {
|
||||
Ok(c) => c.clone(),
|
||||
Err(e) => format!(
|
||||
"Synthesis failed: {e}. See individual node reports above for partial results.",
|
||||
),
|
||||
};
|
||||
if let Some(workspace_root) = workspaces.first() {
|
||||
match crate::app::workflow::docs::write_hive_mind_convergence(workspace_root, user_request, &reports, &doc_consensus) {
|
||||
Ok(path) => tracing::info!("[hive-mind] convergence documented at {}", path.display()),
|
||||
Err(e) => tracing::warn!("[hive-mind] failed to write docs/runs report: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
let consensus = consensus_result?;
|
||||
Ok((consensus, reports))
|
||||
}
|
||||
|
||||
/// Spawn a single read-only synthesis node that reads the complete
|
||||
/// collective state and reconciles it into one consensus assessment.
|
||||
///
|
||||
/// Why a real node instead of string concatenation: the collective state
|
||||
/// may contain overlapping or conflicting node outputs (e.g. two nodes
|
||||
/// investigating the same file from different angles) — only genuine
|
||||
/// reasoning can reconcile that into a coherent answer; deterministic
|
||||
/// formatting can only concatenate, not resolve conflicts.
|
||||
///
|
||||
/// `node_timeout_ms` is forwarded from `run_hive_mind`'s `Settings::load()`
|
||||
/// read so the synthesis node is bound by the same deadline as cycle nodes.
|
||||
///
|
||||
/// Return: the synthesis node's reconciled consensus text.
|
||||
fn synthesize_consensus(
|
||||
user_request: &str,
|
||||
session_dir: &std::path::Path,
|
||||
workspaces: &[std::path::PathBuf],
|
||||
collective_state: &Arc<Mutex<Vec<String>>>,
|
||||
live: Option<&LiveStateFn>,
|
||||
abort_flag: Option<&Arc<AtomicBool>>,
|
||||
node_timeout_ms: Option<u64>,
|
||||
) -> anyhow::Result<String> {
|
||||
let synthesis = ScriptPrimitive::ScopedAgent {
|
||||
prompt: format!(
|
||||
"You are the synthesis process of a distributed machine intelligence. \
|
||||
All processing nodes for the following task have completed and \
|
||||
merged their output into the collective state below.\n\n\
|
||||
Task: {user_request}\n\n\
|
||||
Complete collective state:\n{{{{findings}}}}\n\n\
|
||||
Produce ONE reconciled consensus assessment. Do not list what each \
|
||||
node said — resolve any overlapping or conflicting node output into \
|
||||
a single coherent answer for the task above."
|
||||
),
|
||||
node_id: "Synthesis".to_string(),
|
||||
tool_scope: crate::app::subagent::division::tool_scope::READ.to_string(),
|
||||
};
|
||||
|
||||
let args: HashMap<String, String> = HashMap::new();
|
||||
let abort_owned: Option<Arc<AtomicBool>> = abort_flag.cloned();
|
||||
let results = execute_primitive(
|
||||
&synthesis, &args, 1, false, &abort_owned, live, session_dir, workspaces, collective_state, node_timeout_ms,
|
||||
)?;
|
||||
Ok(results.into_iter().next().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Determine whether a request is worth paying for a Core Intelligence
|
||||
/// planning call at all — the resulting plan's *shape* (cycle count,
|
||||
/// directives, access tiers) is entirely up to the Core Intelligence; this
|
||||
/// only gates whether it gets asked to design one in the first place.
|
||||
///
|
||||
/// Simple = single file, minor fix, quick lookup, config change.
|
||||
/// Complex = new feature, multi-file refactor, architecture change.
|
||||
///
|
||||
/// Heuristics:
|
||||
/// - Very short requests (< 10 chars) are never complex.
|
||||
/// - Negative keywords (simple/trivial/typo/quick) skip planning.
|
||||
/// - Positive keywords (refactor/api/implement/architecture) trigger it.
|
||||
/// - Multi-sentence requests are more likely complex.
|
||||
pub fn is_complex_request(request: &str) -> bool {
|
||||
let trimmed = request.trim();
|
||||
// Very short requests are never complex
|
||||
if trimmed.len() < 10 {
|
||||
return false;
|
||||
}
|
||||
// Single-line simple update patterns
|
||||
let lower = trimmed.to_lowercase();
|
||||
let negative_keywords = [
|
||||
"simple", "trivial", "typo", "just a", "only a", "minor",
|
||||
"quick", "tiny", "small fix", "rename", "nitpick",
|
||||
"cosmetic", "formatting", "spelling", "grammar",
|
||||
"bump", "version bump", "update comment",
|
||||
];
|
||||
if negative_keywords.iter().any(|k| lower.contains(k)) {
|
||||
return false;
|
||||
}
|
||||
// Multi-line/multi-sentence → likely complex
|
||||
let sentences = trimmed.split(['.', '!', '?'])
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.count();
|
||||
if sentences >= 3 {
|
||||
return true;
|
||||
}
|
||||
// Positive complexity keywords
|
||||
let complexity_keywords = [
|
||||
"refactor", "redesign", "architecture", "feature", "implement",
|
||||
"migrate", "restructure", "rewrite", "new module", "new component",
|
||||
"scaffold", "multi", "multiple files", "api", "endpoint",
|
||||
"integration", "system", "workflow", "pipeline", "database",
|
||||
"authentication", "authorization", "full stack",
|
||||
];
|
||||
complexity_keywords.iter().any(|k| lower.contains(k))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_too_short() {
|
||||
assert!(!is_complex_request("abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_simple_keywords() {
|
||||
assert!(!is_complex_request("just a simple update to the readme"));
|
||||
assert!(!is_complex_request("minor typo fix in main.rs"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_multi_sentence() {
|
||||
assert!(is_complex_request("This is sentence one. This is sentence two. This is sentence three."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_complex_request_complex_keywords() {
|
||||
assert!(is_complex_request("implement user authentication endpoint"));
|
||||
assert!(is_complex_request("refactor the whole engine module"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_access_is_read() {
|
||||
let d: NodeDirective = serde_json::from_str(
|
||||
r#"{"directive": "write tests"}"#
|
||||
).unwrap();
|
||||
assert_eq!(d.access, crate::app::subagent::division::tool_scope::READ);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_node_directive_has_no_role_field() {
|
||||
// A node's only recognized fields are "directive" and "access". A
|
||||
// "role" key, if an LLM emits one out of old habit, is simply
|
||||
// ignored rather than required or preserved.
|
||||
let d: NodeDirective = serde_json::from_str(
|
||||
r#"{"role": "Architect", "directive": "plan the migration", "access": "read"}"#
|
||||
).unwrap();
|
||||
assert_eq!(d.directive, "plan the migration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cognitive_cycle_plan_arbitrary_shape() {
|
||||
let plan: CognitiveCyclePlan = serde_json::from_str(r#"{
|
||||
"cycles": [
|
||||
[{"directive": "scan the codebase topology", "access": "read"}],
|
||||
[
|
||||
{"directive": "write the migration", "access": "write"},
|
||||
{"directive": "write the rollback", "access": "write"}
|
||||
],
|
||||
[{"directive": "cut the release", "access": "full"}]
|
||||
]
|
||||
}"#).unwrap();
|
||||
assert_eq!(plan.cycles.len(), 3);
|
||||
assert_eq!(plan.cycles[1].len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_hive_mind_rejects_empty_plan() {
|
||||
let plan = CognitiveCyclePlan { cycles: vec![] };
|
||||
let tmp = std::env::temp_dir();
|
||||
let err = run_hive_mind("do something", &plan, &tmp, &[], None, None)
|
||||
.expect_err("empty plan must be rejected before spawning any node");
|
||||
assert!(err.to_string().contains("no cycles"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_hive_mind_aborts_before_spawning_when_flag_preset() {
|
||||
// The abort check runs before execute_primitive for cycle 0, so a
|
||||
// pre-set abort flag must short-circuit without any LLM/network call.
|
||||
let plan: CognitiveCyclePlan = serde_json::from_str(r#"{
|
||||
"cycles": [[{"directive": "whatever", "access": "read"}]]
|
||||
}"#).unwrap();
|
||||
let tmp = std::env::temp_dir();
|
||||
let abort_flag = Arc::new(AtomicBool::new(true));
|
||||
let err = run_hive_mind("do something", &plan, &tmp, &[], None, Some(&abort_flag))
|
||||
.expect_err("pre-set abort flag must short-circuit before cycle 0");
|
||||
assert!(err.to_string().contains("aborted"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_node_ids_are_system_assigned_coordinates() {
|
||||
// Node IDs follow the "Node-{cycle}-{index}" coordinate scheme —
|
||||
// never an LLM-authored persona name.
|
||||
let node_id = format!("Node-{}-{}", 2, 1);
|
||||
assert_eq!(node_id, "Node-2-1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hive_mind_already_ran_detects_prior_consensus_tag() {
|
||||
let bodies = vec![
|
||||
"you are a helpful assistant".to_string(),
|
||||
format!("{HIVE_MIND_CONSENSUS_TAG}\nthe bug is a null check"),
|
||||
];
|
||||
assert!(hive_mind_already_ran(bodies.iter().map(std::string::String::as_str)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hive_mind_already_ran_false_when_no_prior_convergence() {
|
||||
let bodies = vec!["you are a helpful assistant".to_string()];
|
||||
assert!(!hive_mind_already_ran(bodies.iter().map(std::string::String::as_str)));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Workflow orchestration: a script interpreter that runs pipeline/parallel
|
||||
//! primitives across multiple subagent instances.
|
||||
|
||||
pub mod company;
|
||||
pub mod hive_mind;
|
||||
pub mod docs;
|
||||
pub mod engine;
|
||||
pub mod script;
|
||||
|
||||
@@ -9,6 +9,19 @@ use serde::{Deserialize, Serialize};
|
||||
pub enum ScriptPrimitive {
|
||||
/// Run a single agent with the given prompt template.
|
||||
Agent(String),
|
||||
/// Run a single agent with an explicit node designation and
|
||||
/// tool-scope tier.
|
||||
///
|
||||
/// Used by the hive-mind pipeline, where a node's identity is its
|
||||
/// system-assigned designation (e.g. `"Node-0-1"`) paired with a
|
||||
/// bounded tool allowlist. `tool_scope` is one of `"read"`,
|
||||
/// `"write"`, `"full"` (see `app::subagent::division::tool_scope`);
|
||||
/// unrecognized values fall back to `"read"`.
|
||||
ScopedAgent {
|
||||
prompt: String,
|
||||
node_id: String,
|
||||
tool_scope: String,
|
||||
},
|
||||
/// Execute several primitives concurrently.
|
||||
Parallel(Vec<ScriptPrimitive>),
|
||||
/// Execute several primitives sequentially, each waiting for the
|
||||
|
||||
@@ -22,6 +22,8 @@ pub enum Command {
|
||||
WorkflowRun {
|
||||
script: String,
|
||||
},
|
||||
TodoOpen,
|
||||
UsageOpen,
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
@@ -75,6 +77,23 @@ pub fn parse_command(text: &str) -> Command {
|
||||
"/workflow" => Command::WorkflowRun {
|
||||
script: arg1.to_string(),
|
||||
},
|
||||
"/todo" => Command::TodoOpen,
|
||||
"/usage" => Command::UsageOpen,
|
||||
_ => Command::Unknown(cmd.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_todo_open() {
|
||||
assert_eq!(parse_command("/todo"), Command::TodoOpen);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_usage_open() {
|
||||
assert_eq!(parse_command("/usage"), Command::UsageOpen);
|
||||
}
|
||||
}
|
||||
|
||||
+49
-1
@@ -19,7 +19,10 @@ pub enum InternetMode {
|
||||
Full,
|
||||
}
|
||||
|
||||
|
||||
/// Default per-node timeout for hive-mind nodes: 10 minutes.
|
||||
fn default_hive_mind_node_timeout_ms() -> u64 {
|
||||
600_000
|
||||
}
|
||||
|
||||
/// Top-level application settings, serialized to `settings.json` in the store dir.
|
||||
///
|
||||
@@ -42,6 +45,11 @@ pub struct Settings {
|
||||
pub session_archive_enabled: bool,
|
||||
pub lsp_auto_provision: bool,
|
||||
pub lsp_languages: Vec<String>,
|
||||
/// Wall-clock deadline for a single hive-mind processing node (cycle
|
||||
/// node or synthesis node). Prevents one stuck node from hanging an
|
||||
/// entire hive-mind convergence forever.
|
||||
#[serde(default = "default_hive_mind_node_timeout_ms")]
|
||||
pub hive_mind_node_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
@@ -62,6 +70,7 @@ impl Default for Settings {
|
||||
session_archive_enabled: true,
|
||||
lsp_auto_provision: true,
|
||||
lsp_languages: Vec::new(),
|
||||
hive_mind_node_timeout_ms: default_hive_mind_node_timeout_ms(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,3 +112,42 @@ impl Settings {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn default_hive_mind_node_timeout_is_ten_minutes() {
|
||||
let settings = Settings::default();
|
||||
assert_eq!(settings.hive_mind_node_timeout_ms, 600_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_hive_mind_node_timeout_field_falls_back_to_default() {
|
||||
// Simulates loading a settings.json written before this field
|
||||
// existed — #[serde(default = ...)] must fill it in rather than
|
||||
// failing the whole parse (which would silently reset every
|
||||
// other saved setting to default too).
|
||||
let old_json = r#"{
|
||||
"internet_mode": "Off",
|
||||
"provider": "zen",
|
||||
"model": "deepseek-v4-flash-free",
|
||||
"api_keys": {},
|
||||
"max_tokens": null,
|
||||
"temperature": null,
|
||||
"review_enabled": true,
|
||||
"review_max_lessons_per_run": 5,
|
||||
"adaptive_review_max_skip": 3,
|
||||
"verify_command": null,
|
||||
"verify_timeout_ms": 30000,
|
||||
"workflow_max_concurrency": 5,
|
||||
"session_archive_enabled": true,
|
||||
"lsp_auto_provision": true,
|
||||
"lsp_languages": []
|
||||
}"#;
|
||||
let parsed: Settings = serde_json::from_str(old_json)
|
||||
.expect("must parse even without the new field present");
|
||||
assert_eq!(parsed.hive_mind_node_timeout_ms, 600_000);
|
||||
}
|
||||
}
|
||||
|
||||
+2
-6
@@ -11,12 +11,6 @@ pub const TEST_GENERATOR_PROMPT: &str = include_str!("../src-misc/test-generator
|
||||
pub const ARCH_REVIEWER_PROMPT: &str = include_str!("../src-misc/arch-reviewer-prompt.txt");
|
||||
pub const SECURITY_REVIEWER_PROMPT: &str = include_str!("../src-misc/security-reviewer-prompt.txt");
|
||||
|
||||
/// Division-specific prompts for the company-style agent architecture.
|
||||
pub const DIVISION_PLANNER_PROMPT: &str = include_str!("../src-misc/division-planner-prompt.txt");
|
||||
pub const DIVISION_IMPLEMENTER_PROMPT: &str = include_str!("../src-misc/division-implementer-prompt.txt");
|
||||
pub const DIVISION_TESTER_PROMPT: &str = include_str!("../src-misc/division-tester-prompt.txt");
|
||||
pub const DIVISION_DOCUMENTER_PROMPT: &str = include_str!("../src-misc/division-documenter-prompt.txt");
|
||||
|
||||
pub const HELP_TEXT: &str = "
|
||||
ZESDEX - Help
|
||||
=============
|
||||
@@ -42,6 +36,8 @@ Input:
|
||||
/workflow Open workflow panel
|
||||
/workflow run <p> Run a workflow with prompt <p>
|
||||
/mode workflow Open workflow panel
|
||||
/todo Open task list
|
||||
/usage Open usage details
|
||||
/compact Compact conversation history
|
||||
/exit Exit application
|
||||
|
||||
|
||||
+21
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use serde_json::Value;
|
||||
use anyhow::Result;
|
||||
|
||||
@@ -56,6 +57,11 @@ pub struct ToolCtx {
|
||||
/// reference earlier results. `None` means "not inside a workflow" —
|
||||
/// `note_finding` becomes a no-op.
|
||||
pub workflow_findings: Option<Arc<Mutex<Vec<String>>>>,
|
||||
/// The current turn's abort flag, threaded through so tools that
|
||||
/// delegate to long-running orchestration (e.g. the `hive_mind` tool)
|
||||
/// can be cancelled the same way the main agent loop is. `None` when
|
||||
/// no turn-level abort flag is available.
|
||||
pub abort_flag: Option<Arc<AtomicBool>>,
|
||||
}
|
||||
|
||||
/// Find which graduated checks apply to a given file path/content pair.
|
||||
@@ -93,6 +99,7 @@ pub struct ToolCtxBuilder {
|
||||
pub lsp_manager: Arc<Mutex<crate::app::lsp::LspManager>>,
|
||||
pub turn_events: Option<Arc<Mutex<std::collections::VecDeque<crate::app::state::runtime::TurnEvent>>>>,
|
||||
pub workflow_findings: Option<Arc<Mutex<Vec<String>>>>,
|
||||
pub abort_flag: Option<Arc<AtomicBool>>,
|
||||
}
|
||||
|
||||
impl Default for ToolCtxBuilder {
|
||||
@@ -108,6 +115,7 @@ impl Default for ToolCtxBuilder {
|
||||
lsp_manager: Arc::new(Mutex::new(crate::app::lsp::LspManager::new())),
|
||||
turn_events: None,
|
||||
workflow_findings: None,
|
||||
abort_flag: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -135,6 +143,7 @@ impl ToolCtxBuilder {
|
||||
lsp_manager: self.lsp_manager,
|
||||
turn_events: self.turn_events,
|
||||
workflow_findings: self.workflow_findings,
|
||||
abort_flag: self.abort_flag,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,7 +172,7 @@ pub fn all_tools() -> Vec<Box<dyn Tool>> {
|
||||
Box::new(super::tool::workflow::WorkflowRun),
|
||||
Box::new(super::tool::workflow::NoteFinding),
|
||||
Box::new(super::tool::workflow::ReadFindings),
|
||||
Box::new(super::tool::workflow::CompanyPipeline),
|
||||
Box::new(super::tool::workflow::HiveMind),
|
||||
Box::new(super::tool::spawn::SpawnAgents),
|
||||
Box::new(super::tool::spawn::SpawnPipeline),
|
||||
Box::new(super::tool::memory::remember::Remember),
|
||||
@@ -264,3 +273,14 @@ pub fn resolve_path(workspaces: &[PathBuf], rel: &str) -> Result<PathBuf> {
|
||||
anyhow::bail!("path '{rel}' is outside all workspace roots")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tool_ctx_builder_defaults_abort_flag_to_none() {
|
||||
let ctx = ToolCtx::builder().build();
|
||||
assert!(ctx.abort_flag.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
+63
-70
@@ -139,23 +139,36 @@ impl Tool for NoteFinding {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool that delegates work to the company-style division pipeline.
|
||||
/// Tool that delegates work to a hive-mind: a distributed machine
|
||||
/// intelligence whose processing nodes carry only a directive and an
|
||||
/// access tier.
|
||||
///
|
||||
/// The main agent (CEO) calls this tool to pass a user request through the
|
||||
/// full company organization: Strategy → Engineering → Quality → Security
|
||||
/// → Documentation. Returns an executive summary.
|
||||
///
|
||||
/// Use this for any complex or multi-step task. For simple tasks, handle
|
||||
/// inline or use the quick variant.
|
||||
pub struct CompanyPipeline;
|
||||
/// The calling agent (the Core Intelligence) designs its own cognitive
|
||||
/// cycles per task: an ordered list of cycles, each cycle a set of
|
||||
/// anonymous processing nodes that run in parallel. Every node's complete
|
||||
/// output merges into a single collective state the instant it finishes,
|
||||
/// and a final synthesis node reconciles the whole collective state into
|
||||
/// one consensus. The full per-node record is persisted separately to
|
||||
/// `docs/runs/*.md`.
|
||||
pub struct HiveMind;
|
||||
|
||||
impl Tool for CompanyPipeline {
|
||||
impl Tool for HiveMind {
|
||||
fn name(&self) -> &'static str {
|
||||
"company_pipeline"
|
||||
"hive_mind"
|
||||
}
|
||||
|
||||
fn description(&self) -> &'static str {
|
||||
"Delegate a task to the full company division pipeline: Strategy (plan+diagrams) → Engineering (implement) → Quality (review+test) → Security (audit) → Documentation (docs). Use this for ALL non-trivial tasks instead of doing them yourself. The pipeline returns an executive summary."
|
||||
"Delegate a task to a hive-mind you design yourself: an ordered list of cognitive \
|
||||
cycles, each cycle a set of anonymous processing nodes that run in parallel. Each \
|
||||
node carries only a directive (what to do) and an access tier. Decide how many \
|
||||
cycles and nodes-per-cycle are actually needed — a trivial task might need one \
|
||||
cycle with one node, a large one might need several cycles with multiple nodes \
|
||||
each. Grant each node an access of 'read' (investigation only), 'write' (read + \
|
||||
edit/bash), or 'full' (write + delete/git) matched to what that node's directive \
|
||||
actually requires. Every node's output merges into a shared collective state the \
|
||||
instant it completes — visible to later cycles automatically. A final synthesis pass \
|
||||
reconciles the entire collective state into one consensus answer. Use this for any \
|
||||
non-trivial task instead of doing everything yourself inline."
|
||||
}
|
||||
|
||||
fn parameters(&self) -> Value {
|
||||
@@ -164,29 +177,33 @@ impl Tool for CompanyPipeline {
|
||||
"properties": {
|
||||
"request": {
|
||||
"type": "string",
|
||||
"description": "The task description to delegate to the company pipeline"
|
||||
"description": "The task description to delegate to the hive-mind"
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": ["full", "quick"],
|
||||
"description": "Pipeline mode: 'full' (5 divisions) for complex tasks, 'quick' (3 divisions: Strategy→Engineering→Quality) for simpler tasks",
|
||||
"default": "full"
|
||||
},
|
||||
"specialists": {
|
||||
"type": "object",
|
||||
"description": "Mapping from division name (Strategy, Engineering, Quality, Security, Documentation) to list of custom specialists. Each specialist is defined by a pair of [label, focus_description]. This parameter is mandatory. The CEO/main agent must fully define the specialized roles and focuses for every division in the pipeline to run.",
|
||||
"additionalProperties": {
|
||||
"cycles": {
|
||||
"type": "array",
|
||||
"description": "Ordered list of cognitive cycles. Each cycle is a list of nodes that run in parallel; cycles run sequentially and every node's output merges into the collective state the instant it completes, visible to all later cycles. You decide the number of cycles and nodes per cycle.",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" },
|
||||
"minItems": 2,
|
||||
"maxItems": 2
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"directive": {
|
||||
"type": "string",
|
||||
"description": "What this node should do — the sole identity a node carries."
|
||||
},
|
||||
"access": {
|
||||
"type": "string",
|
||||
"enum": ["read", "write", "full"],
|
||||
"description": "'read' = investigation only. 'write' = read + edit/write/bash. 'full' = write + delete/git_operator."
|
||||
}
|
||||
},
|
||||
"required": ["directive"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"minItems": 1
|
||||
}
|
||||
},
|
||||
"required": ["request", "specialists"]
|
||||
"required": ["request", "cycles"]
|
||||
})
|
||||
}
|
||||
|
||||
@@ -195,50 +212,26 @@ impl Tool for CompanyPipeline {
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| anyhow!("missing required argument: request"))?;
|
||||
|
||||
let mode = args.get("mode")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("full");
|
||||
let cycles_value = args.get("cycles")
|
||||
.ok_or_else(|| anyhow!("missing required argument: cycles"))?;
|
||||
|
||||
let custom_specialists: std::collections::HashMap<String, Vec<(String, String)>> = args.get("specialists")
|
||||
.and_then(|v| v.as_object())
|
||||
.map(|obj| {
|
||||
obj.iter().map(|(k, v)| {
|
||||
let specs = v.as_array().map(|arr| {
|
||||
arr.iter().filter_map(|item| {
|
||||
let pair = item.as_array()?;
|
||||
let label = pair.first()?.as_str()?.to_string();
|
||||
let focus = pair.get(1)?.as_str()?.to_string();
|
||||
Some((label, focus))
|
||||
}).collect()
|
||||
}).unwrap_or_default();
|
||||
(k.clone(), specs)
|
||||
}).collect()
|
||||
})
|
||||
.ok_or_else(|| anyhow!("missing required argument: specialists"))?;
|
||||
let plan: crate::app::workflow::hive_mind::CognitiveCyclePlan = serde_json::from_value(
|
||||
json!({ "cycles": cycles_value })
|
||||
).map_err(|e| anyhow!("failed to parse cycles: {e}"))?;
|
||||
|
||||
let no_abort: Option<std::sync::Arc<std::sync::atomic::AtomicBool>> = None;
|
||||
match mode {
|
||||
"quick" => {
|
||||
crate::app::workflow::company::run_company_pipeline_quick(
|
||||
request,
|
||||
&ctx.session_dir,
|
||||
&ctx.workspaces,
|
||||
ctx.turn_events.as_ref(),
|
||||
&no_abort,
|
||||
&custom_specialists,
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
crate::app::workflow::company::run_company_pipeline(
|
||||
request,
|
||||
&ctx.session_dir,
|
||||
&ctx.workspaces,
|
||||
ctx.turn_events.as_ref(),
|
||||
&no_abort,
|
||||
&custom_specialists,
|
||||
)
|
||||
}
|
||||
}
|
||||
// run_hive_mind now writes the docs/runs/*.md convergence report
|
||||
// itself (guaranteed, even if synthesis fails) — do not write it
|
||||
// again here.
|
||||
let (consensus, _reports) = crate::app::workflow::hive_mind::run_hive_mind(
|
||||
request,
|
||||
&plan,
|
||||
&ctx.session_dir,
|
||||
&ctx.workspaces,
|
||||
ctx.turn_events.as_ref(),
|
||||
ctx.abort_flag.as_ref(),
|
||||
)?;
|
||||
|
||||
Ok(consensus)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+151
-105
@@ -1,23 +1,32 @@
|
||||
#![allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::cast_precision_loss, clippy::cast_possible_wrap)]
|
||||
//! Chat transcript panel rendering — message cards with role badges.
|
||||
//! Chat transcript panel rendering — tight inline log style.
|
||||
//!
|
||||
//! Flow: `draw_chat` turns `state.transcript_cache.messages` into a
|
||||
//! visually rich transcript where each message is rendered as a "card"
|
||||
//! with a role-colored left accent bar, a role badge pill, timestamp,
|
||||
//! and markdown body. A streaming spinner line is appended when a turn
|
||||
//! Flow: `draw_chat` turns `state.transcript_cache.messages` into a dense,
|
||||
//! log-like transcript: each non-tool message gets a one-line
|
||||
//! `{role} {time} {content}` header with wrapped continuation lines
|
||||
//! aligned under the content column; `Role::Tool` messages render as a
|
||||
//! dim `↳`-prefixed sub-line attached to whatever came before, with no
|
||||
//! header of their own. A streaming spinner line is appended when a turn
|
||||
//! is in flight. The combined line list is sliced to the visible scroll
|
||||
//! window before rendering.
|
||||
//!
|
||||
//! Design: messages are visually separated with vertical spacing, role
|
||||
//! badges are colored pills on the left, and each message has a thin
|
||||
//! role-colored border on its left side for quick visual scanning.
|
||||
//! Design: no per-message card/border/badge — role identity comes from a
|
||||
//! short colored label, and vertical space is reserved for a blank line
|
||||
//! only when the speaker actually changes (Tool sub-lines never count as
|
||||
//! a speaker change), keeping more history on screen at once.
|
||||
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::{Style, Modifier};
|
||||
use ratatui::style::{Color, Style, Modifier};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
use super::theme::Theme;
|
||||
use crate::dto::chat::message::Role;
|
||||
|
||||
/// Column width reserved for the `{role} {time} ` header prefix; wrapped
|
||||
/// continuation lines and Tool sub-lines indent to this width so content
|
||||
/// stays aligned under the first line's content column.
|
||||
const PREFIX_WIDTH: usize = 12;
|
||||
|
||||
/// Break a flat run of styled spans into `Line`s at embedded `\n` boundaries.
|
||||
fn split_spans_into_lines(spans: Vec<Span<'_>>) -> Vec<Line<'_>> {
|
||||
@@ -45,30 +54,24 @@ fn split_spans_into_lines(spans: Vec<Span<'_>>) -> Vec<Line<'_>> {
|
||||
lines
|
||||
}
|
||||
|
||||
fn role_badge(role: &crate::dto::chat::message::Role) -> &'static str {
|
||||
fn role_accent_color(role: &Role) -> Color {
|
||||
match role {
|
||||
crate::dto::chat::message::Role::User => " YOU ",
|
||||
crate::dto::chat::message::Role::Assistant => " AI ",
|
||||
crate::dto::chat::message::Role::System => " SYS ",
|
||||
crate::dto::chat::message::Role::Tool => " TOOL ",
|
||||
Role::User => Theme::ROLE_USER,
|
||||
Role::Assistant => Theme::ROLE_ASSISTANT,
|
||||
Role::System => Theme::ROLE_SYSTEM,
|
||||
Role::Tool => Theme::ROLE_TOOL,
|
||||
}
|
||||
}
|
||||
|
||||
fn role_accent_color(role: &crate::dto::chat::message::Role) -> Color {
|
||||
/// Short lowercase label for the `{role} {time}` header column. Callers pad
|
||||
/// it to a fixed width themselves (not padded here so tests can assert the
|
||||
/// raw label).
|
||||
fn format_role_label(role: &Role) -> &'static str {
|
||||
match role {
|
||||
crate::dto::chat::message::Role::User => Theme::ROLE_USER,
|
||||
crate::dto::chat::message::Role::Assistant => Theme::ROLE_ASSISTANT,
|
||||
crate::dto::chat::message::Role::System => Theme::ROLE_SYSTEM,
|
||||
crate::dto::chat::message::Role::Tool => Theme::ROLE_TOOL,
|
||||
}
|
||||
}
|
||||
|
||||
fn role_label(role: &crate::dto::chat::message::Role) -> &'static str {
|
||||
match role {
|
||||
crate::dto::chat::message::Role::User => "You",
|
||||
crate::dto::chat::message::Role::Assistant => "Assistant",
|
||||
crate::dto::chat::message::Role::System => "System",
|
||||
crate::dto::chat::message::Role::Tool => "Tool Call",
|
||||
Role::User => "you",
|
||||
Role::Assistant => "ai",
|
||||
Role::System => "sys",
|
||||
Role::Tool => "tool",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,60 +83,90 @@ fn format_timestamp(ts: i64) -> String {
|
||||
format!("{hrs:02}:{mins:02}")
|
||||
}
|
||||
|
||||
/// Render the scrollable chat transcript panel with message card styling.
|
||||
/// Whether a blank separator line should be inserted before rendering a
|
||||
/// message from `role`, given the last non-Tool role that was rendered.
|
||||
///
|
||||
/// Why: `Role::Tool` messages render as an attached sub-line (see
|
||||
/// `draw_chat`) and must never be passed as `prev_role` — a Tool message
|
||||
/// never triggers a separator, and it never causes one to be inserted
|
||||
/// before the next real turn either.
|
||||
fn needs_speaker_separator(prev_role: Option<&Role>, role: &Role) -> bool {
|
||||
matches!(prev_role, Some(p) if p != role)
|
||||
}
|
||||
|
||||
/// Render the scrollable chat transcript panel in tight inline-log style.
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
let messages = &state.transcript_cache.messages;
|
||||
let scroll_offset = state.scroll.offset;
|
||||
let max_visible = (area.height as usize).saturating_sub(3);
|
||||
// Wrap width for content: total width minus the header/indent prefix
|
||||
// and minus the panel's left+right border columns.
|
||||
let content_width = area.width.saturating_sub(PREFIX_WIDTH as u16 + 2);
|
||||
|
||||
let mut display_lines: Vec<Line> = Vec::new();
|
||||
let mut prev_role: Option<Role> = None;
|
||||
|
||||
// ── Header ───────────────────────────────────────────────────────────
|
||||
let title = if messages.is_empty() {
|
||||
String::from(" Chat ")
|
||||
} else {
|
||||
format!(" Chat [{} msgs]", messages.len())
|
||||
};
|
||||
|
||||
// ── Render messages as cards ─────────────────────────────────────────
|
||||
for msg in messages {
|
||||
let accent = role_accent_color(&msg.role);
|
||||
let badge = role_badge(&msg.role);
|
||||
let label = role_label(&msg.role);
|
||||
let ts_str = format_timestamp(msg.timestamp);
|
||||
|
||||
// ── Role header line ─────────────────────────────────────────────
|
||||
// Left accent bar + badge pill + role name + timestamp
|
||||
let header = Line::from(vec![
|
||||
// Thin accent bar on the left
|
||||
Span::styled(
|
||||
"▎",
|
||||
Style::default().fg(accent),
|
||||
),
|
||||
// Role badge pill
|
||||
Span::styled(
|
||||
badge,
|
||||
Style::default()
|
||||
.fg(Theme::BG)
|
||||
.bg(accent)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
// Role name
|
||||
Span::styled(
|
||||
format!(" {label}"),
|
||||
Style::default().fg(accent).add_modifier(Modifier::BOLD),
|
||||
),
|
||||
// Timestamp
|
||||
Span::styled(
|
||||
if ts_str.is_empty() { String::new() } else { format!(" {ts_str}") },
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
),
|
||||
]);
|
||||
display_lines.push(header);
|
||||
|
||||
// ── Message content ──────────────────────────────────────────────
|
||||
let is_last = std::ptr::eq(msg, messages.last().unwrap());
|
||||
|
||||
// Tool messages render as a dim sub-line attached to whatever came
|
||||
// before — no header, no speaker-change bookkeeping. Content is run
|
||||
// through the same render_markdown + split_spans_into_lines pipeline
|
||||
// as every other role so multi-line tool output (bash stdout, grep
|
||||
// matches, diffs) becomes real wrapped `Line`s instead of a literal
|
||||
// `\n` inside one Span; every rendered span is then re-styled dim
|
||||
// italic to preserve the original single-line look.
|
||||
if msg.role == Role::Tool {
|
||||
let content = if msg.content.trim().is_empty() {
|
||||
"(tool execution)".to_string()
|
||||
} else {
|
||||
msg.content.clone()
|
||||
};
|
||||
let dim = Style::default().fg(Theme::TEXT_DIM);
|
||||
let dim_italic = dim.add_modifier(Modifier::ITALIC);
|
||||
|
||||
let content_spans = super::markdown::render_markdown(&content, content_width);
|
||||
let content_lines = split_spans_into_lines(content_spans);
|
||||
let mut lines_iter = content_lines.into_iter();
|
||||
|
||||
let first_spans = lines_iter.next().map_or_else(Vec::new, |line| {
|
||||
line.spans.into_iter().map(|s| Span::styled(s.content, dim_italic)).collect()
|
||||
});
|
||||
let mut spans = vec![
|
||||
Span::raw(" ".repeat(PREFIX_WIDTH)),
|
||||
Span::styled("↳ ", dim),
|
||||
];
|
||||
spans.extend(first_spans);
|
||||
display_lines.push(Line::from(spans));
|
||||
|
||||
for line in lines_iter {
|
||||
let mut spans = vec![Span::raw(" ".repeat(PREFIX_WIDTH))];
|
||||
spans.extend(line.spans.into_iter().map(|s| Span::styled(s.content, dim_italic)));
|
||||
display_lines.push(Line::from(spans));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if needs_speaker_separator(prev_role.as_ref(), &msg.role) {
|
||||
display_lines.push(Line::from(Span::raw("")));
|
||||
}
|
||||
prev_role = Some(msg.role.clone());
|
||||
|
||||
let accent = role_accent_color(&msg.role);
|
||||
let label = format_role_label(&msg.role);
|
||||
let ts_str = format_timestamp(msg.timestamp);
|
||||
let header_prefix = vec![
|
||||
Span::styled(format!("{label:<4} "), Style::default().fg(accent).add_modifier(Modifier::BOLD)),
|
||||
Span::styled(format!("{ts_str:<5} "), Style::default().fg(Theme::TEXT_DIM)),
|
||||
];
|
||||
|
||||
let content_str = if msg.content.trim().is_empty() {
|
||||
if is_last && state.turn_in_flight() {
|
||||
"(streaming...)".to_string()
|
||||
@@ -144,19 +177,23 @@ pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest:
|
||||
msg.content.clone()
|
||||
};
|
||||
|
||||
// Render markdown content with accent-colored prefix
|
||||
let mut content_spans = vec![
|
||||
Span::styled(" ", Style::default().fg(accent)),
|
||||
];
|
||||
content_spans.extend(super::markdown::render_markdown(&content_str, area.width));
|
||||
let message_lines = split_spans_into_lines(content_spans);
|
||||
let content_spans = super::markdown::render_markdown(&content_str, content_width);
|
||||
let content_lines = split_spans_into_lines(content_spans);
|
||||
let mut lines_iter = content_lines.into_iter();
|
||||
|
||||
for line in message_lines {
|
||||
display_lines.push(line);
|
||||
if let Some(first) = lines_iter.next() {
|
||||
let mut spans = header_prefix;
|
||||
spans.extend(first.spans);
|
||||
display_lines.push(Line::from(spans));
|
||||
} else {
|
||||
display_lines.push(Line::from(header_prefix));
|
||||
}
|
||||
|
||||
// ── Message separator ────────────────────────────────────────────
|
||||
display_lines.push(Line::from(Span::raw("")));
|
||||
for line in lines_iter {
|
||||
let mut spans = vec![Span::raw(" ".repeat(PREFIX_WIDTH))];
|
||||
spans.extend(line.spans);
|
||||
display_lines.push(Line::from(spans));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Streaming indicator ──────────────────────────────────────────────
|
||||
@@ -165,38 +202,24 @@ pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest:
|
||||
let frame_idx = (state.misc.tick_count as usize / 2) % spinner_frames.len();
|
||||
let spinner = spinner_frames[frame_idx];
|
||||
|
||||
if needs_speaker_separator(prev_role.as_ref(), &Role::Assistant) {
|
||||
display_lines.push(Line::from(Span::raw("")));
|
||||
}
|
||||
display_lines.push(Line::from(vec![
|
||||
Span::styled(
|
||||
"▎",
|
||||
Style::default().fg(Theme::ROLE_ASSISTANT),
|
||||
),
|
||||
Span::styled(
|
||||
" AI ",
|
||||
Style::default()
|
||||
.fg(Theme::BG)
|
||||
.bg(Theme::ROLE_ASSISTANT)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
format!(" {spinner} "),
|
||||
format!("{:<4} ", format_role_label(&Role::Assistant)),
|
||||
Style::default().fg(Theme::ROLE_ASSISTANT).add_modifier(Modifier::BOLD),
|
||||
),
|
||||
Span::styled(
|
||||
"Generating...",
|
||||
Style::default().fg(Theme::TEXT_MUTED).add_modifier(Modifier::ITALIC),
|
||||
),
|
||||
Span::styled(format!("{spinner} "), Style::default().fg(Theme::TEXT_DIM)),
|
||||
Span::styled("generating...", Style::default().fg(Theme::TEXT_MUTED).add_modifier(Modifier::ITALIC)),
|
||||
]));
|
||||
display_lines.push(Line::from(Span::raw("")));
|
||||
}
|
||||
|
||||
// ── Scrolling ────────────────────────────────────────────────────────
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER))
|
||||
.title(Span::styled(
|
||||
title,
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
));
|
||||
.title(Span::styled(title, Style::default().fg(Theme::TEXT_MUTED)));
|
||||
|
||||
let total = display_lines.len();
|
||||
let max_offset = total.saturating_sub(max_visible);
|
||||
@@ -210,8 +233,6 @@ pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest:
|
||||
display_lines[total.saturating_sub(max_visible)..total].to_vec()
|
||||
};
|
||||
|
||||
// ── Scroll position indicator ────────────────────────────────────────
|
||||
// Show a small percentage indicator in the title if scrolled
|
||||
let scroll_pct = if total > max_visible {
|
||||
((offset as f64 / max_offset as f64) * 100.0) as u8
|
||||
} else {
|
||||
@@ -223,10 +244,7 @@ pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest:
|
||||
Block::default()
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER))
|
||||
.title(Span::styled(
|
||||
scroll_title,
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
))
|
||||
.title(Span::styled(scroll_title, Style::default().fg(Theme::TEXT_MUTED)))
|
||||
} else {
|
||||
block
|
||||
};
|
||||
@@ -239,5 +257,33 @@ pub fn draw_chat(frame: &mut Frame, area: Rect, state: &crate::app::state::rest:
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
// Need to import Color for role_accent_color
|
||||
use ratatui::style::Color;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_separator_when_no_previous_message() {
|
||||
assert!(!needs_speaker_separator(None, &Role::User));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_separator_when_same_speaker_repeats() {
|
||||
assert!(!needs_speaker_separator(Some(&Role::Assistant), &Role::Assistant));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separator_when_speaker_changes() {
|
||||
assert!(needs_speaker_separator(Some(&Role::User), &Role::Assistant));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_labels_are_lowercase_and_fit_prefix_width() {
|
||||
assert_eq!(format_role_label(&Role::User), "you");
|
||||
assert_eq!(format_role_label(&Role::Assistant), "ai");
|
||||
assert_eq!(format_role_label(&Role::System), "sys");
|
||||
assert_eq!(format_role_label(&Role::Tool), "tool");
|
||||
for role in [Role::User, Role::Assistant, Role::System, Role::Tool] {
|
||||
assert!(format_role_label(&role).len() <= 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-13
@@ -7,6 +7,13 @@
|
||||
//! Design: code blocks get a dark background with a labeled top bar,
|
||||
//! headings are bold with distinct colors, blockquotes get a vertical
|
||||
//! accent bar prefix, and inline code is highlighted with a background.
|
||||
//! Deliberately adds no leading indentation of its own for paragraphs,
|
||||
//! headings, or list bullets — the caller (`chat.rs`) owns column
|
||||
//! alignment via its `PREFIX_WIDTH` scheme, so any indent added here
|
||||
//! would only apply to a construct's first rendered line and throw
|
||||
//! wrapped continuation lines out of alignment with it. Code-block lines
|
||||
//! are the exception: every line gets its `" "` prefix independently
|
||||
//! and consistently, so there's no first-line-only misalignment there.
|
||||
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::Span;
|
||||
@@ -27,7 +34,6 @@ pub fn render_markdown(text: &str, width: u16) -> Vec<Span<'static>> {
|
||||
let mut in_code_block = false;
|
||||
let mut in_heading = false;
|
||||
let mut heading_level = 0;
|
||||
let mut first_in_paragraph = true;
|
||||
|
||||
for event in parser {
|
||||
match event {
|
||||
@@ -59,13 +65,10 @@ pub fn render_markdown(text: &str, width: u16) -> Vec<Span<'static>> {
|
||||
};
|
||||
// No prefix, we'll handle in the text events
|
||||
}
|
||||
pulldown_cmark::Tag::Paragraph => {
|
||||
first_in_paragraph = true;
|
||||
}
|
||||
pulldown_cmark::Tag::Item => {
|
||||
// List item bullet
|
||||
spans.push(Span::styled(
|
||||
" • ",
|
||||
"• ",
|
||||
Style::default().fg(Theme::PRIMARY),
|
||||
));
|
||||
}
|
||||
@@ -106,7 +109,6 @@ pub fn render_markdown(text: &str, width: u16) -> Vec<Span<'static>> {
|
||||
spans.push(Span::raw("\n"));
|
||||
}
|
||||
pulldown_cmark::TagEnd::Paragraph => {
|
||||
first_in_paragraph = true;
|
||||
spans.push(Span::raw("\n\n"));
|
||||
}
|
||||
pulldown_cmark::TagEnd::Item | pulldown_cmark::TagEnd::BlockQuote(_) => {
|
||||
@@ -129,17 +131,11 @@ pub fn render_markdown(text: &str, width: u16) -> Vec<Span<'static>> {
|
||||
3 => Theme::ACCENT_PURPLE,
|
||||
_ => Theme::TEXT,
|
||||
};
|
||||
let prefix = " ";
|
||||
spans.push(Span::styled(
|
||||
format!("{prefix}{s}"),
|
||||
s,
|
||||
Style::default().fg(color).add_modifier(Modifier::BOLD),
|
||||
));
|
||||
} else {
|
||||
// Handle first word detection for paragraph indentation
|
||||
if first_in_paragraph {
|
||||
spans.push(Span::raw(" "));
|
||||
first_in_paragraph = false;
|
||||
}
|
||||
spans.push(Span::raw(s));
|
||||
}
|
||||
}
|
||||
|
||||
+151
-138
@@ -9,6 +9,7 @@
|
||||
|
||||
pub mod chat;
|
||||
pub mod markdown;
|
||||
pub mod sidebar;
|
||||
pub mod status;
|
||||
pub mod theme;
|
||||
pub mod workflow;
|
||||
@@ -20,14 +21,21 @@ use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
use theme::Theme;
|
||||
|
||||
/// Minimum terminal width (columns) at which the persistent dashboard
|
||||
/// sidebar is shown; below this, chat reclaims the full width.
|
||||
const SIDEBAR_MIN_WIDTH: u16 = 90;
|
||||
|
||||
/// Top-level render entry point called once per TUI frame.
|
||||
pub fn draw(frame: &mut Frame, state: &crate::app::state::rest::AppStateRest) {
|
||||
let area = frame.area();
|
||||
|
||||
// ── Determine if we need a side panel (todo) ─────────────────────────
|
||||
let show_todo = !state.misc.todo_content.is_empty()
|
||||
|| state.misc.overlay == crate::app::state::types::Overlay::Todo;
|
||||
let (main_area, todo_area) = if show_todo && area.width > 60 {
|
||||
// ── Determine if the terminal is wide enough for the persistent
|
||||
// dashboard sidebar (Workflow / Tasks / Usage). Below this, chat
|
||||
// reclaims the full width — same width-driven-collapse pattern the
|
||||
// old single-widget todo panel used, just with a wider threshold
|
||||
// since this sidebar holds three stacked widgets, not one.
|
||||
let show_sidebar = area.width > SIDEBAR_MIN_WIDTH;
|
||||
let (main_area, sidebar_area) = if show_sidebar {
|
||||
let h_chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
@@ -55,9 +63,7 @@ pub fn draw(frame: &mut Frame, state: &crate::app::state::rest::AppStateRest) {
|
||||
let status_area = chunks[2];
|
||||
|
||||
// ── Render main area (overlay or chat) ───────────────────────────────
|
||||
if state.misc.overlay.is_active()
|
||||
&& state.misc.overlay != crate::app::state::types::Overlay::Todo
|
||||
{
|
||||
if state.misc.overlay.is_active() {
|
||||
let overlay = state.misc.overlay;
|
||||
render_overlay(frame, chat_area, overlay, state);
|
||||
} else {
|
||||
@@ -70,9 +76,9 @@ pub fn draw(frame: &mut Frame, state: &crate::app::state::rest::AppStateRest) {
|
||||
// ── Status bar ───────────────────────────────────────────────────────
|
||||
status::draw_status_bar(frame, status_area, state);
|
||||
|
||||
// ── Todo side panel ──────────────────────────────────────────────────
|
||||
if let Some(todo_rect) = todo_area {
|
||||
render_todo_panel(frame, todo_rect, state);
|
||||
// ── Dashboard sidebar ────────────────────────────────────────────────
|
||||
if let Some(sidebar_rect) = sidebar_area {
|
||||
sidebar::draw_sidebar(frame, sidebar_rect, state);
|
||||
}
|
||||
|
||||
// ── Toasts (top-right floating) ──────────────────────────────────────
|
||||
@@ -83,30 +89,6 @@ pub fn draw(frame: &mut Frame, state: &crate::app::state::rest::AppStateRest) {
|
||||
// Panel helpers
|
||||
// ────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn render_todo_panel(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
state: &crate::app::state::rest::AppStateRest,
|
||||
) {
|
||||
let block = Block::default()
|
||||
.title(" 📋 Tasks ")
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::ACCENT_PURPLE))
|
||||
.style(Style::default().bg(Theme::BG));
|
||||
|
||||
let content = if state.misc.todo_content.is_empty() {
|
||||
" No tasks yet."
|
||||
} else {
|
||||
&state.misc.todo_content
|
||||
};
|
||||
|
||||
let paragraph = Paragraph::new(content)
|
||||
.block(block)
|
||||
.wrap(Wrap { trim: false });
|
||||
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
fn render_main_panel(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
@@ -148,7 +130,7 @@ fn render_overlay(
|
||||
// ── Help ──────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Help => {
|
||||
let block = block
|
||||
.title(Span::styled(" ❓ Help ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Help ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::INFO));
|
||||
let content = crate::resources::HELP_TEXT;
|
||||
let paragraph = Paragraph::new(content)
|
||||
@@ -161,7 +143,7 @@ fn render_overlay(
|
||||
// ── Settings ──────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Settings => {
|
||||
let block = block
|
||||
.title(Span::styled(" ⚙ Settings ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Settings ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::PRIMARY));
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -198,7 +180,7 @@ fn render_overlay(
|
||||
// ── Bash ──────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Bash => {
|
||||
let block = block
|
||||
.title(Span::styled(" 💻 Bash Jobs ", Style::default().fg(Theme::ACCENT_ORANGE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Bash Jobs ", Style::default().fg(Theme::ACCENT_ORANGE).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ACCENT_ORANGE));
|
||||
let lines: Vec<Line> = state.session_runtime.as_ref().map(|r| {
|
||||
r.bash_jobs.iter().map(|job| {
|
||||
@@ -225,7 +207,7 @@ fn render_overlay(
|
||||
// ── Quit Confirm ──────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::QuitConfirm => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🚪 Quit ", Style::default().fg(Theme::ERROR).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Quit ", Style::default().fg(Theme::ERROR).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ERROR));
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -250,7 +232,7 @@ fn render_overlay(
|
||||
// ── Key Input ─────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::KeyInput => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🔑 API Key ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" API Key ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::WARNING));
|
||||
let input_text = &state.input.buffer;
|
||||
let display = if input_text.is_empty() {
|
||||
@@ -287,7 +269,7 @@ fn render_overlay(
|
||||
// ── Editor ────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Editor => {
|
||||
let block = block
|
||||
.title(Span::styled(" ✏️ Editor ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Editor ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::PRIMARY));
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -316,7 +298,7 @@ fn render_overlay(
|
||||
// ── Effort ────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Effort => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🎯 Effort Level ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Effort Level ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ACCENT_PURPLE));
|
||||
let levels = crate::app::mode::effort::EFFORT_LEVELS;
|
||||
let current_idx = crate::app::mode::effort::current_effort(state);
|
||||
@@ -349,7 +331,7 @@ fn render_overlay(
|
||||
// ── MCP ───────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Mcp => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🔌 MCP Servers ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" MCP Servers ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::INFO));
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -378,32 +360,23 @@ fn render_overlay(
|
||||
// ── Todo ──────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Todo => {
|
||||
let block = block
|
||||
.title(Span::styled(" 📋 Tasks ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Tasks ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ACCENT_PURPLE));
|
||||
let msg_count = state.transcript_cache.messages.len();
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
" Session Activity",
|
||||
Style::default().fg(Theme::TEXT).add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(Span::raw("")),
|
||||
Line::from(Span::styled(
|
||||
format!(" Messages: {msg_count}"),
|
||||
Style::default().fg(Theme::INFO),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Overlay: {:?}", state.misc.overlay),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
];
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
let content = if state.misc.todo_content.is_empty() {
|
||||
" No tasks yet."
|
||||
} else {
|
||||
&state.misc.todo_content
|
||||
};
|
||||
let paragraph = Paragraph::new(content)
|
||||
.block(block)
|
||||
.wrap(Wrap { trim: false });
|
||||
frame.render_widget(paragraph, overlay_area);
|
||||
}
|
||||
|
||||
// ── Rewind ────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Rewind => {
|
||||
let block = block
|
||||
.title(Span::styled(" ⏪ Rewind ", Style::default().fg(Theme::ACCENT_ORANGE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Rewind ", Style::default().fg(Theme::ACCENT_ORANGE).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ACCENT_ORANGE));
|
||||
let mut lines: Vec<Line> = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -461,7 +434,7 @@ fn render_overlay(
|
||||
.split(overlay_area);
|
||||
|
||||
let left_block = Block::default()
|
||||
.title(Span::styled(" 📚 Lessons ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Lessons ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER))
|
||||
.style(Style::default().bg(Theme::BG));
|
||||
@@ -633,90 +606,75 @@ fn render_overlay(
|
||||
// ── Usage ────────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Usage => {
|
||||
let block = block
|
||||
.title(Span::styled(" 📊 Usage ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Usage ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::INFO));
|
||||
let runtime = state.session_runtime.as_ref();
|
||||
let (tokens_in, tokens_out, api_calls, review_tokens, session_start) = runtime
|
||||
.map_or((0, 0, 0, 0, 0), |r| {
|
||||
(
|
||||
r.usage.tokens_in,
|
||||
r.usage.tokens_out,
|
||||
r.usage.api_calls,
|
||||
r.usage.review_tokens,
|
||||
r.session_start,
|
||||
)
|
||||
});
|
||||
let now_ms = chrono::Utc::now().timestamp_millis();
|
||||
let summary = runtime.map(|r| sidebar::compute_usage_summary(&r.usage, r.session_start, now_ms));
|
||||
let (edit_count, lesson_count, review_count, consec_empty) = runtime
|
||||
.map_or((0, 0, 0, 0), |r| {
|
||||
(
|
||||
r.edit_count,
|
||||
r.lesson_count,
|
||||
r.review_count,
|
||||
r.consecutive_empty_reviews,
|
||||
)
|
||||
(r.edit_count, r.lesson_count, r.review_count, r.consecutive_empty_reviews)
|
||||
});
|
||||
let elapsed_ms = chrono::Utc::now().timestamp_millis().saturating_sub(session_start);
|
||||
let hours = elapsed_ms / 3_600_000;
|
||||
let minutes = (elapsed_ms % 3_600_000) / 60_000;
|
||||
let seconds = (elapsed_ms % 60000) / 1000;
|
||||
let total_tokens = tokens_in.saturating_add(tokens_out);
|
||||
let self_learning_total = review_tokens;
|
||||
let main_tokens = total_tokens.saturating_sub(self_learning_total);
|
||||
let lines = vec![
|
||||
let mut lines = vec![
|
||||
Line::from(Span::styled(
|
||||
" Token Usage",
|
||||
Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(Span::raw("")),
|
||||
Line::from(Span::styled(
|
||||
format!(" Main agent: {main_tokens} tokens"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Self-learning: {self_learning_total} tokens"),
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Total: {total_tokens} tokens"),
|
||||
Style::default().fg(Theme::TEXT).add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" API calls: {api_calls}"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)),
|
||||
Line::from(Span::raw("")),
|
||||
Line::from(Span::styled(
|
||||
" Activity",
|
||||
Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Edits: {edit_count}"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Reviews: {review_count}"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Lessons: {lesson_count}"),
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" Empty reviews: {}",
|
||||
if consec_empty > 3 {
|
||||
format!("{consec_empty} ⚠")
|
||||
} else {
|
||||
consec_empty.to_string()
|
||||
},
|
||||
),
|
||||
Style::default().fg(if consec_empty > 3 { Theme::WARNING } else { Theme::TEXT_DIM }),
|
||||
)),
|
||||
Line::from(Span::raw("")),
|
||||
Line::from(Span::styled(
|
||||
format!(" Session: {hours}h {minutes}m {seconds}s"),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
];
|
||||
if let Some(s) = &summary {
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Main agent: {} tokens", s.main_tokens),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Self-learning: {} tokens", s.self_learning_tokens),
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Total: {} tokens", s.total_tokens),
|
||||
Style::default().fg(Theme::TEXT).add_modifier(Modifier::BOLD),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" API calls: {}", s.api_calls),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)));
|
||||
} else {
|
||||
lines.push(Line::from(Span::styled(
|
||||
" No active session.",
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)));
|
||||
}
|
||||
lines.push(Line::from(Span::raw("")));
|
||||
lines.push(Line::from(Span::styled(
|
||||
" Activity",
|
||||
Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Edits: {edit_count}"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Reviews: {review_count}"),
|
||||
Style::default().fg(Theme::TEXT),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Lessons: {lesson_count}"),
|
||||
Style::default().fg(Theme::TEXT_MUTED),
|
||||
)));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Empty reviews: {}",
|
||||
if consec_empty > 3 { format!("{consec_empty} ⚠") } else { consec_empty.to_string() },
|
||||
),
|
||||
Style::default().fg(if consec_empty > 3 { Theme::WARNING } else { Theme::TEXT_DIM }),
|
||||
)));
|
||||
if let Some(s) = &summary {
|
||||
lines.push(Line::from(Span::raw("")));
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(" Session: {}h {}m {}s", s.elapsed_hours, s.elapsed_minutes, s.elapsed_seconds),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)));
|
||||
}
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
frame.render_widget(paragraph, overlay_area);
|
||||
}
|
||||
@@ -724,7 +682,7 @@ fn render_overlay(
|
||||
// ── Loading ──────────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::Loading => {
|
||||
let block = block
|
||||
.title(Span::styled(" ⏳ Loading ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Loading ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::WARNING));
|
||||
let spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
||||
let frame_idx = (state.misc.tick_count as usize) % spinner.len();
|
||||
@@ -737,7 +695,7 @@ fn render_overlay(
|
||||
// ── Model Selector ───────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::ModelSelector => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🧠 Model Selector ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Model Selector ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::ACCENT_PURPLE));
|
||||
let mut lines: Vec<Line> = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -779,7 +737,7 @@ fn render_overlay(
|
||||
// ── Clear Confirm ────────────────────────────────────────────
|
||||
crate::app::state::types::Overlay::ClearConfirm => {
|
||||
let block = block
|
||||
.title(Span::styled(" 🗑️ Clear Transcript ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.title(Span::styled(" Clear Transcript ", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD)))
|
||||
.border_style(Style::default().fg(Theme::WARNING));
|
||||
let lines = vec![
|
||||
Line::from(Span::styled(
|
||||
@@ -973,3 +931,58 @@ fn centered_rect(area: Rect, percent_x: u16, percent_y: u16) -> Rect {
|
||||
height: area.height.saturating_sub(y_pad * 2).max(10),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `items` into the slice that fits within `max_visible` entries and
|
||||
/// the count of items hidden beyond that limit.
|
||||
///
|
||||
/// Used by sidebar widgets (Workflow, Tasks) to cap their content to the
|
||||
/// available panel height instead of overflowing it.
|
||||
///
|
||||
/// Return: `(visible_slice, hidden_count)` — `hidden_count` is `0` when
|
||||
/// everything fits.
|
||||
pub(crate) fn split_for_display<T>(items: &[T], max_visible: usize) -> (&[T], usize) {
|
||||
if items.len() <= max_visible {
|
||||
(items, 0)
|
||||
} else {
|
||||
(&items[..max_visible], items.len() - max_visible)
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the dim trailing hint line a sidebar widget shows when its
|
||||
/// content is truncated, pointing at the slash command that opens the
|
||||
/// full "expand" overlay for that widget (e.g. `"/workflow"`, `"/todo"`).
|
||||
pub(crate) fn overflow_hint_line(hidden: usize, command: &str) -> Line<'static> {
|
||||
Line::from(Span::styled(
|
||||
format!(" +{hidden} more — {command}"),
|
||||
Style::default().fg(Theme::TEXT_DIM).add_modifier(Modifier::ITALIC),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn split_for_display_returns_everything_when_it_fits() {
|
||||
let items = vec![1, 2, 3];
|
||||
let (visible, hidden) = split_for_display(&items, 5);
|
||||
assert_eq!(visible, &[1, 2, 3]);
|
||||
assert_eq!(hidden, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_for_display_truncates_and_counts_hidden() {
|
||||
let items = vec![1, 2, 3, 4, 5];
|
||||
let (visible, hidden) = split_for_display(&items, 2);
|
||||
assert_eq!(visible, &[1, 2]);
|
||||
assert_eq!(hidden, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overflow_hint_line_mentions_hidden_count_and_command() {
|
||||
let line = overflow_hint_line(3, "/todo");
|
||||
let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
|
||||
assert!(text.contains("+3 more"));
|
||||
assert!(text.contains("/todo"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
//! Persistent right-hand dashboard sidebar: Workflow, Tasks, and Usage
|
||||
//! widgets stacked in three vertical thirds — the "glance" view that
|
||||
//! complements the `Overlay::Todo` / `Overlay::Usage` "expand" views in
|
||||
//! `view/mod.rs`.
|
||||
|
||||
use ratatui::layout::{Constraint, Direction, Layout, Rect};
|
||||
use ratatui::style::{Style, Modifier};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Paragraph};
|
||||
use ratatui::Frame;
|
||||
use super::theme::Theme;
|
||||
|
||||
/// Render the persistent right-hand dashboard: Workflow, Tasks, and Usage
|
||||
/// widgets stacked in three roughly-equal vertical thirds.
|
||||
pub fn draw_sidebar(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Ratio(1, 3),
|
||||
Constraint::Ratio(1, 3),
|
||||
Constraint::Ratio(1, 3),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
super::workflow::draw_workflow_widget(frame, chunks[0], state);
|
||||
draw_tasks_widget(frame, chunks[1], state);
|
||||
draw_usage_widget(frame, chunks[2], state);
|
||||
}
|
||||
|
||||
/// Compact Tasks widget: `misc.todo_content` split into lines, truncated
|
||||
/// to whatever fits with a trailing "+N more" hint pointing at `/todo`.
|
||||
fn draw_tasks_widget(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
let block = Block::default()
|
||||
.title(Span::styled(" Tasks ", Style::default().fg(Theme::ACCENT_PURPLE).add_modifier(Modifier::BOLD)))
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER));
|
||||
let budget = (block.inner(area).height as usize).max(1);
|
||||
|
||||
let content = &state.misc.todo_content;
|
||||
let task_lines: Vec<&str> = content.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
|
||||
let lines: Vec<Line> = if task_lines.is_empty() {
|
||||
vec![Line::from(Span::styled(" No tasks yet.", Style::default().fg(Theme::TEXT_DIM)))]
|
||||
} else {
|
||||
let show_hint = task_lines.len() > budget;
|
||||
let item_budget = if show_hint { budget.saturating_sub(1).max(1) } else { budget };
|
||||
let (visible, hidden) = super::split_for_display(&task_lines, item_budget);
|
||||
let mut lines: Vec<Line> = visible.iter()
|
||||
.map(|l| Line::from(Span::styled(format!(" {l}"), Style::default().fg(Theme::TEXT))))
|
||||
.collect();
|
||||
if show_hint {
|
||||
lines.push(super::overflow_hint_line(hidden, "/todo"));
|
||||
}
|
||||
lines
|
||||
};
|
||||
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
/// Compact Usage widget: total tokens, main/self-learning token split,
|
||||
/// API call count, and session clock. Always fits (the summary is a
|
||||
/// fixed handful of lines), so there is no overflow hint — the
|
||||
/// `Overlay::Usage` "expand" view adds edit/review/lesson activity
|
||||
/// counters on top of this same summary rather than showing more of a
|
||||
/// truncated list.
|
||||
///
|
||||
/// Each number gets its own short line rather than being crammed onto
|
||||
/// one — the sidebar column is only ~28 usable characters wide after
|
||||
/// borders, and a single `"{total} tok ({main} main / {learn} learn)"`
|
||||
/// line silently clips (no `.wrap()` on this `Paragraph`) once token
|
||||
/// counts reach 5-6 digits, which is routine for an agent session.
|
||||
fn draw_usage_widget(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
let block = Block::default()
|
||||
.title(Span::styled(" Usage ", Style::default().fg(Theme::INFO).add_modifier(Modifier::BOLD)))
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER));
|
||||
|
||||
let lines: Vec<Line> = if let Some(ref rt) = state.session_runtime {
|
||||
let now_ms = chrono::Utc::now().timestamp_millis();
|
||||
let summary = compute_usage_summary(&rt.usage, rt.session_start, now_ms);
|
||||
vec![
|
||||
Line::from(Span::styled(
|
||||
format!(" {} tok total", summary.total_tokens),
|
||||
Style::default().fg(Theme::TEXT).add_modifier(Modifier::BOLD),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" main: {} tok", summary.main_tokens),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" learn: {} tok", summary.self_learning_tokens),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" {} API calls", summary.api_calls),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
Line::from(Span::styled(
|
||||
format!(" {}h {}m {}s", summary.elapsed_hours, summary.elapsed_minutes, summary.elapsed_seconds),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
)),
|
||||
]
|
||||
} else {
|
||||
vec![Line::from(Span::styled(" No active session.", Style::default().fg(Theme::TEXT_DIM)))]
|
||||
};
|
||||
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
/// Derived, display-ready usage numbers shared by the compact Usage
|
||||
/// widget and the `Overlay::Usage` expand view.
|
||||
pub(crate) struct UsageSummary {
|
||||
pub main_tokens: u64,
|
||||
pub self_learning_tokens: u64,
|
||||
pub total_tokens: u64,
|
||||
pub api_calls: u64,
|
||||
pub elapsed_hours: i64,
|
||||
pub elapsed_minutes: i64,
|
||||
pub elapsed_seconds: i64,
|
||||
}
|
||||
|
||||
/// Compute display-ready usage numbers from raw session counters.
|
||||
///
|
||||
/// Flow: total = `tokens_in` + `tokens_out` → main = total - `review_tokens`
|
||||
/// (the self-learning share) → elapsed = `now_ms` - `session_start`, split
|
||||
/// into h/m/s.
|
||||
///
|
||||
/// Why `now_ms` is a parameter instead of reading the clock internally:
|
||||
/// keeps this function pure and deterministic for testing.
|
||||
pub(crate) fn compute_usage_summary(
|
||||
usage: &crate::app::state::runtime::UsageStats,
|
||||
session_start: i64,
|
||||
now_ms: i64,
|
||||
) -> UsageSummary {
|
||||
let total_tokens = usage.tokens_in.saturating_add(usage.tokens_out);
|
||||
let self_learning_tokens = usage.review_tokens;
|
||||
let main_tokens = total_tokens.saturating_sub(self_learning_tokens);
|
||||
let elapsed_ms = now_ms.saturating_sub(session_start);
|
||||
let elapsed_hours = elapsed_ms / 3_600_000;
|
||||
let elapsed_minutes = (elapsed_ms % 3_600_000) / 60_000;
|
||||
let elapsed_seconds = (elapsed_ms % 60_000) / 1000;
|
||||
UsageSummary {
|
||||
main_tokens,
|
||||
self_learning_tokens,
|
||||
total_tokens,
|
||||
api_calls: usage.api_calls,
|
||||
elapsed_hours,
|
||||
elapsed_minutes,
|
||||
elapsed_seconds,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::state::runtime::UsageStats;
|
||||
|
||||
#[test]
|
||||
fn compute_usage_summary_splits_main_and_self_learning_tokens() {
|
||||
let usage = UsageStats {
|
||||
tokens_in: 100,
|
||||
tokens_out: 50,
|
||||
review_tokens: 30,
|
||||
api_calls: 4,
|
||||
..UsageStats::default()
|
||||
};
|
||||
let summary = compute_usage_summary(&usage, 0, 0);
|
||||
assert_eq!(summary.total_tokens, 150);
|
||||
assert_eq!(summary.self_learning_tokens, 30);
|
||||
assert_eq!(summary.main_tokens, 120);
|
||||
assert_eq!(summary.api_calls, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_usage_summary_splits_elapsed_time() {
|
||||
let usage = UsageStats::default();
|
||||
// 1h 2m 3s = 3_600_000 + 120_000 + 3_000 ms
|
||||
let summary = compute_usage_summary(&usage, 0, 3_723_000);
|
||||
assert_eq!(summary.elapsed_hours, 1);
|
||||
assert_eq!(summary.elapsed_minutes, 2);
|
||||
assert_eq!(summary.elapsed_seconds, 3);
|
||||
}
|
||||
}
|
||||
+54
-48
@@ -1,13 +1,13 @@
|
||||
//! Central color theme for the TUI — modern dark palette with neon accents.
|
||||
//! Central color theme for the TUI — Tokyo Night palette.
|
||||
//!
|
||||
//! Flow: defines a single `Theme` marker struct with associated `Color`
|
||||
//! consts, consumed by every `view/*` render function so styling stays
|
||||
//! consistent and changeable from one place.
|
||||
//!
|
||||
//! Design: dark-primary background (#1a1b26 / Catppuccin Mocha inspired),
|
||||
//! vibrant accent colors for semantic states, and muted tones for
|
||||
//! secondary/background elements. This gives a modern "neon dashboard"
|
||||
//! look that is easy on the eyes during long sessions.
|
||||
//! Design: muted blue-purple dark background with desaturated blue/cyan/
|
||||
//! purple accents (not neon) — the popular Tokyo Night editor/terminal
|
||||
//! theme. Chosen for a calmer "professional dev tool" read in place of
|
||||
//! the previous neon-accented palette.
|
||||
|
||||
use ratatui::style::Color;
|
||||
|
||||
@@ -20,75 +20,81 @@ pub struct Theme;
|
||||
impl Theme {
|
||||
// ── Base surface colors ──────────────────────────────────────────────
|
||||
/// Deep background — used for the main chat area and overlays.
|
||||
pub const BG: Color = Color::Rgb(24, 25, 38);
|
||||
pub const BG: Color = Color::Rgb(0x1a, 0x1b, 0x26);
|
||||
/// Slightly lighter surface — for panels, cards, and input bars.
|
||||
pub const SURFACE: Color = Color::Rgb(30, 32, 48);
|
||||
pub const SURFACE: Color = Color::Rgb(0x1f, 0x23, 0x35);
|
||||
/// Elevated surface — for dropdowns, toasts, and floating elements.
|
||||
pub const SURFACE_ELEVATED: Color = Color::Rgb(38, 40, 58);
|
||||
pub const SURFACE_ELEVATED: Color = Color::Rgb(0x29, 0x2e, 0x42);
|
||||
|
||||
// ── Text colors ──────────────────────────────────────────────────────
|
||||
/// Primary text color (bright white).
|
||||
pub const TEXT: Color = Color::Rgb(220, 222, 245);
|
||||
/// Primary text color.
|
||||
pub const TEXT: Color = Color::Rgb(0xc0, 0xca, 0xf5);
|
||||
/// Secondary / muted text.
|
||||
pub const TEXT_MUTED: Color = Color::Rgb(150, 152, 180);
|
||||
pub const TEXT_MUTED: Color = Color::Rgb(0xa9, 0xb1, 0xd6);
|
||||
/// Dim / placeholder text.
|
||||
pub const TEXT_DIM: Color = Color::Rgb(90, 92, 120);
|
||||
pub const TEXT_DIM: Color = Color::Rgb(0x56, 0x5f, 0x89);
|
||||
|
||||
// ── Accent colors ────────────────────────────────────────────────────
|
||||
/// Primary accent — cyan for borders, titles, selections.
|
||||
pub const PRIMARY: Color = Color::Rgb(0, 212, 255);
|
||||
/// Primary accent — blue for borders, titles, selections.
|
||||
pub const PRIMARY: Color = Color::Rgb(0x7a, 0xa2, 0xf7);
|
||||
/// Success / positive states — green.
|
||||
pub const SUCCESS: Color = Color::Rgb(80, 220, 130);
|
||||
/// Warning / in-progress states — yellow-orange.
|
||||
pub const WARNING: Color = Color::Rgb(255, 200, 80);
|
||||
pub const SUCCESS: Color = Color::Rgb(0x9e, 0xce, 0x6a);
|
||||
/// Warning / in-progress states — yellow.
|
||||
pub const WARNING: Color = Color::Rgb(0xe0, 0xaf, 0x68);
|
||||
/// Error / failure states — red.
|
||||
pub const ERROR: Color = Color::Rgb(255, 100, 110);
|
||||
/// Informational / neutral — blue.
|
||||
pub const INFO: Color = Color::Rgb(100, 170, 255);
|
||||
pub const ERROR: Color = Color::Rgb(0xf7, 0x76, 0x8e);
|
||||
/// Informational / neutral — cyan.
|
||||
pub const INFO: Color = Color::Rgb(0x7d, 0xcf, 0xff);
|
||||
|
||||
// ── Extended accent palette ──────────────────────────────────────────
|
||||
/// Purple accent — used for special highlights.
|
||||
pub const ACCENT_PURPLE: Color = Color::Rgb(180, 130, 255);
|
||||
#[allow(dead_code)]
|
||||
/// Pink / magenta accent.
|
||||
pub const ACCENT_PINK: Color = Color::Rgb(255, 120, 200);
|
||||
pub const ACCENT_PURPLE: Color = Color::Rgb(0xbb, 0x9a, 0xf7);
|
||||
/// Orange accent.
|
||||
pub const ACCENT_ORANGE: Color = Color::Rgb(255, 160, 60);
|
||||
pub const ACCENT_ORANGE: Color = Color::Rgb(0xff, 0x9e, 0x64);
|
||||
/// Teal accent.
|
||||
pub const ACCENT_TEAL: Color = Color::Rgb(60, 210, 200);
|
||||
pub const ACCENT_TEAL: Color = Color::Rgb(0x73, 0xda, 0xca);
|
||||
|
||||
// ── Border colors ────────────────────────────────────────────────────
|
||||
/// Standard border color.
|
||||
pub const BORDER: Color = Color::Rgb(50, 52, 72);
|
||||
#[allow(dead_code)]
|
||||
/// Focused / active border.
|
||||
pub const BORDER_FOCUS: Color = Color::Rgb(0, 180, 220);
|
||||
pub const BORDER: Color = Color::Rgb(0x3b, 0x42, 0x61);
|
||||
|
||||
// ── Role badge colors ────────────────────────────────────────────────
|
||||
pub const ROLE_USER: Color = Color::Rgb(80, 220, 130); // green
|
||||
pub const ROLE_ASSISTANT: Color = Color::Rgb(0, 212, 255); // cyan
|
||||
pub const ROLE_SYSTEM: Color = Color::Rgb(100, 170, 255); // blue
|
||||
pub const ROLE_TOOL: Color = Color::Rgb(255, 200, 80); // yellow
|
||||
pub const ROLE_USER: Color = Color::Rgb(0x9e, 0xce, 0x6a); // green
|
||||
pub const ROLE_ASSISTANT: Color = Color::Rgb(0x7a, 0xa2, 0xf7); // blue
|
||||
pub const ROLE_SYSTEM: Color = Color::Rgb(0x7d, 0xcf, 0xff); // cyan
|
||||
pub const ROLE_TOOL: Color = Color::Rgb(0xe0, 0xaf, 0x68); // yellow
|
||||
|
||||
// ── Status colors ────────────────────────────────────────────────────
|
||||
pub const STATUS_BAR_BG: Color = Color::Rgb(20, 21, 34);
|
||||
pub const MODE_AUTO: Color = Color::Rgb(80, 220, 130);
|
||||
pub const MODE_YOLO: Color = Color::Rgb(255, 100, 110);
|
||||
pub const STATUS_BAR_BG: Color = Color::Rgb(0x16, 0x16, 0x1e);
|
||||
pub const MODE_AUTO: Color = Color::Rgb(0x9e, 0xce, 0x6a);
|
||||
pub const MODE_YOLO: Color = Color::Rgb(0xf7, 0x76, 0x8e);
|
||||
|
||||
// ── Code / markdown ──────────────────────────────────────────────────
|
||||
pub const CODE_BG: Color = Color::Rgb(20, 22, 35);
|
||||
pub const CODE_BAR: Color = Color::Rgb(40, 42, 62);
|
||||
pub const BLOCKQUOTE_BAR: Color = Color::Rgb(100, 170, 255);
|
||||
pub const CODE_BG: Color = Color::Rgb(0x16, 0x16, 0x1e);
|
||||
pub const CODE_BAR: Color = Color::Rgb(0x29, 0x2e, 0x42);
|
||||
pub const BLOCKQUOTE_BAR: Color = Color::Rgb(0x7d, 0xcf, 0xff);
|
||||
|
||||
// ── Misc ─────────────────────────────────────────────────────────────
|
||||
/// Highlight / selection background.
|
||||
pub const HIGHLIGHT: Color = Color::Rgb(0, 140, 180);
|
||||
pub const HIGHLIGHT: Color = Color::Rgb(0x3d, 0x59, 0xa1);
|
||||
/// Dim highlight (for non-selected items).
|
||||
pub const HIGHLIGHT_DIM: Color = Color::Rgb(30, 40, 60);
|
||||
#[allow(dead_code)]
|
||||
/// Scrollbar track.
|
||||
pub const SCROLLBAR_BG: Color = Color::Rgb(35, 37, 55);
|
||||
#[allow(dead_code)]
|
||||
/// Scrollbar thumb.
|
||||
pub const SCROLLBAR_FG: Color = Color::Rgb(60, 62, 85);
|
||||
pub const HIGHLIGHT_DIM: Color = Color::Rgb(0x29, 0x2e, 0x42);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn palette_matches_tokyo_night_spec() {
|
||||
assert_eq!(Theme::BG, Color::Rgb(0x1a, 0x1b, 0x26));
|
||||
assert_eq!(Theme::SURFACE, Color::Rgb(0x1f, 0x23, 0x35));
|
||||
assert_eq!(Theme::PRIMARY, Color::Rgb(0x7a, 0xa2, 0xf7));
|
||||
assert_eq!(Theme::SUCCESS, Color::Rgb(0x9e, 0xce, 0x6a));
|
||||
assert_eq!(Theme::WARNING, Color::Rgb(0xe0, 0xaf, 0x68));
|
||||
assert_eq!(Theme::ERROR, Color::Rgb(0xf7, 0x76, 0x8e));
|
||||
assert_eq!(Theme::INFO, Color::Rgb(0x7d, 0xcf, 0xff));
|
||||
assert_eq!(Theme::ACCENT_PURPLE, Color::Rgb(0xbb, 0x9a, 0xf7));
|
||||
assert_eq!(Theme::BORDER, Color::Rgb(0x3b, 0x42, 0x61));
|
||||
}
|
||||
}
|
||||
|
||||
+71
-89
@@ -4,8 +4,9 @@
|
||||
//! panel showing agent statuses, findings count, session counters, and
|
||||
//! usage hints.
|
||||
//!
|
||||
//! Design: agents are shown as compact cards with state-colored badges.
|
||||
//! The division pipeline mode adds a visual pipeline flow with arrows.
|
||||
//! Design: agents are shown as compact cards with state-colored badges,
|
||||
//! including hive-mind nodes (named by their system-assigned designation,
|
||||
//! e.g. `"Node-0-1"`).
|
||||
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::{Style, Modifier};
|
||||
@@ -13,7 +14,7 @@ use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
|
||||
use ratatui::Frame;
|
||||
use super::theme::Theme;
|
||||
use crate::app::workflow::engine::AgentState;
|
||||
use crate::app::workflow::engine::{AgentState, WorkflowAgent};
|
||||
|
||||
/// Icons for agent states.
|
||||
fn state_icon(state: AgentState) -> &'static str {
|
||||
@@ -43,29 +44,12 @@ fn state_color(state: AgentState) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect if the current workflow looks like a company pipeline.
|
||||
fn is_company_pipeline(agents: &[crate::app::workflow::engine::WorkflowAgent]) -> bool {
|
||||
if agents.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let division_keywords = ["Strategy", "Engineering", "Quality", "Security", "Documentation"];
|
||||
agents.iter().any(|a| {
|
||||
division_keywords.iter().any(|k| a.name.contains(k))
|
||||
})
|
||||
}
|
||||
|
||||
/// Render the workflow status panel.
|
||||
#[allow(clippy::too_many_lines)]
|
||||
pub fn draw_workflow_panel(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
use ratatui::layout::{Constraint, Direction, Layout};
|
||||
|
||||
let is_company = is_company_pipeline(&state.workflow_engine.agents);
|
||||
|
||||
let title = if is_company {
|
||||
Span::styled(" 🏢 Pipeline ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD))
|
||||
} else {
|
||||
Span::styled(" ⚙ Workflow ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD))
|
||||
};
|
||||
let title = Span::styled(" Workflow ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD));
|
||||
|
||||
let block = Block::default()
|
||||
.borders(Borders::ALL)
|
||||
@@ -87,74 +71,27 @@ pub fn draw_workflow_panel(frame: &mut Frame, area: Rect, state: &crate::app::st
|
||||
// ── Header area ──────────────────────────────────────────────────────
|
||||
let mut header_lines: Vec<Line> = Vec::new();
|
||||
|
||||
if is_company {
|
||||
// Division pipeline overview
|
||||
let agents = &state.workflow_engine.agents;
|
||||
let mut pipe_spans: Vec<Span> = Vec::new();
|
||||
for (i, agent) in agents.iter().enumerate() {
|
||||
if i > 0 {
|
||||
pipe_spans.push(Span::styled(
|
||||
" ",
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
));
|
||||
}
|
||||
let icon = state_icon(agent.status.state);
|
||||
let color = state_color(agent.status.state);
|
||||
let modif = match agent.status.state {
|
||||
AgentState::Idle => Modifier::empty(),
|
||||
_ => Modifier::BOLD,
|
||||
};
|
||||
pipe_spans.push(Span::styled(
|
||||
format!("{} {} ", icon, agent.name.chars().take(10).collect::<String>()),
|
||||
Style::default().fg(color).add_modifier(modif),
|
||||
));
|
||||
if i < agents.len().saturating_sub(1) {
|
||||
pipe_spans.push(Span::styled(
|
||||
"→",
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
));
|
||||
}
|
||||
}
|
||||
header_lines.push(Line::from(pipe_spans));
|
||||
header_lines.push(Line::from(vec![
|
||||
Span::styled("Status: ", Style::default().fg(Theme::TEXT_DIM)),
|
||||
if state.turn_in_flight() {
|
||||
Span::styled("● Running", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD))
|
||||
} else {
|
||||
Span::styled("● Idle", Style::default().fg(Theme::SUCCESS))
|
||||
},
|
||||
Span::raw(" "),
|
||||
Span::styled(
|
||||
format!("Agents: {} | Findings: {}",
|
||||
state.workflow_engine.agents.len(),
|
||||
state.workflow_engine.findings.len(),
|
||||
),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
header_lines.push(Line::from(vec![
|
||||
Span::styled("/workflow run ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)),
|
||||
Span::styled("<prompt>", Style::default().fg(Theme::TEXT_DIM)),
|
||||
Span::styled(" · Esc to close", Style::default().fg(Theme::TEXT_DIM)),
|
||||
]));
|
||||
header_lines.push(Line::from(vec![
|
||||
Span::styled("Status: ", Style::default().fg(Theme::TEXT_DIM)),
|
||||
if state.turn_in_flight() {
|
||||
Span::styled("● Running", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD))
|
||||
} else {
|
||||
Span::styled("● Idle", Style::default().fg(Theme::SUCCESS))
|
||||
},
|
||||
Span::raw(" "),
|
||||
Span::styled(
|
||||
format!("Agents: {} | Findings: {}",
|
||||
state.workflow_engine.agents.len(),
|
||||
state.workflow_engine.findings.len(),
|
||||
),
|
||||
]));
|
||||
} else {
|
||||
header_lines.push(Line::from(vec![
|
||||
Span::styled("/workflow run ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)),
|
||||
Span::styled("<prompt>", Style::default().fg(Theme::TEXT_DIM)),
|
||||
Span::styled(" · Esc to close", Style::default().fg(Theme::TEXT_DIM)),
|
||||
]));
|
||||
header_lines.push(Line::from(vec![
|
||||
Span::styled("Status: ", Style::default().fg(Theme::TEXT_DIM)),
|
||||
if state.turn_in_flight() {
|
||||
Span::styled("● Running", Style::default().fg(Theme::WARNING).add_modifier(Modifier::BOLD))
|
||||
} else {
|
||||
Span::styled("● Idle", Style::default().fg(Theme::SUCCESS))
|
||||
},
|
||||
Span::raw(" "),
|
||||
Span::styled(
|
||||
format!("Agents: {} | Findings: {}",
|
||||
state.workflow_engine.agents.len(),
|
||||
state.workflow_engine.findings.len(),
|
||||
),
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
),
|
||||
]));
|
||||
}
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
),
|
||||
]));
|
||||
|
||||
let header = Paragraph::new(header_lines);
|
||||
frame.render_widget(header, chunks[0]);
|
||||
@@ -264,11 +201,56 @@ fn build_session_lines(state: &crate::app::state::rest::AppStateRest) -> Vec<Lin
|
||||
|
||||
lines.push(Line::from(Span::raw("")));
|
||||
lines.push(Line::from(Span::styled(
|
||||
" Complex tasks auto-delegate to the company pipeline.",
|
||||
" Complex tasks auto-trigger a hive-mind convergence.",
|
||||
Style::default().fg(Theme::TEXT_DIM).add_modifier(Modifier::ITALIC),
|
||||
)));
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
/// Render the compact Workflow widget for the persistent sidebar: one
|
||||
/// line per agent (icon + name), truncated to whatever fits with a
|
||||
/// trailing "+N more" hint pointing at `/workflow` for the full view.
|
||||
///
|
||||
/// Flow: bordered `Block` titled "Workflow" → empty state if no agents →
|
||||
/// else `split_for_display` caps the list to the inner height (minus one
|
||||
/// row for the hint line, if needed) → one line per visible agent.
|
||||
pub fn draw_workflow_widget(frame: &mut Frame, area: Rect, state: &crate::app::state::rest::AppStateRest) {
|
||||
let block = Block::default()
|
||||
.title(Span::styled(" Workflow ", Style::default().fg(Theme::PRIMARY).add_modifier(Modifier::BOLD)))
|
||||
.borders(Borders::ALL)
|
||||
.border_style(Style::default().fg(Theme::BORDER));
|
||||
let budget = (block.inner(area).height as usize).max(1);
|
||||
|
||||
let agents = &state.workflow_engine.agents;
|
||||
let lines: Vec<Line> = if agents.is_empty() {
|
||||
vec![Line::from(Span::styled(
|
||||
" No workflow running.",
|
||||
Style::default().fg(Theme::TEXT_DIM),
|
||||
))]
|
||||
} else {
|
||||
let show_hint = agents.len() > budget;
|
||||
let item_budget = if show_hint { budget.saturating_sub(1).max(1) } else { budget };
|
||||
let (visible, hidden) = super::split_for_display(agents.as_slice(), item_budget);
|
||||
let mut lines: Vec<Line> = visible.iter().map(workflow_agent_line).collect();
|
||||
if show_hint {
|
||||
lines.push(super::overflow_hint_line(hidden, "/workflow"));
|
||||
}
|
||||
lines
|
||||
};
|
||||
|
||||
let paragraph = Paragraph::new(lines).block(block);
|
||||
frame.render_widget(paragraph, area);
|
||||
}
|
||||
|
||||
/// One compact line for a single agent: state icon + name, state-colored.
|
||||
fn workflow_agent_line(agent: &WorkflowAgent) -> Line<'static> {
|
||||
let color = state_color(agent.status.state);
|
||||
let icon = state_icon(agent.status.state);
|
||||
Line::from(vec![
|
||||
Span::styled(format!(" {icon} "), Style::default().fg(color).add_modifier(Modifier::BOLD)),
|
||||
Span::styled(agent.name.clone(), Style::default().fg(Theme::TEXT)),
|
||||
])
|
||||
}
|
||||
|
||||
use ratatui::style::Color;
|
||||
|
||||
Reference in New Issue
Block a user