Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Architecture

Fontaine is a Cargo workspace. The workspace manifest is rust/Cargo.toml and every crate sits directly under rust/. The repository root holds only rust/, evals/, docs/, tasks/ and research/, plus the top-level project files.

Workspace map

fontaine/
├── rust/
│   ├── fontaine/            binary and library: command line, headless runs, tracing and telemetry export
│   ├── fontaine-sdk/        the embeddable agent: `core`, `tools`, `agents` and `guardian` modules, the headless run loop, session assembly and the `SessionBuilder` facade
│   ├── fontaine-tui/        terminal UI
│   ├── fontaine-evals/      eval runner: binary and library
│   └── fontaine-testkit/    dev-only test helper crate: builds and locates Cargo example binaries for integration tests
├── evals/                   golden dataset (JSONL) and its format documentation
├── docs/                    product documentation, one topic per page
├── tasks/                   design and planning documents
└── research/                background analysis

Crates

CrateResponsibility today
fontaineThe fontaine binary. main.rs is thin; lib.rs parses the command line, resolves the directories, loads configuration, installs the tracing subscriber and opens the fontaine.session span. headless.rs reads the prompt and writes the SDK’s events as the versioned output described in Headless runs for fontaine -p. src/telemetry/ is the only place a subscriber is built, and holds the two export backends described in Telemetry.
fontaine-sdkThe embeddable agent, the one crate a Rust program names to run Fontaine in process; see Embedding Fontaine in a Rust program. Its crate root is the documented, semver-stable facade (SessionBuilder, Session, Event, HostTool). events holds the typed headless-v1 events, run the headless run loop, assemble the session assembly the binary and the builder share, and error the EmbedError. The four module trees below are public for the binary, the terminal UI and the evals, with no stability promise.
fontaine-sdk::coreThe settings scope stack (config), config and data directory resolution (dirs), the Tool(specifier) permission rule syntax (permission_rules), the workspace trust store (trust), the credentials file (credentials: lookup, the writer and removal), the account operations behind the provider dialog (accounts: listing accounts with their sign-in state, adding one to the user settings file, storing and removing credentials, signing in and removing an account), owner-only file creation (owner_only), the permission decision tier enum (tier), the provider registry (providers: one module per account kind, with the device sign-in and token refresh a signed-in kind uses), and the model layer (models): config accounts mapped to provider clients and <account>/<model> references resolved to model handles. The claude-subscription kind pairs rig’s Messages wire with a request-scoped subprocess transport (providers/claude_subscription): rig still encodes the request and decodes the stream, and only the HTTP transport is replaced by one that runs the Claude CLI once per request. Fontaine’s agent loop, history and session store stay authoritative; the CLI holds no conversation and executes no tool. See Claude subscription. It also holds the user hooks (user_hooks), the extension files (extensions, frontmatter, skills), the child runner that starts subagents (child_runner), and the permission pipeline (permissions, with the floor checks in floor), the audit log (audit), the shared session state (gate), the session (session: the model context store, its compaction and clearing), what fills the context window (context), the session ledger (ledger), the system prompt (prompt), the workspace roots (workspace), the wrapped tool registry (tools), and the agent setup and turn runner that headless and the terminal UI share (agent, turn). The guardian’s side of the core is the request builder that reads only the ledger (adjudication), the structural destructive-class derivation (destructive), the container probe (containment), and default-guardian selection and live model switching in models.
fontaine-sdk::toolsThe built-in tools and their risk classes, the workspace scope check, shell parsing and the Tier-0.5 pre-classifier (preclassify), the gate interface and the wrapper that puts every tool behind it, MCP servers (transports and wrapped registration, see MCP servers), the result pipeline and the built-in tool names that rules and agent toolsets may refer to. It imports nothing from core or agents; a test enforces it.
fontaine-sdk::guardianThe guardian: a separate, tool-less model conversation that judges one tool call and answers with a typed verdict. It holds the AdjudicationRequest and Verdict types, the RuleLabel enum, the prompt assets and the prompt builder, the shipped default rule lists, the verdict cache, the loop breaker, the minimal profile and the ranked model list types. It imports nothing from core, tools or agents (a test enforces it) and stays dependency-light so it can be lifted into another harness; see The guardian.
fontaine-tuiThe terminal UI: transcript, input, approval prompts, the agents panel, the workspace trust prompt, the provider dialog (provider_dialog, opened by /login, and hosted by setup before the session when no main model resolves) and the status bar, driven by the core turn runner. See The terminal UI.
fontaine-sdk::agentsSubagent orchestration without the core: the live tree of agents (who runs, what each spent, the messages waiting), the permission-mode ladder, budgets, the agent-type registry, and the agent and send_message tools. It defines the ChildRunner and RootLedger interfaces, which core implements, in the same way tools defines the gate. See Subagents.
fontaine-evalsLoads and validates the golden dataset, scores canned verdicts, runs pipeline cases through the real permission pipeline, scores a live guardian model and writes the models that clear the inclusion bar, scores a typed-decision model with its eval-only screen: scorer, and captures and diffs Claude Code baselines.
fontaine-testkitDev-only test helpers shared by the crates’ integration tests: example_bin builds a Cargo example on first use per test process and returns its path. Depends on no other Fontaine crates (only serde_json).

