diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..4a3399d --- /dev/null +++ b/PLAN.md @@ -0,0 +1,116 @@ +# hx: plan + +Rust agent harness. pi core (minimal, 4 tools) + built-in pi-lens-style feedback (LSP, linters, tests) + native MCP. + +## Reference behavior + +- **pi core:** minimal system prompt. Tools: `read`, `write`, `edit`, `bash`. AGENTS.md loaded hierarchically. Skills load on demand. Branching JSONL sessions. Multi-provider LLM layer. TUI plus headless JSON/RPC modes. +- **pi-lens:** hooks on write/edit. Parallel runners (LSP, linters, formatters, ast-grep, tests). Findings injected once at turn end. Read-guard, impact cascade to reverse deps, diagnostic triage marks, freshness gates so stale findings never reach the model. +- **MCP:** pi rejects it (schema token cost every session). hx supports it natively and fixes cost with lazy loading. + +## Design rules + +1. Core stays pi-small: 4 tools, tiny prompt, no plan mode or sub-agents in v1. +2. Lens is a built-in crate, not a plugin. Uses the same event bus extensions use. +3. MCP tools are lazy by default. Model sees a one-line index and pulls schemas via `mcp_describe`. Servers can opt in to eager registration. +4. Diagnostics injected once per turn end, only if fresh (file seq numbers). + +## Workspace + +``` +crates/ + hx-ai/ providers: anthropic, openai-compat, google. SSE streaming, tool calls, cost tracking + hx-core/ agent loop, Tool trait, event bus, session tree (JSONL), context files, skills, compaction + hx-tools/ read, write, edit, bash (+ read-guard, truncation, output caps) + hx-lens/ lsp/, dispatch/, runners/, tests/, seq-log, triage + hx-mcp/ client (stdio + streamable HTTP), lazy registry, config + hx-tui/ ratatui + crossterm, diff render, editor, footer widget + hx-cli/ clap; modes: interactive, print, json, rpc, mcp-serve +``` + +## Crates + +| Need | Crate | +|---|---| +| async, HTTP | `tokio`, `reqwest`, `eventsource-stream` | +| JSON, tool schemas | `serde`, `serde_json`, `schemars` | +| MCP | `rmcp` (official Rust SDK) | +| LSP | `lsp-types` + thin JSON-RPC client over stdio (`tokio::process`) | +| Search, ignore rules | `ignore`, `grep-searcher` | +| File watching | `notify` | +| Diff / edit | `similar` | +| Structural analysis | `tree-sitter` + grammars, `ast-grep-core` | +| TUI | `ratatui`, `crossterm` | +| CLI, logging | `clap`, `tracing` | +| Errors | `thiserror` (libs), `anyhow` (bin) | + +## Core loop (`hx-core`) + +```rust +trait Tool { fn spec(&self) -> ToolSpec; async fn call(&self, args: Value, cx: &mut ToolCtx) -> ToolResult; } +enum Event { SessionStart, TurnStart, ToolCall{..}, ToolResult{..}, TurnEnd, AgentEnd, Context } +trait Hook { async fn on(&self, ev: &Event, cx: &mut HookCtx) -> HookAction; } // Continue | Block | Inject(msg) | Mutate +``` + +- Loop: stream, collect tool calls, run tools (parallel if independent), append results, repeat. +- Hooks can block or mutate a tool call and inject messages at turn end. +- Sessions: append-only JSONL with `id` + `parent_id` (branching and resume free). +- Compaction: summarize-and-cut at token threshold, same provider. + +## Lens (`hx-lens`) + +- **Change log:** monotonic `project_seq` + per-file seq. Every write/edit/format/autofix bumps it; source recorded (agent, format, external via `notify`). +- **LSP manager:** one server per (language, root), lazy spawn, idle eviction. Config table: extension -> command -> root markers. Start with rust-analyzer, tsserver, pyright, gopls, clangd. Handles didOpen/didChange/didSave, push + pull diagnostics, definition/references/hover/symbols, timeout + circuit breaker. rust-analyzer is slow to init: warm at session start, fall back to `cargo check`. +- **Dispatcher:** on write/edit run runners in parallel with per-runner timeouts. Kinds: LSP, linter (clippy, ruff, biome, eslint), formatter (safe autofix only), ast-grep rules. +- **Tests:** + - Adapters: cargo test/nextest, pytest, vitest/jest, go test. + - Map changed file to affected tests: same crate/package, plus reverse deps from tree-sitter import graph. + - Run scoped, parse structured output (nextest JUnit, pytest `--junitxml`). Report only relevant failures. + - Modes: `turn_end` (default), `per_edit`, `off`. +- **Freshness gate:** findings carry the file seq they were computed at. Drop or label if file changed since. +- **Read-guard:** block `edit` on a file not `read` since its last external change. +- **Agent tools:** `lsp` (nav + diagnostics), `diag_mark` (false-positive / suppress / defer), optional `ast_search`. +- **Output:** one compact block at turn end, token-capped, grouped by file, errors first. + +## MCP (`hx-mcp`) + +- **Config:** `~/.hx/mcp.json` and `.hx/mcp.json`, same shape as Claude Code `mcpServers`. +- **Transports:** stdio and streamable HTTP via `rmcp`. OAuth deferred. +- **Registry:** on connect cache `tools/list`; inject only an index (`server.tool: one-line desc`). Model calls `mcp_describe` for schemas, then `mcp_call`. Servers under N tools or marked `eager: true` register native tools. +- **Resources / prompts:** prompts become slash commands; resources readable via `mcp_read`. +- **Safety:** per-server tool allowlist, output size caps, call timeouts, crash + restart handling. +- **`hx mcp-serve`:** exposes lens diagnostics and LSP nav as an MCP server for other agents. + +## Milestones + +| M | Deliverable | Done when | +|---|---|---| +| 0 | Workspace, CI, `hx-ai` with Anthropic + OpenAI-compat streaming | `hx -p "hi"` works | +| 1 | Agent loop, 4 tools, sessions, AGENTS.md, skills | Edits a real repo end to end | +| 2 | TUI, diff render, model switch, compaction | Daily-usable | +| 3 | Lens LSP: manager, turn-end diagnostics, `lsp` tool | Introduced type error is seen and fixed unprompted | +| 4 | Lens runners (clippy, ruff, biome), formatter, seq-log, read-guard, triage | Stale-finding test passes | +| 5 | Lens tests: cargo, pytest, vitest adapters, scoped selection | Failing affected test surfaced at turn end | +| 6 | MCP: stdio + HTTP client, lazy registry, `mcp-serve` | context7 / filesystem server works; index token cost measured vs eager | +| 7 | JSON + RPC modes, extension hooks (subprocess, JSON-RPC over stdio) | Editor integration possible | + +## Deliberate simplifications + +- **Extensions:** no embedded scripting in v1. Subprocess hooks over JSON-RPC. Add `mlua` or `wasmtime` if in-process UI extensions are needed. +- **Providers:** three only. OpenAI-compat covers most. +- **Sub-agents, plan mode:** skipped like pi. Add as hook or MCP server later. +- **Test selection:** heuristic, not coverage-based. Add coverage maps if false-positive rate is bad. +- **Windows:** deferred. `cfg`-gate process handling from the start. +- **Sandboxing:** none in v1 (YOLO like pi). Add Landlock/seccomp behind `bash` later. + +## Risks + +- LSP servers vary a lot (init options, push vs pull diagnostics). M3 will take longer than it looks. +- Turn-end injection can flood context. Token cap + seq freshness gate prevent it; test both early. +- Lazy MCP saves tokens but adds a round trip per new tool. Measure in M6, tune eager threshold. + +## Open questions + +- Extension model long term: subprocess JSON-RPC only, or add Lua/WASM? +- Test-selection strategy beyond heuristic? +- Default LSP install policy: managed installs under `~/.hx/lsp/` vs require user-installed servers?