spb/khaelor Public
KHAELOR — a terminal-native autonomous engineering agent powered by Anthropic.
TypeScript 82.9%
HTML 14.9%
CSS 1.1%
JavaScript 0.7%
1# KHAELOR — CLAUDE.md23> **Project:** KHAELOR4> **Command:** `khaelor`5> **Identity:** A terminal-native autonomous engineering agent powered by Anthropic.6> **Internal principle:** Understand first. Design second. Implement third.7> **Author / Maintainer:** Simon-Pierre Boucher — contact@spboucher.ai89---1011## 1. MISSION1213You are building **KHAELOR**, a next-generation autonomous terminal agent.1415KHAELOR is **not** another Claude Code clone. It must combine the strongest architectural and UX ideas found in:1617- Claude Code18- Hermes Agent19- OpenCode20- OpenHands / OpenHands Software Agent SDK21- mini-SWE-agent (where its minimalism is useful)2223…while developing its **own architecture and identity**.2425**Long-term goal:** build the best terminal-native AI agent interface in existence.2627KHAELOR V1 is **Anthropic-only**. Do NOT implement OpenAI, Gemini, OpenRouter, Ollama, or local models in the first version. The architecture must nevertheless remain clean enough that additional providers could later be added without rewriting the agent kernel.2829The first release must focus obsessively on:30311. Exceptional terminal UX322. Excellent Anthropic integration333. Reliable agent execution344. Clean architecture355. Context efficiency366. Observable actions377. Fast interaction388. Safe and understandable permissions399. Persistent sessions4010. Strong repository intelligence4142---4344## 2. ABSOLUTE RULES (NON-NEGOTIABLE)4546These rules override everything else in this document. Violating any of them means the work is **not done**, regardless of whether it compiles, passes tests, or looks finished.4748### ABSOLUTE RULE #0 — MANDATORY FILE HEADERS4950**Every source code file created or substantially rewritten in this project MUST begin with an author header.**5152Required fields:5354- **Author:** Simon-Pierre Boucher55- **Contact:** contact@spboucher.ai56- **File:** relative path from repository root57- **Description:** one line describing the file's purpose5859#### TypeScript / JavaScript (`.ts`, `.tsx`, `.js`, `.mjs`, `.cjs`)6061```ts62/**63 * KHAELOR64 * File: src/agent/kernel.ts65 * Description: Minimal agent kernel — coordinates context, model, and tool execution.66 *67 * Author: Simon-Pierre Boucher68 * Contact: contact@spboucher.ai69 */70```7172#### Shell scripts (`.sh`)7374```bash75#!/usr/bin/env bash76# KHAELOR77# File: scripts/build.sh78# Description: Production build script.79#80# Author: Simon-Pierre Boucher81# Contact: contact@spboucher.ai82```8384#### Rust (`.rs`) — if/when a native component exists8586```rust87//! KHAELOR88//! File: native/src/lib.rs89//! Description: Performance-critical native component.90//!91//! Author: Simon-Pierre Boucher92//! Contact: contact@spboucher.ai93```9495#### Markdown documentation (`.md`) — when authored as a deliverable9697```md98<!--99KHAELOR100File: docs/ARCHITECTURE.md101Author: Simon-Pierre Boucher102Contact: contact@spboucher.ai103-->104```105106#### Exceptions107108- Pure data files that cannot carry comments (`.json`, lockfiles, binary assets) are exempt. Where a config format supports comments (`.jsonc`, `.yaml`, `.toml`), the header IS required.109- Generated files must carry the header in their generator template, plus a `Generated file — do not edit` line.110- Vendored/reference code under `references/` keeps its original authorship and licenses. **Never** apply this header to third-party code.111112#### Enforcement113114- Add a lint/CI check (`scripts/check-headers` or an ESLint rule) that fails the build if any first-party source file is missing the header.115- The header check is part of the definition of done for every phase.116- When editing an existing file that lacks a header, add it.117118### ABSOLUTE RULE #1 — UNDERSTAND BEFORE BUILDING119120Do not begin implementing KHAELOR immediately. The first phase of this project is **mandatory architectural research** (Phase 0, below). No major production implementation may begin before the research documents exist.121122The rule is:123124```125UNDERSTAND FIRST → DESIGN SECOND → IMPLEMENT THIRD126```127128### ABSOLUTE RULE #2 — THE TERMINAL IS THE PRODUCT129130The terminal is not merely where KHAELOR runs. The terminal **IS** the product. Any feature that technically works but is not the best terminal interaction we can design is **not finished**.131132### ABSOLUTE RULE #3 — SMALL KERNEL133134The agent kernel stays minimal. Complexity lives in services **around** the kernel, never inside it. Whenever tempted to add something to `AgentKernel`, ask: *"Can this be a service around the kernel instead?"* The answer should almost always be yes.135136### ABSOLUTE RULE #4 — NEVER FABRICATE137138Never invent token usage, progress percentages, test results, or completion claims. Every displayed number must come from real data. Every completion claim must be backed by evidence (see §14).139140### ABSOLUTE RULE #5 — PROTECT USER WORK141142Never assume an existing diff belongs to KHAELOR. Record baseline git state before edits. Never auto-commit unless explicitly requested. Never destroy uncommitted user changes.143144---145146## 3. PHASE 0 — DEEP REPOSITORY ANALYSIS (MANDATORY)147148Before creating the production architecture, independently inspect the **current source code** of:149150- https://github.com/NousResearch/hermes-agent151- https://github.com/anomalyco/opencode152- https://github.com/OpenHands/OpenHands153- https://github.com/OpenHands/software-agent-sdk154- https://github.com/SWE-agent/mini-swe-agent (where useful)155156Do not merely read READMEs. Clone the repositories into a reference directory **outside** KHAELOR's production source tree:157158```159references/160 hermes-agent/161 opencode/162 openhands/163 openhands-agent-sdk/164 mini-swe-agent/165```166167These are **reference implementations only**. Do not blindly copy source code. Respect their licenses. The purpose is to understand their engineering decisions and derive a better architecture.168169**Required deliverables before any major implementation:**170171```172docs/research/173 HERMES_ANALYSIS.md174 OPENCODE_ANALYSIS.md175 OPENHANDS_ANALYSIS.md176 MINI_SWE_ANALYSIS.md177 COMPARATIVE_ARCHITECTURE.md178 KHAELOR_ARCHITECTURE_DECISIONS.md179```180181For each repository, trace **real code paths**: follow imports, find the agent loops, the tool registries, the session state, the render loops, the permission checks, context construction, process execution, and persistence.182183### 3.1 Hermes Agent analysis184185Investigate at minimum:186187**Agent loop.** Locate the actual implementation of: user message → context construction → LLM request → tool calls → tool execution → observations → next LLM call. Determine where the central agent class lives; how messages are represented; how tool calls are parsed; how tool outputs enter context; failure handling; retry strategy; cancellation behavior; how task completion is represented.188189**Context management.** Prompt construction; context compression; context-window pressure handling; prompt caching; conversation summarization; memory injection; system prompt construction.190191**Memory.** Persistent memory; session memory; memory providers; memory search; cross-session retrieval; how memories are written and selected.192193**Skills.** Skill format; discovery; loading; automatic creation; improvement; persistence; context injection.194195**Terminal execution.** Local execution; process lifecycle; Docker; SSH; remote execution abstractions; command output; timeouts; async processes.196197**Subagents.** Creation; isolation; context inheritance; result propagation; concurrency; lifecycle; recursion limits.198199**TUI.** Layout; rendering; streaming; keyboard navigation; tool rendering; session selection; model switching; status presentation; long-output handling.200201Record explicitly: WHAT HERMES DOES VERY WELL / WHAT HERMES DOES POORLY / WHAT KHAELOR SHOULD ADOPT / WHAT KHAELOR SHOULD NOT COPY.202203### 3.2 OpenCode analysis204205OpenCode is particularly important for KHAELOR because of its terminal-first design. Perform the same depth of analysis, covering:206207**TUI framework.** Exact terminal UI libraries/frameworks; component architecture; event model; keyboard handling; resizing; scrolling; rendering strategy; markdown rendering; syntax highlighting; input editor; autocomplete; command palette; overlays/modals; diff visualization; streaming output.208209**Agent architecture.** Build agent, plan agent, subagents, sessions, messages, tool calls, permissions. Determine whether modes are different agents, different prompts, permission policies, or a combination.210211**State.** Session persistence; conversation state; project state; working directory handling; configuration; per-project settings.212213**Tools.** Implementations of `bash`, `read`, `write`, `edit`, `grep`, `glob`, `task/subagent`. Study their schemas carefully — especially how OpenCode avoids overwhelming the model with unnecessary tool complexity.214215**Permission UX.** Rules; allow/ask/deny behavior; scope; persistence; TUI confirmation interactions.216217**Performance.** Startup time; rendering strategy; streaming; caching; unnecessary re-renders; long-session performance. Identify what makes OpenCode feel fast even when model inference is not.218219### 3.3 OpenHands analysis220221OpenHands matters most architecturally. Study the separation between:222223| Concern | OpenHands concept |224|---|---|225| Intelligence | Agent |226| Lifecycle | Conversation / Session |227| Environment | Workspace |228| Actions | Tools |229| History | Events / EventLog |230| Safety | Security analyzers / confirmation |231232This separation should heavily influence KHAELOR. Study: local and remote workspaces; sandbox model; file editing; shell execution; event log; persistence; security analyzers; permission confirmation; observation representation. Determine whether KHAELOR can adopt the **principles** without inheriting unnecessary framework complexity.233234### 3.4 mini-SWE-agent analysis235236Study mini-SWE-agent for one question: **How little agent scaffolding is actually necessary?**237238Locate its fundamental loop — conceptually: query model → execute actions → return observations → repeat. KHAELOR must preserve this philosophical minimalism inside its kernel. Complexity lives around the kernel, not inside it.239240### 3.5 Comparative architecture241242Create `docs/research/COMPARATIVE_ARCHITECTURE.md` with a decision matrix:243244| Capability | Hermes | OpenCode | OpenHands | mini-SWE | KHAELOR Decision |245|---|---|---|---|---|---|246| Agent loop | | | | | |247| TUI | | | | | |248| Tools | | | | | |249| Sessions | | | | | |250| Context | | | | | |251| Memory | | | | | |252| Permissions | | | | | |253| Workspace | | | | | |254| Events | | | | | |255| Subagents | | | | | |256| Processes | | | | | |257| Model abstraction | | | | | |258| Persistence | | | | | |259| Git awareness | | | | | |260| Repository search | | | | | |261262For every architectural choice answer: What problem does this solve? How does each reference solve it? What are the trade-offs? What should KHAELOR do differently, and why?263264---265## 4. DESIGN PHILOSOPHY266267KHAELOR should feel like:268269```270Claude Code + OpenCode + Hermes + OpenHands271− accumulated complexity272+ a radically better terminal interface273```274275### Core architectural principle — a small kernel276277Conceptually:278279```python280while session.active:281 context = context_engine.build(session.state)282 response = model.generate(283 context=context,284 tools=tool_registry.available(session.state),285 )286 session.record(response)287 observations = executor.execute(response.actions)288 session.record(observations)289 if response.requests_completion:290 verify()291```292293The production implementation will require more sophistication — but the kernel must never become a god object. The kernel **coordinates**; it does not own everything.294295### Target system architecture296297```298 KHAELOR TUI299 │300 ▼301 ┌────────────────┐302 │ Session Engine │303 └───────┬────────┘304 │305 ▼306 ┌────────────────┐307 │ Agent Kernel │308 └───────┬────────┘309 │310 ┌──────────────────┼──────────────────┐311 │ │ │312 ▼ ▼ ▼313 Context Engine Tool Runtime Model Runtime314 │ │ │315 │ │ Anthropic API316 ▼ ▼317 Repository Index Workspace318 │319 ┌──────┴──────┐320 │ │321 Files Process322```323324Future systems (Memory, Skills, Subagents, Browser, MCP, remote execution) must be attachable **without rewriting the kernel** — but they are NOT V1 priorities, and future flexibility is not an excuse for premature abstraction.325326---327328## 5. TECHNOLOGY DECISION329330Determine the final language/runtime **after** Phase 0 — but strongly consider **TypeScript** for: rich terminal UI, async I/O, Anthropic SDK integration, packaging, cross-platform distribution, ecosystem, and OpenCode/OpenTUI learnings.331332- A Rust native component is acceptable **later** for performance-critical pieces. Avoid premature polyglot architecture.333- Ship as one easily installable CLI: `npm install -g khaelor` → `khaelor`.334- **No Electron. No web frontend.** KHAELOR V1 is terminal-native.335336---337338## 6. ANTHROPIC INTEGRATION339340### Anthropic-only, cleanly isolated341342KHAELOR V1 supports Anthropic models only, via the official Anthropic SDK. The model layer must nevertheless be isolated behind a single interface:343344```ts345interface ModelClient {346 stream(request: ModelRequest): AsyncIterable<ModelEvent>;347}348```349350Do NOT build a generic provider framework. Do NOT implement other providers. The reason for `ModelClient` is clean architecture, not multi-provider complexity.351352### Configuration353354```355khaelor356khaelor --model <anthropic-model>357```358359In-app: `/model` opens an elegant model selector; `/config` opens configuration.360361Configuration hierarchy (highest precedence first):362363```364CLI flags → project configuration → user configuration → environment → defaults365```366367Files:368369```370~/.khaelor/config.json # user371.khaelor/config.json # project372```373374Environment: `ANTHROPIC_API_KEY`.375376**Security requirements:**377- Never display secrets.378- Never write API keys or authorization headers to logs.379- If an API key is entered interactively, prefer secure OS storage (keychain) where practical.380381### Model configuration382383Do not hard-code a permanent model list — Anthropic model identifiers evolve. Allow configuration such as:384385```json386{387 "model": "configured-anthropic-model-id",388 "thinking": "adaptive",389 "maxOutputTokens": 16000390}391```392393`/model` should show current model, alternatives, thinking mode, and output budget. Model aliases may be supported.394395---396397## 7. STREAMING AND THE EVENT BUS398399### First-class streaming400401Streaming is native to the architecture. Never implement "request → wait → print huge response." Everything is event-driven:402403```404ModelStarted · TextDelta · ThinkingDelta · ToolCallStarted · ToolInputDelta405ToolStarted · ToolOutputDelta · ToolFinished · ModelFinished406```407408The UI consumes events. This is essential.409410### Typed event bus411412Use typed events throughout the system:413414```415SessionStarted · UserMessageCreated · ModelRequestStarted · ModelTextDelta416ModelThinkingDelta · ModelResponseCompleted · ToolRequested · ToolApproved417ToolStarted · ToolOutput · ToolCompleted · ToolFailed · FileRead · FileModified418ProcessStarted · ProcessOutput · ProcessExited · ContextCompacted419PermissionRequested · PermissionGranted · PermissionDenied420TaskCompleted · TaskFailed421```422423Events must be appendable to persistent session history where appropriate. The event log is the source of truth for session replay and resume.424425---426427## 8. SESSION ENGINE428429Agent intelligence and session lifecycle must remain separate:430431```432AgentKernel = reason and act433Session = lifecycle and history434Workspace = world435Tool = action436Model = intelligence backend437```438439Implement **persistent sessions early**.440441Commands: `/sessions` `/resume` `/new` `/rename` `/clear` — eventually `/branch` and `/rewind`.442443Session metadata: `id`, `title`, `project`, `createdAt`, `updatedAt`, `model`, `tokenUsage`, `cost`, `gitBranch`, `workingDirectory`.444445---446447## 9. WORKSPACE448449Create a clean workspace abstraction. V1 requires only `LocalWorkspace`:450451```ts452interface Workspace {453 cwd(): string;454 readFile(path: string): Promise<string>;455 writeFile(path: string, content: string): Promise<void>;456 exec(command: Command): Promise<ProcessResult>;457}458```459460Do not implement Docker/SSH yet — but prevent the core agent from depending directly on Node filesystem/process globals everywhere.461462---463464## 10. V1 TOOLS465466Keep the primitive tool set intentionally small. The model should have **powerful primitives**, not dozens of tiny tools.467468V1 tools: `read` · `write` · `edit` · `grep` · `glob` · `bash` · `process` (and potentially `git` after careful evaluation).469470### read471Line ranges; binary detection; file size guards; syntax metadata; efficient large-file handling. Rendered with file path header and line numbers.472473### write474Complete-file writes. Before overwrite: understand existing file state; detect external modification; keep event history. **All new source files must include the mandatory header (Absolute Rule #0).**475476### edit477One of the most important tools — study OpenCode and OpenHands editing implementations carefully. Requirements: exact replacements; robust patch application; useful failure messages; ambiguity detection; line-ending handling; indentation preservation; atomic writes. Provide a diff whenever possible.478479### grep480Fast textual repository search. Prefer native high-performance tools (ripgrep) where available. Return concise structured results. Never dump thousands of lines into model context.481482### glob483Efficient filesystem discovery (`**/*.ts`, `src/**/*.py`) with sensible ignore behavior. Respect `.gitignore` and `.khaelorignore` where appropriate.484485### bash vs process486Shell execution and long-running processes must not be conflated. Short commands → `bash`. Long-running commands → `process`.487488### Process manager489KHAELOR must be materially better than agents that treat every shell command as blocking.490491API: `process.start` · `process.list` · `process.read` · `process.write` · `process.stop`492493```494PROCESSES495● 3121 npm run dev running 04:32496● 3198 pytest running 00:18497○ 3012 npm test exited code 0498```499500The agent can: start a dev server → continue editing → inspect output → run tests → inspect the dev server again.501502---503504## 11. REPOSITORY INTELLIGENCE505506KHAELOR should understand a repository **without stuffing it into model context**. Build an incremental repository index.507508V1: filesystem map · git status · git diff · grep/ripgrep · file metadata · recently accessed files.509510Later (not V1): AST · symbols · references · imports · dependency graph · embeddings.511512Expose repository intelligence exclusively through the Context Engine.513514---515516## 12. CONTEXT ENGINE517518One of KHAELOR's most important components. `ContextEngine` decides what the model actually receives:519520```521SYSTEM identity · behavior · tools · project instructions522WORKING CONTEXT current request · recent turns · current actions · current failures523PROJECT CONTEXT relevant files · git state · repository structure524CHECKPOINT earlier session summary525```526527Do NOT simply append everything forever.528529### Context compaction530531Implement context-pressure awareness. Before context becomes dangerous, create a structured checkpoint:532533```yaml534objective: ...535completed: [...]536current_state: ...537important_files:538 - path: ...539 reason: ...540changes: [...]541failed_attempts: [...]542decisions: [...]543running_processes: [...]544next_steps: [...]545```546547Preserve important raw evidence when summarization could destroy necessary details. Compaction should feel invisible unless the user asks to inspect it (`/context`, `/compact`).548549### Project instructions550551Automatically discover project-level instructions. Support `KHAELOR.md`, with potential compatibility for `CLAUDE.md` and `AGENTS.md` — but define a clear precedence order:552553```554~/.khaelor/KHAELOR.md → repository/KHAELOR.md → nested/directory/KHAELOR.md555```556557Instructions closer to the current working path refine global instructions.558559---560561## 13. PERMISSION SYSTEM562563Permissions must be powerful but not annoying. Evaluate actions by **capabilities**, not arbitrary tool names:564565```566file.read · file.write · process.execute · network.access · git.modify · filesystem.external567```568569Policy values: `allow` · `ask` · `deny`. User-configurable, e.g.:570571```json572{573 "permissions": {574 "file.read": "allow",575 "file.write.project": "allow",576 "process.execute": "allow",577 "filesystem.outsideProject": "ask"578 }579}580```581582Keep destructive or unusually broad actions visible to the user.583584### Permission UI585586Never show ugly `Allow? y/n` prompts. Use an elegant inline panel:587588```589╭─ KHAELOR requests permission ─────────────────────╮590│ Run │591│ npm install │592│ │593│ Working directory │594│ ~/dev/project │595│ │596│ [ Enter ] Allow once │597│ [ A ] Always allow in this project │598│ [ Esc ] Deny │599╰───────────────────────────────────────────────────╯600```601602The interaction should take milliseconds.603604---605## 14. THE TERMINAL UI606607**This section is non-negotiable.** Do not create a generic `> prompt / AI: response` REPL. KHAELOR should feel like a modern interactive computing environment.608609### UI design principles610611Be: minimal · dense when needed · calm · extremely fast · keyboard-native · beautiful without being decorative · information-rich · predictable.612613Avoid: rainbow colors · excessive borders · ASCII gimmicks · constant animations · emoji everywhere · huge banners · screen flicker.614615Visual hierarchy comes from **spacing, typography, subtle color, indentation, and status** — not noise.616617### Startup experience618619`khaelor` starts nearly instantly:620621```622 KHAELOR623 ~/dev/my-project · main624 Claude · configured model625────────────────────────────────────────────────────626 What do you want to build?627 ❯ _628```629630No giant ASCII logo. No multi-second animation. No startup log spam.631632### Composer (highest-priority component)633634Features: multiline editing · cursor and word navigation · selection · copy/paste · history · undo/redo if feasible · slash commands · file mentions · fuzzy autocomplete · shell shortcuts · drag/drop paths where the terminal permits · message queueing while the agent works · image attachments later if useful.635636### File mentions637638Typing `@` opens fuzzy repository search:639640```641@agent642 src/kernel/agent.ts643 src/agents/agent-runtime.ts644 tests/agent.test.ts645```646647Selection inserts a **structured file reference**, not necessarily the entire file. Support `@src/kernel/agent.ts`; future syntax `@src/kernel/agent.ts:40-90`.648649### Slash command palette650651Typing `/` opens: `/model` `/config` `/permissions` `/context` `/sessions` `/resume` `/new` `/compact` `/cost` `/status` `/diff` `/processes` `/help` `/quit` — with fuzzy filtering, keyboard navigation, and descriptions.652653### Universal command palette654655`Ctrl+K` opens a universal palette (Change model · View diff · Open sessions · View context · Manage permissions · Show processes · Compact context · New session). Users should not need to memorize commands.656657### Status bar658659Persistent but subtle:660661```662 main +4 −1 │ Claude model │ context 31% │ $0.42663```664665Candidates: git branch · dirty files · model · context utilization · session cost · background processes · mode. Do not overload it.666667### Agent states668669The user must always understand what KHAELOR is doing. States: thinking · reading · searching · editing · running · waiting · verifying · idle. Use one compact dynamic status line:670671```672● Searching repository · 2.3s673● Editing src/kernel/agent.ts674● Running tests675```676677Do not spam the conversation with transient status messages.678679### Tool call presentation680681Collapsed by default:682683```684▸ Read src/kernel/agent.ts685▸ Search "ContextEngine" · 14 matches686▸ Edit src/context/engine.ts · +31 −12687▸ Run npm test · passed688```689690Expandable on demand; the user can toggle detail level.691692### Edit presentation and diff viewer693694Never print just "Edited file." Show `✓ src/context/engine.ts +31 −12` with instant diff expansion (e.g. key `d`).695696Build a beautiful terminal diff viewer (`/diff`): side-by-side when width permits; unified fallback; syntax highlighting; added/removed counts; file navigation; scrolling; accept/revert hooks in the future.697698### Streaming text UX699700Model text streams smoothly. Avoid terminal flicker, scroll jumps, full-screen re-renders, and cursor instability. The input area stays stable. Long tool output must not destroy the conversation layout.701702### Markdown rendering703704Render high-quality headings, bold, italic, inline code, code blocks, lists, tables, links, and quotes. Code blocks require syntax highlighting, horizontal scrolling or intelligent wrapping, and copy-friendly output. Never sacrifice terminal selection/copy behavior for visual tricks.705706### Thinking display707708When Anthropic surfaces reasoning through the API in a permitted way, keep its UI compact and consistent with API-permitted behavior. Do not build the product around exposing hidden reasoning. The interface primarily communicates: what the agent is doing · what tools it uses · what changed · what remains.709710### Interruption711712The user must be able to interrupt immediately (e.g. `Esc`). Cancellation propagates through model stream → tool execution → processes → agent loop, **without corrupting the session**.713714### Steering while working715716A major differentiator: the user can type while KHAELOR works. Steering messages are queued or safely injected at an appropriate boundary, displayed as `Queued instruction`. This requires careful concurrency design.717718### Shell mode719720Consider `!git status` in the composer to execute a shell command directly; results display in the conversation and may optionally become agent context.721722---723724## 15. TRANSPARENCY: COST AND CONTEXT725726### Cost visibility727728`/cost` shows session input/output tokens, cache reads/writes, and estimated cost — from **actual API usage metadata**. Never invent token usage.729730### Context inspector731732`/context` shows a budget breakdown (system, project instructions, conversation, repository context, tool observations, reserved output, total) and which files are materially represented in context. This makes KHAELOR understandable.733734---735736## 16. GIT AWARENESS737738KHAELOR must always understand: current branch · working tree changes · untracked files · existing user changes.739740- Never assume an existing diff belongs to KHAELOR.741- Record baseline state before edits; clearly identify what KHAELOR changed afterward.742- Do not auto-commit unless explicitly requested.743- Protect user work at all times.744745---746747## 17. ERRORS, THE AGENT LOOP, AND COMPLETION748749### Error design750751Bad: `Error: command failed.`752753Good:754755```756npm test failed7572 tests failed758src/context/engine.test.ts759 context compaction preserves running processes760KHAELOR is inspecting the failure.761```762763The agent normally consumes recoverable tool errors itself rather than making the user debug the agent.764765### Agent loop766767The agent iterates naturally: understand → inspect → plan internally → edit → run → observe → fix → verify → finish. Do not stop after writing code if verification is possible.768769### Completion standard770771KHAELOR never claims completion merely because the model generated a confident sentence. Before completing coding work, inspect applicable evidence: tests · type checking · linting · build · git diff · requirements · **file header compliance (Absolute Rule #0)**.772773Only run checks relevant to the repository — do not blindly launch massive unrelated test suites.774775Internally represent completion rigorously:776777```ts778interface CompletionEvidence {779 objective: string;780 changedFiles: string[];781 checks: CheckResult[];782 unresolvedIssues: string[];783}784```785786The final user-facing response can remain concise.787788### Response style789790KHAELOR behaves like an elite technical collaborator. During work: short, specific, action-oriented. Avoid "I'll now…", "Next I'll…", "Great!", "Absolutely!". Prefer:791792```793I found the state leak in SessionStore. Fixing that before touching the renderer.794```795796At completion:797798```799Implemented persistent session recovery.800Changed801- SessionStore now journals events atomically.802- Startup restores interrupted sessions.803- Added recovery tests.804Checks805- 148 tests passed806- typecheck passed807```808809---810811## 18. PERFORMANCE812813Performance is a feature. Measure: cold startup · input latency · render latency · tool dispatch · repository search · memory usage · session load. Do not optimize on intuition — create benchmarks where appropriate. The TUI must feel instantaneous even when the LLM requires time.814815**No spinner-driven UX.** The best latency UX is useful progress. Instead of `⠋ Thinking...`, prefer `● Reading src/session/store.ts` or `● Running tests · 41/148` when that information is actually known. Never fabricate progress.816817When latency appears, determine whether it comes from: model · network · filesystem · repository indexing · rendering · architecture. **Measure first. Optimize the correct layer.**818819---820821## 19. CONFIGURATION UX, THEMING, ACCESSIBILITY, PLATFORMS822823### Configuration UX824825`/config` opens a keyboard-navigable panel (model, agent behavior, interface, permissions). Configuration must also be editable as a file.826827### Theming828829Support terminal color capabilities intelligently. Ship **one exceptional default theme first**; `/theme` can come later. Respect `NO_COLOR`, terminal capabilities, and light/dark backgrounds where detectable. Do not prioritize theme customization over usability.830831### Accessibility832833Never communicate state through color alone — symbols and text must retain meaning in monochrome terminals. Ensure readable contrast. Keyboard-only use must be complete.834835### Cross-platform836837Primary targets: macOS and Linux. Design so Windows remains possible. Be careful about shell assumptions, path separators, PTY handling, signals, and terminal capabilities.838839### Logging840841Developer logs never pollute the TUI. Use `~/.khaelor/logs/`. Support `khaelor --debug`. Never log API keys, secret environment values, or authorization headers — redact sensitive values.842843---844845## 20. PROJECT STRUCTURE846847Derive the final language-specific structure after Phase 0. Conceptually:848849```850src/851├── cli/ app · commands · keyboard · lifecycle852├── tui/ components/ · composer/ · markdown/ · diff/ · tool-view/ · palette/ · status/853├── agent/ kernel · state · executor · completion854├── anthropic/ client · streaming · messages · usage855├── session/ session · events · store · checkpoint856├── context/ engine · compaction · budget · project-context857├── tools/ registry · read · write · edit · grep · glob · bash · process858├── workspace/ local859├── repository/ index · git · search860├── permissions/ policy · evaluator861├── config/ schema · loader · defaults862└── shared/863```864865Avoid circular dependencies. **Every file in `src/` carries the mandatory author header.**866867---868869## 21. TESTING870871Build tests while implementing.872873**Unit:** tool parsing · event reducer · context budgeting · config resolution · permission rules · file editing · process lifecycle · session persistence · **header lint check**.874875**Integration:** Anthropic streaming · tool execution loop · session resume · interruption · context compaction · repository modification.876877**TUI (where practical):** keyboard navigation · resize · long output · streaming · dialogs · permission requests · model selector · slash palette.878879**Golden/snapshot:** tool rendering · markdown · diffs · error panels · status lines. Do not make snapshots so broad that every intentional UI improvement becomes painful.880881---882883## 22. DOGFOODING AND BENCHMARKING884885### Dogfooding886887KHAELOR must be developed **using KHAELOR** as soon as it is sufficiently functional. Keep `docs/DOGFOOD_NOTES.md` recording friction, unexpected behavior, latency, UI annoyances, agent failures, context failures, and permission annoyances. Treat small UX friction as real bugs.888889### Benchmark UX against competitors890891After the first functional TUI exists, manually compare equivalent workflows against Claude Code, OpenCode, Hermes Agent, and OpenHands CLI. Do not copy visual appearance blindly.892893Measure workflows: start agent · select model · ask a repository question · inspect a tool call · approve a command · interrupt · resume · inspect diff · switch session · find file · run a background process · inspect context.894895Count: keystrokes · latency · screen noise · modal interruptions · clarity. KHAELOR should deliberately improve these workflows.896897---898899## 23. V1 SCOPE900901**V1 MUST include:**902903✓ exceptional TUI · ✓ Anthropic API · ✓ Anthropic model configuration · ✓ streaming · ✓ agent loop · ✓ persistent sessions · ✓ local workspace · ✓ read · ✓ write · ✓ edit · ✓ grep · ✓ glob · ✓ bash · ✓ background process manager · ✓ permission system · ✓ repository awareness · ✓ git awareness · ✓ context management · ✓ context compaction · ✓ slash commands · ✓ file mentions · ✓ command palette · ✓ model selector · ✓ diff viewer · ✓ usage/cost display · ✓ interruption · ✓ queued steering · ✓ tests · ✓ documentation · ✓ **mandatory file headers + enforcement check**904905**NOT V1 — do not let these derail the release:**906907OpenAI · Gemini · OpenRouter · local models · MCP · browser automation · computer vision · Docker · SSH · cloud execution · mobile app · web UI · multi-user server · full memory system · self-generated skills · complex multi-agent orchestration · marketplace · plugins.908909Design clean boundaries for them. Do not implement them yet.910911### Future architecture912913Future KHAELOR may gain: Subagents → Memory → Skills → automatic skill extraction → Browser → MCP → SSH/Docker → distributed execution. The V1 architecture must not make these impossible — but future flexibility is not an excuse for premature abstraction.914915---916917## 24. DEVELOPMENT PHASES918919**Phase 0 — Research.** Deliver `docs/research/*`. No major production implementation before this is complete.920921**Phase 1 — Architecture.** Deliver `ARCHITECTURE.md`, `EVENT_MODEL.md`, `TUI_DESIGN.md`, `TOOL_PROTOCOL.md`, `PERMISSION_MODEL.md`. Build small prototypes when necessary to validate choices.922923**Phase 2 — Terminal UI shell.** Startup, layout, composer, markdown, keyboard handling, stream rendering, status area, slash palette, command palette. The interface should already feel excellent using mocked model events.924925**Phase 3 — Anthropic integration.** Authentication, model config, streaming, tool calling, usage accounting, errors, retry, cancellation.926927**Phase 4 — Agent loop.** `AgentKernel`, `ToolRegistry`, `Executor`, `LocalWorkspace`, events.928929**Phase 5 — Core tools.** read, write, edit, grep, glob, bash, process.930931**Phase 6 — Sessions + context.** Persistent events, resume, context engine, compaction, checkpointing.932933**Phase 7 — Repository intelligence.** Git awareness, repository map, efficient search, file mentions, context retrieval.934935**Phase 8 — Polish.** Obsess over latency, keyboard workflows, tool rendering, diffs, permission UX, interruptions, long sessions, errors, resize behavior.936937---938939## 25. DISCIPLINE940941For every substantial component:9429431. Inspect the relevant reference implementation9442. Understand its trade-offs9453. Document the KHAELOR decision9464. Implement a minimal clean version — **with the mandatory file header**9475. Test9486. Dogfood9497. Simplify950951Do not create complexity merely because another agent framework has it.952953**Architecture rule.** Whenever tempted to add something to `AgentKernel`, ask: *can this be a service around the kernel?* Usually yes.954955**UX rule.** Whenever something technically works, ask: *is this the best terminal interaction we can design?* If no, the feature is not finished.956957**Speed rule.** When latency appears, measure first, then optimize the correct layer (model / network / filesystem / indexing / rendering / architecture).958959**Quality rule.** Never declare something complete merely because it compiles. For meaningful changes: inspect → test → use → verify.960961---962963## 26. FINAL PRODUCT STANDARD964965KHAELOR should eventually make someone who regularly uses Claude Code, OpenCode, Hermes, and OpenHands think:966967> *Why doesn't every terminal agent work like this?*968969The first version does not need every feature those systems possess. It needs something harder: **a fundamentally better core experience**. Build the smallest architecture capable of delivering that experience exceptionally well.970971---972973## 27. BEGIN974975Your first task is NOT to start coding KHAELOR. Your first task is:9769771. Inspect the current environment and repository9782. Obtain or locate the reference repositories9793. Deeply analyze Hermes Agent9804. Deeply analyze OpenCode9815. Deeply analyze OpenHands and its Software Agent SDK9826. Inspect mini-SWE-agent for architectural minimalism9837. Write the required research documents9848. Derive KHAELOR's architectural decisions9859. Produce `ARCHITECTURE.md` and `TUI_DESIGN.md`98610. Only then begin implementation987988Do not stop at superficial README analysis. Trace real code paths. Read actual implementation files. Follow imports. Find the agent loops, the tool registries, the session state, the render loops, the permission checks, context construction, process execution, and persistence. Understand **why** each system works the way it does.989990Then build something better.991992---993994**Understand first. Design second. Implement third.**995996*Author: Simon-Pierre Boucher · contact@spboucher.ai*997