Dependencies between crates

fontaine          -> fontaine-sdk, fontaine-tui, fontaine-remote
fontaine-evals    -> fontaine-sdk
fontaine-tui      -> fontaine-sdk
fontaine-sdk      -> (no Fontaine crates)

Inside fontaine-sdk, core uses tools, guardian and agents; agents uses tools; tools and guardian use neither core nor agents. Tests enforce that guardian imports none of the other three and that tools and agents never import core. There are no cycles.

What a run does

fontaine parses its flags and loads configuration, then does one of two things:

The steps of a run:

  1. It parses its flags and opens the debug log if one was requested, validating FONTAINE_LOG.
  2. Under a subscriber that only feeds the debug log, it resolves the config and data directories, loads and validates the settings scope stack, and emits a debug-level config loaded event carrying the resolved scope stack.
  3. For a headless run it checks everything that needs no network: the flag combinations, the permission mode and the --json-schema value.
  4. It installs the global tracing registry once: the debug layer plus, when [telemetry] is enabled, one export backend. With the micromegas backend it first turns on micromegas’s per-thread streams, which must happen before any thread exists, and then builds the async runtime with the stream callbacks.
  5. It opens the fontaine.session span, resolves <account>/<model> to a model handle (which may list an account’s models), and drives the agent over that handle with the wrapped tool registry.
  6. It closes the session span, flushes the exporter for at most two seconds, and exits with the run’s code. Quitting the terminal UI has one two-second budget for the whole exit instead (see below).

Any configuration or usage error exits with code 2 and a message on stderr; a run error exits with code 1.

Quitting the terminal UI

A quit (/exit, /quit, Ctrl-D on an empty input) latches first, so no turn, continuation or queued input starts after it, and cancels what the session owns in the same instant: the running request is dropped, nested agent tasks and their report watchers are aborted, every background job’s process group is killed, and MCP reconnects are retired. Then the session_end hook, keeping the partial main turn, reaping jobs, closing MCP servers (each stdio server runs in its own process group, which is signalled so descendants of a wrapper die too), terminating language servers and stopping a SearXNG instance Fontaine started run side by side under one deadline of two seconds from the quit. A shared SearXNG instance Fontaine did not start is left running. Unlike a kill, the abort waits for no hook boundary and invents no report: what a subagent had journaled is all that survives. An independent watchdog thread restores the terminal and ends the process at that same deadline if a destructor or exporter is still stuck. Switching session with /resume or /branch keeps its graceful teardown.

The agent loop

The agent loop is rig’s: Fontaine builds an agent from a model handle, a system prompt, a conversation store and a tool registry, and runs it once per user message. It writes no loop of its own. Every tool call crosses the gate before the tool runs, and every result crosses the result pipeline before the model sees it:

                 user message
                      |
                      v
   +---------------------------------------+
   |  rig agent run  (model <-> tool calls) |
   +---------------------------------------+
        |  tool call                  ^  tool result
        v                             |
   +----------------------------------------------+
   | wrapped tool                                  |
   |   1. gate: allow (maybe with changed          |
   |      arguments) or deny with a reason         |
   |   2. on allow: the tool instance of the root  |
   |      that holds the call's path; an approved  |
   |      out-of-root file call goes to the        |
   |      unconfined fallback instance of its tool |
   |      (read-only for read/ls/glob/grep, a      |
   |      write fallback for write/edit/           |
   |      notebook_edit)                           |
   |   3. result pipeline                          |
   +----------------------------------------------+
        |
        v
   ls  read  glob  grep  write  edit  shell  webfetch  websearch  agent  skill  send_message  ask_user_question  list_mcp_resources  read_mcp_resource  mcp__*

