Skip to content
Architecture

Architecture

This document describes the internal structure of Ulmi: which package owns what, how data flows through the agent loop, and how the major features connect to each other.

For end-user concepts (what an agent is, how skills work, and so on), see the corresponding feature documents.

High-level layers

┌───────────────────────────────────────────────────────────┐
│                     CLI Layer                             │
│            cobra commands in internal/cli/                │
├───────────────────────────────────────────────────────────┤
│                     TUI Layer                             │
│         App (view) + Deps / SessionRuntime / Turn         │
│         (ui/* widgets, keymap; slash and theme siblings)  │
├───────────────────────────────────────────────────────────┤
│                     Agent Engine                          │
│    internal/agent: tool loop, system prompt, sub-agents   │
├──────────┬──────────┬──────────┬──────────┬───────────────┤
│  Tools   │ Sessions │ Snapshot │  Skills  │  LLM Gateway  │
│  internal│ internal │ internal │ internal │ internal/llm  │
│  /tool   │ /session │ /snapshot│ /skill   │ + providers/  │
├──────────┴──────────┴──────────┴──────────┴───────────────┤
│              Permissions  ·  Token counting               │
│        internal/permission  ·  internal/tokencounter      │
├───────────────────────────────────────────────────────────┤
│                     Configuration                         │
│       internal/config: YAML loader, env interpolation     │
└───────────────────────────────────────────────────────────┘

Each layer depends only on the layers below it (with the small exception that internal/cli is the composition root and is allowed to wire any package together to break would-be import cycles — see internal/cli/snapshotfactory.go).

cli constructs registries and managers, then injects them into tui.New. The TUI does not call providers or tools on the update goroutine: long work returns as typed tea.Msg. There is no second event bus.

    flowchart TB
  CLI["internal/cli<br/>composition root"] --> App["internal/tui.App<br/>value tea.Model"]

  subgraph engine ["Engine"]
    Agent["internal/agent"]
    LLM["internal/llm"]
    Tool["internal/tool"]
    Sess["internal/session"]
    Perm["internal/permission"]
    Task["internal/taskmgr"]
    MCP["internal/mcp"]
    Snap["internal/snapshot"]
    Skill["internal/skill"]
    Slash["internal/slash"]
    Theme["internal/theme"]
  end

  App --> engine
  CLI --> engine
  

Repository layout

ulmi/
├── cmd/ulmi/main.go              entry point
├── docs/                           ← you are here
├── test/
│   ├── integration/                cross-package workflow tests
│   └── e2e/                        binary, PTY, and provider E2E tests
├── internal/
│   ├── agent/                      engine, system prompt, registry, sub-agents
│   ├── cli/                        cobra commands (composition root)
│   ├── config/                     YAML loader + merge + validation
│   ├── customcmd/                  user-defined slash commands
│   ├── diff/                       unified-diff parse and workspace git diff
│   ├── llm/                        Provider interface, registry, message types
│   │   ├── providers/anthropic/
│   │   ├── providers/gemini/
│   │   ├── providers/ollama/
│   │   └── providers/openai/
│   ├── logger/                     slog JSON, Event* turn msgs, rotation
│   ├── lsp/                        experimental LSP client + tool adapters
│   ├── mcp/                        Model Context Protocol client + adapters
│   ├── mention/                    @file mention parse and resolve
│   ├── permission/                 allow/ask/deny evaluator + matcher
│   ├── prompthistory/              composer ↑/↓ / Ctrl+R recall (sqlite Store)
│   ├── session/                    persistence (sqlite/json), compact, export
│   ├── shellsessions/              user-shell session tracking for /ps
│   ├── skill/                      skill loader + matcher + prompt injection
│   ├── snapshot/                   undo/redo manager + cas + shadowgit
│   ├── taskmgr/                    foreground/background sub-agent jobs
│   ├── tokencounter/               estimation + cost + history compaction
│   ├── tool/                       Tool interface, Registry, ExecuteAll
│   │   ├── builtin/                static built-in tool composition
│   │   └── tools/<name>/           one package per built-in tool
│   ├── tui/                        BubbleTea root, coordinators, ui/*, keymap
│   └── worktree/                   git worktree isolation for sub-agents
├── go.mod
├── go.sum
├── Makefile
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
└── README.md

Data flow: a single user turn

The interactive path is a Bubble Tea adapter of agent.DecideNext / AfterToolRound. It does not call RunLoop. Turn never takes App; chrome mutates only in App.applyTurnOutcome.

    sequenceDiagram
  participant User
  participant Composer as ui/composer
  participant App
  participant Turn as tui/turn
  participant LLM as llm.Provider
  participant Agent as internal/agent
  participant Tools as tool.Registry

  User->>Composer: Enter
  Composer->>App: SendMsg
  App->>App: sess.AppendUser, Turn.Start
  Turn->>LLM: Stream via tea.Cmd
  loop tokens
    LLM-->>App: TokenMsg
    App->>App: chat.AppendToLast
  end
  LLM-->>App: StreamDoneMsg
  App->>App: flush buffers and usage
  App->>Turn: OnStreamDone
  Turn->>Agent: DecideNext
  Turn-->>App: Outcome

  alt TurnStop
    App->>App: persist, dequeue, compact
  else NeedConfirm
    App->>App: permission confirm strip
  else NeedTools or StreamBash
    App->>Tools: ExecuteAll or PTY
    Tools-->>App: toolsExecutedMsg
    App->>Turn: OnToolsDone
    Turn->>Agent: AfterToolRound
    Turn-->>App: ContinueStream, Error, or TurnStop
  end
  

The agent loop is one orchestration (DecideNext, AfterToolRound, and agent.RunLoop for the headless path) with two I/O adapters:

  • Interactive: Turn in internal/tui/turn is a Bubble Tea adapter. It streams tokens via tea.Cmd and does not call RunLoop. After each stream App flushes buffers and usage, then Turn.OnStreamDone returns one TurnOutcome. App.applyTurnOutcome is the only chrome mutator (chat, spinner, confirm, PTY, persist, dequeue, compact). Tool batches use ToolEnv; OnToolsDone runs AfterToolRound on a history snapshot.
  • Non-interactive: internal/agent.Engine is a thin caller of RunLoop through SendCompleter (Provider.Send). StreamCompleter drains Provider.Stream for blocking callers. Sub-agents keep Send.

Observability

internal/logger installs JSON slog. At info, a TUI turn and Engine.Send use the same msg values: turn_start, llm_round, tool_done, compact, turn_end, mcp_connect, session_saved. llm_retry is WARN between attempts. MCP client Close failures (reconnect, disconnect, disable, failed ListTools) are WARN (mcp server close failed), not a new INFO event. Correlation (session_id, model, turn_id, job_id, call_id) is copied from the argument context — taskmgr identity attrs are mixed onto that ctx (logger.WithAttrs / SetLogAttrs), not stored as an owner Context. Prompt bodies stay DEBUG. Field list: Configuration → logging.

Key components

internal/llm — LLM Gateway

The chat port in provider.go is a small surface. Every I/O method takes context.Context first. Live model discovery is not on Provider: callers type-assert an optional Cataloger. Registry.Models() is the config catalog (no I/O).

type Provider interface {
    ID() string
    Send(ctx context.Context, req *Request) (*Response, error)
    Stream(ctx context.Context, req *Request) (StreamIterator, error)
    SupportsTools() bool
}

type Cataloger interface {
    ListModels(ctx context.Context) ([]ModelInfo, error)
}

type StreamIterator interface {
    Next(ctx context.Context) (StreamEvent, error)
    Close() error
}

StreamIterator.Next takes the stream context; a canceled ctx returns ctx.Err() immediately. Transport and parse failures are a non-nil error from Next (there is no EventError). Ollama implements Cataloger; OpenAI, Anthropic, and Gemini do not.

Concrete providers live under internal/llm/providers/<name>/ (OpenAI, Anthropic, Google, Ollama). The OpenAI client is reused by OpenRouter, Groq, and Together AI by passing a custom WithProviderID. All four constructors accept WithHTTPClient (nil is ignored). Registry.ProviderFor wraps ErrUnknownProvider so callers use errors.Is.

The Registry maps provider/model model IDs to providers, exposes a curated catalog with pricing and context-window data, and supports model groups for fallback chains.

Stream events follow a unified schema in stream.go so the TUI does not have to know which provider produced the tokens. Callers pass the stream ctx into Next; the TUI keeps turn.Stream.Ctx for the tea.Cmd closure and does not store that ctx on the provider iterator.

internal/agent — Agent Engine

Engine is a thin caller of RunLoop via SendCompleter and the shared DecideNext / AfterToolRound steps:

  1. Append the user message to history.
  2. Send to the provider.
  3. If the response has tool calls, run them concurrently (up to maxParallel, default 10), append results to history, and loop.
  4. Otherwise return the final response.

Built-in agents (build, plan) are described by Def values. User-defined agents are parsed from markdown frontmatter in userdef.go and merged into a shared Registry.

The system prompt is constructed by prompt.go. The TUI keeps a byte-stable base system message (agent body + cwd + tool index) and a trailing volatile message (mode, /goal, skills) so prompt-cache prefixes survive mode changes. Tool schemas are sent in tools[], sorted by name. The TUI split lives in applySystemPrompt (session_mode.go).

Sub-agents are wired via subagent.go and the task tool. Runtime resolves named agent profiles from SubagentCatalog (built-in presets plus user-defined subagent: true agents), supports per-agent models (grunt presets inherit agents.cheap_model), background execution, git worktree isolation, and grader loops. taskmgr.Manager tracks job lifecycle; methods that persist or cancel take ctx first and require a non-nil argument. Identity (session_id, model) is SetLogAttrs / argument ctx, not a stored owner Context. Completed jobs are persisted in the subtasks SQLite table. The TUI exposes /tasks and /batch slash commands for monitoring and fan-out.

internal/tool — Tool framework

A tool is anything implementing the Tool interface in tool.go. The Registry holds them, exports their JSON schemas to the model, and is in charge of:

  • Synchronous permission checking (PermissionChecker for non-interactive runs; the TUI uses its own pre-screening with the confirm dialog).
  • Parallel execution (ExecuteAll) capped by a counting semaphore.
  • Wrapping tool errors in Result.IsError = true instead of propagating Go errors so the agent loop can keep going.

Built-in tools live one package per name under internal/tool/tools/.

internal/tui — BubbleTea TUI

The root model is App in app.go. It is a tea.Model router: Init / Update / View, key and message dispatchers, layout, and named chrome-apply points (applyTurnOutcome, applyPermOutcome, applyOverlayOutcome, applyBashOutcome, applyFocusOutcome, applyChromeOutcome). Feature logic lives on pointer buckets (Deps, SessionRuntime, Turn, perm.State, overlay.State, bash.State, focus.State, chrome.State, promptHistState) or package coordinators. Dispatchers are package functions (updateDispatcher / keyRouter); method values are not required. The method-set budget is TestApp_MethodBudget (12, ceiling 14; later work only lowers it).

Runtime lives on pointer-held buckets so Bubble Tea value-copies of App alias them. Coordinators must not import parent package tui; short names in tui are aliases (type Turn = tueturn.Turn).

    flowchart LR
  subgraph appValue ["App value tea.Model"]
    ViewChrome["status / chat / input / spinner"]
    Layout["width, height, theme, keymap"]
  end

  subgraph buckets ["Pointer buckets never nil after New"]
    Deps["deps *Deps"]
    SessRT["sess *sess.Runtime"]
    Turn["turn *turn.Turn"]
    Overlay["overlay *overlay.State"]
    PermS["perm *perm.State"]
    Bash["bash *bash.State"]
    Focus["focus *focus.State"]
    Chrome["chrome *chrome.State"]
    Prompt["promptHist *sess.PromptHist"]
  end

  appValue --> buckets
  
ConcernTypeFiles
Provider, tools, MCP, taskmgr, snapshot, skills, mentionsDepsapp.go
History, id, title, goal, stats, persistsess.Runtime (SessionRuntime in package tui)internal/tui/sess/
In-flight stream, send queue, per-turn trackers, tool executionturn.Turninternal/tui/turn/
Overlay stack and picker modelsoverlay.State (overlayState in package tui)internal/tui/overlay/
Permission eval, confirm queueperm.State (permState in package tui)internal/tui/perm/
Bash PTY / ! runtimebash.State (bashRunState in package tui)internal/tui/bash/
Session-view focusfocus.State (sessionFocusState in package tui)internal/tui/focus/
Pinned strips, toast, chrome focuschrome.State (chromeState in package tui)internal/tui/chrome/
Composer prompt history (↑/↓ / Ctrl+R)sess.PromptHist (promptHistState in package tui)internal/tui/sess/

Turn is a tea.Cmd adapter of agent.DecideNext / AfterToolRound. It does not call RunLoop. It returns a TurnOutcome; App.applyTurnOutcome applies chrome. Token buffers, spinner, permission confirms, and PTY terminals stay on App. Tests for Turn feed StreamDoneInput / ToolsDoneInput without constructing App; App tests cover layout, keys, overlay, and chrome.

View chrome stays on App: overlay stack on *overlay.State, bash PTY / ! on *bash.State, the permission model on *perm.State, Session view focus on *focus.State, and pinned queue/task strips plus toast and the taskmgr listen loop on *chrome.State. App itself stays a value tea.Model. A pointer-App is a non-goal. App.View lives in app.go.

Update walks updateDispatchers in priority order; the first claim wins. Unclaimed messages go to the top overlay window, otherwise to chat and composer. Keys use keyRouters (exit confirm → bash → window stack → confirm/question/retry → slash/@/$ → leader → direct → composer). Policy returns a named Outcome; chrome writes only in App.applyXOutcome (applyTurnOutcome, applyPermOutcome, applyOverlayOutcome, applyBashOutcome, applyFocusOutcome, applyChromeOutcome). There is no generic applyChrome.

    flowchart TD
  Msg["tea.Msg"] --> Update["App.Update"]
  Update --> Disp["updateDispatchers"]
  Disp --> Win["updateWindowInput"]
  Disp --> Pick["updatePickerClose"]
  Disp --> Panel["updatePanelDialogs"]
  Disp --> Queue["updateChromeQueue"]
  Disp --> Stream["updateStreamChain"]
  Disp --> BashPs["updateBashPs"]
  Disp --> StreamEnd["updateStreamEnd"]
  Disp --> Rest["theme / MCP / tasks / session I/O"]
  Disp --> Fallback["updateFallback"]

  Win --> Keys["keyRouters"]
  Keys --> Bucket["coordinator returns Outcome"]
  Bucket --> Apply["App.applyXOutcome"]
  Apply --> ChromeMut["chat / status / overlay / persist"]
  

New fields on App need a reason they are not Turn, SessionRuntime, or Deps. The placement checklist lives in internal/tui/AGENTS.md.

Sub-packages handle specific concerns:

  • turn/ — in-flight LLM stream, send queue, and tool-batch execution. Must not import views or parent tui.
  • overlay/ — window stack and picker models. Must not import parent tui. May import ui/* widgets.
  • perm/ — session permission model and confirm queue. Must not import parent tui. App.applyPermOutcome stays chrome.
  • bash/ — PTY / ! shell runtime. Must not import parent tui or chat. PTY chrome is a string; App.applyBashOutcome stays chrome.
  • focus/ — full-screen sub-agent Session view. Holds ChatModel / InputModel values. Must not import parent tui. App.applyFocusOutcome stays chrome.
  • chrome/ — pinned strips, toast, chrome focus, and taskmgr listen. Must not import parent tui. Tasks overlay open stays overlay. App.applyChromeOutcome stays chrome.
  • proj/ — engine → widget DTO mappers. Must not import parent tui. May import engine packages; ui/* must not.
  • ui/kit/ — picker overlay chrome, inline autocomplete, and pinned-strip helpers. Leaf: does not import other ui/*.
  • ui/strip/ — permission confirm, retry, question, and live terminal. View() string only; does not import chat.
  • ui/chat/ — transcript, cards, live jobs. SetInlineConfirm(string) only; does not import strip.
  • ui/composer/ — input, slash/@/$, editor overlay, history search. May import kit only among ui/*.
  • ui/status/ — status bar, hints, toast, context overlay, pinned queue/task strips. May import kit only among ui/*.
  • ui/list/ — catalog pickers, help, details. Must not import ui/ops.
  • ui/ops/ — tasks, MCP, ps, permissions, diff. Must not import ui/list.
  • sess/ — conversation history, identity, stats, and persist I/O. Must not import views or parent tui.
  • keymap/ — leader-key + direct binding mapping with config overrides.

Widget packages store projections, not live engine types. Mapping lives in proj/. Intent messages carry IDs; App resolves them against Deps. list must not import ops and ops must not import list. Chat takes inline confirm as a string and does not import strip.

    flowchart BT
  kit["ui/kit<br/>picker chrome, autocomplete, pinned helpers"]
  strip["ui/strip<br/>confirm, retry, question, terminal"]
  chat["ui/chat<br/>transcript, cards, live jobs"]
  composer["ui/composer<br/>input, slash / @ / $, editor"]
  status["ui/status<br/>bar, hints, toast, queue/task strips"]
  list["ui/list<br/>catalog pickers, help, details"]
  ops["ui/ops<br/>tasks, mcp, ps, permissions, diff"]

  strip --> kit
  chat --> kit
  composer --> kit
  status --> kit
  list --> kit
  ops --> kit
  ops --> strip
  ops --> status
  

internal/slash is the slash-command registry plus parser / autocomplete. cli constructs a *slash.Registry before tui.New and injects it with the tui.WithSlashRegistry Option. There is no process-wide slash global.

internal/theme holds palette definitions and the YAML loader. Each App holds a theme.Theme (tui.New / tui.WithTheme / /themes). View(th) takes that palette. theme.Active() / Set() remain for tests that prove paint ignores the process global; production TUI paint does not call them.

Widgets must not import taskmgr, mcp, session, agent, tool/tools/*, shellsessions, or permission (internal/buildcheck). Allowlisted value types stay as-is: llm.ModelInfo, diff, skill.Skill.

    flowchart LR
  subgraph tuiPkg ["internal/tui"]
    App
    Turn
    SessRT["sess"]
    PermB["perm"]
    Proj["proj"]
    UI["ui/*"]
  end

  subgraph leaves ["TUI leaves and siblings"]
    KM["keymap"]
    Syn["syntax"]
    FO["fileopener"]
    Sh["shell"]
    Slash["internal/slash"]
    Theme["internal/theme"]
  end

  subgraph enginePkgs ["Engine"]
    Agent["agent"]
    LLM["llm"]
    Tool["tool"]
    Session["session"]
    PermE["permission"]
    TaskMgr["taskmgr"]
    MCP["mcp"]
    Snap["snapshot"]
    Skill["skill"]
    Mention["mention"]
    PH["prompthistory"]
    Diff["diff"]
    Cfg["config"]
  end

  App --> Turn
  App --> SessRT
  App --> PermB
  App --> Proj
  App --> UI
  App --> leaves
  App --> Mention
  App --> PH

  Turn --> Agent
  Turn --> LLM
  Turn --> Tool
  Turn --> PermE
  Turn --> Snap

  SessRT --> Session
  SessRT --> LLM

  PermB --> PermE
  PermB --> Agent
  PermB --> Cfg

  Proj --> TaskMgr
  Proj --> MCP
  Proj --> Skill
  Proj --> Session
  Proj --> UI

  UI --> Theme
  UI --> Slash
  UI --> KM
  UI --> Diff
  

The TUI never calls providers or tools directly; it dispatches them as tea.Cmd goroutines so the UI stays responsive. App.Context() is the app-lifetime cancel scope (quit cancels it). Prompt history, session SQLite I/O, git diffs, MCP reconnect, $EDITOR / file opener, mention index refresh, and task-manager cancel/steer use it so leftover I/O stops with the process. New still roots that context at context.Background(). Cobra commands pass cmd.Context() (SIGINT from main) into launchTUI so MCP connect during bootstrap is cancelled on Ctrl+C; session resume after tui.New uses App.Context().

internal/permission — Permissions

The priority chain (session mode → rules → agent overrides → preset → per-tool/category global → default) is documented in Permissions and implemented in permission.go. The pattern matcher in matcher.go supports a union of filepath.Match, double-star globs, shell-style globs, and prefix matching so configuration is forgiving regardless of style.

internal/prompthistory — Composer prompt recall

Separate from conversation sessions. Persists submitted input lines (prompts, / commands, ! shell) for ↑/↓ and Ctrl+R, filtered by cwd. Default backend is SQLite at ~/.local/share/ulmi/prompt-history.db via a pluggable Store. Open with OpenContext(ctx, cfg) (Close() has no ctx). The SQLite file is versioned with PRAGMA user_version (migrate.go). See TUI Guide and tui.prompt_history in Configuration.

internal/session — Sessions

Two backends conform to the Store interface. Open with OpenContext(ctx, cfg); Close() is io.Closer (no ctx).

  • sqlite.go (default) using modernc.org/sqlite. Schema steps live in migrate.go (PRAGMA user_version).
  • json.go (one file per session).

Compaction (/compact) is implemented in compact.go; it asks the model to summarise the conversation and replaces history with the summary plus a context marker. Session branching (/fork) uses Fork to deep-copy history into a new ID.

internal/snapshot — Undo / Redo

Manager wraps a pluggable Backend. Two backends ship:

  • cas/ — content-addressable filesystem store (default).
  • shadowgit/ — isolated git repository per session.

File-mutating tools call Capture before mutating and Record after. internal/cli is the composition root: it closes over config.SnapshotsConfig as a snapshot.OpenFunc and injects that into the TUI. The TUI rebinds the manager when the session id changes and toasts if open fails. It does not import cas or shadowgit. Tools find a live manager via snapshot.WithManager(ctx, ...).

internal/skill — Skills

Loads markdown skills from ~/.config/ulmi/skills/ and .ulmi/skills/, matches them against workspace files via globs, and injects the catalog plus active bodies into the trailing (volatile) system message. Implementation: skill.go, matcher.go, catalog.go.

internal/mcp — Model Context Protocol

Four transports (stdio, HTTP, SSE, streamable HTTP) implement one Client (tools + resources + prompts). User-facing type names, aliases, and mcp__server__tool registration: MCP. That combined Client surface stays together: every transport and the Manager use all three capabilities. Revisit if a tools-only transport appears. The Manager connects enabled servers at TUI startup and shuts them down at exit.

internal/lsp — LSP

A minimal LSP client over stdio with five high-level operations (definition, references, hover, workspace symbols, call hierarchy). The auto-detector in detect.go picks a server based on workspace file extensions and PATH availability.

internal/tokencounter — Tokens & cost

Heuristic token estimation by provider family, deterministic cost calculation from pricing in llm.ModelInfo, and the auto-compact threshold. History compaction itself is LLM summarisation in session.Compact.

internal/config — Configuration

YAML-first config with environment-variable interpolation, layered merging (defaults → global → project → CLI overrides), and schema validation. See Configuration for the user-facing view.

Concurrency model

  • The TUI runs on Bubble Tea’s single-goroutine update loop. Long-running work (provider calls, tool execution, file writes) is dispatched as tea.Cmds that run on their own goroutines and post messages back.
  • Tool execution within one assistant turn is parallel with a fixed cap (10 concurrent) using golang.org/x/sync/errgroup plus a counting semaphore (tool.Registry.ExecuteAll).
  • Sub-agents launched by the task tool run in parallel when the model emits multiple task calls in one turn (capped by maxParallel, default 10). Background jobs are tracked by taskmgr.Manager and surfaced in the /tasks overlay. Foreground jobs block the parent until complete.
  • All package-level state (agent.Registry, tool.Registry, the snapshot store, etc.) is guarded by mutexes; the public APIs are safe for concurrent calls.

Token counting & cost

Providers attach llm.Usage to every streaming EventDone (OpenAI stream_options.include_usage, Anthropic message_start/message_delta, Gemini usageMetadata, Ollama eval counts). The TUI accumulates that usage into:

  • per-turn totals (one user prompt → full tool loop), shown as a footer under the assistant reply (tokens: 1.0k↑ 10↓ · 900 cache (90%) · $0.0042);
  • session totals in the status bar ($ spend) and /usage / /details;
  • context fill (ctx N/MAX) from a live estimate of the conversation (system prompt + tool schemas + history), matching /context, including the session prompt-cache hit-rate. This is separate from cumulative session spend. For Ollama, context_window is also sent as options.num_ctx so the local model uses that window instead of the default ~4k.

tokencounter.CalculateUsageCost prices input/output/cache tokens from llm.ModelInfo (catalog defaults, overridable via models.*.input_price etc.). When a provider omits usage, tokencounter.Counter estimates as a fallback. Auto-compact triggers at 80% of the context window (or sessions.auto_compact_tokens when the window is unknown), not cumulative spend. Prompt caching is requested via llm.CacheConfig on each request (llm.cache in config). See internal/tokencounter/counter.go.

Composition root

internal/cli is the only package allowed to import from many otherwise parallel packages. It builds the LLM registry, agent registry, tool registry, permission evaluator, session store, snapshot manager, MCP manager, LSP manager, and the BubbleTea application, then runs the program. Everything else stays decoupled.

The bootstrap path is:

cmd/ulmi/main.go
  → internal/cli.NewRootCmd
      → newTUICmd / newRunCmd / newConfigCmd / newSessionCmd
        / newTasksCmd / newSnapshotCmd / newAgentCmd / newMCPCmd
        / newVersionCmd

Testing strategy

  • Unit tests sit next to each package (*_test.go). Coverage is tracked via make cover. CI runs make cover-ci for a quick percentage of the listed packages; that job omits internal/snapshot (subprocess covdata is not collected) and cmd/ulmi.
  • Integration tests in test/integration/ exercise cross-package workflows and run as part of make test.
  • End-to-end tests in test/e2e/ drive the built binary using PTYs (creack/pty), with a mock LLM provider and golden-file output. make e2e-mock runs them without needing Ollama.
  • Lint is make lint, which installs the golangci-lint version from .golangci-version using the project’s Go toolchain. CI does not use @latest.
  • govulncheck is make govulncheck, pinned in .govulncheck-version the same way.

The CI matrix runs on Ubuntu, macOS, and Windows, builds a stripped binary, and fails if it exceeds 30 MB. See Makefile and .github/workflows/ci.yml.

Where to read the code

If you want to follow a single thread through the codebase, these are good entry points:

  • TUI startup: cmd/ulmi/main.go → internal/cli/root.go → internal/cli/tui.go.
  • Streaming a response: handleSend in customslash.go, internal/tui/turn/turn.go (Start), internal/tui/turn/loop.go (OnStreamDone, OnToolsDone), internal/tui/turn_apply.go (applyTurnOutcome).
  • System prompt: applySystemPrompt in session_mode.go.
  • Tool dispatch: internal/tool/registry.go (ExecuteAll); static tools in internal/tool/builtin/registry.go.
  • Agent loop (headless): internal/agent/engine.go (Send), internal/agent/turn.go (RunLoop, DecideNext, AfterToolRound); interactive adapter is Turn, not a second copy of RunLoop.
  • Permissions: internal/permission/permission.go (Evaluate), internal/permission/checker.go (ExtractSubject).
  • Undo/Redo: internal/snapshot/manager.go (Capture, Undo, Redo).