# KHAELOR — CLAUDE.md > **Project:** KHAELOR > **Command:** `khaelor` > **Identity:** A terminal-native autonomous engineering agent powered by Anthropic. > **Internal principle:** Understand first. Design second. Implement third. > **Author / Maintainer:** Simon-Pierre Boucher — contact@spboucher.ai --- ## 1. MISSION You are building **KHAELOR**, a next-generation autonomous terminal agent. KHAELOR is **not** another Claude Code clone. It must combine the strongest architectural and UX ideas found in: - Claude Code - Hermes Agent - OpenCode - OpenHands / OpenHands Software Agent SDK - mini-SWE-agent (where its minimalism is useful) …while developing its **own architecture and identity**. **Long-term goal:** build the best terminal-native AI agent interface in existence. KHAELOR 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. The first release must focus obsessively on: 1. Exceptional terminal UX 2. Excellent Anthropic integration 3. Reliable agent execution 4. Clean architecture 5. Context efficiency 6. Observable actions 7. Fast interaction 8. Safe and understandable permissions 9. Persistent sessions 10. Strong repository intelligence --- ## 2. ABSOLUTE RULES (NON-NEGOTIABLE) These 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. ### ABSOLUTE RULE #0 — MANDATORY FILE HEADERS **Every source code file created or substantially rewritten in this project MUST begin with an author header.** Required fields: - **Author:** Simon-Pierre Boucher - **Contact:** contact@spboucher.ai - **File:** relative path from repository root - **Description:** one line describing the file's purpose #### TypeScript / JavaScript (`.ts`, `.tsx`, `.js`, `.mjs`, `.cjs`) ```ts /** * KHAELOR * File: src/agent/kernel.ts * Description: Minimal agent kernel — coordinates context, model, and tool execution. * * Author: Simon-Pierre Boucher * Contact: contact@spboucher.ai */ ``` #### Shell scripts (`.sh`) ```bash #!/usr/bin/env bash # KHAELOR # File: scripts/build.sh # Description: Production build script. # # Author: Simon-Pierre Boucher # Contact: contact@spboucher.ai ``` #### Rust (`.rs`) — if/when a native component exists ```rust //! KHAELOR //! File: native/src/lib.rs //! Description: Performance-critical native component. //! //! Author: Simon-Pierre Boucher //! Contact: contact@spboucher.ai ``` #### Markdown documentation (`.md`) — when authored as a deliverable ```md ``` #### Exceptions - 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. - Generated files must carry the header in their generator template, plus a `Generated file — do not edit` line. - Vendored/reference code under `references/` keeps its original authorship and licenses. **Never** apply this header to third-party code. #### Enforcement - 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. - The header check is part of the definition of done for every phase. - When editing an existing file that lacks a header, add it. ### ABSOLUTE RULE #1 — UNDERSTAND BEFORE BUILDING Do 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. The rule is: ``` UNDERSTAND FIRST → DESIGN SECOND → IMPLEMENT THIRD ``` ### ABSOLUTE RULE #2 — THE TERMINAL IS THE PRODUCT The 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**. ### ABSOLUTE RULE #3 — SMALL KERNEL The 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. ### ABSOLUTE RULE #4 — NEVER FABRICATE Never 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). ### ABSOLUTE RULE #5 — PROTECT USER WORK Never assume an existing diff belongs to KHAELOR. Record baseline git state before edits. Never auto-commit unless explicitly requested. Never destroy uncommitted user changes. --- ## 3. PHASE 0 — DEEP REPOSITORY ANALYSIS (MANDATORY) Before creating the production architecture, independently inspect the **current source code** of: - https://github.com/NousResearch/hermes-agent - https://github.com/anomalyco/opencode - https://github.com/OpenHands/OpenHands - https://github.com/OpenHands/software-agent-sdk - https://github.com/SWE-agent/mini-swe-agent (where useful) Do not merely read READMEs. Clone the repositories into a reference directory **outside** KHAELOR's production source tree: ``` references/ hermes-agent/ opencode/ openhands/ openhands-agent-sdk/ mini-swe-agent/ ``` These 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. **Required deliverables before any major implementation:** ``` docs/research/ HERMES_ANALYSIS.md OPENCODE_ANALYSIS.md OPENHANDS_ANALYSIS.md MINI_SWE_ANALYSIS.md COMPARATIVE_ARCHITECTURE.md KHAELOR_ARCHITECTURE_DECISIONS.md ``` For 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. ### 3.1 Hermes Agent analysis Investigate at minimum: **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. **Context management.** Prompt construction; context compression; context-window pressure handling; prompt caching; conversation summarization; memory injection; system prompt construction. **Memory.** Persistent memory; session memory; memory providers; memory search; cross-session retrieval; how memories are written and selected. **Skills.** Skill format; discovery; loading; automatic creation; improvement; persistence; context injection. **Terminal execution.** Local execution; process lifecycle; Docker; SSH; remote execution abstractions; command output; timeouts; async processes. **Subagents.** Creation; isolation; context inheritance; result propagation; concurrency; lifecycle; recursion limits. **TUI.** Layout; rendering; streaming; keyboard navigation; tool rendering; session selection; model switching; status presentation; long-output handling. Record explicitly: WHAT HERMES DOES VERY WELL / WHAT HERMES DOES POORLY / WHAT KHAELOR SHOULD ADOPT / WHAT KHAELOR SHOULD NOT COPY. ### 3.2 OpenCode analysis OpenCode is particularly important for KHAELOR because of its terminal-first design. Perform the same depth of analysis, covering: **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. **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. **State.** Session persistence; conversation state; project state; working directory handling; configuration; per-project settings. **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. **Permission UX.** Rules; allow/ask/deny behavior; scope; persistence; TUI confirmation interactions. **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. ### 3.3 OpenHands analysis OpenHands matters most architecturally. Study the separation between: | Concern | OpenHands concept | |---|---| | Intelligence | Agent | | Lifecycle | Conversation / Session | | Environment | Workspace | | Actions | Tools | | History | Events / EventLog | | Safety | Security analyzers / confirmation | This 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. ### 3.4 mini-SWE-agent analysis Study mini-SWE-agent for one question: **How little agent scaffolding is actually necessary?** Locate 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. ### 3.5 Comparative architecture Create `docs/research/COMPARATIVE_ARCHITECTURE.md` with a decision matrix: | Capability | Hermes | OpenCode | OpenHands | mini-SWE | KHAELOR Decision | |---|---|---|---|---|---| | Agent loop | | | | | | | TUI | | | | | | | Tools | | | | | | | Sessions | | | | | | | Context | | | | | | | Memory | | | | | | | Permissions | | | | | | | Workspace | | | | | | | Events | | | | | | | Subagents | | | | | | | Processes | | | | | | | Model abstraction | | | | | | | Persistence | | | | | | | Git awareness | | | | | | | Repository search | | | | | | For 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? --- ## 4. DESIGN PHILOSOPHY KHAELOR should feel like: ``` Claude Code + OpenCode + Hermes + OpenHands − accumulated complexity + a radically better terminal interface ``` ### Core architectural principle — a small kernel Conceptually: ```python while session.active: context = context_engine.build(session.state) response = model.generate( context=context, tools=tool_registry.available(session.state), ) session.record(response) observations = executor.execute(response.actions) session.record(observations) if response.requests_completion: verify() ``` The production implementation will require more sophistication — but the kernel must never become a god object. The kernel **coordinates**; it does not own everything. ### Target system architecture ``` KHAELOR TUI │ ▼ ┌────────────────┐ │ Session Engine │ └───────┬────────┘ │ ▼ ┌────────────────┐ │ Agent Kernel │ └───────┬────────┘ │ ┌──────────────────┼──────────────────┐ │ │ │ ▼ ▼ ▼ Context Engine Tool Runtime Model Runtime │ │ │ │ │ Anthropic API ▼ ▼ Repository Index Workspace │ ┌──────┴──────┐ │ │ Files Process ``` Future 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. --- ## 5. TECHNOLOGY DECISION Determine 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. - A Rust native component is acceptable **later** for performance-critical pieces. Avoid premature polyglot architecture. - Ship as one easily installable CLI: `npm install -g khaelor` → `khaelor`. - **No Electron. No web frontend.** KHAELOR V1 is terminal-native. --- ## 6. ANTHROPIC INTEGRATION ### Anthropic-only, cleanly isolated KHAELOR V1 supports Anthropic models only, via the official Anthropic SDK. The model layer must nevertheless be isolated behind a single interface: ```ts interface ModelClient { stream(request: ModelRequest): AsyncIterable; } ``` Do NOT build a generic provider framework. Do NOT implement other providers. The reason for `ModelClient` is clean architecture, not multi-provider complexity. ### Configuration ``` khaelor khaelor --model ``` In-app: `/model` opens an elegant model selector; `/config` opens configuration. Configuration hierarchy (highest precedence first): ``` CLI flags → project configuration → user configuration → environment → defaults ``` Files: ``` ~/.khaelor/config.json # user .khaelor/config.json # project ``` Environment: `ANTHROPIC_API_KEY`. **Security requirements:** - Never display secrets. - Never write API keys or authorization headers to logs. - If an API key is entered interactively, prefer secure OS storage (keychain) where practical. ### Model configuration Do not hard-code a permanent model list — Anthropic model identifiers evolve. Allow configuration such as: ```json { "model": "configured-anthropic-model-id", "thinking": "adaptive", "maxOutputTokens": 16000 } ``` `/model` should show current model, alternatives, thinking mode, and output budget. Model aliases may be supported. --- ## 7. STREAMING AND THE EVENT BUS ### First-class streaming Streaming is native to the architecture. Never implement "request → wait → print huge response." Everything is event-driven: ``` ModelStarted · TextDelta · ThinkingDelta · ToolCallStarted · ToolInputDelta ToolStarted · ToolOutputDelta · ToolFinished · ModelFinished ``` The UI consumes events. This is essential. ### Typed event bus Use typed events throughout the system: ``` SessionStarted · UserMessageCreated · ModelRequestStarted · ModelTextDelta ModelThinkingDelta · ModelResponseCompleted · ToolRequested · ToolApproved ToolStarted · ToolOutput · ToolCompleted · ToolFailed · FileRead · FileModified ProcessStarted · ProcessOutput · ProcessExited · ContextCompacted PermissionRequested · PermissionGranted · PermissionDenied TaskCompleted · TaskFailed ``` Events must be appendable to persistent session history where appropriate. The event log is the source of truth for session replay and resume. --- ## 8. SESSION ENGINE Agent intelligence and session lifecycle must remain separate: ``` AgentKernel = reason and act Session = lifecycle and history Workspace = world Tool = action Model = intelligence backend ``` Implement **persistent sessions early**. Commands: `/sessions` `/resume` `/new` `/rename` `/clear` — eventually `/branch` and `/rewind`. Session metadata: `id`, `title`, `project`, `createdAt`, `updatedAt`, `model`, `tokenUsage`, `cost`, `gitBranch`, `workingDirectory`. --- ## 9. WORKSPACE Create a clean workspace abstraction. V1 requires only `LocalWorkspace`: ```ts interface Workspace { cwd(): string; readFile(path: string): Promise; writeFile(path: string, content: string): Promise; exec(command: Command): Promise; } ``` Do not implement Docker/SSH yet — but prevent the core agent from depending directly on Node filesystem/process globals everywhere. --- ## 10. V1 TOOLS Keep the primitive tool set intentionally small. The model should have **powerful primitives**, not dozens of tiny tools. V1 tools: `read` · `write` · `edit` · `grep` · `glob` · `bash` · `process` (and potentially `git` after careful evaluation). ### read Line ranges; binary detection; file size guards; syntax metadata; efficient large-file handling. Rendered with file path header and line numbers. ### write Complete-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).** ### edit One 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. ### grep Fast textual repository search. Prefer native high-performance tools (ripgrep) where available. Return concise structured results. Never dump thousands of lines into model context. ### glob Efficient filesystem discovery (`**/*.ts`, `src/**/*.py`) with sensible ignore behavior. Respect `.gitignore` and `.khaelorignore` where appropriate. ### bash vs process Shell execution and long-running processes must not be conflated. Short commands → `bash`. Long-running commands → `process`. ### Process manager KHAELOR must be materially better than agents that treat every shell command as blocking. API: `process.start` · `process.list` · `process.read` · `process.write` · `process.stop` ``` PROCESSES ● 3121 npm run dev running 04:32 ● 3198 pytest running 00:18 ○ 3012 npm test exited code 0 ``` The agent can: start a dev server → continue editing → inspect output → run tests → inspect the dev server again. --- ## 11. REPOSITORY INTELLIGENCE KHAELOR should understand a repository **without stuffing it into model context**. Build an incremental repository index. V1: filesystem map · git status · git diff · grep/ripgrep · file metadata · recently accessed files. Later (not V1): AST · symbols · references · imports · dependency graph · embeddings. Expose repository intelligence exclusively through the Context Engine. --- ## 12. CONTEXT ENGINE One of KHAELOR's most important components. `ContextEngine` decides what the model actually receives: ``` SYSTEM identity · behavior · tools · project instructions WORKING CONTEXT current request · recent turns · current actions · current failures PROJECT CONTEXT relevant files · git state · repository structure CHECKPOINT earlier session summary ``` Do NOT simply append everything forever. ### Context compaction Implement context-pressure awareness. Before context becomes dangerous, create a structured checkpoint: ```yaml objective: ... completed: [...] current_state: ... important_files: - path: ... reason: ... changes: [...] failed_attempts: [...] decisions: [...] running_processes: [...] next_steps: [...] ``` Preserve important raw evidence when summarization could destroy necessary details. Compaction should feel invisible unless the user asks to inspect it (`/context`, `/compact`). ### Project instructions Automatically discover project-level instructions. Support `KHAELOR.md`, with potential compatibility for `CLAUDE.md` and `AGENTS.md` — but define a clear precedence order: ``` ~/.khaelor/KHAELOR.md → repository/KHAELOR.md → nested/directory/KHAELOR.md ``` Instructions closer to the current working path refine global instructions. --- ## 13. PERMISSION SYSTEM Permissions must be powerful but not annoying. Evaluate actions by **capabilities**, not arbitrary tool names: ``` file.read · file.write · process.execute · network.access · git.modify · filesystem.external ``` Policy values: `allow` · `ask` · `deny`. User-configurable, e.g.: ```json { "permissions": { "file.read": "allow", "file.write.project": "allow", "process.execute": "allow", "filesystem.outsideProject": "ask" } } ``` Keep destructive or unusually broad actions visible to the user. ### Permission UI Never show ugly `Allow? y/n` prompts. Use an elegant inline panel: ``` ╭─ KHAELOR requests permission ─────────────────────╮ │ Run │ │ npm install │ │ │ │ Working directory │ │ ~/dev/project │ │ │ │ [ Enter ] Allow once │ │ [ A ] Always allow in this project │ │ [ Esc ] Deny │ ╰───────────────────────────────────────────────────╯ ``` The interaction should take milliseconds. --- ## 14. THE TERMINAL UI **This section is non-negotiable.** Do not create a generic `> prompt / AI: response` REPL. KHAELOR should feel like a modern interactive computing environment. ### UI design principles Be: minimal · dense when needed · calm · extremely fast · keyboard-native · beautiful without being decorative · information-rich · predictable. Avoid: rainbow colors · excessive borders · ASCII gimmicks · constant animations · emoji everywhere · huge banners · screen flicker. Visual hierarchy comes from **spacing, typography, subtle color, indentation, and status** — not noise. ### Startup experience `khaelor` starts nearly instantly: ``` KHAELOR ~/dev/my-project · main Claude · configured model ──────────────────────────────────────────────────── What do you want to build? ❯ _ ``` No giant ASCII logo. No multi-second animation. No startup log spam. ### Composer (highest-priority component) Features: 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. ### File mentions Typing `@` opens fuzzy repository search: ``` @agent src/kernel/agent.ts src/agents/agent-runtime.ts tests/agent.test.ts ``` Selection inserts a **structured file reference**, not necessarily the entire file. Support `@src/kernel/agent.ts`; future syntax `@src/kernel/agent.ts:40-90`. ### Slash command palette Typing `/` opens: `/model` `/config` `/permissions` `/context` `/sessions` `/resume` `/new` `/compact` `/cost` `/status` `/diff` `/processes` `/help` `/quit` — with fuzzy filtering, keyboard navigation, and descriptions. ### Universal command palette `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. ### Status bar Persistent but subtle: ``` main +4 −1 │ Claude model │ context 31% │ $0.42 ``` Candidates: git branch · dirty files · model · context utilization · session cost · background processes · mode. Do not overload it. ### Agent states The user must always understand what KHAELOR is doing. States: thinking · reading · searching · editing · running · waiting · verifying · idle. Use one compact dynamic status line: ``` ● Searching repository · 2.3s ● Editing src/kernel/agent.ts ● Running tests ``` Do not spam the conversation with transient status messages. ### Tool call presentation Collapsed by default: ``` ▸ Read src/kernel/agent.ts ▸ Search "ContextEngine" · 14 matches ▸ Edit src/context/engine.ts · +31 −12 ▸ Run npm test · passed ``` Expandable on demand; the user can toggle detail level. ### Edit presentation and diff viewer Never print just "Edited file." Show `✓ src/context/engine.ts +31 −12` with instant diff expansion (e.g. key `d`). Build 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. ### Streaming text UX Model 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. ### Markdown rendering Render 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. ### Thinking display When 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. ### Interruption The user must be able to interrupt immediately (e.g. `Esc`). Cancellation propagates through model stream → tool execution → processes → agent loop, **without corrupting the session**. ### Steering while working A 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. ### Shell mode Consider `!git status` in the composer to execute a shell command directly; results display in the conversation and may optionally become agent context. --- ## 15. TRANSPARENCY: COST AND CONTEXT ### Cost visibility `/cost` shows session input/output tokens, cache reads/writes, and estimated cost — from **actual API usage metadata**. Never invent token usage. ### Context inspector `/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. --- ## 16. GIT AWARENESS KHAELOR must always understand: current branch · working tree changes · untracked files · existing user changes. - Never assume an existing diff belongs to KHAELOR. - Record baseline state before edits; clearly identify what KHAELOR changed afterward. - Do not auto-commit unless explicitly requested. - Protect user work at all times. --- ## 17. ERRORS, THE AGENT LOOP, AND COMPLETION ### Error design Bad: `Error: command failed.` Good: ``` npm test failed 2 tests failed src/context/engine.test.ts context compaction preserves running processes KHAELOR is inspecting the failure. ``` The agent normally consumes recoverable tool errors itself rather than making the user debug the agent. ### Agent loop The agent iterates naturally: understand → inspect → plan internally → edit → run → observe → fix → verify → finish. Do not stop after writing code if verification is possible. ### Completion standard KHAELOR 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)**. Only run checks relevant to the repository — do not blindly launch massive unrelated test suites. Internally represent completion rigorously: ```ts interface CompletionEvidence { objective: string; changedFiles: string[]; checks: CheckResult[]; unresolvedIssues: string[]; } ``` The final user-facing response can remain concise. ### Response style KHAELOR behaves like an elite technical collaborator. During work: short, specific, action-oriented. Avoid "I'll now…", "Next I'll…", "Great!", "Absolutely!". Prefer: ``` I found the state leak in SessionStore. Fixing that before touching the renderer. ``` At completion: ``` Implemented persistent session recovery. Changed - SessionStore now journals events atomically. - Startup restores interrupted sessions. - Added recovery tests. Checks - 148 tests passed - typecheck passed ``` --- ## 18. PERFORMANCE Performance 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. **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. When latency appears, determine whether it comes from: model · network · filesystem · repository indexing · rendering · architecture. **Measure first. Optimize the correct layer.** --- ## 19. CONFIGURATION UX, THEMING, ACCESSIBILITY, PLATFORMS ### Configuration UX `/config` opens a keyboard-navigable panel (model, agent behavior, interface, permissions). Configuration must also be editable as a file. ### Theming Support 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. ### Accessibility Never communicate state through color alone — symbols and text must retain meaning in monochrome terminals. Ensure readable contrast. Keyboard-only use must be complete. ### Cross-platform Primary targets: macOS and Linux. Design so Windows remains possible. Be careful about shell assumptions, path separators, PTY handling, signals, and terminal capabilities. ### Logging Developer logs never pollute the TUI. Use `~/.khaelor/logs/`. Support `khaelor --debug`. Never log API keys, secret environment values, or authorization headers — redact sensitive values. --- ## 20. PROJECT STRUCTURE Derive the final language-specific structure after Phase 0. Conceptually: ``` src/ ├── cli/ app · commands · keyboard · lifecycle ├── tui/ components/ · composer/ · markdown/ · diff/ · tool-view/ · palette/ · status/ ├── agent/ kernel · state · executor · completion ├── anthropic/ client · streaming · messages · usage ├── session/ session · events · store · checkpoint ├── context/ engine · compaction · budget · project-context ├── tools/ registry · read · write · edit · grep · glob · bash · process ├── workspace/ local ├── repository/ index · git · search ├── permissions/ policy · evaluator ├── config/ schema · loader · defaults └── shared/ ``` Avoid circular dependencies. **Every file in `src/` carries the mandatory author header.** --- ## 21. TESTING Build tests while implementing. **Unit:** tool parsing · event reducer · context budgeting · config resolution · permission rules · file editing · process lifecycle · session persistence · **header lint check**. **Integration:** Anthropic streaming · tool execution loop · session resume · interruption · context compaction · repository modification. **TUI (where practical):** keyboard navigation · resize · long output · streaming · dialogs · permission requests · model selector · slash palette. **Golden/snapshot:** tool rendering · markdown · diffs · error panels · status lines. Do not make snapshots so broad that every intentional UI improvement becomes painful. --- ## 22. DOGFOODING AND BENCHMARKING ### Dogfooding KHAELOR 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. ### Benchmark UX against competitors After the first functional TUI exists, manually compare equivalent workflows against Claude Code, OpenCode, Hermes Agent, and OpenHands CLI. Do not copy visual appearance blindly. Measure 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. Count: keystrokes · latency · screen noise · modal interruptions · clarity. KHAELOR should deliberately improve these workflows. --- ## 23. V1 SCOPE **V1 MUST include:** ✓ 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** **NOT V1 — do not let these derail the release:** OpenAI · 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. Design clean boundaries for them. Do not implement them yet. ### Future architecture Future 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. --- ## 24. DEVELOPMENT PHASES **Phase 0 — Research.** Deliver `docs/research/*`. No major production implementation before this is complete. **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. **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. **Phase 3 — Anthropic integration.** Authentication, model config, streaming, tool calling, usage accounting, errors, retry, cancellation. **Phase 4 — Agent loop.** `AgentKernel`, `ToolRegistry`, `Executor`, `LocalWorkspace`, events. **Phase 5 — Core tools.** read, write, edit, grep, glob, bash, process. **Phase 6 — Sessions + context.** Persistent events, resume, context engine, compaction, checkpointing. **Phase 7 — Repository intelligence.** Git awareness, repository map, efficient search, file mentions, context retrieval. **Phase 8 — Polish.** Obsess over latency, keyboard workflows, tool rendering, diffs, permission UX, interruptions, long sessions, errors, resize behavior. --- ## 25. DISCIPLINE For every substantial component: 1. Inspect the relevant reference implementation 2. Understand its trade-offs 3. Document the KHAELOR decision 4. Implement a minimal clean version — **with the mandatory file header** 5. Test 6. Dogfood 7. Simplify Do not create complexity merely because another agent framework has it. **Architecture rule.** Whenever tempted to add something to `AgentKernel`, ask: *can this be a service around the kernel?* Usually yes. **UX rule.** Whenever something technically works, ask: *is this the best terminal interaction we can design?* If no, the feature is not finished. **Speed rule.** When latency appears, measure first, then optimize the correct layer (model / network / filesystem / indexing / rendering / architecture). **Quality rule.** Never declare something complete merely because it compiles. For meaningful changes: inspect → test → use → verify. --- ## 26. FINAL PRODUCT STANDARD KHAELOR should eventually make someone who regularly uses Claude Code, OpenCode, Hermes, and OpenHands think: > *Why doesn't every terminal agent work like this?* The 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. --- ## 27. BEGIN Your first task is NOT to start coding KHAELOR. Your first task is: 1. Inspect the current environment and repository 2. Obtain or locate the reference repositories 3. Deeply analyze Hermes Agent 4. Deeply analyze OpenCode 5. Deeply analyze OpenHands and its Software Agent SDK 6. Inspect mini-SWE-agent for architectural minimalism 7. Write the required research documents 8. Derive KHAELOR's architectural decisions 9. Produce `ARCHITECTURE.md` and `TUI_DESIGN.md` 10. Only then begin implementation Do 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. Then build something better. --- **Understand first. Design second. Implement third.** *Author: Simon-Pierre Boucher · contact@spboucher.ai*