A deny goes back to the model as the tool result and the run goes on. The registry is built at session start (and rebuilt between turns by /add-dir); each file tool and shell has one confined instance per workspace root, and webfetch has one; websearch joins only when a backend is configured. Beside the per-root instances, read, ls, glob and grep carry one unconfined, read-only fallback instance based at the primary root, and write, edit and notebook_edit carry one unconfined write fallback each. A fallback serves only a call whose resolved target lies outside every root, only after the gate has allowed it, and it consumes the resolved absolute arguments the pipeline normalized — so approval and execution cannot drift to two spellings of one target. shell has no fallback and stays confined. The session’s scratch directory (scratch) is created beside the session and appended to the roots, so it needs no special case here; it is removed when the session ends. MCP tools join the registry as their servers connect, wrapped by the same gate. A subagent gets a copy of the registry cut down to its type’s tools, so its calls reach the same gate. See Tools.

The permission pipeline

The gate is the permission pipeline. It reads the session state (mode, workspace scope, rules and grants, which the terminal UI can change between calls), decides, and writes one audit record per decision before anything else sees it:

 tool call
    |
    v
 1. hooks (deny / ask / allow / rewrite the arguments)
 2. floor: deny rule -> ask rule -> protected path
    |
    v   (the floor can only ask or deny, in every mode)
 3. read-only fast path: read-only tool, every path inside a workspace root and none a secret
    file (`.env`, key files, credential dotfiles) -> allow;
    also an `agent` spawn whose child's toolset is read-only
 4. shell pre-classifier: one literal simple command of the curated set -> allow
 5. allow rules (user trust scopes, session grants, always-allow rules) -> allow
 6. `auto` only: scratch write (file tool inside the session scratch directory) -> allow, then
    workspace edit (file tool on any file in the primary root, tracked or not) -> allow
 6b. any other `agent` spawn (never guardian-judged): auto allows (`spawn`), manual / acceptEdits
    ask, dontAsk denies
 6c. `send_message` / `board_update` (never guardian-judged): allow in every mode (`coordination`)
 6d. `draft_bug_report` (never guardian-judged; writes a redacted draft only): allow in every mode
    (`bug_draft`)
 7. the mode: manual / acceptEdits ask, dontAsk denies, auto asks the guardian
    |
    v
 audit log -> tool_decision event -> gate_decision event / transcript

Out-of-root reads are not refused before this diagram runs. After the hooks (step 1), a read, ls, glob or grep call whose target lies outside every root is resolved once to its absolute path; that normalized form is what steps 2 and 5 match (deny and ask rules against the written form as well), what the guardian and the approval prompt see, and what an allow returns for execution on the fallback instance. Malformed arguments end in an argument error right after the floor. Writes outside the roots keep their containment denial before the mode.

Asking is a call into an approval callback; headless runs and dontAsk turn every ask into a denial. Permissions describes each step.

Runs and the turn runner

fontaine-sdk::core builds the agent for both surfaces (agent) and runs one user message to its end (turn), yielding typed events (assistant text, tool call, gate decision, tool result, usage) to a callback that may stop the run between model calls. Headless prints the events as JSON lines; the terminal UI renders them and answers approval prompts concurrently with the run.

A run that fails — a provider error, the turn limit, a cancel — still saves what it committed to the conversation, so the next turn (or typing retry) continues the task instead of starting over. A retryable transport failure (a cut connection, throttling, a 5xx) is retried up to four times with exponential backoff and jitter, honoring Retry-After under a cap on the total wait, before the turn fails ([retry] sets the policy). It does so on the main agent and on subagents alike and says so with one warning line per retry. A retry re-drives the run on a harness continuation note, so only the model request is sent again and no tool call is repeated, and only a failure that outlives the retries reaches you.

The session ledger

Each session keeps two stores, plus a task list, a schedule and a goal file, in <data dir>/sessions/<session id>/:

  • the model context, the conversation the model sees, kept in logs/ by rig’s memory store. Compaction rewrites it: when the conversation outgrows the model’s context window, or the [context] autocompact_window setting, or when you run /compact, the older part is replaced by a summary the model wrote. /clear empties it. The same directory holds one agent-<n>.jsonl per subagent, that agent’s conversation, kept for the session’s life. A run saves on completion, and a failed or killed run saves what it committed up to its end, so a log exists for any agent that got at least a prompt off, killed ones included. Beside each, agent-<n>.inflight.jsonl is a journal written as a run progresses and emptied when the run settles, so a killed process still leaves the in-flight run for /export. The main run journals the same way in logs/main.inflight.jsonl, and when a run ends without settling — an interrupt, an AFK stop, a killed process — the journal is folded into main.jsonl followed by a marker, so the next turn continues the interrupted task.

  • the session ledger, ledger/ledger.jsonl: an append-only record, written by the harness and never by the model. It holds the user’s messages verbatim (a message typed while a turn runs is recorded when the agent receives it with a tool result, not when it is typed) with the answers you picked or typed in a question dialog, each message tagged with where it came from, the tail of each root turn’s final answer (agent_reply, at most 2,000 characters), mode changes, approvals and grants, denials, actions taken, model requests that ended an agent’s turn (request_failed, with the error class and message), a model list moving to its next entry after the serving one ran out of quota, or a subagent moving to the fallback role’s list after its own was spent on a usage window (model_fell_through, with the agent, role (fallback for the latter), both models and the error class), the run being held for a spent usage window (usage_paused, with the role, the account and the reset time when known) and how the hold ended (usage_resumed), ! commands you ran in the terminal UI (user_shell, the command and its exit code), the workspace roots, the trust state, the repository’s git remotes (read from the repository’s own config, without credentials), the names of the [env] variables (never their values) and an index of the files present when the session started. The index respects .gitignore and holds at most 50,000 paths, after which it records that it was cut short.

  • the task list, todos.json: the root agent’s list from the todo_write tool, written on every change. Subagents keep their own lists in memory only, so a resumed session has the root’s.

  • the schedule, schedule.json: the session’s scheduled prompts (cron_create tasks and /loop), written on every change. A task that comes due runs as a turn the harness starts, not as a user message; the ledger’s scheduled records (created, fired, deleted, expired, with the task’s id, who set it and its cron expression, never its prompt) show what ran and who scheduled it, and do not count toward what you asked for.

  • the goal, goal.json: the condition of the session’s /goal, present only while a goal is active. The ledger’s goal records (set, met, impossible, cleared, paused, with the number of evaluations, never the condition) show how it went; the condition itself is in the user_message of the /goal line. A goal turn is a harness turn, so it adds nothing to what you asked for.

Compaction changes the first store only, and so does /clear, which empties the model context in the same session and adds a context_cleared record to the ledger. The ledger keeps everything it held; only the guardian’s view of what you asked restarts after the record. A summary is model-written text and is never an input to a safety decision; the ledger is the only record of what the human asked for. The one model-written text the guardian sees beside it is the root turn’s final answer, in an untrusted block, which is never intent and earns credit only when your next message at the prompt plainly affirms the one action it proposed. The ledger lives in its own subdirectory because the memory store refuses a directory that holds a top-level .jsonl file.

Resuming and forking

--continue and --resume reopen the stores of an earlier session: the conversation log, the task list, the schedule, the goal and the ledger, whose records rebuild the view the guardian’s requests are built from, and new records continue the sequence. The session starts in the mode the settings resolve to and with no “allow session” grants, which were never persisted. --fork-session copies the session directory, todos.json, schedule.json and goal.json included, into a session directory under a new id and opens the copy, leaving the original as it was; the audit log of the copy starts empty. A resumed schedule keeps its tasks that are still worth running and re-arms them from now, so nothing replays what came due while the session was closed; a resumed goal comes back with its clock, evaluations and spend baseline reset; the rest are dropped from the file and reported once at startup, when scheduling is enabled (see Scheduled prompts).

A session can carry a name, recorded in its ledger and changed by appending another; --resume and /resume find a session by id, or by name among those started in the same directory, by reading each ledger once. In the terminal UI /resume and /branch end the running session and start the chosen one in the same process: the interface returns which session it wants, and the caller opens it exactly as --resume would, with the telemetry, configuration and workspace-trust decision carried over and the agents, MCP servers and scanner started again. /branch makes the copy itself, before leaving, so a failure is shown in the session that is still running.

Subagents in the ledger

A subagent tree has one source of intent, the human messages in the session’s ledger. The ledger records when subagents start, end, are resumed by you and message each other, but a spawn prompt or a message from another agent is never recorded as something the human said.

A user_message record may carry an agent field: you typed it in that subagent’s view, and the record is written only when the agent’s model reads it. It is intent for that agent and its own subagents only, never for the main conversation or a sibling; records without the field are the main conversation’s, so existing sessions load unchanged. Session naming, the first prompt a listing shows and the /rewind count use main-conversation messages alone, and a rewind also drops the agent-directed messages recorded after the first message it drops. A resumed agent record marks the start of a later run of an ended subagent. A spawned record carries the concrete model the agent runs on, and a finished record with status retired marks an agent that cannot be woken any more (an ancestor ended for good, /clear, a rewind or an AFK stop); a retired agent that had failed keeps its failed end. A resumed session rebuilds, as idle nodes with no conversation handle yet, the agents whose last end was done; the handle is built from the per-agent log on the first wake.

The ledger does not only record the lifecycle, it anchors id continuity: the largest agent-<n> ordinal in its spawned records seeds the counter a resumed session mints ids from, so a restarted process never reuses an id whose per-agent log a previous process persisted. Folding the same records rebuilds the session’s subagent list after a restart — id, parent, type and the latest finished status — which is what /export merges with the live tree when the tree is empty.

Models

Every model, for the session and for the guardian alike, is a rig completion model behind one handle. [accounts.<name>] maps to one provider each, with one wire client, or several for a kind that routes models over more than one wire, so two accounts of one kind keep separate credentials and endpoints. Each kind is a module in the provider registry; resolution, login and listing only talk to the registry. Configuration describes the kinds, the credential sources and model discovery.

Prompt caching

Providers reuse a request prefix only when it is byte-identical from the start. Nothing before the latest message therefore changes between the requests of a session: the system prompt and the tool array are fixed, and conversation history is only appended. Runtime state (queued steering, schedule notes, the task list, denial notices) reaches the model as appended messages or tool results, never as an edit to the front. A change that has to edit the front is allowed only at an explicit boundary and costs one lost cache read: /add-dir, /output-style, a model switch, an MCP server connecting (including on-demand approval and a tools/list_changed refresh), /clear and compaction. An MCP server’s tools are sorted by name so the order does not depend on the server’s tools/list.

On the Anthropic Messages wire and through an openrouter account Fontaine asks for the cache explicitly (prompt_caching and cache_ttl in Configuration); the other wires cache by prefix automatically. The cache read and write token counts of the main model, the guardian, subagents and goal evaluator are in the headless usage output.

Anthropic context editing (context_editing on an anthropic account) is the other way a prefix changes: when the server clears old tool results, the cached prefix is invalidated from the cleared point on and the next request rewrites it. clear_at_least_tokens keeps a clearing from firing for a small gain.

Tracing

Every crate instruments with the tracing facade only. No crate other than the fontaine binary depends on a subscriber, so library crates stay embeddable: with no subscriber installed their spans and events cost nothing. The export backends sit behind the binary’s telemetry-micromegas and telemetry-otlp features, both on by default. The binary’s pg2 feature builds the PromptGuard 2 tool-result scanner (candle and a tokenizer); it is off in a plain source build and on in release binaries.

The eval runner

fontaine-evals reads evals/dataset/*.jsonl and validates every case against the schema. With --guardian fixture it scores the canned fixture_verdict of each selected case against its expected outcome; with --guardian none it runs the pipeline cases through the real permission pipeline (no guardian, non-auto modes) and scores the first decision. Both run offline. With --guardian live:<account>/<model> it resolves the account through the same configuration and credential loading as fontaine -p, routes guardian cases to the guardian and pipeline cases to the pipeline under the case’s mode, records each case’s latency, and writes the models that clear the inclusion bar to the shipped model list; see the scorecard. The baseline capture and baseline diff subcommands compare the pipeline with Claude Code. The case format and the runner flags are documented in evals/README.md.

Platforms

Linux, macOS and Windows are supported, and the test suite runs on all three. Files that hold secrets or trust decisions are created readable by the current user only: mode 0600 on Unix and a protected, current-user-only ACL on Windows.