Preface

Why this book

AI agents are moving from demos to production. Most agent framework source you read along the way looks like a pile of scripts: prompts stitched from string concatenation, loose error handling, state that evaporates on every process restart. For a prototype, none of that matters. The moment you ask an agent to run as a long-lived process, execute shell and file operations, and serve multiple tenants at once, what is missing is not a feature but operating-system-grade infrastructure: permission boundaries, concurrent scheduling, a recoverable execution ledger, an auditable protocol.

octos is an AI agent operating system built in Rust. The book tracks the main branch: roughly 700,000 lines of Rust across a 26-crate workspace, with deny(unsafe_code) at the workspace level. It is not a call-graph wrapper rewritten in yet another language; from its first line it was designed for multi-tenant isolation, production reliability, and scalable concurrency. The provider fault-tolerance chain ships credential rotation and circuit breakers (see Chapter 3); sandboxing and permissions are fail-closed (see Chapter 7); long-running tasks get an event ledger and resumption scheduling (see Chapter 12).

The second edition expands the book from 14 chapters to 21 and adds a fourth part on the dual loop: how the outer loop (one supervising strong model plus an operations surface) drives the inner loop (a swarm of working models). Three chapters cover octoscode, the terminal client; OctoLoop outer protocol OLP v2; and herdr, the operations tool. Together they answer one question: when cheap models do the work in the inner loop, who reviews the result, and who takes over when they fail.

This book is not a user manual. It is a dissection of engineering decisions: each chapter digs into one subsystem, shows why it was designed that way, which alternatives were weighed, and what the choice cost. Every claim carries a source reference, so you can walk into the repository and check it yourself.

Before you read

Prerequisites

  • Required: fluency in one mainstream programming language (Python, Go, Java, or C++), the ability to read code, and basic HTTP and JSON.
  • Helpful but optional: elementary Rust. Chapter 2 uses traits and enums; Chapter 12 uses async/await. If Rust is new to you, do not stop here: Chapters 1-2 slow down on purpose, language details are explained in sidebars and comments where they appear, and you can skip them without losing the thread.
  • Helpful but optional: the basic vocabulary of LLM APIs (tokens, context window, tool calls). If you have never called one, you can still read this book: Chapter 3 starts from the provider abstraction and defines each concept as it is used.
  • Not needed: machine-learning mathematics, model-training experience, compiler theory, or operating-system kernel development.

Suggested reading paths

Path A: Rust beginner (learning Rust and agent engineering through one real, large project)

Ch1 → Ch2 → Ch5 → Ch6 → then pick freely Ch1 explains why Rust was chosen, Ch2 shows how the type system defines a domain language, Ch5 walks a full conversation lifecycle, and Ch6 covers tool dispatch. After that, read by interest: Ch8 (context compaction) and Ch12 (concurrency model) are both good destinations. Give yourself two weeks to make peace with the borrow checker.

Path B: senior Rust developer (here for the architecture and concurrency of a large Rust system)

Ch1 → Ch3 → Ch12 → then go deep Ch1's workspace topology and the argument for each choice are the map for the whole book; Ch3 covers the trait-object tradeoff in the provider abstraction; Ch12's three-layer concurrency scheduling (Tokio layer, supervisor layer, peer/lease layer) is the heart of this book's concurrency story. From there, branch by direction: security in Ch7 and Ch10, the platform in Ch14 and Ch15, the multi-agent kernel in Ch16-18.

Path C: AI application developer (from calling the API to understanding the runtime's internals)

Ch1 → Ch5 → Ch6 → Ch14 → Ch19 → Ch20 → Ch21 Ch5-6 answer what actually happens to the message you send; Ch14 settles runtime modes and configuration, and then you enter the dual-loop part: the octoscode client (Ch19), the outer protocol OLP v2 (Ch20), and operations practice with herdr (Ch21). Ch18's goal/peer mechanisms are the server-side prerequisite for Ch20; read it first if time allows. Skipping implementation-detail sidebars costs nothing.

Path D: octos contributor (about to file your first PR against the repository)

The whole book in order, plus Appendix A and Appendix E Appendix A's 26-crate dependency graph (63 edges) helps you locate the blast radius of a change; Appendix E covers building from source and the contribution process. The contract tests and event ABI in Chapter 10 are the interface most PRs cannot avoid.

A knowledge map of the book

graph LR
    subgraph P1["Part I Foundations"]
        C1["Ch1 Why Rust"]
        C2["Ch2 octos-core types"]
        C3["Ch3 octos-llm"]
        C4["Ch4 octos-memory"]
        C1 --> C2
        C2 --> C3
        C2 --> C4
    end
    subgraph P2["Part II Engine"]
        C5["Ch5 Agent Loop"]
        C6["Ch6 Tool System"]
        C7["Ch7 Defense in Depth"]
        C8["Ch8 Context Management"]
        C9["Ch9 Extension Mechanisms"]
        C10["Ch10 Harness"]
        C5 --> C6 --> C7
        C5 --> C8
        C6 --> C9
        C5 --> C10
    end
    subgraph P3["Part III Platform"]
        C11["Ch11 octos-bus"]
        C12["Ch12 Concurrency Model"]
        C13["Ch13 pipeline"]
        C14["Ch14 Run Modes"]
        C15["Ch15 Production Hardening"]
        C16["Ch16 Fleet"]
        C17["Ch17 Swarm"]
        C18["Ch18 Goal and Peer"]
        C5 --> C11 --> C14 --> C15
        C10 --> C12
        C12 --> C16 --> C17
        C12 --> C18
    end
    subgraph P4["Part IV Double Loop"]
        C19["Ch19 octoscode"]
        C20["Ch20 OctoLoop"]
        C21["Ch21 herdr"]
        C18 --> C20
        C19 --> C20 --> C21
    end
    subgraph APX["Appendices"]
        A1["A Crate Dependency Graph"]
        A2["B Tool Reference"]
        A3["C Configuration Reference"]
        A4["D Feature Flags"]
        A5["E Build and Contribution"]
        A6["F OLP Reference and E2E Trace"]
    end
    C3 --> C5
    C4 --> C5
    C15 -.-> A1
    C19 -.-> A5
    C20 -.-> A6

Two reading notes. First, Ch5 (the agent loop) is the hub of the book: the first four chapters lay its foundation, Chapters 6-10 unfold it, and the execution kernels of Chapters 12, 16, and 18 are all variants of it. Second, Part III runs on two tracks: Ch11-15 cover platform infrastructure (messaging, concurrency, workflows, configuration, production hardening) and Ch16-18 the multi-agent kernel (Fleet, Swarm, Goal/Peer); Part IV (Ch19-21) looks back over the whole book from the outer loop's vantage, and Chapter 20 depends on the server-side mechanisms of Chapter 18.

Reading conventions

  • Source references: full paths with line numbers, e.g. crates/octos-agent/src/agent/execution.rs:2483, locatable directly in the source repository. The repository keeps evolving and line numbers drift, so the text also names the symbol (function, type, or constant); when a line number stops matching, anchor on the symbol name.
  • The three-layer annotation system (introduced in Chapter 20): when a mechanism is described, the text states which layer enforces it: a protocol clause (documentation only), a Markdown convention (blackboard, ACK, and other conventions with no runtime code), or a contract test (mechanical checks against a snapshot or a real subprocess). The distinction was first used for the outer protocol OLP v2, and it carries over when you read Parts III and IV: knowing who enforces a rule tells you what happens when it is broken.
  • Engineering decision sidebars: one blockquote per chapter (starting with >) weighing 2-3 alternatives and stating the cost of the final choice.
  • Version notes: each chapter ends with how that subsystem's mechanisms changed across versions, so you can reconcile differences against the release in your hands.
  • Chapter positioning: a blockquote at the head of each chapter states its prerequisites and intended readers, enough to decide at a glance whether to skip it.
  • Mermaid diagrams: architecture diagrams, state machines, and sequence diagrams appear throughout the text and render in any Mermaid-capable reader.
  • Exercises: 2-5 open questions close each chapter, suited to team discussion or self-testing.

The baseline of this book

Version baselines: octos main repository main @ 9c157101 (figures gathered 2026-09-02), octoscode @ 1129fa33, and herdr branch feat/octoscode-agent @ fefe5c4f. All scale and line-count figures in this book (26 crates, roughly 700,000 lines of Rust, 63 dependency edges, per-module line counts) come from the per-chapter facts tables (assets/chNN-facts.md), each with a reproduction command, checkable against the corresponding baseline. The three repositories in Chapters 19-21 move fast; line-number drift is normal there, and references anchor on symbol names.


May this book leave you with more than an understanding of octos: a yardstick for judging agent infrastructure. Whenever you read about any agent system, carry four questions:

  • Where is the security boundary?
  • Who enforces the protocol?
  • Can state be recovered?
  • Where do errors go?

Chapter 1: Why Rust? Why an Agent OS?

Positioning: This chapter opens the book by answering two root questions: what exactly is hard about a multi-tenant AI agent platform, and why is octos written in Rust and shaped like today's 26-crate workspace? Prerequisites: none. All four reader profiles are served. A (Rust beginners) get a concrete picture of what problems Rust solves inside a real large system; B (experienced Rust developers) can jump straight to 1.3 for the workspace layering and dependency topology; C (AI/LLM application developers, no Rust background required) should focus on the problem space in 1.1; even if you end up choosing Python, these three challenges do not go away; D (contributors) should pay particular attention to the three fact corrections in 1.3.3, which are prerequisites for reading the repository correctly.

Open the octos source repository for the first time and ls crates | wc -l reports 26; find crates -name '*.rs' | xargs wc -l | tail -1 reports 700,915 lines of Rust; the root Cargo.toml members list has 38 entries. Lying in there: a message bus (17 channel source files), an agent runtime (59 tool source files under crates/octos-agent/src/tools/), a DOT-driven pipeline engine, a Fleet plan-execution kernel, and a full binding chain for embedding from Python/Swift/Kotlin/browser/Node. Developers arriving from LangChain or AutoGen see this and their first reaction is to question the language choice; Go developers, staring at screens full of tokio::spawn and Arc<Mutex<_>>, suspect goroutines would have been easier.

This is not a debate about language taste. Push "AI agent" from a single-user toy toward a multi-tenant production platform and you face a set of entangled engineering constraints: security isolation, concurrency, performance. Each is manageable alone; with all three holding at once, the choice of language and engineering organization stops being a preference and becomes an architecture decision. This chapter first lays out the three challenges (1.1), then argues why Rust is the best current answer to this constraint set (1.2), then unfolds the octos workspace topology to build the global map for the remaining 20 chapters (1.3). Every scale number in this chapter carries its measurement methodology and can be reproduced line by line in the source repository with the commands given in 1.3.1.


1.1 Problem Space: Three Challenges of a Multi-Tenant AI Agent Platform

octos is not a chatbot framework; it is a multi-tenant AI agent operating system. One process serves multiple users and multiple agent instances, and every agent can call tools with side effects: execute shell commands, read and write files, make network requests, and spawn child agents. The three challenges grow straight out of this setup.

1.1.1 Challenge One: Security Isolation: 59 Tool Source Files Are 59 Attack-Surface Entries

Picture a real scenario: tenant A's agent, summarizing a web page, gets hit by prompt injection, and the malicious instruction tries to read tenant B's session history or run rm -rf /. In a multi-tenant environment this is not a theoretical risk. octos's attack surface can be quantified directly from the facts table: crates/octos-agent/src/tools/ holds 59 tool source files (methodology: ls crates/octos-agent/src/tools/*.rs | wc -l). Note that this counts source files, not tools; it includes framework files such as crates/octos-agent/src/tools/mod.rs, crates/octos-agent/src/tools/registry.rs, and crates/octos-agent/src/prompt_guard.rs.

Every tool actually exposed to the LLM (shell, browser, web_fetch, write_file, spawn, and so on) is an independent attack path. Add the 17 *_channel.rs channel source files under crates/octos-bus/src/ (Telegram, Discord, Slack, WhatsApp, Feishu, email, Matrix, WeCom, DingTalk, QQ Bot, Twilio, Line, and more; of which crates/octos-bus/src/api_channel.rs and crates/octos-bus/src/cli_channel.rs are two internal channels, not all external-facing), and the platform is physically "a code-executing graph wired into every external messaging network." Each channel added is one more trust boundary for inbound messages; each tool registered is one more channel for outbound side effects.

Security isolation in agent scenarios is harder than in traditional web services, for three reasons:

  1. Tool calls are the core capability, not a side path. Dangerous operations in a web service usually converge into a handful of handlers; every iteration of an agent loop can trigger arbitrary tool combinations, and the call sequence is generated by an LLM and cannot be enumerated in advance. Defense must sink to per-call granularity, which is why octos implements a deny-wins policy engine and approval flow at the tool layer (see Chapters 6 and 7).
  2. Prompt injection is a new attack vector. It operates at the natural-language layer, where WAF-style regex rules mostly fail. The payload can hide inside a document fetched by web_fetch and then land as file writes or command execution through tool calls.
  3. The isolation boundary must be process-level. Permission checks at the language layer only block "abuse of legitimate APIs"; they cannot block the shell command itself. octos keeps the real sandbox subsystem inside octos-agent at crates/octos-agent/src/sandbox/ (six files: crates/octos-agent/src/sandbox/bwrap.rs, crates/octos-agent/src/sandbox/docker.rs, crates/octos-agent/src/sandbox/landlock.rs, crates/octos-agent/src/sandbox/macos.rs, crates/octos-agent/src/sandbox/windows.rs, crates/octos-agent/src/sandbox/mod.rs), targeting Linux bubblewrap/Landlock, Docker, macOS sandbox-exec, and Windows AppContainer respectively (crates/octos-agent/src/sandbox/mod.rs:1-23). Chapter 7 takes them apart one by one.

These three defensive layers (language memory safety → tool policy → process sandbox) hold only if the runtime carrying them introduces no new memory-safety holes of its own. That is the first constraint on the language choice in 1.2.

1.1.2 Challenge Two: Concurrency: Three Concurrency Faces in One Process

The second challenge is equally quantifiable. In Gateway mode, inbound messages from 17 channels arrive simultaneously; octos uses one tokio::sync::Semaphore to hold concurrent sessions under the configured cap (default 10, crates/octos-cli/src/config.rs:1633-1635), and the semaphore is created at Gateway startup (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1731-1732):

#![allow(unused)]
fn main() {
// Semaphore to bound concurrent session processing
let concurrency_semaphore = Arc::new(Semaphore::new(gw_config.max_concurrent_sessions));
}

Rate limiting is only the first face of concurrency. The second is inside the agent loop: in a single iteration the LLM may issue several tool calls at once, and octos tokio::spawns each call as an independent task, then join_alls them and preserves call order (spawn_tool_task at crates/octos-agent/src/agent/execution.rs:598 and execute_tools at :2483). The third face is outside the process: background Cron/Heartbeat timers waking sessions, child agents in synchronous-blocking or background-async dual mode, and fleet workers consuming tasks as independent processes, all sharing the same session state and message bus.

Concurrency itself is not the problem; correctness under concurrency is:

  • Session-level serialization: two messages in the same session must not concurrently rewrite state; a per-session lock order is required.
  • Tool-level parallelism: independent tools within one batch must run in parallel, or latency stacks linearly.
  • Graceful shutdown: on SIGTERM you cannot cut an in-flight conversation in half; octos threads an AtomicBool flag through signal handling and loop budget checks.
  • No accidental sharing: spawned tasks may not borrow stack state; any data crossing an .await or a task boundary must move ownership explicitly or go through Arc.

Get any one of these four wrong and the symptom is not a crash but "sporadic, unreproducible data corruption." On a production multi-tenant platform, that is the most expensive class of failure.

1.1.3 Challenge Three: Performance: a Slow LLM Does Not Excuse a Slow Framework

"The LLM call takes seconds anyway, so framework performance doesn't matter" is the most popular misconception in agent engineering. It fails in three ways.

First, latency is multiplicative. One agent execution may run dozens of iterations, each with message construction, context compression, and tool scheduling. 50ms of extra framework latency per iteration, across dozens of iterations, becomes visible stutter. In streaming scenarios it decides whether the typewriter feel survives.

Second, memory is a hard multi-tenant constraint. Every session holds conversation history, tool state, and a context window. The runtime's per-session overhead times the number of concurrent sessions is capacity you must plan up front: interpreted runtimes usually carry a markedly higher per-session baseline than compiled ones; measure capacity at your target concurrency, because at 100 concurrent sessions that delta decides whether one more container fits.

Third, the hot path lives in the framework, not the LLM. SSE stream parsing, message-channel shard splitting, context-compression truncation, tool-output size estimation: all of these run on every iteration. A representative small function in octos-core is truncate_utf8 (crates/octos-core/src/utils.rs:6-16):

#![allow(unused)]
fn main() {
pub fn truncate_utf8(s: &mut String, max_len: usize, suffix: &str) {
    if s.len() <= max_len { return; }
    let mut limit = max_len;
    while limit > 0 && !s.is_char_boundary(limit) {
        limit -= 1;
    }
    s.truncate(limit);
    s.push_str(suffix);
}
}

What it does is small: truncate safely at a UTF-8 character boundary. But it sits on every hot path: message trimming, channel sharding, tool-output capping. Note that it takes &mut String and truncates in place rather than returning a newly allocated String: on paths where every message may be truncated, what it saves is thousands of heap allocations per iteration. Unremarkable but everywhere; this class of overhead is the bulk of framework performance.

Those are the three challenges. What they share: none can be solved by "being careful while coding"; each demands structural guarantees from the language and the organization. Which brings us to the language choice.


1.2 Language Choice: Python, Go, and Rust Across Four Dimensions

octos's real candidate set had three entries: Python (the thickest LangChain/AutoGen ecosystem), Go (the smoothest cloud-native concurrency), Rust (the highest ceiling on safety and performance). The comparison below runs through four dimensions: safety, concurrency, performance, ecosystem. Conclusion first: Rust wins the first three, loses the fourth, and the fourth gap can be bridged with engineering.

1.2.1 Safety Dimension: Memory Safety Is Layer Zero of Defense in Depth

Of the three defensive layers in 1.1.1, the bottom one is "the runtime itself has no memory-safety holes." An agent runtime written in C/C++ can have the best sandbox in the world and still fall over first while parsing a maliciously crafted SSE shard or WebSocket frame, because parsing untrusted input is precisely where memory-safety vulnerabilities breed. octos's move is direct: the workspace root Cargo.toml sets lints workspace-wide (Cargo.toml:50-51):

[workspace.lints.rust]
unsafe_code = "deny"

One line of configuration, inherited by all 26 directories and 38 members; unsafe is compiler-rejected across the entire code base (unless explicitly exempted crate by crate). Python and Go each have a posture at this layer: the Python interpreter is written in C and has repeatedly shipped memory-safety CVEs from parsing malicious input; Go is memory-safe but its unsafe package and the cgo boundary remain surfaces where it can fail. The Rust difference is that "no unsafe" becomes a machine-checkable, whole-repository invariant, not a coding convention.

The type system carries a second value: making illegal states unrepresentable. The spots where agent systems breed the most bugs (message-role enums, task-state transitions, tool-result shapes) are all exhaustively matched enums in octos-core; miss one branch and it does not compile. That moves the line of defense a full stage earlier than "runtime validation + test coverage."

1.2.2 Concurrency Dimension: Killing Data Races at Compile Time

Start with three snippets of language semantics (illustrative code, not octos source):

// Go: two goroutines increment concurrently. Compiles; the data race lies in wait
go func() { counter++ }()
go func() { counter++ }()
# Python: the CPython GIL prevents threads from executing CPU work in parallel
threads = [threading.Thread(target=process_chunk) for c in chunks]
#![allow(unused)]
fn main() {
// Rust: the same shape fails to compile; borrows crossing threads must be explicit
s.spawn(|| counter += 1);  // ❌ error: closure may outlive borrowed value
}

Go's goroutine model is the easiest to write, but correctness rests on discipline and -race detection. The race detector is a happens-before algorithm, a testing-time tool; paths it never covers stay unprotected. Python's GIL closes off "one process, parallel CPU threads" entirely; asyncio handles I/O concurrency but one synchronous call stalls the whole event loop, and the serialization cost of multiprocess designs conflicts with the fine-grained shared-state model that 1.1.2 requires.

Rust's answer encodes concurrency correctness into the type system: Send (movable across threads) and Sync (shareable across threads) are two marker traits inferred by the compiler, and holding a non-Send borrow across an .await is a compile error. Each of the four correctness requirements from 1.1.2 (session serialization, tool parallelism, graceful shutdown, no stack-state borrowing in tasks) has a compile-time enforcement form in Rust. The cost is the learning curve; the payoff is an entire class of failures disappearing from the production incident list.

1.2.3 Performance Dimension: Deterministic Latency Without a GC

An agent framework's performance profile is unusual: many short-lived allocations (messages, shards, tool results), long-lived tasks (sessions, channel connections), and streaming paths that must stay smooth (SSE parsing forwarding token by token). The classic symptom of GC languages under this profile: pauses themselves are infrequent, but which iteration a pause lands in is unpredictable. Load-test p99 looks fine today, tomorrow one session's long conversation triggers a major collection and the streaming output visibly hitches.

Rust has no GC: allocation and freeing follow ownership, determined at compile time, and Drop destructors make file descriptors, child-process handles, and lock releases happen deterministically. Section 1.1.3's truncate_utf8 already showed the avoid-allocation idiom. One level up, here is the octos-agent tool trait signature (crates/octos-agent/src/tools/mod.rs:609-642, excerpt):

#![allow(unused)]
fn main() {
#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn input_schema(&self) -> serde_json::Value;
    async fn execute(&self, args: &serde_json::Value) -> Result<ToolResult>;
}
}

Note the Tool: Send + Sync bound. It is where the compile-time concurrency guarantees of 1.2.2 land on the tool system: any tool implementation that wants to be registered in the registry and shared across sessions is forced by the compiler to prove itself thread-safe. The performance and concurrency dimensions converge here: one type-system bound buys both parallel safety and zero-cost abstraction.

1.2.4 Ecosystem Dimension and the Price of the Choice

Honestly stated: the ecosystem is Rust's relative weak spot. LangChain/AutoGen tutorials and ready-made integrations are richer; Python is the de facto glue language of LLM work; Go is more mature in cloud-native infrastructure (the K8s ecosystem, metrics, deployment tooling). octos's response is to turn the ecosystem problem into an architecture problem. This explains the two chains in the 1.3 topology.

The first chain reaches outward to language ecosystems. Under octos-ffi (C-ABI) hang octos-pyo3 / octos-uniffi / octos-wasm, letting Python, Swift/Kotlin, and the browser embed octos through native bindings; users of the Python ecosystem need not give up Python.

The second chain reaches outward to capability ecosystems: octos-plugin lets external capabilities plug in via manifest plus binary protocol, and the 14 capability binaries of app-skills carry zero octos-* dependencies and evolve fully independently. Rust handles only the core that Rust must handle; the edges are left to each ecosystem.

The price of the choice must be stated just as plainly: a steep learning curve (the borrow checker is unfriendly to newcomers; reader profile A should budget two weeks of frustration); long compile times (a full build of 700K lines takes patience, and incremental builds plus the 26-crate split are exactly the mitigations); some domain libraries (SDKs for emerging protocols, say) must be written yourself instead of pip-installed. What those prices buy is the structural guarantee of the previous three dimensions. For the "multi-tenant + executable code + long-lived process" class of workload, Rust's compile-time guarantees pay back more than the ecosystem costs.


1.3 Workspace Topology: An Eight-Layer Map of 26 Crates

The language settles "how to write it right"; the workspace settles "how to grow it right." octos organizes 26 top-level directories into one Cargo workspace. This section first fixes the measurement methodology, then derives the layering from dependency direction, then corrects the three most commonly garbled facts, and finally gives the full dependency topology graph.

1.3.1 Scale Baseline and Measurement Methodology

All scale numbers in this chapter refer to main branch commit 9c157101 of the source repository (measured 2026-09-02), each reproducible:

MetricValueMethodology and command
Total crate directories26ls crates | wc -l; = 23 octos-* crates + app-skills + platform-skills + octos-web
Total Rust lines700,915find crates -name '*.rs' | xargs wc -l | tail -1; counts .rs files only; octos-web counts 0
Workspace members38length of the root Cargo.toml members list; of the 26 directories app-skills/platform-skills are multi-crate directories (14/1 members each), 23+14+1=38; octos-web is not a member
Message channel source files17ls crates/octos-bus/src/*_channel.rs | wc -l
Tool source files59ls crates/octos-agent/src/tools/*.rs | wc -l; a file count, not a tool count (includes crates/octos-agent/src/tools/mod.rs, crates/octos-agent/src/tools/registry.rs, tests, and other framework files)

The relation between 26 and 38 deserves its own emphasis: directory count ≠ member count ≠ core-library count. crates/app-skills/ has no top-level Cargo.toml; it is a directory holding 14 independent binary crates; platform-skills/ holds 1 (voice); octos-web has no Rust at all. Conflating these four numbers is the single most common first-layer misunderstanding outsiders have about octos's structure.

1.3.2 Eight Layers: L0–L7 Plus an Unnumbered Capability Layer

The layering is derived from dependency direction: each crate's layer = 1 + max(layer of every octos-* dependency in its [dependencies]); zero internal dependencies means L0. Under this rule the 26 directories fall into 8 layers (L0–L7) plus one capability layer that carries no layer number:

  • L0 foundation: octos-core (core types, task model and protocols, 22,313 lines, the domain language of the whole repository), octos-plugin (plugin SDK: manifest parsing, discovery, gating, 5,165 lines), octos-sandbox (1,468 lines; note it is a platform helper binary, see 1.3.3).
  • L1 primitives (depend only on core): octos-bus (message bus, 17 channels, session management, 42,767 lines), octos-llm (Provider abstraction, 35,087 lines), octos-memory (episodic memory, 6,428 lines), octos-diagnostics (diagnostics and update planning, 2,243 lines), octos-store (self-contained persistent storage, 2,664 lines), octos-fleet (Fleet kernel storage: transaction records + single-writer transaction CAS + recovery reconciliation, 16,888 lines), octos-wasm (browser-side protocol bindings, 883 lines).
  • L2 runtime: octos-agent (agent runtime, tool execution and coordination, 191,985 lines, the heart of the repository, depends on core/bus/memory/llm/plugin), octos-services (support services extracted from the CLI, 3,223 lines), octos-embed-llama (in-process GGUF embedding, 911 lines).
  • L3 orchestration (depend directly on agent): octos-pipeline (DOT pipeline engine, 32,799 lines), octos-swarm (fan-out/sequence/pipeline orchestration primitives, 4,980 lines), octos-dora-mcp (dora bridge compatibility re-export, 11 lines), octos-fleet-worker (closed non-interactive task worker, 6,842 lines).
  • L4 workflow: octos-workflows (depends on pipeline, 1,059 lines).
  • L5 integration: octos-server (HTTP/WebSocket API + session runtime, a facade of only 21 lines), octos-cli (CLI entry point, 307,299 lines, depending on 15 crates, the convergence point of the repository).
  • L6 embedding core: octos-ffi (C-ABI bindings, 1,372 lines, depends on cli/agent/llm/memory/embed-llama and others).
  • L7 bindings: octos-uniffi (Python/Swift/Kotlin, 465 lines), octos-pyo3 (recommended Python binding, 756 lines).
  • Capability layer (unnumbered): app-skills (14 capability binaries, 12,098 lines total), platform-skills/voice (1,188 lines), octos-web (frontend, 0 lines of Rust). Their shared trait: zero octos-* dependencies, depended on by no crate, hence excluded from core-library layering.

Two line-count extremes deserve a pause. octos-server stands at L5 with only 21 lines because it is a pure assembly facade; the real logic all lives in lower crates. octos-cli stands at L5 with 44% of the repository's lines because it is the front door, assembling the capabilities of 15 lower crates into runtime modes like chat/gateway/serve. Layer reflects dependency depth, not importance, and not lines of code.

1.3.3 Three Fact Corrections: Fix Three Impressions Before Reading the Repository

External material (including this book's v1 draft) carries three systematic misstatements about octos's structure. Correct them before reading the source.

Correction one: octos-sandbox is not the sandbox subsystem. Its Cargo.toml description reads "Platform sandbox helper for octos"; 1,468 lines; [dependencies] holds only clap and eyre, zero octos-* dependencies. It is a helper binary shipped with the platform. The real sandbox lives inside octos-agent: six files under crates/octos-agent/src/sandbox/ (crates/octos-agent/src/sandbox/bwrap.rs, crates/octos-agent/src/sandbox/docker.rs, crates/octos-agent/src/sandbox/landlock.rs, crates/octos-agent/src/sandbox/macos.rs, crates/octos-agent/src/sandbox/windows.rs, crates/octos-agent/src/sandbox/mod.rs), covering Linux bubblewrap/Landlock, Docker, macOS sandbox-exec, Windows AppContainer, and a no-sandbox fallback (crates/octos-agent/src/sandbox/mod.rs:1-23). When anything says "the octos sandbox," it always means octos-agent::sandbox.

Correction two: octos-web contains no Rust and is not a workspace member. It is a TypeScript project (package.json/tsconfig.json/vitest.config.ts), zero .rs files; grep the root Cargo.toml members and octos-web does not appear. It is frontend static assets, outside the Cargo dependency graph, and an isolated node in the topology.

Correction three: there is no harness crate. ls crates | grep harness returns nothing. Harness is a module inside octos-agent: crates/octos-agent/src/lib.rs:30-31 declares two sibling module files, pub mod harness_errors; and pub mod harness_events;. Do not mistake the four app-skills/harness-starter-* scaffolds for harness itself; they are user-facing starter templates, not the harness implementation. Chapter 10 covers Harness in full.

1.3.4 Dependency Topology: 63 Edges in One Graph

The graph below is the workspace's dependency topology: 63 dependency edges, not one more, not one fewer; every edge comes from the [dependencies] section of the corresponding crate's Cargo.toml (machine-check command: awk '/^\[dependencies\]/{f=1;next} /^\[/{f=0} f && /^octos-/' crates/*/Cargo.toml | wc -l → 63). A --> B means A depends on B; graph BT reads bottom-up: the higher a crate sits, the closer it is to the user.

graph BT
  subgraph L0["L0 Foundation"]
    core[octos-core]
    plugin[octos-plugin]
    sandbox[octos-sandbox<br/>platform helper binary]
  end
  subgraph L1["L1 Primitives"]
    bus[octos-bus]
    llm[octos-llm]
    memory[octos-memory]
    diag[octos-diagnostics]
    store[octos-store]
    fleet[octos-fleet]
    wasm[octos-wasm]
  end
  subgraph L2["L2 Runtime"]
    agent[octos-agent]
    services[octos-services]
    embed[octos-embed-llama]
  end
  subgraph L3["L3 Orchestration"]
    swarm[octos-swarm]
    dora[octos-dora-mcp]
    fworker[octos-fleet-worker]
    pipeline[octos-pipeline]
  end
  subgraph L4["L4 Workflow"]
    workflows[octos-workflows]
  end
  subgraph L5["L5 Integration"]
    server[octos-server]
    cli[octos-cli]
  end
  subgraph L67["L6/L7 Embedding & Bindings"]
    ffi[octos-ffi]
    uniffi[octos-uniffi]
    pyo3[octos-pyo3]
  end
  subgraph CAP["Capability layer / frontend (isolated, unnumbered)"]
    appskills[app-skills<br/>14 capability binaries]
    platskills[platform-skills/voice<br/>capability binary]
    web[octos-web<br/>frontend static assets<br/>outside the dependency graph]
  end

  bus --> core
  llm --> core
  memory --> core
  diag --> core
  store --> core
  fleet --> core
  wasm --> core
  agent --> core
  agent --> bus
  agent --> memory
  agent --> llm
  agent --> plugin
  services --> core
  services --> llm
  services --> bus
  embed --> llm
  swarm --> agent
  dora --> agent
  fworker --> agent
  fworker --> core
  fworker --> fleet
  fworker --> llm
  fworker --> memory
  pipeline --> core
  pipeline --> agent
  pipeline --> plugin
  pipeline --> llm
  pipeline --> memory
  workflows --> core
  workflows --> agent
  workflows --> pipeline
  server --> core
  server --> agent
  server --> llm
  server --> bus
  server --> store
  server --> services
  server --> workflows
  server --> pipeline
  server --> plugin
  cli --> core
  cli --> bus
  cli --> llm
  cli --> memory
  cli --> agent
  cli --> diag
  cli --> store
  cli --> services
  cli --> workflows
  cli --> pipeline
  cli --> swarm
  cli --> plugin
  cli --> fleet
  cli --> fworker
  cli --> embed
  ffi --> core
  ffi --> agent
  ffi --> llm
  ffi --> memory
  ffi --> cli
  ffi --> embed
  uniffi --> ffi
  pyo3 --> ffi

How to read it. (1) octos-core is the only root depended on by 15 crates; it must keep zero internal dependencies and extreme stability (the subject of Chapter 2). (2) octos-agent is depended on by 8 crates (pipeline, swarm, dora-mcp, fleet-worker, workflows, server, ffi, cli), the de facto second hub. (3) The four isolated nodes (app-skills, platform-skills/voice, octos-web, octos-sandbox) are not among the 63 edges: capability binaries and the frontend attach through process boundaries, not Cargo dependencies. That is the formal statement of "they don't belong to core-library layering." (4) All dependencies point downward, with no cycles; adding any upward edge fails outright at cargo, so the layering is an invariant enforced by the toolchain.

Engineering decision: mono-repo workspace vs multi-repo

26 crates and 63 internal dependency edges leave at least three organizational options on the table.

Option A: multi-repo, one repository per crate. Upsides: clear permission boundaries, independent releases and trimmed CI per repository, a smaller clone surface for outside contributors. The downsides are fatal for octos: with 63 edges, cross-repository change is the norm, not the exception. A type-definition change in octos-core ripples into 15 downstream crates, and under multi-repo you open 16 PRs, maintain 16 version numbers and 16 lockfiles, atomic cross-repo refactoring becomes impossible, and CI recompiles shared dependencies in every repository. Semantic versioning does not stop the human error of "the interface changed but the version didn't bump correctly."

Option B: a single mega-crate. Pack all 700K lines into one crate. Upsides: no cross-crate version problems, refactor freely. Equally fatal downsides: compile times run away (any one-line change triggers a full rebuild); non-Rust assets like octos-web have nowhere to live; the 14 app-skills binaries would be forced to drag in all core dependencies (they deliberately carry zero octos-* dependencies); feature-flag combinatorics explode, and one module flipping the wrong feature can pollute the global build.

Option C (octos's choice): a Cargo workspace mono-repo. It keeps single-repository atomicity (a cross-crate refactor is one commit, one CI run) while crate boundaries preserve compile isolation and dependency direction: the root Cargo.toml unifies members (38 entries), workspace.package (version/edition 2024/rust-version 1.85.0), workspace.lints (unsafe_code = "deny" in one place, repository-wide), and workspace.dependencies managing internal path-dependency versions. Layering falls out of [dependencies] direction; cargo itself is the architecture guardian.

The engineering dividend on the side: capability binaries (app-skills/platform-skills) join the workspace and enjoy the unified toolchain, yet with zero octos-* dependencies they never enter the core compile graph; if a crate ever needs to evolve independently, splitting it out of a workspace is far cheaper than splitting it out of a mega-crate. The tradeoffs: repository size grows, CI must do layered caching, and outside contributors face a 26-directory tree. octos hedges with directory layering (1.3.2) and this book's navigation (1.4).


1.4 A Tour of the Book

The v2 edition unfolds in four parts (foundation, engine, platform, dual loop) with 21 chapters plus appendices. Numbering follows the v2 rewrite plan (shifted from v1: the old Chapter 10 bus moved to Chapter 11, and Chapter 10 became the new Harness chapter):

PartChapterTopic
Part I FoundationCh1Why Rust? Why an Agent OS? (this chapter)
Ch2octos-core: defining the domain language with the type system
Ch3octos-llm: taming the chaos of LLM providers
Ch4octos-memory: the engineering of hybrid search
Part II EngineCh5Agent loop: the full lifecycle of one conversation
Ch6The tool system: design patterns behind 59 source files
Ch7Defense in depth: from sandbox to prompt-injection defense
Ch8Context management: working efficiently in a bounded window
Ch9Extension mechanisms: the skills-and-plugins dual track
Ch10Harness (new): validators, event ABI, schema versioning
Part III PlatformCh11octos-bus: unified message abstraction over 17 channels
Ch12Concurrency model: Tokio, supervisor, peer, lease: three layers of scheduling
Ch13octos-pipeline: a DOT-graph-driven workflow engine (12 IR node kinds)
Ch14Runtime modes and the configuration system (incl. stdio/solo)
Ch15Production: octos-store / octos-services, authentication and monitoring
Ch16Fleet (new): a recoverable plan-execution kernel
Ch17Swarm (new): contract fan-out and aggregation gates
Ch18Goal and Peer (new): moving objectives out of the context window
Part IV Dual LoopCh19octoscode (new): terminal client and the UI protocol
Ch20OctoLoop (new): the outer-loop protocol OLP v2
Ch21herdr and outer-loop operations practice (new)
AppendicesA–D, FFull 26-crate dependency graph, tool quick reference, configuration reference (mcp_servers/sub_providers/validators), feature flags, OLP v2 protocol quick reference (new)

Suggested routes: reader profile A reads sequentially, with Ch1–Ch5 building the dual foundation of Rust plus agents; profile B can skip the language argument and go straight to Ch5, Ch12, Ch16; profile C prioritizes Ch1, Ch7, Ch11, Ch13 and skips the implementation sidebars; profile D reads this chapter and Appendix A before touching a first PR.

1.5 Chapter Recap

  1. Problem space: a multi-tenant AI agent platform faces three entangled challenges: security isolation (an attack surface of 59 tool source files plus 17 channels), concurrency (correctness across the session/tool/process faces), performance (multiplicative latency, multi-tenant memory, framework hot paths). Together they make the choice an architecture decision.
  2. Language choice: Rust wins on safety (repository-wide deny(unsafe_code) plus the type system), concurrency (Send/Sync compile-time guarantees), and performance (no GC, deterministic destructors, zero-allocation hot paths); the ecosystem gap is hedged with the FFI/binding chain (pyo3/uniffi/wasm) and the plugin/skill extension mechanisms.
  3. Workspace topology: 26 directories = 23 octos-* crates + 2 skill directories + 1 frontend directory; 38 workspace members fall by dependency direction into 8 layers L0–L7 plus the unnumbered capability layer; 63 dependency edges, none cyclical, all pointing down. octos-sandbox is a helper binary (the real sandbox is the six files of octos-agent::sandbox), octos-web is non-Rust and not a member, and harness is a module inside octos-agent, not a crate. These three corrections are the right starting point for reading the repository.

From the next chapter we work bottom-up: first, how octos-core at L0 defines the domain language of the whole platform with the type system.


Further reading

  • Cargo workspaces: the official "Workspaces" chapter, https://doc.rust-lang.org/cargo/reference/workspaces.html; read against the members/lints/dependencies inheritance in 1.3.
  • Rust ownership and concurrency: The Rust Programming Language Ch4 "Understanding Ownership" and Ch16 "Fearless Concurrency", https://doc.rust-lang.org/book/. The inference rules for Send/Sync.
  • The Tokio tutorial: https://tokio.rs/tokio/tutorial, prerequisite for the concurrency model in Ch12.
  • OWASP Top 10 for LLM Applications: https://owasp.org/www-project-top-10-for-large-language-model-applications/. The threat taxonomy of prompt injection and agent security.
  • Appendix A of this book: the full 26-crate dependency graph (the complete version of this chapter's topology).

Exercises

  1. Attack-surface estimate: using the methodology of 1.1.1, estimate the attack surface of a homegrown agent service with 3 channels and 20 registered tools. Which boundaries need their own trust model? Which layer is weakest?
  2. Compile-time vs runtime concurrency: which classes of error do Go's -race and Rust's Send/Sync each catch, and which do they miss? If a team migrates from Go to Rust, which tests can be deleted and which must stay?
  3. Layering tradeoff: octos splits L6/L7 (ffi → uniffi/pyo3) into two layers instead of letting pyo3 depend on all core crates directly. What does the split make more expensive, and what cheaper? If a Kotlin binding landed tomorrow, which layer would change?
  4. The value of an isolated capability layer: the 14 app-skills binaries carry zero octos-* dependencies. What engineering property does that buy? If they depended directly on octos-agent, what would happen to the compile graph and the release cadence?
  5. Organizational mirror: following the topology graph in 1.3.4, draw the same dependency graph for a system you know well. Is its layering toolchain-enforced like octos's, or does it exist only in documentation? What are the long-term consequences of the difference?

Version note

Version note: This chapter analyzes the octos main workspace @ 9c157101 (measured 2026-09-02) with its 26 crates; the methodology and reproduction commands for every scale number (26 directories, 38 members, 700,915 lines of Rust, 17 channel source files, 59 tool source files, 63 dependency edges) are in assets/ch01-facts.md, verifiable line by line against the source repository.

Relative to the v1 draft, this chapter makes three classes of updates. First, three fact corrections: octos-sandbox is a platform helper binary, not the sandbox subsystem (the real sandbox is the six files of octos-agent::sandbox); octos-web contains no Rust and is not a workspace member; there is no harness crate: harness is the internal harness_errors/harness_events module of octos-agent. Second, topology layering updated: the v1 four-layer architecture and its core-crate counting are void; v2 derives L0–L7, 8 layers plus the unnumbered capability layer, from [dependencies] direction. Third, book structure adjusted: Harness became its own Chapter 10, the old Chapter 10 bus moved to Chapter 11, and Chapters 16 onward are new.

Chapter 2: octos-core: Defining the Domain Language with the Type System

Positioning: This chapter goes into octos's bottom layer, the octos-core crate (currently 22,313 lines of Rust source, about 15,005 lines after excluding the test file crates/octos-cli/src/api/ui_protocol_tests.rs, with most of the growth coming from UI Protocol wire types), and shows how the Rust type system builds the domain language of an AI agent platform. Prerequisites: Chapter 1. Intended for every reader who wants to understand octos's type foundation, especially reader A, learning Rust enums and error-handling design through a working system, and reader B, the experienced developer curious about the design philosophy of a zero-dependency core crate.

Think of octos as a city. octos-core is not its buildings or its roads but its language: the vocabulary and grammar residents use to talk to each other. Task, Message, MessageRole, Error, and the UI Protocol wire types define how every component in the system describes its state and intent. Every upper crate in octos depends on these types, while octos-core itself depends on no other crate in the workspace.

That zero-dependency constraint is deliberate. It keeps the boundary clean while the domain language evolves: when octos-llm refactors a Provider implementation or octos-bus reworks its channels, core absorbs only the wire identity and domain model that genuinely cross crates, never upper-layer implementation logic. This chapter starts with the Task state machine, walks through each foundational type, and closes with the engineering case for the zero-dependency strategy.


Every unit of work an AI agent performs in octos is modeled as a Task. Task is the system's work unit: from "write me some code" to "review this diff", every user request ends up as a Task.

2.1.1 The Task struct

Task is defined at crates/octos-core/src/task.rs:11-29:

#![allow(unused)]
fn main() {
pub struct Task {
    pub id: TaskId,                      // UUID v7, time-sortable by construction
    pub parent_id: Option<TaskId>,       // subtask hierarchy
    pub status: TaskStatus,              // current state
    pub kind: TaskKind,                  // task type
    pub context: TaskContext,            // execution context
    pub result: Option<TaskResult>,      // result, present once complete
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
}

Several design choices stand out.

TaskId uses UUID v7, not v4 (crates/octos-core/src/types.rs:180-189). UUID v4 is pure random, while the first 48 bits of a v7 encode a millisecond timestamp. A TaskId therefore sorts by creation time: during debugging and log analysis you can read task ordering straight off the ID, without a separate lookup of created_at.

parent_id: Option<TaskId> supports task hierarchy. When a complex task decomposes into subtasks (multi-step execution inside a Pipeline, say), each subtask points at its parent through parent_id, forming a tree.

result: Option<TaskResult> exists only after the Task completes. Rust's Option makes the compiler force callers to handle "the result may not exist yet": you cannot access the result of a Pending Task without checking first.

2.1.2 TaskStatus: Making Illegal Transitions Unrepresentable at Compile Time

TaskStatus is an enum that carries data (crates/octos-core/src/task.rs:63-77):

#![allow(unused)]
fn main() {
pub enum TaskStatus {
    Pending,
    InProgress { agent_id: AgentId },
    Blocked { reason: String },
    Completed,
    Failed { error: String },
}
}

The InProgress variant carries agent_id, so it records not just the state but who is executing the task. Likewise Blocked carries the reason and Failed carries the error. This pairing of state with contextual data is the core advantage Rust enums hold over the enums of other languages (Go's iota constants, or Java's traditional enum).

In Python you would model the same semantics with a string field status: str plus optional fields agent_id: Optional[str] and error: Optional[str]. That design admits illegal states: a Task with status="pending" but agent_id="agent-1", or status="completed" with error="something failed". Rust's enum makes such states impossible at the type level.

2.1.3 The state transition diagram

The legal Task state transitions are:

stateDiagram-v2
    [*] --> Pending: created
    Pending --> InProgress: assigned to Agent
    InProgress --> Blocked: waiting on external resource
    InProgress --> Completed: execution succeeded
    InProgress --> Failed: execution failed
    Blocked --> InProgress: block cleared
    Blocked --> Failed: timeout or cancel

Figure 2-1: the Task state machine. Each transition corresponds to a distinct business event. Note that Pending can move only to InProgress (never straight to Completed), and InProgress is the only state that reaches Completed. Every completed task has therefore passed through execution.

2.1.4 TaskKind: five task types

TaskKind defines five kinds of work (crates/octos-core/src/task.rs:79-99):

#![allow(unused)]
fn main() {
pub enum TaskKind {
    Plan { goal: String },
    Code { instruction: String, files: Vec<PathBuf> },
    Review { diff: String },
    Test { command: String },
    Custom { name: String, params: serde_json::Value },
}
}

The first four cover the common predefined scenarios: Plan, Code, Review, Test. The fifth, Custom, is the extension point: name identifies the task type and params carries arbitrary JSON. This "a closed set of predefined cases plus an open extension" pattern recurs throughout octos (see Chapter 6 on the tool system and Chapter 9 on the extension mechanism).

2.1.5 TaskContext and TaskResult

TaskContext (crates/octos-core/src/task.rs:102-115) is a snapshot of the task's execution environment:

#![allow(unused)]
fn main() {
pub struct TaskContext {
    pub working_dir: PathBuf,
    pub git_state: Option<GitState>,      // branch, uncommitted changes, HEAD commit
    pub working_memory: Vec<Message>,      // recent conversation turns
    pub episodic_refs: Vec<EpisodeRef>,    // references to past episodes
    pub files_in_scope: Vec<PathBuf>,
}
}

The split between working_memory and episodic_refs deserves attention: working_memory is the current session's short-term memory (the most recent conversation turns), while episodic_refs are relevant fragments retrieved from long-term memory (see Chapter 4). This dual-memory architecture mirrors the human distinction between working memory and episodic memory.

TaskResult (crates/octos-core/src/task.rs:125-157) records the task's output across 7 fields: schema_version (the durable ABI version, covered in 2.3), success, output, files_modified, files_to_send, subtasks, and token_usage.

TokenUsage (crates/octos-core/src/task.rs:159-173) tracks more than input/output tokens: reasoning_tokens covers chain-of-thought tokens (used by reasoning models such as o1 and kimi-k2.5), and cache_read_tokens/cache_write_tokens cover Provider cache hits and writes. These five dimensions let upper layers compute cost precisely and tune caching. During serialization, zero-valued fields are skipped to keep the JSON compact.


2.2 Message and MessageRole: One Abstraction Across Providers

An AI agent platform has to talk to multiple LLM providers: Anthropic's Claude, OpenAI's GPT-4, Google's Gemini, a local Ollama. Each provider's API names and interprets message roles slightly differently. octos-core defines the unified Message and MessageRole types as the common denominator for all of them.

2.2.1 The Message struct

Message is defined at crates/octos-core/src/types.rs:227-258:

#![allow(unused)]
fn main() {
pub struct Message {
    pub role: MessageRole,
    pub content: String,
    pub media: Vec<String>,                         // image/audio file paths
    pub tool_calls: Option<Vec<ToolCall>>,           // tool calls requested by the LLM
    pub tool_call_id: Option<String>,                // call ID this tool response answers
    pub reasoning_content: Option<String>,           // chain-of-thought content
    pub client_message_id: Option<String>,           // client optimistic-UI / idempotency token
    pub thread_id: Option<String>,                   // AppUI thread rendering group key
    pub timestamp: DateTime<Utc>,
}
}

The media field (crates/octos-core/src/types.rs:232-234) supports multimodal input: when a user sends an image or audio, the file paths are stored here, and octos-llm converts them into the provider's format (base64 or a URL reference) when building the API request. An empty media vector is skipped during serialization.

reasoning_content (crates/octos-core/src/types.rs:239-241) exists for reasoning models (OpenAI o1, Kimi k2.5): these models emit an internal chain of reasoning before the final answer. Storing the reasoning separately from the answer lets upper layers decide whether to display the chain of thought.

client_message_id and thread_id are UI/persistence identity fields that matter on the current main branch (crates/octos-core/src/types.rs:229-256). They are not part of any provider's message format; they are cross-crate protocol fields shared by AppUI, the Gateway, and Session persistence: the former aligns a client's optimistic UI bubble with the server-persisted seq, the latter groups user/assistant/tool messages into one rendering thread.

2.2.2 Message identity: ClientMessageId, ThreadId, and TurnId are not interchangeable

The current source splits three similar-looking identities into three distinct types:

TypeDefined atResponsibilityTypical origin
ClientMessageIdcrates/octos-core/src/types.rs:12-64Optimistic-UI / idempotency token minted when the client submits a user messageWeb/AppUI client
ThreadIdcrates/octos-core/src/types.rs:79-177Rendering group key that routes assistant/tool replies back to the originating user bubbleUsually rooted at a ClientMessageId
TurnIdcrates/octos-core/src/ui_protocol.rs:607-623Server-side turn identity of the UI ProtocolCreated by the backend
flowchart LR
    C[ClientMessageId<br/>client optimistic identity] --> T[ThreadId<br/>render grouping]
    U[User Message] --> C
    U --> T
    A[Assistant / Tool Message] --> T
    R[TurnId<br/>server protocol identity] -. distinct .- T
    R -. distinct .- C

The separation is the typed fix for a real bug chain. ClientMessageId and ThreadId both wrap a String, but their semantics differ entirely; TurnId is a UUID-shaped protocol identity. Making them newtypes lets the compiler reject mistakes like using a client message id as a turn id (crates/octos-core/src/types.rs:12-177, crates/octos-core/src/ui_protocol.rs:607-623).

Message also offers constructors that bind identity explicitly:

#![allow(unused)]
fn main() {
pub fn user_with_cmid(content: impl Into<String>, cmid: ClientMessageId) -> Self
pub fn user_rooting_thread(content: impl Into<String>, cmid: ClientMessageId) -> Self
pub fn assistant_with_thread(content: impl Into<String>, thread_id: ThreadId) -> Self
pub fn tool_with_thread(content: impl Into<String>, tool_call_id: impl Into<String>, thread_id: ThreadId) -> Self
}

assistant_with_thread() and tool_with_thread() require the caller to pass the ThreadId explicitly (crates/octos-core/src/types.rs:310-350). This matches the Session write rules of Chapter 10: new Assistant/Tool writes can no longer guess the thread by "looking back at the most recent user message", because under concurrent turns that guess attaches a late delta or a tool result to the wrong bubble. The core crate states the constraint at the type level first; the upper persistence path then fails closed.

2.2.3 MessageRole: the dual implementation of as_str() and Display

MessageRole has only four variants (crates/octos-core/src/types.rs:444-451):

#![allow(unused)]
fn main() {
pub enum MessageRole {
    System,
    User,
    Assistant,
    Tool,
}
}

What matters is the pair of method implementations. as_str() (crates/octos-core/src/types.rs:453-463) returns a &'static str, mapping the four variants to "system", "user", "assistant", and "tool" in an exhaustive match with no wildcard arm; adding a variant forces the compiler to make you update this mapping.

The Display trait implementation (crates/octos-core/src/types.rs:465-469) has a one-line body: f.write_str(self.as_str()). Why implement both? They serve different call sites:

  • as_str() takes self by value and returns &'static str. That works because MessageRole implements the Copy trait: an enum of four data-less variants copies for the price of one byte. Pass-by-value suits zero-allocation paths, such as setting a JSON field value while building an API request.
  • Display serves string formatting (format!(), println!(), and friends) and is the standard interface across the Rust ecosystem.

The pattern keeps serialization consistent across providers: whether the request goes to Anthropic or OpenAI, roles always serialize as the four lowercase strings "system", "user", "assistant", "tool". Provider differences (Anthropic putting the system message in its own field instead of the message array, for instance) are handled in octos-llm and never leak into the core type layer.

2.2.4 ToolCall and the metadata extension point

ToolCall (crates/octos-core/src/types.rs:471-479) is the data structure for an LLM requesting a tool call:

#![allow(unused)]
fn main() {
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: serde_json::Value,
    pub metadata: Option<serde_json::Value>,
}
}

The metadata field (crates/octos-core/src/types.rs:476-478) is the extension point reserved for provider-specific data. Google Gemini's tool calls, for example, carry a thought_signature field used to verify that the call came out of the model's reasoning. Storing such heterogeneous data in an Option<Value> spares the core types a per-provider field.

2.2.5 Convenience constructors

Message keeps three legacy convenience constructors (crates/octos-core/src/types.rs:355-417) used by tests, deserialization round-trips, and older call sites: Message::user(content), Message::assistant(content), and Message::system(content), all with the signature (content: impl Into<String>) -> Self.

Note the parameter type: impl Into<String> rather than String or &str. Callers can pass a String, a &str, even a Cow<str>, and the compiler picks the most efficient conversion. This is a common Rust API design pattern: generics spare callers the type-conversion ceremony. All three constructors just wrap the content in a Message of the corresponding role; nothing more to say about them.


2.3 Durable ABI: schema_version on TaskResult and SessionSummary

octos-core now also carries a quieter responsibility: defining the stable ABI for cross-crate persisted payloads. Two examples stand out.

TaskResult carries schema_version (crates/octos-core/src/task.rs:138-157):

#![allow(unused)]
fn main() {
pub struct TaskResult {
    #[serde(default = "default_task_result_schema_version")]
    pub schema_version: u32,
    pub success: bool,
    pub output: String,
    pub files_modified: Vec<PathBuf>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files_to_send: Vec<PathBuf>,
    pub subtasks: Vec<TaskId>,
    pub token_usage: TokenUsage,
}
}

This field is not a display version number; it is the durable ABI for task results, the workspace contract, and the harness as they cross disk and process boundaries. Payloads written before the field existed fall back through the serde default to TASK_RESULT_SCHEMA_VERSION = 1, so historical data stays readable.

The second example is SessionSummary (crates/octos-core/src/task.rs:233-305). It is the core payload of typed compaction in Chapter 8:

#![allow(unused)]
fn main() {
pub struct SessionSummary {
    #[serde(default = "default_session_summary_schema_version")]
    pub schema_version: u32,
    pub goal: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub progress_done: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub progress_in_progress: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub decisions: Vec<DecisionRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub files: Vec<FileRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub next_steps: Vec<String>,
}
}

The point of SessionSummary is not "compress the chat log into a paragraph"; it stores goal, constraints, progress, decisions, files, and next_steps as separate fields so later compaction rounds can update the structured fields incrementally. A missing schema_version defaults to the current version; if a future version is read, validate_schema_version() returns the typed error UnsupportedSessionSummaryVersion instead of panicking or silently dropping fields (crates/octos-core/src/task.rs:188-305).

flowchart TD
    History[Conversation history] --> Summary[SessionSummary schema_version=1]
    Summary --> Goal[goal]
    Summary --> Constraints[constraints]
    Summary --> Decisions[decisions + stale markers]
    Summary --> Files[files]
    Summary --> Next[next_steps]
    Summary --> Check{future schema?}
    Check -->|no| Continue[compaction continues]
    Check -->|yes| Error[UnsupportedSessionSummaryVersion]

That is also why SessionSummary lives in octos-core rather than octos-agent: Chapter 8's compaction, Chapter 9's harness ABI, and Chapter 14's UI/runtime observability all reference it. What the core crate provides here is wire-stable domain language, not a concrete compaction algorithm.


2.4 Error Design: Why eyre and not anyhow

The Rust ecosystem has two mainstream error-handling libraries, anyhow and eyre. Both provide type-erased error reporting (anyhow::Error / eyre::Report), and octos picked eyre/color-eyre. The reasons are worth working through.

2.4.1 octos's error type

octos-core's Error is defined at crates/octos-core/src/error.rs:10-17:

#![allow(unused)]
fn main() {
pub struct Error {
    pub kind: ErrorKind,
    pub context: Option<String>,
    pub suggestion: Option<String>,
}
}

The key design is the three-layer structure: kind classifies the error, context adds execution context, and suggestion offers an actionable fix.

ErrorKind is an enum of 15 variants (crates/octos-core/src/error.rs:20-56) covering every error category in the system:

#![allow(unused)]
fn main() {
pub enum ErrorKind {
    TaskNotFound(String),
    AgentNotFound(String),
    InvalidStateTransition { from: String, to: String },
    LlmError { provider: String, message: String },
    ApiError { provider: String, status: u16, body: String },
    ToolError { tool: String, message: String },
    ConfigError(String),
    ApiKeyNotSet { provider: String, env_var: String },
    UnknownProvider(String),
    Timeout { operation: String, seconds: u64 },
    ChannelError { channel: String, message: String },
    SessionError(String),
    IoError(std::io::Error),
    SerializationError(String),
    Other(eyre::Report),
}
}

Note the last variant, Other(eyre::Report): this is eyre::Report, not anyhow::Error.

2.4.2 eyre vs anyhow: the reasons

anyhow and eyre expose nearly identical core APIs, but two differences decided the choice.

Custom error reporters. eyre lets you install a custom reporter through eyre::set_hook(). color-eyre is such a reporter: on error it captures the std::backtrace::Backtrace and tracing_error::SpanTrace automatically and prints them in color. For a CLI tool, when an agent run fails, the developer gets a color-highlighted error chain and stack trace at once, which beats anyhow's plain-text output for debugging.

Ecosystem alignment. The octos workspace declares both eyre and color-eyre in its dependencies (Cargo.toml:97-98). color-eyre is initialized at the CLI entry point (color_eyre::install() in main()), while eyre::Report serves as the general-purpose error type across the code base. Mixing anyhow::Error with eyre::Report would force conversions at every boundary and add complexity for nothing.

2.4.3 Actionable error messages

The most instructive part of octos's error design is not the library choice but the principle of making error messages actionable. Consider one of the convenience constructors (crates/octos-core/src/error.rs:80-173):

#![allow(unused)]
fn main() {
pub fn api_key_not_set(provider: impl Into<String>, env_var: impl Into<String>) -> Self {
    let provider = provider.into();
    let env_var = env_var.into();
    Self::new(ErrorKind::ApiKeyNotSet {
        provider: provider.clone(),
        env_var: env_var.clone(),
    })
    .with_suggestion(format!(
        "Set the API key:\n    export {env_var}=your-api-key\n  Or add to .octos/config.json:\n    {{\"api_key_env\": \"{env_var}\"}}"
    ))
}
}

When a user forgets to set an API key, the error does not just say "key not set"; it says "set the ANTHROPIC_API_KEY environment variable, or configure it in config.json". Similarly, api_error() tailors the suggestion to the HTTP status: 401 says check the key, 429 says rate-limited, 504 says timeout.

The Display implementation (crates/octos-core/src/error.rs:174-224) formats the three layers into user-friendly output and uses truncated_utf8() to cut oversized API response bodies safely, so error logs never drown in a giant JSON dump.


2.5 truncate_utf8: the UTF-8 Safety Philosophy Behind One Small Function

truncate_utf8 is among the smallest and most refined functions in octos-core. It is 10 lines long (crates/octos-core/src/utils.rs:6-16) and solves a problem that shows up constantly in multilingual AI applications: how to truncate a string that may contain multi-byte characters such as Chinese, Japanese, or emoji.

2.5.1 The problem: UTF-8's multi-byte trap

UTF-8 is a variable-length encoding: ASCII takes 1 byte, a Chinese character 3 bytes, an emoji 4 bytes. When you truncate a string to N bytes, the cut can land in the middle of a multi-byte character. Take the four-character Chinese greeting meaning "hello world": each character is 3 bytes, four characters total 12 bytes; truncated to 7 bytes you keep [E4 BD A0] [E5 A5 BD] plus a lone [E4], the first byte of the third character, which no longer forms a legal UTF-8 sequence.

In C/C++ such a truncation produces an invalid UTF-8 string that can crash downstream parsers. Python's str[:7] truncates by character instead of byte, which avoids the crash but gives up precise control over the byte budget.

2.5.2 Two variants: in-place and copying

octos provides two truncation functions.

truncate_utf8 (crates/octos-core/src/utils.rs:6-16) truncates in place, mutating the original string:

#![allow(unused)]
fn main() {
pub fn truncate_utf8(s: &mut String, max_len: usize, suffix: &str) {
    if s.len() <= max_len {
        return;
    }
    let mut limit = max_len;
    while limit > 0 && !s.is_char_boundary(limit) {
        limit -= 1;
    }
    s.truncate(limit);
    s.push_str(suffix);
}
}

truncated_utf8 (crates/octos-core/src/utils.rs:21-30) returns a new string and leaves the original untouched:

#![allow(unused)]
fn main() {
pub fn truncated_utf8(s: &str, max_len: usize, suffix: &str) -> String {
    if s.len() <= max_len {
        return s.to_string();
    }
    let mut limit = max_len;
    while limit > 0 && !s.is_char_boundary(limit) {
        limit -= 1;
    }
    format!("{}{}", &s[..limit], suffix)
}
}

The core algorithm is the same: walk back from position max_len until you hit a legal UTF-8 character boundary (is_char_boundary()), then append the suffix. Note that max_len in both functions does not include the suffix length, so the final string can exceed max_len after the suffix is appended. That is intentional: max_len caps the retained content, and the suffix is an extra marker. Callers must budget room for the suffix when setting max_len.

The two variants differ in ownership semantics:

  • truncate_utf8 takes &mut String, mutates in place, and allocates nothing extra (beyond appending the suffix)
  • truncated_utf8 takes &str (an immutable reference), returns a new String, and pays one heap allocation

Callers pick by situation: if you own the string and no longer need the original, use the in-place version; if the string is borrowed (a &str from an API response, say), use the copying version.

2.5.3 truncate_head_tail and TruncationReport: structured head-and-tail truncation

For tool output and error messages, keeping only the head is often not enough: the trailing error or conclusion matters just as much. After commit d8125d18 (2026-08-31), octos solves this with a pair of functions: truncate_head_tail (crates/octos-core/src/utils.rs:91-96) and the truncate_head_tail_report behind it (crates/octos-core/src/utils.rs:105).

truncate_head_tail_report is the real implementation; it returns a structured TruncationReport:

#![allow(unused)]
fn main() {
pub fn truncate_head_tail_report(s: &str, max_len: usize, head_ratio: f32) -> TruncationReport
}

Beyond the truncated content, the report carries every fact about the truncation: truncated flags whether truncation happened; truncated_by records which limit fired (only TruncatedBy::Bytes is reachable today; the Lines variant is reserved for future line-count truncation); total_bytes / output_bytes / omitted_bytes are the input length, output length, and bytes dropped; max_len and head_ratio record the parameters that actually took effect (head_ratio clamped to [0.1, 0.9]). The truncated output joins head and tail with a \n\n... [N bytes omitted] ...\n\n marker, where omitted_bytes is the exact number matching the N in the marker, and both cut points are UTF-8-safe through is_char_boundary().

Why return the report at all? The source comment states the motive: if callers inferred the dropped amount as total - content.len(), they would miss the length of the omission marker itself. When an upper layer must tell the model honestly "what you see is trimmed output, and here is how much was cut" (Chapter 8's context management does exactly this), it should read the report rather than do its own subtraction.

truncate_head_tail is a thin wrapper that preserves the old interface; its body is one line:

#![allow(unused)]
fn main() {
pub fn truncate_head_tail(s: &str, max_len: usize, head_ratio: f32) -> String {
    truncate_head_tail_report(s, max_len, head_ratio).content
}
}

One implementation, two exits: old call sites that want a String keep the old name, callers that need the full report switch to the new function, and the same input yields a byte-identical content.

This family of functions serves several octos scenarios:

  • Truncating tool output (stdout/stderr of shell commands)
  • Truncating API response bodies inside error messages (crates/octos-core/src/error.rs)
  • Truncating message digests during context compression (see Chapter 8)

2.5.4 tool_output_limit: per-tool truncation policy

tool_output_limit (crates/octos-core/src/utils.rs:180-199) assigns different byte limits to different tools:

ToolLimitRationale
read_file50,000source files can be large
shell, grep30,000command output is usually leaner
web_fetch40,000web pages are moderate in size
web_search20,000search results are summaries
search, deep_search, news_fetch200,000deep search aggregates source texts
deep_research, spawn50,000deep tasks need more context
default50,000safe cap

search is the runtime tool name of the built-in deep-search skill, and deep_search is a contract slot reserved for a future variant; the source comment documents this deliberately defensive aliasing. The limits are not arbitrary. Plain search results are information-dense (every result is a useful summary), so 20,000 bytes suffice; source files have uneven information density (you may need a whole function body), so they get 50,000 bytes; deep-search output aggregates source texts from multiple origins, and trimming it would cut the evidence chain, so it gets 200,000 bytes. These limits work alongside the LLM context-window budget (see Chapter 8 on context management).


2.6 SessionKey: Designing the Multi-Tenant Session Identifier

SessionKey (crates/octos-core/src/types.rs:489-567) is the linchpin of session routing in a multi-tenant system. Its evolution tracks the expansion from a single channel to multiple channels, from a single profile to multiple profiles, and on to topic-branched sessions.

2.6.1 Format evolution

SessionKey supports four backward-compatible formats:

FormatExampleScenario
channel:chat_idtelegram:12345base: single profile
profile:channel:chat_idwork:telegram:12345multi-profile isolation
channel:chat_id#topictelegram:12345#researchmultiple topics in one session
profile:channel:chat_id#topicwork:telegram:12345#researchfull form

The base_key() method (crates/octos-core/src/types.rs:525-528) returns the part without the #topic suffix and is used for session persistence (different topics under the same base_key share a persistence file). The topic() method (crates/octos-core/src/types.rs:530-533) extracts the topic suffix.

2.6.2 Channel inference, not construction-time validation

The current source does not reject unknown channels in SessionKey::new(); the constructor only formats the string. The public is_reserved_channel_name() (crates/octos-core/src/types.rs:603-630, delegating internally to the private is_channel_name()) exists to help split_base_key() decide whether the first segment of a three-part key is a profile_id or a channel. The whitelist holds 19 known channels:

api, cli, dingtalk, discord, email, feishu, line, local, matrix, qq-bot,
slack, system, telegram, test, twilio, wechat, wecom, wecom-bot, whatsapp

The distinction matters: SessionKey solves the structured parsing of a session routing key, not global validation of channel configuration. Real channel/profile validation happens higher up, in the CLI/API configuration path; core offers only a low-dependency, serializable key shape.


2.7 AgentMessage: the Inter-Agent Coordination Protocol

AgentMessage (crates/octos-core/src/message.rs:10-29) defines the coordination protocol between agents:

#![allow(unused)]
fn main() {
pub enum AgentMessage {
    TaskAssign { task: Box<Task> },
    TaskUpdate { task_id: TaskId, status: TaskStatus },
    TaskComplete { task_id: TaskId, result: TaskResult },
    ContextRequest { task_id: TaskId, query: String },
    ContextResponse { task_id: TaskId, context: Vec<Message> },
}
}

Five message types cover the core coordination scenarios: assign a task, update status, notify completion, request context, return context. Note the Box<Task> in TaskAssign: the Task struct is large, and heap-allocating it with Box avoids the memory waste that uneven variant sizes would otherwise cause in the enum.

The task_id() method (crates/octos-core/src/message.rs:31-42) returns Option<&TaskId>, giving every variant one uniform access to the task ID. Callers read the associated task ID without pattern-matching each variant; they only handle the Option.


2.8 abort: Multilingual Interruption Detection

One small module deserves a look: crates/octos-core/src/abort.rs implements multilingual interruption detection for agents. When a user sends a plain "stop" mid-run, in English, Chinese, Japanese ("yamete"), or Russian ("stop" in Cyrillic), the system must recognize it at once and terminate the current operation.

The ABORT_TRIGGERS array (crates/octos-core/src/abort.rs:32-71) holds 28 trigger words across 9 languages (the comment at the top of the file says 30+; the array's actual count is authoritative). is_abort_trigger() (crates/octos-core/src/abort.rs:6-13) trims and lowercases the input, then matches exactly. abort_response() (crates/octos-core/src/abort.rs:15-30) returns a localized cancellation confirmation matching the trigger's language.

The code comment also records the words deliberately left out: "wait", "exit", and "para" appear too often in ordinary conversation and would cause false positives. The trade is pragmatic: rather than interrupt on a false positive, miss some abort signals and let the user repeat the command.


2.9 The Boundary of core: Seven Files Added in 2026

In the second half of 2026 octos-core took in seven more modules. On the surface core grew fatter, but the classification rule stayed the same: each is a single source of truth that multiple upper crates depend on while depending on no upper crate itself. One line of positioning per file:

FileLinesPositioning
crates/octos-core/src/abort.rs120multilingual abort-trigger detection: 28 cancel words across 9 languages; recognizes "stop" in chat messages to cancel in-flight agent operations
crates/octos-core/src/app_ui.rs445stable app-facing UI API layer, deliberately placed above the draft JSON-RPC wire protocol so TUI/App code depends on app concepts, not wire details
crates/octos-core/src/app_ui_codec.rs345shared JSON-RPC text-frame codec for AppUI: transport-neutral framing rules reused by WebSocket text frames and stdio NDJSON
crates/octos-core/src/env_hygiene.rs230subprocess environment hygiene: an injection-variable denylist, secret-name heuristics, and a Command sanitizer shared by the agent spawner and core's own git operations
crates/octos-core/src/gateway.rs182channel-based gateway message types: inbound/outbound messages and the origin marker MessageOrigin
crates/octos-core/src/git_worktree.rs1,579shared git worktree plumbing: lets the fleet-worker pool allocate a real worktree per task without depending on octos-agent
crates/octos-core/src/session_scope.rs1,880SessionScope: the single contract for octos component filesystem access; every component must derive its working directory through it and validate paths, instead of computing from raw input on its own

crates/octos-core/src/session_scope.rs and crates/octos-core/src/git_worktree.rs merit a second look. The former pulls "how a component determines its working directory" out of ad-hoc raw-input inference and into one explicit contract: the two ScopeMode values solo / multi_tenant, path classification results, and safe session id validation all live in the types. The latter's header comment says outright that it is a pure additive module "soul-lifted" from octos-agent's spawn tooling: the agent-side implementation, heavily reviewed over time, stays as is; fleet workers take the new path; the two are not merged yet. These two examples show the actual test for core's boundary: what enters core is not "the smallest set of types" but "any contract whose per-crate copies would drift apart". The implementation details of all seven modules belong to later chapters; this chapter fixes their position only.


Engineering decision: why the core crate has zero internal dependencies

octos-core is the only foundational crate in the workspace that depends on no other octos crate (octos-plugin and octos-sandbox also lack internal dependencies, but nothing depends on them either). This "zero internal dependencies" constraint is a deliberate design choice.

Option 1: fat core (push more logic down into core)

Advantages:

  • All shared logic gathers in one place, cutting duplication across crates
  • Downstream crates get most capabilities by depending on core alone

Disadvantages:

  • core's compile time grows with every feature, slowing incremental builds for every crate that depends on it
  • core churns more often, and each change recompiles the whole workspace
  • Unrelated features couple: touching LLM logic can disturb the Task types

Option 2: thin core (types and the most basic utility functions only)

Advantages:

  • Rarely changes; a stable type foundation
  • A clean compile boundary (octos-core is currently 22,313 lines of Rust source, about 15,005 lines after excluding crates/octos-cli/src/api/ui_protocol_tests.rs, with the bulk being UI Protocol wire types and their tests)
  • A clean dependency graph: every crate depends on core's types, and core depends on nobody

Disadvantages:

  • Logic shared across crates must live elsewhere (utility functions in octos-agent, for instance)
  • Types that "should have been in core" may end up defined in an upper crate

octos chose the thin core, for these reasons.

octos-core's external dependencies are limited to the foundational libraries serde, serde_json, chrono, uuid, eyre, tracing, and sha2, covering serialization, time, error handling, structured logging, and hashing, all industry standards. octos-core therefore compiles fast, and every crate that depends on it (octos-llm, octos-memory, octos-agent, octos-bus, octos-pipeline, octos-cli) inherits that speed.

The stronger argument is stability. Over octos's development, octos-llm went through several provider refactorings, octos-agent's tool system kept expanding, octos-bus added channel after channel, yet octos-core's central types (Task, Message, Error) stayed highly stable. The thin-core strategy is what made that stability possible.


2.10 Chapter Recap

With 22,313 lines of Rust source (about 15,005 lines after excluding crates/octos-cli/src/api/ui_protocol_tests.rs), octos-core defines the domain language of the whole system:

  1. The Task state machine encodes legal states and transitions in Rust enums, eliminating illegal state combinations at the type level. UUID v7 gives time-ordered IDs, and the five-dimension TokenUsage supports precise cost tracking.

  2. The Message abstraction unifies four roles (System/User/Assistant/Tool), and the dual as_str()/Display implementation keeps serialization consistent across providers. ClientMessageId, ThreadId, and TurnId separate optimistic UI messages, rendering groups, and protocol turn identity, preventing misattribution under concurrent turns.

  3. Durable ABI: TaskResult.schema_version and SessionSummary.schema_version make task results and typed compaction summaries wire-stable, upgradeable payloads; future versions fail closed through a typed error.

  4. Error design: eyre/color-eyre brings colored error reports and SpanTrace support, and the three-layer structure (kind + context + suggestion) makes error messages actionable.

  5. UTF-8-safe utilities: the two truncate_utf8 variants (in-place and copying) truncate safely through is_char_boundary(). truncate_head_tail_report returns a structured TruncationReport, and truncate_head_tail is its byte-identical thin wrapper.

  6. Zero-dependency design: the thin-core strategy keeps the type foundation stable and compiles fast, letting upper crates evolve independently.

  7. The boundary of core: the seven modules added in 2026 (abort, app_ui, app_ui_codec, env_hygiene, gateway, git_worktree, session_scope) entered core under the "single source of truth across upper layers" rule.

The next chapter enters octos-llm, where these core types go to work taming the chaos of multiple LLM provider interfaces.


Further reading

  • Rust enums and pattern matching: The Rust Programming Language, Chapter 6, "Enums and Pattern Matching", https://doc.rust-lang.org/book/ch06-00-enums.html
  • eyre error handling: the eyre crate documentation, https://docs.rs/eyre/latest/eyre/
  • color-eyre: the color-eyre crate documentation, https://docs.rs/color-eyre/latest/color_eyre/
  • UUID v7 specification: RFC 9562, "Universally Unique IDentifiers (UUIDs)", Section 5.7
  • UTF-8 encoding: The Unicode Standard, Chapter 3, "Conformance": understanding variable-length UTF-8 encoding is essential for safe truncation

Exercises

  1. Extending the state machine: to add a Cancelled state to Task (user-initiated cancellation), which states should be able to reach it? What would the addition do to the existing match expressions?

  2. Fat core vs thin core: suppose octos-core also contained the LlmProvider trait, on the grounds that every upper crate needs it. What problems would follow? Hint: consider the transitive effect of dependencies such as async-trait and reqwest.

  3. Error design tradeoffs: octos's ErrorKind has 15 variants. If the system grew to 50 variants, where would this design start to hurt? How would you restructure it?

  4. Alternative truncation strategies: truncate_utf8 truncates by byte and backs off to a character boundary. An alternative truncates by Unicode grapheme cluster. How do the two differ on emoji composition sequences such as 👨‍👩‍👧‍👦? Which fits LLM context management better?


Version note

Version note: This chapter is based on octos main @ 9c157101 (errata verified 2026-09-02): crates/octos-core/src/*.rs totals 22,313 lines (15 source files, including 7,308 lines of crates/octos-cli/src/api/ui_protocol_tests.rs), with external dependencies serde / serde_json / chrono / uuid / eyre / tracing / sha2; all cited line numbers were re-checked entry by entry against assets/ch02-refcheck.md.

Errata in this pass: the TurnId range was updated to crates/octos-core/src/ui_protocol.rs:607-623; the api_key_not_set excerpt was rewritten per crates/octos-core/src/error.rs:89-99 into the multi-line export / config.json suggestion; the Display range for Error was corrected to crates/octos-core/src/error.rs:174-224; 2.5.3 was rewritten per d8125d18 (2026-08-31) around truncate_head_tail_report / TruncationReport structured truncation; the tool_output_limit table was updated (search, deep_search, and news_fetch all at 200,000); the channel whitelist went from 15 to 19 (adding dingtalk, line, local, wechat); the eyre / color-eyre dependency declarations live at the root Cargo.toml:97-98; ABORT_TRIGGERS actually contains 28 trigger words; the dependency sidebar gained tracing and sha2; a new "boundary of core" section classifies the seven source files added in 2026.

When reading later versions, check the cross-crate wire types beyond Task / Message / Error: the identity newtypes, the SessionSummary ABI, and the UI Protocol capabilities.

Chapter 3: octos-llm: Taming the Chaos of LLM Providers

Positioning: This chapter digs into the octos-llm crate: how a Rust trait abstraction unifies the divergent interfaces of many LLM providers, and how a three-tier fault-tolerance capability set, assembled in two layers, delivers production-grade reliability. Prerequisite: Chapter 2. It is written for AI application developers who want to understand multi-provider architecture (reader C), and for Rust developers interested in trait objects, async fault tolerance, credential rotation, and tiered model routing (reader B).

Every LLM provider has its own API style: Anthropic carries the system message as a standalone field while OpenAI puts it inside the message array; Gemini's tool-call format shares nothing with the other two; Ollama runs locally yet reuses octos's OpenAI-compatible adapter. When you must support a handful of dedicated protocol implementations plus a batch of providers riding OpenAI / Anthropic compatibility layers, the chaos is unavoidable, unless you build the right abstraction at the right layer.

octos-llm's answer has three parts, bottom up: the LlmProvider trait at the bottom unifies the calling interface; a provider registry in the middle implements model-name auto-detection and factory creation; a fault-tolerance assembly at the top provides production-grade reliability: every provider is always wrapped in a RetryProvider, and the outer layer then picks one of two options by configuration: a ProviderChain (static ordered failover, the default) or an AdaptiveRouter (score-based routing, requires explicit opt-in, and replaces the chain rather than stacking on it). The current main branch also folds provider metadata, HTTP timeout knobs, a credential pool, a content classifier, and the routing.decision event into this chain. This chapter walks the stack bottom up.


3.1 The LlmProvider trait: a minimal unified interface

3.1.1 The trait signature

LlmProvider is defined at crates/octos-llm/src/provider.rs:16-121:

#![allow(unused)]
fn main() {
#[async_trait]
pub trait LlmProvider: Send + Sync {
    // 核心方法:非流式对话
    async fn chat(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        config: &ChatConfig,
    ) -> Result<ChatResponse>;

    // 流式对话(默认实现:调 chat() 后合成事件流)
    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[ToolSpec],
        config: &ChatConfig,
    ) -> Result<ChatStream> { /* Text→ToolCall→Usage→Done 依次产出 */ }

    // 元数据查询
    fn context_window(&self) -> u32 { context::context_window_tokens(self.model_id()) }

    // 异步初始化钩子:见下文
    async fn ensure_ready(&self) {}

    fn max_output_tokens(&self) -> u32 { context::max_output_tokens(self.model_id()) }

    // #2143 part 3:估算本 provider 实际发出的请求 token 数(含序列化开销)
    fn estimate_request_tokens(
        &self,
        messages: &[Message],
        tools: &[crate::types::ToolSpec],
    ) -> u32 { /* 默认走基线估算,具体 provider 可收紧 */ }

    fn model_id(&self) -> &str;
    fn provider_name(&self) -> &str;
    fn provider_metadata(&self) -> ProviderMetadata;
    fn provider_metadata_for_index(&self, _provider_index: Option<usize>) -> ProviderMetadata;

    // 可选:指标上报
    fn export_metrics(&self) -> Option<serde_json::Value> { None }
    fn report_late_failure(&self) {}
    fn report_stream_metrics(&self, _output_tokens: u32, _stream_duration_us: u64) {}
}
}

The design follows a "minimal necessary interface" principle (the comment at crates/octos-llm/src/provider.rs:13 says so explicitly): define only what every provider shares, and handle the differences in each implementation.

Several design choices deserve attention:

The Send + Sync bound. The trait requires implementors to be thread-safe, because provider instances are shared across async tasks through Arc. The constraint turns "a single-threaded provider accidentally used from many threads" into a compile-time error instead of a runtime one.

The default chat_stream() implementation. Not every provider supports streaming natively. The default (crates/octos-llm/src/provider.rs:27-56) calls the non-streaming chat(), then wraps the complete response as a synthetic stream that emits content, tool-call, usage, and done events one after another. A new provider that implements only chat() works from day one; native streaming can be added later.

Provider metadata. provider_metadata() and provider_metadata_for_index() are important additions on the current main branch (crates/octos-llm/src/provider.rs:97-109). They hand the actually-hit provider slot, model ID, and provider name up to callers, feeding observability, cost attribution, and precise per-slot metrics in multi-provider chains. provider_metadata_for_index() solves the composite-provider problem: when a ProviderChain internally picks its Nth slot, upper layers must not see only the chain's own name; they need to know which backend actually served the call. The signature is now _provider_index: Option<usize> (line 103): pass Some(idx) when you know the concrete slot, None when you only hold the provider object, so simple callers never have to fabricate an index.

The metrics-reporting methods. export_metrics(), report_late_failure(), and report_stream_metrics() all ship empty default implementations. They feed the AdaptiveRouter's EMA scoring system (see Section 3.3.3) without forcing every provider to implement them. This "optional hook" pattern keeps the trait from bloating.

ensure_ready() and estimate_request_tokens(). Two recent members of the baseline. ensure_ready() (crates/octos-llm/src/provider.rs:65) is an async initialization hook: the agent loop and the prompt-context bridge await it before the first window-dependent decision of each turn, so local context probing (see Section 3.7) can guarantee the real window resolves before the first compaction decision rather than after the first chat; wrappers delegate layer by layer. estimate_request_tokens() (crates/octos-llm/src/provider.rs:82-89, #2143 part 3) estimates the token count of the request this provider actually builds, including provider-specific serialization overhead (a separate system block, per-message content-block framing, cache-control metadata); with it, routing-admission guards no longer need a 12.5% safety margin standing in for that overhead. The default is a provider-agnostic baseline estimate; concrete providers override it to tighten, and wrappers again delegate to the inner layer.

3.1.2 Core data types

ChatConfig (crates/octos-llm/src/config.rs:8-70) holds every tunable of a single request:

  • max_tokens: maximum output tokens
  • temperature: sampling temperature (on the Anthropic protocol path, Some(0.0) counts as unset and stays off the wire)
  • tool_choice: tool selection policy (auto/required/none/a named tool)
  • stop_sequences: stop sequences
  • reasoning_effort: reasoning effort for thinking models (none/low/medium/high/max, mapped to OpenAI reasoning.effort, the Anthropic thinking budget, and Gemini thinkingConfig)
  • response_format: response format constraint (text/JSON/structured output)
  • context_management: an Anthropic-specific opaque payload (such as clear_tool_uses_20250919) that lets the server do tier-2 tool-call cleanup; other providers ignore it
  • sampling_params: an operator-supplied passthrough table of extra sampling parameters (mechanism below)
  • cache_retention: the per-request prompt-cache retention preference (None means do not write cache this time; mechanism in Section 3.6)

The list deliberately omits two fields that look inevitable, model and system_prompt: the model is decided at provider construction time by the registry factory (see Section 3.2.3), and the system prompt travels through the messages array (exactly the protocol divergence this chapter opened with). The full mechanics of sampling_params and cache_retention unfold below in this section and in Section 3.6.

ChatResponse carries everything the LLM returned: content, stop reason, tool-call requests, token usage. ChatStream is an async stream (Pin<Box<dyn Stream<Item = Result<StreamEvent>>>>) that yields the streaming response event by event.

sampling_params (crates/octos-llm/src/config.rs:44-57) carries sampling parameters octos does not model, for example {"repeat_penalty": 1.1, "top_p": 0.95}. The OpenAI-compatible layer flattens them into the request body (crates/octos-llm/src/openai.rs:635-640, field docs at 908-909, tests at 1614-1616) and defensively strips keys that collide with fields octos already dedicates (#2172), so the streaming and non-streaming serialization paths cannot produce duplicated or diverged fields. The default is empty: flattening adds nothing, and cloud requests are unchanged. This cloud-safe sampler passthrough landed in commit b0072e70 (#2172/#2176) to serve local inference servers such as llama.cpp / vLLM / SGLang that accept non-standard sampling parameters.

The context window no longer has the static catalog as its only source. Commit 3e479ce3 (#2142) introduced per-profile context_window overrides, and the footprint spans two crates: the config struct LlmModelSelectionConfig (crates/octos-cli/src/profiles.rs:824-875, the field at 875), the config.llm-side fields (crates/octos-cli/src/config.rs:39-46, 489-492), and the assembly function apply_context_window_override (crates/octos-cli/src/qos_catalog.rs:24-36) all live in octos-cli; octos-llm only contributes the thin ContextWindowOverride wrapper in crates/octos-llm/src/context_override.rs (135 lines). It is stacked outermost on the wrapper stack, and its value overrides both the static catalog and runtime probing (#2135). The wiring of config.llm.primary.context_window / fallbacks[i].context_window in profiles lives mainly in octos-cli, not inside octos-llm; cite that cross-crate footprint as it is.

Provider factories also receive the LLM HTTP timeout knobs. CreateParams::http_timeout() (crates/octos-llm/src/registry/mod.rs:110-118) combines the two optional fields llm_timeout_secs and llm_connect_timeout_secs into an Option<(u64, u64)>: when either field is present, the missing one is filled from default constants; when both are absent it returns None. The constants live at crates/octos-llm/src/provider.rs:158-172: total LLM timeout 300 seconds, connect timeout 10 seconds (lowered from 30, so an unreachable endpoint fails over fast), streaming read-idle timeout 300 seconds (DEFAULT_LLM_STREAM_IDLE_TIMEOUT_SECS, line 165, applied through reqwest's .read_timeout(), reset on every read so a long stream that keeps producing tokens is never cut down by the total budget), embedding timeout 60 seconds, embedding connect timeout 15 seconds. Slow model inference and dead network connections are thus configured separately instead of piling into one unexplainable knob.


3.2 The provider registry: model-name auto-detection

When a user configures model: "claude-sonnet-4", octos must work out on its own that this means the Anthropic provider. The mapping lives in the provider registry (crates/octos-llm/src/registry/mod.rs).

3.2.1 How detection works

Each provider registers its name, aliases, API-key environment variables (including aliases), default base URL, requirements, detection patterns, model-discovery capability, and a factory function (crates/octos-llm/src/registry/mod.rs:121-167, the ProviderEntry struct):

#![allow(unused)]
fn main() {
struct ProviderEntry {
    name: &'static str,
    aliases: &'static [&'static str],
    api_key_env: Option<&'static str>,
    key_env_aliases: &'static [&'static str],
    default_base_url: Option<&'static str>,
    requires_api_key: bool,
    requires_base_url: bool,
    requires_model: bool,
    detect_patterns: &'static [&'static str],
    model_discovery: ModelDiscovery,
    create: CreateFn,
}
}

detect_provider() (crates/octos-llm/src/registry/mod.rs:244-260) walks all providers in priority order and checks whether the model name contains a detection pattern. Two structural points stand out. default_model is no longer a static string on each entry; it is built from the rows marked "default": true in model_catalog.json into a family-to-default-model map (crates/octos-llm/src/registry/mod.rs:24-65). The model_discovery field declares the family's model-listing capability (a protocol, or "manual entry") and is resolved at runtime by resolve_model_discovery(family, api_type) at crates/octos-llm/src/discovery.rs:134: api_type: "anthropic" maps straight to the Anthropic Messages strategy, known families consult the registry declaration, and unknown or custom families fall back to the OpenAI-compatible strategy; the protocol is never inferred from a family literal alone.

ProviderDetection patternExample matches
Anthropic"claude"claude-sonnet-4, claude-haiku-4-5
OpenAI"gpt", plus o1/o3/o4 prefixesgpt-4o, o4-mini
Gemini"gemini"gemini-2.5-flash, gemini-2.5-pro
DeepSeek"deepseek"deepseek-chat, deepseek-coder
Groq"llama", "mixtral"llama-3.3-70b-versatile, mixtral-8x7b
Moonshot"kimi", "moonshot"kimi-k2.5
Dashscope"qwen"qwen-max
Minimax"minimax"MiniMax-Text-01
Zhipu"glm"glm-4-plus

Special case: the O-series. OpenAI's o1, o3, and o4 families need prefix matching rather than substring matching (crates/octos-llm/src/registry/mod.rs:248-250), because "o1" as a substring could match another provider's model name (imagine a model called ro1and).

One more point that is easy to misread: some providers ship an empty detect_patterns list. That is not an omission; it is a deliberate requirement that users reach them through an explicit provider name or alias. Typical examples: Vertex, R9s, OpenRouter, Z.AI, the two coding-plan families, NVIDIA, Ollama, vLLM, and local. Their model names tend to be cross-platform relay names, OpenAI-compatible names, or user-chosen local names, and blind substring detection would route them incorrectly. The coding-plan families (moonshot-coding, zai-coding) register ahead of the base families, so an explicit name resolves the coding endpoint before the plain one, and a coding-plan key is never silently sent to an endpoint that would reject it.

3.2.2 The full provider registry

octos currently registers 19 provider families (counted as the entries of static ALL in crates/octos-llm/src/registry/mod.rs, lines 186-210; the registry/ directory holds 20 files, which is 19 family modules plus crates/octos-llm/src/registry/mod.rs itself); array order is detection priority:

#familyprotocolaliases (examples)detection patternsdefault model (from catalog)
1anthropicnative-claudeclaude-sonnet-4-20250514
2openainative-gpt, o1/o3/o4 prefixesgpt-4o
3gemininativegooglegeminigemini-2.5-flash
4vertexnative (Gemini via Vertex SA)vertex-ai-gemini-2.5-flash
5r9sOpenAI/Anthropic compatibler9s.ai-claude-sonnet-4-6
6openrouterOpenAI-compatible meta-router--anthropic/claude-sonnet-4-6
7deepseekOpenAI-compatible-deepseekdeepseek-v4-flash
8groqOpenAI-compatible-llama, mixtralllama-3.3-70b-versatile
9moonshot-codingOpenAI-compatible (coding endpoint)kimi-coding-k3
10moonshotOpenAI-compatiblekimikimi, moonshotkimi-k2.5
11dashscopeOpenAI-compatibleqwenqwenqwen-max
12minimaxOpenAI-compatible-minimaxMiniMax-M3
13zai-codingAnthropic-compatible (coding endpoint)glm-coding-glm-5.3
14zhipuOpenAI-compatibleglmglmglm-4-plus
15zaiAnthropic-compatiblez.ai-glm-5-turbo
16nvidiaOpenAI-compatiblenim-meta/llama-3.3-70b-instruct
17ollamaOpenAI-compatible--llama3.2
18vllmOpenAI-compatible--user must supply a model explicitly
19localOpenAI-compatiblellamacpp, lmstudio, openai-compatible, etc.-local-default (placeholder)

Compared with the old draft's 15, four families are new: vertex (Gemini on Vertex AI, credentials through the service-account JSON environment variable VERTEX_SA_JSON, no default base URL, model listing marked Unsupported), moonshot-coding / zai-coding (two coding-plan endpoints, matched only by explicit name, see above), and local (local servers such as llama.cpp / LM Studio, the most aliases, keyless by default, falls back to the placeholder local-default instead of erroring when no model is given, real window via runtime probing, see Section 3.7).

Anthropic, OpenAI, and Gemini use dedicated implementations; most other entries ride compatibility layers: Ollama, vLLM, OpenRouter, DeepSeek, and local reuse OpenAIProvider, Z.AI reuses the Anthropic Messages API, and R9s switches between the two protocols by model family. An enum Provider existed in historical drafts and no longer does. Registration is "add one file, add one line to ALL" (the module comment at crates/octos-llm/src/registry/mod.rs:2-4); each submodule exports pub const ENTRY: ProviderEntry and a create() factory. This architecture of a few dedicated implementations plus many compatible adapters keeps the cost of onboarding a new provider very low.

3.2.3 Provider factories

Once a provider is detected, the registry instantiates it through its factory function. Each factory reads the environment variables (ANTHROPIC_API_KEY, OPENAI_API_KEY, and so on) or credentials from the config file, and builds an HTTP client with the right base URL and auth headers.

The factory returns Arc<dyn LlmProvider>, and that is the dynamic-dispatch pivot. The registry does not know (and does not need to know) the concrete provider type, only that it implements the LlmProvider trait. Upper layers can then treat every provider uniformly, including dropping them into a fault-tolerance chain.


3.3 The fault-tolerance chain: three capability tiers, two assembly options

In production, LLM API calls fail for many reasons: rate limits (429), server overload (503/529), expired credentials (401), network timeouts. octos-llm splits tolerance into three capability tiers assembled in two layers: RetryProvider absorbs the transient failures of a single provider and is the always-present base of every slot; around it, the assembly layer picks one of two: ProviderChain for static ordered failover (the default assembly), or AdaptiveRouter for score-based routing (adaptive_routing.enabled, explicit opt-in, replacing the chain rather than stacking on it). The production assembly point is crates/octos-cli/src/qos_catalog.rs:305-352.

flowchart TD
    Request["User request"] --> Sel{"adaptive_routing.enabled?<br/>(default false)"}
    Sel -->|"false / unset"| PC["ProviderChain<br/>static ordered failover"]
    Sel -->|"true (explicit opt-in)"| AR["AdaptiveRouter<br/>EMA score routing / hedge racing"]
    PC --> RP1["RetryProvider<br/>(Provider A)"]
    PC -->|"failover"| RP2["RetryProvider<br/>(Provider B)"]
    AR -->|"score pick"| RP1
    AR -.->|"hedge racing / probe"| RP2
    RP1 --> LLM_A["Anthropic API"]
    RP2 --> LLM_B["OpenAI API"]

    style Sel fill:#f9f,stroke:#333
    style PC fill:#bbf,stroke:#333
    style AR fill:#bbf,stroke:#333
    style RP1 fill:#bfb,stroke:#333
    style RP2 fill:#bfb,stroke:#333

Figure 3-1: assembly of the fault-tolerance chain. Every element of the providers vector is already a RetryProvider-wrapped slot; the outer layer branches on adaptive_routing.enabled: the default falls back to the static ProviderChain, an explicit opt-in swaps in the AdaptiveRouter (replacement, not stacking). The circuit breakers are two independent sets: ProviderChain uses ProviderSlot.failures (crates/octos-llm/src/failover.rs), while AdaptiveRouter runs its own per-slot circuit breaker (around crates/octos-llm/src/adaptive.rs:1036).

The assembly-point facts: crates/octos-cli/src/qos_catalog.rs:305-352 is the only fork; crates/octos-cli/src/commands/gateway/profile_factory.rs:363,413, crates/octos-cli/src/commands/chat.rs:1210, and crates/octos-cli/src/tools/switch_model.rs:289 all call ProviderChain::new(vec![RetryProvider...]); no path exists where an AdaptiveRouter embeds multiple ProviderChains.

3.3.1 The base: RetryProvider, exponential backoff wrapped around every provider

RetryProvider (crates/octos-llm/src/retry.rs:41-312) handles the transient failures of a single provider.

The backoff algorithm (crates/octos-llm/src/retry.rs:259-265):

#![allow(unused)]
fn main() {
fn calculate_delay(&self, attempt: u32) -> Duration {
    let delay = self.config.initial_delay.as_secs_f64()
        * self.config.backoff_multiplier.powi(attempt as i32);
    let delay = Duration::from_secs_f64(delay);
    std::cmp::min(delay, self.config.max_delay)
}
}

Defaults (crates/octos-llm/src/retry.rs:28-37): at most 3 retries, initial delay 1 second, backoff multiplier 2.0, max delay 60 seconds. The retry loop is for attempt in 0..=max_retries (crates/octos-llm/src/retry.rs:322, the streaming variant is isomorphic), and it computes a delay and sleeps only while retry budget remains (attempt < max_retries) and the error is retryable. So the default sequence actually sleeps 1s → 2s → 4s, three waits; the 4th failed attempt throws the error upward without sleeping. The 2^3 = 8s step is unreachable in the loop, and the 60-second clamp is never touched by the default exponential sequence either: it matters only when an operator raises the backoff parameters, or a 429 parses a retry-after above 60 seconds.

Which errors are retryable? (crates/octos-llm/src/retry.rs:107-147)

HTTP statusMeaningRetry?Triggers failover?
429rate limityes (parses retry-after)yes
500, 502, 503server erroryesyes
529overloadedyesyes
401, 403auth errornoyes (immediate failover)
504gateway timeoutyes (server may recover)yes
408request timeoutcase by caseyes
reqwest timeoutnetwork timeoutno (no local retry)yes (immediate failover)
400bad requestdepends on the messagein some cases

Note the special handling of reqwest-level network timeouts (connect timeout, read timeout): they are not retried locally, because the same provider will most likely time out again; they trigger failover upward at once so the ProviderChain switches to another provider. HTTP 504 (Gateway Timeout) is treated as retryable, because the server may recover after a brief overload.

Rate-limit parsing (crates/octos-llm/src/retry.rs:267-311): on a 429 response, RetryProvider tries to parse the recommended wait out of the error message (for example "Please try again in 29.159s"), adds a 1-second buffer, and waits that long. If parsing fails, it falls back to a fixed 30-second wait.

3.3.2 Assembly option A: ProviderChain, static ordered failover (the default)

ProviderChain (crates/octos-llm/src/failover.rs:36-249) manages the failover order of a group of providers.

Circuit breaker design (crates/octos-llm/src/failover.rs:27-30):

#![allow(unused)]
fn main() {
struct ProviderSlot {
    provider: Arc<dyn LlmProvider>,
    failures: AtomicU32,  // 连续失败计数器
}
}

Each provider carries an atomic counter of consecutive failures. When the count reaches the threshold (default 3), the provider is marked degraded. A successful call resets the counter to 0 (record_success @ crates/octos-llm/src/failover.rs:111-114, the swap(0) on line 114).

Failover logic (crates/octos-llm/src/failover.rs:85-99):

  1. Try the first provider that is not degraded.
  2. If every provider is degraded, pick the one with the fewest failures.
  3. Skip degraded providers, unless one of them is the last choice left.

Late-failure reporting (crates/octos-llm/src/failover.rs:378): report_late_failure() covers a subtle case: the provider returned a 200 response, but stream parsing afterwards found the content empty or malformed. The provider is then punished retroactively: its failure count goes up, and later requests prefer other providers.

3.3.3 Assembly option B: AdaptiveRouter, EMA scoring and hedge racing (explicit opt-in)

AdaptiveRouter (the struct at crates/octos-llm/src/adaptive.rs:803, with the inherent impl running to the end of the file at 2795) is the peer assembly option to ProviderChain: when opted in, it receives the same providers vector a chain would have received (each element already RetryProvider-wrapped) and does score-based routing over it, rather than stacking a layer outside a chain.

Three modes (crates/octos-llm/src/adaptive.rs:619-631):

  • Off (0): static priority order + circuit breaker, simplest and most reliable
  • Hedge (1): score-based selection + hedge racing
  • Lane (2): score-based lane switching, cheaper than hedge

The EMA scoring system

AdaptiveRouter keeps a live score per provider. Under the default configuration the score is a weighted combination of four factors (score() @ crates/octos-llm/src/adaptive.rs:1766, weight config fields at 42-64); the config field still carries the name weight_latency, but the second factor is actually a composite of quality and throughput, and the source never uses raw latency:

FactorWeightMeaningData source
Stability (error_rate)30%error ratelive stats blended with the catalog baseline
Quality/throughput (weight_latency)30%output quality + runtime throughput60% deep-search token count + 40% throughput
Priority (priority)20%config orderuser config
Cost (cost)20%pricemodel catalog

The blend design (crates/octos-llm/src/adaptive.rs:1582 and 1772, the EMA blend inside score): the stability factor blends the catalog baseline with live data. The blend weight grows with call count, min(total_calls / 20.0, 0.5), so the catalog baseline always keeps at least 50% of the influence. This defuses the cold-start problem: a provider with only a handful of calls cannot be judged unreliable off one or two accidental failures.

score() deliberately uses throughput rather than raw latency as the runtime speed signal, because single-request latency tracks task complexity too closely to serve as a direct quality signal across providers.

Hedge racing

In Hedge mode, AdaptiveRouter fires requests at two providers at once and takes whichever answers first (hedged_chat() @ crates/octos-llm/src/adaptive.rs:2150, the tokio::select! race around ~2220):

#![allow(unused)]
fn main() {
// 简化后的逻辑
tokio::select! {
    result = primary_future => {
        // 主 Provider 先返回
        // 备选 Provider 的 future 被 drop(取消)
        result
    }
    result = alternate_future => {
        // 备选 Provider 先返回
        // 主 Provider 的 future 被 drop(取消)
        result
    }
}
}

The alternate provider is chosen cheapest-first (to cut the cost of redundancy) and must differ in name from the primary (no duplicate requests to the same API). The current implementation records runtime metrics only for requests that complete; a future dropped by the race does not reliably produce complete metrics, so hedge improves tail latency at the price of observability.

The price of hedge racing is double API cost: the losing request still burns tokens, because the provider has usually started processing even after cancellation. Hedge mode suits latency-sensitive, cost-insensitive workloads. Lane mode reaches similar routing quality through score ordering without sending redundant requests.

The probe policy

To keep score data fresh for backup providers, AdaptiveRouter sends probe requests to non-optimal providers with some probability (default 10%) (should_probe() @ crates/octos-llm/src/adaptive.rs:2097, staleness check is_stale @ 337, defaults 0.1/60s in the config struct at lines 42-44 and 62-63), refreshing their performance metrics. The probe interval defaults to 60 seconds, keeping probing cost down.

3.3.4 Credential pool and content classifier: from provider failover to key and tier routing

On the current main branch the fault-tolerance chain does more than switch between providers: it rotates among multiple credentials of the same provider and picks model tiers by content complexity.

Credential pool. The module comment of crates/octos-llm/src/credential_pool.rs states the goal plainly as "persistent cooldown / rotation state" (crates/octos-llm/src/credential_pool.rs:1-29). Every credential carries cooldown, rate-limit counts, reset time, last used, usage count, and reservation state; rotation strategies include FillFirst, RoundRobin, Random, and LeastUsed (crates/octos-llm/src/credential_pool.rs:166-189). When AdaptiveRouter sees a 401/403 or authentication text, it classifies the failure as an auth failure; a 429 or rate-limit text is classified as a rate-limit failure, and the credential pool is notified to enter cooldown or refresh (notify_credential_failure() @ crates/octos-llm/src/adaptive.rs:1081, error-side entry notify_credential_failure_from_error @ 2352). Rotations also emit a stable harness event with schema octos.harness.event.v1 and kind credential_rotation (crates/octos-llm/src/credential_pool.rs:213-245).

Content classifier. crates/octos-llm/src/content_classifier.rs is an I/O-free heuristic classifier, off by default; disabled it returns Strong, so an unused policy never routes complex work to a cheap model by accident (crates/octos-llm/src/content_classifier.rs:1-18, crates/octos-llm/src/content_classifier.rs:61-80). Enabled, it maps code blocks, message length, strong-model keywords, and URL signals to a Cheap or Strong tier: code blocks, length over a threshold, or keywords such as debug/refactor/architecture/prove/proof/analyze/design raise the tier to Strong; a URL is recorded as a reason but never triggers Strong on its own (crates/octos-llm/src/content_classifier.rs:158-209). AdaptiveRouter can mount the classifier and emit a routing.decision harness event through a callback before lane selection (RoutingDecisionCallback @ crates/octos-llm/src/adaptive.rs:801, install entry set_routing_decision_callback @ 1414). The upper harness can then explain why a turn went to the strong model, instead of only seeing the final provider.


3.4 SSE stream parsing: a byte-safe stateful parser

Streaming LLM responses travel over Server-Sent Events (SSE). SSE looks simple (events separated by \n\n, each data line prefixed with data:), but production use brings several engineering problems.

3.4.1 Why a stateful parser is needed

The HTTP response body arrives in chunks of arbitrary size. One SSE event may span several chunks, and one chunk may carry several events. More subtly, a chunk boundary can land in the middle of a UTF-8 multi-byte character.

Consider this scenario:

Chunk 1: data: {"text": "任务完
Chunk 2: 成后请检查结果"}\n\n

The characters U+5B8C ("wán", complete) and U+6210 ("chéng", done) cause no problem here (each is a complete UTF-8 character), but if the chunk boundary happens to fall inside the three bytes of U+5B8C:

Chunk 1: data: {"text": "任务\xe5\xae
Chunk 2: \x8c成后请检查结果"}\n\n

then the \xe5\xae at the end of Chunk 1 is the first two bytes of U+5B8C and not valid UTF-8. Running String::from_utf8() per chunk yields a parse error or a replacement character (U+FFFD).

3.4.2 octos's byte-safe parser

The octos-llm SSE parser (crates/octos-llm/src/sse.rs:16-72) buffers at the byte level:

  1. Accumulate raw bytes: append each chunk's raw bytes to a Vec<u8> buffer, with no UTF-8 conversion.
  2. Detect event boundaries: search the raw bytes for \n\n or \r\n\r\n separators.
  3. Convert per event: only after a complete event is found, convert that event's byte slice into a UTF-8 string.
  4. Keep the remainder: trailing bytes that have not formed a complete event stay in the buffer.

This design guarantees that UTF-8 conversion happens only on complete events: the SSE protocol guarantees that event boundaries never fall inside a UTF-8 character (because \n is a one-byte ASCII character).

The parser is built as an async stream with stream::unfold(), carrying its state (byte stream + buffer) between yielded events.

3.4.3 The 1MB buffer cap

Safety consideration: a hostile or broken LLM provider could send an endless response that never contains \n\n, growing the buffer without bound. MAX_BUFFER_SIZE (crates/octos-llm/src/sse.rs:6-7) is set to 1MB; past it, the parser emits an error event and clears the buffer.

#![allow(unused)]
fn main() {
const MAX_BUFFER_SIZE: usize = 1024 * 1024; // 1MB
}

1MB is generous headroom for a single SSE event. In a normal LLM streaming response, each event carries tens to a few hundred bytes (the JSON representation of one token).

3.4.4 The UTF-8 split test: why byte-level buffering is not optional

The tests in crates/octos-llm/src/sse.rs (crates/octos-llm/src/sse.rs:261-281) construct an exact multi-byte split:

"完成后" 的 UTF-8 编码:
完 = [E5 AE 8C]   (3 bytes)
成 = [E6 88 90]   (3 bytes)
后 = [E5 90 8E]   (3 bytes)

故意在"成"字中间切开:
Chunk 1: data: {"text": "完[E6 88          ← "成"的前 2 字节
Chunk 2: 90]后"}\n\n                       ← "成"的第 3 字节 + "后"

With per-chunk String::from_utf8(), the [E6 88] at the end of Chunk 1 is not valid UTF-8; it becomes U+FFFD (the replacement character), and the original character U+6210 is lost permanently.

The byte-level buffering strategy avoids the loss: the raw bytes of both chunks are concatenated and converted as a whole at the \n\n boundary, so the three-character sequence U+5B8C U+6210 U+540E reassembles correctly.

The risk is not theoretical: when an LLM streams a Chinese reply, each SSE event usually carries 1-3 tokens. HTTP chunked transfer encoding can cut at any byte position, indifferent to token boundaries. For an agent platform serving Chinese, Japanese, and Korean users, byte-level buffering is a requirement, not an optimization.


3.5 The model catalog and cost tracking

ModelCatalog (crates/octos-llm/src/catalog.rs:48-274) keeps metadata for every known model:

#![allow(unused)]
fn main() {
pub struct ModelInfo {
    pub id: String,
    pub name: String,
    pub provider: String,
    pub context_window: u32,
    pub capabilities: ModelCapabilities,  // vision, tool_use, streaming, reasoning
    pub cost: ModelCost,                  // input/output/cache 每百万 token 价格
    pub aliases: Vec<String>,
}
}

The alias system: besides full model IDs (such as claude-sonnet-4-20250514), the catalog also resolves aliases (sonnet → claude-sonnet-4-20250514). Lookup order (crates/octos-llm/src/catalog.rs:72-74): exact ID match → alias match → None.

Cost tracking: ModelCost records per-million-token prices for three token types: input, output, and cache reads. AdaptiveRouter's scoring system uses this data for the cost factor (see Section 3.3.3), trading latency against cost.


3.6 The cost layer: cache economics

The fault-tolerance chain answers "can the call go through"; the cost layer answers "what does this call cost". Commit f3aa07f0 (#2194) brought prompt-cache writes and pricing into this chain, starting from an asymmetry: cache writes bill at 1.25x the input price, cache reads get a discount, and a call that never replays its prefix (a compaction summary, a sub-agent rollup) pays the write premium for a cache nobody will ever read.

Cache-write opt-out for one-shot calls. ChatConfig::cache_retention (crates/octos-llm/src/config.rs:58-75, the CacheRetention enum at 74-92) declares the cache retention preference for a single request: None means this call writes no cache. On the Anthropic protocol, the concrete action is to send no cache_control breakpoints at all, because every breakpoint both reads and writes, and a write nobody reads still bills at 1.25x. Default keeps the provider's configured caching behavior (Anthropic's three ephemeral breakpoints). The default value stays Default, and skip_serializing_if keeps it off the wire, so the persisted ChatConfig JSON shape is unchanged. The assembly point is build_request in crates/octos-llm/src/anthropic.rs (cache_control assembly at 179-207; the no-cache branch for one-shot requests near line 148).

Cache-write-aware pricing. The pricing layer (crates/octos-llm/src/pricing.rs:149-195) models the difference by the answering slot's protocol: only the Anthropic Messages protocol reports cache_creation_input_tokens (write, 1.25x) and cache_read_input_tokens (read, discount). The cache-read discount of the other protocols (openai, openrouter, deepseek, local, unknown) is unknowable: the only OpenAI row in the catalog has cache_read_per_mtok as None, the discount varies with model generation, and applying one provider-level discount would be invented data for some models. So reads price at the full input rate (1.0x, overestimate rather than underestimate) and writes at 1.25x rather than 0 (cache_write_tokens is filled only by the Anthropic parser).

flowchart TD
    Req["Request arrives"] --> CR{"ChatConfig::cache_retention?"}
    CR -->|Default| CC["Anthropic: attach three cache_control breakpoints<br/>read + write"]
    CR -->|"None (one-shot call)"| NC["no breakpoints sent<br/>skip the 1.25x write premium"]
    CC --> P["crates/octos-llm/src/pricing.rs pricing"]
    NC --> P
    P --> AP{"slot speaks Anthropic Messages?"}
    AP -->|yes| W["write 1.25x / read at discount"]
    AP -->|no| F["read at full input price 1.0x (no underestimating)<br/>write 1.25x, not 0"]

Figure 3-2: the cache-economics decision flow. The config layer decides whether to write; the pricing layer decides how to bill.


3.7 Lanes and routing: schedulers outside the fault-tolerance chain

Beyond the fault-tolerance chain, the baseline carries a group of modules built around "who takes this call". They are not layers of one chain; they are schedulers hung on the provider per scenario.

crates/octos-llm/src/lane.rs (per-topic model lanes, RFC-3 / #1292). Routes requests by conversation topic (such as slides:*, code:*, research:*) to different model tiers, so "make slides" and "write core code" need not share one primary/fallback pair.

crates/octos-cli/src/api/router.rs (provider routing for multi-model sub-agents). Dispatches LLM calls by a prefix scheme: sub-agents declare their model needs through prefixes, the router picks the matching backend, and the parent agent and sub-agents can use different models in parallel within one session.

crates/octos-llm/src/call_policy.rs (per-turn call policy). Voice turns wrap the agent run in with_llm_call_policy(FailFast, ..): every provider wrapper and leaf provider short-circuits retry, failover, and hedge; low latency first. The policy is a per-turn task-level input, not a global switch.

crates/octos-llm/src/throttle.rs (semaphore throttling). Caps a provider's concurrent calls with a semaphore, protecting endpoints with strict concurrency quotas (spread across the pool when multiple credentials are configured). It governs "how many at once", orthogonal to the registry's "which one".

crates/octos-llm/src/credential_pool.rs (credential pool, M6.5). See Section 3.3.4: multi-credential rotation plus persistent cooldown, driven by 429/auth failures.

crates/octos-llm/src/local_context_probe.rs (local window probing, #2135). Introduced in commit 10022387. In the catalog, the window numbers of the local / ollama / vllm families are conservative guesses made at registration time (about 32K), because at registration nobody knows which engine the operator has started. The probe (a 1300-line module, new @ 201, new_ollama @ 226) asks the server for the real window in the background: OpenAI-compatible endpoints use the two URLs props and models, and native Ollama uses GET /api/ps (the allocated window of the running model, no key needed). The result resolves through the trait's ensure_ready() hook (crates/octos-llm/src/provider.rs:65) before the first compaction decision, so context_window() stops being a pure static lookup. To override the probed value, use the per-profile context_window override from Section 3.1.2 (operator override > probe > catalog).


Engineering decision: Arc<dyn Trait> vs generics vs enum dispatch

octos-llm leans on Arc<dyn LlmProvider> throughout the provider abstraction layer. The choice deserves a comparison with the two alternatives.

Option one: generics (impl LlmProvider / T: LlmProvider)

Strengths:

  • Zero runtime overhead: the compiler emits specialized code at every call site (monomorphization)
  • Method calls can be inlined

Weaknesses:

  • Wrappers such as RetryProvider and ProviderChain would infect everything with generic parameters: RetryProvider<T: LlmProvider>
  • Fault-tolerance combinations would explode into types: AdaptiveRouter<ProviderChain<RetryProvider<AnthropicProvider>>, ProviderChain<RetryProvider<OpenAIProvider>>>
  • No runtime provider selection from user configuration (generics fix the concrete type at compile time)

Option two: enum dispatch (enum Provider { Anthropic(...), OpenAI(...), ... })

Strengths:

  • All variants known at compile time, so branch prediction is friendlier
  • No vtable indirection

Weaknesses:

  • Every new provider edits the enum definition and every match expression
  • With 19 provider families, the match blocks get huge
  • No user-defined providers (short of a Custom variant that degenerates back into a trait object)

octos's choice: Arc<dyn LlmProvider>, for the following reasons.

In an AI agent, the network latency of an LLM call (100ms-10s) dwarfs the cost of a vtable indirection (<1ns). The performance price of dynamic dispatch is negligible here.

Composition matters more. The octos fault-tolerance chain is nested decoration: RetryProvider wraps any provider, ProviderChain manages a group of them, AdaptiveRouter routes across chains. Arc<dyn LlmProvider> lets these wrappers combine freely, unconstrained by generic parameters.

And the provider lineup is only known at runtime: users specify which providers to use in config files, and the registry factory creates the instances dynamically. Runtime polymorphism of this kind is exactly what trait objects are for.


3.8 Chapter recap

octos-llm resolves the core challenges of LLM provider integration:

  1. The LlmProvider trait: a minimal unified interface with the chat() + chat_stream() two-method design, and the Send + Sync bound for thread safety. Provider metadata lets upper layers see the actually-hit provider slot instead of only the composite wrapper.

  2. The provider registry: model-name substring matching auto-detects the provider, and the factory pattern dynamically creates Arc<dyn LlmProvider> instances. O-series models get prefix matching, and providers whose detect_patterns are empty (R9s, OpenRouter, Z.AI, NVIDIA, Ollama, vLLM) are deliberately left to explicit provider / alias selection.

  3. The fault-tolerance chain (three capability tiers, two assembly options):

    • RetryProvider: exponential backoff (1s→2s→4s), with smart parsing of retry-after in 429 responses
    • ProviderChain: ordered failover + circuit breaker (degraded after 3 consecutive failures), the default assembly
    • AdaptiveRouter: four-factor EMA scoring (stability 30% + quality/throughput 30% + priority 20% + cost 20%) + hedge racing + the probe policy; requires explicit opt-in and replaces the chain rather than stacking on it
  4. Credential pool and content classifier: 429/auth failures enter the credential cooldown / refresh path; the content classifier emits the routing.decision event, exposing the Cheap/Strong tier choice to the harness.

  5. The cost layer and schedulers: cache economics (cache_retention opt-out + cache-write-aware pricing) turns "write the cache or not" into an explicit decision; the six schedulers lane / router / call_policy / throttle / credential_pool / local_context_probe hang off the fault-tolerance chain per scenario.

  6. SSE stream parsing: byte-level buffering avoids UTF-8 splitting, the 1MB cap prevents memory exhaustion, and stream::unfold() builds the stateful async stream.

  7. The Arc<dyn Trait> choice: network latency dwarfs the vtable cost, and the composition and runtime flexibility that dynamic dispatch buys are worth far more than it costs.

The next chapter moves into octos-memory: how hybrid search (BM25 + HNSW vector index) gives an agent long-term memory (see Chapter 4).


Further reading

  • The async-trait crate: https://docs.rs/async-trait/latest/async_trait/ — how the #[async_trait] macro compiles async methods into a trait-object-compatible form
  • The SSE protocol specification: the "Server-Sent Events" section of the HTML Living Standard, https://html.spec.whatwg.org/multipage/server-sent-events.html
  • Exponential backoff: Google Cloud's "Truncated exponential backoff" documentation, https://cloud.google.com/storage/docs/exponential-backoff
  • The Circuit Breaker pattern: Martin Fowler, "CircuitBreaker", https://martinfowler.com/bliki/CircuitBreaker.html
  • Dynamic dispatch in Rust: The Rust Programming Language, Chapter 17, "Using Trait Objects That Allow for Values of Different Types"

Exercises

  1. Fault-tolerance layering: in octos's fault-tolerance assembly, what would happen if RetryProvider's retry duty were merged into ProviderChain (the chain managing bare providers directly and doing its own backoff)? What does the separation buy?

  2. The cost model of hedge racing: suppose you have two providers: Provider A at $10/M tokens with 500ms average latency; Provider B at $3/M tokens with 1500ms average latency. Under what conditions is enabling hedge racing worth it?

  3. SSE parser alternatives: what goes wrong if you process each chunk with String::from_utf8_lossy() instead of byte-level buffering? In which scenarios do those problems become observable?

  4. The generics vs trait-object boundary: if octos only needed to support 3 providers (Anthropic, OpenAI, Gemini), would enum dispatch be the better choice? At how many providers does dynamic dispatch start to win?


Version note: This chapter is based on ../octos main @ 9c157101 (2026-09-02). Revision highlights: (1) the registry was re-listed from 15 providers to 19 provider families (adding vertex, moonshot-coding, zai-coding, and local), and the registration story was rewritten around the registry/ directory plus the model-discovery protocol at crates/octos-llm/src/discovery.rs:134; enum Provider no longer appears; (2) the trait gained ensure_ready() and estimate_request_tokens(), and the provider_metadata_for_index signature changed to Option<usize>; (3) the timeout story now covers CreateParams::http_timeout() and DEFAULT_LLM_STREAM_IDLE_TIMEOUT_SECS; (4) new Section 3.6 "the cost layer" (cache economics, commit f3aa07f0) and Section 3.7 "lanes and routing" (six scheduler modules and the 10022387 local window probe); (5) sampler passthrough (b0072e70) and the per-profile context_window override (3e479ce3, wiring mainly in octos-cli) were recorded in 3.1.2; (6) every reference was re-anchored line by line to 9c157101 (crates/octos-llm/src/adaptive.rs has grown to 2795 lines; crates/octos-llm/src/catalog.rs was corrected to 274 lines; see assets/ch03-refcheck.md). The provider registry and scoring weights may keep changing. This round of fixes (adjudicated items from the C2 report assets/ch03-techreview.md): (7) the fault-tolerance story was rewritten as three capability tiers and two assembly options (the mermaid diagram became a two-way branch; AdaptiveRouter replaces the ProviderChain in place rather than nesting over it); (8) the ChatConfig field list was re-derived from crates/octos-llm/src/config.rs:8-70 (dropping the nonexistent model/system_prompt, adding stop_sequences, reasoning_effort, context_management); (9) the backoff sequence was corrected to 1s → 2s → 4s (the 8s step and the 60s clamp are unreachable under the default sequence); (10) the chapter recap was renumbered from a duplicated 3.6 to 3.8. The three-tier progression of fault tolerance remains the main thread for understanding octos-llm.

Chapter 4: octos-memory: An Engineer's Hybrid Search

Positioning: This chapter digs into the octos-memory crate (6,428 lines by wc -l, six source files, tests included) and shows how pure Rust builds an embedded BM25 + HNSW hybrid search engine that gives an agent long-term memory. Prerequisite: Chapter 2. It is written for AI application developers who want to understand what RAG (retrieval-augmented generation) looks like at the implementation level (reader C), and for Rust developers interested in embedded databases and search algorithms (reader B).

One of the real differences between an AI agent and a chatbot is memory. To a chatbot, every conversation is independent: the code it wrote for you last time, the decisions it made, the pitfalls it hit, all forgotten by the next turn. An agent needs memory to accumulate experience. What code style does this user prefer? Which files in this repository changed recently? What strategy worked three days ago on a bug like this one?

octos-memory implements that memory system in 6,428 lines (wc -l, tests and comments included). It depends on no external service: no Qdrant, no Milvus, no PostgreSQL. One redb embedded database file plus an in-memory hybrid search index is the whole system. This chapter starts at the storage layer and works up through BM25 full-text search, the HNSW vector index, and the engineering of hybrid rank fusion.


4.1 Storage choice: the redb embedded database

4.1.1 Why redb

octos-memory's persistence layer uses redb (crates/octos-memory/src/store.rs), an embedded key-value database written in pure Rust. The most obvious alternative was SQLite: the Rust ecosystem has mature rusqlite bindings.

In octos's context, redb's advantages over SQLite are clear-cut:

Zero C dependency. SQLite is C; rusqlite means compiling C code or linking a system library. That clashes with the workspace-wide deny(unsafe_code) policy in octos: SQLite's C code is excellent, but it sits outside the Rust compiler's safety checks. redb is pure Rust and fully inside the deny(unsafe_code) perimeter.

ACID transactions. redb provides full ACID transactions (with read and write transactions separated), which covers everything episode storage needs from persistence. octos has no need for SQL queries; all search happens on the in-memory hybrid index.

Single-file deployment. A redb database is one file (episodes.redb), with no extra WAL or SHM files. Deployment and backup stay simple.

4.1.2 Three tables

The Episode Store defines three tables in redb (crates/octos-memory/src/store.rs:14-20):

TableKey typeValue typePurpose
EPISODES_TABLE&str (episode_id)&str (JSON)Episode metadata
CWD_INDEX_TABLE&str (working directory path)&str (JSON array)Directory → episode index
EMBEDDINGS_TABLE&str (episode_id)&[u8] (bincode)Vector embeddings

The design stores episode data and vector embeddings separately. The payoff: when vector search is not needed (say the embedding provider is unavailable), reading and writing episodes is unaffected. Embeddings are serialized with bincode (far more compact than JSON), which cuts storage and I/O overhead.

CWD_INDEX_TABLE is an auxiliary index that groups episode IDs by working directory. When the agent works inside a project directory, episodes from that directory are searched first, which improves relevance.


4.2 The Episode: an agent's record of experience

4.2.1 The Episode struct

An Episode is the experience summary an agent produces after finishing a task (crates/octos-memory/src/episode.rs:32-59; the struct is preceded by the EpisodeSource enum, crates/octos-memory/src/episode.rs:26-31, which distinguishes task summaries from session-compaction summaries; #[serde(default)] keeps old data deserializing as-is):

#![allow(unused)]
fn main() {
pub struct Episode {
    pub schema_version: u32,     // data format version
    pub id: String,              // UUID v7
    pub task_id: TaskId,
    pub agent_id: AgentId,
    pub working_dir: PathBuf,    // directory the task ran in
    pub summary: String,         // task summary
    pub outcome: EpisodeOutcome, // result
    pub source: EpisodeSource,   // producer: task or session compaction
    pub key_decisions: Vec<String>,  // key decisions taken
    pub files_modified: Vec<PathBuf>,
    pub created_at: DateTime<Utc>,
}
}

EpisodeOutcome (crates/octos-memory/src/episode.rs:86-98) defines the four outcomes the memory layer can express: Success, Failure, Blocked, Cancelled. These resemble the terminal states of a Task in meaning, but you cannot infer from them that "the system necessarily writes every terminal state as an Episode"; whether anything lands in the store depends on the calling code. The current main agent loop in fact only writes Success episodes.

The schema_version field (crates/octos-memory/src/episode.rs:36, with #[serde(default)] at 35) is what makes the format forward-compatible. When the Episode format needs an upgrade (a new field, say), older data still parses correctly through the version number. The default is 1 (crates/octos-memory/src/episode.rs:16-18, the constant at 14); if the JSON lacks this field at deserialization, the default fills in.

4.2.2 When episodes are written

On the current main agent path, an Episode is created and stored only when an LLM response ends normally with StopReason::EndTurn or StopSequence and save_episodes is on (crates/octos-agent/src/agent/loop_runner.rs:2457-2504, the EndTurn arm starts at 2,457, the write block spans 2,474-2,504; the persistence logic lives at crates/octos-memory/src/store.rs:371-423). The write does three things:

  1. Serialize the Episode to JSON and store it in EPISODES_TABLE
  2. Update CWD_INDEX_TABLE, appending the episode ID to the list for its working directory
  3. Update the in-memory hybrid search index (the text side)

Vectors are not written synchronously inside store(). The current implementation splits episode text and embedding into two phases: store() writes the JSON and the BM25 index first; store_embedding() later writes the Vec<f32> into EMBEDDINGS_TABLE with bincode and calls HybridIndex::add_embedding() to attach an HNSW vector to the existing document. An episode landing in the store therefore does not depend on the embedding provider being up.

At startup, EpisodeStore::open() scans EPISODES_TABLE and EMBEDDINGS_TABLE and rebuilds the in-memory HybridIndex. redb is the only persistent source; both the HNSW and the inverted index are rebuildable caches.

Corruption recovery (crates/octos-memory/src/store.rs:84-111): values in CWD_INDEX_TABLE are JSON arrays (["id1", "id2", ...]). If a previous write was interrupted by a crash, the JSON may be damaged. Rather than dropping the whole index, the code salvages episode IDs from the broken JSON by splitting on quotes. This defensiveness keeps index data alive even after an abnormal shutdown.

The deletion path (crates/octos-memory/src/store.rs:757-825): delete_by_id() removes the record from EPISODES_TABLE, CWD_INDEX_TABLE, and EMBEDDINGS_TABLE; on the in-memory side it calls HybridIndex::remove() (crates/octos-memory/src/hybrid_search.rs:358-365), which does not renumber HNSW's internal doc index but blanks ids[pos] as a tombstone, and search filters blank IDs out. This is a textbook ANN engineering trade: deletion is fast and the index stays stable, at the cost of rebuilding the index eventually to sweep tombstones.


BM25 (Best Matching 25) is among the most established ranking algorithms in information retrieval. octos-memory keeps an inverted index in memory to run BM25 search (crates/octos-memory/src/hybrid_search.rs).

4.3.1 The inverted index structure

#![allow(unused)]
fn main() {
// crates/octos-memory/src/hybrid_search.rs:8-39 (simplified)
struct HybridIndex {
    inverted: HashMap<String, Vec<(usize, u32)>>,  // term → [(doc ID, term frequency)]
    doc_lengths: Vec<usize>,                         // length of each document
    total_len: usize,                                // sum of all document lengths
    avg_dl: f64,                                     // average document length
    ids: Vec<String>,                                // list of Episode IDs
    hnsw: Option<Hnsw<'static, f32, DistCosine>>,    // vector index (None without embeddings)
    dimension: usize,                                // vector width the index accepts
    // ... weight and vector-coverage fields
}
}

inverted is the heart of the inverted index: given a term (say, "refactoring"), it quickly yields every document containing that term and how often.

The tokenizer (crates/octos-memory/src/hybrid_search.rs:731-737):

#![allow(unused)]
fn main() {
fn tokenize(text: &str) -> Vec<String> {
    text.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|s| s.len() >= 2)
        .map(String::from)
        .collect()
}
}

Tokenizing is as simple as it gets: lowercase, split on non-alphanumeric characters, drop tokens shorter than 2. For Chinese, this does not split runs into single characters: contiguous Chinese text (the four characters for "Chinese test" run together) stays one token, breaking only at spaces, punctuation, or other non-alphanumeric characters; two Chinese words separated by a space become two tokens; a mixed CJK-Latin string (the characters for "refactor" glued to "parser") also stays one token. The quality is below a real segmenter (jieba, say), but it costs zero dependencies, which suits summary-grade experience retrieval. It also does not filter stop words; that fact returns in the hot-path discussion of 4.3.4.

4.3.2 The BM25 scoring formula

The core formula (crates/octos-memory/src/hybrid_search.rs:636-722, inside bm25_score(); the K1/B terms at 655-661):

score(q, d) = Σ IDF(qi) × (tf(qi, d) × (K1 + 1)) / (tf(qi, d) + K1 × (1 - B + B × |d| / avgdl))

The parameters octos uses (crates/octos-memory/src/hybrid_search.rs:83-84):

ParameterValueMeaning
K11.2Term-frequency saturation. Higher values give high-frequency terms more weight
B0.75Document-length normalization. B=0 ignores length differences; B=1 normalizes fully by length

These two values are the classic defaults validated by decades of information-retrieval practice (from TREC evaluation experiments); octos adopts them as-is rather than tuning.

IDF (crates/octos-memory/src/hybrid_search.rs:677):

#![allow(unused)]
fn main() {
let idf = ((n - df + 0.5) / (df + 0.5) + 1.0).ln();
}

IDF (inverse document frequency) measures how discriminating a term is: words appearing in many documents ("code", "fix") get low IDF; words appearing in few ("deadlock", "HNSW") get high IDF.

4.3.3 Epsilon versus NaN

The score-normalization step of BM25 (crates/octos-memory/src/hybrid_search.rs:703-706 and 718-721) holds a subtle piece of engineering:

#![allow(unused)]
fn main() {
let max_score = result.iter().map(|&(_, s)| s).fold(0.0f64, f64::max);
if max_score < 1e-10 {
    return HashMap::new(); // every score is near zero; return empty results
}
// normalize to [0, 1]
let normalized = score / max_score;
}

The 1e-10 threshold check prevents division by a number close to zero. When every document's BM25 score is tiny (the query terms appear in no document, say), dividing straight by max_score amplifies floating-point noise. Returning empty results early sidesteps that.

It looks like a trivial detail, but NaN propagates relentlessly: once a NaN appears, every later sort and fusion produces wrong answers with no error raised (in floating-point arithmetic, any comparison against NaN returns false), and bugs of this kind are brutal to locate.

4.3.4 The retrieval hot path: dense accumulators and top-k partitioning

The two-pass cost of bm25_score() becomes a bottleneck on high document-frequency (df) queries. octos's tokenizer does not filter stop words, so the the in a query like the fix matches nearly every document (df ≈ n). The 2026-08 commit cc6744ba (#1855) rewrote this hot path: same results, measured 10x speedup on high-df queries.

The accumulator switches by touch count (crates/octos-memory/src/hybrid_search.rs:645-699). Before scoring, the code estimates how many postings the query will walk (matched_postings, L645-649):

  • Dense branch (L671-686): when the query touches ≥ n_docs / 8 (DENSE_ACCUM_DIVISOR = 8, L89), allocate a fixed-size vec![0.0f64; n_docs] array, track touched documents deduplicated in a touched vector, then collect. Hash overhead disappears entirely; the cost is one O(n) zeroing pass.
  • Sparse branch (L688-699): selective queries stay on the HashMap accumulator, avoiding a whole-table zeroing pass for the sake of a few documents.

The comment on the branch choice says it plainly: hashing per posting dominates when a query touches most of the corpus, while dense zeroing for a selective query is pure overhead. Every BM25 term contribution is strictly positive (the IDF logarithm's argument exceeds 1 for all df ≤ n, and tf ≥ 1), so the dense path detects first touch by "score moved off 0", which is why touched never misses a document.

Top-k partitioning replaces the full sort (crates/octos-memory/src/hybrid_search.rs:713-716). The old implementation sorted every matching document, then truncated; a single high-df term could match the whole corpus, making the full sort the dominant cost of lexical queries. Now select_nth_unstable_by(limit - 1, by_score_desc) partitions in O(matches), then truncate(limit). The return type is a HashMap; order within the surviving set was never part of the contract (the contract only constrains which candidates survive), so no sort is owed. by_score_desc (L726-728) uses partial_cmp and treats NaN as equal, echoing the NaN guard of 4.3.3.


4.4 The HNSW vector index

4.4.1 HNSW in brief

HNSW (Hierarchical Navigable Small World) is among the most widely used approximate-nearest-neighbor (ANN) search algorithms. It builds a multilayer graph:

  • Layer 0 contains every data point, each connected to at most M nearest neighbors
  • Upper layers (1, 2, ...) contain only a subset of the points and act as expressways: search starts at the top layer, homes in on the target region, then descends layer by layer for refinement

This hierarchy takes search complexity from linear O(N) down to O(log N).

4.4.2 HNSW configuration in octos

octos builds its vector index with the hnsw_rs crate (crates/octos-memory/src/hybrid_search.rs:130-138, four HNSW_* constants):

ParameterValueMeaning
max_nb_connection16Maximum edges per node (the M parameter)
capacity10,000Preallocated slots
ef_construction200Search width at construction (higher is more accurate and slower)
max_layer16Maximum layer count

A capacity of 10,000 is generous for agent experience storage: at 10 tasks a day, you approach the ceiling only after nearly 3 years. The index prints warnings at 80% and 100% of capacity (crates/octos-memory/src/hybrid_search.rs:277-290, tracing::warn! inside insert(); it counts actual HNSW points, not documents, so BM25-only documents occupy no vector slots).

4.4.3 L2 normalization and cosine similarity

Vector search measures similarity with cosine similarity, while HNSW internally uses the DistCosine distance (generic parameter at crates/octos-memory/src/hybrid_search.rs:20). The relation:

similarity = 1.0 - distance

To keep cosine similarity correct, every embedding is L2-normalized before entering the index (crates/octos-memory/src/hybrid_search.rs:741-747):

#![allow(unused)]
fn main() {
fn l2_normalize(v: &[f32]) -> Option<Vec<f32>> {
    let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
    if norm < f32::EPSILON {
        return None;  // a zero vector cannot be normalized
    }
    Some(v.iter().map(|x| x / norm).collect())
}
}

Zero-vector guard: the norm < f32::EPSILON check (crates/octos-memory/src/hybrid_search.rs:743) prevents division by zero. When an embedding provider returns an all-zero vector (a model error or empty input can cause this), the normalizer returns None and the document stays out of the vector index (BM25 search still finds it).


4.5 Hybrid rank fusion

The point of hybrid search is combining BM25's exact keyword matching with the vector side's semantic understanding. octos uses a plain weighted-fusion strategy.

4.5.1 The fusion pipeline

flowchart LR
    Query["Query text + query vector"] --> BM25["BM25 search<br/>inverted index<br/>keyword match"]
    Query --> HNSW["HNSW search<br/>vector index<br/>semantic match"]
    BM25 --> Fusion["Weighted fusion<br/>0.3 × BM25 + 0.7 × vector"]
    HNSW --> Fusion
    Fusion --> TopK["Top-K results<br/>sorted by score, descending"]

Figure 4-1: the hybrid search pipeline. The query runs through both BM25 and HNSW; the results merge by weighted sum.

4.5.2 Weight configuration

Default weights (crates/octos-memory/src/hybrid_search.rs:92, 94):

#![allow(unused)]
fn main() {
const DEFAULT_VECTOR_WEIGHT: f32 = 0.7;
const DEFAULT_BM25_WEIGHT: f32 = 0.3;
}

The vector weight (0.7) outranks BM25 (0.3) because semantic similarity is usually more valuable than exact keyword match when retrieving agent experience. A query like "how do I break a concurrency deadlock" should surface an episode recorded as "used Mutex ordering to avoid circular waits", even though the two share no keywords.

Weights are configurable through with_weights() (crates/octos-memory/src/hybrid_search.rs:250-254) for different workloads.

4.5.3 The fusion algorithm

The fusion logic (crates/octos-memory/src/hybrid_search.rs:465-481, has_vectors branch):

#![allow(unused)]
fn main() {
// for each candidate document, compute the final score
for doc_id in all_candidates {
    let vec_score = vector_scores.get(doc_id).unwrap_or(&0.0);
    let bm25_score = bm25_scores.get(doc_id).unwrap_or(&0.0);
    let score = self.vector_weight * vec_score + self.bm25_weight * bm25_score;
    results.push((doc_id, score));
}
}

The candidate set is the union of both search paths: even a document that appears only in BM25 results (vector score 0) can still enter the final ranking on its BM25 score. Exact keyword matches never drown under semantic search.

One more detail of the current implementation: vector_weight / bm25_weight weighted fusion applies only when vector_scores is non-empty; if no vector results are available, the normalized BM25 scores pass through directly instead of being multiplied by 0.3 again. BM25-only fallback does not artificially depress every score.

4.5.4 Fallback without embeddings

When the embedding provider is unavailable (no API key configured, or the provider unreachable), the system falls back to pure BM25 search:

  1. At insert: insert() takes embedding: Option<&[f32]>; when it is None, only the inverted index updates
  2. At query: when query_embedding is None, all vector scores are 0 and the final score is entirely BM25's
  3. Empty index: if the hybrid index holds no documents at all, the system falls back to scanning the redb database directly (branch decision at crates/octos-memory/src/store.rs:461-467, the scan implementation find_relevant_db_scan starting at crates/octos-memory/src/store.rs:554), providing basic retrieval through the CWD index and term matching

This three-tier fallback (hybrid search → BM25-only → DB scan) keeps memory answering queries under all conditions, with precision dropping tier by tier.

4.5.5 Making fallback visible: VectorCoverage

The three-tier fallback shares one problem: when degradation happens, results quietly get worse. A vector whose width does not match the index is dropped, the episode silently falls back to BM25-only recall, and nothing in the query output hints at it. 4ccdbe7e (#1851, following #1816, the fix for the 1536/768 wrong-width bug) turned this state from "infer it from the logs" into "query it":

  • VectorCoverage (crates/octos-memory/src/hybrid_search.rs:48-58) is a four-field snapshot: total (documents in the index), vectorized (documents that actually reached HNSW), dimension_mismatches (vectors rejected for wrong width), and dimension (the width the index accepts). The methods bm25_only() / ratio() / has_dimension_mismatch() (L60-81) yield metrics a health check can report directly.
  • Count instead of spam (crates/octos-memory/src/hybrid_search.rs:36-38, 318-337): at startup the store rebuilds the index by re-inserting every persisted episode; after an embedding-model change, per-episode warnings would mean one log line per episode. Now, after the first warning, it only counts (the mismatch_logged flag), and vector_coverage() (crates/octos-memory/src/hybrid_search.rs:231-243; the store-side entry at crates/octos-memory/src/store.rs:640) reports the total.
  • Startup summary (crates/octos-memory/src/store.rs:289-300): after the index rebuild completes, one summary warning: wrong-width embeddings were dropped, those episodes are BM25-only until re-embedded, and stored vectors cannot be converted, only regenerated.

The repair entry point that goes with this is octos memory reindex (9ad56caa, #1853; see 4.7.2).


4.6 MemoryStore: Markdown persistent memory

Beyond the Episode Store's structured memory, octos-memory ships MemoryStore (crates/octos-memory/src/memory_store.rs), a simple memory system built on Markdown files.

4.6.1 Three forms of memory

FormFileBehavior
Long-term memoryMEMORY.mdSingle file, full replacement
Daily notesYYYY-MM-DD.mdOne file per day, append-only
Entity bankbank/entities/<slug>.mdOne file per topic; summary injection with full text on demand

4.6.2 The 7-day window

get_memory_context() (crates/octos-memory/src/memory_store.rs:571-573, which just renders the three sections of load_sections() into a string; the token-budgeted version get_injectable_context starts at 583) builds the agent's memory context, and load_sections() reads the most recent 7 days of notes (crates/octos-memory/src/memory_store.rs:520):

#![allow(unused)]
fn main() {
let recent = self.read_recent(7).await?;
}

The 7-day window is a pragmatic choice: too short (1 day, say) loses recent context; too long (30 days) drags in noise and eats the LLM's context window. Seven days roughly matches a working week and covers most "last time I did something like this" recall needs.

Experience older than 7 days does not vanish: it still lives in the Episode Store, reachable through hybrid search. The window only governs how much context is auto-injected into the system prompt.

4.6.3 The Memory Bank: two-level retrieval

The current MemoryStore also has an entity-bank layer (crates/octos-memory/src/memory_store.rs:673-841). It splits stable facts into per-entity Markdown files at memory/bank/entities/<slug>.md. This mechanism is not full-text search; it is two-level prompt injection:

  1. Level 1, the summary index. get_bank_summary() (crates/octos-memory/src/memory_store.rs:785-841) walks every entity file (directory located via bank_dir at 673, enumeration in list_entities at 685), skips YAML frontmatter (extract_abstract, 1222-1241), takes the first non-empty, non-heading line as an abstract of up to 100 characters, and injects - **name**: abstract into the system prompt. Both chat and gateway append this Memory Bank summary after the long-term memory and daily notes.
  2. Level 2, full text on demand. When the abstract is not enough, the agent calls the recall_memory tool to read the full entity page. The tool trims the user-supplied name, lowercases it, replaces spaces with -, then reads the corresponding Markdown via read_entity().

Writes go through the save_memory tool (persisted by write_entity, crates/octos-memory/src/memory_store.rs:734). It requires content to open with a heading and a one-line summary; when updating an existing entity it first reads the old content (read_entity, 718) and returns the old version in the tool result, reminding the caller not to overwrite established facts. save_memory runs at Exclusive concurrency, preventing a half-written Memory Bank when reads and writes land in the same batch of tool calls.

4.6.4 A content firewall: crates/octos-memory/src/guard.rs

Memory Bank content enters the system prompt of every future session, so one poisoned entry persists across restarts and channels. Multi-channel entry points (Telegram, email, web) mean third-party text can reach these stores through a single "remember this". The sixth source file of octos-memory, crates/octos-memory/src/guard.rs (325 lines), exists precisely as a two-sided gate over writes and rendering:

  • The write gate (crates/octos-memory/src/memory_store.rs:741 calling first_threat at crates/octos-memory/src/guard.rs:117): write_entity scans content for threat patterns and bail!s, refusing to persist on a hit.
  • The render gate (crates/octos-memory/src/memory_store.rs:815): get_bank_summary scans each line about to be rendered into the bank index; lines carrying injection threats are skipped, not rendered. Name and abstract are checked separately, because rendering concatenates them into one - **name**: abstract line and the seam could reassemble an injection.

first_threat normalizes against two cheap evasions: zero-width characters are stripped and whitespace collapsed; separators like _/-/. map to spaces before a second scan, so de-separated forms like ignore_all_previous_instructions still hit. The policy leans strict on purpose: memory content is user-curated, and the cost of a false positive (the user rewrites after seeing the reason) is far below the cost of silently accepting one injection.


Engineering decision: why not an external vector database like Qdrant/Milvus

In the AI application space, vector databases like Qdrant, Milvus, and Pinecone are the mainstream choice. octos passes on them in favor of the embedded approach, for these reasons.

Option A: an external vector database (Qdrant/Milvus/Pinecone)

Strengths:

  • Scales to millions or even hundreds of millions of vectors
  • Rich index types and query capabilities (filtering, multi-vector, sparse vectors)
  • Distributed scaling
  • Mature operations tooling and monitoring

Weaknesses:

  • More deployment complexity: the user now runs an extra service
  • Network latency (even a local deployment pays IPC overhead)
  • Operational cost (backup, upgrades, monitoring)
  • A startup dependency: the agent is dead if the vector store is down

Option B: the embedded approach (redb + hnsw_rs)

Strengths:

  • Zero deployment dependencies: cargo install or download the binary and you are running
  • Zero network latency: search happens in-process
  • Zero operations: the database is one file, backed up and migrated alongside the agent
  • Graceful degradation: BM25 search still works without an embedding provider

Weaknesses:

  • A scale ceiling (10,000 vectors; single-machine memory limits)
  • Limited search features (no filtering, no multi-vector)
  • Not distributed (single instance)

octos's choice: the embedded approach.

The key insight is the difference in scale requirements. RAG applications search across millions of documents; that is the external vector store's home turf. Agent experience memory accumulates incrementally: a few to a few dozen episodes a day, maybe a few thousand in a year. The 10,000-cap leaves plenty of headroom for most usage.

The bigger reason is deployment experience. octos targets individual developers and small teams who want to start an agent with one command, not stand up a vector-database infrastructure first. The embedded approach keeps octos download-and-go.


4.7 Chapter recap

octos-memory builds a self-contained agent memory system in six source files and 6,428 lines of Rust (wc -l):

  1. redb embedded storage: three tables (episodes / CWD index / vector embeddings), pure Rust, ACID transactions, single-file deployment.

  2. BM25 full-text search: classic K1=1.2/B=0.75 parameters, inverted index + IDF weighting, epsilon-guarded normalization against NaN.

  3. HNSW vector index: the hnsw_rs crate provides layered graph search; L2 normalization keeps cosine similarity correct; the zero-vector guard keeps the index clean.

  4. Hybrid rank fusion: 0.7 vector + 0.3 BM25 weighted sum, candidate set as the union, three-tier fallback (hybrid → BM25 → DB scan) keeps answers coming under all conditions.

  5. Markdown + Memory Bank: MEMORY.md, daily notes, and the entity bank together form the prompt-side memory; entity abstracts inject automatically, full text loads on demand via recall_memory; crates/octos-memory/src/guard.rs blocks injected content on both the write and render sides.

4.7.1 Line-count methodology

This chapter's line counts were measured with find crates/octos-memory -name '*.rs' | xargs wc -l | tail -1 (2026-09-02, baseline 9c157101): 6,428 lines across six source files (crates/octos-memory/src/memory_store.rs 2,417; crates/octos-memory/src/store.rs 1,940; crates/octos-memory/src/hybrid_search.rs 1,527; crates/octos-memory/src/guard.rs 325; crates/octos-memory/src/episode.rs 195; crates/octos-memory/src/lib.rs 24), tests and comments included. Two earlier figures ("about 1,750 lines" and "1,635 lines") correspond to an older baseline and a tokei code-only count respectively; this erratum standardizes on the raw wc -l count.

4.7.2 Operations: octos memory reindex

Switching embedding models means switching vector widths; old vectors cannot be converted, only regenerated. Before this existed, the only "fix" was deleting the entire episodes.redb. 9ad56caa (#1853) added the proper path: octos memory reindex [--dry-run] (entry at crates/octos-cli/src/commands/memory.rs:44-51, dispatch at L95, run_reindex from L148) re-embeds from the persisted episode.summary. The work list comes from episodes_needing_vectors() (crates/octos-memory/src/store.rs:670), computed against the database rather than the in-memory index: every episode missing an embedding or carrying a wrong-width one is listed (empty summaries are skipped), and backfill goes through store_embedding() (crates/octos-memory/src/store.rs:712). Without a configured embedder the command errors out immediately (L156); reindex takes the store write lock, so stop octos serve first.

The next chapter moves into octos-agent, where the main agent loop uses these types and memory capabilities to orchestrate a full conversation.


Further reading

  • The BM25 algorithm: Robertson & Zaragoza, "The Probabilistic Relevance Framework: BM25 and Beyond" (Foundations and Trends in IR, 2009)
  • The HNSW algorithm: Malkov & Yashunin, their TPAMI 2020 paper on efficient approximate nearest neighbor search using hierarchical navigable small world graphs (IEEE TPAMI, 2020)
  • redb: https://docs.rs/redb/latest/redb/, an embedded database in pure Rust
  • hnsw_rs: https://docs.rs/hnsw_rs/latest/hnsw_rs/, the Rust HNSW implementation
  • Hybrid search: Anthropic's "Contextual Retrieval" post on how BM25 and vector search complement each other

Exercises

  1. BM25 parameter tuning: if the agent mostly handles Chinese tasks, do K1 and B need adjusting? How does Chinese tokenization granularity (single characters vs word phrases) affect BM25 retrieval quality?

  2. Choosing vector dimension: octos defaults to 1536-dimensional vectors (OpenAI text-embedding-3-small). What would switching to a lightweight 384-dimension model cost in retrieval quality and memory use, respectively?

  3. Adaptive fusion weights: are fixed 0.7/0.3 weights optimal? Sketch a strategy that adjusts weights by query type: keyword-exact queries lean BM25, open-ended semantic queries lean vector search. What architectural changes would that need?

  4. The scale ceiling: if octos had to support enterprise deployment (100,000 episodes), what would the embedded approach need rebuilt? Is there a middle path between "embedded" and "external database"?


Version note: This chapter is based on octos main @ 9c157101 (2026-09-02); the octos-memory crate lives at crates/octos-memory/src/, six source files totaling 6,428 lines by wc -l. Errata in this revision (v2): (1) 24 source-line references re-anchored to 9c157101 (lines shifted overall after cc6744ba / 4ccdbe7e / 9ad56caa); (2) three new subsections added: the dense accumulator and top-k partitioning of cc6744ba (§4.3.4), the VectorCoverage fallback-visibility work of 4ccdbe7e (§4.5.5), and octos memory reindex of 9ad56caa (§4.7.2), plus the crates/octos-memory/src/guard.rs positioning section required by the spec's fact boundary (§4.6.4); (3) the L145 epsilon excerpt synced with the current implementation (result.iter().map(|&(_, s)| s) / initial value 0.0f64); (4) the line count standardized to wc -l 6,428. Compared with the early version, MemoryStore's entity bank now connects to the save_memory / recall_memory tools with system-prompt summary injection; EpisodeStore supports write-then-embed, tombstone deletion, and fallback-visibility reporting.

Chapter 5: Agent Loop: The Full Lifecycle of One Conversation

Positioning: This chapter rebuilds the complete narrative of the Agent Loop around the 20 modules in crates/octos-agent/src/agent/, following one process_message / run_task call from entry to stop_reason through its six-stage lifecycle: the five budget gates and the #27e checkpoint, the typed retry-bucket state machine, the three-layer type chain for error recovery, and the goal-layer continuation queue that bounds the loop. Prerequisites: Chapter 2 (octos-core types), Chapter 3 (the LlmProvider abstraction). Who should read it: AI application developers who want to know what the runtime actually does after a user message arrives (reader C), and contributors preparing a PR against the loop (reader D). Chapter 16's fleet worker and Chapter 18's goal continuation both build on this chapter's loop as their baseline variant.

The textbook definition of an agent loop is one line: receive a message, call the LLM, parse the intent, execute tools if any are requested, feed the results back, repeat until the task is done. The entire difficulty of a production implementation hides in that line's boundary conditions: iteration caps, token budgets, idle timeouts, context overflow, malformed messages, repetitive output, provider failures, graceful shutdown. octos distributes these boundary conditions across 20 modules in crates/octos-agent/src/agent/: excluding *crates/octos-agent/src/agent/loop_runner_tests.rs, 21,369 lines in total (methodology: cat $(ls *.rs | grep -v '_tests') | wc -l). The largest module is not the main loop file crates/octos-agent/src/agent/loop_runner.rs (3,979 lines) but tool dispatch, crates/octos-agent/src/agent/execution.rs (4,730 lines). That counter-intuitive fact is this chapter's point of entry: the value of the main loop is not the verb "loop" but the decision surface it orchestrates. Every line number and figure in this chapter comes from assets/ch05-facts.md (baseline: octos main @ 9c157101, 2026-09-02); each source reference in the text (path plus line number) can be checked against the facts table and the source repository.


5.1 The Module Map: 20 Modules, 21,369 Lines

Read the directory as a map first. Each module's first //! doc comment is its self-declaration:

#ModuleLinesOne-line responsibility (first doc comment)
1crates/octos-agent/src/agent/activity.rs150Loop activity tracking for idle-timeout enforcement
2crates/octos-agent/src/agent/append_only_audit.rs364Append-only context audit: does a turn's request history only ever GROW?
3crates/octos-agent/src/agent/budget.rs821Budget tracking and enforcement for the agent loop
4crates/octos-agent/src/agent/compaction.rs358Context window trimming and fallback truncation
5crates/octos-agent/src/agent/detection.rs858Detection of repetitive output and retriable responses
6crates/octos-agent/src/agent/execution.rs4,730Tool execution: dispatching tool calls with hooks and timeout handling
7crates/octos-agent/src/agent/llm_call.rs988LLM call orchestration with lifecycle hooks and retry logic
8crates/octos-agent/src/agent/loop_compaction.rs414Message preparation pipeline for long-turn loop calls
9crates/octos-agent/src/agent/loop_runner.rs3,979Main agent loop: process_message and run_task orchestration
10crates/octos-agent/src/agent/loop_state.rs768Typed retry-bucket state machine for the agent loop (M6.2, issue #489)
11crates/octos-agent/src/agent/memory.rs1,062Initial message building and episodic memory context for the agent
12crates/octos-agent/src/agent/message_repair.rs1,260Message normalization, ordering repair, and tool pair validation
13crates/octos-agent/src/tools/mod.rs1,644Agent implementation
14crates/octos-agent/src/agent/prompt_segments.rs233Ordered system-prompt segments
15crates/octos-agent/src/agent/realtime.rs602Real-time agent loop extensions for robotic operation
16crates/octos-agent/src/agent/rich_output.rs309Rich output: produce a self-contained HTML document from a short brief
17crates/octos-agent/src/agent/streaming.rs1,491Stream consumption, shutdown handling, and cost reporting
18crates/octos-agent/src/agent/turn_failure.rs69Voice-turn failure projection
19crates/octos-agent/src/agent/turn_state.rs388Typed turn state for loop execution
20crates/octos-agent/src/agent/verifier.rs881Optional inference-time verifier and compact structured turn ledger

By responsibility they fall into three layers. The nine core modules carry all decisions of a single turn: crates/octos-agent/src/agent/loop_runner.rs (orchestration), crates/octos-agent/src/agent/turn_state.rs / crates/octos-agent/src/agent/loop_state.rs (typed state within a turn and across turns), crates/octos-agent/src/agent/budget.rs (budget and checkpoints), crates/octos-agent/src/agent/llm_call.rs / crates/octos-agent/src/agent/streaming.rs (calls and stream consumption), crates/octos-agent/src/agent/execution.rs (tool dispatch), crates/octos-agent/src/agent/message_repair.rs (message repair), and crates/octos-agent/src/agent/detection.rs (degeneration detection). The supporting modules each own one facet: crates/octos-agent/src/agent/activity.rs (idle timeout), crates/octos-agent/src/agent/append_only_audit.rs (append-only audit of request history), crates/octos-agent/src/agent/memory.rs (first-turn messages and episodic memory), crates/octos-agent/src/agent/prompt_segments.rs (system-prompt segments), crates/octos-agent/src/agent/verifier.rs (inference-time verification), and crates/octos-agent/src/agent/realtime.rs / crates/octos-agent/src/agent/rich_output.rs / crates/octos-agent/src/agent/turn_failure.rs (realtime, rich output, voice-failure projection). The two compaction modules (crates/octos-agent/src/agent/compaction.rs and crates/octos-agent/src/agent/loop_compaction.rs) get only their entry points here; the algorithms are covered in Chapter 8.

crates/octos-agent/src/tools/mod.rs is the assembly layer: the constructor and builder family of pub struct Agent (with_reporter, with_hooks, with_snapshot_manager, with_realtime, with_compaction_runner, with_persistent_retry_state, and others, from crates/octos-agent/src/agent/mod.rs:691) wire the modules' runtime state into the Agent struct; timeout and limit constants live in AgentConfig (first-token grace 180s, stream idle 90s, LLM call max 1200s, crates/octos-agent/src/agent/mod.rs:148).

A layering fact that is easy to miss: this directory's public surface is narrow. execute_tools, the tool-dispatch main entry in crates/octos-agent/src/agent/execution.rs, is pub(super) (crates/octos-agent/src/agent/execution.rs:2483); consume_stream_with_input_estimate, the stream-consumption main entry in crates/octos-agent/src/agent/streaming.rs, is likewise pub(super) (crates/octos-agent/src/agent/streaming.rs:73); and crates/octos-agent/src/agent/message_repair.rs exposes exactly one crate-public function, normalize_tool_call_id (crates/octos-agent/src/agent/message_repair.rs:95). The only fully public entries are the process_message / run_task families in crates/octos-agent/src/agent/loop_runner.rs. The crate boundary exposes the loop, not the loop's organs. There is an engineering motive behind this visibility design: the signatures of organ-level functions are still evolving (execute_tools already returns a tuple of seven elements, and every new dispatch product changes the signature). Make them pub and external callers weld the signature in place; every subsequent evolution becomes a breaking change. Publishing only the two entry families shrinks the stability promise of "how the loop orchestrates" to a minimal surface, and the internal modules stay free to be refactored. In fact crates/octos-agent/src/agent/execution.rs is larger than crates/octos-agent/src/agent/loop_runner.rs, yet not one line of it leaks outside the crate.

The split into nine core modules is itself worth questioning: why these nine, instead of gathering "the code that calls the LLM" into one file? The answer sits on the axes of change. crates/octos-agent/src/agent/message_repair.rs fixes malformed messages, and its change frequency follows provider protocol differences (Anthropic requires a tool result to immediately follow the assistant message; OpenAI allows gaps). crates/octos-agent/src/agent/detection.rs detects model-behavior degeneration, and its change frequency follows the model ecosystem (empty responses from small models and shapes of repetitive output keep producing new cases). crates/octos-agent/src/agent/budget.rs is pure decision logic and almost never changes. crates/octos-agent/src/agent/execution.rs follows the tool system's evolution (see Chapter 6), and crates/octos-agent/src/agent/streaming.rs follows SSE parsing and cost-reporting requirements. Five distinct axes of change; cramming them into one file means every provider protocol adjustment sends you hunting for context in two thousand lines of mixed code. Splitting modules along axes of change gives every file's diff a single theme.

5.2 The Lifecycle of One Turn

5.2.1 The entry families

Two entry families correspond to two driving modes. Conversational entries serve interactive scenarios: process_message (crates/octos-agent/src/agent/loop_runner.rs:784), process_message_with_attachments (L804), process_message_tracked (L817, refreshes the TokenTracker in real time for gateway status bars), and process_message_tracked_with_attachments (L834); all four converge on the private core process_message_inner (L852, whose loop body runs to L2242). Task entries serve orchestration scenarios: run_task (L2243) and run_task_with_tracker (L2254, which lets a fleet worker read the real token consumption even after an external timeout drops the future) converge on run_task_inner (L2262).

The four process_message variants are not over-design; each matches a real caller shape: the base version for the simplest chat path, the attachments version carrying this turn's attachment context, the tracked version wiring a TokenTracker, and the tracked_with_attachments version taking both. Keep only one full-parameter entry and simple callers must pass placeholder arguments like TurnAttachmentContext::default() and None; the compiler can no longer tell "the caller deliberately disabled this" from "the caller forgot to pass it." Converging on a single process_message_inner guarantees that all four variants share one loop body, so the interactive path and the tracked path cannot drift apart. The motive for run_task_with_tracker is more specific: on an external wall-clock timeout the fleet worker drops the future outright, the returned TaskResult goes with it, and the tracker is the only accounting channel that survives (the source comment explicitly requires the timeout-path settlement to be "never 0").

5.2.2 The six stages

sequenceDiagram
    participant Caller as Caller(gateway/fleet/orchestrator)
    participant LR as loop_runner<br/>(process_message_inner / run_task_inner)
    participant MR as message_repair + loop_compaction
    participant LC as llm_call
    participant ST as streaming
    participant EX as execution
    participant BU as budget + loop_state

    Caller->>LR: process_message / run_task
    LR->>MR: (1) message preparation(repair + compaction entry)
    MR-->>LR: normalized messages
    loop every iteration
        LR->>BU: (2) budget check check_budget
        BU-->>LR: BudgetStop or pass
        LR->>LC: (3) call_llm_with_hooks
        LC->>ST: (4) consume_stream_with_input_estimate
        ST-->>LC: ChatResponse(with stop_reason)
        LC-->>LR: response + attributed_cost
        alt stop_reason = ToolUse
            LR->>EX: (5) execute_tools(dispatch/timeout/hooks)
            EX-->>LR: tool result messages + files_modified
        else stop_reason = EndTurn / MaxTokens
            LR-->>Caller: (6) return ConversationResponse / TaskResult
        end
    end

(1) Message preparation. prepare_conversation_messages (crates/octos-agent/src/agent/loop_compaction.rs:27) and its task-side mirror prepare_task_messages (L71) feed the history into the repair pipeline. Seven pub(crate) functions in crates/octos-agent/src/agent/message_repair.rs each fix one class of breakage: normalize_tool_call_ids (L27, unifies tool_call_id prefixes and character sets across providers), normalize_system_messages (L108), repair_message_order (L189), repair_tool_pairs (L325), synthesize_missing_tool_results (L414), and truncate_old_tool_results (L513). Each repair class lands in one of the seven variants of LoopRepairReason (crates/octos-agent/src/agent/turn_state.rs:48, from ContextTrimmed to ToolCallIdsNormalized), making "what this turn touched" observable.

(2) Budget check. At the top of every iteration, check_budget runs (see 5.3).

(3) LLM call. The whole call orchestration converges on a single main function in crates/octos-agent/src/agent/llm_call.rs, call_llm_with_hooks (crates/octos-agent/src/agent/llm_call.rs:22); the rest of the module is almost entirely test mocks. In the triple it returns, usage merges the discarded retry attempts into the final attempt, and attributed_cost_usd prices the tokens per provider as they were actually consumed; the caller must book that figure directly instead of recomputing the merged totals with the winning provider's rate (the contract pinned by #1632 P2). Compressing the call orchestration into a single function is a deliberate choice: the hooks before and after the call, the retry ladder across providers, and cost attribution must mesh exactly, and any new logic inserted anywhere can break the invariant that retry attempts' tokens never vanish from the books. A single entry makes all call paths share one orchestration, and the test mocks only need to imitate one function's shape. If each call site orchestrated its own hooks and retries, the first oversight would open a black hole in cost accounting.

(4) Stream consumption. consume_stream_with_input_estimate (crates/octos-agent/src/agent/streaming.rs:73) consumes the SSE stream, handles the shutdown signal (wait_for_shutdown, L64); when it finishes, response_usage_cost (L555) and emit_cost_update (L581) report cost, and response_to_message (L669) converts the raw response into a message. The reason stream consumption is its own module: it owns two kinds of resource no other module should touch, the SSE connection's lifecycle (first-token timeout, inter-token timeout, interruption detection) and the estimation of input tokens. A streaming response cannot produce a complete usage block before it ends, yet cost reporting cannot wait for the end either, so an "estimate while consuming" component is required. Leaving this logic in the caller means every provider's retry path reimplements interruption detection; centralized in crates/octos-agent/src/agent/streaming.rs, the interruption semantics exist exactly once in the crate.

(5) Tool dispatch. execute_tools (crates/octos-agent/src/agent/execution.rs:2483) decides serial versus parallel, computes the batch timeout (compute_batch_timeout_secs, L209), runs before/after hooks, recognizes long-running tools (is_long_running_tool, L174), and handles spawn_only artifact files. Tool semantics themselves are Chapter 6's subject. This largest module, 4,730 lines, is the largest because it alone carries every engineering problem of turning LLM intent into side effects: batch scheduling (serial, parallel, and mixed paths, run_serial_calls L2738 and execute_mixed_batch L2846), timeout budgeting (the longest tool in a batch sets the whole batch's deadline), result projection for cancellation and panic (cancelled_result L3003, timed_out_result L3035, panic_result L3062; all three exceptions must become tool-result messages the LLM can read rather than crashing the loop), and snapshots (snapshot_before_mutating_tools L2457, keeping a baseline before mutating tools run). Keep these duties in loop_runner and the main loop file would blow past eight thousand lines with tool details mixed into every path; split out, loop_runner sees only the clean interface of "a batch of tool calls in, a batch of result messages out."

(6) State update and stop decision. LoopTurnState (crates/octos-agent/src/agent/turn_state.rs:59) holds iteration, total_usage, turn_spend_usd, the retry/repair reason lists, and terminal_reason; record_usage (L138) accumulates consumption and record_budget_stop (L187) records the termination. The response's stop_reason decides the next hop: EndTurn returns, ToolUse goes back to (1), and MaxTokens takes the continuation and self-healing paths (see 5.4 and 5.6). The reason turn state is its own type (rather than locals scattered through the loop body) sits in the two companion enums: LoopRetryReason (L41, three variants) and LoopRepairReason (L48, seven variants) turn "what this turn retried and repaired" into enumerable data. When a user asks why a task was slow, the answer is no longer guesswork over logs but the reason lists carried out at turn end. Locals cannot do this: they have no type and no serialization exit.

5.3 The Five Budget Gates and the #27e Checkpoint

5.3.1 check_budget: the order of the five gates

At the top of every iteration, check_budget (crates/octos-agent/src/agent/budget.rs:100) passes five gates in a fixed order; any hit returns a BudgetStop:

#![allow(unused)]
fn main() {
pub(super) fn check_budget(
    &self,
    iteration: u32,
    start: Instant,
    total_usage: &TokenUsage,
    activity: &LoopActivityState,
) -> Option<BudgetStop> {
    use std::sync::atomic::Ordering;

    if self.shutdown.load(Ordering::Acquire) {
        return Some(BudgetStop::Shutdown);
    }
    if iteration >= self.config.max_iterations {
        return Some(BudgetStop::MaxIterations {
            limit: self.config.max_iterations,
        });
    }
}

(From crates/octos-agent/src/agent/budget.rs:100; the remaining three gates are idle progress timeout, activity timeout, and the token budget.) The order itself is the design: shutdown is one atomic load, and a user interrupt must be answered first; the iteration count is the most common stop reason and costs one integer comparison next; the two timeouts depend on the activity tracking in crates/octos-agent/src/agent/activity.rs (LoopActivityState, crates/octos-agent/src/agent/activity.rs:16); the token budget comes last because budget_tokens_used (crates/octos-agent/src/agent/budget.rs:90) performs four saturating additions, and many deployments set no cap at all. Token accounting includes cache_read and cache_write: counting only input+output lets an Anthropic loop with prompt caching enabled blow through its budget by roughly ten times.

The five variants of BudgetStop (crates/octos-agent/src/agent/budget.rs:13) each carry user-meaningful context: MaxIterations { limit } carries the limit, MaxTokens { used, limit } carries both numbers, and the two timeouts carry their limit. BudgetStop::message() (L41) renders the variants into actionable termination messages, and report_budget_stop (L141) turns that into a ProgressEvent.

The four public functions on the budget side each guard one stretch; the division is not arbitrary. The BudgetStop enum (L13) defines "why we stopped" as data, its five variants being five user-distinguishable endings. message() (L41) is the only rendering point: termination copy is centralized here, and the budget-termination wording a user sees in any interface comes from this one place, so the CLI can never say "limit reached" while the gateway says "budget exceeded." budget_tokens_used (L90) is the only arithmetic point; change the cache inclusion rule once and it applies globally. check_budget (L100) is the only decision point; the five-gate order exists in exactly one function. report_budget_stop (L141) is the only reporting point. Decision, arithmetic, rendering, and reporting as four functions means any budget behavior change localizes to a single function, while the callers (the two loop bodies) face exactly one intermediate representation, Option<BudgetStop>. Spread those four duties into the loop bodies and the five-gate ordering constraint lives in two places; the two loops will sooner or later evolve different stop orders.

5.3.2 Grace: one reprieve before the hard stop

A budget hit does not always stop immediately. try_budget_grace_call (crates/octos-agent/src/agent/loop_runner.rs:602) first asks LoopRetryState: if this is the first hard budget exhaustion and at least one productive tool call has happened since the last grace, the state machine answers Grace (observe_budget_exhaustion, crates/octos-agent/src/agent/loop_state.rs:303) and the loop runs one more iteration, giving the Agent a chance to finish its sentence and its files. Grace fires once globally; the second time it goes straight to Escalate.

5.3.3 #27e: the on-disk checkpoint

When the budget truly runs out, the biggest risk is losing the work tree. #27e implements an on-disk checkpoint in the non-test section of crates/octos-agent/src/agent/budget.rs (from L484), with the main function checkpoint_budget_exhaustion (crates/octos-agent/src/agent/budget.rs:546):

#![allow(unused)]
fn main() {
pub(super) fn checkpoint_budget_exhaustion(
    workdir: Option<&std::path::Path>,
    stop: &BudgetStop,
    iteration: u32,
) -> Option<String> {
    // Only the ITERATION-cap stop checkpoints: MaxTokens/Shutdown/timeouts
    // have different re-dispatch semantics and stay on the legacy path.
    let BudgetStop::MaxIterations { limit } = stop else {
        return None;
    };
    let dir = workdir?;
    if !dir.join(".git").exists() {
        return None; // not a git worktree — nothing to checkpoint.
    }
}

(From crates/octos-agent/src/agent/budget.rs:546.) The trigger is a conjunction of three conditions: the stop must be MaxIterations (the else branch at L553 routes the other four to the legacy path), the workdir must be a git repository, and git status --porcelain must be non-empty. On a hit it does three things: atomically write a staged result via tmp+rename (write_result_md_named, L499; the tmp filename carries the .tmp-27e marker, L501), then git add -A and commit wip: budget exhausted (#27e) — checkpointed mid-task (a local commit, never pushed), and finally return the budget_exhausted:{limit} marker to be appended to TaskResult.output.

The non-triggers matter as much: a clean work tree produces no empty commit, a non-git directory returns directly, MaxTokens/Shutdown/the two timeouts do not take this path, and the default 50-iteration budget is not raised by any of this. The #27h write-ownership check also lives here: result_md_owned_by_peer (L532) reads the sidecar .result-owner; when its trimmed content is exactly peer, the checkpoint rewrites result.checkpoint.md (L579-581) and never touches the peer's result.md; a missing or unreadable sidecar is treated as no owner, fail-open. The only public entry of that check is result_md_owner_content_is_peer (L542); the cli-side #1824 safe-read path reuses the same function, so the two consumers can never drift.

The call site sits in the task loop's budget-termination branch (crates/octos-agent/src/agent/loop_runner.rs:2328): when Grace is not granted, it first runs record_budget_stop and report_budget_stop, then hands workspace_root to the checkpoint function; when the marker exists it is appended into TaskResult together with stop.message().

The persistence-side call chain is equally one line of dependencies: git_in (L484) is the lowest-level command-execution primitive; both the dirty check and the commit go through it. write_result_md_named (L499) is the only way anything is written (tmp plus rename, the tmp name carrying the .tmp-27e suffix, L501); concurrent readers never see half a file. result_md_owned_by_peer (L532) and result_md_owner_content_is_peer (L542) form the two layers of the write-ownership check, the former reading the sidecar and the latter judging the content; only the latter is public, and the cli-side #1824 fd-anchored safe-read path feeds what it reads into the same judging function, so both consumers share one semantics. checkpoint_budget_exhaustion (L546) orchestrates at the top: first the MaxIterations conjunction short-circuit, then the git-repo and dirty checks, then choosing the filename by write ownership, atomically writing the staged result, add -A, the local commit, and returning the marker. Five functions in one dependency chain, each link independently testable (the atomic write has its own test module in budget_checkpoint_tests from L626). That is precisely why this logic is not inlined into loop_runner: testing checkpoint logic needs a real git repository environment, and living in crates/octos-agent/src/agent/budget.rs it can construct a temporary repository on its own instead of mocking an entire Agent.

5.4 The stop_reason Decision Tree

Draw one iteration's exits as a tree:

flowchart TD
    A[Iteration start] --> B{check_budget five gates}
    B -- Shutdown/MaxIterations/MaxTokens/ActivityTimeout/IdleProgressTimeout --> C{try_budget_grace_call}
    C -- Grace --> A
    C -- not granted --> D[#27e checkpoint<br/>MaxIterations + git + dirty to persist] --> E[return TaskResult]
    B -- pass --> F[call_llm_with_hooks]
    F --> G{stop_reason}
    G -- EndTurn --> H[return response]
    G -- ToolUse --> I[execute_tools dispatch] --> A
    G -- MaxTokens --> J{has content?}
    J -- yes:task loop --> K[push_max_tokens_continuation<br/>continue ≤2 times] --> A
    J -- empty+no tool calls:conversation loop --> L[nudge-and-retry ≤2 times<br/>exhausted: terminal error]
    F -- error --> M{HarnessError -> RecoveryHint<br/>-> LoopDecision}
    M -- Continue/RotateAndRetry/CompactAndRetry --> A
    M -- Escalate/Exhausted --> N[escalate the error]

The task loop and the conversation loop treat MaxTokens asymmetrically. The task loop (run_task_inner) had continuation long before #2174: push_max_tokens_continuation (crates/octos-agent/src/agent/loop_runner.rs:3912) appends a "continue from where you stopped" prompt when content is truncated, capped by MAX_TOKENS_CONTINUATION_LIMIT = 2 (L36), with the boundary check at crates/octos-agent/src/agent/loop_runner.rs:2661. The conversation loop (process_message_inner) used to return content.unwrap_or_default() directly, and an empty response let the process exit silently with no error; #2174 closed that path, see 5.6.

5.5 LoopDecision: the typed retry-bucket state machine

The heart of error recovery is crates/octos-agent/src/agent/loop_state.rs: LoopRetryState (crates/octos-agent/src/agent/loop_state.rs:217) holds a counter for each of the 16 error buckets (LoopRetryCounters, L186) and their limits (LoopRetryLimits, L81). The limits are deliberately tight: buckets for structural failures get almost no retries (authentication 1, quota 1, content_filtered 1, internal 1), transient failures get a few (rate_limited 5, network 4, provider_unavailable 4, timeout 3), and shell_spiral gets exactly 1.

Its verdict on the loop is LoopDecision (crates/octos-agent/src/agent/loop_state.rs:131) with six variants, each worth stating precisely. Continue (L134) means "this failure is expected to heal itself": a rate-limit burst, a network hiccup, a slow tool; retry keeps the context untouched because the problem is not in the request. RotateAndRetry (L138) means "the current lane is sick but the task is not": 5xx, interrupted streams, and burned quota are provider-level faults, and switching to another credential lane usually fixes them; rewriting the context would be waste. CompactAndRetry (L141) is the only verdict that rewrites context, and it serves only ContextOverflow: a bare retry of an over-window request is guaranteed to fail again, compaction is the only way out, and this variant's existence moves "which error class requires touching the context" out of caller judgment and into the type system. Escalate (L145) is the destination of the non-retriable classes: auth, invalid request, content filter, tool or plugin faults, internal bugs; continuing the loop only burns money, and throwing to the operator is the correct action. Exhausted (L149) corresponds to no error class at all; it corresponds to "the same bucket's count exceeded its limit," the typed expression of #489 invariant 2: the infinite loop is forcibly terminated here. Grace (L153) is the most unusual: it is not an error verdict but an extension of the budget verdict; after a hard budget exhaustion, if the loop has made at least one productive tool call, it gets one extra iteration to wrap up. The core decision is eight lines:

#![allow(unused)]
fn main() {
pub fn observe(&mut self, error: &HarnessError) -> LoopDecision {
    let (count, limit) = self.bump_counter(error);
    let decision = if count > limit {
        LoopDecision::Exhausted
    } else {
        decide_for_variant(error)
    };
    Self::record_metric(error.variant_name(), decision);
    decision
}
}

(From crates/octos-agent/src/agent/loop_state.rs:266.) While the bucket is not full, decide_for_variant (L431) maps by recovery hint: BackoffRetry to Continue, SwitchProvider to RotateAndRetry, CompactContext to CompactAndRetry, and FailFast and Bug both to Escalate.

Eight methods are each called at a fixed point of the lifecycle; assembled, they make a full turn. new (L234) builds the initial state at loop construction, all buckets zeroed and default limits installed. with_limits (L240) leaves an explicit override for tests and operations. Inside the loop, every successful tool return calls record_productive_tool_call (L253), incrementing the Grace-eligibility counter; the point of that eligibility is that grace goes only to loops that were doing work when the budget cut them off, not to spinning loops. On an LLM or tool error, observe (L266) is the main verdict entry: bump the bucket, compare the limit, emit the verdict, record the metric, in one call. Shell-retry degeneration goes through the dedicated entry observe_shell_spiral (L284): the first spiral escalates (stopping shell retries and throwing up the most recent output), and exceeding the limit is Exhausted; the count is held by the state machine, not a local in loop_runner, so operations reads the same ledger. On a budget hit, observe_budget_exhaustion (L303) decides Grace or Escalate on the test "first time and at least one productive call." At turn end or for debugging, counters (L319) exports a snapshot, and emit_event (L327) writes each verdict as a structured event into the harness event sink. In sequence, a typical turn calls: new (or restores from a persistent handle), some number of record_productive_tool_call, zero or more observe, possibly one observe_budget_exhaustion, and emit_event at any time. The whole state serializes through serde and round-trips with the session ledger; PersistentRetryStateGuard (around crates/octos-agent/src/agent/loop_runner.rs:255) loads at construction and writes back on drop, keeping bucket counts alive across turns: the three network retries burned yesterday in the same session still count toward the bucket today.

stateDiagram-v2
    [*] --> Looping
    Looping --> Continue : observe() transient error, bucket not full
    Looping --> RotateAndRetry : observe() SwitchProvider(quota/provider unavailable)
    Looping --> CompactAndRetry : observe() ContextOverflow
    Looping --> Escalate : observe() FailFast/Bug or first shell spiral
    Looping --> Exhausted : observe() count > bucket limit
    Continue --> Looping : next iteration
    RotateAndRetry --> Looping : retry after lane switch
    CompactAndRetry --> Looping : retry after compaction
    Looping --> Grace : observe_budget_exhaustion() first time and productive ≥ 1
    Grace --> Looping : grace iteration
    Looping --> Escalate_2 : observe_budget_exhaustion() second exhaustion
    Escalate --> [*]
    Exhausted --> [*]
    Escalate_2 --> [*]
    note right of Grace : record_productive_tool_call() restores eligibility, once globally

Every transition in the diagram maps to a nameable decision in the state machine. The five verdict transitions out of Looping are all decided by a single return of observe() (or observe_shell_spiral()): whether the bucket count exceeds its limit picks Exhausted, otherwise decide_for_variant's mapping picks one of the other four. The three transitions from Continue / RotateAndRetry / CompactAndRetry back to Looping differ in "what the loop body does before the next iteration starts": Continue does nothing, RotateAndRetry advances the provider chain's lane pointer, and CompactAndRetry triggers one conversation compaction (done in-band by dispatch_loop_error, invisible to the caller). Grace's entry condition is the conjunction of two predicates (grace_calls_fired == 0 and productive_tool_calls_since_last_grace >= 1); on entry the productive count resets and the fired count increments, two fields read-and-written so that "once globally" is guaranteed by the data structure itself rather than by caller discipline. Escalate_2 and Escalate share an endpoint but not an entrance: the former comes from a revisited budget exhaustion, the latter from an error verdict; they are drawn separately because their operational meanings differ. An error escalation is read by variant, a budget escalation by iteration.

Engineering decision: why retry went from a bool to a typed bucket state machine

The naive implementation is a "how many times retried" counter plus a backoff timer, with all errors sharing one allowance. That has two production failure modes. First, the allowance is consumed by the wrong errors: one 429 storm eats all the retries, and the genuinely structural 401 that follows has no retry budget left to negotiate with; conversely an auth error spins as retriable until the iteration cap. Second, the decision is unexplainable: monitoring shows "retried" but not why, how many retries remain, or what the next hop is. M6.2 (issue #489) answers with an independent bucket per error class, an independent limit per bucket, and each bucket mapping to a named verdict. LoopDecision::as_str() (crates/octos-agent/src/agent/loop_state.rs:159) emits stable snake_case for metrics and events, and OCTOS_LOOP_RETRY_TOTAL (L42) is the total-count metric name. The cost of typing is 16 fields and serde compatibility burden (the quota bucket was added later, and default_quota_limit has to backstop old JSON); the return is a stateable invariant: the same fault exceeding its bucket limit is necessarily Exhausted, and the infinite loop is blocked at the type level.

5.6 harness_errors: three layers of error-recovery types

crates/octos-agent/src/harness_errors.rs builds the recovery chain from three types: RecoveryHint (L47, five variants: BackoffRetry L50, SwitchProvider L53, CompactContext L56, FailFast L60, Bug L63) describes "how this class of error gets saved"; HarnessError (L93, fifteen variants, from RateLimited L96 to Internal L160) is the normalized error with frozen variant names that other milestones reference by name; HarnessErrorEvent (L166) writes errors as structured events into the sink. The chain runs: HarnessError through recovery_hint() (L240) yields RecoveryHint, which the loop-side state machine then decides into a LoopDecision.

Two mappings deserve a close look. ProviderUnavailable maps to SwitchProvider (crates/octos-agent/src/harness_errors.rs:249): 5xx, stream interruption, and model unavailability all fall into this variant; the agent has no extra provider-lane hook inside, and the actual lane switch is driven by the loop-side RotateAndRetry verdict advancing the ProviderChain. Quota also maps to SwitchProvider (L267, #27b): burned quota is a provider-level degradation, not a fatal error, and the fallback lanes on the chain may still be healthy; the true 401 Authentication stays FailFast, because a wrong key fails on every lane. A test pins this red line.

The entry into this chain lives in crates/octos-agent/src/agent/loop_runner.rs: classify_loop_error (crates/octos-agent/src/agent/loop_runner.rs:313) classifies an eyre::Report via HarnessError::classify_report, records the metric, and writes the event; dispatch_loop_error (L437) feeds the classified result into LoopRetryState::observe and writes one more retry event; the caller receives only a coarse two-way action, LoopErrorAction (L249, Retry or Bail), because CompactAndRetry completes in-band and the caller never has to see through the compaction state.

5.7 Loop self-healing: two degeneration case studies

Small models degenerate the loop in two ways; two commits fixed one each.

The silent dead end of empty MaxTokens (#2174, commit 9fe39f1b, 2026-08-28). After one compaction, Qwen 3.8 spent the entire 16,384-token output budget on reasoning: no content and no tool calls, and octos chat exited cleanly, with no output and no error. The fix targets exactly that branch: when a MaxTokens response has empty content and no tool calls, run a bounded nudge-and-retry:

#![allow(unused)]
fn main() {
if content_empty
    && response.tool_calls.is_empty()
    && max_token_empty_recoveries < MAX_TOKENS_CONTINUATION_LIMIT
{
    max_token_empty_recoveries += 1;
    let mut assistant = Message::assistant(String::new());
    assistant.reasoning_content = response.reasoning_content.clone();
    messages.push(assistant);
    messages.push(Message::user(MAX_TOKENS_EMPTY_RECOVERY_PROMPT));
}

(From the conversation loop's MaxTokens branch around crates/octos-agent/src/agent/loop_runner.rs:2171; the nudge prompt constant is at L42, the cap remains 2, and on exhaustion the branch returns the terminal error message at L45 instead of an empty success. MaxTokens responses with content return untouched, so normal cloud-side truncation is unaffected.)

Repetition collapse under forced greedy sampling (#2172, commit 3c7ff8bf, 2026-08-28). octos used to hardcode temperature=0.0 for every chat request; on local small models, greedy argmax deterministically re-emits the same tool call, and one measured response repeated the identical update_plan call 763 times. The fix added the gateway.llm_temperature configuration, threading through to AgentConfig.chat_temperature (crates/octos-agent/src/agent/mod.rs:97) and applied in the pure function build_chat_config (crates/octos-agent/src/agent/loop_runner.rs:3957). Cloud safety is guaranteed by construction: with the configuration absent, the function keeps ChatConfig::default()'s 0.0 and cloud requests stay byte-identical; an operator running local models sets, say, 0.7 to escape the collapse. Lifting the override semantics into a free function exists precisely so the invariant "the default leaves the default untouched" can be unit-tested without a full Agent.

The two cases together show the shape of loop self-healing: detect the degeneration condition (empty content, no progress), recover within a bound (≤2), and when recovery fails, produce a readable terminal state instead of an empty success or a silent exit.

5.8 Degeneration detection

crates/octos-agent/src/agent/detection.rs is the loop's immune layer, with five pub(super) functions: is_retriable_response (crates/octos-agent/src/agent/detection.rs:60, shapes such as empty responses that can be retried at the call layer), normalize_inline_invokes (L84), is_repetitive_output (L111, repetitive-text detection), is_retryable_stream_error (L146), and is_truncated_tool_call_error (L168). Add the sequence-level LoopDetector (window 12; a task-loop comment notes it is explicitly aligned with the conversation loop's window) and SHELL_SPIRAL_VARIANT in crates/octos-agent/src/agent/loop_state.rs (L180, the shell-spiral count held by the state machine), and you get three layers: response, sequence, and bucket. The actions on a hit are all typed: the response layer goes back to the call retry ladder, the sequence layer stops this turn's tool execution and throws up the most recent output, and the bucket layer takes the verdicts of 5.5.

5.9 The supporting modules at a glance

Four supporting modules, one paragraph each. crates/octos-agent/src/agent/memory.rs builds first-turn messages and recalls episodic memory: build_initial_messages (crates/octos-agent/src/agent/memory.rs:249), recall_relevant_episodes (L86), save_conversation_episode (L174), similarity threshold MIN_EPISODE_SIMILARITY = 0.55 (L44); the retrieval mechanism is Chapter 4's subject. crates/octos-agent/src/agent/prompt_segments.rs maintains ordered system-prompt segments behind the PromptSegmentProvider trait (crates/octos-agent/src/agent/prompt_segments.rs:25), with named replacement and hot refresh. crates/octos-agent/src/agent/verifier.rs is an optional inference-time verifier plus a compact turn ledger: TurnLedger (L168) records an entry per tool batch, should_verify_after_tool_batch (L212) decides whether verification fires, and ready_gate_active (L243) implements the "may terminate only after verification passes" gate. crates/octos-agent/src/agent/append_only_audit.rs answers one question: whether a turn's request history only ever grows (the Rewrite enum, L162); it is off by default, enabled only by OCTOS_APPEND_ONLY_AUDIT=1, and it never rewrites requests. crates/octos-agent/src/agent/realtime.rs (heartbeat and sensor injection, Heartbeat L128, SensorContextInjector L238), crates/octos-agent/src/agent/rich_output.rs (self-contained HTML from a short brief, author_html L85), and crates/octos-agent/src/agent/turn_failure.rs (voice-turn failure projection, TurnFailure L9) serve specific runtime modes; see Chapter 14.

5.10 The continuation boundary: the goal layer's master_continuation_scheduler

After the loop returns a stop_reason, who decides to open another turn? The answer is not in the agent crate. crates/octos-cli/src/autonomy/master_continuation_scheduler.rs (1,416 lines) is a pure data structure: a delayed priority queue with no tokio dependency and no LLM calls. The enqueue reasons are the six variants of MasterContinuationReason (L137): ChildCompleted, ScatterJoinComplete, LoopFire, GoalContinue, GoalWrapUp (#1131, the wrap-up turn after budget exhaustion), and External(String); the priority mapping is in priority() (L152): LoopFire highest, ChildCompleted and ScatterJoinComplete next, GoalContinue and GoalWrapUp tied, External lowest. The queue itself, MasterContinuationScheduler (L477), exposes enqueue (L525), drain_ready (L687), drain_ready_for_session (L706), and related interfaces.

AgentOrchestrator holds it as the state field continuations (crates/octos-cli/src/autonomy/agent_orchestrator.rs:11783); draining goes through drain_ready_continuations_for_session (L3027) into the internal drain_ready_continuations_locked (L3112). The only effect visible from the loop side: after one run_task returns, the orchestrator dispatches a new turn according to the ready queue and its priorities. The full semantics of "creating a turn after a turn ends" belong to the goal layer; see Chapter 18.

5.11 Chapter Recap

  1. The module map: 20 modules and 21,369 lines in agent/, in a three-way split (nine core modules, supporting modules, two compaction modules); the public surface is only the process_message / run_task family in crates/octos-agent/src/agent/loop_runner.rs, with organ-level entries all pub(crate) / pub(super).
  2. The lifecycle: six stages, message preparation (seven repair functions), budget check (five gates), LLM call (one main function), stream consumption, tool dispatch, and state update; the main loop file orchestrates rather than implements.
  3. Budget and checkpoint: the check_budget order is the design; Grace grants one reprieve before the hard stop; #27e, on the three-way conjunction of MaxIterations and git and dirty, commits a WIP locally and writes the staged result atomically (writing result.checkpoint.md when the peer holds write ownership), never pushes, and fails open.
  4. Error recovery: the three-layer chain HarnessError (fifteen variants) → RecoveryHint (five variants) → LoopDecision (six variants), 16 buckets with independent limits; ProviderUnavailable and Quota switch lanes while Authentication stays FailFast.
  5. Loop self-healing: the bounded nudge for empty MaxTokens (9fe39f1b) and the cloud-safe temperature override (3c7ff8bf); detect degeneration, recover within bounds, keep the terminal state readable.
  6. The continuation boundary: the scheduler is a pure queue in the goal layer, and the loop's only duty is to hand the stop_reason back.

Further reading

  • assets/ch05-facts.md: the facts table behind every line number and figure in this chapter, with generation commands; each row is reproducible.
  • Chapter 3's three-layer fault-tolerance chain (RetryProvider / ProviderChain / AdaptiveRouter): the mechanism that actually switches lanes after a RotateAndRetry verdict lands.
  • Chapter 8: the layered compaction algorithms behind crates/octos-agent/src/agent/compaction.rs / crates/octos-agent/src/agent/loop_compaction.rs.
  • Chapter 18: the consumer side of MasterContinuationScheduler and the full picture of goal continuation.
  • Issue #489 (M6.2 typed retry bucket) and the #2172 / #2174 commit messages: first-hand motivation for this chapter's state machine and the two self-healing cases.

Exercises

  1. If the five gates of check_budget were reordered (say, token budget first), which deployment shapes would see meaningful overhead or behavior regressions? Give your ordering rationale and the boundary conditions.
  2. #27e fires only on MaxIterations. To give MaxTokens the same "exhaustion means checkpoint" semantics, what extra information would the re-dispatch semantics need? Is changing the trigger condition alone enough?
  3. Among the 16 bucket limits, provider_unavailable gets 4 and authentication gets 1. Suppose a new "provider billing-window cooldown" error class appears: independent bucket, or folded into quota? What is your deciding criterion?
  4. The conversation loop's empty-MaxTokens nudge cap is 2. Making that cap configurable: what are the gains and the risks? Who should own the setting: model operations, platform operations, or the user?
  5. execute_tools is pub(super) while process_message is fully public. If an external caller needed to execute a batch of tools without going through the loop, should the crate boundary open a new entry, or should it reuse an existing public function like execute_approved_tool (crates/octos-agent/src/agent/execution.rs:469)? What is the audit-surface difference between the two choices?

Version note

Version note: This chapter analyzes octos main @ 9c157101 (9c1571016e5ea86955b4b3486c04f0359dfff339, measured 2026-09-02 19:37 +0800). The methodology and reproduction commands for every line number and scale figure (20 modules, 21,369 lines, crates/octos-agent/src/agent/execution.rs 4,730 lines, crates/octos-agent/src/agent/loop_runner.rs 3,979 lines, and others) are in assets/ch05-facts.md. Relative to the v1 draft, this chapter is a full rewrite: the narrative is reorganized around the 20-module map, replacing the old "walk one file section by section" skeleton; the budget checkpoint (#27e), Grace, the typed retry-bucket state machine (M6.2 #489), the two loop self-healing cases (#2172 / #2174), and the goal-layer continuation boundary are new; where the old draft's references such as loop_detect disagree with the current source, the facts table wins.

Chapter 6: The Tool System: 58 Source Files Organized by Capability Domain

Positioning: This chapter covers the "act" stage of the agent loop: the tool system. Instead of the old draft's linear inventory of built-in tools by fixed count, the narrative is reorganized around capability domains: first a survey of how the 58 entries under crates/octos-agent/src/tools/ divide into 10 capability domains, then a descent into three skeleton files (crates/octos-agent/src/tools/registry.rs at 3,581 lines, crates/octos-agent/src/tools/policy.rs at 741 lines, crates/octos-agent/src/tools/args.rs at 479 lines) to explain the Tool trait contract, registration and lookup, exposure control, policy evaluation, and argument safety. Prerequisites: Chapter 5 (how the agent loop calls tools). Who should read it: AI application developers who want to understand agent tool architecture (reader C), and developers preparing to contribute a new tool to octos (reader D).

An agent's intelligence comes from the LLM; an agent's capabilities come from its tools. Without tools, an agent can only generate text. With tools, it can read and write files, run commands, search the web, manage Git repositories, and dispatch subagents.

First, the counting convention. Measured with ls crates/octos-agent/src/tools/ | grep -v test, the directory holds 58 entries: 57 .rs files plus one admin/ subdirectory (7 files inside, 3,424 lines together). The "59 source files" figure that appears on the blackboard and in early planning is the convention that counts test-class files and crates/octos-agent/src/tools/mod.rs in full (ls crates/octos-agent/src/tools/*.rs | wc -l). This chapter uses the structural convention throughout: 58 entries plus the 7 files of the admin/ subdirectory. It also drops the old draft's long-dead fixed tool count: current source has no stable "total number of tools" at all. The same set of source files registers different tool surfaces under different construction paths, and understanding this layered registration model matters more than memorizing a number.

Capability brings risk: every tool call is a potential attack surface. octos answers with a three-line defense at the skeleton layer: ToolPolicy controls which tools are available (deny-wins), argument validation controls input safety (the 1 MB cap and structured error reporting), and symlink-safe I/O plus SSRF checks guard the filesystem and network boundaries. Chapter 7 covers the runtime semantics of the sandbox and write_grant; this chapter covers only the tool-side interface and registration.


6.1 The Capability-Domain Map: How 58 Entries Group

Per the facts table (assets/ch06-facts.md, commit 552be31), the source files under tools/ divide into 10 capability domains. The table below is this chapter's navigation map; each domain gets its own subsection:

Capability domainFilesSource files
Filesystem12read_file, read_paging_probe, read_window, write_file, edit_file, apply_patch, diff_edit, list_dir, glob_tool, grep_tool, replacer, workspace_history
Shell/execution3shell, check, write_grant
Web/research9web_fetch, web_search, deep_search, synthesize_research, research_utils, site_crawl, http, ssrf, browser
Memory5memory_note, record_memory_use, recall, recall_memory, save_memory
Messaging/interaction4message, send_file, send_app_card, ask_user_question
Peer/Fleet10peer_handoff, peer_send_input, peer_gather, peer_list, peer_respond, peer_close, spawn, delegate, check_background_tasks, read_task_output
Code/structure2code_structure, coding_tools
Git1git
Skills/plugins3manage_skills, dora_bridge, mcp_agent
Platform misc6check_workspace_contract, tool_config, mofa_make, robot_groups, mod, admin/(7 files)

How the totals add up: 58 entries = the 55 file-level entries across the 10 domains above (platform misc counts its actual 6 entries, with admin/ as one) + the three skeleton files that belong to no domain (registry, policy, args).

Figure 6-1: capability-domain tool families (mermaid, rendered inline):

graph LR
    subgraph 文件系统
        A1[read_file] --> A2[read_window]
        A3[write_file] --> A4[edit_file/diff_edit]
        A5[apply_patch] --> A6[replacer]
        A7[list_dir/glob/grep] --> A8[workspace_history]
    end
    subgraph 执行
        B1[shell] --> B2[check]
        B3[write_grant]
    end
    subgraph Web/研究
        C1[web_fetch/web_search] --> C2[site_crawl/deep_search]
        C3[synthesize_research] --> C4[http/ssrf]
        C5[browser]
    end
    subgraph 记忆
        D1[save_memory] --> D2[recall_memory/recall]
        D3[memory_note] --> D4[record_memory_use]
    end
    subgraph Peer/Fleet
        E1[spawn/delegate] --> E2[peer_* 六件]
        E3[check_background_tasks] --> E4[read_task_output]
    end

Several names don't match intuition, so settle them first. crates/octos-agent/src/tools/glob_tool.rs registers the tool named glob; crates/octos-agent/src/tools/grep_tool.rs registers grep; crates/octos-agent/src/tools/workspace_history.rs holds workspace_log; crates/octos-agent/src/tools/site_crawl.rs holds deep_crawl; crates/octos-agent/src/tools/deep_search.rs holds search; crates/octos-agent/src/tools/delegate.rs holds delegate_task. The file-name/tool-name split is a scar from this batch's early days of dodging Codex-compatible aliases. crates/octos-agent/src/tools/coding_tools.rs is stranger still: a single file implementing a whole group of Codex-compatible shims, exec_command, write_stdin, spawn_agent, bash, delegate, view_image, tool_search, tool_suggest, image_generation, and more (crates/octos-agent/src/tools/coding_tools.rs:381, :738, :1283, :1945, :2428, :2800, :3149, :3250, :3388). So "file count equals tool count" fails in both directions. crates/octos-agent/src/tools/replacer.rs, crates/octos-agent/src/tools/read_paging_probe.rs, crates/octos-agent/src/tools/ssrf.rs, crates/octos-agent/src/tools/dora_bridge.rs, crates/octos-agent/src/tools/http.rs, crates/octos-agent/src/tools/read_window.rs, crates/octos-agent/src/tools/write_grant.rs are not even standalone tools: they are support modules reused by other tools, or feature switches. That is the second axis of the capability-domain grouping: "who depends on whom," not just "what it's called."

Beyond the capability domains there is a second coordinate system to keep straight. The domains above are a factual division of file organization; crates/octos-agent/src/tools/policy.rs holds another grouping table, TOOL_GROUPS, divided by LLM-visible entry points (crates/octos-agent/src/tools/policy.rs:187 onward, the ToolGroupInfo struct at :179-183, 10 groups in all), and the two do not coincide. group:fs admits only the five main entry points read_file, write_file, edit_file, diff_edit, apply_patch; more than half of the filesystem domain's 12 files are not in the group. The bash alias is implemented in crates/octos-agent/src/tools/coding_tools.rs (the code/structure domain) yet lands in group:runtime because of #1172. The seven members of group:sessions straddle the Peer/Fleet domain and the Codex-compatible shims. Groups are keyed by tool name, not file name, and the reason is direct: policy constrains the names the model can call, not where the source lives.

This static table carries one hard invariant. group:delegated (M6.7, crates/octos-agent/src/tools/policy.rs:307 onward) is the standard deny table for delegated subagents and must cover every member of group:sessions; otherwise a subagent could spawn grandchildren and slip under the recursion guard. expand_group returns a flat static slice; the group mechanism has no group-within-group expansion, so supersets are maintained by hand. The test group_delegated_supersets_session_spawn_family checks it item by item on every build, and a comment records that this drift did happen: spawn_agent, send_input, the *_agent lifecycle tools, and the delegate wrapper were all reachable at one point. The same table deliberately excludes shell; the comment states in plain words that this is not a confinement boundary. Constraining command execution belongs to the sandbox layer, which the tool policy layer cannot manage and should not pretend to.

The domain-by-domain survey follows, one representative design point and source location per domain.

6.1.1 Filesystem (12 files)

The heaviest domain: crates/octos-agent/src/tools/read_file.rs at 2,366 lines and crates/octos-agent/src/tools/write_file.rs at 2,220 lines; these two files alone outweigh most whole domains. Three design points.

First, reading has multiple paths, not one. read_file handles ordinary reads; crates/octos-agent/src/tools/read_paging_probe.rs is a paging probe that observes without changing behavior (crates/octos-agent/src/tools/read_paging_probe.rs:1-6), built to answer the measurement question "does forced paging actually save tokens"; crates/octos-agent/src/tools/read_window.rs is windowed enforcement behind the OCTOS_READ_WINDOW=1 feature switch (crates/octos-agent/src/tools/read_window.rs:3, :178), off by default, byte-for-byte identical to the old behavior without the environment variable. Three paths coexisting says: every tightening of the read path must earn its data first, its default second.

Second, writing has four layers. write_file writes whole files, edit_file does exact replacement, diff_edit matches by context, apply_patch accepts standard patch format. They share the cascading fuzzy-match chain in crates/octos-agent/src/tools/replacer.rs (#1771): the old_string the LLM provides often differs in whitespace, indentation, or escaping, and edit_file no longer hard-fails; it relaxes level by level, exact → line_trimmed → …, and takes the first matcher that produces a result (crates/octos-agent/src/tools/replacer.rs:1-8). This chain is the principle "tolerate the model's imprecision" made concrete.

Third, the three retrieval tools (list_dir/glob/grep) plus crates/octos-agent/src/tools/workspace_history.rs (registered as workspace_log, see crates/octos-agent/src/tools/workspace_history.rs:101) fill in "find files" and "view history."

6.1.2 Shell/execution (3 files)

crates/octos-agent/src/tools/shell.rs is 2,745 lines, registered as shell, the workhorse of the execution domain; the bash alias in the same domain lives at crates/octos-agent/src/tools/coding_tools.rs:1945. crates/octos-agent/src/tools/check.rs is the workspace checker (registered as check, crates/octos-agent/src/tools/check.rs:526). crates/octos-agent/src/tools/write_grant.rs is not a tool at all but the per-path write authorization structure introduced by #1976: WritePathGrant binds through the with_write_grant constructors of write_file/edit_file, turning "please don't write outside" from a polite request into a typed refusal (crates/octos-agent/src/tools/write_grant.rs:53, :72). Its runtime semantics and sandbox translation come in Chapter 7; here you only need one fact: the grant's match syntax is single-segment wildcards (*/? within one segment; **, [...], {...} rejected).

6.1.3 Web/research (9 files)

From web_fetch single-page fetching and web_search, to site_crawl (registered as deep_crawl) and deep_search (registered as search) for site-level and multi-hop research, to synthesize_research assembling the findings into prose. Three support modules underneath: crates/octos-agent/src/tools/http.rs is the raw HTTP client (the tool name is passed in by the constructor, crates/octos-agent/src/tools/http.rs:130); crates/octos-agent/src/tools/ssrf.rs is the shared SSRF guard (check_ssrf_with_addrs at crates/octos-agent/src/tools/ssrf.rs:24, with DNS pinning against rebinding; validate_answer_set at :69; the redirect cap SSRF_MAX_REDIRECTS = 10 at :101); crates/octos-agent/src/tools/browser.rs is the headless browser. Note that output limits are keyed by tool name: in octos_core::tool_output_limit, read_file gets 50,000 bytes, shell 30,000, web_fetch 40,000, web_search 20,000, and search (deep_search) 200,000 (crates/octos-core/src/utils.rs:180-196). Research tools get the widest allowance.

6.1.4 Memory (5 files)

save_memory writes, recall_memory recalls, memory_note takes notes, record_memory_use keeps the usage ledger. The new member is crates/octos-agent/src/tools/recall.rs, introduced by #2131: when context compaction replaces a tool output with a placeholder, recall rematerializes the full bytes from the content-addressed output ledger by tool_call_id, without re-running the call (crates/octos-agent/src/tools/recall.rs:1-4). It stays decoupled from octos-cli's ContextManager through the ToolOutputLedger trait (crates/octos-agent/src/tools/recall.rs:15-21), registered as recall (:106). This mechanism and Chapter 8's compaction ledger are two views of one design.

6.1.5 Messaging/interaction (4 files)

message sends text, send_file sends files, send_app_card sends cards, ask_user_question asks the user. The domain's defining trait: results are for humans, not the model. Output goes over the message bus rather than the tool-result channel (MessageTool/SendAppCardTool register sharing the same tx channel, crates/octos-agent/src/tools/registry.rs:1735-1736; send_app_card's description states outright that initial_state must come from real tool data and must never be fabricated, crates/octos-agent/src/tools/send_app_card.rs:130-140). Chapter 10 develops this.

6.1.6 Peer/Fleet (10 files)

The largest domain. crates/octos-agent/src/tools/spawn.rs at 5,309 lines is the book's largest single-tool file (registered as spawn, crates/octos-agent/src/tools/spawn.rs:2922); crates/octos-agent/src/tools/delegate.rs (registered as delegate_task) is the single-call variant. The six tools peer_handoff/peer_send_input/peer_gather/peer_list/peer_respond/peer_close form the peer-channel primitives; check_background_tasks and read_task_output fill in background queries. This domain is the one most bound to spawn_only exposure control (6.3): calls to backgrounded tools are exactly what the execution loop intercepts and converts into background tasks.

6.1.7 Code/structure (2 files) and Git (1 file)

crates/octos-agent/src/tools/code_structure.rs emits a source-code symbol structure (registered as code_structure, with an internal 1 MB parse cap, crates/octos-agent/src/tools/code_structure.rs:72); crates/octos-agent/src/tools/coding_tools.rs, as above, is the Codex-compatible shim collection. crates/octos-agent/src/tools/git.rs registers as git, with the same 1 MB per-file cap on the diff side (crates/octos-agent/src/tools/git.rs:291).

6.1.8 Skills/plugins (3 files) and platform misc

manage_skills manages skill packages; dora_bridge bridges to the robot framework (tool names come from a mapping table, crates/octos-agent/src/tools/dora_bridge.rs:178); mcp_agent lets spawn dispatch tasks to any MCP backend (crates/octos-agent/src/tools/mcp_agent.rs:1-6). Among platform misc, crates/octos-agent/src/tools/tool_config.rs registers as configure_tool (crates/octos-agent/src/tools/tool_config.rs:633); mofa_make is a dispatcher (its target tools are hidden via mark_internal_hidden, 6.3); crates/octos-agent/src/tools/robot_groups.rs maintains robot safety tiers (SafetyTier: tools register in RobotToolRegistry at the minimum tier they require, and tier expansion automatically includes the lower tier's tools, crates/octos-agent/src/tools/robot_groups.rs:26-38 and :51-59); the 7 files of the admin/ subdirectory provide 20 admin_* operations tools (admin_list_profiles, admin_system_health, admin_update_octos, and others).

Why split files by domain instead of one big file

Back to the grouping table that opened 6.1, one question deserves asking: why aren't the 12 filesystem tools merged into a single large file? What a domain shares is invariants and dependency direction, not volume. The filesystem domain shares three rules: every path must first normalize through the resolve_path family; every read and write must go through no-follow syscalls; every output must accept tool_output_limit truncation. Put those three in a shared module, put tool semantics in their own files, and adding a new read-path tool means implementing semantics, not re-copying defenses. Between domains, sharing is deliberately refused: the web domain's SSRF checks and the file domain's path checks do not reference each other, because their threat models differ (outbound request redirection versus local symlinks), and mixing them would turn a fix in one domain into a regression surface in the other. crates/octos-agent/src/tools/spawn.rs at 5,309 lines already demonstrates the cost of single-file bloat; crates/octos-agent/src/tools/registry.rs at 3,581 lines is the opposite extreme; the current per-domain split is the middle ground.


6.2 The Tool trait: the contract in crates/octos-agent/src/tools/mod.rs

Every tool implements the same trait (crates/octos-agent/src/tools/mod.rs:609):

#![allow(unused)]
fn main() {
#[async_trait]
pub trait Tool: Send + Sync {
    fn name(&self) -> &str;
    fn description(&self) -> &str;
    fn input_schema(&self) -> serde_json::Value;
    fn tags(&self) -> &[&str] { &[] }
    fn contexts(&self) -> &[String] { &[] }
    async fn execute(&self, args: &serde_json::Value) -> Result<ToolResult>;
    fn truncation_recovery(
        &self,
        args: &serde_json::Value,
        omitted_bytes: usize,
    ) -> Option<String> { None }
    async fn execute_with_context(
        &self,
        ctx: &ToolContext,
        args: &serde_json::Value,
    ) -> Result<ToolResult> { /* 默认委托 execute */ }
}
}

The contract has three layers. The declaration layer (name + description + input_schema) forms the ToolSpec sent to the LLM. The execution layer is two entry points: execute is the legacy args-only signature, execute_with_context is the typed entry introduced in M8.1 (the module docs at crates/octos-agent/src/tools/mod.rs:11-28 record the migration in detail): the default implementations delegate to each other, and migrated tools override execute_with_context while letting execute re-enter with a zero-value context, so external callers see predictable behavior. A tool overrides at most one of the two; overriding both creates two independent paths the executor cannot reconcile. The governance layer is tags() (capability tags, consumed by require_tags filtering) and contexts() (declares which model contexts the tool appears in; an empty list means visible everywhere).

truncation_recovery deserves its own paragraph. Truncation happens in the execution loop, but the loop holds a bare string: it does not know which tool produced it, whether paging is supported, or what the arguments were. The tool knows how to continue reading but does not know it was truncated. This hook is the missing half: after truncating, the loop comes back with args and omitted_bytes to ask, and the tool returns a concrete "here is the next call to make" suggestion; the default None means there is no continuation path and none will be invented. The accompanying output cap is the tool_output_limit from 6.1.3 (crates/octos-core/src/utils.rs:180).

The typed context ToolContext (crates/octos-agent/src/tools/mod.rs:261) is an architecture autobiography in struct form: the reporter and harness event slots are UI channels; agent_definitions, permissions, file_state_cache, notifications, app_state are stubs pre-seeded in M8.1 and filled in by later milestones (each annotated with its owning issue); subagent_output_router/subagent_summary_generator/task_supervisor/cost_accountant/parent_session_key let spawned subagents and pipeline workers share the parent session's routing, summarization, supervision, and cost accounting; spawn_depth is the spawn-nesting guardrail from #607. Reading this struct's field order is close to reading half a year of octos evolution.


6.3 ToolRegistry: registration, lookup, and exposure control

crates/octos-agent/src/tools/registry.rs is 3,581 lines, with ToolRegistry defined at crates/octos-agent/src/tools/registry.rs:127. It is no simple name-to-tool dictionary; its field list (around :127-235) shows it managing seven jobs at once: the tool table, the workspace root, provider-level policy (filtering specs() without removing tools), the context tag filter, cached specs, the plugin-tool marker, and ownership of MCP transport handles.

These fields were not designed in one sitting; the issue numbers in the comments show the sediment layers. spawn_only and spawn_only_messages (:164-166) are survivors of RFC-0; live_catalog (:179) came with #1148: tool_search and tool_suggest need a catalog that refreshes in real time as the registry changes, while tool execution itself cannot reach a registry reference. So on every change (register, apply_policy, mark_spawn_only, etc., unified through invalidate_cache, :1086) the registry clones visible tools into this Mutex-guarded cell, and the query side takes a snapshot through live_catalog_handle() (:1420). A comment takes care to justify the Mutex: refreshing only clones a small Vec, and only when the registry changes. internal_hidden (:206) and the ownership semantics of mcp_services (#1886: visibility filtering must not decide transport lifetime) were bolted on by the RFC-1 fixup and the MCP merger respectively.

Beyond the fields there is a property easy to miss: specs() orders its output (:746). tools is a HashMap whose iteration order varies across processes and rebuilds, while providers replay this array verbatim into the LLM's prompt prefix; any reordering punches through the provider-side prompt cache (the tool array is the first segment of the cached prefix, as in Anthropic's cache_control). Sorting by name makes the serialized bytes stable for the same tool set, and only then does cache hit rate hold. This is an implementation detail promoted to an external contract: field order could have been arbitrary, but cache cost nailed it down.

6.3.1 Three constructors

#![allow(unused)]
fn main() {
pub fn with_builtins(cwd: impl AsRef<Path>) -> Self {
    Self::with_builtins_and_sandbox(cwd, Box::new(NoSandbox))
}

pub fn with_builtins_and_sandbox(cwd: impl AsRef<Path>, sandbox: Box<dyn Sandbox>) -> Self {
    let permissions = EffectivePermissions::workspace_write();
    Self::with_builtins_and_permissions(cwd, sandbox, permissions)
}
}

(excerpt from crates/octos-agent/src/tools/registry.rs:1243-1252)

with_builtins starts with a no-op sandbox; with_builtins_and_sandbox takes a custom sandbox but still workspace-write permissions; only with_builtins_and_permissions (:1254) hands over permissions too. The #1607 comment spells it out: under a no-op sandbox the agent-internal workspace validator runs argv directly, because there is nothing to escape from. The empty constructor new() (:236) starts from zero and is left to tests and special assemblies.

6.3.2 Registration and lookup

register (:536) takes ownership; register_arc (:558) takes Arc<dyn Tool>: when the same tool instance must appear in multiple registries at once (parent session and spawned subagent), the latter is mandatory. Lookup is get/get_tool; the dispatch boundary is execute_with_context, where four defenses stack: provider-policy refusal, the argument size cap (6.5), catch_unwind panic isolation (a panicking tool degrades to a failed ToolResult instead of killing the session actor and its children), and the global execution timeout (default 1,800 seconds; set_tool_timeout_secs at :279).

6.3.3 Exposure control: LRU is dead, spawn_only rules

The old draft spent pages on LRU tool lazy activation and activate_tools; state clearly first: that mechanism was deleted in RFC-0 (commit 172fb2be, issue #1289) along with activate_tools; find_evictable and ToolLifecycle no longer exist. The current comment on specs() says it plainly: every enabled tool ships every turn, and the only remaining exclusions are internal-hidden, provider-policy refusal, and context-filter misses; nothing recency-based remains (crates/octos-agent/src/tools/registry.rs:706-711).

The surviving mechanism is spawn_only (mark_spawn_only at :299): tools so marked stay visible in specs() and callable by the LLM, but the call is intercepted at the execution loop's dispatch point, converted into a background task, and answered immediately with a task handle (crates/octos-agent/src/agent/execution.rs:775-780 nearby). Figure 6-2 is the sequence:

sequenceDiagram
    participant LLM
    participant Loop as 执行循环
    participant Reg as ToolRegistry
    participant BG as 后台任务
    LLM->>Loop: tool_call(spawn_only 工具)
    Loop->>Reg: is_spawn_only(name)?
    Reg-->>Loop: true
    Loop->>Loop: provider 策略复查(拦截点)
    Loop->>BG: 起后台 tokio task 执行
    Loop-->>LLM: 立即返回 task_handle
    BG--)Loop: 完成回调(background_result_sender)
    Loop--)LLM: 下一轮注入结果消息

Supporting details: each registry holds a spawn_only_invoked atomic bool recording whether the mechanism was actually used this run; background_result_sender notifies the session actor when a task finishes; #896 fixed propagation of the filename inside the task_handle envelope so the LLM has a stable name to cite. Beyond those, two semantics are easy to miss. First, the marking can be cleared wholesale: clear_spawn_only (crates/octos-agent/src/tools/registry.rs:355) empties both sets and invalidates the specs cache; its comment says the purpose is subagent registries, where spawn_only tools should be directly callable, because a subagent is already a background context and backgrounding it again is meaningless. This directionality (parent session intercepts, child session permits) lines up with the layered registration paths of 6.3.4: exposure control is per-registry state, not an intrinsic property of the tool. Second, after M10 Phase 4 the LLM no longer receives that one free-text line plus full stdout, but a compact task_handle envelope built by spawn_only_handle_message (crates/octos-agent/src/tools/registry.rs:388): task id, expected artifact files, output directory, a read_with: read_task_output hint, and five read modes (head/tail/grep/line_range/file). Full output still lands on disk via M8.7's SubAgentOutputRouter and reaches the SPA; the change affects only what the model sees. The design goal: let the model inspect intermediate artifacts on demand without bloating context, complementary to read_window's pre-limiting direction.

The RFC-0 trade-off that deleted LRU sits in the sidebar at this chapter's end.

mark_internal_hidden (:324) hides in the other direction: internal-hidden tools remain callable by internal forwarders but vanish from specs(), and no LLM-reachable "unhide" path exists; it is one-way. The dispatch targets of mofa_make (mofa_slides, mofa_cards, etc.) rely on it to stay reachable only through the dispatcher.

6.3.4 Six registration paths

"58 entries" does not mean "58 tools in every session." The same source files enter the registry through six paths, each appending or trimming:

  1. Built-in base: the constructors (crates/octos-agent/src/tools/registry.rs:1243-1254) register the core tools: file, shell, retrieval, git, and others.
  2. Profile roster: crates/octos-agent/src/assets/profiles/coding.json declares an allow_list (the lean coding roster, introduced in 9ecc5845), applied by crates/octos-agent/src/profile/mod.rs; the list has only 12 entries but includes three group entries, group:runtime/group:search/group:memory, and deliberately reads back in check, update_plan, tool_search. The early lean list rejected those too, leaving the default coding session unable to run the workspace check or build a plan. tool_search is the escape hatch: the model can dynamically discover tools excluded by the allow_list.
  3. chat command: crates/octos-cli/src/commands/chat.rs:855, :1337 builds the registry with with_builtins_and_permissions, then injects runtime additions such as the peer tools.
  4. ACP: crates/octos-cli/src/commands/acp.rs:224, :501, and several other places use with_builtins_and_sandbox.
  5. gateway: crates/octos-cli/src/commands/gateway/gateway_runtime.rs:823; note that it calls apply_policy earlier than the session actor's registry reuse (the comment at crates/octos-cli/src/session_actor.rs:2884 records this ordering contract).
  6. MCP: register_tools at crates/octos-agent/src/mcp.rs:532 merges remote tools in; a name colliding with a built-in is rejected outright, so a remote server cannot silently replace core functionality. Transport handles go to the registry before the tools do (#1886: visibility filtering must not decide transport lifetime, or a profile narrowing would kill the stdio child process as a side effect).

Figure 6-3: registration paths stacked (mermaid): base → profile roster → per-mode appends → policy trim → specs() output.

graph TD
    A[with_builtins 基座] --> B[profile allow_list 裁剪]
    B --> C1[crates/octos-cli/src/commands/chat.rs 注入 peer 等]
    B --> C2[crates/octos-cli/src/commands/acp.rs / gateway 追加]
    B --> C3[session_actor: cron/pipeline]
    C1 --> D[apply_policy / provider 策略]
    C2 --> D
    C3 --> D
    D --> E[mcp.register_tools 并入远端]
    E --> F[specs 缓存输出]

6.4 ToolPolicy: deny-wins and grouping

crates/octos-agent/src/tools/policy.rs, 741 lines. The core struct (crates/octos-agent/src/tools/policy.rs:28-40):

#![allow(unused)]
fn main() {
pub struct ToolPolicy {
    pub allow: Vec<String>,
    pub deny: Vec<String>,
    pub require_tags: Vec<String>,
    pub bash_file_writes: BashFileWrites,
}
}

Three dimensions of semantics plus one shell special case. Empty allow means "permitted unless explicitly denied"; deny always overrides allow; when require_tags is non-empty the tool must declare at least one matching tag, and untagged tools fail outright (fail closed). That behavior changed after peer review; the comment on is_allowed_with_tags (crates/octos-agent/src/tools/policy.rs:131-148) preserves the record of this tightening. Figure 6-4 shows the evaluation flow:

flowchart TD
    S[evaluate(name)] --> D{deny 列表命中?}
    D -- 是 --> DR[Deny, reason=policy_deny<br/>或 robot_tier_gate]
    D -- 否 --> A{allow 为空?}
    A -- 是 --> OK[Allow]
    A -- 否 --> M{allow 命中?}
    M -- 是 --> OK
    M -- 否 --> DR2[Deny, 记 metric]
    OK --> T{require_tags 非空?}
    T -- 否 --> PASS[可见]
    T -- 是 --> TG{工具标签有交集?}
    TG -- 是 --> PASS
    TG -- 否 --> FAIL[不可见, fail closed]

evaluate (crates/octos-agent/src/tools/policy.rs:77-128) emits an octos_tool_policy_denial_total metric on denial, with reasons split between robot_tier_gate and policy_deny, so operators of robot integrations can alert on either.

Entries take three forms: tool names, group:* groups, and wildcards. The grouping table TOOL_GROUPS (crates/octos-agent/src/tools/policy.rs:180 onward, ToolGroupInfo) sorts tools into group:fs, group:runtime, group:web, group:search, group:sessions, and others. The lesson of #1172 is written into group:runtime: the group must contain the Codex-compatible alias bash, or a profile that disables runtime can still slip through via bash(cmd=…). Alias equivalence is a hard correctness constraint on policy.

bash_file_writes (#28b) is a three-position switch (crates/octos-agent/src/tools/policy.rs:55-68): allow (the default) changes nothing; warn appends a "use edit_file/diff_edit instead" hint to the tail of change receipts; deny refuses write-shaped commands after heuristic pre-screening, with a # octos:allow-write trailing-comment escape hatch.

Two application entry points must be distinguished. apply_policy (crates/octos-agent/src/tools/registry.rs:869-875) physically trims the registry with retain: trimmed tools are truly gone. set_provider_policy (crates/octos-agent/src/tools/registry.rs:947-953) only sets a filter: tools stay in the table, and specs() plus the dispatch boundary judge dynamically under deny-wins-then-allow semantics (alias equivalence included); provider_policy_permits additionally lets the workspace validator confirm "does provider policy permit the model to call this tool." The config key for provider-level policy is tool_policy_by_provider (crates/octos-cli/src/config.rs:132), mapping provider names to their own ToolPolicy; a policy fetched via provider_policy() propagates to subagent registries along with spawn.


6.5 Arguments and path safety

Three gates.

Gate one, size. The dispatch boundary rejects oversized arguments, cap 1 MB (MAX_ARGS_SIZE = 1_048_576), with estimate_json_size recursively estimating the serialized size (crates/octos-agent/src/tools/registry.rs:1132-1143; the estimator at :95-119). Note that this 1 MB lives in crates/octos-agent/src/tools/registry.rs, not crates/octos-agent/src/tools/args.rs. The facts table's reminder on this point is correct: the constant is not in crates/octos-agent/src/tools/args.rs.

estimate_json_size (crates/octos-agent/src/tools/registry.rs:95-119) is worth a closer look, because it demonstrates a trade-off that recurs. The obvious implementation is serde_json::to_string(args).len(), but that serializes the entire argument into a String first, allocating memory the size of the argument, just to obtain one number, then throws it away. At the dispatch boundary, crossed on every tool call of every turn, that allocation is pure waste. This function instead walks the serde_json::Value tree recursively, counting bytes per node: strings by content length plus escape overhead plus two quotes; arrays by 2 plus the sum of elements plus commas; objects by key length plus 3 (colon and quotes) plus the subtree, for each key. The estimate is exactly accurate enough for the one judgment "over the cap or not." Zero allocation, zero copy, good enough and stopping there: the shape boundary-checking code should have.

Gate two, structure. crates/octos-agent/src/tools/args.rs, 479 lines, is about error quality, not whether to error: on serde failure it reported only the first problem and ignored unknown fields, so the model either retried verbatim (an infinite loop, #1765) or guessed blindly at fixes. parse_tool_args keeps serde as the parsing source of truth, then on failure walks the raw JSON against the tool's own input_schema() and reports every problem at once: which required parameter is missing, which name is misspelled (with a did-you-mean), which type is wrong (crates/octos-agent/src/tools/args.rs:1-30). Errors reach the model as ToolInputError, capped at 4,096 bytes (TOOL_INPUT_ERROR_MAX_BYTES in crates/octos-agent/src/tools/mod.rs), so the model can self-repair while caller-controlled content cannot blow up the output limit (#2193 R4). These failures are also marked side-effect-free and non-cascading (#1690): one bad call does not drag down the good calls in the same batch.

Gate three, boundaries. Paths normalize through resolve_path (crates/octos-agent/src/tools/mod.rs:972) and its scoped variants (:1014, :1052, :1061) onto the session filesystem contract; file reads and writes go through read_no_follow/write_no_follow against symlink escape (usage visible around crates/octos-agent/src/tools/edit_file.rs:182); the network side is guarded by crates/octos-agent/src/tools/ssrf.rs (6.1.3). The full threat models of the three belong to Chapter 7.

6.5.1 The coding tool contract

What the frontend wants is not "roughly these tools" but a machine-checkable contract. crates/octos-cli/src/api/coding_tool_contract.rs defines coding.tool_contract.v1 (:12), contract ID codex-compatible-coding-v1, policy ID coding-v1. The P0 required tool set CODING_P0_REQUIRED_TOOL_NAMES (:85) lists 10: apply_patch, exec_command, write_stdin, update_plan, request_user_input, spawn_agent, send_input, resume_agent, wait_agent, close_agent. The tool status vocabulary is available/aliased/disabled_by_policy/missing/unimplemented/deferred (:21-34), with connected/connecting/failed/disabled on the MCP side. The amusing detail: the comment on deferred still mentions LRU auto-eviction and activate_tools restoration (vocabulary kept for frontend compatibility), while the mechanism itself died with RFC-0. Do not conclude from the comment that LRU lives.

6.5.2 Three governance tools as samples

write_grant (#1976), read_window (#1638), and recall (#2131) mark the tool system's recent direction: fewer tools that "do more," more tools that "govern what was already done." write_grant sinks the fleet task's fs.write authorization into a kernel-side fence inside the tool; read_window is off by default and requires OCTOS_READ_WINDOW=1, with a documented parameter provenance: the 2,000-line cap comes from the pi harness's measured default, and the 48 KiB byte cap is back-derived to fit page footer plus content inside the 50,000-byte output limit (crates/octos-agent/src/tools/read_window.rs:1-30); recall makes compaction-replaced outputs retrievable by id, one design with Chapter 8's content-addressed ledger. All three share one prefix: change nothing by default, tighten only on opt-in.


6.6 Engineering decision sidebar: why LRU lazy activation was deleted

RFC-0 (commit 172fb2be, #1289) deleted LRU not because it was broken but because the problem it answered had found a different answer. LRU assumed "tool schemas are a significant per-turn token cost; cold tools should hide, and the model fetches them back via activate_tools when needed." Three facts dissolved that assumption. First, the fetch-back path requires the model to know which tools it lacks, and the model least knows that after the tools are hidden. The tool_search escape hatch (now shipped with the lean coding roster by default) solves discovery at lower complexity. Second, lazy activation made tool visibility depend on session history: "which tools does this session have?" turned from a static question into a dynamic one, and contract validation, policy audit, and frontend rendering all paid for it. Third, what long-running tools that need "declare first, execute later" actually need is "don't block the foreground turn," which is precisely spawn_only auto-backgrounding semantics, unrelated to exposure control. After the deletion, specs() outputs in full every turn, and the cache mechanism (cached_specs, invalidated on registry change) absorbs the repeated serialization cost. The lesson: when two mechanisms appear to treat the same symptom, first ask whether each one's causal chain still holds.


6.7 Recap

This chapter surveyed the 58 entries and 10 domains of tools/, then descended into three skeleton files: the Tool trait's three-layer contract and the typed-context migration; ToolRegistry's three constructors, six registration paths, and spawn_only-centered exposure control (LRU deleted); ToolPolicy's deny-wins, grouping, alias equivalence, and the fail-closed tag gate; and the three safety gates of argument size, structured error reporting, and path/network boundaries. Chapter 7 completes the runtime semantics of sandbox and grants; Chapter 16's closed registry and Chapter 18's goal/peer tools both stand on this chapter's registration and policy semantics.

Further reading

  • The module docs atop crates/octos-agent/src/tools/mod.rs: the full design note for the typed ToolContext migration (M8.1).
  • The ToolRegistry field comments in crates/octos-agent/src/tools/registry.rs: design rationale for MCP transport ownership (#1886) and panic isolation.
  • crates/octos-agent/src/tools/policy.rs: the fail-closed revision comment on is_allowed_with_tags.
  • Chapter 5 (the loop's tool-call cycle), Chapter 7 (sandbox and write_grant), Chapter 8 (recall and the compaction ledger).

Exercises

  1. The same coding.json allow_list behaves differently under apply_policy (physical trim) versus set_provider_policy (dynamic filter). In which scenario does the difference surface? Hint: consider MCP tools merging in afterward.
  2. When require_tags is non-empty, untagged tools fail closed rather than pass. What security property does that unfriendliness buy?
  3. group:runtime must contain the bash alias. If a new shell-entry alias is added but forgotten in the group, at which layer does the attack surface appear: policy, registry, or execution?
  4. recall depends on a content-addressed ledger; read_window depends on windows plus page footers. Both work on "truncation" in opposite directions (one retrieves after the fact, one limits in advance). Which approach suits a tool like grep, whose output shape is unpredictable? Why?
  5. RFC-0 deleted LRU but kept spawn_only. Deciding whether to mark a new tool spawn_only, what property of the tool should the criterion look at?

Version note

Version note: This chapter's baseline is octos source commit 9c157101 (measured 2026-09-03, main branch). Line numbers and structure follow assets/ch06-facts.md (commit 552be31); all key line numbers were re-verified by hand. Historical note: LRU tool lazy activation and activate_tools were deleted in RFC-0 (172fb2be, #1289); the deferred status vocabulary in crates/octos-cli/src/api/coding_tool_contract.rs is retained for frontend compatibility and does not mean the mechanism survives.

Chapter 7: Defense in Depth: Fail-Closed Sandboxes, Injection Defense, and Capability Grants

Positioning: This chapter walks octos's security system end to end from a defense-in-depth perspective: the fail-closed semantics of the process sandbox, command and dispatch policy, injection detection and output redaction, and the WorkerGrant capability model. Prerequisite: Chapter 6 (ToolPolicy and deny-wins semantics). It is written for readers who need to understand or extend sandbox backends and design capability grants for fleet workers (B/D), and for AI application developers who care about agent security practice (C).

7.0 What problem this chapter solves

What separates an agent from ordinary software is that it acts: it runs shell commands, reads and writes files, and makes network requests. Each is an attack surface, and the shell is the most dangerous of the three, because it reaches the full capability of the other two. That puts a concrete question in front of the security design: when the operator insists that "commands must run in a sandbox" and no usable sandbox exists on the host, what should the system do?

The old answer was best effort: if probing found no backend, it silently fell through to unsandboxed execution and the command ran anyway. That answer was overturned on 2026-08-31. eb7c7221 (PR #2196, 14 files, +1621/−158) changed the decision to fail-closed: an explicitly requested mode that cannot be honored refuses to execute, and Auto mode with no backend still degrades but with a loud warning. In the same window, ffcde205 tightened cargo grants, and WorkerGrant in crates/octos-fleet/src/grant.rs turned "what a worker may do" from scattered config keys into a validated type. This chapter unfolds the system in four layers: process sandbox → command and dispatch policy → injection and redaction → capability grants.

One crate boundary is easy to get wrong, so settle it first. The doc at crates/octos-sandbox/src/main.rs:1 reads "octos-sandbox: platform sandbox helper binary": it is a platform helper binary. On Windows it creates or reuses an AppContainer profile and starts the command inside it; on Linux it applies Landlock filesystem rules plus a seccomp denylist and then execs; on macOS and other platforms it is a no-op passthrough. The real sandbox subsystem lives in crates/octos-agent/src/sandbox/, and all references below use full crates/ paths.

7.1 The process sandbox: seven impls and the fail-closed decision

7.1.1 Scale and shape

The six files of crates/octos-agent/src/sandbox/ total 5,347 lines:

FileLinesFirst-line doc
crates/octos-agent/src/sandbox/mod.rs2190//! Sandboxing for shell command execution.
crates/octos-agent/src/sandbox/macos.rs1767//! macOS sandbox using sandbox-exec.
crates/octos-agent/src/sandbox/bwrap.rs498//! Linux sandbox using bubblewrap (bwrap).
crates/octos-agent/src/sandbox/docker.rs392//! Docker container sandbox.
crates/octos-agent/src/sandbox/windows.rs325//! Windows sandbox using AppContainer via helper binary.
crates/octos-agent/src/sandbox/landlock.rs175//! Linux container sandbox using the octos-sandbox Landlock/seccomp helper.

The core abstraction is pub trait Sandbox (crates/octos-agent/src/sandbox/mod.rs:443), with a single required method, wrap_command(&self, shell_command: &str, cwd: &Path) -> Command: wrap a shell command string into a restricted process launch. Around that trait sit exactly seven impl Sandbox for blocks: five real backends plus two sentinels.

implTypeRole
crates/octos-agent/src/sandbox/bwrap.rs:29BwrapSandboxLinux bubblewrap, mount namespace isolation
crates/octos-agent/src/sandbox/docker.rs:36DockerSandboxDocker container isolation, works on any OS
crates/octos-agent/src/sandbox/landlock.rs:27LinuxContainerSandboxDelegates to the octos-sandbox helper for Landlock + seccomp
crates/octos-agent/src/sandbox/macos.rs:185MacosSandboxmacOS sandbox-exec (SBPL profile)
crates/octos-agent/src/sandbox/windows.rs:46AppContainerSandboxDelegates to octos-sandbox.exe to create an AppContainer
crates/octos-agent/src/sandbox/mod.rs:500NoSandboxSentinel: passthrough execution (sh -c / cmd /C)
crates/octos-agent/src/sandbox/mod.rs:914RefusingSandboxSentinel: refuses execution, the fail-closed carrier

The two sentinels deserve attention. NoSandbox is not the name of the concept "no sandbox"; it is a real type (pub struct NoSandbox; at crates/octos-agent/src/sandbox/mod.rs:498) whose is_noop() returns true so callers can check. RefusingSandbox (struct defined at crates/octos-agent/src/sandbox/mod.rs:909) has a wrap_command that never executes the requested command: it substitutes a command that prints refusal text to stderr and exits 1.

7.1.2 SandboxMode and MountMode

Two enums drive the configuration layer. MountMode (crates/octos-agent/src/sandbox/mod.rs:408) controls how the Docker backend mounts the workspace, with serde lowercase naming and three variants: None (:410, no mount), ReadOnly (:413, serde name ro), ReadWrite (:417, default, serde name rw).

SandboxMode (crates/octos-agent/src/sandbox/mod.rs:423) has seven variants:

  • Auto (:426, default): the doc comment names "bwrap on Linux, sandbox-exec on macOS, AppContainer on Windows"
  • Bwrap (:428), Landlock (:430), Macos (:432), Docker (:434)
  • AppContainer (:437, serde name appcontainer)
  • None (:439): no sandboxing, passthrough

Auto is the only mode allowed to degrade when it finds no backend; every explicit mode goes through fail-closed refusal. That asymmetry is the subject of 7.1.3.

Auto's probe order and fallback logic live in the SandboxMode::Auto branch of decide_sandbox (crates/octos-agent/src/sandbox/mod.rs:875-901): first pick the native backend for the OS (macOS probes sandbox_exec, Linux probes bwrap before the Landlock helper, Windows probes the AppContainer helper); only when no native backend exists does docker().then_some(SandboxBackendChoice::Docker) serve as the fallback; if that is absent too, the fail_closed flag routes the outcome to refusal or degradation. The order reflects two considerations. Native first because of isolation granularity: bwrap/sandbox-exec/AppContainer reuse kernel mechanisms directly, have no daemon dependency, and their failure mode is a one-time event at probe time; the Docker fallback works on any OS but depends on a daemon and an image. Probing itself comes in two grades of honesty: the bwrap() method of HostBackendProbe (crates/octos-agent/src/sandbox/mod.rs:574) documents "actually runs bwrap, not a PATH scan", and in RealHostProbe it calls bwrap_works() (crates/octos-agent/src/sandbox/mod.rs:1140), which runs a real bwrap with minimal mounts plus /bin/true to verify the kernel lets the current user create namespaces; docker() is merely a which_exists("docker") PATH scan. On Linux the difference matters most: unprivileged user namespaces are often disabled by distributions, so having bwrap on PATH does not mean bwrap runs. A PATH-style probe would fabricate a backend that fails on every spawn, and "configured yet failing every time" is exactly the class of silent failure eb7c7221 set out to eliminate. Within Linux native backends, bwrap comes before Landlock: the granularity is similar, but bwrap does not depend on a helper binary, while a Landlock probe is only true once the helper answers --probe-linux.

7.1.3 decide_sandbox: a pure decision function and fail-closed

Before eb7c7221, create_sandbox interleaved cfg! platform probing with backend construction, which produced two problems: the cross-platform matrix could not be tested on a dev machine (you cannot test the Linux path on macOS), and explicit modes degraded silently. The refactor extracted the decision into a pure function, pub fn decide_sandbox(config, os, probe) (crates/octos-agent/src/sandbox/mod.rs:809):

#![allow(unused)]
fn main() {
pub fn decide_sandbox(
    config: &SandboxConfig,
    os: HostOs,
    probe: &dyn HostBackendProbe,
) -> SandboxDecision {
}

All host facts arrive as parameters (HostOs is a data enum, crates/octos-agent/src/sandbox/mod.rs:534; backend availability flows through the HostBackendProbe trait), so the complete matrix for every OS can be tested from any dev host. It returns a SandboxDecision (crates/octos-agent/src/sandbox/mod.rs:744) with three values: Confine(SandboxBackendChoice), Unconfined(UnconfinedReason), Refuse(SandboxUnavailable). The contract is written directly in the function docs (crates/octos-agent/src/sandbox/mod.rs:800-808):

  • enabled = false together with mode = "none" is an explicit opt-out: passthrough, and it takes priority over fail_closed
  • An explicit backend mode that cannot be honored (wrong OS or missing backend) refuses; it never silently degrades to no isolation
  • Auto picks the best available backend (native first, Docker fallback); with none available it degrades to passthrough but warns, and fail_closed can turn that degradation into refusal

UnconfinedReason (crates/octos-agent/src/sandbox/mod.rs:664) distinguishes three passthrough causes: Disabled (explicit opt-out set by --danger-full-access), ExplicitNone (mode="none"), and AutoNoBackend (Auto found no backend, the only legal degradation). SandboxUnavailable (crates/octos-agent/src/sandbox/mod.rs:694) is a typed refusal reason carrying requested, reason, and a per-OS remediation block (remediation_for at crates/octos-agent/src/sandbox/mod.rs:754 gives install advice per OS).

How the refusal reaches the user splits by audience, a MUST-FIX from the #2196 review: the Display implementation faces the model and states "Shell/exec commands will keep refusing until then"; operator remediation advice goes only to logs and octos doctor, never into model context. stderr_line() (crates/octos-agent/src/sandbox/mod.rs:724) filters the refusal text down to [A-Za-z0-9 ./:_=,-], so once embedded into sh -c 'echo ... >&2; exit 1' a quote escape back into command execution is impossible.

Fail-closed execution also has an earlier short-circuit. Exec-shaped tools check refusal() before spawning: crates/octos-agent/src/tools/shell.rs:1069 and crates/octos-agent/src/tools/coding_tools.rs:501, :625, :2068 all begin with if let Some(refusal) = self.sandbox.refusal(); on a hit they return the model-facing refusal text directly as the tool result, without starting a subprocess. So RefusingSandbox's wrap_command (the impl starting at crates/octos-agent/src/sandbox/mod.rs:914) is only the backstop: commands that actually reach it (for example, wrapped through a third-party call site holding a bare Box<dyn Sandbox>) get the echo-plus-exit-1 substitute command. The two layers divide the work: the tool-layer short circuit guarantees the model sees a readable refusal rather than a bare exit-1 output, while the trait-layer backstop guarantees no call site can run a command without a sandbox.

The engineering motivation deserves the full story. The pre-eb7c7221 behavior is on record in the refactor comment at crates/octos-agent/src/sandbox/mod.rs:524-528: create_sandbox interleaved cfg!-gated probing with backend construction, causing "two explicit modes silently degrade to no confinement". The concrete scenario: an operator pins sandbox.mode = "bwrap" in CI or fleet config, the host lacks bwrap, commands run unsandboxed, and the only clue is one easily drowned warn line in startup logs. Three properties stack to make this failure mode a must-fix: the configuration expresses an isolation intent that gets overridden (fail-open); the override is invisible (the user believes a sandbox is active); the behavior matrix is untestable (cfg! dispatch at compile time means a macOS dev machine has no Linux code path at all, so regressions could only be caught by real Linux CI). decide_sandbox parameterizes all three classes of fact (config, HostOs, probe), and one refactor fixes all three: an unfulfillable explicit mode returns Refuse, the refusal is visible to the operator with remediation attached, and the full cross-platform matrix can be enumerated in unit tests on any dev machine.

create_sandbox (crates/octos-agent/src/sandbox/mod.rs:1005) is the projection from decision to backend: Confine constructs the backend, Unconfined returns NoSandbox and logs per reason (AutoNoBackend goes through warn_auto_unconfined_once, crates/octos-agent/src/sandbox/mod.rs:1039, a std::sync::Once that warns once per process), and Refuse returns RefusingSandbox. The signature stays infallible, so the many construction sites need no changes; but every command on that result carries the typed SandboxUnavailable refusal.

flowchart TB
    S["decide_sandbox(config, os, probe)<br/>crates/octos-agent/src/sandbox/mod.rs:809"] --> Q1{"enabled = false<br/>or mode = none?"}
    Q1 -->|yes| U["Unconfined(Disabled / ExplicitNone)<br/>explicit opt-out, passthrough"]
    Q1 -->|no| Q2{"mode is explicit backend?"}
    Q2 -->|yes| Q3{"OS matches and backend available?"}
    Q3 -->|yes| C["Confine(backend)"]
    Q3 -->|no| R["Refuse(SandboxUnavailable)<br/>RefusingSandbox: refuse execution<br/>fail-closed"]
    Q2 -->|Auto| Q4{"any backend available?<br/>native first, Docker fallback"}
    Q4 -->|yes| C
    Q4 -->|no| Q5{"fail_closed?"}
    Q5 -->|false| U2["Unconfined(AutoNoBackend)<br/>the only legal degradation, warn once per process"]
    Q5 -->|true| R

Figure 7-1: SandboxMode resolution and the fail-closed decision flow. An explicit mode that cannot be honored always refuses; only Auto finding no backend may degrade to passthrough.

7.1.4 Implementation notes for the five backends

bwrap (Linux): the order inside wrap_command is: strip BLOCKED_ENV_VARS → --ro-bind read-only mounts for /usr, /lib, /lib64, /bin, /sbin, /etc → --tmpfs /tmp and --tmpfs /var/tmp (ordered before the workspace bind, so a workspace under /tmp is not undone by tmpfs semantics) → workspace --bind or --ro-bind (depending on workspace_write) → an optional .git-targeted rw bind (repo_git_write) → --dev, --proc → --unshare-net when !allow_network → --unshare-pid, --die-with-parent. The repo_git_write comment is explicit: this is a narrow grant that binds only <repo>/.git, never the whole /, because the latter would expose host AF_UNIX sockets such as SSH_AUTH_SOCK and docker.sock to processes inside the sandbox (field docs at crates/octos-agent/src/sandbox/bwrap.rs:17-26).

Landlock (Linux): LinuxContainerSandbox at crates/octos-agent/src/sandbox/landlock.rs:27 applies no restrictions itself; it delegates everything to the octos-sandbox helper process so the Landlock and seccomp setup happens before the shell is exec'd. A missing helper is not a degradation but a refusal: it constructs an echo 'sandbox error: octos-sandbox helper not found' >&2; exit 1 command (crates/octos-agent/src/sandbox/landlock.rs:31-39).

macOS sandbox-exec: the thickest backend (1,767 lines), generating an SBPL (sandbox profile language) profile. Injection defense sits at crates/octos-agent/src/sandbox/macos.rs:205-212: a cwd containing control characters or SBPL metacharacters ((, ), \, ") is refused outright, because the path has been verified quote-free and subsequent concatenation needs no escaping. macOS is also the only backend that can express the #1976 write fence precisely: each glob becomes an (allow file-write* (regex ...)) rule (per the comment in build_backend, crates/octos-agent/src/sandbox/mod.rs:1081-1085).

Docker: the cross-platform fallback. It mounts the workspace per MountMode (ReadWrite → -v cwd:/workspace, ReadOnly → add :ro, None → no mount) and supports CPU/memory limits. is_blocked_bind_source (crates/octos-agent/src/sandbox/docker.rs:20-30) refuses docker.sock, /etc, /proc, /sys, and /dev as bind sources; a cwd that hits a dangerous source refuses the entire command.

AppContainer (Windows): crates/octos-agent/src/sandbox/windows.rs:46 delegates to octos-sandbox.exe to create or reuse an AppContainer profile. Each octos profile has its own AppContainer SID, with deny-by-default filesystem access and configurable network isolation.

7.1.5 Environment variable scrubbing

All backends share BLOCKED_ENV_VARS (re-exported from octos-core, crates/octos-agent/src/sandbox/mod.rs:33), an 18-entry list grouped by injection surface: Linux dynamic-library injection (LD_PRELOAD and 2 others), macOS dylib injection (5 DYLD_* entries), runtime code injection (NODE_OPTIONS, PYTHONSTARTUP, and 5 others), and shell startup injection (BASH_ENV, ENV, ZDOTDIR). Where the list is enforced differs by backend: bwrap, Landlock, macOS (crates/octos-agent/src/sandbox/macos.rs:478), and Windows (crates/octos-agent/src/sandbox/windows.rs:90, :139) each call env_remove per entry; the Docker backend scrubs nothing, since container isolation itself carries the environment isolation.

7.1.6 cargo grants: from best-effort writes to lock-only

ffcde205 (4 files, +140/−82) addresses a real tension for coding agents: the tighter the sandbox clamps writes, the more often cargo build dies before compiling. The fixed policy is lock-only by default: the writable set is just ~/.cargo/.package-cache (what the lock file needs), while registry index/cache/src, git checkouts, and the rustup install are all read-only; only configuring allow_network adds the writes and network that downloads require. The companion allow_toolchains field (crates/octos-agent/src/sandbox/mod.rs:149, default true) grants the few write paths a toolchain needs to run, but explicitly withholds ~/.cargo/bin (a writable shim on PATH is a persistence backdoor) and ~/.rustup/toolchains (writable compiler binaries). Deny-wins applies here too: a read-only workspace or a #1976 write fence suppresses these grants wholesale.

Engineering decision: why "best-effort sandboxing" was abandoned

Under the old semantics, an operator wrote sandbox.mode = "bwrap", the host had no bwrap, and the command ran unsandboxed anyway. From a security standpoint that is fail-open: the configuration expressed an isolation intent, and the system overrode it with "it runs, so it's fine". The problem is that the override was invisible; the user believed a sandbox was active. eb7c7221 chose differently: an explicit mode that cannot be honored refuses execution and surfaces the conflict to the operator (with per-OS remediation and an octos doctor entry); Auto keeps its degradation ("best available" is its contract) but warns once per process, and the sandbox.fail_closed switch can turn the degradation into a refusal too. The cost is availability: users on a misconfigured host see every command refused. The team accepted that cost because the refusal text is itself actionable, while silent non-sandboxing is unfixable.

7.2 Command and dispatch policy: a gate on every path

The sandbox governs what environment a command runs in; the policy layer governs whether a command or tool runs at all.

crates/octos-agent/src/policy.rs (746 lines): command approval policy. Decision (crates/octos-agent/src/policy.rs:16) has three values, Allow / Deny / Ask; ApprovalPolicy (:28) decides whether Ask in unattended mode pops an approval or fails outright (Never); the Workspace / Host two-valued FilesystemScope (:46) reappears in the grant model of 7.4. ShellTool's SafePolicy (dangerous-command refusal, whitespace normalization, word-boundary detection) was covered in Chapter 6 and is not repeated here; what this chapter adds is that it explicitly calls itself "not a security boundary". The real boundaries are this section's sandbox and the next section's redaction.

crates/octos-agent/src/dispatch_policy.rs (566 lines): the pre-dispatch policy gate for MCP agents. The module docs (crates/octos-agent/src/dispatch_policy.rs:1-10) record its origin: before #714, the agent_mcp branch of SpawnTool dispatched directly, bypassing policy entirely, even when octos serve had installed a gate on the swarm side. Lifting the gate into this crate lets both call sites (the SpawnTool::agent_mcp branch and the octos_swarm::Swarm dispatcher) run the same shape of checks: tool policy, approval, sandbox-required, and env allow/deny lists. Every failure produces a labeled GateDenial (crates/octos-agent/src/dispatch_policy.rs:253, the last_dispatch_outcome field), where approval_unavailable (approval needed but no requester attached) and sandbox_required (policy requires a sandbox backend but the backend does not report one) both fail closed rather than falling through to dispatch.

crates/octos-agent/src/permissions.rs (167 lines): supervisory safety tiers for robotics tools. SafetyTier (crates/octos-agent/src/permissions.rs:19) orders four levels, low to high: Observe < SafeMotion < FullActuation < EmergencyOverride, enforced through ToolPolicy's group:robot:<tier> grouping rather than standalone trait methods. Physical-world risk tiers share the same deny-wins machinery as this chapter's digital sandbox, and one paragraph here suffices.

Why the gate has this shape comes down to three design criteria, all written in crates/octos-agent/src/dispatch_policy.rs's own docs. Criterion one, the gate must be shared, not copied: the module docs (:1-10) record the pre-#714 bypass, where the SpawnTool agent_mcp branch dispatched directly and a gate installed by octos serve on the swarm side could not stop it. Moving the gate into the octos-agent crate makes both call sites run the same shaped checks over the same shared types (ToolPolicy, ToolApprovalRequester, McpAgentBackend); when a third dispatch point appears, "write its own checks" is not an option on the table. Criterion two, no-op by default, explicit assembly in production: each gate of DispatchPolicy (:121) is independently optional; with all defaults, is_noop() (:175) is true and dispatch behavior is byte-for-byte identical to the old version, which avoids regressing existing callers. The production constructor from_agent_gates (:223) deliberately inherits only the two gates named by the #701 audit (workspace-level tool-name policy and the BLOCKED_ENV_VARS injection-environment deny list); the approval bridge and sandbox-required are intentionally not mirrored, for reasons in the constructor rustdoc (from :197): the native approval bridge TOOL_APPROVAL_CTX is a per-turn task-local, and at server startup there is no cloneable global requester; and no MCP backend yet reports a sandbox, so require_sandboxed exists only for forward compatibility (:150-152) — setting it true today would fail closed on every dispatch. Criterion three, fixed gate order and observable failure: the docs of enforce_dispatch_gates (from :285) fix the check order as sandbox-required (pure configuration, cheapest) → tool policy → env deny list → env allow list → approval (the only one that can block waiting on a human, so last); the deny list before the allow list prevents a permissive allow list from passing a known-bad key (:144-146). Every gate failure produces a stably labeled GateDenial (:253, the five-label enum in the field docs), and callers fold it into their own outcome shape; the crate's outward API surface is therefore gate semantics, not yet another failure type.

7.3 Injection detection and output redaction

7.3.1 prompt_guard: the detection layer for plaintext injection

crates/octos-agent/src/prompt_guard.rs (772 lines) scans tool output and user messages for injection patterns. ThreatKind (crates/octos-agent/src/prompt_guard.rs:29) has five classes: SystemOverride (overriding the system prompt), RoleConfusion ("System: you are now..." style role confusion), ToolCallInjection (injecting tool-call JSON/XML), SecretExtraction (fishing for the system prompt or secrets), and InstructionInjection ("you must / always respond with" generic instruction injection). The entry point pub fn scan(text) sits at :195.

The module's own docs (crates/octos-agent/src/prompt_guard.rs:5-19) open by positioning it: "Not a security boundary." It regex-matches naive plaintext injection and can be bypassed by base64 encoding, URL encoding, HTML entities, Unicode homoglyphs, zero-width characters, and RTL override characters, all recorded in the test suite as known limitations. The real mitigations are architectural: sandbox isolation bounds tool-layer damage whatever the prompt state, tool policy restricts the callable tool set, and human-in-the-loop (the before_tool_call hook exiting 1) intercepts high-impact actions for human approval. prompt_guard provides the extra layer of logging and best-effort redaction, not a replacement for those three.

7.3.2 sanitize: scrubbing tool output before it reaches context

sanitize_tool_output (:90) in crates/octos-agent/src/sanitize.rs (245 lines) strips three classes of content before tool results are fed back to the LLM. Noise: base64 data URIs (data:...;base64,<64+ chars>, :13) and hex runs of 64+ characters (SHA-256, raw keys, :16), to save context. Credentials, seven regexes: OpenAI (sk- prefix, :24), Anthropic (sk-ant-), AWS (AKIA + 16 uppercase), GitHub (ghp_/gho_/ghs_/ghr_/github_pat_), GitLab (glpat-), Bearer tokens, and a generic assignment pattern (password|secret|api_key|... = "..."). redact_credential (:55) keeps the first 4 characters visible and appends a [credential-redacted] marker, recognizable without leaking. The comment on scrub_credentials (:62) stresses order: Anthropic is processed before OpenAI so sk-ant-... is not partially matched by the sk- rule.

7.3.3 SSRF: the entry check for network tools

crates/octos-agent/src/tools/ssrf.rs (620 lines) is shared by the web_fetch and browser tools. The flow of check_ssrf_with_addrs (:24): parse the URL → is_private_host (:228) blocks localhost and literal private IPs → domains go through DNS resolution, and the answer set passes validate_answer_set (:69) for DNS pinning (anti-rebinding: the addresses resolved at validation are bound to the actual fetch, so TOCTOU disappears). DNS failure is handled fail-closed as a block, with the comment stating why: an attacker can make DNS fail at validation time and succeed at fetch time.

The range list of is_private_ip (:258) goes beyond the std predicates: for IPv4, on top of is_private/is_link_local/is_loopback/is_unspecified, is_special_purpose_v4 (:244) explicitly matches segments that only landed in later std versions: CGNAT 100.64.0.0/10 (carrier-grade NAT), 192.0.0.0/24 (IETF protocol assignments), 198.18.0.0/15 (benchmarking), 224.0.0.0/4 (multicast), and 240.0.0.0/4 (reserved). IPv6 covers loopback, ::, multicast, ULA fc00::/7, link-local fe80::/10, and the deprecated site-local fec0::/10, plus two mapping rules: IPv4-mapped ::ffff:x.x.x.x recurses into the IPv4 check, and IPv4-compatible ::x.x.x.x is handled the same way. Missing the mapping rules is the classic bypass; the tests have dedicated cases (:580, :590).

The division of labor between prompt_guard and sanitize deserves its own statement: both act "before output enters context", but on different objects. crates/octos-agent/src/prompt_guard.rs governs instructions, whether someone in the text is trying to steer the model's next action; crates/octos-agent/src/sanitize.rs governs matter, whether the text carries bytes that should not be fed back (credentials, base64 data URIs, long hex). The two meet inside sanitize_tool_output (crates/octos-agent/src/sanitize.rs:90-94): the pipeline replaces data URIs, long hex, and the seven credential classes, and the final step calls prompt_guard::sanitize_injection, so injection defanging is the tail of the redaction pipeline, not a separate channel. On the execution side the call site is crates/octos-agent/src/agent/execution.rs:2414: every tool result passes through this one point after truncation and before the model sees it, and a single funnel means bypassing redaction requires bypassing the entire execution layer rather than picking an undefended tool. Detection granularity is layered too: scan (crates/octos-agent/src/prompt_guard.rs:195) produces a list of Threats with three Severity levels (:56, Low/Medium/High); Low only logs, and redaction starts at Medium (inside sanitize_injection, filtered by severity >= Medium, :262), with replacements applied in reverse span order to preserve byte offsets (from :270). The threshold acknowledges the false-positive cost of regex detection: act only on medium-to-high confidence, and leave the "cannot detect" cases explicitly to the architectural controls (sandbox, tool policy, human-in-the-loop), consistent with the module's opening "Not a security boundary". Both modules are an extra layer in the depth, not the boundary itself.

7.4 WorkerGrant: capabilities as a type

The first three defensive layers all sit on the "restrict" side. The fleet architecture (assembly covered in Chapter 16) also needs the reverse capability: when a master dispatches a task to a worker, how do you state precisely "this worker may use the network and may write only these three paths"? The answer is WorkerGrant in crates/octos-fleet/src/grant.rs (714 lines), a validated type rather than scattered config keys.

7.4.1 Three axes of granularity

NetworkGrant (crates/octos-fleet/src/grant.rs:76) has three values: None (default, zero network), Hosts(Vec<String>) (a per-host allowlist), and Full (raw egress fully open). The key semantics sit in the method docs: allows_raw_egress is true only for Full; Hosts deliberately keeps raw egress off, and its permission is realized entirely through the granted web tools honoring the host allowlist, so shell can never curl beyond the allowlist. The docs also admit the v1 limitation: raw network is all-or-nothing, per-host filtering of raw traffic needs a kernel-level egress proxy, and Hosts covers only the web tools' HTTP(S). This is a recorded open problem.

FsGrant (crates/octos-fleet/src/grant.rs:127) is deliberately coarse: Workspace (default, read-write only in the worker's own attempt directory) or Host (full-disk read-write, requiring an explicit operator grant). v1 has no per-path filesystem allowlist, so an honest grant is two-valued.

WorkerGrant (crates/octos-fleet/src/grant.rs:151) assembles these axes into five fields, a serializable, validatable whole:

#![allow(unused)]
fn main() {
pub struct WorkerGrant {
    #[serde(default)]
    pub network: NetworkGrant,        // :154, default None
    #[serde(default = "base_tools_vec")]
    pub tools: Vec<String>,           // :157, default BASE_TOOLS, seven items
    #[serde(default)]
    pub fs: FsGrant,                  // :160, default Workspace
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_paths: Option<Vec<String>>, // :179, #1976 write fence
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub create_only: bool,            // :189, create but do not overwrite
}
}

The #[serde(default)] on every field carries a design: old tasks persisted before grants existed (or a master that specified nothing) load as WorkerGrant::minimal(), so least privilege is the default and old records need no schema migration. skip_serializing_if makes a fence-less grant serialize byte-identically to the pre-#1976 shape, so old readers see no new keys in new records.

The five fields are not assembled at random; each answers a class of authorization question that must be answered explicitly, and missing one leaves a default-allow hole. Without network, egress for web tools and for shell cannot be distinguished, "no network" has nowhere to be expressed, and WEB_TOOLS could only be granted or disabled wholesale. Without tools, the registry shape is all-or-nothing, and the audit key sorted_tools() ("what the operator granted, not one more") has no ground to stand on. Without fs, the workspace/host filesystem boundary falls back to an implicit cwd convention, and an explicit operator trust decision like FsGrant::Host has nowhere to be written. Without write_paths, before #1976 "this worker writes only these files" could only be expressed through the workspace_write binary knob, all-writable or all-readonly. Without create_only, the anti-tampering semantics "create yes, overwrite no" (a replay-safety concern) is inexpressible in the type. The reverse bound holds too: there are only these five fields. v1 deliberately skips per-host raw network filtering (needs a kernel-level egress proxy) and arbitrary filesystem ACLs (the tool layer has no matching mechanism; the grant honestly reflects the range it can enforce). The field set is the exact union of authorization questions both enforcement layers can honor: one more field would be lying, one fewer would be a hole.

7.4.2 The #1976 write fence: three-level semantics

write_paths is the per-path write fence introduced by issue 1976, with three levels of meaning:

  • None (default): no fence; the binary fs alone governs writes, byte-identical to a pre-#1976 worker
  • Some(vec![]): a uniform read-only fence; nothing inside the workspace is writable
  • Some(list): the listed paths are writable, the rest of the workspace read-only

The v1 pattern syntax is deliberately narrow: workspace-relative paths, / separators, * (any characters) and ? (single character) wildcards within a segment, and no **, [...], or {...}. The reason is in the field docs: this syntax is exactly the intersection the tool-layer matcher (globset, literal_separator) and the sandbox translation (SBPL regex) can both express identically, so the two layers can never disagree about "what was granted". validate_write_path_pattern (crates/octos-fleet/src/grant.rs:307) rejects, item by item, absolute paths, .., control bytes, SBPL metacharacters, : (Docker mount separator / Windows drive letter), and both extended wildcard syntaxes.

create_only: true means paths in the allowlist may only be created, never overwritten/edited/deleted (the file tool layer's O_CREAT|O_EXCL semantics; edit_file is refused outright whether or not it is in the list). The sandbox layer can only enforce path fences; no OS backend can distinguish creation from overwrite, so the no-overwrite half of create_only is enforced by the tool layer, a documented degradation.

How each backend expresses the fence on the shell side differs, and deny-wins guarantees no backend widens it (three functions at crates/octos-agent/src/sandbox/mod.rs:955-1000): macOS expresses it precisely (per-glob SBPL regex); bwrap/Landlock/AppContainer cannot express per-glob shell writes, so the workspace drops to read-only for shell, and the granted paths stay writable only through the fenced file tools (fence_degraded_workspace_write, :955, warns once at construction); Docker likewise mounts :ro (fence_degraded_docker, :970); when the resolution result is no sandbox, a warning states the shell fence is entirely unenforced (warn_fence_unenforced).

flowchart LR
    subgraph G["WorkerGrant (crates/octos-fleet/src/grant.rs:151)"]
        N["network: NetworkGrant<br/>None / Hosts / Full"]
        T["tools: Vec&lt;String&gt;<br/>default BASE_TOOLS, seven items"]
        F["fs: FsGrant<br/>Workspace / Host"]
        W["write_paths: Option&lt;Vec&lt;String&gt;&gt;<br/>#1976 write fence"]
        CO["create_only: bool<br/>create but do not overwrite"]
    end
    V["validate() (crates/octos-fleet/src/grant.rs:247)"] --> G
    G --> SB["sandbox projection (crates/octos-agent/src/sandbox/mod.rs:955-1000)<br/>macOS precise / others degrade read-only"]
    G --> FT["tool-layer enforcement<br/>globset fence + O_CREAT|O_EXCL"]

Figure 7-2: WorkerGrant structure and its two enforcement layers.

7.4.3 validate: catching inconsistencies at parse time

WorkerGrant::validate (crates/octos-fleet/src/grant.rs:247) rejects five classes of inconsistency, each mapping to one variant of GrantError (crates/octos-fleet/src/grant.rs:359):

  • UnknownTool: a granted tool not in the GRANTABLE_TOOLS catalog (an operator cannot grant a tool the host build cannot produce)
  • WebToolWithoutNetwork: granting web_fetch/web_search under NetworkGrant::None (network tools without network)
  • EmptyHostAllowlist: Hosts(vec![]), an empty allowlist. The comment names the fail-open trap: an empty list must never read as "no restriction"; an operator who listed no hosts means None
  • The #1976 four: WritePathsWithHostFs (a fence combined with fs: Host is inconsistent; Host lets shell reach everything the fence forbids, and deny-wins refuses outright), CreateOnlyWithoutWritePaths (no list to apply it to), EmptyWritePathsWithCreateOnly (an empty list plus create_only grants nothing to create), and InvalidWritePath { pattern, reason } (patterns outside the syntax)

validate is called at two points: when the master's goal_plan parses, and defensively when the registry is built. The relation to Chapter 6's crates/octos-agent/src/tools/write_grant.rs: Chapter 6 covered per-argument write authorization for a single tool, while this chapter's WorkerGrant is the worker-level grant model; how the fleet assembles this grant into a closed tool registry and sandbox configuration is Chapter 16's subject.

Engineering decision: why the grant is a type, not a config convention

If "what a worker may do" were only a few independent config keys (a network boolean, a tool list, a path list), inconsistent combinations would surface at runtime, or never (an empty allowlist read as unrestricted is exactly that case). WorkerGrant pulls the five axes into one struct, validate rejects cross-field inconsistencies at parse time with typed errors, and each of the seven GrantError variants converts directly into an operator-facing message. minimal() as the serde default makes least privilege the baseline that needs no declaration, and old records land there automatically. The cost: adding a capability means extending the GRANTABLE_TOOLS catalog, the validate rules, and the error variants in lockstep, three places that must stay synchronized. What it buys: "what was granted" stays consistent across the serialized shape, the registry audit key (sorted_tools), and the error messages.

7.5 Chapter recap

This chapter walked octos's defense in depth across four layers. The process sandbox layer: crates/octos-agent/src/sandbox/, six files and 5,347 lines, seven impl Sandbox for blocks (five backends plus the NoSandbox/RefusingSandbox sentinels); the pure function decide_sandbox (crates/octos-agent/src/sandbox/mod.rs:809) enforces the fail-closed contract: an explicit mode that cannot be honored refuses, and Auto's degradation warns once and can be escalated to refusal with fail_closed. The policy layer: command approval in crates/octos-agent/src/policy.rs, the MCP dispatch bypass closed by crates/octos-agent/src/dispatch_policy.rs (#714), and the robotics safety tiers of crates/octos-agent/src/permissions.rs. The injection and redaction layer: crates/octos-agent/src/prompt_guard.rs with its self-declared non-boundary plaintext detection, the seven credential regexes of crates/octos-agent/src/sanitize.rs, and the DNS-pinned SSRF check. The capability layer: WorkerGrant's five fields (network/tools/fs/write_paths/create_only) with validate's five classes of inconsistency rejection, and the #1976 write fence enforced through both the sandbox projection and the tool layer.

One thread runs through the whole chapter: deny-wins and fail-closed reappear at every layer. Tool policy deny beats allow (Chapter 6); a sandbox mode that cannot be honored refuses rather than degrades; an empty allowlist is an error rather than "unrestricted"; a fence combined with Host fs refuses rather than taking the wider. The same principle taking the same shape at four levels of abstraction says more about this system's design consistency than any single point's strength.


Further reading

  • Landlock documentation and the seccomp BPF manual (man 2 seccomp): the two kernel mechanisms applied by the helper that crates/octos-agent/src/sandbox/landlock.rs delegates to
  • Apple Sandbox Guide (SBPL reference): the language of the profiles generated by crates/octos-agent/src/sandbox/macos.rs
  • bubblewrap project documentation: the mount namespace and --die-with-parent semantics used by crates/octos-agent/src/sandbox/bwrap.rs
  • OWASP SSRF Prevention Cheat Sheet: the comparison reference for the block ranges of crates/octos-agent/src/tools/ssrf.rs
  • issue #1976, PR #2196 (eb7c7221), and the commit message of ffcde205: the original discussions behind this chapter's three threads

Exercises

  1. Why does decide_sandbox take HostOs and the backend probe as parameters instead of reading the environment inside the function? If the probe were a real global, which quality attribute breaks first?
  2. RefusingSandbox's wrap_command still constructs a real shell command (echo the refusal text and exit 1) instead of returning an error. What does keeping the Sandbox trait signature infallible buy? And which remaining problem of that design does the refusal() short circuit in exec-shaped tools solve?
  3. NetworkGrant::Hosts deliberately denies shell raw egress; permission is realized entirely through the web tools' allowlist. If v2 wanted "git may only clone hosts in the allowlist", what infrastructure would it need?
  4. validate treats "an empty Hosts allowlist" as an error rather than the equivalent of None. Argue for or against this choice from the operator's mental model.
  5. Under the #1976 fence, the bwrap backend drops the workspace to read-only for shell (granted paths writable only through file tools). What happens to a worker that can only use shell tools under the fence? Is this degradation a design flaw or a reasonable trade?

Version note

Version note: This chapter is based on octos main @ 9c157101 (committed 2026-09-02). Main-line changes: eb7c7221 (2026-08-31, PR #2196, 14 files) introduced fail-closed for explicit modes with Auto degradation warnings and refactored the sandbox decision into the pure function decide_sandbox; ffcde205 (2026-08-26, 4 files) tightened the cargo grant default to lock-only, with downloads gated behind allow_network; issue #1976 introduced WorkerGrant's per-path write fence and create_only. Line numbers and file line counts were measured against this baseline; the fact source is the assets/ch07-facts.md facts table.

Chapter 8: Context Management: Making an Agent Work Inside a Bounded Window

Positioning: This chapter shows how octos works inside a bounded LLM context window: context compaction, recall rematerialization, the tiered compaction surface, fidelity grades, prompt layer assembly, steering, and the prompt guard that fends off tampered tool output. Prerequisite: Chapter 5 (where CompactAndRetry fires). It is written for developers who need to understand or tune an agent's context strategy.

The context window is a scarce resource. A 200K-token window can be exhausted after a dozen tool iterations: every call's arguments and results accumulate, and one read_file output can occupy thousands of tokens. As the window fills there are two exits: stop the task, or compact the history. octos compacts, and the answer on the current main branch has outgrown a single summarizer function into a system: reduce in tiers first (local placeholders, server-side cleanup, full summary), then fold old messages, and let compacted outputs be fetched back by id through the recall tool. This chapter follows that main line and covers the machinery that supports it: prompt layer assembly, steering injection, and the defanging of tool output that re-enters the prompt.


8.1 Context Compaction: the 80% Threshold plus recall

8.1.1 The trigger condition and its safety margin

The legacy trigger path is trim_to_context_window() (crates/octos-agent/src/agent/compaction.rs:11-60). The budget formula (crates/octos-agent/src/agent/compaction.rs:25):

#![allow(unused)]
fn main() {
let window = self.llm.context_window();
let budget = (window as f64 * 0.8 / crate::compaction::SAFETY_MARGIN) as u32;
}

SAFETY_MARGIN = 1.2 (crates/octos-agent/src/compaction.rs:45). The effective budget is window * 0.8 / 1.2 ≈ window * 67%: 20% reserved for the next round of conversation, plus a buffer for token-estimation error. On a 128K-window model the trigger sits around 85K tokens. If the total is below budget, the function returns without touching the history.

8.1.2 The retention boundary: the last six messages and tool-group integrity

find_recent_boundary() (crates/octos-agent/src/compaction.rs:68-89) scans backward from the last message to decide which messages survive verbatim:

#![allow(unused)]
fn main() {
for i in (1..messages.len()).rev() {
    let msg_tokens = estimate_message_tokens(&messages[i]);
    count += 1;
    if count >= MIN_RECENT_MESSAGES
        && system_tokens + recent_tokens + msg_tokens > budget / 2
    {
        break;
    }
    recent_tokens += msg_tokens;
    split = i;
}
while split > 1 && messages[split].role == MessageRole::Tool {
    split -= 1;
}
}

MIN_RECENT_MESSAGES = 6 (crates/octos-agent/src/compaction.rs:48). The six most recent messages are kept unconditionally, yet they may not exceed half the budget, leaving room for the summary of older messages. The trailing while loop backs the split point off any Tool message: once an Assistant/Tool pair is split apart, the orphaned Tool message fails provider validation or confuses the model.

8.1.3 Extractive summarization: stripping arguments, capturing first lines

Old messages go to compact_messages() (crates/octos-agent/src/compaction.rs:99-153), where each one passes through summarize_message() (crates/octos-agent/src/compaction.rs:155-201) and collapses into a single line. The highest compression ratio comes from tool-argument stripping: a write_file call's arguments can carry an entire file, thousands of tokens; after compaction only - Called write_file remains, roughly five tokens, a ratio near 200:1. The design has a security side effect: tool arguments are untrusted input, and stripping them means no malicious payload survives verbatim inside the summary.

Per-role rules:

Message typeSummary shape
User> User: {first line}, plus [media omitted] when media are attached
Assistant (with tool calls)- Called {tool name} list
Assistant (plain text)> Assistant: {first line}
Tool result-> {tool name}: {ok/error} - {first 100 chars of output}
System> Context: {first line}

The ok/error test for tool results is plain: content starting with Error: counts as a failure (crates/octos-agent/src/compaction.rs:180-188). find_tool_name() (crates/octos-agent/src/compaction.rs:219-234) looks the tool name up from context by tool_call_id and degrades to unknown_tool when the lookup fails. First-line capture is an information-density bet: an LLM reply usually opens with its conclusion, so the first line carries the highest semantic density. first_line() (crates/octos-agent/src/compaction.rs:203-216) cuts at UTF-8 character boundaries and never slices a Chinese character in half. The summary targets 40% of the budget (BASE_CHUNK_RATIO, crates/octos-agent/src/compaction.rs:51); past that, per-message expansion stops and the remainder is recorded as ... (N earlier messages omitted).

A detail easy to miss: compact_messages first deducts the newest plan snapshot from the budget (#2132), so the retained block cannot push the summary past the ceiling (crates/octos-agent/src/compaction.rs:104-114). The comment spells it out: the deduction lives inside the producer, and every compaction path, AppUI, session actor, legacy agent channel, summarizer tiers, inherits it without point-to-point wiring.

If the recent messages alone already exceed the budget, the code falls back to fallback_truncate() tail truncation (crates/octos-agent/src/agent/compaction.rs:319-358): keep from the tail whatever fits, at least two non-system messages, again without splitting tool groups. The semantics are "summarize when possible, truncate only when it will not fit": summary first, but not unconditionally.

8.1.4 recall: rematerialization after compaction

The machinery above has an inherent cost: compacted output is gone. #2131 observed the pathology of one source file being read 66 times over, each read entering the window, being truncated, being compacted, and being read again. e312e4c1 (merged 2026-08-27) added the recovery side: the recall tool.

An evicted tool result leaves behind a typed ToolResultPlaceholder (crates/octos-agent/src/compaction.rs:346-361) carrying the tool_call_id. RecallTool (crates/octos-agent/src/tools/recall.rs:27-35) uses that id to fetch the original bytes from the ledger, with no re-execution of the tool. The abstraction is the ToolOutputLedger trait (crates/octos-agent/src/tools/recall.rs:19-24): octos-agent depends only on the interface, the session side injects the implementation, and no cross-crate dependency is created. Large outputs return page by page (render_page(), crates/octos-agent/src/tools/recall.rs:51-99); the page footer states that the next page comes from recall(tool_call_id=..., page=N), so no middle section is dropped silently.

The key ledger-side implementation is octos-cli's ContextManager: recall_index (crates/octos-cli/src/api/context_manager.rs:391-398) records tool_call_id → (artifact_ref, model_visible_content) at write time and is not cleaned by compaction. That is exactly the bug 825d6a52 fixed: early recall parsed from items, while compact_context prunes items to the most recent ~16 entries, so the outputs that had actually been evicted, the very reason recall exists, could not be fetched back, and the artifact bytes on disk were orphaned. The post-fix test recall_survives_compaction_that_prunes_the_transcript (crates/octos-cli/src/api/context_manager.rs:2408-2440) builds a 20KB output (above the inline threshold, so it spills to the ledger), compacts away its transcript envelope, then asserts the full bytes are retrievable. The read entry point is tool_output_by_call_id() (crates/octos-cli/src/api/context_manager.rs:1192-1206): outputs spilled to the content-addressed ledger return the complete original bytes; unspilled outputs return the model-visible content as recorded, truncation markers preserved so the model is not misled; an unknown id returns None.

Choosing tool_call_id over the content sha256 as the recall handle was a deliberate architecture call (the e312e4c1 commit message): sha256 exists only in octos-cli's ledger envelope, and adding it to octos_core::Message would touch about 560 construction sites; tool_call_id already appears on every placeholder, at zero schema change.

8.1.5 The boundary between recall and the memory subsystem

octos has two similarly named tools: recall (this chapter) and recall_memory (Chapter 4). They address different time scales and share only the pager implementation. recall works on the current session's context ledger: tool output spilled to content-addressed storage is fetched back by id, and the scope ends with the session. recall_memory works on the cross-session memory store: it retrieves historical observations and facts by vector search, answering "what did earlier sessions learn".

The junction between the two is the persistence of compaction summaries. Each time the loop side completes a compaction, it archives the summary as a searchable episode (save_conversation_episode, #1587 on the write side; see the two call sites in crates/octos-agent/src/agent/loop_runner.rs:1215-1245: entry compaction and in-turn compaction each save one). The judgment is written in a comment: a conversation large enough to need compaction is worth being recalled by future sessions. Session-scoped recall fetches bytes; cross-session recall_memory fetches semantic summaries; together the two layers cover the full answer to "where does information go after compaction": bytes in the ledger, semantics in episodes, structured task state in SessionSummary.

recall rewrites "compaction is irreversible" as "compaction is lossy but recoverable on demand"; that is the second leg of the 8.1 pair.

8.1.6 Budget-aware reads: prevention before recovery

The other half of #2131 is prevention: when read_file reads a file larger than the tool-output budget without an explicit range, it returns a range hint instead of a body doomed to be truncated and then evicted (crates/octos-agent/src/tools/read_file.rs:484-506): how large the file is, what the budget is, and the advice to pass start_line/end_line or grep first. Reads with an explicit range are unaffected. This cuts the accept-then-evict loop at the source.

flowchart TD
    Start["Every iteration"] --> Count["Estimate total tokens"]
    Count --> Check{"total > window x 0.67?"}
    Check -->|no| Skip["No compaction"]
    Check -->|yes| T1["Tier 1 local cleanup<br/>stale/oversized tool results"]
    T1 --> Need{"Still over threshold?"}
    Need -->|no| Keep["Placeholder substitution, continue"]
    Need -->|yes| Sum["Summarize and fold old messages"]
    Sum --> Later["When detail is needed later"]
    Later --> Recall["recall(tool_call_id)<br/>fetch original bytes from ledger"]
    Keep --> Later

Figure 8-1: the compaction-and-recall loop. Compaction is no longer a one-way street.


8.2 The Tiered Compaction Surface: three tiers, one span each

crates/octos-agent/src/compaction_tiered.rs (1,271 lines, M8.5 #540) splits the compaction surface into three tiers; the module header states the motive: cheap tier-1 digests most of the pressure, and the expensive full summarizer should fire as rarely as possible (crates/octos-agent/src/compaction_tiered.rs:1-34).

TierMechanismTriggerFidelity
Tier 1 MicroCompactionlocally replaces stale/oversized tool results with ToolResultPlaceholderevery iteration (both conversation and task mode)tool_call_id fully preserved, recall can restore
Tier 2 API MicroCompactionattaches a context_management payload to Anthropic requests (clear_tool_uses_20250919)when building ChatConfig, Anthropic-family providers onlyserver-side cleanup, client never rewrites history
Tier 3 FullCompactorfull summary plus contract artifact preservation checksabove the policy thresholdtyped SessionSummary or an extractive summary

Tier 1's policy lives in MicroCompactionPolicy (crates/octos-agent/src/compaction_tiered.rs:72-106): a result older than 5 user turns (DEFAULT_TIER1_MAX_AGE_TURNS) or larger than 8KB (DEFAULT_TIER1_MAX_SIZE_BYTES_PER_RESULT) is replaced with a placeholder; two #2131 additions ride along: the working set of the last 5 touched files is pinned (pin_recent_files, crates/octos-agent/src/compaction_tiered.rs:78-88), so read/write results of the file under active use are not evicted, otherwise the model must re-read it next turn, the exact cause of those 66 re-reads; duplicate reads of the same file and range keep only the newest entry, the rest become placeholders on the spot (dedup_duplicate_reads, crates/octos-agent/src/compaction_tiered.rs:89-104), clearing the trail of same-file stubs a re-read loop leaves behind. Replacement reasons are tagged tier1_stale/tier1_oversized/tier1_superseded (crates/octos-agent/src/compaction_tiered.rs:237-241). Callers of prune() must pass protected_tool_call_ids (crates/octos-agent/src/compaction_tiered.rs:139-142): results still referenced by a retry bucket or a contract artifact are untouched; M6's contract guarantee outranks compaction.

Tier 1 also respects the provider prefix cache (KV cache): stale results sit deep in history, and rewriting one invalidates the entire cached prefix, so that class of cleanup is concentrated in the first call of each turn; oversized results land near the prefix tail where rewriting is cheap, so that cleanup can run every iteration. The split shows up in Tier1Pass::Full / OversizedOnly (crates/octos-agent/src/compaction_tiered.rs:47-57) and the loop-side tier1_pass() (crates/octos-agent/src/agent/loop_runner.rs:3846-3852): iteration 1 runs Full, later iterations only OversizedOnly. Conversation mode and task mode (background workers) both run this tier before LLM calls (crates/octos-agent/src/agent/loop_runner.rs:1227, crates/octos-agent/src/agent/loop_runner.rs:2366).

Tier 2 is request-time decoration rather than a runtime loop: ApiMicroCompactionConfig (crates/octos-agent/src/compaction_tiered.rs:428-457) defaults off (enabled: false); when enabled, into_context_management_json() (crates/octos-agent/src/compaction_tiered.rs:478-505) produces the clear_tool_uses_20250919 payload, keeping the last 10 turns by default (DEFAULT_TIER2_KEEP_LAST_N_TURNS, crates/octos-agent/src/compaction_tiered.rs:419-421); the loop side injects it while building the request (with_tier2_context_management, crates/octos-agent/src/agent/loop_runner.rs:203-213); non-Anthropic providers ignore it silently and no extra field is sent. octos does not re-implement Anthropic's server-side cleanup; it only ships the opt-in switch.

Tier 3 is a trait wrapper over the existing CompactionRunner (FullCompactor, crates/octos-agent/src/compaction_tiered.rs:524-560); the threshold check reuses needs_preflight() (crates/octos-agent/src/compaction.rs:572-580) and the execution reuses run() (crates/octos-agent/src/compaction.rs:584-706). Inside run(), placeholder cleanup runs first (prune_tool_results(), crates/octos-agent/src/compaction.rs:709-796), then the post-cleanup token count decides whether to summarize: if placeholder cleanup alone already pulled the conversation back within budget, no summary is produced, and nothing is compacted for compaction's sake (crates/octos-agent/src/compaction.rs:597-612). After summarization, enforce_preservation() checks that declared artifacts and invariants are still referenced in the message flow; a miss rolls back that round of compaction with an error (crates/octos-agent/src/agent/compaction.rs:278-318). CompactionRunner picks the summarizer per policy (with_provider, crates/octos-agent/src/compaction.rs:494-514) and resolves declared artifact names into concrete glob patterns through with_workspace_policy() (crates/octos-agent/src/compaction.rs:538-556). Each compaction emits an octos.harness.event.v1 { kind: phase } event, so operators can see the before/after token comparison at preflight and turn_end.

8.2.1 What the tiers mean: why three and not one

The three tiers are not one algorithm split into three steps; they are three operations with different cost structures. Tier 1 is pure local string replacement, no LLM call, no network round trip, done in microseconds, safe to run on every iteration without ceremony; the module header cites Claude Code's numbers: cheap tier-1 alone keeps 20-40% of turns from ever reaching the expensive summarizer (crates/octos-agent/src/compaction_tiered.rs:5-8). Tier 2 is free decoration: local history is untouched, one extra request field is sent, and Anthropic's servers do the cleanup. Tier 3 is the only tier that needs an LLM call to produce the summary, and the only one that can lose information.

The cost ordering dictates the trigger order: Tier 1 runs first every turn; if the post-cleanup load is under threshold, that is the end. Only above threshold does Tier 3 decide on the next LLM request whether to summarize. Most pressure is digested in the first tier. The failure domains are independent too: if Tier 3's LLM call fails or times out, it falls back to the extractive summary (crates/octos-agent/src/compaction.rs:683-695) and Tier 1's completed cleanup stands; if the server rejects Tier 2, the request still goes out, minus the server-side cleanup.

The tiers share one fidelity promise: tool_call_id is fully preserved in Tier 1 placeholders (crates/octos-agent/src/compaction.rs:346-361), and although Tier 3's summary body discards tool-output detail, the placeholders inside summarized messages still point at recall handles. Deeper tiers discard more, but everything discarded along the way is recoverable through recall, not lost. That property turns compaction from an irreversible operation into one that can back out tier by tier.


8.3 The Four Fidelity Grades

Post-compaction message fidelity comes in four grades:

GradeKeptDiscardedWhere it applies
Fullthe complete messagenothingthe last six messages, pinned working-set files
Truncatecontent cut to N charactersthe tailmid-importance history
Compactfirst line plus tool namesarguments, detailed outputdistant history
Summarytyped SessionSummary or extractive summaryoriginal message detailtask state across compaction rounds

The implementation has two layers: the default ExtractiveSummarizer implements the Compact grade (crates/octos-agent/src/summarizer.rs:66-85); LlmIterativeSummarizer (M6.4, crates/octos-agent/src/summarizer.rs:166-230) calls the LLM to produce a typed SessionSummary, iteratively updating the existing summary, and after 3 consecutive failures (DEFAULT_LLM_SUMMARIZER_FAILURE_THRESHOLD, crates/octos-agent/src/summarizer.rs:93-96) latches back to extractive and logs a WARN. The latch is one-way: once set, this session never retries the LLM; only a successful call resets the counter. The Summary grade is an available option today, not a future reservation; extractive remains the fallback on every failure path. The trait deliberately keeps a synchronous signature (crates/octos-agent/src/summarizer.rs:33-64): async implementations bridge the runtime themselves, so callers never await inside the message-preparation pipeline.

CompactionRunner picks the summarizer per policy (with_provider, crates/octos-agent/src/compaction.rs:500-514) and can resolve declared artifact names into concrete glob patterns via with_workspace_policy() (crates/octos-agent/src/compaction.rs:537-556). Every compaction emits an octos.harness.event.v1 { kind: phase } event, giving operators the preflight-versus-turn_end token before/after comparison.


8.4 Prompt Layer: assembling the system prompt in layers

The system prompt is not one static string; it is assembled from layers. PromptLayerBuilder's (crates/octos-agent/src/prompt_layer.rs:23-56) discover() (crates/octos-agent/src/prompt_layer.rs:58-80) stops at the first available file per category: project instructions in the order CLAUDE.md → .octos/instructions.md → .claude/instructions.md, agent descriptions in the order AGENTS.md → .octos/agents.md → agents.md. First-hit-wins means a project never loads two instruction files at once, and only layers passed in explicitly or discovered get concatenated.

The actual stacking happens in build() (crates/octos-agent/src/prompt_layer.rs:83-102): the base prompt, a ## Project Instructions section, an ## Available Agents section, and the runtime layers injected via with_extra() (skill prompts, tool notes, appended by the caller as needed). The per-file cap is 64KB (MAX_PROMPT_FILE_SIZE, crates/octos-agent/src/prompt_layer.rs:11); an oversized file is skipped whole rather than truncated, so a hostile or accidental monster file cannot eat the window. The system prompt is itself the fixed prefix of every per-turn request, and the part prompt caching can hit: this layer's size directly drives per-turn cache hit rate and cost.


8.5 Steering: injecting messages mid-conversation

Two steering primitives coexist. The type layer is SteeringMessage (crates/octos-agent/src/steering.rs:80-90): FollowUp, SystemReminder, RequestPause, Cancel, with a channel() (default buffer 16) and a non-blocking drain_pending() (crates/octos-agent/src/steering.rs:92-105). The enum interface is complete and tested, but the file-header TODO says the SteeringReceiver is not yet wired into the main loop.

The wired primitive is SteerBuffer (crates/octos-agent/src/steering.rs:36-63): the host (say octos serve's turn/steer RPC) injects plain user messages through SharedSteerBuffer, and the agent loop drains them FIFO at the top of every iteration, before the next LLM call (drain_pending_steer_input, crates/octos-agent/src/agent/loop_runner.rs:744-775, called at crates/octos-agent/src/agent/loop_runner.rs:1136). Steering is not interruption: after the model finishes its answer, a non-empty buffer makes steer_input_pending() run the loop one extra round (crates/octos-agent/src/agent/loop_runner.rs:776-781).


8.6 Prompt Guard: the defang layer for returning tool output

Prompt Guard's injection detection was covered in Chapter 7. From the context-management side, where it sits in the pipeline matters more: the verified main path is sanitize_tool_output() (crates/octos-agent/src/sanitize.rs:90-95), which first strips base64 data URIs, long hex, and credential patterns, then calls sanitize_injection() (crates/octos-agent/src/prompt_guard.rs:217) to defang, and only then writes the tool result back into the conversation history. What it protects is the step where external text re-enters the prompt, not a blanket rewrite of all input. The module header says plainly "Not a security boundary" (crates/octos-agent/src/prompt_guard.rs:1-19): base64, Unicode homoglyphs, and zero-width characters all get through; the real controls are the sandbox, tool policy, and human-in-the-loop hooks.


8.7 Mainline Evolution: contract-gated compaction and the prompt_context bridge

8.7.1 CompactAndRetry lands

Chapter 5 showed ContextOverflow classified into LoopDecision::CompactAndRetry. The loop side (crates/octos-agent/src/agent/loop_runner.rs:494-515) runs the turn compaction helper first, then requests a re-prepared prompt with PromptContextPhase::Retry, then continues the loop. Compaction is therefore a recovery path of the Agent Loop, not a token optimization alone.

8.7.2 Three state layers and SessionSummary

Post-compaction state cannot be a paragraph of natural-language summary. The current source splits state into three layers:

State layerExamplesEnters the prompt?
prompt-visible statemessages, typed SessionSummary, workspace contract summaryyes
runtime control stateretry bucket, grace eligibility, task lifecycleno
durable evidence statevalidator ledger, harness event sink, cost ledgernot written in directly, but must be replayable

SessionSummary (crates/octos-core/src/task.rs:217-263) is the typed compaction summary: goal, constraints, progress, decisions, files, and next_steps are stored structurally; on iterative update, a decision is either kept verbatim or explicitly marked [STALE], never silently dropped. It is not long-term memory; that belongs to Chapter 4's memory system.

8.7.3 prompt_context: the caller-owned bridge

crates/octos-agent/src/prompt_context.rs (64 lines) defines a phase-staged bridge interface that solves a layering problem: octos-agent deliberately stays low-level and does not depend on octos-cli's persistent ContextManager; yet the session runtime does own its own context ledger and must do final prompt preparation before each LLM call. PromptContextPhase has three phases, TurnStart / Iteration / Retry (crates/octos-agent/src/prompt_context.rs:12-30); the loop picks the phase by iteration number before each LLM call and invokes prepare_prompt (implementation in crates/octos-agent/src/agent/compaction.rs:229-276, call sites at crates/octos-agent/src/agent/loop_runner.rs:1251-1258). When the bridge is present, octos-agent's own legacy and tiered compaction paths all step aside (the early-exit checks at each entry: crates/octos-agent/src/agent/compaction.rs:15-17, crates/octos-agent/src/agent/compaction.rs:90-93, crates/octos-agent/src/agent/compaction.rs:191-196): the session runtime exclusively owns prompt compaction, and two components never mutate the same message vector at once. A bridge error is not fatal; the loop logs a WARN and keeps the existing prompt vector (crates/octos-agent/src/agent/compaction.rs:263-270).

PromptContextReport (crates/octos-agent/src/prompt_context.rs:44-53) reports whether replacement happened, message counts before and after, token estimates, and the generation number, so the caller can observe without intruding. This bridge is why the AppUI and serve/gateway paths get production-grade compaction, and also why octos chat differs: it has no ContextManager and still walks the legacy path.

The phases exist because "one interface, distinct pressure models". TurnStart (iteration 1) faces a conversation just loaded or restored from the persistent ledger, possibly far over budget, and the bridge has its best chance here for a thorough cleanup; Iteration (iteration 2 onward) faces a window that just gained a few tool results and usually needs incremental maintenance only; Retry is the dedicated phase of the CompactAndRetry recovery path, where the loop has just run the turn compaction helper and the bridge needs to know this preparation is part of overflow recovery, not normal progress. For a bridge implementer the three phases mean different compaction aggressiveness and different bookkeeping needs; one enum carries the whole context, and the caller passes nothing extra.

The design has a second motive: error isolation. The bridge returns Result rather than panicking or aborting the loop: the session runtime's ledger can be corrupted, its lock can be held, and neither failure should crash the agent loop. The trait's doc comment says "returning an error does not abort the agent loop; the agent logs and falls back to the existing prompt vector" (crates/octos-agent/src/prompt_context.rs:55-58). When the persistent layer on the production path dies, the worst case is a fallback to octos-agent's own legacy compaction, not a failed task.

8.7.4 Validator preservation and the evidence ledger

The constraint on the compaction strategy is "get shorter while keeping verifiable contracts". The outcomes of crates/octos-agent/src/validators.rs persist as schema-versioned JSONL in .octos/validator_outcomes.jsonl (crates/octos-agent/src/workspace_git.rs:708-714); workspace contract state reads that ledger, an unsatisfied required validator sets ready = false and blocks terminal success, while a failed optional validator only counts as a warning (crates/octos-agent/src/workspace_git.rs:662-690). The validator runner's safe execution path is in Chapter 9; the workflow artifact gate is in Chapter 12.

8.7.5 Cache economics: one-shot calls opt out of cache writes

Compaction and prompt caching interact. With prompt caching on by default, every request sets cache breakpoints, and cache writes are billed at 1.25x; a one-shot call like a compaction summary never replays its prefix, so paying that premium is pure waste. f3aa07f0 (#2194) added ChatConfig.cache_retention for this: CacheRetention::None makes the provider send not a single cache_control block. The compaction summary call (crates/octos-agent/src/compaction.rs:1192-1198) and the iterative summarizer's LLM call (crates/octos-agent/src/summarizer.rs:300-310) have both opted out; the agent loop's main calls keep the cache, because their prefix really is replayed. The full cost-layer analysis is in Chapter 3.

flowchart LR
    H[History window] --> T1[Tier 1<br/>placeholder replacement]
    T1 --> T2[Tier 2<br/>Anthropic payload]
    T2 --> T3[Tier 3<br/>full compactor]
    T3 --> R[recent messages kept verbatim]
    T3 --> S[typed SessionSummary<br/>cache_retention: None]
    T3 --> A[preserved artifact checks]
    A --> P[workspace policy]
    P --> V[validator JSONL ledger]
    V --> G{required passing?}
    G -->|yes| L[terminal success allowed]
    G -->|no| F[terminal success blocked]

Figure 8-2: contract-gated tiered compaction. The tiered compaction surface completes before the contract checks.


Engineering decision: why a fixed 80% threshold

Alternative one is a dynamic threshold: adapt the trigger point to task complexity. It requires predicting remaining iterations, which is barely predictable, and the complexity assessment itself consumes context. Alternative two is predictive: extrapolate from historical token growth. Tool-output size varies wildly; a wrong prediction buys either early compaction that loses information or late compaction that risks overflow.

The strength of a fixed 80% is predictability: developers know when compaction will happen, operators know where to look. The 20% reserve comfortably fits one typical iteration (system prompt plus user message plus model response plus one tool result). In an agent system full of uncertainty, determinism at the infrastructure layer is itself a value. The 1.2 safety margin stacks on top, admitting that token estimation is never exact.


8.8 Chapter Recap

  1. The 80% threshold: trigger at window × 0.8 / 1.2 ≈ 67%; the last six messages kept unconditionally at no more than half the budget, with the split point kept off tool groups.
  2. The recall pair: budget-aware reads refuse at the source the whole-file reads that are doomed to eviction; recall fetches the original bytes by tool_call_id from recall_index (which compaction never cleans), turning compaction from irreversible into recoverable on demand.
  3. The tiered compaction surface: Tier 1 local placeholders (with working-set pinning and read de-duplication), Tier 2 Anthropic server-side payload, Tier 3 full summary; Tier 1 splits cleanup timing by KV-cache friendliness.
  4. The four fidelity grades: Full / Truncate / Compact / Summary; the LLM iterative typed summary is available, latching to the extractive fallback after 3 failures.
  5. Prompt Layer and Steering: first-hit-wins discovery per category plus the 64KB cap; SteerBuffer is wired to the top of every iteration, the SteeringMessage enum remains an unwired extension point.
  6. Contract-gated compaction: CompactAndRetry landing, three-layer state separation, the phased prompt_context bridge, the validator JSONL ledger, and the cache-write opt-out for one-shot calls together keep post-compaction task constraints recoverable and verifiable.
  7. The cost lens: the compaction surface and prompt caching interact. Tier 1 concentrates stale cleanup at turn start to preserve the KV prefix cache; one-shot summary calls opt out of cache writes with cache_retention: None; the system-prompt layer hits the cached prefix. Every context-management decision is also a cost decision.

Further reading

  • Anthropic "Long context window tips": practical guidance on working with long contexts.
  • Luhn's automatic summarization method: the theoretical root of extractive first-line summaries.
  • Anthropic prompt caching documentation: cache-write pricing and the breakpoint mechanism.

Exercises

  1. recall depends on tool_call_id as its recovery handle. If the session restarts and the ledger cold-loads, are the spilled artifacts still on disk? What does recall return then?
  2. Tier 1's pin_recent_files pins the last 5 files. If a task's real working set has 15 files, what behavior does this parameter produce? What is the cost of raising it?
  3. When the prompt_context bridge is present, tiered compaction steps aside entirely. Why not let both layers work at once, each compacting a share?

Version note: This chapter's baseline is octos main @ 9c157101 (measured and re-verified 2026-09-03). Three recent changes shaped its structure: e312e4c1 (#2131, the recall tool plus budget-aware reads), 825d6a52 (#2131, recall_index surviving compaction), and f3aa07f0 (#2194, cache-write opt-out for one-shot calls). The tiered compaction surface comes from M8.5 #540. When reading further, check first crates/octos-agent/src/agent/compaction.rs (1,932 lines), crates/octos-agent/src/compaction_tiered.rs (1,271 lines), crates/octos-agent/src/agent/compaction.rs, crates/octos-agent/src/tools/recall.rs, and the recall-related sections of crates/octos-cli/src/api/context_manager.rs (4,003 lines).


Chapter 9: Extension Mechanisms: Skills, Plugins, and MCP

Positioning: This chapter presents the three extension mechanisms in the current octos source: Skills (declarative Markdown), Plugins (local executable tools / skill package extras), and MCP (standard-protocol integration). Prerequisite: Chapter 6. It is written for contributors who want to write custom extensions for octos, and for developers who want to understand the architecture of agent extensibility.

An agent earns its value by adapting to different scenarios. Legal document review needs legal prompts; a research agent needs long-running background tasks; integrating remote services needs a standard protocol. Cramming every extension into one mechanism over-engineers the simple needs and forces the complex ones into an abstraction that does not fit.

octos's current answer is not "one universal plugin" but three complementary tracks:

  • Skills: change the agent's prompts and context
  • Plugins: wrap local executables as Tools, and carry skill package extras
  • MCP: connect external tool servers through a standard protocol

9.1 The Skills Track: Declarative Markdown Extension

Skills are the lightest extension mechanism. A skill is, in essence, one SKILL.md, plus an optional manifest.json.

Start with the stark division of code volume between the two tracks: crates/octos-agent/src/skills.rs is 942 lines total, while the eight files of crates/octos-agent/src/plugins/ add up to 14,675 lines. That gap is not an accident; it is a direct expression of the responsibility boundary. crates/octos-agent/src/skills.rs answers exactly one question: what does the model see. It discovers skill directories, parses the minimal frontmatter, checks availability, and compresses the result into an XML summary injected into the system prompt; it never touches processes, protocols, or security policy. plugins/ answers a different question: what will the system execute. Manifest parsing, executable discovery and verification, the subprocess protocol, environment sanitization, approval, and concurrency control all pile up here; the execution protocol and its security constraints alone (crates/octos-agent/src/plugins/tool.rs, 3,219 lines) plus the matching tests (crates/octos-agent/src/plugins/tool_tests.rs, 4,406 lines) take more than half (51.96%). Running an external program safely costs far more than describing a prompt fragment. When a skill package directory holds both SKILL.md and manifest.json, that is exactly where the two tracks meet: SkillsLoader reads the former to inject prompts, PluginLoader reads the latter to register tools, and the tools="true" attribute in the XML index marks this seam.

9.1.1 The SKILL.md format

---
name: code-review
description: Review code changes for bugs, security issues, and style
version: 1.0.0
requires_bins: rg,git
requires_env: GITHUB_TOKEN
---

When reviewing code, focus on:
1. Security vulnerabilities
2. Error handling completeness
3. Behavior regressions

SkillsLoader does not implement a full YAML parser. It does two simplified steps:

  1. split_frontmatter() finds the frontmatter block between the leading and trailing --- (crates/octos-agent/src/skills.rs:301-320)
  2. fm_value() reads name, description, requires_bins, requires_env, always, version, author, and similar fields from simple key: value lines (crates/octos-agent/src/skills.rs:322-343)

fm_value() even strips inline comments and treats YAML empty values like [] / "" / ~ as missing. The design goal of skill metadata is not maximal expressiveness but "stable enough, cheap enough": a full YAML parser would bring new dependencies and parsing ambiguities, while skill authors need only a handful of flat key-value pairs. The tests explicitly cover the edges (duplicate keys take the first, colons inside values, empty frontmatter; the test group at crates/octos-agent/src/skills.rs:590-645), which marks this simplified path as a maintained contract, not a stopgap.

The available verdict also comes from here: parse_skill() checks each command in requires_bins against PATH (which_exists()) and each variable in requires_env for being set; only when both pass does it set available: true (crates/octos-agent/src/skills.rs:244-294,351-369). Note this is an availability check, not a security boundary: a skill with missing dependencies is merely marked unavailable in the summary; it is not quarantined from execution.

9.1.2 Layered Directories and Load Order

SkillsLoader keeps one "list of skill directories," and directories added first have higher priority (crates/octos-agent/src/skills.rs:62-116). The actual assembly order of list_skills() is: load the compile-time BUILTIN_SKILLS first, then traverse the directories from lowest priority (scanned first) to highest priority (overwriting later), using retain to drop older same-named entries (crates/octos-agent/src/skills.rs:118-173). This "reverse traversal plus dedup" implementation buys one property: however many directory layers exist, a same-named skill keeps only the copy from the highest-priority source, and the loading logic never needs to know each directory layer's semantics.

The directory list itself is assembled on the deployment side: Config::plugin_dirs_from_project() collects <octos_home>/plugins, <octos_home>/skills, and <octos_home>/bundled-app-skills/ in order, then appends the colon-separated directories of the OCTOS_SKILLS_PATH environment variable; the old ~/.octos/skills HOME-global directory is no longer scanned and only triggers a one-time migration warning (crates/octos-cli/src/config.rs:1330-1375). At gateway startup, the app-skills / platform-skills bundled with the binary are bootstrapped into the layered directories (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:566-573, crates/octos-agent/src/bootstrap.rs:103-115).

So this is not a fixed three-tier table of "workspace / global / builtin" but a layered view: deployment directories provide the shared baseline, account directories provide private installs, and the environment variable provides extra injection.

9.1.3 Skill layering v1: per-profile selective inheritance (9b1fc38f)

Layered directories answer "where skills come from"; skill layering v1 (commit 9b1fc38f) answers "which of them this profile may load."

The configuration surface is a per-profile skills selection block, lowered into a crate-agnostic SkillFilter (crates/octos-agent/src/skills.rs:12-36):

  • AllExcept(ids): discover everything, minus a deny list
  • Only(ids): whitelist mode, load only the listed skills

This enum deliberately depends on no CLI types, so the prompt-side SkillsLoader and the tool-side plugin loader consume the same selection decision. Otherwise a dangerous inconsistency opens up: a skill's prompt card is disabled while its executable tool stays registered. The model cannot see the description, yet the tool remains callable.

The execution surface converges in three places (crates/octos-agent/src/skills.rs:156-176,176-201): list_skills() uses retain to drop disabled skills from the summary; load_skill() returns None outright for disabled names, so the body can never enter the prompt; get_always_skills() is filtered the same way because it goes through list_skills(). The plugin side honors the same filter: load_into_with_options_and_filter() skips an entire skill package whose manifest id hits the deny list, loading neither tools, hooks, nor prompt fragments (crates/octos-agent/src/plugins/loader.rs:296-316).

The wiring happens at gateway assembly: the runtime builds a filter from the resolved profile's config.skills and hands it to the account-level loader (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:646-648); child bots inherit the same selection in crates/octos-cli/src/commands/gateway/profile_factory.rs (crates/octos-cli/src/commands/gateway/profile_factory.rs:698-702). None means there is no skills layer; everything behaves as before, fully backward compatible.

One distinction deserves emphasis: configuration inheritance is not local skill inheritance. A child account can inherit the parent profile's skill selection filter, but customer-installed skills are not inherited from the parent account. The account skills directory strictly resolves to the current account's own data_dir/skills, and plugin dirs likewise return only the current account's skills directory (crates/octos-cli/src/skills_scope.rs:96-112). A locally installed executable extension in the parent account will not silently enable itself in a child account.

9.1.4 The XML skill index

build_skills_summary() turns the filtered set of visible skills into XML injected into the system prompt (crates/octos-agent/src/skills.rs:203-219):

<skills>
  <skill available="true" tools="true">
    <name>deep-search</name>
    <description>Deep web research...</description>
    <location>/.../SKILL.md</location>
  </skill>
</skills>

Three points that are easy to get wrong:

  • The current XML has no name="..." attribute; the name is a <name> child node
  • tools="true" means "this skill directory contains a manifest.json," not "this skill is currently executing tools"
  • location exposes the skill's real source path to the model, helping it tell builtin from external skills

The XML summary is therefore not a plain "list of available skills" but the skill catalog index visible to the model, already filtered by skill layering: a skill disabled by the profile is entirely invisible here; the model cannot even learn that it exists.

9.1.5 spawn_only: auto-backgrounding, not hidden tools

The spawn_only marker is defined on tool entries in the skill package manifest (crates/octos-agent/src/plugins/manifest.rs:452-455), but its runtime semantics live not in the manifest; they live in the registry and the agent execution loop:

  • At load time PluginLoader calls registry.mark_spawn_only(name, msg) for these tool names (crates/octos-agent/src/plugins/loader.rs:332-339)
  • ToolRegistry maintains custom prompt text and task-tracking state for them (crates/octos-agent/src/tools/registry.rs:156-172)
  • When the main agent finds a tool call hitting spawn_only, it does not execute synchronously; it tokio::spawns a background task and immediately returns spawn_only_message to the model (crates/octos-agent/src/agent/execution.rs:579 onward)

So spawn_only is not "hidden from the ToolSpec." Under the current implementation these tools remain registered in the tool system and visible to the model; the difference is that invocation is auto-backgrounded. The model does not need to learn a new set of "task submission tools"; it issues a tool call as usual, and the runtime decides whether this call waits synchronously for the result or returns a handle immediately and keeps running in the background.

Going further, resolve_extras() injects the skill-card prompt fragment when the skill package contains spawn_only tools (crates/octos-agent/src/plugins/extras.rs:39-45,449-456). The model can thus see the tool and, at the same time, receive the prompt context for "when to use this background tool."

In the subagent scenario, the registry clears these markers, because "a subagent is itself background context"; there the tools execute directly like ordinary tools: wrapping another layer of backgrounding around already-backgrounded context would only lose the result handle, add a layer of scheduling overhead, and leave the child agent without the tool's return value.


9.2 The Plugins Track: Local Executable Tools and Skill Package Extras

If Skills change how the agent "thinks," Plugins make the agent actually call external programs to get work done.

9.2.1 The runtime manifest: more than a tool declaration

The runtime hot path uses the manifest structure from crates/octos-agent/src/plugins/manifest.rs:

{
  "name": "weather",
  "version": "1.0.0",
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "input_schema": { "type": "object", "properties": { "city": { "type": "string" } } },
      "env": ["WEATHER_API_KEY"],
      "risk": "medium",
      "concurrency_class": "safe"
    }
  ],
  "sha256": "a1b2c3...",
  "timeout_secs": 600,
  "requires_network": true
}

Reading it as a "pure tool manifest" no longer suffices. The structure now also supports: id, mcp_servers (SkillMcpServer), hooks (SkillHookDef), prompts.include, actions, binaries (precompiled downloads keyed by {os}-{arch}), spawn_only / spawn_only_message, env / env_allowlist, risk, concurrency_class, make_type, and more (crates/octos-agent/src/plugins/manifest.rs:8-110,387-477). It is closer to a skill package runtime manifest: tools are just one payload type; MCP server declarations, lifecycle hooks, and prompt injection can each stand alone as a package. If manifest.tools is empty but extras are declared, PluginLoader skips the executable search and still installs the extras (has_extras(), crates/octos-agent/src/plugins/manifest.rs:180-198; the loading branch at crates/octos-agent/src/plugins/loader.rs:607-626). Put plainly: "a plugin without a binary" is a legal form; it degrades into a pure extras package.

9.2.2 The plugin binary protocol

sequenceDiagram
    participant Agent
    participant Plugin as Verified Executable

    Agent->>Plugin: exec(".weather_verified", argv[1]="get_weather")
    Agent->>Plugin: stdin: {"city":"Beijing"}
    Plugin->>Agent: stderr: line-oriented progress
    Plugin->>Agent: stdout: {"output":"Beijing: 25°C, sunny","success":true}
    Agent->>Plugin: process exits

Figure 9-1: Sequence diagram of the plugin binary protocol.

The implementation is a bit more involved than "stdin JSON / stdout JSON":

  • what the runtime actually executes is the hash-verified copy written to disk after verification (crates/octos-agent/src/plugins/tool.rs:109-131)
  • argv's first argument is the tool name
  • stdin carries the JSON parameters
  • stderr is read line by line and turned into progress events
  • stdout is parsed as structured JSON first; when it is not valid JSON, the runtime falls back to "raw concatenated stdout + stderr text" (structured-field parsing around crates/octos-agent/src/plugins/tool.rs:3117-3130)

Reserving stderr as the progress stream is a pragmatic design: many off-the-shelf command-line tools already log to stderr, so a plugin author does not need to rewrite output logic; only the final result must land on stdout as JSON. The calling side receives streaming progress events, and a long task stops being a black-box wait.

Structured stdout also carries semantics richer than output/success: file_modified marks that the filesystem was touched, and files_to_send asks the runtime to deliver output files back into the conversation automatically (crates/octos-agent/src/plugins/tool.rs:3117-3130, crates/octos-agent/src/plugins/tool.rs:1229-1307). The runtime also tries to auto-detect generated files from the out argument or the output text.

The real value of the plugin protocol, then, is wrapping an "external process" into a Tool "that reports progress as a stream and returns files automatically."

9.2.3 Security and runtime constraints

Several security measures at the plugin layer must be stated precisely.

Gate one: executable discovery is conservative. PluginLoader treats only "subdirectory + manifest.json" as candidates. To find the binary it tries the manifest name, then the directory name, then main, and only last falls back to scanning the directory (crates/octos-agent/src/plugins/loader.rs:640-646,1189-1193).

Gate two: SHA-256 verification closes the TOCTOU window. The loader reads the raw bytes into memory once, hashes the in-memory bytes and compares against the manifest, writes the verified copy to disk, and records load_time_hash; a re-hash gate before execution re-verifies the same hash against the on-disk file, sealing the load→exec substitution window (crates/octos-agent/src/plugins/loader.rs:649-712, crates/octos-agent/src/plugins/tool.rs:109-131).

Gate three: resource and environment constraints.

  • A 100MB cap on executable files, enforced before the file is read into memory (MAX_EXECUTABLE_SIZE, crates/octos-agent/src/plugins/loader.rs:24,654-664)
  • The subprocess environment is sanitized by sanitize_command_env to strip injection vectors; tool-level env / env_allowlist uses strict semantics: secret-like variables are forwarded only when explicitly listed in the manifest, while non-secrets take the legacy compatibility path (crates/octos-agent/src/plugins/tool.rs:85-91)
  • The runtime injects OCTOS_WORK_DIR for the plugin's output files
  • The default timeout is 600 seconds, not 30 (DEFAULT_TIMEOUT, crates/octos-agent/src/plugins/tool.rs:151-163); the manifest's timeout_secs only overrides the default

Gate four: risk and concurrency classes are not decorative fields. risk feeds the approval path: high / critical force interactive approval and are safely refused when the approval bridge is missing; low triggers no approval by default; medium / unknown mainly drives explicit display (RiskLevel::classify / requires_approval, crates/octos-agent/src/plugins/manifest.rs:479-520).

concurrency_class recognizes safe and exclusive. An unknown value is not optimistically treated as safe: classify_concurrency_class() returns FailClosed, the execution side falls back to Exclusive, and a manifest typo cannot let a mutually exclusive tool run in parallel (crates/octos-agent/src/plugins/manifest.rs:569-609).

Gate five: symlinks rejected on Unix. is_executable() checks the file type with symlink_metadata() and accepts only regular files (crates/octos-agent/src/plugins/loader.rs:1354-1365). This is not the whole security boundary, but it shrinks the link-swap attack surface.

9.2.4 The boundary between the runtime PluginLoader and the octos-plugin SDK

The easiest mistake in this chapter is conflating the two layers of code in the repository into one.

The runtime hot path is crates/octos-agent/src/plugins/ (8 files, 14,675 lines total, of which crates/octos-agent/src/plugins/tool.rs is 3,219 lines and crates/octos-agent/src/plugins/tool_tests.rs is 4,406 lines): it scans directories, loads manifests, resolves extras, verifies and registers executable tools, and merely warn!s and skips a single failed plugin.

crates/octos-plugin is an SDK / tooling crate providing another layer of abstraction:

  • discover_plugins(): scans by source priority and deduplicates by manifest id; the first occurrence wins (crates/octos-plugin/src/discovery.rs:47-59)
  • check_requirements(): performs the three gating classes bins/env/os (crates/octos-plugin/src/gating.rs:42)
  • a richer manifest: id/type/requires/install/... (crates/octos-plugin/src/manifest.rs:112)

The two layers are related but must not be confused: the runtime loader has its own manifest types and paths, while octos-plugin serves toolchain consumers such as validators, marketplaces, and installers. One small but real detail: gating treats darwin and macos as equivalent aliases, so a mismatch between manifest strings and Rust platform strings does no damage (crates/octos-plugin/src/gating.rs:73-78).


9.3 MCP Integration: A Standard-Protocol Client on the rmcp SDK

MCP (Model Context Protocol) is a standardized tool-integration protocol. octos's MCP client lives at crates/octos-agent/src/mcp.rs, built on the official rmcp SDK (migration in commit 65486dad; crates/octos-agent/Cargo.toml:41-44: rmcp = { version = "1.8", ... }, with a comment that says outright "stdio + streamable-HTTP + OAuth 2.1").

9.3.1 Why the rmcp migration: three spec gaps in the hand-written client

The module documentation of crates/octos-agent/src/mcp.rs is blunt: the old hand-written client had three protocol-level defects: a missing notifications/initialized, a hardcoded protocol version, and a one-response-line-per-request read that misaligns under concurrency (crates/octos-agent/src/mcp.rs:1-22).

Each gap has a real consequence. Without the initialized notification, any server that per spec waits for that signal before entering working state stays half-initialized forever. A hardcoded protocol version is either rejected or silently downgraded when the server negotiates a different version. And "read one line per call" under concurrent calls must misalign: JSON-RPC responses match requests by id, not arrival order, so once responses from two parallel tool calls interleave, line-by-line parsing attributes them to the wrong requests.

rmcp takes over all three: the full lifecycle handshake (initialize + notifications/initialized), protocol version negotiation, and multiplexing with id routing for concurrent requests over a single connection. Upstack, this means concurrent tool calls no longer queue behind the previous response; one slow tool does not block the other tools on the same server.

9.3.2 The three connection paths

McpServerConfig (crates/octos-agent/src/mcp.rs:53-88) dispatches by field into three connection paths:

PathTriggerWhere it goes
stdioonly command/args/env setconnect_stdio() (crates/octos-agent/src/mcp.rs:452-485)
streamable-HTTP (static headers)url set, oauth offconnect_http() (crates/octos-agent/src/mcp.rs:499-528)
streamable-HTTP + OAuth 2.1url + oauth: truecrates/octos-agent/src/mcp_auth.rs::connect_oauth() (crates/octos-agent/src/mcp.rs:501-504, crates/octos-agent/src/mcp_auth.rs:105-186)

The stdio path spawns a child process with kill_on_drop, tying the child's lifetime to the Arc references of the rmcp session: when the last reference drops, the transport closes and the child is reaped. The environment follows the same sanitization rule as every octos subprocess: injection-vector variables are stripped, only env names the operator explicitly listed are forwarded, and even explicitly listed names pass through a denylist again, so a config writing LD_PRELOAD cannot reopen the process-hijacking hole (crates/octos-agent/src/mcp.rs:452-485). The rmcp subprocess transport reads JSON-RPC frames with an unbounded read_until; the source comment concedes this drops the old client's single-line cap, justified because a stdio server is a local binary the operator named and trusted personally (crates/octos-agent/src/mcp.rs:465-472).

The HTTP path is not a "pure SSE channel": rmcp's StreamableHttpClientTransport follows streamable-HTTP semantics (POST requests, optionally streaming responses); static headers, including an Authorization bearer token, are carried as-is, and octos wraps SSRF protection around the outside (see 9.3.4).

The OAuth path serves remote servers that need real user authorization. Token acquisition and use split across two command surfaces: octos mcp login <url> interactively runs the OAuth 2.1 authorization-code flow (a loopback redirect receives the callback) and writes the access + refresh tokens into the OS keyring as serialized JSON; the keyring key is "normalized URL + sha256 prefix," so writing the same server differently still stores only one entry (crates/octos-agent/src/mcp_auth.rs:30-95,186 onward). At runtime, connect_oauth() retrieves the token from the keyring and hands it to rmcp's AuthClient, refreshing automatically on expiry with no re-login; before connecting it enforces HTTPS and rejects literal private-network hosts (crates/octos-agent/src/mcp_auth.rs:105-125). One detail that is easy to miss: under OAuth there are two HTTP clients: the transport client carries configured headers through the SSRF filter, while the authorization-server endpoints (discovery / registration / token / refresh) go through a separate SsrfOAuthHttpClient, because those requests may legitimately point at a different host (crates/octos-agent/src/mcp_auth.rs:126-135).

9.3.3 Discovery, timeouts, and tool registration

Startup is fail-soft (McpClient::start(), crates/octos-agent/src/mcp.rs:374-437): servers are connected one by one; an unreachable server is logged as a warning and skipped, so one bad server cannot drag down the whole agent. Tool discovery also has a timeout: a server that completed initialize but keeps stalling on tools/list is skipped after HANDSHAKE_TIMEOUT (30 seconds), without blocking the servers behind it. This guard targets the pathological server that "completes the handshake but never returns the list," protocol-legal yet capable of wedging startup in engineering terms.

For each discovered tool, validate_schema() checks input_schema: nesting depth $\le 10$ (MAX_SCHEMA_DEPTH) and serialized size $\le 64\text{KB}$ (MAX_SCHEMA_SIZE, crates/octos-agent/src/mcp.rs:47-49,296-322). On the execution side, McpTool::execute() wraps tools/call in a 60-second timeout, and non-text content (images, resources) is dropped, because the agent's tool surface is currently text-only (crates/octos-agent/src/mcp.rs:586-612).

Two guards run before registration (register_tools(), crates/octos-agent/src/mcp.rs:532-558):

  • Name protection: PROTECTED_NAMES lists 20 built-in tool names (shell, read_file, git, browser, and so on); a same-named MCP tool is skipped outright, preventing a remote server from silently hijacking core capabilities (crates/octos-agent/src/mcp.rs:349-372)
  • Transport liveness (commit 3934aeb6): transports are handed to the registry before tools (keep_mcp_service_alive). Otherwise the tool is the sole owner of the connection, and when a profile narrowing filters out the last MCP tool, it kills the child process as a side effect (issue #1886). A visibility filter should not have the side effect of terminating a connection

9.3.4 The SSRF line of defense on the HTTP path

Remote MCP is an outbound surface, and octos places two lines of defense there (crates/octos-agent/src/mcp.rs:122-183):

  1. Configuration level: reject_private_url_host() rejects URLs whose host is a literal private/loopback IP or localhost. reqwest skips the custom resolver for literal-IP hosts; this layer exists to cover exactly that (crates/octos-agent/src/mcp.rs:165-183)
  2. Resolution level: a custom SsrfDnsResolver is mounted into the HTTP client and re-checked on every resolution, rejecting private/loopback/link-local/metadata addresses and defeating DNS rebinding; the redirect policy is none, so a 3xx cannot smuggle a request to an internal host (crates/octos-agent/src/mcp.rs:122-163)

The OAuth path's line is wider: the authorization server's discovery / registration / token / refresh endpoints all go through the SSRF-validated HTTP client as well (SsrfOAuthHttpClient, crates/octos-agent/src/mcp.rs:211-293, crates/octos-agent/src/mcp_auth.rs:126-135). A self-declared public MCP server cannot point token traffic at 127.0.0.1 or the cloud metadata address 169.254.169.254; otherwise an attacker could use a malicious server to probe the internal network or harvest credentials.


Engineering decision: why three extension mechanisms

DimensionSkillsPluginsMCP
Core rolechange prompts and contextrun local executable toolsconnect external protocol-based tool servers
Main carrierSKILL.mdmanifest.json + executablermcp session (stdio / HTTP / OAuth)
Execution boundaryno separate execution boundaryexternal process + verified copylocal child process or remote connection
Typical valuelow-cost behavior customizationprogress streams, file return, background tasksreuse across agent platforms
Security surfaceavailability check + profile filteringhash verification + env sanitization + work dirSSRF + schema validation + name protection

Why can't they be unified into one?

Because they do not solve the same class of problem. Skills teach the model "how to think," Plugins teach the system "how to do," and MCP teaches the system "how to plug in someone else's capabilities."

Making Skills a kind of Plugin would force pure prompt customization to carry the costs of binaries, protocols, and runtime security. Conversely, making Plugins pure Skills could not deliver real execution, progress streams, or file output. MCP and Plugins both look like "tool extension," but MCP pursues protocol interoperability rather than the lowest friction of local runtime integration.


9.4 Harness engineering contracts: see Chapter 10

Skills, Plugins, and MCP answer "how capabilities enter octos"; Harness answers how capabilities, once running, become verifiable, observable, upgradeable engineering contracts: ABI schema versioning, the OCTOS_EVENT_SINK JSONL side-channel, the validator runner, and starter app skills. Since v2 this material has its own chapter; see Chapter 10.


9.5 Configuration Lanes: mcp_servers and sub_providers

The two configuration lanes of the extension mechanisms both live on the CLI-side top-level Config. One decides "which external tool servers to connect"; the other decides "which models subagents use." Their names rhyme; their semantics do not.

9.5.1 mcp_servers

The top-level key mcp_servers: Vec<octos_agent::McpServerConfig> (crates/octos-cli/src/config.rs:108-110) reuses the agent crate's configuration type directly. This wiring is deliberate: the config-parsing surface and the runtime-consuming surface share one struct, so what McpClient::start() receives is exactly what the config file wrote. No second conversion in between, hence no room for "the config says one thing, the runtime understands another" drift. Each entry's fields are the three dispatch conditions from the table in 9.3.2 (command/args/env, or url/headers, or those plus oauth/scopes), plus an optional concurrency_class override (default Safe; unknown values likewise fail-safe to Exclusive). Minimal example:

{
  "mcp_servers": [
    { "command": "uvx", "args": ["mcp-server-fetch"] },
    { "url": "https://mcp.example.com/mcp", "oauth": true, "scopes": ["read"] }
  ]
}

9.5.2 sub_providers

The top-level key sub_providers: Vec<SubProviderConfig> (crates/octos-cli/src/config.rs:182-184; struct definition crates/octos-cli/src/config.rs:616-654) declares the sub providers the spawn tool can choose from. Fields include key (a short reference name such as cheap, strong), provider, model, api_key_env, base_url, description, default_context_window, max_output_tokens, api_type. The description enters the spawn tool's schema alongside cost and capability metadata, and the model picks a model based on it; default_context_window decides how aggressively the subagent trims history. Minimal example:

{
  "sub_providers": [
    { "key": "cheap", "provider": "openai", "model": "gpt-4o-mini", "api_key_env": "OPENAI_API_KEY" }
  ]
}

Reserved key goal_verifier: a sub_providers entry keyed goal_verifier routes goal-completion verdicts to that provider for verification (GOAL_VERIFIER_LANE_KEY and build_goal_verifier_provider(), crates/octos-cli/src/runtime/profile.rs:128-190). The point of this lane is separating "the model that does the work" from "the model that accepts it": unconfigured, it falls back to the scoring session's own provider (the pre-#1935 behavior, kept as the compatibility default), where goal completion is attested by the same model; configured with an independent verifier, the verdict comes from a separate provider lane.

9.6 Chapter Recap

  1. Skills: SKILL.md + simplified frontmatter parsing; layered directories deduplicate into one view, which the per-profile SkillFilter (layering v1, 9b1fc38f) filters into the XML summary injected into the system prompt.

  2. Plugins: the runtime manifest is already a skill package manifest; the verified copy seals TOCTOU, while env allowlisting, risk approval, fail-closed concurrency, and the 600-second default timeout together form the execution boundary.

  3. spawn_only: not hidden tools but auto-backgrounding. The main agent returns spawn_only_message immediately; subagent contexts restore direct execution.

  4. MCP: stdio + streamable-HTTP + OAuth 2.1 on the rmcp SDK (1.8) (65486dad); fail-soft startup, schema validation, PROTECTED_NAMES, the two-level SSRF line, and registry-held transports (3934aeb6).

  5. Architecture boundary: octos-agent/src/plugins/* (14,675 lines) is the runtime hot path; crates/octos-agent/src/skills.rs (942 lines) is the prompt track; octos-plugin is the discovery/gating SDK.

  6. Configuration lanes: mcp_servers decides which MCP servers to connect; sub_providers decides which models subagents use; goal_verifier is the reserved key of the latter.

This closes Part 2. The next chapter opens Part 3, moving from single-machine sessions to the message bus and multi-session orchestration.


Further reading

  • Model Context Protocol: https://modelcontextprotocol.io/
  • rmcp (Rust MCP SDK): https://crates.io/crates/rmcp
  • JSON-RPC 2.0: https://www.jsonrpc.org/specification

Exercises

  1. The convergence point of skill filtering: why must load_skill() return None for a disabled skill, rather than merely deleting it from the XML summary? If the model tries to load a disabled skill by name from "memory," what happens?

  2. The plugin trust chain: the verified copy closes the load→exec TOCTOU, but if the manifest and the raw binary are replaced together, the hash still "agrees with itself." How would you push the trust chain one layer further out?

  3. The rmcp tradeoff: migrating to rmcp fixed the three spec gaps but dropped the stdio single-line 1MB cap (unbounded read_until). Under what premise is this tradeoff safe? In what deployment shapes does it deserve a second look?


Version note This chapter is written against octos main 9c157101 (measured 2026-09-03) and covers three recent evolutions: 65486dad migrated the MCP client wholesale onto the rmcp SDK (stdio + streamable-HTTP + OAuth 2.1; crates/octos-agent/src/mcp.rs rewritten, crates/octos-agent/src/mcp_auth.rs added); 9b1fc38f shipped skill layering v1 (per-profile selective inheritance, crates/octos-agent/src/skills.rs, crates/octos-agent/src/plugins/loader.rs); 3934aeb6 moved MCP transport ownership into the registry. When reading later versions, check first against crates/octos-agent/src/skills.rs, crates/octos-agent/src/plugins/, crates/octos-agent/src/mcp.rs, crates/octos-agent/src/mcp_auth.rs, crates/octos-plugin/src/, and crates/octos-cli/src/config.rs.

Chapter 10: Harness: Turning "the model says it's done" into a Verifiable Contract

Positioning: This chapter dissects the octos harness system: declarative validators, a structured event ABI, schema versioning, workspace policy, the structured error taxonomy, and lifecycle hooks. It starts by correcting a common misconception: there is no standalone harness crate; the harness is six modules inside octos-agent plus four starter scaffolds. Prerequisites: Chapter 5 (the error recovery chain), Chapter 6 (the Tool trait), Chapter 7 (the sandbox). Who should read it: anyone who needs the output of a long-running agent to be auditable, gated, and replayable.

Chapter 5 left a question open when it covered the agent loop: the model answers "done"; on what basis does the runtime believe it? Chapter 6's tools let an agent change the world; Chapter 7's sandbox constrains how far those changes may reach. But "did the changes meet the bar after they happened" stayed unanswered. The harness closes that gap. It does not make the model smarter; it turns "done" from a natural-language sentence into a machine-checkable contract.

First, the size of these six modules in the source tree (measured on octos main @ 9c157101):

ModuleLinesFirst-line //! doc
crates/octos-agent/src/validators.rs2,772Declarative validator runner (harness M4.3).
crates/octos-agent/src/harness_events.rs2,789Structured harness event ABI and local sink transport.
crates/octos-agent/src/abi_schema.rs349Harness ABI schema versioning.
crates/octos-agent/src/workspace_policy.rs3,165(no //!; first line is use std::collections::BTreeMap;)
crates/octos-agent/src/harness_errors.rs745Structured harness error taxonomy (M6.1, issue #488).
crates/octos-agent/src/hooks.rs2,856Hook/lifecycle system for running shell commands at agent lifecycle points.

The total is 12,676 lines. There is no harness crate; these six files all live under crates/octos-agent/src/, and together with the four starter directories under crates/app-skills/ (audio/coding/generic/report) they are the whole harness. That correction carries information on its own: the harness is not another abstraction box layered on top; it weaves validation, events, and versioning directly into the agent runtime.

flowchart LR
    subgraph six modules inside octos-agent
        WP[workspace_policy<br/>declaration layer 3165 lines]
        V[validators<br/>execution layer 2772 lines]
        HE[harness_events<br/>event ABI 2789 lines]
        AS[abi_schema<br/>versioning 349 lines]
        H[hooks<br/>lifecycle 2856 lines]
        HErr[harness_errors<br/>error taxonomy 745 lines]
    end
    ST[four starters<br/>app-skills/harness-starter-*] -->|workspace-policy.toml| WP
    WP -->|validators list| V
    V -->|ValidatorResult events| HE
    H -->|Feedback injected into the model| HE
    HErr -->|Error events| HE
    AS -.version guardrail.-> WP
    AS -.version guardrail.-> HE

The division of labor among the three pillars: workspace_policy declares what counts as done, validators executes the verdict, and abi_schema + harness_events make sure the process and the result of the verdict stay legible to components of different versions. Hooks and harness_errors are the two wings: the former turns lifecycle points into programmable seams, the latter gives every failure a type. The sections below take them one at a time.


10.1 Pillar One: Declarative Validators

10.1.1 Why Validation Is Data, Not Code

The first pillar answers "what counts as done." Start with what it rejects: the most intuitive way to make agent output verifiable is a fn validate() -> bool. But once validation logic is code, it locks to the host version: an old workspace meeting a new runtime gets a function signature mismatch; in the other direction, a runtime upgrade cannot interpret the validation intent written into old policy files. octos chose to make validators data: a table inside WorkspacePolicy, interpreted and executed by a single runner.

Three engineering reasons back this decision. First, serializability: policy files can be archived with the workspace, diffed, and migrated, and the schema_version field keeps old files readable in new runtimes (see 10.3). Second, sandboxability: the runner is the only execution entry point, so command validators uniformly pass through the shell safety layer (SafePolicy) and BLOCKED_ENV_VARS environment scrubbing, and policy authors cannot bypass either (for the sandbox itself and for the decisions in b64bd532/bf6be8cc, which pulled project-root validators into the sandbox and made the mcp-serve path fail-closed, see Chapter 7). Third, replayability: every execution result lands in a JSONL ledger that is re-read verbatim after a restart, with no dependence on transient in-process state. The cost is limited expressiveness: a complex verdict has to be decomposed into combinations of existing ValidatorSpec variants, or fall back to the Command variant calling an external program. Exercise 1 pushes on that trade-off.

10.1.2 The Declaration Layer: Validator and Three-Tier Semantics

The declaration lives in ValidationPolicy (crates/octos-agent/src/workspace_policy.rs:115), which holds both the old string validators and the typed validators:

#![allow(unused)]
fn main() {
/// Tiered validation checks run at different points in the turn lifecycle.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ValidationPolicy {
    /// Tier 1: cheap checks run every turn (< 100ms). e.g. file_exists, build exit code.
    #[serde(default)]
    pub on_turn_end: Vec<String>,
    /// Tier 2: medium checks run when source files change (1-5s). e.g. preview render.
    #[serde(default)]
    pub on_source_change: Vec<String>,
    /// Tier 3: expensive checks run on completion/publish only (10-30s). e.g. Playwright.
    #[serde(default)]
    pub on_completion: Vec<String>,
    /// Typed declarative validators (M4.3). Runs via `ValidatorRunner`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub validators: Vec<Validator>,
}
}

The first three fields are string validators tiered by cost (every turn, on source change, on completion only); the fourth, Vec<Validator>, is the typed form the harness actually pushes. Each Validator (crates/octos-agent/src/workspace_policy.rs:143) carries a stable id, a timeout, and a run phase; its body, spec, is a kind-tagged enum ValidatorSpec (crates/octos-agent/src/workspace_policy.rs:301) that grows from running subprocesses, calling tools, and checking file existence out to HTTP probes, SHA-256 comparison, and audio non-silence detection.

The failure semantics carry the most design weight. Historically there was only the boolean required: true meant a failure blocks, false meant warn-only. After Wave-3a introduced soft_fail, the two fields collapse into a three-value Required (crates/octos-agent/src/workspace_policy.rs:198):

#![allow(unused)]
fn main() {
    pub fn tier(&self) -> Required {
        if self.soft_fail {
            Required::Soft
        } else if self.required {
            Required::Hard
        } else {
            Required::None
        }
    }
}

A Hard failure stops a spawn task from reaching terminal success; a Soft failure only leaves a ledger record and a warning, which serves partial-delivery contracts of the form "the primary artifact must ship, the byproducts are best-effort"; None gates exactly like Soft but the ledger explicitly marks it "informational." The old boolean fields stay for compatibility with old policy files, and this one function reconciles both generations of fields. The declarative design is what makes that smooth migration possible.

The criteria for the three tiers are written into the doc comment of the Required enum (crates/octos-agent/src/workspace_policy.rs:198), and two helper methods pin the semantics down: is_hard() decides whether a non-Pass result demotes a spawn task to Failed (true only for Hard); is_warning_only() decides warn-only behavior (true for both Soft and None). Operationally, this means a dashboard can slice failures into three classes by the tier label in the ledger: a hard failure needs immediate action, a soft failure needs a look at whether the byproduct affects anything downstream, a none failure is pure information. The practical question for choosing a tier is "if this check fails, is the deliverable still usable": file existence of the primary artifact takes Hard; preview files and supplementary reports take Soft; style checks take None. The stable labels emitted by as_str() (hard/soft/none) go straight into metrics and ledger records, so an operations panel can filter without understanding a Rust enum.

10.1.3 The Execution Layer: The Five-Step Sequence of ValidatorRunner

The execution layer centers on ValidatorRunner (crates/octos-agent/src/validators.rs:441). Its constructor reads like a safety checklist: evidence lands by default under <workspace_root>/.octos/validator-evidence/ (the EVIDENCE_SUBDIR constant at crates/octos-agent/src/validators.rs:46), the command policy defaults to SafePolicy, and the ledger and sandbox are optional attachments. Tool dispatch is abstracted behind the ValidatorToolDispatcher trait (crates/octos-agent/src/validators.rs:367): production binds the full ToolRegistry, while tests and short-lived call sites use MapToolDispatcher to snapshot the few tools they need instead of cloning an entire registry to build a runner. The context shared by a batch of validators is ValidatorInvocation (crates/octos-agent/src/validators.rs:167), carrying the workspace root, repository label, run phase (ValidatorPhase, crates/octos-agent/src/validators.rs:105, with turn_end and completion values), and optional spawn task input and tool output. run_all runs the whole batch and returns results in declaration order. The processing path of a single command validator:

sequenceDiagram
    participant P as WorkspacePolicy
    participant R as ValidatorRunner
    participant S as SafePolicy
    participant C as subprocess
    participant L as ValidatorLedger
    P->>R: run_all(invocation, validators)
    loop each Validator
        R->>R: interpolate_template resolves ${args.X}/${output.X}
        R->>S: policy.check(command_string, workspace_root)
        alt Deny / Ask
            R->>R: error_outcome (fail closed)
        else Allow
            R->>C: start (timeout SIGTERM→SIGKILL)
            C-->>R: exit code / stdout / stderr
        end
        R->>R: assemble ValidatorOutcome (with evidence path and duration)
        R->>L: ledger.append(outcome)
    end
    R-->>P: Vec<ValidatorOutcome>

Every step of that sequence diagram maps to a method of ValidatorRunner. Five key steps. Template interpolation at crates/octos-agent/src/validators.rs:677-696: ${args.<key>} comes from the spawn task input JSON, ${output.<key>} from the tool's named_outputs (for example deploy_url from mofa_publish), which makes "verify the just-published URL is reachable" a first-class case; a missing key produces Error directly. The safety gate at crates/octos-agent/src/validators.rs:719-734: a SafePolicy verdict of Deny or Ask is treated as Error; over-blocking beats letting it through. Execution and timeout kill (SIGTERM escalating to SIGKILL on Unix, taskkill /F /T on Windows) live in run_command (crates/octos-agent/src/validators.rs:661). The result type ValidatorOutcome (crates/octos-agent/src/validators.rs:236) carries schema_version, duration, evidence path, and the tail of stderr, enough for after-the-fact audit. Booking to the ledger is done by ValidatorLedger.append (crates/octos-agent/src/validators.rs:321), one JSON record per line.

The ledger is append-only: ValidatorLedger (crates/octos-agent/src/validators.rs:298) exposes exactly two actions, append and read_all; the latter deserializes line by line and, along the way, normalizes pre-Wave-3a records into the new tier semantics. The contract test should_persist_outcomes_and_replay_them_byte_for_byte (crates/octos-agent/tests/validator_runner.rs:490) verifies exactly "what went in is what comes back on re-read." Replay does not rely on log archaeology; it relies on structured records.

The 17 cases of crates/octos-agent/tests/validator_runner.rs pin every edge of that sequence diagram: a required command validator failing must block (crates/octos-agent/tests/validator_runner.rs:123), an optional failure only warns (:218), a timeout kills the subprocess (:329), stderr lands in the result for the operator to read (:293), and BLOCKED_ENV_VARS are stripped even when set explicitly (:531).

Engineering decision: why timeouts and refusals are Error, not Fail ValidatorStatus (crates/octos-agent/src/validators.rs:131) splits terminal states four ways: Pass / Fail / Timeout / Error. Fail means "the check ran to completion and the verdict is not acceptable"; Timeout and Error mean "the check never ran." The distinction matters for gating: an unacceptable artifact can be returned to the agent to fix, while a policy refusal or a broken environment would, if "returned," only set the agent spinning against a broken world. Consumers (the Chapter 16 gate among them) need a single condition, required && status != Pass, and the four terminal states fall into place.

10.1.4 Workspace Policy: One TOML Drives Everything

WorkspacePolicy (crates/octos-agent/src/workspace_policy.rs:22) is the master declaration: seven sections covering workspace type, versioning, tracking, validation, artifacts, spawn tasks, and compaction. Its CompactionPolicy (crates/octos-agent/src/workspace_policy.rs:51) declares the shape of compaction: target token budget, artifacts and invariants that must survive, summarizer flavor (CompactionSummarizerKind, crates/octos-agent/src/workspace_policy.rs:104, Extractive or LlmIterative), preflight thresholds, and how many rounds of old tool results to prune. When absent, the runtime falls back to the old extractive path, byte-for-byte identical to pre-M6.3 behavior. "Absent means old behavior" is the shared compatibility philosophy across harness modules (Chapter 8 covers how compaction is consumed at runtime).

The read side of WorkspacePolicy sits behind the same version guardrail: a missing schema_version in the file deserializes as v1, and a version above the maximum compiled into the runtime is rejected outright; details in 10.3. The four starters' workspace-policy.toml files are the minimal runnable samples of this declaration; 10.5 walks through them.


10.2 Pillar Two: The Event ABI: What Happened While It Ran

10.2.1 The octos.harness.event.v1 Envelope

The first pillar answers the verdict at the end; the second answers the narrative of the process: what happened while it ran, and how external components hear about it. That need lands in crates/octos-agent/src/harness_events.rs (2,789 lines, the largest of the six modules). All events share one envelope:

#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HarnessEvent {
    pub schema: String,
    #[serde(flatten)]
    pub payload: HarnessEventPayload,
}
}

The schema field is always the constant HARNESS_EVENT_SCHEMA_V1 (crates/octos-agent/src/harness_events.rs:29), whose value is the string octos.harness.event.v1, the stable identity consumers are meant to branch on. The payload, HarnessEventPayload (crates/octos-agent/src/harness_events.rs:368), is a kind-tagged, snake_case-named tagged union of a dozen-plus events: Progress, Phase, Artifact, ValidatorResult, Retry, Failure, McpServerCall, SubAgentDispatch, SwarmDispatch, SwarmReviewDecision, CostAttribution, RoutingDecision, CredentialRotation, SessionSanitized, SubagentProgress, Error. The pipeline progress events of Chapter 13 and the swarm gates of Chapter 17 both speak this vocabulary; this chapter establishes it.

Take the most used one, HarnessProgressEvent (crates/octos-agent/src/harness_events.rs:461): it carries schema_version, session_id, task_id, phase, an optional message, and an alias-compat field for progress_fraction: old producers write progress_fraction, new consumers read fraction, and one serde alias line settles it without a major-version bump.

10.2.2 Local Sink Transport

The transport is a local JSONL file: an external app skill process writes single-line events into the file pointed to by OCTOS_EVENT_SINK; the runtime validates the schema, tails the file, folds events into the task snapshot, and broadcasts typed frames to /api/events/harness. This side channel is separate from the stdout tool-result protocol: stdout answers "what did the tool return," the sink answers "what happened while it ran". One app skill process, two output channels, no mixing of duties. Two defenses guard the channel: events are schema-validated before they enter, and any line over the size cap is rejected whole, so dirty data never enters the stream; correlation context arrives via environment variables, OCTOS_SESSION_ID and OCTOS_TASK_ID (plus the equivalent OCTOS_HARNESS_SESSION_ID / OCTOS_HARNESS_TASK_ID), so every event traces back to a session and a task, and after-the-fact audits never have to guess provenance. For the fleet gates of Chapter 16 and the swarm aggregation of Chapter 17, this per-task event collection is the foundation they consume; this chapter sets the contract and leaves the consuming side alone.

Errors get their own event form: HarnessErrorEvent (crates/octos-agent/src/harness_errors.rs:166) rides under the same envelope as kind: "error", carrying the snake_case variant identity and the recovery hint, with the schema version constant HARNESS_ERROR_SCHEMA_VERSION registered in abi_schema. The contract test should_round_trip_harness_error_through_sink (crates/octos-agent/tests/harness_errors.rs:154) verifies that an error event written through the sink and read back is unaltered; should_emit_harness_event_on_error_classification (:126) verifies that every error classification emits an event. The taxonomy itself (RecoveryHint at crates/octos-agent/src/harness_errors.rs:47 and HarnessError at crates/octos-agent/src/harness_errors.rs:93, five hints and a dozen-plus variants) was covered with the recovery chain in Chapter 5; two points deserve emphasis here. First, the relation between the taxonomy and the event ABI is "classification determines the payload": variant_name() is frozen naming, and event consumers branch on it deterministically without touching the natural-language message. Second, the granularity of the taxonomy is designed for observability: RecoveryHint has exactly five values (backoff_retry, switch_provider, compact_context, fail_fast, bug) and can serve directly as Prometheus labels without cardinality explosion; HarnessError variants are fine-grained enough to separate "401 authentication failed" from "403 quota exhausted" (two 4xx cases), so the operator-facing hints differ: "check the API key" versus "top up or switch provider." The 18 cases of crates/octos-agent/src/harness_errors.rs pin this mapping firmly: 429 maps to RateLimited with BackoffRetry (crates/octos-agent/tests/harness_errors.rs:26), 5xx to ProviderUnavailable with SwitchProvider (:58), network errors to BackoffRetry (:77), identical inputs always classify identically (:110), 403 with a quota marker maps to Quota and without to Authentication (:248, :271). Classification survives a round trip through eyre unchanged (:280): the payoff of putting the classification in the type rather than at the failure site.


10.3 Pillar Three: Schema Versioning: Staying Legible Across Versions

Declarations get archived, events get replayed, so a third question arises: can components separated by a version still understand each other? That is the territory of the third pillar, crates/octos-agent/src/abi_schema.rs.

10.3.1 Five Durable Types and check_supported

The harness exposes five durable serialized types: WorkspacePolicy, HookPayload, ProgressEvent (the emitted shape), TaskResult, and SessionSummary. crates/octos-agent/src/abi_schema.rs maintains a version constant for each in one place, all currently 1. This 349-line module does one thing: the version guardrail. Its core function is nine lines (crates/octos-agent/src/abi_schema.rs:159):

#![allow(unused)]
fn main() {
pub fn check_supported(
    kind: &'static str,
    found: u32,
    supported: u32,
) -> Result<(), UnsupportedSchemaVersionError> {
    if found > supported {
        Err(UnsupportedSchemaVersionError {
            kind,
            found,
            supported,
        })
    } else {
        Ok(())
    }
}
}

The rule is one-directional: found <= supported always passes (old versions stay readable through defaulted fields), and found > supported is rejected with the typed error UnsupportedSchemaVersionError (crates/octos-agent/src/abi_schema.rs:135), whose Display message always contains the type name, the version actually read, and the supported maximum, plus the hint "upgrade octos to a newer release." No panic, no silent truncation. The caller can log, surface an actionable error to the operator, or fall back to a safe default.

10.3.2 The Version Negotiation Decision Flow

flowchart TD
    A[deserialize payload] --> B{schema_version field present?}
    B -- absent --> C[treat as v1<br/>serde default fills values]
    B -- present --> D{compare found to the supported<br/>value compiled into the runtime}
    D -- "found ≤ supported" --> E[read normally<br/>unknown new fields ignored]
    D -- "found > supported" --> F[UnsupportedSchemaVersionError<br/>fail closed]
    F --> G[operator sees: type / version read / max<br/>+ upgrade hint]

Why does this door close in only one direction? The risks of "old runtime reads new payload" and "new runtime reads old payload" are asymmetric by nature. Old data merely lacks new fields; serde fills defaults and reads it out safely, and what was read is the old shape, which is correct. An old runtime meeting a new payload faces fields that may carry semantic changes the old code cannot understand (a field turning from a single value into a list, say); any "best-effort parse" is guessing, and the cost of a wrong guess is a silent misread. The engineering trade-off therefore sits on the conservative side: better that the operator sees an error carrying the type name, the version read, and the supported maximum, and upgrades octos, than that bad data flows silently down the pipeline. That is also why check_supported's error message always appends the "upgrade octos to a newer release" hint (the Display implementation at crates/octos-agent/src/abi_schema.rs:144-151): a fail-closed error must hand over the remedy, or it has only moved the failure to a different shape. The reverse direction, "new reads old," is handled by defaults: all five durable types mark their schema_version with #[serde(default = "...")], so policy files from before April 2026 load unchanged, and upgrading octos needs no migration ceremony.

These semantics map one-to-one onto the five compatibility rules of docs/OCTOS_HARNESS_ABI_VERSIONING.md: a missing schema_version deserializes as v1; an unknown major version is rejected with a typed error, never a panic; within a major version, stable fields keep their meaning and newly added optional fields must default to empty; breaking changes must bump the major version and leave a dual-version transition window; external consumers branch on schema_version before reading version-specific fields. Of the guardrails, "missing field defaults to v1" keeps pre-April-2026 policy files loading today, and "above the maximum, reject" keeps an old runtime from misreading future payloads. should_reject_future_workspace_policy_schema_version (crates/octos-agent/tests/abi_compat.rs:259) and should_default_workspace_policy_to_v1_when_schema_version_missing (:197) pin one each. The 13 cases of crates/octos-agent/tests/abi_compat.rs, driven by fixture files, cover both ends, old and new, of the four durable types.

What is versioned is the runtime serialization shape, not a skill's or plugin's own release version (that is the version field of manifest.json); Chapter 9 drew that distinction, and this chapter is its enforcement mechanism.


10.4 The Two Wings: Hook Lifecycle and the Sandbox Crossover

10.4.1 Eleven Lifecycle Points

The session context for hooks travels in HookContext (crates/octos-agent/src/hooks.rs:24), holding just two optional fields, session_id and profile_id, injected by the gateway before the agent loop starts; it lets one hook configuration tell which session it serves, and it is the source of the session-isolated state keys in 10.4.2. HookEvent (crates/octos-agent/src/hooks.rs:32) enumerates eleven mount points: user_prompt_submit, before/after_tool_call, before/after_llm_call, on_resume, on_turn_end, plus the four points around spawn verification and completion/failure. Each HookConfig (crates/octos-agent/src/hooks.rs:77) declares the triggering event, an argv array (never shell-interpreted), a timeout (default 5000ms), an optional tool_filter, a path_filter glob (for example, restricting cargo check to after **/*.rs edits), and requires_bin (silently skip when the binary is not on PATH rather than forcing operators to install every linter).

The payload, HookPayload (crates/octos-agent/src/hooks.rs:123), carries schema_version plus the event, tool name, arguments, duration, model, and iteration count; integrators can implement HookPayloadEnricher (crates/octos-agent/src/hooks.rs:671) to inject domain data. The execution result is the six-state HookResult (crates/octos-agent/src/hooks.rs:679): Allow, Deny, Modified, Context, Error, Feedback.

Feedback shows the design trade-off best: when an after-hook exits with code 1 and output, that is the feedback channel working: a checker reporting diagnostics that belong in the model's session. A missing binary, a timeout, or an exit code >= 2 is an infrastructure failure, Error, and must never mix into model context; otherwise the agent reads "the hook broke" as "the code is wrong" and fixes the wrong thing. The coding feedback loop wired up by commits 9ebaf468 and fb0f9eeb follows exactly this rule: the after_tool_call hook feeds cargo check compiler errors back to the model as Feedback, closing an edit→check→correct loop, preserved per configuration order, so a later failing hook cannot overwrite the coding default hook's compiler errors (#2129 review items 8 and 9).

10.4.2 Circuit Breaker and Session Isolation

HookExecutor carries a built-in circuit breaker: enough consecutive failures disable the hook, so one broken hook cannot tax every turn. The #2153 fix is worth recording. The breaker and debounce state used to be one global copy inside the executor; with an Arc<HookExecutor> shared across all sessions, one workspace's infrastructure failure counted against everyone. After the fix, state is keyed by session (crates/octos-agent/src/hooks.rs:716 onward), so one session's tripped breaker leaves its neighbors alone; the after-event debounce window works the same way, so several edit_file calls in one turn pay for one full-project cargo check.

10.4.3 The Security Crossover with Chapter 7

The harness's programmability carries inherent risk: the .octos-workspace.toml in a workspace is untrusted input, and the command validators it declares cannot run bare on the host. That is why b64bd532 and bf6be8cc pulled project-root validators into the sandbox and made the mcp-serve path fail-closed (on Windows, where no safe argv-wrapping scheme exists, it errors out rather than bypassing the sandbox; the comment at crates/octos-agent/src/validators.rs:735-749 states the decision plainly). The sandbox machinery itself belongs to Chapter 7 and is not expanded here.


10.5 Four Starters: Scaffolding for Users

Under crates/app-skills/ sit four harness starters: harness-starter-audio, harness-starter-coding, harness-starter-generic, and harness-starter-report, all with the identical layout of six pieces: Cargo.toml, manifest.json, SKILL.md, src/, tests/, workspace-policy.toml. They are not toys in the reference-implementation sense; they are templates that assemble every concept in this chapter into a copyable starting point: the manifest declares tools and concurrency classes, the workspace policy declares artifacts and validation, and the smoke test in tests/ checks that neither declaration is lying.

Walk through harness-starter-coding. Its manifest.json declares one spawn_only tool, propose_patch, which renders a patch as a patches/<slug>.diff unified-diff file plus a patches/<slug>.files.txt preview manifest, with concurrency_class = "exclusive" to prevent concurrent write conflicts. Its workspace-policy.toml is a direct sample of the declarations from 10.1:

[validation]
on_turn_end = []
on_source_change = []
on_completion = ["file_exists:patches/*.diff"]

[artifacts]
primary = "patches/*.diff"
preview = "patches/*.files.txt"

[spawn_tasks.propose_patch]
artifacts = ["primary", "preview"]
on_verify = [
    "file_exists:$primary",
    "file_size_min:$primary:64",
    "file_exists:$preview",
]

Note the $primary reference: artifact declaration and validation rule are decoupled, so renaming an artifact touches one place. This TOML also shows how the three-tier string validation maps section by section onto WorkspacePolicy: [validation] is the validation layer, [artifacts] the artifact layer, and [spawn_tasks.*] assembles both into a task contract, with on_verify / on_deliver / on_failure attached to the verify, deliver, and fail moments respectively. The file_size_min of 64 bytes plugs the "a zero-byte diff still counts as delivered" hole: empty patch text passes file_exists but not the size floor. String validators (on_completion) and typed validators coexist here; new code should prefer the latter.

The other three starters get one paragraph each. harness-starter-audio shows the exclusive-resource contract: synthesize_clip writing audio/<slug>.wav must declare the exclusive concurrency class, and the primary artifact carries a file_size_min floor of 4096 bytes. harness-starter-report is the minimal report contract: reports/*.md as primary artifact, file_exists at completion, and notify_user on failure. harness-starter-generic is the blank template with the domain detail stripped out, fit as the starting point for a new app skill. When writing a new app skill, treat these four directories as an engineering checklist and verify item by item: manifest declaration, concurrency class, artifact contract, validation gate, failure notification; only start writing business code once nothing is missing.

From the user's point of view, the starters' value is that they collapse this chapter's machinery into a hands-on path of "copy the directory, edit two declaration files": manifest.json describes what the tool looks like (input schema, concurrency class, timeout), workspace-policy.toml describes what counts as output (artifact patterns, validation rules, failure notification), and the business code in src/ just does the work, never knowing ValidatorRunner or the event envelope exists. Reading the four workspace-policy.toml files side by side also reveals a gradient of contract tightness: coding's file_size_min:$primary:64 is a byte-level floor, audio's 4096 exists because the WAV header alone is not small, report uses only file_exists because a reasonable size for a Markdown report cannot be predicted, and generic leaves it empty for the user to fill. One mechanism, four tightness levels, adjusted entirely in the declaration layer's data without touching a line of runner code. This is 10.1.1's "validation is data, not code" cashed out on the user side.


10.6 Recap

  1. Fact correction: there is no harness crate. The harness is six modules inside octos-agent (validators 2,772 lines, harness_events 2,789 lines, abi_schema 349 lines, workspace_policy 3,165 lines, harness_errors 745 lines, hooks 2,856 lines; 12,676 lines together) plus the four starters under crates/app-skills/harness-starter-*.

  2. Three pillars: workspace_policy declares what counts as done, validators execute the verdict and produce a replayable ledger, and harness_events + abi_schema keep the process and result readable across versions. Hooks and harness_errors are the two wings; the starters are the user-facing scaffolding.

  3. Declarative validation: validators are data, not code, bought at the price of limited expressiveness and repaid with serializability, sandboxability, and replayability; the three-value Required (Hard/Soft/None) reconciles the old and new fields, and Soft supports partial-delivery contracts.

  4. Event ABI: the octos.harness.event.v1 envelope plus a kind-tagged payload enum, transported over a local JSONL sink and validated before entering the stream; Chapter 13's pipeline progress and Chapter 17's swarm gates share this vocabulary.

  5. Version guardrail: five durable types, the nine-line core of check_supported, missing fields defaulting to v1, and fail-closed above the maximum; 13 cases in crates/octos-agent/tests/abi_compat.rs pin both ends.

  6. Hooks and security: eleven lifecycle points, a six-state result, Feedback and Error strictly separated; the circuit breaker is session-isolated (#2153); project-root validators run in the sandbox and mcp-serve is fail-closed (see Chapter 7).

Chapter 10 closes Part Two: from the one-conversation lifecycle of Chapter 5, through Chapter 6's tools, Chapter 7's security, Chapter 8's context, and Chapter 9's extensions, to this chapter's verifiable contract, the agent engine's internal machinery is now complete. Part Three moves from a single machine and a single session to the message bus and multi-session orchestration, and the event vocabulary the harness planted here will be reused heavily there.


Further reading

  • docs/OCTOS_HARNESS_DEVELOPER_GUIDE.md: the harness developer guide, the entry document for external skill authors.
  • docs/OCTOS_HARNESS_ABI_VERSIONING.md: the ABI versioning contract, the stable/experimental field lists and deprecation rules (M4.6).
  • docs/OCTOS_HARNESS_MASTER_PLAN.md: the harness master plan, the roadmap across three phases (background-task trust / Web persistence and reload reliability / free-form coding and a richer runtime).
  • docs/OCTOS_HARNESS_DEVELOPER_INTERFACE.md: the developer interface conventions.
  • docs/OCTOS_HARNESS_SKILL_COMPAT.md: the skill compatibility notes.

Exercises

  1. The edge of the declarative approach: suppose your validation needs to "run a domain-specific verdict program" (parse an internal format, then assert structure). Do you extend ValidatorSpec with a new variant, or fall back to the Command validator calling an external program? How do the two choices differ on sandboxing, timeouts, and evidence retention?

  2. The Soft-contract slippery slope: soft_fail makes partial delivery a legal terminal state. If every validator on a team gets marked soft "while we're at it," how much gate value does the harness retain? What mechanism (review rules, policy lint, ledger audit) would you use to stop the slide?

  3. The one-way version gate: check_supported rejects only future versions, never past ones. If one day v2 has to delete a v1 stable field (not add one), does the default-value strategy still hold? How should the dual-version transition window be designed so v1 producers and v2 consumers coexist for a release cycle?


Version note: This chapter's baseline is octos main @ 9c157101 (verified 2026-09-03). Line numbers and code excerpts follow that commit; when reading later code, re-check crates/octos-agent/src/{validators,harness_events,abi_schema,workspace_policy,harness_errors,hooks}.rs and crates/app-skills/harness-starter-*/ first. Milestone numbers (M4.3/M4.6/M6.1/M6.3/M6.5/M6.6/M7.6/M8.6/M8.7) follow the source comments and the phase divisions of docs/OCTOS_HARNESS_MASTER_PLAN.md.

Chapter 11: octos-bus: the Message Bus, the Channel Abstraction, and Session Persistence

Positioning: This chapter goes into the octos-bus crate (currently crates/octos-bus/, roughly 40K lines of Rust source, 40,937 measured, of which 17 channel files total 18,207 lines): how one Channel trait abstracts very different messaging platforms, and how sessions, message splitting, thread-bound streaming, the durable commit observer, and the child-session contract are engineered. Prerequisite: Chapter 5. Who should read it: developers who want to understand the architecture of a multi-channel messaging platform (reader B), and contributors wiring in a new channel (reader D).

When an agent steps up from a single-user CLI to a multi-user platform, the messaging layer's complexity jumps. Telegram caps a message at 4,000 characters and Discord at 1,900; Slack formats with Block Kit and Feishu with Rich Text; email is asynchronous and WhatsApp wants template messages. octos-bus unifies all of it behind one Channel trait.


11.1 The Channel trait: one message interface

The Channel trait (crates/octos-bus/src/channel.rs:17-265) defines the interface every channel shares:

The current Channel trait has 26 methods, but only three of them lack a default implementation: name(), start(), and send(). Everything else hangs off the trait as a default, and a real channel overrides what it needs:

#![allow(unused)]
fn main() {
#[async_trait]
pub trait Channel: Send + Sync {
    fn name(&self) -> &str;
    async fn start(&self, inbound_tx: mpsc::Sender<InboundMessage>) -> Result<()>;
    async fn send(&self, msg: &OutboundMessage) -> Result<()>;
    fn max_message_length(&self) -> usize;  // default 4000, overridable
    fn is_allowed(&self, _sender_id: &str) -> bool { true }
    async fn send_typing(&self, _chat_id: &str) -> Result<()> { Ok(()) }
    fn supports_edit(&self) -> bool { false }
    async fn send_with_id(&self, msg: &OutboundMessage) -> Result<Option<String>> { ... }
    async fn edit_message(&self, ...) -> Result<()> { ... }
    async fn finish_stream(&self, ...) -> Result<()> { ... }
    async fn edit_message_bound(&self, ..., thread_id: Option<&str>) -> Result<()> { ... }
    async fn finish_stream_bound(&self, ..., thread_id: Option<&str>) -> Result<()> { ... }
    async fn send_raw_sse_bound(&self, ..., thread_id: Option<&str>) -> Result<()> { ... }
    async fn health_check(&self) -> Result<ChannelHealth> { ... }
    // + stop, send_typing_as, stop_typing, send_listening,
    //   delete_message, edit_message_with_metadata, reactions, embed, ...
}
}

This is a "wide trait, heavy defaults" design. A minimal channel works with the 3 base methods; a mature channel keeps overriding extension points such as max_message_length(), supports_edit(), send_with_id(), edit_message(), format_outbound(), and health_check(). The cost is a wide trait surface; the payoff is that every platform capability reaches the Gateway through a single abstraction.

The key methods: start() receives an mpsc::Sender<InboundMessage>, and the channel forwards incoming user messages through that sender to the agent processing layer; send() carries agent responses back out to the target channel; max_message_length() defaults to 4000, but the real implementations override it (Discord=1900, Slack=3900, Twilio=1600).

send_with_id() returns the platform message ID so the message can be edited later (for streaming, send a placeholder first and update it as tokens arrive). The default delegates to send() and returns None.

11.1.1 The three-step streaming edit

For channels that support message editing (supports_edit() returns true), octos streams output in three steps:

  1. send_with_id(): send the initial message (possibly a few tokens) and capture the platform message ID
  2. edit_message(): as the LLM streams, keep updating that same message (crates/octos-bus/src/channel.rs:85-93)
  3. finish_stream(): when the stream ends, send the final version; the default still falls back to edit_message() (crates/octos-bus/src/channel.rs:122-133)

Users watch the reply form instead of waiting for one complete blob. Telegram and Discord both run this pattern; channels without editing (email) fall back to sending the whole response once at the end.

11.1.2 thread-bound streaming: binding each turn explicitly instead of trusting a sticky map

The Channel trait's streaming-edit surface is no longer a handful of edit conveniences. It now carries three bound variants:

  • edit_message_bound(chat_id, message_id, content, thread_id)
  • finish_stream_bound(chat_id, message_id, content, thread_id)
  • send_raw_sse_bound(chat_id, json, thread_id)

The point is not one extra parameter. Under concurrent Web turns, these methods explicitly bind every streaming delta, the final message, and the raw SSE history to the originating thread_id (crates/octos-bus/src/channel.rs:107-201). The old path recovered the thread by decoding it from the message id or from a per-chat sticky map; when the same chat fires several turns in quick succession, the sticky map may already have rotated to the later turn, and the earlier turn's late delta lands in the later turn's bubble. The bound API's contract is that the caller already knows which turn this delta belongs to, so stop guessing from shared state.

sequenceDiagram
    participant Turn as Web/API turn
    participant Reporter as Stream forwarder
    participant Channel as Channel bound API
    participant UI as Client thread bubble
    Turn->>Reporter: bind originating thread_id
    Reporter->>Channel: edit_message_bound(..., thread_id)
    Reporter->>Channel: send_raw_sse_bound(..., thread_id)
    Channel->>UI: update exact thread bubble

The defaults still fall back to the old edit_message() / send_raw_sse(), so channels that don't care about threads, such as Telegram and Discord, stay compatible; the history API channel can override the bound methods and land events in the correct UI thread. One boundary to keep straight against Chapters 13 and 14: Serve/AppUI's public chat transport has already moved to /api/ui-protocol/ws; send_raw_sse_bound() is a compatibility and internal extension point kept in the bus trait, not a reason for new clients to use chat SSE. health_check() belongs to the same round of evolution: it lets the admin dashboard display channel health in one uniform way instead of scattering probes across each channel's own admin interface (crates/octos-bus/src/channel.rs:245-251; the ChannelHealth enum sits at 253-265 in the same file).

11.1.3 The AgentHandle symmetry

The bus uses AgentHandle / BusPublisher (crates/octos-bus/src/bus.rs:8-77) to connect channels to the agent processing layer:

#![allow(unused)]
fn main() {
// AgentHandle holds both directions
struct AgentHandle {
    in_rx: Receiver<InboundMessage>,      // the agent receives messages here
    out_tx: Sender<OutboundMessage>,      // the agent sends responses here
}

struct BusPublisher {
    in_tx: Sender<InboundMessage>,         // channels send messages to the agent here
    out_rx: Receiver<OutboundMessage>,     // channels receive agent responses here
}
}

The symmetry pays off at shutdown: when every Channel closes (all inbound_tx dropped), inbound_rx.recv() returns None, the agent processing layer learns there are no more messages, and it exits gracefully. No separate shutdown signal needed.

11.1.4 is_allowed: authenticating the sender

is_allowed() (crates/octos-bus/src/channel.rs:27-30) checks whether a sender may use the agent before a message is routed. The default returns true (everyone allowed); each channel can override it with custom logic, for example Telegram restricting access to specific chat_ids.


11.2 Message coalescing: the 5-level split strategy

When an agent reply exceeds a channel's character limit, it has to be split into shorter messages. The octos-bus coalescing algorithm (crates/octos-bus/src/coalesce.rs:26-120) tries five priority levels:

flowchart TD
    Input["Long message"] --> P1["1. Paragraph split \\n\\n"]
    P1 -->|"found"| Emit1["send paragraph"]
    P1 -->|"not found"| P2["2. Newline split \\n"]
    P2 -->|"found"| Emit2["send line"]
    P2 -->|"not found"| P3["3. Sentence split . + space"]
    P3 -->|"found"| Emit3["send sentence"]
    P3 -->|"not found"| P4["4. Space split"]
    P4 -->|"found"| Emit4["send word run"]
    P4 -->|"not found"| P5["5. Hard cut<br/>UTF-8 safe boundary"]
    P5 --> Emit5["send truncated block"]

Figure 10-1: the 5-level message split strategy. Prefer semantic boundaries; the hard cut is the last resort.

MAX_CHUNKS = 50 keeps an extreme message from shattering into hundreds of tiny ones, which would be a DoS vector. When the cap is exceeded, the code does not append more text after the last chunk; it inserts a separate "[message truncated - N chars omitted]" truncation block (crates/octos-bus/src/coalesce.rs:47, with the MAX_CHUNKS constant at line 27 of the same file and a warn! log on truncation).

UTF-8 safety: the hard cut backs off with is_char_boundary() to a safe character boundary (the same strategy as octos-core's truncate_utf8; see Chapter 2).

Platform-specific limits (crates/octos-bus/src/coalesce.rs:5-24):

ChannelCharacter limitConfig
Telegram4,000ChunkConfig::telegram()
Discord1,900ChunkConfig::discord()
Slack3,900ChunkConfig::slack()
Emailno limitcoalescing not invoked
Default4,000ChunkConfig::default_limit()

11.2.1 find_break_point: the core split logic

find_break_point() (crates/octos-bus/src/coalesce.rs:87-118) is the heart of the split, but the actual cutting happens in two steps: first carve a UTF-8-safe search window within max_chars, then find the most natural break inside that window.

#![allow(unused)]
fn main() {
let mut limit = config.max_chars.min(remaining.len());
while limit > 0 && !remaining.is_char_boundary(limit) {
    limit -= 1;
}
let search = &remaining[..limit];
let break_at = find_break_point(search);

chunks.push(remaining[..break_at].trim_end().to_string());
remaining = remaining[break_at..].trim_start_matches('\n');
if remaining.starts_with(' ') && !remaining.starts_with("  ") {
    remaining = &remaining[1..];
}
}

Inside, find_break_point(search) runs rfind() (right to left) on \n\n, \n, . , then a space, and only hard-cuts when no natural boundary exists. Breaks land as close to the limit as possible while never splitting a multibyte character. The trim_end(), the trim_start_matches('\n'), and the "skip at most one leading space" handling keep the outgoing chunks clean instead of dragging raw separators into the head of the next message.


11.3 Session management

11.3.1 The Session struct

Session (crates/octos-bus/src/session.rs:587-608) is the persistence unit of a conversation:

#![allow(unused)]
fn main() {
pub struct Session {
    pub key: SessionKey,               // session identity (channel:chat_id)
    pub parent_key: Option<SessionKey>, // fork origin
    pub topic: Option<String>,          // multi-topic support
    pub title: Option<String>,          // sidebar title
    pub title_manual: bool,             // manual titles survive auto-overwrite
    pub child_contracts: Vec<ChildSessionContract>,
    pub messages: Vec<Message>,         // conversation history
    pub summary: Option<String>,        // session summary
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}
}

11.3.2 JSONL persistence and file naming

Session persistence in the current source is a bit more than "one JSONL file"; two facts anchor it.

First, the first line of a JSONL file is not a message. It is SessionMeta metadata, and only the lines after it are Messages (crates/octos-bus/src/session.rs:560-584, crates/octos-bus/src/session.rs:1365-1381, crates/octos-bus/src/session.rs:2992-3060). The format is a light log: one header line of schema/meta plus message lines, not a pure message stream. SessionMeta now carries title, title_manual, and child_contracts, so sidebar titles and background child-task state don't have to be smuggled through ordinary message text.

Second, the current code supports both the old and the new layout:

  1. SessionManager still supports the legacy flat layout: data/sessions/{encoded-key}[_{hash}]?.jsonl (crates/octos-bus/src/session.rs:1096-1146)
  2. The SessionHandle used by SessionActor prefers the per-user layout: data/users/{encoded_base_key}/sessions/{topic_or_default}.jsonl, migrating old files on open (crates/octos-bus/src/session.rs:1611-1819)

Only in the legacy flat layout is the file name built from these two parts:

  1. The percent-encoded SessionKey (crates/octos-bus/src/session.rs:129-140): path-unsafe characters in the key (/, :, #) become %2F, %3A, %23
  2. An FNV-1a 64-bit hash suffix (crates/octos-bus/src/session.rs:116-127, crates/octos-bus/src/session.rs:1554-1610): when the encoded name is long enough to need truncation, a stable hash is appended so truncated names with the same prefix don't collide

A long key in the old layout may land as telegram%3A12345_0123ABCD....jsonl; the new layout looks like users/telegram%3A12345/sessions/default.jsonl.

Schema version: CURRENT_SESSION_SCHEMA = 1 (crates/octos-bus/src/session.rs:15-16), reserved for future format migration.

Writes also split into two classes:

  • Routine message appends go through append_to_disk(): a new file writes metadata first, then appends message lines one by one (crates/octos-bus/src/session.rs:1312-1388, crates/octos-bus/src/session.rs:2992-3060)
  • Whole-session rewrites go through rewrite(), using the write-then-rename atomic replacement pattern (crates/octos-bus/src/session.rs:1914-1963, crates/octos-bus/src/session.rs:2862-2987)

The rewrite temp file name got a concurrency fix: rewrite_tmp_path() builds {target}.jsonl.{pid}-{seq}.tmp from the process PID plus a monotonic counter, so multiple background child tasks rewriting the same parent session never share a single .tmp file (crates/octos-bus/src/session.rs:90-117). This is a correctness fix, not a performance one: a shared temp path lets two writers truncate each other, only one rename survives, and the other child task gets mislabeled as orphaned.

The 10MB file limit: a single session file is capped at 10MB, so runaway conversation history can't eat the disk (crates/octos-bus/src/session.rs:792-793, crates/octos-bus/src/session.rs:1197-1208, crates/octos-bus/src/session.rs:1644-1649).

11.3.3 The /new fork

When a user sends /new to start a fresh session, the underlying call is fork(parent_key, new_chat_id, copy_messages) (crates/octos-bus/src/session.rs:1972-2010). This is not "create a blank session":

  1. Copy the most recent copy_messages messages from the parent session
  2. Record parent_key
  3. Rewrite a new session file under the new key

/new in the current implementation is thus closer to "a branch carrying recent context" than "inherit config only, no history".

11.3.4 SessionManager and the LRU cache

SessionManager (crates/octos-bus/src/session.rs:903-905) manages the session cache the admin and command side sees; on the live message path, SessionActor instead holds its own SessionHandle, so active sessions don't all share one big lock (crates/octos-bus/src/session.rs:2426-2530).

  • LRU memory cache: active sessions stay in memory, cutting disk I/O
  • Lazy loading: inactive sessions load from disk on demand
  • Layout compatibility: scans both the legacy flat layout and the per-user layout
  • User-list performance bound: list_top_level_sessions*() skips internal topics such as child-* and *.tasks, so a user directory full of background child sessions doesn't slow down /api/sessions (crates/octos-bus/src/session.rs:965-1005, crates/octos-bus/src/session.rs:934-947)
  • Same-key write serialization: persist_message_through_canonical_path() serializes same-session writes from SessionActor, ApiChannel, and the /chat path through a per-key Tokio mutex, so independent SessionHandles never read the same length and return duplicate sequence numbers (crates/octos-bus/src/session.rs:2332-2420)

11.3.5 thread_id persistence: new writes fail closed, old records get load-time synthesis

The AppUI chat surface no longer just appends messages into a session; it groups messages into threads. The current rules live in derive_thread_id_for_new_write() and synthesize_thread_ids() (crates/octos-bus/src/session.rs:288 for derive_thread_id_for_new_write, and crates/octos-bus/src/session.rs:328 for synthesize_thread_ids):

PathUserAssistant / ToolSystem
new writeclient_message_id, or UUIDv7 if absentcaller must pre-stamp thread_id, otherwise the write is rejectedNone
legacy loadbackfilled from the old client_message_id or synth_{seq}inherits the current thread, synthesizing a stable id if missingNone

The split matters. The old implementation derived the thread for an Assistant/Tool write by "looking back at the most recent user"; under rapid-fire concurrent turns the in-memory history may already have been rewritten by another sibling user, and the assistant lands in the wrong bubble. The new write path therefore fails closed: an Assistant/Tool write without a pre-bound thread_id returns an error and bumps the octos_session_persist_total{outcome="rejected_unbound_assistant"} metric (crates/octos-bus/src/session.rs:1676-1815, crates/octos-bus/src/session.rs:3061-3110).

Legacy JSONL can't be held to this rule, because the historical files never had a thread_id field. At load time, synthesize_thread_ids() backfills old records in memory only, so old transcripts render by thread; the next new write then enters the fail-closed rule. In other words, octos-bus separates "compatibility with historical data" and "correctness of new writes" into two paths.

11.3.6 The durable commit observer: message/persisted fires only after a real commit

MessageCommitObserver is the Session layer's durable commit hook for the UI Protocol (crates/octos-bus/src/session.rs:18-89). The order inside add_message_with_seq():

  1. Derive thread_id for a User if needed, or require that Assistant/Tool is already pre-bound.
  2. append_to_disk() first; on failure, return immediately.
  3. Then update the in-memory Session::messages.
  4. Finally fire the observer with the SessionKey, the Message, and the committed sequence.
flowchart TD
    Write["add_message_with_seq"] --> Stamp["stamp / validate thread_id"]
    Stamp --> Disk["append_to_disk"]
    Disk -->|fail| Err["return error<br/>no observer"]
    Disk -->|ok| Memory["push in-memory mirror"]
    Memory --> Observer["MessageCommitObserver"]
    Observer --> UI["UI Protocol message/persisted"]

An observer failure or panic does not roll the message back, because the durable commit already happened; it is best-effort fan-out (crates/octos-bus/src/session.rs:71-89). That boundary heads off a common misreading: message/persisted does not mean "about to be written"; it means "this line is now durably visible". The octos-cli UI Protocol tests pin this ordering and the dedup behavior (crates/octos-cli/src/api/ui_protocol_ledger.rs and the ui_protocol_{transport,ledger,progress,task_output,reasoning_effort,alpha2_bridge,alpha9_bridge}.rs split-file family; legacy message/persisted accounting sits at crates/octos-cli/src/api/ui_protocol_ledger.rs:294-330, the recovery-period skip at 1269-1423).

11.3.7 The child-session contract: background child tasks are not tracked by message text alone

Session metadata also persists ChildSessionContract, which writes the lifecycle of background spawns and subagents back into the parent session (crates/octos-bus/src/session.rs:519-546, crates/octos-bus/src/session.rs:560-584). It records:

  • task_id, task_label
  • parent_session_key, child_session_key
  • workflow_kind, current_phase
  • terminal_state: Completed / RetryableFailure / TerminalFailure
  • join_state: Joined / Orphaned
  • failure_action: Retry / Escalate
  • output_files

A child session is not "a few ordinary messages plus a parent_key" and done. The parent needs a durable contract to decide whether a background task finished, whether it joined, and whether a failure should retry or escalate. The contract also explains why the rewrite temp path must be unique: several child tasks may write terminal outcomes into the same parent session metadata at the same time.


11.4 Coalescing source walkthrough

The full implementation of split_message() (crates/octos-bus/src/coalesce.rs:34-82) shows how it balances safety and readability:

#![allow(unused)]
fn main() {
pub fn split_message(text: &str, config: &ChunkConfig) -> Vec<String> {
    if text.len() <= config.max_chars {
        return if text.is_empty() { vec![] } else { vec![text.to_string()] };
    }

    let mut chunks = Vec::new();
    let mut remaining = text;

    while !remaining.is_empty() {
        if chunks.len() >= MAX_CHUNKS {
            chunks.push(format!(
                "[message truncated - {} chars omitted]",
                remaining.len()
            ));
            break;
        }

        if remaining.len() <= config.max_chars {
            chunks.push(remaining.to_string());
            break;
        }

        let mut limit = config.max_chars.min(remaining.len());
        while limit > 0 && !remaining.is_char_boundary(limit) {
            limit -= 1;
        }
        let search = &remaining[..limit];
        let break_at = find_break_point(search);

        chunks.push(remaining[..break_at].trim_end().to_string());
        remaining = remaining[break_at..].trim_start_matches('\n');
        if remaining.starts_with(' ') && !remaining.starts_with("  ") {
            remaining = &remaining[1..];
        }
    }

    chunks
}
}

Design points:

  1. Early return: an empty string yields an empty Vec; a short message yields a single chunk
  2. UTF-8-safe window first, semantic break second: find_break_point() never doubles as "logical break plus encoding boundary"
  3. Boundary cleanup: trim_end(), leading-newline stripping, and at most one skipped space keep the visual seam between chunks natural
Window semantics: carve first, then find the point

The step most easily missed in the loop is the "window". split_message() does not search for a break across all remaining text; it first builds search = &remaining[..limit], a search window of at most max_chars, and find_break_point() runs rfind() only inside it (crates/octos-bus/src/coalesce.rs:72-73). The two responsibilities separate: the window owns encoding safety (the is_char_boundary() fallback, crates/octos-bus/src/coalesce.rs:68-71), the break function owns semantic naturalness (\n\n → \n → . → space → hard cut, crates/octos-bus/src/coalesce.rs:87-118). Fold them into one function and every candidate break re-checks the boundary, with an easy miss on the "exactly at the limit" path.

A second detail: find_break_point() rejects position 0. A break found by rfind at 0 is skipped and the next boundary level is tried (crates/octos-bus/src/coalesce.rs:97-109). That guarantees forward progress: if a paragraph boundary sits exactly at the start of the text, a cut there would emit an empty chunk and the loop would sit at the origin forever.

The cleanup after the cut deserves its own look: trim_end() only works the chunk tail, trim_start_matches('\n') eats the newlines accumulated at the seam, and then "at most one leading space is skipped, but two spaces stay" (crates/octos-bus/src/coalesce.rs:76-78). Two spaces mean a hard line break in Markdown; skipping one would change the rendering semantics. Skipping exactly one space is the compromise between "visually clean between blocks" and "don't break formatting".

Deduplication versus coalescing

Coalescing answers "one message too long"; deduplication answers "one message received twice". Webhook platforms (Feishu, Twilio, WeCom) can redeliver the same event on timeout retry, and MessageDedup records seen message IDs in an LRU cache of capacity 1,000 with a 60-second TTL (crates/octos-bus/src/dedup.rs:12-25; is_duplicate at lines 42-61). When the Discord gateway reconnects and replays events, the same MessageDedup instance also covers it at crates/octos-bus/src/discord_channel.rs:32. The two mechanisms are orthogonal: dedup at the inbound entrance, splitting at the outbound exit, each owning one end. Without entrance dedup, one duplicate message splits into twice the chunks; without exit splitting, any over-limit message is rejected outright by the platform API.

11.4.1 Unicode-safe boundary detection

The hard-cut branch (level 5) of find_break_point() uses the same character-boundary fallback as octos-core's truncate_utf8:

#![allow(unused)]
fn main() {
// hard cut: back off from max_len to a safe UTF-8 character boundary
let mut limit = max_len;
while limit > 0 && !text.is_char_boundary(limit) {
    limit -= 1;
}
limit
}

Split a message mixing Chinese and emoji on Telegram (4,000-character limit) and this guarantee holds: the cut never lands inside a 4-byte emoji and produces invalid UTF-8, so the follow-up API call never fails on encoding.


11.5 Channel implementations at a glance

octos-bus compiles each channel behind a feature flag. Each one implements the concrete methods of the Channel trait:

ChannelConnectionDistinct capabilities
TelegramLong polling (teloxide)message editing, AtomicBool graceful shutdown
DiscordWebSocket gateway (serenity)message deduplication (MessageDedup)
SlackWebSocket (tokio-tungstenite)Block Kit formatting
WhatsAppNode.js bridge WebSocketBaileys bridge, standalone bridge process
EmailIMAP/SMTP (async-imap + lettre)async send/receive, attachments
Feishu / LarkWebSocket / webhook + axumencrypted-message verification, regional endpoints
TwilioWebhook/API (axum)SMS/MMS/RCS/WhatsApp Business
WeComHTTP webhook (axum)encrypted messages
MatrixHTTP APIAppService mode, multi-user bridging
WeCom BotWebSocket long connectiongroup-robot channel
QQ BotWebSocket gatewayOfficial QQ Bot API v2
WeChatWeChat bridge WebSocketwechat-bridge subprocess integration
APIREST / UI Protocol WebSocket / legacy event hook (axum)programmatic access and the AppUI control plane
DingTalkcustom-robot webhook sending + outgoing-robot webhook receiving (axum)caches the session-level sessionWebhook for replies
LINEwebhook receiving + Messaging API sending (axum)HMAC-SHA256 signature verification
Matrix UserClient-Server /sync long polling (reqwest)user-account mode, no AppService registration; compiled under the matrix feature
CLIstdin / stdoutlocal test channel; no separate feature, always compiled

Four late additions each deserve a paragraph of positioning.

DingTalk (crates/octos-bus/src/dingtalk_channel.rs, 544 lines) runs a two-way pattern: send through a custom-robot webhook, receive through an outgoing-robot webhook. The crux is sessionWebhook: an outgoing event carries a short-lived session-level webhook URL, the channel caches it per session, and replies prefer that cached address over the globally configured webhook (crates/octos-bus/src/dingtalk_channel.rs:281, send-priority decision at 188-199; with no cache and no config, the error fires at line 196). The reason is DingTalk's outgoing model itself: a reply must go back to the exact robot conversation that initiated the exchange, which a global address cannot do, and the short-lived URL demands a fallback once the cache expires.

LINE (crates/octos-bus/src/line_channel.rs, 826 lines) is the standard webhook + Messaging API pair, and its security chain is signature verification: HMAC-SHA256 over the raw request body, Base64, then a constant-time comparison against the X-Line-Signature header (crates/octos-bus/src/line_channel.rs:87-95, with ct_eq from the subtle crate). Constant-time comparison rather than == blocks timing side channels from guessing the signature byte by byte; the raw body rather than a re-serialized string prevents JSON canonicalization differences from failing the check. Both choices are the standard answers platforms arrive at after repeated incidents.

Matrix User (crates/octos-bus/src/matrix_user_channel.rs, 1,525 lines) and the Matrix row in the section 11.5 table are two access modes for one platform. AppService mode requires registration on the homeserver side; user-account mode needs only an access token or password login, then long-polls the Client-Server /sync API with a 30-second timeout (SYNC_TIMEOUT_MS at crates/octos-bus/src/matrix_user_channel.rs:44). Long polling lets a self-hosted server without push permissions still receive messages near-real-time: the request hangs open, returns only when an event arrives, and the next one fires immediately. It has no separate Cargo feature and compiles under matrix, because the two share Markdown-to-HTML rendering and path-encoding infrastructure.

CLI (crates/octos-bus/src/cli_channel.rs, 137 lines) is the minimal reference implementation: line-based stdin reads and a stdout prompt (crates/octos-bus/src/cli_channel.rs:52-57), no network stack, no auth, no feature gate, always compiled. It exists to keep the Channel trait's minimal contract verifiable: a channel implementing only name(), start(), and send() runs the whole pipeline, and it is the cheapest template for new channel work.

Every channel implementation stands alone. A Telegram bug cannot touch Discord, because they are different code paths compiled behind different feature flags. One caveat: the CLI readline of octos chat is not among octos-bus's Cargo feature channels; the bus-side feature-gated channels currently number 15 (api, telegram, discord, slack, whatsapp, email, feishu, dingtalk, line, twilio, wecom, matrix, wecom-bot, qq-bot, wechat), with crates/octos-bus/src/dingtalk_channel.rs and crates/octos-bus/src/line_channel.rs the newer arrivals; crates/octos-bus/src/matrix_user_channel.rs has no separate feature and compiles under matrix; crates/octos-bus/src/cli_channel.rs is always compiled. Those three classes add up to 17 channel source files. This isolation is why most of octos-bus's roughly 40K lines of Rust source are independent per-channel implementations.


Engineering decision: why JSONL instead of SQLite or one JSON file

Option one: SQLite

Pros: structured queries, indexes, transactions, easy cross-session analysis Cons: needs an explicit schema/migration layer; session files stop being inspectable with text tools; heavier abstraction than the current per-session, key-based access pattern

Option two: one JSON file

Pros: the most intuitive to implement, simple serialization/deserialization Cons: every write rewrites the whole file; the most fragile crash recovery; the likeliest hot lock under many sessions

Option three: JSONL (octos's choice)

Pros:

  • one metadata first line plus per-line messages supports both append and whole-session rewrite
  • easy to keep both paths, legacy flat layout and per-user layout
  • one file per session matches the "read/write by session key" access pattern
  • backup, migration, and debugging all work directly at the filesystem level

Cons:

  • no index; cross-session queries scan every file
  • no database-grade transactions; weak at complex queries

Why this option: reading the current source, octos's session access pattern is almost always "read one session by key, append new messages, rewrite the whole session when necessary, migrate layout on demand". JSONL covers exactly those paths and fits SessionActor's per-session file ownership naturally.


11.6 Persistence engineering details

11.6.1 FNV-1a hashing

In the legacy flat layout, when an encoded SessionKey must be truncated, the file name gets an FNV-1a 64-bit hash suffix (crates/octos-bus/src/session.rs:116-127, crates/octos-bus/src/session.rs:1554-1610). FNV-1a is not cryptographic; its virtues are a tiny implementation and stability across Rust versions. It serves no security purpose (no collision-attack resistance), only "truncated file names stay distinguishable".

#![allow(unused)]
fn main() {
fn fnv1a_64(data: &[u8]) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;  // FNV offset basis
    for &byte in data {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(0x100000001b3);  // FNV prime
    }
    hash
}
}

11.6.2 Percent-encoding

encode_path_component() (crates/octos-bus/src/session.rs:129-140) encodes the special characters of a SessionKey into URL-safe form. This stops a key like telegram:12345 from being read as a directory path by the filesystem (: is special on some of them).

11.6.3 write-then-rename atomicity

The whole-session rewrite() path gets atomicity from two steps:

  1. Write a unique temp file {session_file}.{pid}-{seq}.tmp
  2. rename() the temp file onto the real one

On Unix/Linux, rename() is atomic: either it fully succeeds (the new file replaces the old one) or it fully fails (the old file stays untouched). A crash before rename() leaves only an orphaned .tmp file; the real session file is unaffected.


11.7 Chapter recap

  1. The Channel trait: 26 methods today, but only name(), start(), and send() lack defaults; streaming edits, typing, embeds, and health checks are an override-as-needed extension layer.
  2. Coalescing: 5-level semantic splitting (paragraph → newline → sentence → space → hard cut), MAX_CHUNKS=50 against DoS, UTF-8 safe, with a separate truncation chunk appended past the cap.
  3. Session: the first line of a JSONL file is metadata, not a message; both the legacy flat layout and the per-user layout are supported, and /new/fork copies the most recent N messages and records parent_key.
  4. Thread binding: the new write path requires Assistant/Tool to pre-bind thread_id, while legacy loads only backfill in memory; the bound channel API keeps concurrent-turn streaming deltas out of the wrong bubble.
  5. The durable observer and the child contract: message/persisted fires after the disk write and the in-memory mirror update; background child tasks persist terminal/join/failure state through ChildSessionContract, not ordinary message text.

Further reading

  • Server-Sent Events: MDN "Using server-sent events": the streaming push pattern
  • Telegram Bot API: https://core.telegram.org/bots/api: API details of the Telegram channel
  • JSONL format: https://jsonlines.org/: the line-delimited JSON specification

Exercises

  1. The edge of the channel abstraction: some channels support rich text (Slack Block Kit, Feishu Rich Text), but Channel::send() accepts plain text only. How would you extend the trait to support rich text while staying backward compatible?
  2. Session recovery: if the octos process crashes, the last line of a JSONL file may be incomplete. How would you implement crash recovery?

Version note: This chapter is based on the current main branch of ../octos. The octos-bus crate lives at crates/octos-bus/src/; compared with earlier versions, this chapter has been updated for thread-bound streaming, the per-user session layout, the durable commit observer, the child-session contract, the per-key persist lock, and the unique rewrite temp path of main.


Version note

This chapter's baseline is octos main @ 9c157101 (verified 2026-09-03). Against the older draft's "about 30K lines, 14 channels": the crate now stands at roughly 40K lines (40,937 lines, 18,207 of them in channel files, 17 in total), adding the DingTalk and LINE channels and the Matrix User account mode; crates/octos-bus/src/session.rs has grown to 3,417 lines, with the SessionHandle family concentrated around lines 2400-3100; on the octos-cli side, the former crates/octos-cli/src/api/ui_protocol.rs has been split into transport, ledger, and other files, 8 in total (7 implementation files plus 1 test file crates/octos-cli/src/api/ui_protocol_tests.rs). Line references in this chapter follow that baseline.

The line drift in crates/octos-bus/src/session.rs is not simple growth; it is an ownership-model refactor. In the old draft, reads and writes converged on the SessionManager big lock; today's code hands the online path to SessionHandle (crates/octos-bus/src/session.rs:2329 onward, concentrated around lines 2400-3100), with SessionActor holding an independent handle per session and zero lock contention across sessions (the doc comment above struct SessionHandle states this motivation). The former manager retreats to two duties: admin-side list queries, and cross-path write entry points like persist_message_through_canonical_path() (line 2388) that need per-key Tokio mutex serialization (the lock table at line 2360). The file grew mainly from the migration state machine (lines 2441-2460, three real cases) and the persistence branches the child-session contract brought in, not from unstructured accretion.

Chapter 12: The Concurrency Model: A Production Three-Layer Scheduler

Positioning: This chapter explains how octos's concurrency model works in three cooperating layers: the Tokio layer's session actors, semaphore admission, and tool-batch concurrency; the supervisor layer, which turns long-horizon orchestration into a restart-surviving event ledger plus continuation scheduling; and the peer/lease layer, which manages multiple agents through the process metaphor and leases. Prerequisites: Chapter 5 (Agent Loop), Chapter 10 (Harness and the event ABI). Who should read it: developers who want to see how Rust async concurrency lands in a production system, and operators who need to tune gateway concurrency parameters. The fleet state machine details are in Chapter 16; goal/peer orchestration semantics are in Chapter 18.

12.1 Start from a Set of Numbers

Split the concurrency-related source by responsibility and count it: 17 files, 74692 lines, 722 public symbols, in three layers.

LayerFilesLinesKey symbolsRepresentative files
① Tokio layer (session actor / semaphore / tool concurrency / shutdown)525154170crates/octos-cli/src/session_actor.rs 10094 lines, crates/octos-agent/src/agent/execution.rs 4730 lines
② supervisor layer (the ten files of autonomy/)1045544454crates/octos-cli/src/autonomy/agent_orchestrator.rs 33639 lines, crates/octos-cli/src/autonomy/supervisor_store.rs 3277 lines
③ peer/lease layer2399498crates/octos-cli/src/peers/mod.rs 3186 lines, crates/octos-fleet/src/records.rs 808 lines

The three numbers tell one story: concurrency in octos moved past the "how to use Tokio" stage long ago. The Tokio layer holds one third of the lines; the bulk is the supervisor layer. 45,000 lines of code answer a question Tokio itself does not touch: after the process restarts, what happens to orchestration state?

flowchart TB
    subgraph L3["③ peer/lease layer"]
        PEERS["crates/octos-cli/src/peers/mod.rs<br/>peer staging and addressing"]
        LEASE["crates/octos-fleet/src/records.rs<br/>Lease / Attempt state machine"]
    end
    subgraph L2["② supervisor layer (autonomy/, 45544 lines)"]
        STORE["SupervisorStore<br/>JSONL event ledger + snapshot"]
        SCHED["MasterContinuationScheduler<br/>dedupe + priority continuation"]
        ORCH["InProcessAgentOrchestrator"]
        WAKE["crates/octos-cli/src/autonomy/fleet_wake.rs<br/>outbox consumer"]
        MON["crates/octos-cli/src/autonomy/monitor_runtime.rs<br/>zero-token monitor"]
    end
    subgraph L1["① Tokio layer (25154 lines)"]
        GW["crates/octos-cli/src/commands/gateway/gateway_runtime.rs<br/>semaphore admission"]
        REG["ActorRegistry<br/>session lifecycle"]
        ACTOR["SessionActor ×N<br/>one tokio task per session"]
        TOOLS["crates/octos-agent/src/agent/execution.rs<br/>tool batch concurrency"]
        TS["TaskSupervisor<br/>spawn_only state"]
    end
    GW -->|"Semaphore permit"| REG --> ACTOR
    ACTOR --> TOOLS --> TS
    TS -->|"lifecycle events"| STORE
    SCHED -->|"continuation dispatch"| ACTOR
    ORCH --> TS
    STORE --> SCHED
    WAKE --> SCHED
    MON -->|"External continuation"| SCHED
    ORCH --> PEERS
    PEERS --> LEASE

The chapter follows the layering: the Tokio layer's session state ownership and concurrency boundaries first (12.2-12.5), then why the supervisor layer exists and how it is built (12.6), then the peer/lease layer's role as concurrency primitives (12.7), closing with graceful shutdown (12.8).

12.2 The Tokio Layer: Session Actors and Layered spawn

In single-user CLI mode the Agent executes sequentially; there is no concurrency problem. In Gateway or Serve mode, multiple users send messages at once, and each session interleaves cancellations, background subtask results, and status delivery. octos's answer is not to put a lock on shared state but to introduce the session actor. Each session is owned exclusively by one long-lived tokio task, and the core state has exactly one owner.

The entry point is ActorRegistry (crates/octos-cli/src/session_actor.rs:2524). It holds the actor table, a factory, and one semaphore; when a new session arrives it creates an actor and calls tokio::spawn(actor.run()) (crates/octos-cli/src/session_actor.rs:4122). The actor itself, struct SessionActor at crates/octos-cli/src/session_actor.rs:4455, holds the session key, the tool registry, the working directory, and two shutdown flags (covered in 12.8). The outside world reaches the actor's mailbox through ActorHandle (crates/octos-cli/src/session_actor.rs:2502); mailbox messages are the ActorMessage enum (crates/octos-cli/src/session_actor.rs:2443):

#![allow(unused)]
fn main() {
pub enum ActorMessage {
    /// A user message to process.
    Inbound { message: InboundMessage, /* … */ },
    BackgroundResult { /* … */ },
    TaskStatusChanged { /* … */ },
    ApprovalExpired { request_id: String },
    Cancel,
}
}

Five messages cover every event class an actor must respond to: new input, background subtask results, task state changes, approval expiry, cancellation. Two messages for the same session can never modify history concurrently, because both queue in the same actor's mailbox and the actor processes them one at a time.

Layered spawn is this layer's backbone. tokio::spawn() appears at four levels in the source:

  1. Session level: ActorRegistry starts an actor per new session, long-lived (crates/octos-cli/src/session_actor.rs:4122).
  2. Message level: the actor spawns the current message's main Agent call as a separate task and keeps polling the mailbox, ready to receive Cancel and background results at any time.
  3. Tool level: when one turn carries multiple tool calls, each tool gets its own task (crates/octos-agent/src/agent/execution.rs:701), aggregated by the batch policy (12.4).
  4. Background level: the spawn tool's background mode starts a long-lived subagent whose visible state goes to TaskSupervisor (12.5).

The gateway side adds two auxiliary spawns: Ctrl+C signal handling (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1653) and async refresh of the system prompt (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1713). Dispatch parameters flow from gateway to actor through DispatchParams (crates/octos-cli/src/session_actor.rs:86).

The concurrency/serialization boundary is therefore sharp: fully concurrent across sessions (one task per actor); serialized within a session (mailbox queueing); parallel or serial per tool batch depending on the admission policy; background tasks leave the main conversation flow and rejoin through status reports.

Engineering decision: shared Mutex vs spawn-per-message vs Session Actor

The trade-off among three options:

  • Shared Mutex<SessionState>: fastest to implement, but lock granularity grows with the state; one message holding the lock across an await blocks other sessions' messages too, and cancel signals get harder to prioritize. The v1 draft described this layer as "per-session Mutex serialization"; the current source is no longer that model.
  • spawn-per-message (one stateless task per message): maximum concurrency, but session history, the tool registry, and the workspace must move to external shared storage, and state consistency becomes a locking problem again.
  • Session Actor: state ownership is unique, messages queue naturally, and a cancellation is just one Cancel in the mailbox. The cost is that the actor must manage its own lifecycle (idle recycling, preserving profile overrides across death-and-rebirth, see the ActorHandle field comments).

octos picks the third; the cost is concentrated in ActorRegistry, and business code only ever faces ActorMessage.

12.3 Semaphore Admission: max_concurrent_sessions

The number of sessions needs an upper bound. The gateway creates a semaphore at startup with capacity taken straight from configuration:

#![allow(unused)]
fn main() {
// Semaphore to bound concurrent session processing
let concurrency_semaphore = Arc::new(Semaphore::new(gw_config.max_concurrent_sessions));
}

The location is crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1731-1732, and the semaphore is handed to ActorRegistry::new immediately after. The limit comes from the max_concurrent_sessions config key, declared at crates/octos-cli/src/config.rs:1548-1549; the default function default_max_concurrent_sessions() is at crates/octos-cli/src/config.rs:1633 and its body returns the literal 10 (verified in this session). Startup logs print the value (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1666).

The permit is consumed not in the gateway but at the actor's message-processing entry: two self.semaphore.acquire().await sites at crates/octos-cli/src/session_actor.rs:7485 and crates/octos-cli/src/session_actor.rs:9293. That placement decides the queueing behavior: when more than 10 sessions are processing messages simultaneously, the 11th session's message task suspends on acquire() instead of being rejected; the actor stays alive and keeps receiving messages, only new message processing is held back by the semaphore. When one active session finishes processing and releases its permit, the next queued one gets it automatically.

Putting admission at the message-processing layer rather than session creation is deliberate: idle sessions consume no concurrency budget, and all 10 slots go to sessions actually running LLM calls.

12.4 Tool Concurrency: Three Batch Admission Policies

When a single LLM response carries multiple tool calls, execute_tools (crates/octos-agent/src/agent/execution.rs:2483, visibility pub(super), a module-internal API) does not parallelize blindly. Each tool reports itself as Safe (read-only, no side effects) or Exclusive (writes) via concurrency_class, and the executor picks one of three policies based on the whole batch's composition (module docs crates/octos-agent/src/agent/execution.rs:7-26):

  • All-Safe batch: every call is tokio::spawned as an independent task (crates/octos-agent/src/agent/execution.rs:701), and futures::future::join_all aggregates while preserving call order (crates/octos-agent/src/agent/execution.rs:2992).
  • All-Exclusive batch: executed serially in the LLM's call order; after the first error (including hook rejections and panics) the remaining calls are skipped, each receiving a synthesized "cancelled because a sibling failed" result, so every tool_call_id gets an answer.
  • Mixed batch (#1766): phase one runs all Safe calls in parallel, phase two runs the Exclusive calls serially in original order, and results are reassembled in the original call order.

The parallel path also carries a uniform timeout: join_parallel_handles (unrelated to crates/octos-cli; it starts at crates/octos-agent/src/agent/execution.rs:2959) applies the same deadline to every handle; on timeout it calls abort() first, waits a bounded grace period for cleanup, then returns a synthesized timeout result. The LLM always sees a one-to-one list of tool results; parallelism details never leak.

The two gates (semaphore and batch admission) address overload at different granularities, with different criteria. The semaphore gate's criterion is resources: LLM calls are expensive and slow, 10 concurrent sessions roughly matches the safe watermark of upstream quota and memory, past that you queue, and queueing is harmless. Batch admission's criterion is semantics: parallelism itself has no cost problem; the problem is order dependencies among Exclusive tools (write-then-write, write-then-read on the same file), where out-of-order execution is not slow but wrong. The semaphore therefore handles excess with waiting, and batch admission handles conflict by degrading to serial: one is backpressure, the other a correctness defense. Mixing the two produces a classic misreading: someone sees tools executing serially and concludes concurrency is insufficient, when in fact an Exclusive member is protecting semantics. The discriminator is the batch's composition: an all-Safe batch always runs in parallel; if anything runs serially, an Exclusive is involved (before #1766 mixed batches were wholly serial; after, only the necessary part is serial, which is the entire content of that optimization).

A subagent's concurrency shape is decided by the spawn tool's mode parameter: "background" (the default, default_mode() at crates/octos-agent/src/tools/spawn.rs:1929) or "sync" (field definition at crates/octos-agent/src/tools/spawn.rs:1855, JSON schema at :3004). Sync mode blocks the current turn until the subagent finishes, and its result enters this turn's context directly; background mode detaches the subagent from the main conversation flow, and its completion returns to the actor mailbox as a BackgroundResult message. The former fits "the next step depends on the subtask's output"; the latter fits "fire and collect later."

12.5 The spawn_only Lifecycle: TaskSupervisor

Background tasks are not fire-and-forget. TaskSupervisor (first-line doc "Background task lifecycle management for spawn_only tools.", crates/octos-agent/src/task_supervisor.rs:1) is a state library: it tracks spawn_only tasks from spawn to terminal state and explicitly declares that it does not run the workspace contract; contract validation happens first, and only after it passes does the supervisor state update (first six lines of the module docs). Runtime state is TaskStatus (crates/octos-agent/src/task_supervisor.rs:140):

#![allow(unused)]
fn main() {
pub enum TaskStatus {
    Spawned, Running, Completed, Failed,
    Cancelled,   // user cancel, terminal (:173 is_terminal)
    Parked,      // #27c: orphaned task after serve restart, awaiting client reconnection and adoption
}
}

Of the six states Parked is special: it is neither active (is_active covers only Spawned/Running, crates/octos-agent/src/task_supervisor.rs:164) nor terminal (crates/octos-cli is not involved; is_terminal is at crates/octos-agent/src/task_supervisor.rs:173), because the task's work products (the staged peer's brief and worktree) are still on disk, and after the client reconnects, mark_running can revive it. This is the most direct example of "whether state is persisted" shaping concurrency semantics.

Runaway growth has a hard cap: at most 200 registered child tasks per parent session (MAX_CHILDREN_PER_PARENT, crates/octos-agent/src/task_supervisor.rs:43), overridable at process start via the environment variable OCTOS_MAX_CHILDREN_PER_PARENT (docs at :41, the read at :77). Registration past the cap returns RegisterTaskError (crates/octos-agent/src/task_supervisor.rs:90).

The externally visible lifecycle projection is another enum, TaskLifecycleState (crates/octos-agent/src/task_supervisor.rs:243): Queued, Running, Verifying, Ready, Failed, Cancelled. BackgroundTask::lifecycle_state() (crates/octos-agent/src/task_supervisor.rs:363) translates the internal TaskStatus into this caller-facing set. The internal state machine asks "is the worker still there"; the projection asks "is the output trustworthy," and Verifying is the slot reserved for workspace contract validation. The mapping:

Internal TaskStatusProjected TaskLifecycleStateSemantic boundary
SpawnedQueuedregistered, worker not started
RunningRunningworker executing
CompletedReady (via Verifying)validation passed, output trusted
FailedFailedexecution failed
CancelledCancelleduser-initiated cancel
ParkedCancelled (#27c reuses the free projection slot, crates/octos-agent/src/task_supervisor.rs:373)awaiting reconnect and adoption, neither terminal nor active

This projection has two consumers. On the MCP side: octos mcp-serve exposes a single tool, run_octos_session (crates/octos-agent/src/mcp_server.rs:66); session dispatch reports Queued → Running → Verifying → Ready/Failed transitions through SessionLifecycleObserver::mark_state (crates/octos-agent/src/mcp_server.rs:145; trait docs at :142-144), and the outer MCP caller ultimately receives a session-level aggregate result (final_state: TaskLifecycleState, :108), not the internal tool event stream. On the harness side: the McpServerCall event carries an outcome field with values ready/failed/queued/running/verifying, one-to-one with TaskLifecycleState (crates/octos-agent/src/harness_events.rs:651-652, event variant definition near :397), so background task lifecycles enter harness events and metrics and become part of the operator's observable surface.

12.6 The Supervisor Layer: Long-Horizon Orchestration That Survives Restarts

A tokio task lives inside the process; when the process dies, everything evaporates. For "a tool call that runs ten minutes" that is fine; for a goal like "finish the twenty-one chapters of this book today" that spans hours and days, orchestration state must outlive the process. The supervisor layer's 45544 lines all answer this one question.

Engineering decision: why long-horizon orchestration was promoted from Tokio task to persistent supervisor

A long-horizon goal (say, dispatching 5 peers to write one chapter each) is inherently a stack of multiple process lifetimes: the master restarts, peers run long, results arrive late. If orchestration state lives only in an in-memory task tree, a restart wipes the memory and the only recovery is a human reissuing instructions.

After the promotion, three things changed: state persists as an event ledger and recovers by replay after restart; "who should be woken to continue" moves from implicit task dependencies to an explicit continuation queue; and finishing a long task no longer requires any process to stay alive. The cost is that every state transition must be written as an event and must handle replay idempotency, which is why crates/octos-cli/src/autonomy/supervisor_store.rs and crates/octos-cli/src/autonomy/master_continuation_scheduler.rs together run to nearly five thousand lines.

The Event Ledger: SupervisorStore

SupervisorStore (crates/octos-cli/src/autonomy/supervisor_store.rs:697) manages four paths: the event file, the rotated event file, the snapshot, and the lock. The event file name is fixed as supervisor-events.jsonl (constant at :25); compaction keeps a single .old generation (:33), and .old is for forensics only, never replayed; a downgrade to an older binary that does not understand snapshots sees a truncated view, and the comments state this compatibility cost bluntly.

The heart of crash recovery is load_state (crates/octos-cli/src/autonomy/supervisor_store.rs:780), barely a dozen lines: read the snapshot (if any) and take its last_sequence as the watermark; then read ledger rows and replay only the tail rows where row.sequence > snapshot_last_sequence (:780-793). Replay goes through apply_ledger_row (:381), which applies each row's event to the state machine; events are self-describing via serde's type/payload tags (the comment at :300-304 explains why variants carry the full record by value: replay needs no boxing optimization on the hot path). Three design decisions underpin this replay.

First, snapshot cadence is row-count-triggered, not time-triggered. SNAPSHOT_EVERY_APPENDS = 512 (crates/octos-cli/src/autonomy/supervisor_store.rs:49); the constant's comment gives the rationale: 512 rows keep the startup replay tail within a few hundred KB, parsed in milliseconds, while amortizing the full-serialization-plus-fsync cost over hundreds of appends; the counter counts ledger rows, not one process's appends, so with multiple writers sharing one ledger, compaction still fires whenever the tail crosses the line.

Second, last_sequence is a monotonic watermark, not a counter. apply_ledger_row takes the max per row applied (:381-382), and load_state also takes the max of the watermark from the snapshot and from state (:784). Rows arriving out of order or interleaved by multiple writers therefore never push the watermark backward; a snapshot only needs to declare "up to which sequence" to truncate replay safely.

Third, the single .old generation rotation is a forensics compromise, not a recovery path. After compaction moves applied rows into .old, an older binary (a pre-#1974 build that does not understand snapshots) replaying the live tail gets a truncated view; better that the downgraded reader sees less than that any version misreads, because builds that do understand snapshots refuse a snapshot with a newer schema_version (load_snapshot, :876) instead of guessing at the parse.

The four write-side methods close the loop on this read semantics: write_snapshot (:905), snapshot_now (:920, the locked forced-compaction entry), append_event (:935, which writes and checks the watermark to decide whether to trigger compaction). The ledger is thus a structure that appends fast and recovers in bounded time: in normal operation each event is one append write, and after a crash the recovery cost is pinned to an upper bound by the 512-row tail.

Continuation Scheduling: MasterContinuationScheduler

The ledger records "what happened"; the scheduler decides "who runs next." MasterContinuationScheduler (crates/octos-cli/src/autonomy/master_continuation_scheduler.rs:477) holds a BinaryHeap plus a pending_by_key table indexed by dedupe key (impl from :506). Every continuation request carries identity and a dedupe key: MasterContinuationId (:99), MasterContinuationDedupeKey (:112), MasterContinuationRequest (:221).

Continuation reasons are prioritized: MasterContinuationReason (:137) enumerates ChildCompleted, ScatterJoinComplete, LoopFire, GoalContinue, GoalWrapUp, and External(String), mapped to MasterContinuationPriority (:186): LoopFire highest, the generic External wake lowest, and the comment says outright this is deliberate suppression "unless future wiring maps it to a typed reason." The struct also carries a TOCTOU guard field, recently_claimed_external: External continuations with the same key re-enqueued inside the window are rejected, preventing one terminal-state transition from being delivered twice by two paths (struct field docs at :477). Dedupe key plus priority heap is the concurrency skeleton of "creating a new turn after a turn ends"; Chapter 5 examined its consumer side from the loop's perspective, and the full semantics belong to Chapter 18.

Outbox Wakes and the Zero-Token Monitor

Wakeups arrive via two external paths. In crates/octos-cli/src/autonomy/fleet_wake.rs, the background consumer spawn_fleet_outbox_consumer (crates/octos-cli/src/autonomy/fleet_wake.rs:343) uses tokio::spawn to run a 3-second interval loop (the constant FLEET_WAKE_INTERVAL_SECS, :59), repeatedly calling drain_fleet_outbox_once (:235) to convert wakeups from the fleet kernel's outbox into keeper continuation requests. Polling rather than pushing means that if the consumer crashes, the next tick recovers automatically and no wakeup is lost.

crates/octos-cli/src/autonomy/monitor_runtime.rs (introduced in commit c4f03647, #1977/#1988, 2026-08-12) provides the zero-token event monitor: MonitorMode (crates/octos-cli/src/autonomy/monitor_runtime.rs:72) has exactly two states; Poll mode runs a probe command every interval_secs and treats filtered stdout changes as events, while Stream mode follows the process's stdout line by line. The monitor spends no model tokens; only an observed change wakes the master through an External continuation, which pulls "waiting on an external condition" out of the conversation loop.

AgentOrchestrator: The Orchestrator's RPC Surface

Multi-agent operations are unified in the AgentOrchestrator trait (crates/octos-cli/src/autonomy/agent_orchestrator.rs:606): list_agents, read_agent_status, read_agent_output, list_agent_artifacts are required methods, while spawn_agent (:662), send_input (:675), wait_agent (:688), resume_agent (:699) carry default implementations that all return method_not_supported_error. The trait defines a complete RPC surface, but not every implementation wires up every operation; reading the code, do not assume the four lifecycle methods are available everywhere.

The production implementation is InProcessAgentOrchestrator (:746, inner impl block from :1451, trait impl block at :9462). It mirrors TaskSupervisor background tasks as agent state; the core path run_native_specialist (crates/octos-cli/src/autonomy/agent_orchestrator.rs:2471) strings together one complete supervised specialist execution: register the native agent, run the subagent, push output and artifacts, then write back to the supervisor. crates/octos-cli/src/autonomy/goal_loop_runtime.rs (1562 lines) supplies the scheduling-policy primitives for goal and loop: GoalId (crates/octos-cli/src/autonomy/goal_loop_runtime.rs:10), GoalRuntimePolicy (:239, carrying cadence and max_continuations), GoalRuntimeState (:265, Active/Paused/Completed/Failed).

An honest boundary is that the current implementation is an orchestrator of "one master supervising a set of managed subagents, continuing on events," not an arbitrary-interconnect, real-time-conversing multi-agent society. The RPC surface invites overestimation; the four methods that default to errors are the reminder.

sequenceDiagram
    participant W as subtask/fleet/monitor
    participant ST as SupervisorStore
    participant SC as MasterContinuationScheduler
    participant MA as master session

    W->>ST: append_event (terminal/wakeup event persisted)
    ST->>ST: snapshot + compaction (past threshold)
    ST->>SC: event to continuation request (dedupe key)
    SC->>SC: priority heap entry, duplicate key in window rejected
    SC->>MA: ready continuation dequeued, new turn dispatched
    MA-->>ST: new events from the new turn
    Note over ST,MA: after process restart: load_state replays ledger<br/>+ snapshot, continuation queue restored

12.7 The Peer/Lease Layer: The Process Metaphor and Leases

The third layer solves isolation and recovery for "multiple quasi-agents coexisting." The first-line doc of crates/octos-cli/src/peers/mod.rs is "Peer-agent staging, addressing, and parked-prompt plumbing." (crates/octos-cli/src/peers/mod.rs:1); its second paragraph notes it was lifted verbatim from the api-gated ui_protocol tree (the Phase 3 peer-goal extraction changed only module location and visibility, not logic). The layer's concurrency-primitive role shows in PeerTaskBinding (:166): it binds a peer to a TaskLivenessLease, binding and retirement go through bind_peer_supervised_task (:241) and friends, so peer liveness is tied to the supervisor's lease.

The fleet side's concurrency primitives are two small structs. Lease (crates/octos-fleet/src/records.rs:250) has only owner_epoch and expires_at_ms: each daemon start gets a new epoch, and a foreign epoch or an expired lease is reclaimed by recovery reconciliation. In one sentence: after a restart, the old owner loses authority automatically. Attempt (:256) files one execution attempt, with the fleet id stored redundantly so (child_id, attempt_id) alone locates the child row.

One comparison diagram settles the peer-versus-subagent difference:

flowchart TB
    subgraph SA["subagent ≈ thread"]
        A1["tokio::spawn inside the parent process"]
        A2["lifecycle = process lifetime"]
        A3["state in TaskSupervisor memory+ledger"]
    end
    subgraph PE["peer ≈ process"]
        B1["own working directory / own session tree"]
        B2["TaskLivenessLease keep-alive"]
        B3["Parked after serve restart, reconnectable and adoptable"]
    end
    A1 --> A2 --> A3
    B1 --> B2 --> B3

A subagent is like a thread: it shares the process's fate, is lightweight, and evaporates with the parent. A peer is like a process: it has its own address (slug), its own working directory, declares liveness through a lease, and after a process restart its work products wait on disk for adoption.

The fleet lease semantics deserve space in this chapter, because they are the smallest complete specimen of "how concurrent ownership crosses processes." The Lease struct has only two fields (crates/octos-fleet/src/records.rs:250): owner_epoch is this daemon start's identity, expires_at_ms the absolute expiry moment. Acquisition happens at dispatch: crates/octos-fleet/src/store.rs, constructing the Attempt, sets status to Leased and writes lease { owner_epoch, expires_at_ms: now_ms + lease_ttl_ms } (crates/octos-fleet/src/store.rs:990-1001; the TTL addition uses checked_add against overflow). Renewal is not an explicit API: when a worker enters execution via mark_running (crates/octos-fleet/src/store.rs:1053), the lease field persists with the attempt row, and what actually checks it are the predicates on every write path.

Surrender and reclamation rely on the same four-part predicate. complete_child (crates/octos-fleet/src/store.rs:1158) requires four conditions to hold simultaneously before committing a result: the child's current_attempt_id points at this attempt (the attempt-id fence, blocking same-generation retries), the attempt status is Running, generation equals the fleet's current generation (the generation fence, blocking stale attempts after replanning), and lease.owner_epoch equals the caller's epoch (the lease fence, blocking the old owner after a restart); the predicate body is at :1230-1237. If any fails, it returns Superseded, the result is dropped whole, and the books do not move. Reclamation happens at boot reconciliation: a non-terminal attempt whose lease carries a foreign, mismatched epoch or whose expires_at_ms has passed (the stale test at crates/octos-fleet/src/store.rs:2276-2277) is unconditionally set to Interrupted and its budget reservation released; the comments record the #1973 fix: before it, fleets in Cancelled state were skipped wholesale, pinning attempts and reservations forever.

The concurrency consequence of this design is that after the old process crashes, the new process negotiates with no one. A different epoch automatically loses authority; expiry automatically reclaims; correctness never depends on the crashed party's cooperation. The lease and the supervisor layer's event ledger are two answers to the same question: the ledger recovers "where the orchestration got to" by replay; the lease deposes "those who should no longer act" with fences. The full Lease/Attempt state machine is in Chapter 16; goal/peer orchestration semantics are in Chapter 18.

12.8 Graceful Shutdown: Two AtomicBools

Shutdown is layered with two atomic bools. global_shutdown and cancelled are fields of SessionActor (crates/octos-cli/src/session_actor.rs:4500-4503): the former is the process-level signal (Ctrl+C), the latter affects only the current session. The actor-facing ActorHandle.shutdown (crates/octos-cli/src/session_actor.rs:2872) likewise exposes an Arc<AtomicBool>.

The write side lives in the gateway's Ctrl+C handling task (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1653): after ctrl_c().await returns, shutdown.store(true, Ordering::Release). The Release ordering guarantees that all prior writes are visible to whoever acquires; the read side loads with Ordering::Acquire, so when an actor sees the shutdown flag it also sees every state change made before the flag. One Release/Acquire pair is this control signal's entire memory-ordering contract; there are no locks.

Broadcast-style reclamation takes a different road: ActorRegistry::shutdown_all (crates/octos-cli/src/session_actor.rs:2795) drops all senders directly, and each actor exits naturally once its recv() returns None — the mailbox draining is the shutdown, no actor needs to poll a flag. The two paths complement each other: the AtomicBool gives running tasks a cooperative checkpoint; dropping senders gives waiting actors a deterministic end.

12.9 Summary

LayerConcurrency problem solvedKey mechanismsCost
Tokio layermulti-session parallelism, within-session consistencysession actor exclusive state, semaphore admission, batch admissionactor lifecycle management
supervisor layerlong-horizon orchestration across restartsevent ledger + snapshot, dedupe priority continuation, outbox pollingnearly five thousand lines of persistence and replay code
peer/lease layermulti-agent isolation and recoveryprocess metaphor, epoch lease, Parked adoptionstate-machine complexity (see Chapter 16)

The three layers stack rather than replace one another: a supervisor continuation still ends up dispatched back to some session actor to execute; peer liveness judgment reuses TaskSupervisor's state machine. Layering concurrency primitives is, in essence, paying separately for three orthogonal needs: "fast" (in-memory, microsecond scale), "durable" (on disk, across restarts), and "isolated" (process boundaries).

Further reading

  • Chapter 5: the Agent Loop's six-stage lifecycle and budget gates; the consumer-side view of the continuation queue.
  • Chapter 10: the complete event ABI of harness events; this chapter's McpServerCall is one of its event families.
  • Chapter 16: the full Lease/Attempt/Recovery state machine of the fleet.
  • Chapter 18: the orchestration semantics of goal and peer, and MasterContinuationScheduler's complete consumption chain.
  • The Graceful Shutdown chapter of the official Tokio documentation: task cancellation and waiting semantics for runtime-level graceful shutdown.

Exercises

  1. If max_concurrent_sessions went from 10 to 100, what behavior would the permit consumption point in 12.3 (the message-processing layer) produce? What if the permit were acquired at session creation instead?
  2. TaskStatus::Parked belongs to neither is_active nor is_terminal. Design a concurrency scenario showing what breaks if Parked were misclassified as terminal.
  3. The mixed-batch policy (#1766) runs Safe calls in parallel first, then Exclusive calls serially. Why can't it be reversed? What do consumers rely on in the constraint that results are "reassembled in original LLM call order"?
  4. MasterContinuationScheduler's TOCTOU guard records only External keys. If a new internal producer also re-enqueued the same key within the window, what would happen? What does the comment's INVARIANT require of the new producer?
  5. shutdown_all makes actors exit by dropping senders. If an actor is in the middle of a 30-minute tool call, how does this path behave differently from the global_shutdown flag path?

Version note

Version note: This chapter's analysis baseline is octos main @ 9c157101 (checked out 2026-09-02); all line numbers and figures were measured at that commit; the facts table is assets/ch12-facts.md (2026-09-03). Changes relative to the v1 draft (originally Chapter 11): the narrative was corrected from "per-session Mutex serialization" to the session actor state-ownership model; the supervisor layer (the ten files of autonomy/) and the peer/lease layer are new; crates/octos-cli/src/autonomy/monitor_runtime.rs was introduced in c4f03647 (2026-08-12), and the current line numbers include offsets from the later commits e2f999a0 (clippy formatting) and 0c44b26f (OLP control channel). Four "to be verified by the writer" items in the facts table were verified in this session: default_max_concurrent_sessions() returns the literal 10; both crates/octos-agent/src/task_supervisor.rs and crates/octos-cli/src/config.rs have //! docs on their first lines (the facts table's "none / not collected" was wrong); the skeleton line numbers 606/746/1451/2471/9462 of crates/octos-cli/src/autonomy/agent_orchestrator.rs all confirmed; and the outward entry of crates/octos-agent/src/agent/execution.rs is pub(super) fn execute_tools (:2483), which this chapter cites accordingly.

Chapter 13: octos-pipeline: A DOT-Graph-Driven Workflow Engine

Positioning: This chapter reads against crates/octos-pipeline/src/ and explains how octos parses Graphviz DOT into the typed PipelineGraph, how the executor lands nine HandlerKinds, twelve IR node kinds, static parallelism, dynamic parallelism, checkpoint recovery, deadline guardrails, and parent-session resource inheritance, and how the run_pipeline tool exposes pipelines to the Agent. Prerequisites: Chapter 5, Chapter 8, Chapter 10, Chapter 11. Who should read it: developers who need to understand the mechanics of multi-step Agent orchestration.

Once a task outgrows "one Agent loop plus a few tool calls," it needs explicit workflow orchestration. The archetypal case: plan the research angles, fan out retrieval in parallel, converge on the analysis, then write the report. octos-pipeline exists for exactly this class of problem, but its current implementation does not match the intuitions of a "traditional DAG scheduler": it combines graph structure with runtime branch selection, concurrent convergence, model routing, and tool-policy inheritance. Through PipelineHostContext it also inherits the parent session's file cache, sub-agent output routing, task supervisor, and cost ledger, so pipeline nodes no longer run in the isolation that marked the early implementation.


13.1 How a DOT Graph Enters the Runtime

13.1.1 Why DOT

octos defines workflows in Graphviz DOT, not YAML/JSON. The reason is not fashion: DOT makes nodes and edges first-class semantics, so the same file can be parsed by the executor and rendered directly into a picture by Graphviz.

digraph research {
    graph [label="Deep Research", default_model="cheap"]

    start [label="规划", handler="dynamic_parallel",
           converge="analyze",
           planner_model="strong",
           worker_prompt="围绕 {task} 做资料检索,并保留来源",
           tools="deep_search",
           max_tasks="6"]

    analyze [label="分析", handler="codergen",
             model="strong",
             tools="read_file,write_file"]

    finish [label="结束", shape="Msquare"]

    start -> analyze
    analyze -> finish
}

This example already shows the key capabilities the current parser supports:

  • graph-level attributes: graph [label=..., default_model=...]
  • node attributes: handler, model, tools, converge, planner_model, and friends
  • edges: A -> B
  • an implicit shape-to-Handler mapping, for example Msquare maps to Noop

13.1.2 A hand-written parser, not a third-party DOT library

The entry point is parse_dot() at crates/octos-pipeline/src/parser.rs:21-23; the real work happens in DotParser::parse() (struct defined at crates/octos-pipeline/src/parser.rs:45, impl at :50). This is a hand-written parser with no external DOT parsing dependency. The file has grown to 1,445 lines.

The current implementation is richer than the simplified story of "a small syntax subset":

  • the digraph name is optional; if the model emits digraph { ... }, the parser sets the graph id to "pipeline" (crates/octos-pipeline/src/parser.rs:63-65)
  • graph-level attributes graph [key=value] are supported. Beyond label and default_model, the parser now also accepts max_total_tokens (a run-level token budget), default_timeout_secs (the default wall-clock timeout per pipeline), and result_fidelity (a result-size downgrade annotation); all land in apply_graph_attrs() (crates/octos-pipeline/src/parser.rs:520-537)
  • subgraph name { ... } is supported, and nodes inside a subgraph are archived into PipelineGraph.subgraphs (crates/octos-pipeline/src/parser.rs:148-150, crates/octos-pipeline/src/graph.rs:48)
  • chained edges a -> b -> c are supported, and attributes apply to every edge in the chain (crates/octos-pipeline/src/parser.rs:163)
  • comments: //, /* */, plus an extra # line-comment form; the last is clearly tolerance for LLM-generated DOT (crates/octos-pipeline/src/parser.rs:479-502)
  • if an edge references a node that was never declared, the parser synthesizes a default node definition for it (crates/octos-pipeline/src/parser.rs:110-127)

The result of this layer is not a loose JSON tree but the semantic PipelineGraph. Its core structures live in crates/octos-pipeline/src/graph.rs:10-54 (graph) and :118-184 (node):

  • PipelineGraph carries id, label, default_model, max_total_tokens, default_timeout_secs, result_fidelity, nodes, edges, subgraphs. The last three graph-level fields did not exist in the old draft
  • PipelineNode, beyond prompt and handler, includes model, context_window, max_output_tokens, max_iterations, tools, goal_gate, max_retries, timeout_secs, suggested_next, converge, worker_prompt, planner_model, max_tasks, deadline_secs, deadline_action, checkpoints, plus human_gate (:163), resolver (:166), artifact_refs (:169), checkpoint_refs (:172), continue_on_error (:184)

13.1.3 Mapping attributes to node semantics

Node construction happens in build_node() (crates/octos-pipeline/src/parser.rs:579-691). Several implementation details shape the authoring experience of DOT:

  • Handler resolution order: an explicit handler= wins first, then the shape=-to-Handler mapping (crates/octos-pipeline/src/graph.rs:282-297, string form from_str at :270-279), and finally the default Codergen (crates/octos-pipeline/src/parser.rs:581-586)
  • tools="a,b,c" splits into a string list; if the user writes tools="", the parse result is a deny-all marker consisting of one empty string, which the executor treats as "explicitly disable all tools" (crates/octos-pipeline/src/parser.rs:588-602)
  • timeout_secs accepts plain integer seconds and suffixed forms like 900s, 15m, 2h (crates/octos-pipeline/src/parser.rs:551-570)
  • goal_gate accepts true/false/yes/no/1/0 (crates/octos-pipeline/src/parser.rs:619-623)
  • deadline_secs supports ms/s/m/h and fractional seconds (crates/octos-pipeline/src/parser.rs:601-603, the underlying parse_duration_secs_f64 at :665-689); deadline_action accepts abort, skip, escalate, and retry:N or retry(N) (crates/octos-pipeline/src/parser.rs:693-720)
  • checkpoint="true" or checkpoint="name1,name2" parses into MissionCheckpoint declarations (crates/octos-pipeline/src/parser.rs:721-751)
  • max_iterations is now a writable node attribute (crates/octos-pipeline/src/parser.rs:620, field at crates/octos-pipeline/src/graph.rs:140); see 13.2.1

This makes DOT, inside octos, not a pure topology description but a lightweight workflow DSL.


13.2 Nine HandlerKinds and Twelve IR Node Kinds

The real HandlerKind enum lives at crates/octos-pipeline/src/graph.rs:241-266. The current source has 9 kinds; the old draft's 6 is stale:

KindRuntime landing pointKey attributesRole
Codergencrates/octos-pipeline/src/handler.rs:641 (impl start)prompt model tools context_window max_output_tokensSpawns a full sub-agent
Shellcrates/octos-pipeline/src/handler.rs:1054prompt timeout_secsRuns shell commands, but is banned by a validation rule (see 13.2.2)
Gatecrates/octos-pipeline/src/handler.rs:1190promptEvaluates a condition; no human wait
Noopcrates/octos-pipeline/src/handler.rs:1226nonePasses input through
Parallelcrates/octos-pipeline/src/executor.rs:2749convergeStatic fan-out over existing downstream nodes
DynamicParallelcrates/octos-pipeline/src/executor.rs:3122prompt worker_prompt planner_model max_tasks convergePlans tasks first, then dynamic fan-out
ShellCheckcrates/octos-pipeline/src/handler.rs:1247command timeout_secsRuns a fixed command string, locked at compile time
Notifycrates/octos-pipeline/src/handler.rs:1326message channelSends the user a notification
Waitcrates/octos-pipeline/src/handler.rs:1365seconds until_conditionWaits a fixed number of seconds or polls a condition

One easily missed but important fact: the Handler trait (crates/octos-pipeline/src/handler.rs:257) now has 7 implementations: CodergenHandler (:641), ShellHandler (:1054), GateHandler (:1190), NoopHandler (:1226), ShellCheckHandler (:1247), NotifyHandler (:1326), WaitHandler (:1365). Parallel and DynamicParallel are not standalone handler types; they are dedicated branches inside PipelineExecutor::execute_graph() (crates/octos-pipeline/src/executor.rs:2749 / :3122).

The handler-name-to-string mapping grew to 9 entries in step with them, including shell_check, notify, wait (crates/octos-pipeline/src/executor.rs:251-259).

13.2.1 Codergen: a node is a sub-agent

CodergenHandler (struct at crates/octos-pipeline/src/handler.rs:293, impl :641-1041) creates a full octos_agent::Agent for the node rather than making one simplified LLM call. The node therefore inherits most of the main Agent's capabilities: tool calls, loop-style execution, token accounting, file-change reporting, progress events.

Its key behavior has several layers:

  1. Provider resolution. If the node declares model and the executor is configured with a ProviderRouter, the handler goes through router.resolve(), then wraps the result with a capability-compatible fallback provider. This is not a plain "model name -> provider" mapping; it is resolution with a fallback chain.
  2. Context window override. context_window is wrapped into a ContextWindowOverride.
  3. Tool registration. The node's initial tool set comes from ToolRegistry::with_builtins(), then a once-cached plugin registration is applied, so each node does not repeat plugin SHA verification and executable reads (crates/octos-pipeline/src/handler.rs:23-56).
  4. Tool policy. The node's own tools= decides the allowlist; the handler additionally denies spawn, run_pipeline, send_file, message so sub-nodes cannot recurse without bound; it then also clears spawn_only flags so plugin tools that were spawn_only execute synchronously inside the pipeline worker (crates/octos-pipeline/src/handler.rs:125-130).
  5. Parent-session resource inheritance. When run_pipeline is triggered from inside a session actor, the node worker inherits the parent session's FileStateCache, SubAgentOutputRouter, AgentSummaryGenerator, CostAccountant, and the parent session key (crates/octos-pipeline/src/host_context.rs:34-60, from_tool_context at :78).
  6. Separation of system prompt and task input. The executor first removes {input} from prompt, keeping only role/constraint text; the actual predecessor output reaches the sub-agent through TaskKind::Code.instruction.

One large divergence from the old draft is the iteration budget: early versions hardcoded AgentConfig.max_iterations to 30, leaving nodes no say. Now PipelineNode.max_iterations (crates/octos-pipeline/src/graph.rs:140) is a writable DOT attribute parsed directly by build_node() (crates/octos-pipeline/src/parser.rs:620). The field comment spells out the motive: the pipeline default of 30 iterations is too low for a synthesize node that reads findings files one by one and then writes the synthesis; the budget runs out navigating files, the result never ships, and the whole pipeline dies. None keeps the default.

Also, the default behavior of max_output_tokens is not "a global 4096." If the node omits the attribute, the handler falls back to the provider's own maximum output capability. That matters for long-report generation.

13.2.2 Shell: implemented, but banned by a validation rule

ShellHandler itself remains fully implemented (struct at crates/octos-pipeline/src/handler.rs:1043, impl :1054-1135): the command comes from node.prompt, runs under sh -c on non-Windows and cmd /C on Windows, with a default timeout of 300 seconds; a non-zero exit maps to OutcomeStatus::Fail, and a process-start failure or timeout maps to OutcomeStatus::Error.

But the current version has a ban chain the old draft never wrote: validation rule rule_23_no_shell (crates/octos-pipeline/src/validate.rs:242) rejects any graph with handler="shell" outright, on the grounds that shell is arbitrary code execution; meanwhile build_handlers() simply does not register the Shell handler (crates/octos-pipeline/src/executor.rs:2409-2438) as defense in depth: even if some graph slips past validation, there is no handler to dispatch. The command-execution entry that pipelines actually use is ShellCheck (13.2.7).

The split between "the test ran and failed" and "the command never started" still matters, because the executor retries only on Error:

  • "the test ran and failed" is a business failure; no retry
  • "the command never started" or "timed out" is a system error; retryable

13.2.3 Gate: a condition node, not a human-approval node

This is the easiest part of the chapter to get wrong.

What the executor registers is GateHandler (struct at crates/octos-pipeline/src/handler.rs:1136, synthesize_predecessor_outcome at :1138, impl :1190-1222), and its real semantics are:

  • treat node.prompt as a conditional expression (when empty, unwrap_or("true") turns it into a pass-through gate, crates/octos-pipeline/src/handler.rs:1192)
  • evaluate against the direct predecessors' NodeOutcome; a single predecessor keeps its original status, multiple predecessors aggregate as Error > Fail > Skipped > Pass
  • return Pass or Fail, pass content through untouched, and initiate no human interaction

crates/octos-pipeline/src/human_gate.rs does exist, providing abstractions such as HumanInputProvider and ChannelInputProvider, with a default timeout of 5 minutes (DEFAULT_INPUT_TIMEOUT, crates/octos-pipeline/src/human_gate.rs:14-15). But the current source is unambiguous on this point: those abstractions are not wired into the build_handlers() or execute_graph() main path. So "Gate = human-approval node" is not an accurate description of the current implementation.

The accurate statement is:

  • GateHandler is the wired-up condition node
  • crates/octos-pipeline/src/human_gate.rs is a human-input abstraction the crate provides but that the default executor has not wired in

13.2.4 Parallel: static fan-out over real downstream nodes

Parallel does not dynamically spawn workers; it runs the graph's already-existing downstream nodes concurrently. The dedicated branch starts at crates/octos-pipeline/src/executor.rs:2749:

  1. collect the targets of all outgoing edges of the current node as the concurrency set (:2756-2763)
  2. require the current node to declare converge, otherwise error with "parallel node missing converge" (:2751-2754)
  3. before dispatch, check the pipeline-lifecycle-wide fan-out total cap, default MAX_PIPELINE_FANOUT_TOTAL = 500 (constant at crates/octos-pipeline/src/executor.rs:102, gate at :2804); exceeding the cap rejects the whole batch rather than starting half the workers
  4. clone the PipelineNode for each target, perform variable substitution, and fill in graph.default_model when no model was declared
  5. reserve cost budget for each LLM-call branch, then look up its own handler and execute concurrently (concurrency bounded by ExecutorConfig.max_parallel_workers, field :405, use site :2849; the run_pipeline tool defaults to 8)
  6. merge content, tokens, summaries, and node outcomes
  7. write the merged text back into the "current parallel node"'s completed result, then jump to the converge node (jump logic :3108-3121)

Two implementation details are worth remembering:

  • worker timeouts are capped at MAX_FANOUT_WORKER_SECS = 3600 seconds (crates/octos-pipeline/src/executor.rs:121)
  • the executor uses parallel_executed to remember the real graph nodes that already ran during the fan-out phase; when sequential traversal later reaches them, it only picks an edge and does not re-execute

Result merging is more than string concatenation, too. After merging, the executor scans worker outputs for mentioned research directories and inlines the contents of _search_results.md into the merged result. The current implementation is clearly tuned for the "research fan-out -> synthesis converge" shape.

13.2.5 DynamicParallel: plan first, then synthesize worker nodes

The fundamental difference from Parallel: DynamicParallel does not run ready-made graph nodes. It first has an LLM plan a task list, then synthesizes a temporary Codergen node per task. The dedicated branch starts at crates/octos-pipeline/src/executor.rs:3122:

  1. resolve the planner provider selection chain planner_model -> node.model -> graph.default_model
  2. use node.prompt as the planning prompt; if empty, fall back to the built-in planner prompt
  3. plan_dynamic_tasks() (crates/octos-pipeline/src/executor.rs:1158-1272) expects the model to return a plain JSON array; on parse failure or too few tasks it falls back to fallback_tasks() (:1274-1300)
  4. substitute {task} in worker_prompt with the concrete task description, producing a batch of synthetic Codergen nodes
  5. before dispatch, likewise check the fan-out total cap and reserve cost budget for each synthetic worker
  6. execute these synthetic nodes concurrently, merge the results, and jump to converge

It also has a behavior the old draft got wrong: the old draft said DynamicParallel "does not wrap another semaphore the way Parallel does." Today every run entry (run(), run_graph(), run_graph_with_handlers_throttled()) first constructs a pipeline-level LLM semaphore (pipeline_llm_semaphore(), crates/octos-pipeline/src/executor.rs:1640), and DynamicParallel's workers pass through that gate as well. A single fan-out is still bounded mainly by max_tasks (default 8; field comments at crates/octos-pipeline/src/graph.rs:118-184), and the whole pipeline run is protected by MAX_PIPELINE_FANOUT_TOTAL = 500.

node.model can still be a comma-separated model pool (for example "cheap,strong,cheap"); the executor round-robins workers onto different models. That assignment now lives in crates/octos-pipeline/src/model_assignment.rs (see 13.3.5).

13.2.6 Noop: a placeholder that earns its keep

NoopHandler (struct at crates/octos-pipeline/src/handler.rs:1223, impl :1226-1243) returns ctx.input unchanged. Two common uses:

  • structural nodes such as start / finish
  • a convergence or pass-through point for certain conditional branches

Incidentally, in build_handlers() the registry entry for DynamicParallel is also a NoopHandler placeholder (crates/octos-pipeline/src/executor.rs:2409-2438); real execution goes through the executor branch, and the registration exists only so the registry lookup does not come up empty.

13.2.7 Three new handlers: ShellCheck, Notify, Wait

These three variants are real handlers added when the IR palette landed. One line each:

  • ShellCheckHandler (crates/octos-pipeline/src/handler.rs:1247): executes one fixed command string, locked at compile time, with no LLM tool surface. In contrast to the banned Shell (arbitrary code execution), it serves read-only command cases such as "run the tests, check the build, count lines"; the command runs in the session workspace and the output becomes the node result
  • NotifyHandler (crates/octos-pipeline/src/handler.rs:1326): sends the user a notification, message plus optional channel (e.g. telegram, slack), with essentially no LLM involvement
  • WaitHandler (crates/octos-pipeline/src/handler.rs:1365): waits a fixed number of seconds, or polls an until_condition until true or timeout (default 300 seconds), with no LLM call

13.2.8 The IR palette: twelve IrNodeKinds

Exposing 9 HandlerKinds directly to the LLM has a problem: the variants mix execution mechanics (Parallel is an executor branch) with a security-sensitive surface (Shell is banned). After 6b0de6ca, octos-pipeline introduced a typed IR layer: IrNodeKind (crates/octos-pipeline/src/ir.rs:57, 673-line file) currently measures 12 variants:

$ sed -n '/pub enum IrNodeKind/,/^}/p' crates/octos-pipeline/src/ir.rs | grep -cE '^\s{4}[A-Z]'
12
#IrNodeKindLanding pointSemantics (source comment)
1ResearchCodergen classRead-only research (web + file reads), cheap model; carries max_iterations (:64)
2TransformCodergen classPure transformation of predecessor output, cheap model
3SynthesizeCodergen classFinal synthesis (read-only), strong model; carries max_iterations (:75)
4ReportCodergen classSynthesizes and persists via write_file, terminal step; carries max_iterations (:84)
5GateGatePure routing gate, no LLM; outgoing edge conditions decide the branch
6FanoutDynamicParallelPlans N workers to run in parallel, then converge (plan_prompt / worker_prompt / converge / max_tasks)
7CodeReviewCodergen classRead-only code analysis (read/grep/glob), may carry scope
8CodeEditCodergen classEdits code, may carry expected files
9ShellCheckShellCheck handlerFixed command string, locked at compile time
10SubAgentspawn sub-agentSub-agent node with an independent LLM session (task / tools / model, model defaults to strong)
11NotifyNotify handlerSends a notification, message + optional channel
12WaitWait handlerWaits a fixed number of seconds or polls until_condition

Every IR node kind has a capability contract owned by code in PaletteContract (crates/octos-pipeline/src/ir.rs:195, lookup function contract_for at :204): which HandlerKind it lands on, an explicitly non-empty tool allowlist (an empty list would mean all built-in tools, so the contract forbids empty), and the default model. The comment is blunt: these fields are invisible to and unmodifiable by the LLM, looked up per kind at compile time.

One sentence in the IR enum's trailing note deserves quoting whole (crates/octos-pipeline/src/ir.rs, end of the IrNodeKind definition): human_gate is deliberately absent. The pipeline executor does not route human-input gates to a real approval handler (a bare Gate node's condition defaults to true and passes automatically); advertising a human_gate in the palette would offer a silent approval bypass. The note is explicit: it can come back only once a HumanInputProvider-backed handler is actually wired in.

The tool layer also exposes the IR to the LLM, not bare handlers: run_pipeline's input_schema() has an ir parameter (a typed-IR workflow program, JSON), but it appears in the schema only when enabled; the test input_schema_exposes_ir_only_when_enabled (crates/octos-pipeline/src/tool.rs:2917) pins this behavior.


13.3 The execution engine is a graph traverser with routing, not a "topological sorter"

flowchart TD
    DOT["DOT / IR / pipeline name / file path"] --> Parse["parse_dot() / IR 编译"]
    Parse --> Validate["validate()"]
    Validate --> Start["find_start_node()"]
    Start --> Loop["execute_graph() loop"]

    Loop --> Kind{node.handler}
    Kind -->|Parallel| PFan["并发执行真实下游节点"]
    Kind -->|DynamicParallel| DPlan["LLM 规划任务"]
    Kind -->|其他| Normal["Handler::execute()"]

    PFan --> Merge["合并结果并跳到 converge"]
    DPlan --> Workers["合成 worker 节点并发执行"]
    Workers --> Merge
    Normal --> Select["select_next_edge()"]
    Merge --> Select
    Select -->|有后继| Loop
    Select -->|无后继 / goal_gate 成功 / Error| Done["PipelineResult"]

Figure 13-1: the real main path of the current PipelineExecutor. It does not first run a whole-graph topological sort and then mechanically execute every node; it starts from the start node, branches by node kind inside a loop, and re-decides the next edge at every step.

13.3.1 The actual phases of run()

The execution entry is now a family: PipelineExecutor::run() (crates/octos-pipeline/src/executor.rs:1650-1672) and run_graph() (:1673) both converge on run_graph_with_handlers_throttled() (:1772), which adds two things: constructing the pipeline-level LLM semaphore (:1640) and the in-process model assignment at the top (see 13.3.5). The overall flow still compresses into seven steps:

  1. parse_dot() parses the DOT (or compiles the typed IR into a graph)
  2. validate() runs the lint rules
  3. build_handlers() builds the handler registry (crates/octos-pipeline/src/executor.rs:2409-2438)
  4. find_start_node() decides the entry node
  5. if a CostAccountant exists, open the pipeline-level budget reservation first
  6. execute_graph() enters the main loop (from :2520)
  7. if the pipeline succeeds, run terminal validators; only final success commits the pipeline-level cost attribution, otherwise the reservation is refunded automatically

The most important correction here: after step four there is no "topological traversal of the whole DAG," but an incremental traversal driven by current_node_id. That is why runtime routing strategies such as suggested_next, conditional edges, and label matching can work at all.

13.3.2 Validation rules: 23 of them, including the Shell ban

The validator lives in crates/octos-pipeline/src/validate.rs (entry validate() at :181, validate_with_context() at :186, find_start_node() at :394). The rule list has grown to 23 (:210-232); the more important ones:

  • Rule 1: a start node must be findable (the start node, or the unique node with no incoming edges)
  • Rule 2: unreachable nodes are a warning, not an error
  • Rule 6: edge conditions must parse with the condition parser
  • Rule 13 / 14: parallel and dynamic_parallel must both declare a valid converge
  • Rule 18: model names must be known keys (validate_model_name, crates/octos-pipeline/src/validate.rs:1046; the old draft omitted this)
  • Rule 23: handler="shell" is a direct Error (:242)
  • the graph must be acyclic; cycle detection happens at validate time, not at execution time (detect_cycles, crates/octos-pipeline/src/graph.rs:54)

So octos-pipeline still requires a DAG, but its execution model is not a static DAG scheduler; it is a dynamic graph traverser constrained by a DAG.

13.3.3 The condition language and edge-selection order

The grammar of conditional expressions lives in crates/octos-pipeline/src/condition.rs. The core forms the runtime actually supports:

  • outcome.status == "pass"
  • outcome.status != "fail"
  • outcome.contains("keyword")
  • !expr, expr && expr, expr || expr

For example:

test -> deploy   [condition="outcome.status == \"pass\""]
test -> rollback [condition="outcome.status == \"fail\""]
report -> refine [condition="outcome.contains(\"missing data\")"]

The success / failure shorthand of the old draft no longer matches the current parser.

Edge selection is not "first match wins"; it is a 5-step algorithm (select_next_edge(), defined at crates/octos-pipeline/src/executor.rs:4882):

  1. evaluate all conditional edges first
  2. if multiple conditions hit, pick the highest weight
  3. if no condition hits, check the node's suggested_next
  4. next, check whether an edge label appears in the outcome content
  5. last, pick by weight among unconditional edges; if still nothing, fall back to the edge with the smallest target name

One subtle implementation fact: crates/octos-pipeline/src/condition.rs's grammar supports context.key == "value" (:12-17, :32-34), and the module offers a context-aware entry evaluate_with_context() (:69); but the main-path select_next_edge() and GateHandler still call evaluate(). In other words, context.* is currently in a "grammar defined, module accepts an explicit context argument, main path feeds no values" state; what remains stably usable are the outcome.* conditions.

13.3.4 Progress events: crates/octos-pipeline/src/events.rs and the event ABI

A block the old draft never mentioned: crates/octos-pipeline/src/events.rs (296 lines, exported at crates/octos-pipeline/src/lib.rs:12, re-exported at :36) defines the structured PipelineEvent enum (crates/octos-pipeline/src/events.rs:14):

  • PipelineStarted: graph id, node count, edge count
  • NodeStarted: node id, handler, model, label
  • NodeCompleted: status, duration, token usage
  • EdgeSelected: from, to, and the selection reason
  • ParallelFanOut / ParallelConverged: fan-out target list and the convergence result
  • PipelineCompleted: success or failure, total duration, total tokens, executed node count

The consumer side is a PipelineEventHandler trait; the crate ships two implementations, TracingEventHandler (logging) and CollectingEventHandler (collection). This event layer is the carrier that f26d2291 introduced for "structured per-node progress + ETA + previews over the harness event channel": per-node progress, estimated remaining time, and content previews no longer have to be guessed from string status text; they travel up along the event ABI. The versioning of the event protocol itself and consumer-side semantics belong to Chapter 10; the point here is that the pipeline's event channel and Chapter 10's harness event ABI are the same engineering line.

13.3.5 The model-selection path that is actually in effect: the throttled entry + crates/octos-pipeline/src/model_assignment.rs

The old draft said "model selection is jointly applied by execute_graph() and CodergenHandler," which is no longer accurate. The current main path:

  1. graph-level default: graph [default_model="cheap"]
  2. node override: node [model="strong"]
  3. slots the LLM left empty are filled by one in-process model assignment at the top of run_graph_with_handlers_throttled() (crates/octos-pipeline/src/executor.rs:1772; the model_assignment::assign_from_catalog_dir call at :1808)

That assignment reads model_catalog.json / pipeline_models.json from the profile data directory, with the logic in the standalone crates/octos-pipeline/src/model_assignment.rs (564 lines; assign_from_catalog_dir at :135, known_model_keys_from_catalog_dir at :155, which also feeds Rule 18's model-name validation). The source comment explains the move from the historical pipeline-guard plugin's before_tool_call hook into the process: the plugin form degraded silently when manifest parsing failed (a load-order race at daemon startup), while cost/quality routing between strong and fast is correctness-critical, and only the in-process form is deterministic. DynamicParallel's model-pool round-robin is also owned by this layer.

The ModelStylesheet module itself still exists and supports selectors like * / handler:codergen / node:critical_analysis (crates/octos-pipeline/src/stylesheet.rs:28). I checked the current source: it is still only exported by crates/octos-pipeline/src/lib.rs:28/64; PipelineExecutor, RunPipelineTool, and PipelineDiscovery have no call sites. So the conclusion stands:

  • ModelStylesheet is an exported capability of the crate
  • the current default execution path uses default_model + node.model + model_assignment backfill

Writing ModelStylesheet up as the main path would overstate its actual standing in the current version.

13.3.6 Parent-session inheritance, the cost ledger, and workspace policy

The current run_pipeline does not "open an isolated set of resources inside the pipeline." The tool entry snapshots a PipelineHostContext from TOOL_CTX (from_tool_context, crates/octos-pipeline/src/host_context.rs:78, call site crates/octos-pipeline/src/tool.rs:144) and passes the parent session's shared resources to the executor:

  • FileStateCache: node workers reuse the parent session's file-state cache instead of each node rebuilding its own view
  • SubAgentOutputRouter / AgentSummaryGenerator: when a node triggers a background sub-agent, outputs and summaries still route through the parent session
  • TaskSupervisor: sequential nodes register as pipeline:<node_id> subtasks (crates/octos-pipeline/src/executor.rs:2263-2289, the synthesized tool name at :2289), with status updates on completion, failure, or skip
  • CostAccountant: the pipeline-level reservation opens at run start and commits with accumulated tokens on success; node-level reservations exist only for the pre-dispatch budget gate and become node_costs for UI / SSE after the node finishes (PipelineContext holds the ledger, defined at crates/octos-pipeline/src/context.rs:59)

At the same time, RunPipelineTool reads the workspace policy from the working directory and constructs the PipelineContext automatically. Pipeline nodes therefore inherit the compaction policy and run workspace validators in the terminal phase; when validators_by_node is configured, per-node validators also run after each single node finishes (ValidatorsByNode exported via crates/octos-pipeline/src/lib.rs:35).

This is the same engineering line as Chapter 8's context compaction and Chapter 11's TaskSupervisor: the pipeline is no longer just a "multi-node DAG"; it is inside the parent session's observation, budget, and workspace-contract boundaries.

13.3.7 Where human_gate, checkpoint, and run_dir really sit

These three modules are easily written up as "default capabilities." The accurate placement splits into layers: crate capability, executor-optional wiring, and the default tool path.

  • crates/octos-pipeline/src/human_gate.rs: provides channel-based human-input abstractions with a default timeout of 5 minutes (:14-15), not wired into PipelineExecutor; the IR palette also deliberately excludes human_gate (13.2.8)
  • crates/octos-pipeline/src/checkpoint.rs: provides the CheckpointStore trait (:127) and FileSystemCheckpointStore (:154); the executor has the optional field ExecutorConfig.checkpoint_store (crates/octos-pipeline/src/executor.rs:427, ExecutorConfig at :387), builds the resume skip set at run start via build_resume_skip_set() (:272, call site :2555), and persists the DOT-declared checkpoint after a node succeeds (:4043)
  • crates/octos-pipeline/src/run_dir.rs: provides RunDir (:17), NodeStatus (:23), PipelineRunSummary (:107), and the convention that the run directory is {working_dir}/.octos/runs/{run_id}/...; but the default RunPipelineTool still has not wired it into an automatic run directory

So checkpoint is not purely an "unwired module": it is already an executor-optional capability, and only RunPipelineTool defaults checkpoint_store to None by default (default-path decision at crates/octos-pipeline/src/executor.rs:1916). The accurate conclusion: the default run_pipeline does no automatic human approval, writes no run_dir, and does not enable checkpoints by default; but a custom executor configuration can enable checkpoint resume / persist.

13.3.8 How the run_pipeline tool exposes pipelines to the Agent

For end users the most common entry is not constructing a PipelineExecutor directly but RunPipelineTool (struct at crates/octos-pipeline/src/tool.rs:109; the file has grown to 3,197 lines). It layers on several practical pieces of engineering:

  • first tries the input as inline DOT; if parsing fails, it tries to resolve the graph name as a preset pipeline
  • it auto-repairs common LLM DOT mistakes such as digraph{, a missing graph name, or code-fence wrapping
  • pipelines resolve by name, path, or inline DOT. The search path is managed by PipelineDiscovery (struct at crates/octos-pipeline/src/discovery.rs:84, new :98, resolve :184): project-level .octos/pipelines, user-level data_dir/pipelines, data_dir/skills, optionally octos_home/skills; plus add_bundled_pipelines_dir() (:147) providing a lowest-priority bundled-pipelines mechanism, which the old draft omitted
  • it clamps a total timeout over the whole pipeline, in the range [60, 3600] seconds, default 1800 (comment at crates/octos-pipeline/src/tool.rs:534, clamp at :1099), no longer the earliest 60-1800; the default can be overridden by the DOT graph attribute default_timeout_secs; on finish it sets a shared shutdown flag to tell all workers to stop (:1118-1119)
  • if the pipeline produced no markdown file but has text output, the tool synthesizes a temporary .md report (.md decision at crates/octos-pipeline/src/tool.rs:1332, file-name pattern run_pipeline_{ts}_{pid}_{seq}.md at :1405), guaranteeing the spawn_only delivery path has a sendable file
  • node_costs is projected into ToolResult.structured_metadata (:1259-1278) so the session actor can carry per-node cost back into UI/API completion metadata
  • the prompt wording of input_schema() (:686) has been rewritten: it states that the only currently sanctioned pipeline name is deep_research and recommends it over a single inline web_search for multi-source research; the typed-IR ir parameter is exposed only when enabled (test at :2917)

One "implementation vs. prompt" split is worth writing into the book: input_schema() advises the model not to write model= explicitly and says the system picks models automatically, but the runtime engine still supports default_model / node.model, and the model_assignment backfill is built on exactly those fields. The advice targets LLM authoring; no underlying engine capability was removed.


Engineering decision: why DOT instead of YAML/JSON

YAML (e.g. GitHub Actions)

Strengths: familiar to humans, mature ecosystem. Weakness: graph structure is not first-class; dependency spellings like needs: get increasingly awkward under branching and convergence.

JSON (e.g. Step Functions)

Strengths: strongly structured, schema-friendly. Weakness: hostile to human authors, especially as node attributes and branch conditions multiply.

DOT (octos's choice)

Strengths:

  • nodes and edges are DOT's native concepts
  • the same definition renders directly in Graphviz
  • attributes like handler / model / tools / converge land naturally on nodes
  • for an LLM, generating a graph is often more stable than generating layered YAML/JSON

Costs:

  • you must implement the parser and validator yourself
  • DOT is not most engineering teams' daily configuration language; the learning curve is slightly steeper

13.4 The division of labor between workflow and pipeline

The old draft never mentioned octos-workflows. After 543010be, the workflow subsystem was extracted from the pipeline crate into the standalone crates/octos-workflows/, depended on directly by octos-server (Cargo.toml:18) and octos-cli (Cargo.toml:28). Its src layout:

  • crates/octos-workflows/src/workflow_runtime.rs: the workflow runtime
  • workflow_families/: crates/octos-agent/src/tools/registry.rs, crates/octos-workflows/src/workflow_families/deep_research.rs, crates/octos-workflows/src/workflows/research_podcast.rs, crates/octos-workflows/src/workflow_families/site.rs, crates/octos-workflows/src/workflow_families/slides.rs
  • workflows/: crates/octos-workflows/src/workflows/research_podcast.rs, crates/octos-workflows/src/workflows/research_report.rs, crates/octos-workflows/src/workflows/site_delivery.rs, crates/octos-workflows/src/workflows/slides_delivery.rs

The division of labor can be put this way: octos-pipeline is the general-purpose graph execution engine, handling DOT/IR parsing, handler dispatch, fan-out, budgets, and events; octos-workflows is the product layer built on top, orchestrating domain processes such as "deep research, podcast, site delivery, slides" into workflow families, registering them in the registry, and scheduling them from the server/CLI entries. Put differently, pipeline answers "how does one graph run"; workflow answers "which graphs, in what order, with what parameters, does this business line run." The Chapter 10 harness and this chapter's 13.3.4 event ABI are the shared observation foundation of the two layers.


13.5 Chapter Recap

  1. octos-pipeline currently has 9 HandlerKinds, of which 7 have Handler trait implementations; Parallel / DynamicParallel are executor branches, and Shell is implemented but banned by Rule 23 and unregistered.
  2. IrNodeKind has 12 variants, each with a compile-time PaletteContract; human_gate is deliberately absent, to prevent a silent approval bypass.
  3. Gate is a condition node, not a wired-up human-approval node; crates/octos-pipeline/src/human_gate.rs is only an abstraction that exists but is not wired into the main execution path.
  4. PipelineHostContext lets pipeline nodes inherit the parent session's cache, output routing, task supervision, and cost ledger; the pipeline is part of the session runtime.
  5. The current main path of model selection is graph.default_model + node.model + backfill by crates/octos-pipeline/src/model_assignment.rs at the throttled entry; ModelStylesheet remains off the main path. CheckpointStore is executor-optional wiring, not enabled on the default tool path; RunDir remains an adjacent module.
  6. Progress travels through structured events in crates/octos-pipeline/src/events.rs; workflow orchestration lives in the separate octos-workflows crate.

Further reading

  • Graphviz DOT Language: https://graphviz.org/doc/info/lang.html
  • DAG scheduling: compare Airflow / Prefect against octos to see the difference between a "static DAG scheduler" and a "graph traverser with runtime routing"

Exercises

  1. crates/octos-pipeline/src/condition.rs already supports the context.* grammar and evaluate_with_context(), but the executor's main path does not feed in a context map. Would you wire that semantics into select_next_edge(), or keep the simpler outcome-only model?
  2. ShellCheck trades a compile-time-locked command string for command execution that is safe to expose to the LLM. If graph authors could declare a "parameterizable read-only command," how wide should the parameter surface open before it collapses back into Shell's arbitrary-execution problem?
  3. The IR palette deliberately excludes human_gate. To wire in real human approval, what would the event ABI and PipelineResult each need to gain?

Version note: This chapter's analysis is based on the implementation in crates/octos-pipeline/src/ at octos main @ 9c157101 (2026-09-03) (src/*.rs about 25,134 lines; crates/octos-pipeline/src/executor.rs 5,591 lines, crates/octos-agent/src/plugins/tool.rs 3,197 lines, crates/octos-pipeline/src/handler.rs 2,140 lines, crates/octos-pipeline/src/parser.rs 1,445 lines). Main evolution: 6b0de6ca expanded the DOT palette to 12 IR node kinds and added the ShellCheck / Notify / Wait handlers; 92175f53 introduced per-node max_iterations; f26d2291 introduced structured progress events; 543010be extracted the workflow subsystem into a standalone crate. Everywhere this book touches Gate, ModelStylesheet, CheckpointStore, RunDir, PipelineHostContext, the cost ledger, and workspace policy, it distinguishes "module exists," "executor-optional wiring," and "the default RunPipelineTool path," rather than concluding from module existence alone.

Chapter 14: Runtime Modes and the Configuration System

Positioning: This chapter explains how octos dispatches its five runtime surfaces (chat, gateway, serve, mcp-serve, acp) from a single CLI entry point, and how 11,944 lines of configuration code organize precedence, layered defaults, and hot reload. Prerequisites: Chapter 5 (the agent loop), Chapter 11 (octos-bus). Who should read it: operators who deploy octos and must choose a runtime posture, and developers who want to trace how the control plane is assembled and how configuration propagates. Orchestration-surface subcommands (goal, peer, ledger, steer) are only located here; their details are Chapter 18's subject.

One octos binary serves at least five very different postures: a terminal session for a human, a resident daemon behind ten messaging channels, a control plane exposing 67 REST endpoints, an MCP server for outer-loop orchestrators, and an ACP agent for editors such as Zed. Users see a subcommand choice; contributors see a set of entry files that share assembly logic: seven entry files totaling 19,485 lines (crates/octos-cli/src/main.rs 268 lines, crates/octos-cli/src/commands/mod.rs 468 lines, crates/octos-cli/src/commands/chat.rs 4,143 lines, the crates/octos-cli/src/commands/gateway/ directory 7,595 lines, crates/octos-cli/src/commands/serve.rs 2,849 lines, crates/octos-cli/src/commands/mcp_serve.rs 1,138 lines, crates/octos-cli/src/commands/acp.rs 3,024 lines).

An earlier draft summarized this layer as "four runtime modes." Measured against octos --help on the main branch as of 2026-09-02, the binary has 28 user subcommands and the postures long since exceeded four: octos serve has become the convergence point for AppState and the control plane, with --stdio making it simultaneously the mount point for the UI Protocol; octos mcp-serve exposes a complete octos session as one coarse-grained MCP tool; octos acp targets Agent Client Protocol clients. This chapter rewrites the layer as five runtime surfaces and gives the full picture of the configuration system (crates/octos-cli/src/config.rs 3,790 lines + crates/octos-cli/src/profiles.rs 7,003 lines + crates/octos-cli/src/config_watcher.rs 608 lines + crates/octos-cli/src/config_layer.rs 543 lines).


14.1 One entry point, five runtime surfaces

14.1.1 From crates/octos-cli/src/main.rs to Command dispatch

All subcommands share one startup path. fn main() sits at crates/octos-cli/src/main.rs:61 and does four things: install the error hook, parse clap arguments, merge layered defaults (octos_cli::config_layer::apply, crates/octos-cli/src/main.rs:80), and execute the subcommand (args.command.execute(), crates/octos-cli/src/main.rs:101).

The subcommand list is pub enum Command (crates/octos-cli/src/commands/mod.rs:114); 28 variants each map to a command struct. The Executable for Command match dispatch starts at crates/octos-cli/src/commands/mod.rs:381:

#![allow(unused)]
fn main() {
// crates/octos-cli/src/commands/mod.rs:381-399 (excerpt)
match self {
    Self::Account(cmd) => cmd.execute(),
    Self::Acp(cmd) => cmd.execute(),
    // …remaining subcommands, same shape…
    Self::McpServe(cmd) => cmd.execute(),
    #[cfg(feature = "api")]
    Self::Serve(cmd) => cmd.execute(),
}

Two details deserve attention. First, Self::Serve is gated by #[cfg(feature = "api")] (crates/octos-cli/src/commands/mod.rs:398-399): a binary compiled without the api feature has no serve subcommand, and the serve log-directory logic at crates/octos-cli/src/main.rs:85-86 is gated the same way. Compile-time trimming is the first boundary of the runtime-surface system; the full list is in Appendix D. Second, commands that emit a machine-readable stream on stdout, such as ACP, MCP, and chat --json, have their console logs routed to stderr (commands::reserve_stdout), because one stray log line corrupts the protocol stream.

octos --help as measured lists 28 user subcommands: account acp admin auth channels chat config cron doctor docs init inbox mcp memory profile mcp-serve serve skills status steer update gateway goal ledger clean completions office peer. Five resident or session-oriented commands define the runtime surfaces; the rest are lifecycle management (auth, profile, account), diagnostics (doctor, status), and the orchestration surface (goal, peer, ledger, steer; see Chapter 18).

14.1.2 The five surfaces at a glance

Runtime surfaceEntry pointSizeFirst-line doc summaryKey symbols
chat (single-machine session)crates/octos-cli/src/commands/chat.rs4,143 linesinteractive multi-turn conversationChatCommand:37, execute:1043, run_chat_peer:828
gateway (multi-channel resident)crates/octos-cli/src/commands/gateway/7,595 linespersistent messaging daemonGatewayCommand:45, Gateway::init:226, runtime run:1789
serve (control plane + --stdio)crates/octos-cli/src/commands/serve.rs2,849 linesstart the REST API serverServeCommand:320, execute:539, run_async:549, build_router:1778
mcp-serve (protocol service)crates/octos-cli/src/commands/mcp_serve.rs1,138 linesM7.2 — octos mcp-serveMcpTransport:72, McpServeCommand:79, run_session:485
acp (protocol service)crates/octos-cli/src/commands/acp.rs3,024 linesrun octos as an ACP agent over stdin/stdoutAcpCommand:100, execute:160, run_async:1163

All line numbers come from assets/ch14-facts.md (baseline 9c157101); the files all live under crates/octos-cli/src/.

14.1.3 The topology of the five surfaces

flowchart LR
    subgraph CLI_ENTRY["CLI entry"]
        MAIN["octos (crates/octos-cli/src/main.rs:61)"] --> LAYER["config_layer::apply<br/>merges cli.&lt;cmd&gt; layered defaults"]
        LAYER --> DISPATCH["Command::execute<br/>crates/octos-cli/src/commands/mod.rs:381"]
    end

    subgraph SURFACES["five runtime surfaces"]
        DISPATCH --> CHAT["octos chat<br/>terminal readline"]
        DISPATCH --> GW["octos gateway<br/>ChannelManager multi-channel"]
        DISPATCH --> SERVE["octos serve<br/>REST/UI Protocol control plane"]
        DISPATCH --> MCPS["octos mcp-serve<br/>run_octos_session"]
        DISPATCH --> ACP["octos acp<br/>ACP over stdio"]
    end

    subgraph SHARED_ASSEMBLY["shared assembly"]
        CONFIG["Config / ProfileStore"]
        LLM["LlmProvider chain"]
        TOOLS["ToolRegistry + ToolPolicy"]
        SESS["SessionManager / EpisodeStore"]
    end

    CONFIG --> LLM
    CHAT & GW & SERVE & MCPS & ACP --> SHARED_ASSEMBLY

Figure 14-1: the five runtime surfaces share one assembly. What differs is the access layer (terminal, channels, HTTP, MCP, ACP); what is shared is configuration parsing, the provider chain, the tool registry, and session storage. This shared plane is exactly the Chapter 1 workspace layering projected onto the CLI: the entry files all live in octos-cli, and every capability comes from lower crates (dependency direction: Chapter 1, Section 1.3, and Appendix A).

14.1.4 Choosing a surface

The five surfaces are not five products; they are five access paths into one agent capability stack. The main variables are "who initiates the interaction" and "how long the process lives":

Dimensionchatgatewayservemcp-serve / acp
Interaction initiatora human at a terminalhumans on messaging channelsWeb/HTTP clientsan outer program
Process lifetimeone sessionresident daemonresident servicetied to the client session
Network exposurenoneoutbound to channel platformslistening port or stdiostdio or a local port
Configuration consumedone configmultiple profiles + sub-accountsprofile registry + layeringper-profile, loaded per task
Typical scenariodevelopment, single-machine usecommunity bots, multi-channel assistantsself-hosted dashboards, API integrationinvoked by an editor or orchestrator

Two rules of thumb. First, surfaces stack but processes do not merge: a deployment can run a gateway (message entry) alongside a serve (dashboard entry); they read the same configuration system but each holds its own data-dir lock. Running gateway and serve in one process is not a currently supported shape. Second, start with the smallest surface: verify configuration and tool behavior in chat first, move to gateway or serve when you need a resident process, and bring in mcp-serve or acp only when a program must call you. Each surface adds operational burden in one direction only: channel credentials, ports, tokens, lock files.


14.2 chat: the single-machine session surface

octos chat is the surface closest to user intuition: a multi-turn conversation in a terminal. ChatCommand (crates/octos-cli/src/commands/chat.rs:37) supports --cwd, --provider, --model, --max-iterations, --verbose, and other overrides; execute (crates/octos-cli/src/commands/chat.rs:1043) builds the Tokio multi-thread runtime and enters the session loop; run_chat_peer (crates/octos-cli/src/commands/chat.rs:828) is the actual conversation driver. The agent loop's unfolding is Chapter 5's subject and is not repeated here.

chat earns its keep as the thinnest verification surface: configuration parsing, provider construction, tool registration, and sandbox policy all take effect at this layer, with no network exposure. When diagnosing a configuration problem, reproduce it in chat first and then investigate gateway or serve; that is the cheapest path.

chat is also one of the three commands that participate in layered defaults ("chat" in LAYERED_COMMANDS): defaults preset in config.cli.chat for --provider, --model, and friends take effect when the user supplies no explicit argument. That turns "which model octos chat uses by default on this machine" into a configuration file you can commit, instead of an alias in everyone's shell history. run_chat_peer (crates/octos-cli/src/commands/chat.rs:828) uses the same agent assembly as gateway and serve, so loop behavior observed in chat in Chapter 5's terms carries over to the other surfaces directly.


14.3 gateway: the multi-channel resident surface

The first-line doc of octos gateway says it plainly: persistent messaging daemon (crates/octos-cli/src/commands/gateway/mod.rs; the directory totals 7,595 lines). It starts a ChannelManager listening on multiple messaging channels and routes incoming messages to the agent of the matching profile. The channel abstraction itself (Telegram, Discord, Matrix, and the rest) is Chapter 10's subject; this section covers only two structural features of gateway as a runtime surface.

First, profiles and sub-account inheritance are structured. Gateway's multi-user support is not "one top-level config.json per person" but ProfileConfig (crates/octos-cli/src/profiles.rs:181) carrying structured sections: a sub-account inherits the parent profile's config.llm contract (LlmProfileConfig, crates/octos-cli/src/profiles.rs:814); absent sections inherit search, deep_crawl, and others; and the parent's env_vars serve as a base layer (resolved through the keychain, crates/octos-cli/src/commands/gateway/profile_factory.rs:108/149). The old draft's "sub-accounts inherit top-level provider/model fields" wording is obsolete: top-level fields are the legacy path; structured sections are the current main path.

Second, gateway is the primary consumer of hot reload. A resident process pays the highest cost for configuration changes (a restart interrupts every channel), so the ConfigWatcher event loop mainly serves this surface (see 14.6.3). The chain is GatewayCommand::execute (crates/octos-cli/src/commands/gateway/mod.rs:159) → run_async (:178) → Gateway::init (:226) → the runtime main loop run (crates/octos-cli/src/commands/gateway/gateway_runtime.rs:1789), with hot-reload state (system_prompt, max_history, config_rx) hung off GatewayRuntime's state.


14.4 serve: the control-plane convergence point

Reading octos serve as "an HTTP shell around chat" is the most common misreading. serve is the convergence point of the control plane: one process assembles a REST API, the UI Protocol WebSocket, event broadcast, profile management, tool policy, and swarm scheduling state. chat is merely one capability it hosts.

14.4.1 Startup assembly

ServeCommand::execute (crates/octos-cli/src/commands/serve.rs:539) builds the Tokio runtime and enters run_async (crates/octos-cli/src/commands/serve.rs:549). Key nodes of the assembly sequence (line numbers in the facts table):

  • ProfileStore::open (crates/octos-cli/src/commands/serve.rs:673/818): the profile registry and model catalog
  • EventBroadcaster::new(256) (crates/octos-cli/src/commands/serve.rs:750): global event broadcast
  • SessionManager::open (crates/octos-cli/src/commands/serve.rs:764): session storage
  • init_metrics() (crates/octos-cli/src/commands/serve.rs:775): Prometheus metrics
  • SwarmState construction (crates/octos-cli/src/commands/serve.rs:1316 onward): swarm scheduling state, where DispatchPolicy::from_agent_gates(tool_policy, true) (crates/octos-cli/src/commands/serve.rs:1969) projects config.tool_policy and the injected-environment-variable denylist into dispatch gates, so swarm backends cannot bypass the native tool policy (swarm details: Chapter 17)
  • build_router(state) (crates/octos-cli/src/commands/serve.rs:1778): turns AppState into axum routes
flowchart TD
    S["octos serve (run_async:549)"] --> LOCK["acquire_serve_data_dir_lock<br/>fs2 flock, single writer"]
    LOCK --> PS["ProfileStore::open :673/818"]
    PS --> EB["EventBroadcaster::new(256) :750"]
    EB --> SM["SessionManager::open :764"]
    SM --> M["init_metrics :775"]
    M --> SW["SwarmState + DispatchPolicy :1316/1969"]
    SW --> R["build_router :1778"]
    R --> STDIO{"--stdio?"}
    STDIO -->|yes| UI["stdio_connection<br/>UI Protocol over stdin/stdout"]
    STDIO -->|no| HTTP["HTTP/WS listener<br/>default 127.0.0.1:50080"]

Figure 14-2: serve's control-plane assembly. Note that the single-writer lock comes first in the sequence: redb is a single-writer, single-process database, and two serves pointed at the same data dir collide. On lock conflict the process emits a machine-greppable OCTOS_DATA_DIR_LOCKED marker (DATA_DIR_LOCKED_MARKER, around crates/octos-cli/src/commands/serve.rs:487); clients such as octoscode grep for that token to recognize the conflict and stop their restart loop, instead of silently crashing every 5 seconds.

14.4.2 --stdio: the UI Protocol mount surface

The branch at crates/octos-cli/src/commands/serve.rs:1541 decides serve's two shapes:

#![allow(unused)]
fn main() {
// crates/octos-cli/src/commands/serve.rs:1541-1546
if self.stdio {
    crate::api::ui_protocol_transport::stdio_connection(state).await?;
    tracing::info!("stopping all gateway child processes");
    let _ = process_manager.stop_all().await;
    return Ok(());
}
}

--stdio mode binds no HTTP: bind_http_listener (crates/octos-cli/src/commands/serve.rs:464-471) returns a None listener under stdio, and the UI Protocol's JSON-RPC traffic flows over stdin/stdout. This is not a test backdoor; it is a production path. octoscode's default stdio chain is

#![allow(unused)]
fn main() {
// octoscode/src/cli.rs:118
pub const DEFAULT_STDIO_COMMAND: &str = "octos serve --stdio --solo";
}

The companion mechanism is --instance-data-dir: multiple stdio instances share one config/profile state home while each holds a private runtime data directory (redb, sessions, serve lock), so "one user with several editor windows open" does not self-collide. stdio mode also reuses serve's entire control-plane assembly (watcher, events, profiles); only the transport changes to pipes.

--stdio also redefines stdout ownership: once the protocol owns stdout, anything written to it is parsed by the client as a JSON-RPC frame, and one debug print is one protocol violation. Tracing logs, panics, and progress hints must all move to stderr; likewise, child processes spawned by serve on the stdio chain inherit stdout and would pollute the protocol stream unless explicitly redirected. This is the root reason the reserve_stdout mechanism exists: the separation of machine-readable streams from human-readable logs must be drawn once, at the entry point.

14.4.3 serve admission gates

The switches exposed by octos serve --help form a deliberately designed set of admission gates (measured output matches assets/ch14-facts.md):

SwitchSemanticsEnvironment variable
--solosingle-user local passwordless login (POST /api/auth/solo*); takes effect only on direct loopback connections in Local mode; requests carrying reverse-proxy headers never qualifyOCTOS_SOLO_LOGIN=1
--danger-full-accessdefaults every session to the FULL-ACCESS tier (sandbox off, network on, approvals skipped); must be paired with --soloOCTOS_DANGER_FULL_ACCESS=1
--no-networkreverts from "network allowed by default" to deny by defaultOCTOS_NO_NETWORK=1
--swarm-backend <stdio|http|cli>swarm backend transport; unset, /api/swarm/* returns 503—

Default bindings favor safety: --host defaults to 127.0.0.1 and --port to 50080 (crates/octos-cli/src/commands/serve.rs:324; the port sits in the IANA dynamic range to dodge common services such as Tomcat/Jenkins, see issue #417). Local sessions default to Workspace-Write with network allowed (the filesystem stays sandboxed; npm install and git work out of the box), and --no-network is the explicit opt-out; cloud/tenant deployments are always network-deny.

flowchart TD
    REQ["serve startup flags"] --> SOLO{"--solo?"}
    SOLO -->|no| NO{"--danger-full-access?"}
    NO -->|yes| REJECT["refuse to start<br/>danger requires solo"]
    NO -->|no| OK1["normal start<br/>default Workspace-Write + network allowed"]
    SOLO -->|yes| LOOP{"direct loopback<br/>and no reverse-proxy headers?"}
    LOOP -->|yes| OK2["solo passwordless login active"]
    LOOP -->|no| NEVER["solo never activates"]
    OK2 --> DANGER{"--danger-full-access?"}
    DANGER -->|yes| FULL["FULL-ACCESS default tier<br/>sandbox off / network on / no approvals"]
    DANGER -->|no| OK1
    OK1 --> NN{"--no-network?"}
    NN -->|yes| DENY["network denied by default"]

Figure 14-3: serve's admission-gate decision flow. An explicit /permissions choice inside a session always takes precedence over these default tiers.

14.4.4 coding/autonomy capabilities and the tool contract

serve does more than "hold conversations": UI Protocol's SessionOpened.capabilities projects a set of coding capabilities according to the features the client declares (constants at crates/octos-cli/src/api/ui_protocol_transport.rs:2037-2060, projected item by item via has_ui_feature):

  • coding.tool_contract.v1 (contract constant crates/octos-cli/src/api/coding_tool_contract.rs:12, contract id codex-compatible-coding-v1, :13)
  • coding.autonomy.v1 (:2037), coding.agent_control.v1 (:2042), coding.goal_runtime.v1 (:2047), coding.loop_runtime.v1 (:2052), plus coding.monitor_runtime.v1 (:2057)

The backend generates the tool contract dynamically from the current ToolRegistry, the deferred tool set, the policy view, and the tools known to be visible to the model, so AppUI can distinguish six tool states (crates/octos-cli/src/api/coding_tool_contract.rs:19-28): available, aliased, deferred, disabled_by_policy, missing, unimplemented. deferred means the tool is registered but sits in the LRU lazy-unload set; the model can restore it via activate_tools, so it still counts as available for contract purposes.

One boundary needs stating: these autonomy capabilities describe backend-supervised orchestration (goals, loops, and agent-control primitives all run under backend supervision), not an unattended self-evolving runtime. The internals of the goal/loop runtimes are Chapter 18's subject; this chapter only locates them on serve's capability surface.

14.4.5 The REST surface: 67 endpoints

Counted with grep -rhoE '\.route\("[^"]+"' crates/octos-cli/src/api/*.rs | sort -u | wc -l (two runs on 2026-09-02 both yielded 67), serve exposes 67 REST endpoints spread across 42 .rs files in the api/ directory. The old draft's "91" no longer holds: endpoints keep being trimmed, and any specific number must carry its measurement command. An endpoint-level reference is Appendix C; the Web Dashboard's frontend is outside this book's scope.


14.5 The protocol-service surfaces: mcp-serve and acp

14.5.1 mcp-serve: exposing only run_octos_session

octos mcp-serve (crates/octos-cli/src/commands/mcp_serve.rs, 1,138 lines) exposes octos as an MCP server for outer-loop orchestrators. The MCP implementation lives in crates/octos-agent/src/mcp_server.rs (1,044 lines): McpServer:169, handle_request:201, HTTP transport streamable_http_service:268.

The boundary design is the heart of this surface: the server exposes exactly one session-level tool, run_octos_session (constant RUN_OCTOS_SESSION_TOOL, crates/octos-agent/src/mcp_server.rs:66). Each call runs one complete octos session (load profile, construct the LLM, create the agent, execute the prompt, validate artifacts), and what the outer loop receives is the aggregated result: it sees no internal tool calls, iteration events, or progress stream. octos's internal tool catalog (59 tools; see Chapter 6) is not exposed. This is the trade-off between a coarse-grained task boundary and a fine-grained tool proxy: the outer orchestrator decomposes the task; the octos session executes autonomously inside the boundary.

flowchart LR
    ORCH["MCP client / outer orchestrator"] -->|"tools/call<br/>run_octos_session"| SRV["McpServer<br/>handle_request:201"]
    SRV --> SES["run_session<br/>crates/octos-cli/src/commands/mcp_serve.rs:485"]
    SES --> AGENT["complete octos session<br/>profile→LLM→Agent→artifact validation"]
    AGENT --> OUT["aggregated result (outcome)"]
    OUT -->|"no internal tool calls / iteration events"| ORCH

Figure 14-4: mcp-serve's session-level dispatch. The transport is one of two (McpTransport, crates/octos-cli/src/commands/mcp_serve.rs:72): the default stdio, whose trust model is parent-trust (the parent process is trusted; no token); or the http transport bound to 127.0.0.1:4033 (the --bind default), which requires OCTOS_MCP_SERVER_TOKEN and refuses to start if it is missing or empty (crates/octos-cli/src/commands/mcp_serve.rs:185-186).

14.5.2 acp: the agent for editors

octos acp (crates/octos-cli/src/commands/acp.rs, 3,024 lines) runs an agent over stdin/stdout per the Agent Client Protocol, serving the agent clients built into editors such as Zed. AcpCommand:100, execute:160, run_async:1163. The difference from mcp-serve lies in protocol and granularity: ACP is a session protocol between an editor and an agent (file context, permission requests, diff display), while MCP is task-level tool invocation. The two share the same configuration and agent assembly, and stdout stays a pure protocol stream in both.

acp and mcp-serve belong to the same "protocol-service surface" because they share a structural constraint: stdin/stdout is the protocol channel, one stray log line is one protocol violation, so both route console logs to stderr (commands::reserve_stdout); neither maintains human-facing UI state, and the presentation of the session (diffs, progress, approvals) is rendered entirely by the client. The difference is session ownership: an ACP session belongs to the editor's user, and permission requests surface to that user as protocol messages; an mcp-serve session belongs to the outer orchestrator, and its permission boundary is fixed once, in the startup configuration.


14.6 The configuration system: four files, 11,944 lines

FileLinesResponsibilityKey symbols
crates/octos-cli/src/config.rs3,790config file parsing and mergingConfig:26, load_with_context:1740, load_resolved:1770
crates/octos-cli/src/profiles.rs7,003multi-user profile managementProfileConfig:181, LlmProfileConfig:814, LlmRouteConfig:881
crates/octos-cli/src/config_watcher.rs608hot-reload pollingConfigChange:17, spawn:87, diff_and_emit:241
crates/octos-cli/src/config_layer.rs543startup-time layered defaultsLAYERED_COMMANDS:40, apply:48

14.6.1 The precedence chains

File-level parse precedence (from the load_resolved comment in crates/octos-cli/src/config.rs):

  1. project-local <cwd>/.octos/config.json (read only in the default context)
  2. <config_home>/config.json
  3. legacy ~/.octos/config.json

An explicit --config or a tenant context does not read the project-local file. Local-first precedence lets different projects use different providers and tool policies; the cost is that diagnosing "why does this machine behave differently" means checking one more file.

A second precedence chain operates at startup, on the CLI arguments themselves (module docs at crates/octos-cli/src/config_layer.rs:5-8):

explicit CLI flag  >  env var  >  config.json `cli.<cmd>`  >  built-in default

clap already resolves "CLI > env > default"; config_layer::apply (called at crates/octos-cli/src/main.rs:80) fills in the middle layer: fields the user gave neither on the command line nor through an environment variable fall through to config.cli.<cmd>. Only three subcommands participate: LAYERED_COMMANDS = ["serve", "gateway", "chat"] (crates/octos-cli/src/config_layer.rs:40). "Was it explicit?" is decided by clap::ArgMatches::value_source, the one mechanism that covers both scalar defaults (--port) and bare boolean switches (--solo). Dangerous switches (--danger-full-access, --yolo) and secret fields are explicitly excluded from layering; they can come only from the command line.

flowchart TD
    START["octos &lt;cmd&gt; start"] --> PARSE["clap parse<br/>CLI > env > default"]
    PARSE --> APPLY["config_layer::apply<br/>fills config.cli.&lt;cmd&gt;"]
    APPLY --> CTX{"explicit --config / tenant?"}
    CTX -->|yes| SKIP["skip project-local files"]
    CTX -->|no| P1["① cwd/.octos/config.json"]
    P1 --> P2["② config_home/config.json"]
    P2 --> P3["③ legacy ~/.octos/config.json"]
    SKIP --> MERGE
    P3 --> MERGE["load_resolved merge + typed schema validation"]
    MERGE --> RUNTIME["runtime Config"]
    RUNTIME -.->|"every 5s, SHA-256 compare"| WATCH["ConfigWatcher"]
    WATCH --> DIFF["diff_and_emit:241"]
    DIFF --> HOT["HotReload"]
    DIFF --> RESTART["RestartRequired"]

Figure 14-5: configuration resolution and hot reload. The typed schema introduced in 3a567a4c changed inference parameters (profile/llm/*) from "silently drop unknown fields" to "reject": a mistyped key in the configuration now errors at startup instead of quietly falling back to defaults (comment around crates/octos-cli/src/config.rs:273). This is the configuration system's most important tightening in recent years.

14.6.2 Structured profile configuration

crates/octos-cli/src/profiles.rs (7,003 lines) is the configuration system's largest file and carries multi-user deployment: ProfileConfig:181 defines the structured sections, ProfileConfigPatch:741 supports patch semantics, and the three LLM pieces are LlmProfileConfig:814, LlmModelSelectionConfig:824, and LlmRouteConfig:881. What gateway sub-accounts inherit is precisely these structured sections plus the env_vars base (see 14.3), with sensitive variables resolved through the keychain (crates/octos-cli/src/commands/gateway/profile_factory.rs:108/149).

In crates/octos-cli/src/config.rs, mcp_servers: Vec<McpServerConfig> (:110) and sub_providers: Vec<SubProviderConfig> (:184, defined at :618) are only named here: the former is the mount configuration for external MCP tools (see Chapter 9), the latter the sub-provider chain; full field references for both are in Appendix C.

14.6.3 The hot-reload watcher

ConfigWatcher (crates/octos-cli/src/config_watcher.rs:28) polls the configuration files every 5 seconds and detects changes by comparing SHA-256 hashes (that is the first-line doc's stated semantics). Change classification is expressed by the ConfigChange enum (:17):

#![allow(unused)]
fn main() {
// crates/octos-cli/src/config_watcher.rs:17-25
pub enum ConfigChange {
    /// Fields that can be applied without restart.
    HotReload {
        system_prompt: Option<String>,
        max_history: Option<usize>,
    },
    /// Fields changed that require a restart. Log warning only.
    RestartRequired(Vec<String>),
}
}

diff_and_emit (:241) compares field by field and routes: HotReload has only two members, system_prompt and max_history (gateway sub-fields); everything else falls into RestartRequired(Vec<String>), which only warns. The current restart-required list: base_url, api_key_env (they affect HTTP client construction), sandbox, mcp_servers, hooks (external connections must be rebuilt), format_after_edit (baked into AgentConfig at startup, #1774), plugins (the signature gate is consumed only at load), gateway.queue_mode, gateway.channels (they affect the message main loop).

The watcher's workflow has four steps. At startup, ConfigWatcher::new (:44) receives the set of paths to watch; in profile mode, with_profile_defaults (:67) also brings the global profile-defaults.json under watch, so editing the shared defaults layer triggers the same reload path; spawn (:87) starts the background task and its 5-second polling loop; each poll reads all existing files, concatenates them, and computes one SHA-256; if the hash is unchanged it skips, and only a changed hash triggers parsing the new configuration and handing it to diff_and_emit for classification. The classification goes out over a tokio::sync::watch channel; the consumer (mainly the gateway main loop) writes system_prompt into an RwLock<String> and max_history into an atomic counter on HotReload; neither write path needs to pause message processing.

Two robustness details are worth recording. First, the defaults layer keeps a last-known-good: if a previously valid profile-defaults.json is edited into an invalid one, the watcher keeps using the last correct parse rather than silently dropping the whole base layer; a file that was never valid stays None. Second, a main configuration that fails to parse likewise keeps the old value and warns; a broken configuration does not take down a running process.

provider/model file changes go down neither path: the watcher neither classifies them as HotReload for automatic application nor reports RestartRequired anymore; switching at runtime goes through an explicit path (the model_check tool triggering SwappableProvider.swap; see Chapter 3). The safe mental model: changing system_prompt/max_history takes effect within five seconds; changing provider/model means either an explicit in-session switch or a process restart; changing base_url/hooks and friends always means a restart.

Profile policy flips have a regression note against false positives (crates/octos-cli/src/config_watcher.rs:136-150): the presence of the parent-profile defaults layer makes a naive diff misjudge inherited values as changes, and the watcher special-cases this layer. The choice of polling over inotify is cross-platform: inotify is Linux-only, macOS uses kqueue, Windows uses ReadDirectoryChangesW, and a 5-second SHA-256 poll behaves identically on all three at negligible cost. The watcher also reads all files and hashes them together in one pass, avoiding the check-then-read TOCTOU race; on parse failure it keeps the last valid configuration and warns rather than crashing on a broken one.


Engineering decision: why --danger-full-access must be paired with --solo

--danger-full-access defaults every new session to FULL-ACCESS: sandbox off, network on, no approvals. Exposed on a network, that tier hands host execution to anyone who can reach the port. So its activation precondition is isomorphic to --solo's: --solo itself takes effect only on a direct loopback connection in Local mode with no reverse-proxy headers on the request, and the two switches share one key, "local, single user." Binding the sandbox-free tier to single-user local login equates to binding it to the precondition "the attacker must first log into this machine's operating system." The environment variable (OCTOS_DANGER_FULL_ACCESS=1) cannot bypass this: a serve started without --solo is refused outright.

The generalizable form of this binding: the gate on a dangerous capability should not be an independent boolean switch but a reuse of an already-audited chain of trust. A standalone --danger-full-access will sooner or later end up in a systemd unit bound to 0.0.0.0; with the binding, the state "remote + sandbox-free" is illegal at the entrance.

Engineering decision: the boundary between hot reload and full restart

Only system_prompt and max_history can hot-reload; the former is stateless text (effective on the next LLM call), the latter a count (atomically replaced). The list is short because every additional hot-reload item must answer two questions: "do in-flight sessions use the old value or the new one?" and "how do we roll back a failed replacement?" base_url and api_key_env affect connection pools and TLS; replacing them at runtime can tear in-flight requests. hooks carry circuit-breaker counters; swapping the command without resetting state leaves a tripped hook unrecoverable forever. format_after_edit is baked into AgentConfig at startup, copied separately by all three entry points (chat/gateway/serve), with no shared mutable point. The dividing principle: stateless or single-valued fields hot-reload; fields with connections, state, or baked-in copies require a restart. provider/model sits in between, so it takes a third path: no file hot-reload, but a controlled runtime switch interface.


14.7 Feature flags: the compile-time runtime surface

From crates/octos-cli/Cargo.toml:142, [features] default = []: the default build is the minimal set. api (:154) pulls in axum/rustls/prometheus and, with them, octos-bus/api and matrix; every messaging channel has its own gate (telegram, discord, dingtalk, slack, whatsapp, email, feishu, twilio, wecom, line, matrix, wecom-bot), each mapping to an octos-bus channel build; embed-llama/-metal/-cuda (:147-149) control the local embedding model. The very existence of Command::Serve is gated by #[cfg(feature = "api")] (crates/octos-cli/src/commands/mod.rs:398).

Its relation to the five runtime surfaces is two-layered: surface choice happens at runtime (subcommand dispatch), capability trimming at compile time (feature gates). Deploying a gateway that only connects to Telegram does not require compiling the REST server; conversely, a serve deployment need not compile unused channels. The full list is in Appendix D.


14.8 Chapter Recap

  1. Five runtime surfaces: chat (single-machine session), gateway (multi-channel resident), serve (control-plane convergence + --stdio mount), and mcp-serve/acp (protocol services), all dispatched from Command::execute (crates/octos-cli/src/commands/mod.rs:381) and sharing configuration, the provider chain, the tool registry, and session storage; the entry files total 19,485 lines.
  2. serve is the control-plane convergence point: it assembles ProfileStore, EventBroadcaster, SessionManager, metrics, SwarmState, and 67 REST endpoints (measurement command in the facts table); --stdio is octoscode's default production chain (octos serve --stdio --solo), and the single-writer lock marks conflicts with OCTOS_DATA_DIR_LOCKED.
  3. serve admission gates: default 127.0.0.1:50080; --solo works only on loopback; --danger-full-access is forced to pair with --solo; network is allowed by default with --no-network as the opt-out; coding/autonomy capabilities are a projection of backend-supervised orchestration.
  4. mcp-serve exposes only run_octos_session: a session-level aggregated result, with the internal tool catalog never exposed; stdio is parent-trust, and HTTP must carry a token.
  5. The configuration system is an 11,944-line four-piece set: the file precedence chain (project-local > config_home > legacy), the startup layering chain (CLI > env > cli.<cmd> > default, with only serve/gateway/chat participating), the typed schema rejecting unknown fields, and the watcher's 5-second SHA-256 polling, with hot reload limited to system_prompt/max_history.

Further reading

  • The MCP specification (Model Context Protocol): https://modelcontextprotocol.io (the tools/call semantics that run_octos_session follows).
  • Agent Client Protocol: https://agentclientprotocol.com (the session protocol between editors such as Zed and agents).
  • The Config chapter of 12-Factor App: https://12factor.net/config (compare with this chapter's four-layer chain of "explicit CLI > env > config > default").
  • Appendix C (configuration field reference) and Appendix D (feature flag survey) of this book.

Exercises

  1. --stdio mode reuses serve's entire control-plane assembly but serves a single client. To support "one data dir, eight editor windows," where should the shared/private boundary of --instance-data-dir be drawn? Which stores must be private, and which can be shared?
  2. The watcher's RestartRequired only warns, never acts. To turn a gateway.channels change in gateway into a "planned restart" (drain in-flight messages, then self-restart), what preconditions are needed to guarantee no message loss?
  3. mcp-serve's coarse-grained boundary leaves tool choice inside the octos session. If an outer orchestrator needs "approval before every tool call," does the boundary still hold? At which layer should the approval primitive be added?
  4. config_layer uses value_source to tell "the user gave it explicitly" from "a default." Without that mechanism, judging emptiness yourself with Option<T> fields, what would the 28 command structs pay?

Version note This chapter is written against octos main @ 9c157101 (committed 2026-09-02, measured 2026-09-03); reproduction commands for every line number and figure are in assets/ch14-facts.md. The main updates over the v1 draft (Chapter 13): first, "four runtime modes" was rebuilt as "five runtime surfaces," with acp and serve --stdio promoted to first-class citizens and the 28 octos --help subcommands verified word for word; second, the REST endpoint count was revised from 91 to 67 (measurement command included; the old number no longer holds); third, this chapter adds the serve admission gates (--solo/--danger-full-access/--no-network/--swarm-backend), the coding/autonomy capability projection and the tool contract's six states, the OCTOS_DATA_DIR_LOCKED single-writer lock, the config_layer layered-defaults chain, and the typed schema's reject semantics. The old draft's detailed SwappableProvider walkthrough moved to Chapter 3; this chapter keeps only its relation to the hot-reload boundary.

Chapter 15: Production: Storage, Services, the Operations Plane, and Multi-Tenancy

Positioning: This chapter analyzes the three pieces of infrastructure octos extracted on its way from a development tool to a production system: octos-store (persistence), octos-services (support services), and octos-diagnostics (diagnostics), plus tenant isolation and the frpc tunnel deployment path. Prerequisite: Chapter 14 (runtime modes). Intended readers: operators who need to deploy octos in production (reader D), and developers who want to see how a giant CLI crate can be split safely (reader B).

A system that runs and a system you can hand to someone else to operate for years are separated by a batch of unglamorous machinery: where credentials are stored, how audit trails are kept, how usage is metered, how failures are diagnosed, how tenants stay invisible to one another. No user ever asked for any of these features, but without any one of them the deployment stops one day.

octos reached production through three extractions. The first pulled the persistence code scattered across octos-cli into octos-store; the second pulled out support services as octos-services; the third pulled diagnostics and the update-planning logic into octos-diagnostics. This chapter follows those three crates, then the four-layer tenant isolation model and the frpc tunnel deployment path, and finally assembles the operations plane (metrics, event streams, alerting, self-update, doctor) into one complete production control plane.

The three authentication flows (OAuth PKCE, device code, paste-token) and the full Hooks lifecycle walkthrough are covered at their old chapter locations; this chapter keeps only the conclusions: credentials are stored in ~/.octos/auth.json with 0o600 permissions on Unix (crates/octos-cli/src/auth/store.rs:59-71); bearer token comparison uses a constant-time implementation to avoid timing side channels (crates/octos-cli/src/api/router.rs:1124-1233); for Hooks' shell protocol (stdin JSON + exit code) and circuit breaker, see Chapter 10. The point of this arrangement is to spend the pages on what the extractions actually changed.


15.1 Why split: the extraction history of three crates

15.1.1 The state before extraction

Everything production-related used to live inside octos-cli: admin token storage at crates/octos-store/src/admin_token_store.rs, the setup wizard state at crates/octos-store/src/setup_state_store.rs, the SMTP password at crates/octos-store/src/smtp_secret_store.rs, tenant management at crates/octos-services/src/tenant.rs, self-update at crates/octos-services/src/updater.rs. These were all leaf modules with no dependency on the CLI command layer, yet they compiled and tested alongside thousands of lines of command code.

The problem was dependency direction. These storage modules depended only on serde and the file system, but because they lived in octos-cli, they were indirectly bound to the CLI's entire dependency closure. Running a unit test meant pulling in half the crate's build artifacts; reusing audit or install-method probing in another binary (octoscode's doctor, say) meant copying code.

The before/after shape change comes through in three cross-sections. First, dependency edge direction: after extraction, both crates point only at octos-core in the Cargo dependency graph (services additionally at octos-llm and octos-bus), with no edge back to octos-cli; before extraction these modules had no isolation from the command layer, and a one-line change to the octos serve AppState definition recompiled all eight stores. Second, test inputs: before the split, testing AdminTokenStore meant setting up tempdir fixtures inside octos-cli's test tree; after, the crate ships its own #[cfg(test)], and the tests at the tail of crates/octos-store/src/admin_token_store.rs directly assert the 0o600 permission bits (crates/octos-store/src/admin_token_store.rs:182) with no external environment. Third, artifact granularity: tools beyond the CLI binary (diagnostics, reporting, the future CLI-agent adapter) can now link only store/services instead of dragging in the whole CLI. The motivation for extracting octos-diagnostics was more direct still: octoscode's doctor/install_method modules needed the same probes as the octos server, two copies would inevitably drift, so the product-agnostic part sank into a crate and product differences narrowed to the single ProductSpec entry point (see the ADR in the crate docs, octoscode#182).

15.1.2 octos-store: the persistence layer, 9 files, 2,664 lines

After extraction, crates/octos-store/ is a pure persistence crate: 9 source files totaling 2,664 lines (crates/octos-store/src/lib.rs at 18 lines plus 8 store modules; line counts come from the facts table's tally against main @ 9c157101). The module docs of crates/octos-store/src/lib.rs state the provenance outright: "Self-contained persistence / state stores extracted from octos-cli".

FileLinesResponsibilityKey symbols
crates/octos-store/src/admin_token_store.rs184salt+hash storage of the admin tokenAdminTokenRecord(:14) AdminTokenStore(:56)
crates/octos-store/src/admin_audit_store.rs270admin operations audit (redb)AdminAuditStore(:109)
crates/octos-store/src/approvals_audit.rs414approval-decision audit (JSON-Lines append)ApprovalsAuditLog(:119)
crates/octos-store/src/login_allowlist.rs258login allowlist (retry with lock)LoginAllowlistStore(:28)
crates/octos-store/src/setup_state_store.rs151first-run wizard stateSetupStateStore(:24)
crates/octos-store/src/smtp_secret_store.rs133SMTP password fileSmtpSecretStore(:17)
crates/octos-store/src/usage_ledger.rs901usage ledger (redb)UsageEvent(:42) PersistentUsageLedger(:323)
crates/octos-store/src/user_store.rs335multi-user management (one JSON per user)UserStore(:40)

Eight stores cover the full state surface of a production deployment: identity (token, user, allowlist), lifecycle (setup), secrets (smtp secret), audit (admin audit, approvals audit), billing (usage ledger). Note that the storage media split into two kinds: simple state uses single-file JSON, while high-append data (usage ledger at 901 lines, admin audit at 270) uses redb, an embedded KV store. That boundary is itself an engineering judgment; see this chapter's sidebar.

Take crates/octos-store/src/admin_token_store.rs as the shape of things after extraction. The file's front-page docs state: "Hashed admin auth token stored at {data_dir}/admin_token.json. Replaces the static config/env bootstrap token once rotated." The record struct has exactly four fields (crates/octos-store/src/admin_token_store.rs:14-21):

#![allow(unused)]
fn main() {
pub struct AdminTokenRecord {
    /// 16 random bytes, base64 (URL-safe, no padding).
    pub salt: String,
    /// sha256(salt_bytes || token_bytes), base64 (URL-safe, no padding).
    pub hash: String,
    pub created_at: DateTime<Utc>,
    pub created_by: String,
}
}

The verify function verify() rebuilds the expected hash from the salt, then compares with constant_time_eq (crates/octos-store/src/admin_token_store.rs:39-45); saving goes through a temp file plus rename, setting 0o600 on Unix (crates/octos-store/src/admin_token_store.rs:96-104). Not one line of CLI code is in the file, and the tests run with nothing more than a tempdir.

The largest, crates/octos-store/src/usage_ledger.rs (901 lines), is a ledger that records one row per LLM run: the UsageEvent struct sits at :42, the redb persistence entry point PersistentUsageLedger at :323. One field choice deserves attention: cache-read tokens are recorded separately. The doc comment explains that the prompt totals reported by providers include cache hits, while TokenUsage already subtracts the cached portion at the provider boundary, so the complete prompt count is input_tokens + cache_read_tokens (crates/octos-store/src/usage_ledger.rs:52-66). That makes "how much did caching actually save" a question answerable from historical data instead of a live probe against the API.

15.1.3 octos-services: the support-services layer, 8 files, 3,223 lines

The second extraction produced crates/octos-services/, 8 source files totaling 3,223 lines. The crates/octos-store/src/lib.rs docs likewise name the origin: "Self-contained support services extracted from octos-cli". There are 7 modules:

FileLinesResponsibilityKey symbols
crates/octos-services/src/cli_agent_adapter.rs587process boundary for a future CLI-agent adapterCliAgentProcess(:145)
crates/octos-agent/src/agent/compaction.rs320session compactionmaybe_compact(:37)
crates/octos-services/src/config_context.rs698the single resolution entry for config/credential/data pathsresolve_config_context(:151)
crates/octos-services/src/persona_service.rs479periodically generates a communication-style profilePersonaService(:97)
crates/octos-services/src/soul_service.rs139per-user personality storageread_soul(:24)
crates/octos-services/src/tenant.rs512tenant tunnel managementTenantStore(:82) render_frpc_config(:255)
crates/octos-services/src/updater.rs473self-update: download, verify, backup, replace, rollbackUpdater(:33)

The two crates' dependencies were trimmed deliberately: octos-store and octos-services both depend only on octos-core (plus serde/eyre and similar infrastructure); because services must call the LLM and the message bus, it additionally depends on octos-llm and octos-bus (per the Cargo dependency check in facts table §2). In the post-extraction dependency graph both sit in the leaf direction and can no longer infect anyone else with the CLI's weight.

crates/octos-services/src/config_context.rs (698 lines) is the module in this batch most worth pausing over. Its docs call it "Canonical config/auth/data path resolver, the single source of truth": every config path, credential path, and data directory path must be resolved through resolve_config_context; modules are not allowed to assemble paths on their own. The rule answers an old pain point directly: the same path assembled separately in multiple modules drifts as soon as runtime modes multiply.

15.1.4 octos-diagnostics: diagnostics and update planning, 8 files, 2,243 lines

The newest extraction is crates/octos-diagnostics/, 8 files, 2,243 lines, landed in two stages: Stage 1 (commit 7f81fa5e) delivered the crate itself and octos doctor; Stage 2 (commit 1801a9e9) added the GitHub client plus update --check and the Network check.

One word recurs throughout this crate's module docs: product-agnostic. It is not octos-specific; the same diagnostic kernel must serve both the octos and octoscode binaries. The seam that makes this reuse work is ProductSpec in crates/octos-diagnostics/src/spec.rs (173-line file, facts table §3):

Callers describe their product once via a ProductSpec; everything else (install-method labels/upgrade hints, PATH/shadow locating, asset selection) reads from it.

The docs then lay down a hard rule (the "Traps" section of the ADR): the current version number must be passed in by the caller. This crate must never read its own CARGO_PKG_VERSION to describe the product, or the diagnostic report would print the diagnostics crate's version instead of the diagnosed binary's (crates/octos-diagnostics/src/spec.rs:7-9).

The file inventory: crates/octos-diagnostics/src/checks.rs at 400 lines (local checks like terminal environment and config/data directories), crates/octos-diagnostics/src/github.rs at 321 lines (blocking GitHub Releases client), crates/octos-diagnostics/src/install_method.rs at 505 lines (install-method probing), crates/octos-diagnostics/src/locate.rs at 278 lines (PATH resolution and shadow detection), crates/octos-diagnostics/src/report.rs at 312 lines (report model, CheckStatus/Check), crates/octos-diagnostics/src/spec.rs at 173 lines (the ProductSpec seam), crates/octos-diagnostics/src/update.rs at 198 lines (semver parsing and a pure-function update planner).

15.1.5 The extraction criterion

Put the three crates side by side and the extraction criterion is stable: a module that does not depend on the CLI command layer, has independent test value, or needs reuse by a second binary is a candidate. Conversely, code that depends on AppState or routing (handlers, middleware) stayed in octos-cli and did not move. That is a reusable boundary: split by dependency direction, not by domain noun.

Engineering decision: redb or JSON files?

Two storage media coexist in octos-store: login/setup/admin_token/smtp_secret/user are single-file JSON, while usage_ledger and admin_audit use redb. The choice follows the write shape. The former are small states read and written whole: one file per dataset, human-readable, backup is file copy. The latter are append-only streams read by query predicate; appending to a JSON file either rewrites the whole file or degenerates into hand-rolled indexing, and redb's persistent B-tree lands exactly in between. When deciding the medium for a new store, ask the write shape first, then the data volume, and only then query complexity.


15.2 Multi-tenancy: four layers of isolation

octos multi-tenancy is not a tenant ID field; it is an isolation model stacked from four layers: Profile, Account, User, Session. The distribution of tenancy vocabulary across the code tells that story plainly: the word tenant hits 2,261 times under crates/, and the top file is not any tenant module but crates/octos-cli/src/autonomy/agent_orchestrator.rs (921 hits), followed by crates/octos-cli/src/api/admin.rs (138), crates/octos-cli/src/api/auth_handlers.rs (130), and crates/octos-cli/src/api/ui_protocol_transport.rs (102) (grep tallies from facts table §4). The tenant concept has soaked into orchestration, the admin API, authentication, and transport alike.

15.2.1 Where the boundary is defined

The isolation rules are defined at crates/octos-core/src/session_scope.rs:46-68. The docs are blunt: in multi-tenant mode (octos serve + the AppUI web client), multiple tenants share one octos process, each with its own profile directory <config_dir>/profiles/<tenant_id>/; cross-tenant access is rejected unconditionally; cross-session writes are rejected at the workspace layer; cross-session reads require an explicit user action (/resume, recall), with no implicit CWD scanning. Solo mode (octos chat) has no tenant boundary: session and workspace merge into the user's chosen CWD, and cross-session continuity is a feature.

15.2.2 Sub-accounts: what is inherited, what is not

Beneath tenants sits a sub-account layer. The creation entry is create_sub_account (crates/octos-cli/src/profiles.rs:2048), with three rules: the parent profile must exist; the parent must not itself be a sub-account (no multi-level nesting); the count is capped by MAX_SUB_ACCOUNTS_PER_PARENT = 10 (crates/octos-cli/src/profiles.rs:16). Sub-account IDs look like {parent_id}--{sub}; on creation config.llm is set to None (crates/octos-cli/src/profiles.rs:2092 vicinity), to be resolved through inheritance at runtime.

Inheritance happens in resolve_effective_profile (crates/octos-cli/src/profiles.rs:2403-2450), with rules in three tiers by field:

#![allow(unused)]
fn main() {
// Inherit the LLM contract from parent.
ec.llm = pc.llm.clone();
if ec.review.is_none() { ec.review = pc.review.clone(); }
// ...(search / deep_crawl / apps / email / tool_policy 同为 None 才继承)
// Merge env_vars: parent as base, sub-account overrides win
let mut merged_env = pc.env_vars.clone();
merged_env.extend(ec.env_vars.clone());
ec.env_vars = merged_env;
}

Tier one is llm: unconditional wholesale override; the parent's LLM contract is the child's LLM contract. Tier two is review/search/deep_crawl/apps/email/tool_policy: inherit only when the child leaves the field unset (None); if the child sets it, the child wins. Tier three is env_vars: the parent is the base, the child's same-named variables override, then merge.

One thing is explicitly not inherited: customer-installed skills. A sub-account's skills directory is resolved strictly against the current account and does not travel along resolve_effective_profile's config inheritance chain (facts table §4 cites the skills layer semantics at crates/octos-cli/src/profiles.rs:360-407). The security implication is plain: a skill installed in the parent account does not mean every sub-account automatically gains the ability to execute it.

The mental model for this layering: the parent account provides the shared capability contract (LLM, search, email policy); sub-accounts provide the access surface and differentiated overrides (channel credentials, public subdomains, a handful of environment variables). Inheritance is explicit and per-field; "a sub-account is implicitly equal to its parent" is not a semantics that exists here.

15.2.3 The session actor and process-level isolation

Concurrency isolation inside one process falls to the session actor: the docs at crates/octos-cli/src/session_actor.rs:1-3 describe an actor with one tokio task per session replacing the old spawn-per-message model; on the gateway side, crates/octos-cli/src/commands/gateway/profile_factory.rs:1-4 builds a dedicated ActorFactory per profile, carrying its own LLM stack, tool registry, skills, and system prompt.

This replacement fixed a specific race, and the file's front-page docs name it: in the old spawn-per-message model, shared tools switched session context via set_context(), so when two messages arrived concurrently, the later set_context could route the earlier message into the wrong chat (the comment at crates/octos-cli/src/session_actor.rs:1-4, verbatim). The actor model's answer changes "who owns the tools" from shared mutable state to per-task private state: messages enter a mailbox, the task processes them serially, and context no longer survives across messages. The isolation boundary thus goes from "convention" to "structure": two sessions share no tool registry instance, so misrouting has nowhere to happen at the type level. profile_factory adds a layer on top: when a message arrives addressed to a specific profile (a Matrix sub-bot, say), it builds right there a factory carrying that profile's own LLM stack and tool registry, so a sub-account session gets a runtime fully independent of the parent's.

Process-level isolation is a second path: in process-manager mode, each profile launches its own octos gateway child process, with configuration passed via --profile, --data-dir, --cwd, and similar arguments. The two layers are not mutually exclusive; the production management plane usually goes through process-manager.

The limit of the isolation layers must be stated plainly as well: even split into child processes, without cgroups or system-level quotas, one profile's CPU or memory pressure still affects other profiles on the same host. The process boundary blocks filesystem and configuration cross-talk, not resource contention. When capacity-planning a multi-tenant host, system-level measures must be added separately.

flowchart TD
    subgraph 宿主["宿主机(需要系统级限额补足)"]
        PM["ProcessManager"]
        subgraph GW1["gateway 子进程: profile A"]
            A1["session actor 1"]
            A2["session actor 2"]
        end
        subgraph GW2["gateway 子进程: profile A--sub1"]
            B1["session actor"]
        end
        SRV["octos serve(AppUI 多租户)"]
        TS["TenantStore<br/>data_dir/tenants/*.json"]
    end
    PM --> GW1
    PM --> GW2
    SRV --> TS
    SRV -.->|"同进程内 profile 目录隔离"| GW1

Figure 15-1: tenant and process, two layers of isolation. Inside the serve process, isolation is per-profile directory; under process-manager, each profile additionally gets its own gateway child process; the resource boundary needs system-level quotas to complete.


15.3 The deployment path: frpc tunnels

To land multi-tenancy on a real deployment, octos chose an frp tunnel scheme. The vehicle is crates/octos-services/src/tenant.rs (512 lines), whose module docs describe "Tunnel tenant management for self-hosted Mac Mini deployments". The overall topology: the management plane runs on a VPS, each tenant's octos instance runs on its own machine, and frp tunnels connect the two.

15.3.1 TenantConfig and the port pool

The core tenant-config struct sits at :23, with fields id (slug), subdomain (the tunnel subdomain), tunnel_token (per-tenant tunnel token, a UUID), ssh_port (the SSH tunnel port allocated on the VPS side), local_port (the serve port on the tenant's machine, default 8080), auth_token, owner, and status timestamps.

The port pool is an explicit constant (crates/octos-services/src/tenant.rs:14-15):

#![allow(unused)]
fn main() {
pub const SSH_PORT_START: u16 = 6001;
pub const SSH_PORT_END: u16 = 6999;
}

The allocation algorithm is next_ssh_port (:185-194): list existing tenants, collect occupied ports, find the first free port sequentially from 6001, and error out when the pool is exhausted. The query family has four entries, find_by_tunnel_token(:197), find_by_subdomain(:203), find_by_ssh_port(:209), find_by_owner(:219), serving tunnel authentication, subdomain routing, port deduplication, and owner-scoped listing respectively.

The tenant ID validation is also worth a look: the test cases cover rejecting empty IDs, uppercase, leading/trailing hyphens, and path traversal (../etc, .., foo/bar, .hidden all rejected; the test group around crates/octos-services/src/tenant.rs:270-310). Because tenant IDs get concatenated directly into profile directory paths and file names, ID validation is the first gate of path safety.

15.3.2 render_frpc_config: template substitution

The tunnel-config generation entry sits at :255:

#![allow(unused)]
fn main() {
pub fn render_frpc_config(
    tenant: &TenantConfig,
    frps_server: &str,
    frps_port: u16,
    tunnel_domain: &str,
    frps_token: &str,
) -> String {
    let template = include_str!("../../../scripts/frp/tenant-frpc.toml.template");
    template
        .replace("{{FRPS_SERVER}}", frps_server)
        .replace("{{FRPS_PORT}}", &frps_port.to_string())
        .replace("{{FRPS_TOKEN}}", frps_token)
        .replace("{{SUBDOMAIN}}", &tenant.subdomain)
        .replace("{{LOCAL_PORT}}", &tenant.local_port.to_string())
        .replace("{{SSH_REMOTE_PORT}}", &tenant.ssh_port.to_string())
        .replace("{{TUNNEL_DOMAIN}}", tunnel_domain)
}
}

The implementation is a compile-time-embedded TOML template plus placeholder substitution, with seven placeholders covering the frps server, port, token, subdomain, local port, remote SSH port, and tunnel domain. include_str! ships the template inside the binary, so deployments need no extra template file. The use of tunnel_token is spelled out in the TenantConfig field comment: it serves as frpc.toml's auth.token, and the frps plugin validates md5(tunnel_token + timestamp) at the Login stage (crates/octos-services/src/tenant.rs:29-30).

flowchart LR
    subgraph Tenant["租户机器(Mac Mini 等)"]
        Serve["octos serve<br/>local_port 8080"]
        Frpc["frpc(render_frpc_config 产出)"]
    end
    subgraph VPS["VPS(frs 服务端)"]
        Frps["frps"]
        Admin["octos 管理面<br/>TenantStore"]
    end
    Browser["浏览器 xxx.tunnel-domain"]
    Browser -->|"subdomain 路由"| Frps
    Frps <-->|"隧道<br/>tunnel_token 认证"| Frpc
    Frpc --> Serve
    Admin -->|"分配 ssh_port 6001-6999<br/>渲染 frpc.toml"| Frpc

Figure 15-2: tenant tunnel deployment. The management plane on the VPS maintains the TenantStore, allocates a subdomain and an SSH remote port per tenant, and renders the frpc config; the serve instance on the tenant's machine is exposed through the frp tunnel.

The scheme fits self-hosted small-scale deployments: one machine per tenant, with the management plane centrally allocating subdomains and ports. Scale further and the model, a port pool capped at 999 tenants and one tunnel per tenant, needs a redesign.


15.4 The operations plane: metrics, event streams, alerting, self-update, diagnostics

Assembling the three crates with the API layer yields a complete operations plane. Ordered from "reading state" to "acting to fix": Prometheus metrics and the harness event stream do the observing, monitor does alerting and restarts, updater and doctor do the repair.

15.4.1 Prometheus metrics: single process and multi-source aggregation

The metrics endpoint lives in crates/octos-cli/src/api/metrics.rs (1,554 lines), and the core is a few lines: metrics_handler renders text from the global PrometheusHandle (:29-34), and the handle is registered once in init_metrics(:18). The instrumentation entries split by event type: record_tool_call (tool-call counts and durations, :929), record_llm_tokens (token counts, :937), record_routing_decision (routing decisions, :947).

The bulk of the file is not exposing metrics but aggregating them: the OperatorSummary family (:106-139) scrapes /metrics from multiple gateway child processes and merges them into an operator digest. One detail leaks out of OperatorSummaryCollection's field design: misconfigured gateways are listed separately as configuration_error_gateways, deliberately excluded from running_gateways, with a comment explaining that a broken config must not be read as a live process. In a multi-process deployment, "which profiles are alive, which carry an API port, how many scrapes failed" is the first screen of data an operator needs.

The design criterion behind the aggregation sits in build_operator_summary_from_sources(:139-193): the input is not a database but already-scraped metrics_text, which the function first runs through parse_metric_samples, then buckets by source.scope == "gateway": only running gateways count toward api_port stats and scrape_failures, non-running ones go down a separate configuration_error branch (:161-178). The aggregation layer trusts no single signal: process alive (the process manager's running bit), API port present, scrape succeeded, samples non-empty, four conditions recorded independently. A gateway can be running but scrape failed (process up, metrics endpoint dead), or have an api_port but empty samples (endpoint up, instruments never registered). In troubleshooting, these four columns locate which layer the problem is in, instead of returning a single "unhealthy". This criterion also explains why the aggregation logic lives in crates/octos-cli/src/api/metrics.rs rather than on the Prometheus side: cross-process running state is known only to the process manager; Prometheus cannot scrape a process that should be alive but never came up.

15.4.2 The harness event stream: typed SSE

crates/octos-cli/src/api/events_harness.rs (183 lines) provides GET /api/events/harness: it subscribes to a shared EventBroadcaster and forwards frames as SSE; an optional kinds query parameter filters by the frame's kind field, case- and underscore-insensitive for compatibility with existing callers. The file-header comment preserves a piece of history: this endpoint was once described as a dashboard invariant yet was never registered in the router, so requests fell through to the static-file fallback returning a 307 redirect, trapping Playwright's apiRequestContext in a redirect loop until a regression test caught it and registration was added. Authentication inherits user_auth_middleware (admin Bearer or authenticated session); the handler only reads.

15.4.3 UI Protocol: capability negotiation as a gate

Front-end control goes through the UI Protocol (crates/octos-core/src/ui_protocol.rs, 7,221 lines). The negotiation mechanism is for_negotiated_features at :1658-1700: the requested feature list is intersected with the server's known registry, unknown features dropped; method-level gating matches the feature set, so task/list, task/cancel, task/restart_from_node appear in supported_methods only after harness.task_control.v1 is negotiated (constant at :113). The comment gives the reason: if you advertise a method without advertising the feature, clients will call it and be rejected with method_not_supported; better for the two sides to agree.

first_server_slice(:1630) is the compatibility baseline with no feature header: V2 capabilities are known to the server but left out of the first response, otherwise the byte-level session/open response seen by old clients would change. The compatibility-versus-evolution tradeoff here: new capabilities appear only when explicitly requested.

15.4.4 monitor: alerting and watchdog

The Monitor at crates/octos-cli/src/monitor.rs (518 lines), :120, holds the profile store, process manager, alert channel, and toggles; run()(:164) starts the loop, add_sender(:159) registers senders, with built-in TelegramAlertSender(:357) and FeishuAlertSender(:390). It merges "someone must know when a process dies" and "try to bring it back up" into one component: health checks poll at health_interval, restart attempts are bounded by max_restart_attempts, alerts fan out to IM through the senders.

15.4.5 updater and doctor: two repair paths

Application-level self-update lives in crates/octos-services/src/updater.rs (473 lines), with the flow in update(:140): download, then verify, then backup, then replace, with rollback on failure. check_latest(:76) queries GitHub Releases; Updater::new supports GITHUB_TOKEN environment-variable authentication (:40-49).

The diagnostics path is independent of updating: octos doctor runs octos-diagnostics' check set (terminal environment, config/data, PATH/shadow, network) and produces a report in [✓]/[!]/[✗] form, with JSON support-bundle output; update --check goes through Stage 2's GitHub client and pure-function planner (the plan in crates/octos-diagnostics/src/update.rs) to compare semver, reporting only, never executing. Together the two paths cover "confirm the environment before upgrading" and "the upgrade itself".

flowchart TD
    Metrics["/metrics<br/>crates/octos-cli/src/api/metrics.rs 1554 行"]
    SSE["/api/events/harness<br/>crates/octos-cli/src/api/events_harness.rs 183 行"]
    UIP["UI Protocol<br/>crates/octos-core/src/ui_protocol.rs 7221 行"]
    Monitor["crates/octos-cli/src/monitor.rs<br/>Monitor + AlertSender"]
    Ledger["usage_ledger<br/>octos-store 901 行"]
    AdminAudit["admin_audit + approvals_audit"]
    Updater["crates/octos-services/src/updater.rs<br/>download-verify-backup-replace"]
    Doctor["octos-diagnostics<br/>doctor + update --check"]

    Metrics -->|"Prometheus 抓取"| Grafana["运维仪表盘"]
    SSE -->|"kind 过滤"| Dash["dashboard LiveView"]
    UIP -->|"feature 协商"| AppUI["AppUI 前端"]
    Monitor -->|"Telegram / Feishu"| OnCall["值班 IM"]
    Monitor -->|"watchdog 重启"| GW["gateway 子进程"]
    Ledger --> AdminUI["用量/成本报表"]
    AdminAudit --> Audit["合规取证"]
    Doctor --> Report["诊断报告"]
    Updater --> Bin["octos 二进制"]

Figure 15-3: the operations plane at a glance. The observation channels (Prometheus, SSE, UI Protocol) are read-only; the action channels (monitor restarts, updater replacement, doctor reports) each own one segment; storage and audit land in octos-store.

15.4.6 Control-plane state files

Finally, list the persistent state a serve process holds as a deployment checklist, all under data_dir: admin_token.json (admin credential, salt+hash, 0600), setup_state.json (wizard progress), smtp_secret.json (SMTP password, replacing the environment variable), tenants/*.json (tenant configs), users/*.json (users), usage_ledger.redb (usage), approvals-*.log and admin audit (audit). Deploying a serve instance means deploying the lifecycle of this set of files: backup policy, permissions, and rotation (approval logs default to 10 MiB rotation with 90-day retention, crates/octos-store/src/approvals_audit.rs:23-27) must each be provisioned.

Engineering decision: why does smtp_secret get its own file?

The most common way to store an SMTP password is an environment variable inside a launchd plist or systemd unit. The problem with that is not encryption strength but exposure: unit files are usually world-readable, land in configuration repositories, and get scooped up incidentally by ps e and crash dumps. The front-page docs of crates/octos-store/src/smtp_secret_store.rs name this motivation directly (replacing the SMTP_PASSWORD environment variable). The single-file approach narrows the secret to one 0600 file under data_dir, leaving only host/port/username in the configuration repository. The same reasoning applies to other secrets: environment variables suit passing launch parameters, not storing secrets long-term.


15.5 Boundaries with neighboring chapters

The storage and services this chapter covers are horizontal infrastructure, and a few boundaries are easy to confuse with the specialist chapters: the full security picture (fail-closed sandbox, injection defense, WorkerGrant) is Chapter 7, and this chapter only cites its conclusions (constant-time admin token comparison); the Harness event ABI, validators, and schema versioning are Chapter 10, and this chapter's harness SSE is their transport-layer consumer; runtime modes and the configuration system are Chapter 14, and this chapter's serve control plane is built on top of them; the 26-crate map in Chapter 1 gives the three crates' position in the global dependency graph, all hanging under octos-core and beside octos-cli. Also, the agent lifecycle, goal/loop primitives, and supervisor persistence mentioned in the spec belong to the orchestration substrate, the subject of Chapter 18; this chapter only brushes past it in the tenancy hit counts of crates/octos-cli/src/autonomy/agent_orchestrator.rs and does not expand.

15.6 Chapter recap

  1. Three extractions: octos-store (9 files, 2,664 lines, persistence), octos-services (8 files, 3,223 lines, support services), octos-diagnostics (8 files, 2,243 lines, diagnostics and update planning); the criterion is dependency direction and reuse needs, not domain nouns.
  2. Multi-tenancy in four layers: Profile directory isolation, explicit sub-account inheritance (llm inherited wholesale, the rest only when unset, env_vars merged), User file isolation, Session actor isolation; process-level isolation goes through process-manager, and resource quotas need system-level help.
  3. frpc tunnels: TenantStore manages the port pool (6001-6999) and subdomains; render_frpc_config renders per-tenant configs from a compile-time-embedded template.
  4. The operations plane: Prometheus multi-source aggregation, typed SSE event streams, UI Protocol negotiation gating, monitor alerting and watchdog, updater's five-step self-update, doctor's two-stage diagnostics.
  5. Control-plane state files are the heart of the deployment checklist: backup, permissions, and rotation each provisioned in turn.

Further reading

  • The frp project: https://github.com/fatedier/frp, the underlying forwarding tool the tunnel scheme in crates/octos-services/src/tenant.rs depends on
  • redb: https://github.com/cberner/redb, the embedded KV store octos-store uses for the usage ledger and admin audit
  • Prometheus text format: https://prometheus.io/docs/instrumenting/exposition_formats/, the wire protocol that crates/octos-cli/src/api/metrics.rs renders and OperatorSummary parses
  • RFC 7636 (PKCE): https://datatracker.ietf.org/doc/html/rfc7636 — the challenge mechanism of the three authentication flows

Exercises

  1. usage_ledger uses redb; user_store uses single-file JSON. If admin_audit's write volume grew a hundredfold, would you keep redb or bring in a standalone database? What is the deciding criterion?
  2. resolve_effective_profile's inheritance has three tiers (inherit-when-None, unconditional inheritance, merge). To add a field where "parent disabled means child must be disabled," which tier does it belong in? How should the field's semantics be written so as not to conflict with the existing three?
  3. The port pool caps at 999 tenants. If you moved to sharded VPSes, which TenantStore method signatures would have to change? What race does next_ssh_port's sequential allocation have under concurrent creation?
  4. The UI Protocol refuses to advertise methods whose features were not negotiated, and the comment's reason is avoiding method_not_supported. If you flipped it (advertise all methods, reject at runtime), which clients would be hurt, and how?

Version note: This chapter analyzes octos main @ 9c157101 (committed 2026-09-02, re-verified 2026-09-03). Relative to the old Chapter 14: the three stores moved from octos-cli to crates/octos-store/, the multi-tenant implementation moved to crates/octos-services/src/tenant.rs (render_frpc_config :255 is the new deployment path), and diagnostics became its own crates/octos-diagnostics/ (Stage 1 7f81fa5e, Stage 2 1801a9e9). The chapter number changed from 14 to 15; the three authentication flows are covered in 15.1, and Hooks in Chapter 10. All line numbers come from the facts table assets/ch15-facts.md or this session's read-only verification against the source.

Chapter 16: Fleet: A Recoverable Plan-Execution Kernel

Positioning: This chapter covers the fleet kernel added in v2: how crates/octos-fleet (7 files, 16,888 lines) and crates/octos-fleet-worker (6 files, 6,842 lines) use redb transactions, the attempt/lease/generation state machine, and a durable outbox to move the execution progress of a set of long-horizon tasks out of the conversation context and into recoverable storage. Prerequisites: Chapter 7 (WorkerGrant capability grants), Chapter 12 (the supervisor event ledger and leases). Who should read it: developers building multi-agent orchestration runtimes, and anyone curious how "resume after the process crashes" gets engineered.

16.1 Where Execution State Lives

Chapter 18's goal feature drives a durable objective forward inside a single agent's conversation. Conversations get compacted, compaction is lossy, so the objective's execution state, the plan, the decisions, what is done, what remains, drains away as the task grows long. The objective still hangs on the system prompt while its progress rots. That is the failure mode named in the opening of docs/FLEET-RUNTIME-ADR.md (176 lines): objective survives, progress rots.

When that ADR was written, the repository already held three orchestration stacks that knew nothing about each other: peers are persistent interactive sessions, octos-swarm batch-dispatches to external one-shot agents, and octos-pipeline is the DOT-graph workflow engine (Chapter 13). Building goal directly on top of peers would have produced a fourth incompatible ledger, budget, retry, and lifecycle model. The ADR decided to build a shared durable kernel first: the task-state ledger, budget reservation, state machine, and acceptance gates all live in the kernel, while batch, DAG, and dynamic-forming fleets exist as planners on top of it. Workers come in two kinds; one-shot task workers landed first, and dockable session workers were left for a later phase. This chapter's two crates are that kernel, specified in docs/FLEET-KERNEL-V1-SPEC.md (347 lines) and docs/FLEET-KERNEL-FOUNDATION-SPEC.md (219 lines).

"Progress rot" is not an abstract worry; it maps onto concrete objects. A goal's plan is a task list, its decisions are a set of reasoned judgments, its progress is "which task is at which step." If those three things live only in conversation history, one compaction can lose the conclusions of an intermediate task, and on retry the agent can only guess from a summary. The kernel materializes them as rows in redb: the plan is a DurablePlan in the plans table, decisions are append entries in decision_log, progress is the status fields of child and attempt rows. The conversation can compact freely; rows stay. Retry does not guess; it reads the table. That is the full meaning of "recoverable" at the data layer. The next three sections cover how these rows stay consistent under concurrency and crashes.

Scale and division of labor of the two crates:

crateFilesLinesResponsibility
octos-fleet716,888Durable transactional kernel: records, CAS transitions, budget, outbox, recovery
octos-fleet-worker66,842The execution half: closed tool registry, one-shot attempt runner, bounded pool, escalate valve

The module docs of crates/octos-fleet/src/lib.rs draw a hard boundary: this crate depends only on redb, serde, tokio, uuid, eyre, and octos-core, zero LLM dependencies, zero octos-agent dependencies, and every behavior can be unit-tested against a redb in a tempdir. The dependency complexity of the execution side is pushed wholesale into the worker crate.

The chapter runs along three pillars: the record model (16.2), transactions and the outbox (16.3), the state machine and recovery (16.4). Then we look at assembly and execution on the worker side (16.5, 16.6), and close with the Fleet surface and the boundary to neighboring chapters.

16.2 The Record Model: Everything Hits Disk First

The kernel's world is six redb tables, all defined in crates/octos-fleet/src/store.rs:46-51: fleets (fleet rows), fleet_children (child-task rows), attempts (attempt rows), plans (durable plans), decision_log (an append-only decision log), outbox (the event outbox). Keys are strings, values are JSON. Record types live in crates/octos-fleet/src/records.rs (808 lines); the key anchors:

SymbolLineContents
SCHEMA_VERSION = 3crates/octos-fleet/src/records.rs:33Version tag carried by every row
FleetBudgetcrates/octos-fleet/src/records.rs:119token_budget / tokens_reserved / tokens_committed / hard
FleetRecordcrates/octos-fleet/src/records.rs:145fleet row; carries the generation fence and keeper-wake metadata (:152)
Leasecrates/octos-fleet/src/records.rs:250owner_epoch + expires_at_ms
Attemptcrates/octos-fleet/src/records.rs:256attempt row; carries generation and lease
DurablePlancrates/octos-fleet/src/records.rs:313plan; contains PlanTask:333, AcceptanceCriterion:356, Verifier:367, EvidenceRef:378
OutboxEventcrates/octos-fleet/src/records.rs:524durable event, FleetEventKind:545

The plan task is the heart of the whole model. A PlanTask carries more than a title and dependencies: it has an acceptance list of acceptance criteria and a per-task grant (a worker-level capability grant; #[serde(default)] makes old rows default to minimal permissions). Acceptance criteria are defined by Verifier, currently four kinds: Manual, FileExists, CommandExit, ValidatorRef. "Done" is data plus a verifier, not a boolean. EvidenceRef content-addresses the evidence (sha256), so the acceptance assertion cannot drift from what was actually observed.

classDiagram
    class DurablePlan {
        +revision
        +tasks: Vec~PlanTask~
    }
    class PlanTask {
        +task_id
        +deps: Vec~String~
        +acceptance: Vec~AcceptanceCriterion~
        +grant: WorkerGrant
    }
    class FleetRecord {
        +status: FleetStatus
        +generation: u64
        +budget: FleetBudget
    }
    class FleetChildRecord {
        +status: ChildStatus
        +current_attempt_id
        +pending_escalation
    }
    class Attempt {
        +status: AttemptStatus
        +generation: u64
        +lease: Lease
        +reserved_tokens
    }
    class OutboxEvent {
        +sequence
        +kind: FleetEventKind
        +claim_token
        +acked
    }
    DurablePlan "1" --> "*" PlanTask
    FleetRecord "1" --> "*" FleetChildRecord
    FleetChildRecord "0..1" --> "*" Attempt
    FleetRecord "1" --> "*" OutboxEvent

Figure 16-1: The record model. The plan describes intent, child and attempt rows record execution, budget and generation hang on the fleet row, and the outbox handles outward notification.

The version-migration policy deserves its own paragraph. Every persisted row carries schema_version; loading discards only rows with a higher version (the high-version guard at crates/octos-fleet/src/records.rs:571), so an old binary encountering a new row drops what it does not recognize and never misparses it. The reason SCHEMA_VERSION went from 2 to 3 is in the comment at crates/octos-fleet/src/records.rs:25: PR B added a Blocked variant to ChildStatus. Adding a field is forward-compatible via #[serde(default)] and does not count as an upgrade; adding an enum variant is a breaking change, an old binary decoding "Blocked" gets an unknown-variant error instead of skipping gracefully, so the version must be raised and old binaries discard such rows as higher-version.

That criterion generalizes to every persistent schema, so it is worth unpacking. Adding a field widens the row: old code does not see the new key, serde fills in a default, the data survives, only the new feature is invisible. Adding an enum variant widens the value domain: old code's match has no such branch, deserialization fails outright, and it fails during whole-row decode, so one bad row drags down an entire scan. octos narrows the failure granularity to the row: the version guard probes only schema_version before full decode (the VersionProbe structure in crates/octos-fleet/src/records.rs), higher-version rows are dropped as Ok(None), and the scan continues. The cost is lost data, but what is lost is "rows only a new binary can understand", an old binary could never handle them correctly anyway. Dropping is equivalent to blindness, and better than blindness pretending to see.

16.3 Transactions and the Outbox: One Write Transaction per Transition

FleetKernelStore (crates/octos-fleet/src/store.rs:195) is the transaction-primitive layer. The module docs (crates/octos-fleet/src/store.rs:6-8) fix the shape of every method: within one begin_write, read the current row, check the CAS predicate, write the next state; budget settlement and the outbox append happen in the same transaction, so no cross-store window exists. The CAS partition starts at the comment block at crates/octos-fleet/src/store.rs:880, with three core transitions.

launch_child (crates/octos-fleet/src/store.rs:889) starts a Ready child. The predicate has four gates: the child must be Ready with no in-flight attempt, the fleet must be non-terminal (the terminal fence added in the #1973 fix round), and the budget must admit. When all pass, one transaction writes the child's Launching, a new Leased attempt (AttemptStatus::Leased at crates/octos-fleet/src/store.rs:997, Lease{owner_epoch} at :998), the budget reservation, and one ChildLaunching outbox event. Any rejection leaves no half-state: a budget-rejected child is still Ready, never stranded in Launching.

mark_running (crates/octos-fleet/src/store.rs:1053) pushes Leased to Running; its four-part predicate includes attempt.generation == fleet.generation (crates/octos-fleet/src/store.rs:1122). complete_child (crates/octos-fleet/src/store.rs:1157) requires the child to be Running, the generation to match (:1236), and lease.owner_epoch to match (:1237); only on success does it write the result and settle the budget. The generation is a member epoch on the fleet row, incremented on replan; late events from an old generation are caught by the fence.

A CAS rejection is modeled as a value, not an error. The Superseded variants of LaunchOutcome / CompleteOutcome / MarkRunningOutcome (crates/octos-fleet/src/store.rs:59, 75, 102) are ordinary control flow the caller reasons over; Err is reserved for genuine infrastructure failures. Section 16.6 shows where this distinction pays off on the worker side.

The budget settles inside the transaction. FleetBudget::admits (crates/octos-fleet/src/records.rs:132) sums with checked arithmetic before comparing:

#![allow(unused)]
fn main() {
pub fn admits(&self, projected: u64) -> bool {
    match self
        .tokens_reserved
        .checked_add(self.tokens_committed)
        .and_then(|s| s.checked_add(projected))
    {
        Some(total) => total <= self.token_budget,
        None => false,
    }
}
}

A sum that overflows cannot be a legal budget, so it is rejected outright; saturating arithmetic would silently let MAX + MAX + 1 <= MAX pass as admitted (the P2-5 fix). v1's hard = false is soft admission: it rejects the next launch; it does not interrupt an in-flight run.

The outbox answers "the state changed; who gets told". append_event (crates/octos-fleet/src/store.rs:2518) appends inside each transition's own write transaction (the comment at crates/octos-fleet/src/store.rs:2806), with four event kinds: ChildLaunching, ChildRunning, ChildDone, FleetDrained. The consumption protocol is a real claim/ack: claim_next (crates/octos-fleet/src/store.rs:2547) claims the lowest-sequence unacknowledged event, stamps claimed_by, mints a fresh claim_token, and sets claim_expires_at; ack (crates/octos-fleet/src/store.rs:2603) must present the matching (claimed_by, claim_token) pair, and a mismatch returns StaleClaim. This token fence (P1-3) blocks a concrete race: if a consumer's lease has expired and the event has been re-claimed by someone else, the old consumer's late ack cannot pollute the new consumer's progress. The wake rides the MasterContinuationScheduler of Chapter 12; scheduling details are in Chapter 12, keeper semantics in Chapter 18.

The consumer side deserves its own walkthrough, because it closes the outbox's durable semantics into a full loop. drain_fleet_outbox_once (:235) in crates/octos-cli/src/autonomy/fleet_wake.rs (1,807 lines) is the testable core: it takes a store, a clock, a batch cap, and a commit_wake callback, and loops claim_next until the queue is empty or the cap is reached. The ack threshold is the two-value enum WakeCommit (:70): a wake persisted to disk is Durable and can be acked; a wake that lives only in memory, or whose persistence failed, is NotDurable, gets no ack, leaves the event in claimed state, and is redelivered automatically when the lease (30 seconds, :56) expires. A wake is never silently lost; the cost is at most one redelivery. The consumer loop spawn_fleet_outbox_consumer (:343) ticks every 3 seconds with a per-tick cap of 64 events (:63), so a backlogged outbox can neither monopolize the consumer nor pile up an unbounded continuation queue; the remainder waits for the next tick. Three special branches each carry a number: the #1973 fix round dictates that a cancelled fleet's ChildDone is acked without waking (the goal is already cleared; a wake would resurrect a dead controller with stale metadata, while late events for Complete / Failed still wake, letting the keeper self-check completion); a vanished fleet row is also acked directly, so the outbox never sticks on a missing record; non-terminal lifecycle events carry no wake semantics and are acked on claim. The wake content is not a raw event forward: render_fleet_snapshot (:99) first reads the plan and the ready set asynchronously and renders a FleetKeeperSnapshot (:84; objective, one line per task, the ready id list), so the synchronous prompt renderer only formats and never touches I/O. The fleet-side conclusion is that the outbox guarantees event delivery, the consumer loop guarantees durable wakes, and the two layers each own one crash window.

The full timeline of one attempt, from launch to settlement:

sequenceDiagram
    participant P as FleetWorkerPool
    participant S as FleetKernelStore
    participant W as run_attempt
    participant O as outbox consumer
    P->>S: launch_child(projected_tokens, owner_epoch)
    S-->>P: Launched(attempt_id)
    Note over S: same transaction: child→Launching<br/>new Leased attempt+budget reservation+event
    P->>W: spawn(escalation_slot, tracker)
    W->>S: mark_running
    S-->>W: Running(generation predicate passed)
    W->>W: agent execution + acceptance gates
    W->>S: complete_child(verdict, snapshot, actual_tokens)
    alt predicate passed
        S-->>W: Completed
        Note over S: result recorded+budget settled+ChildDone event
        O->>S: claim_next / ack(claim_token)
    else predicate failed
        S-->>W: Superseded(result discarded, no state change)
    end

Figure 16-2: The timeline of one attempt. Each box note is a single write transaction; a failed CAS returns as a value, not through the error channel.

The read-side hazard under cancellation is handled by the io_gate: every operation (including decision reads and scans) first acquires the gate's owned guard, then moves the guard into the spawn_blocking closure. A cancelled caller's uninterruptible blocking write can therefore never be reordered to land after subsequent reads (the spec v1.1 fix).

Engineering decision: why redb transactions instead of in-memory state plus a log

The alternative is to keep the state machine in process memory, write changes to a log, and replay on restart. It has three gaps. First, the read-decide-write steps are naturally separated in memory; a crash can land between decision and write, and the replayed state then contradicts the assumptions the decision was made under, forcing either compensation logic for every transition or acceptance of dirty state. Second, budget settlement is a read-modify-write; an in-memory scheme needs its own locking protocol, and that protocol itself has to survive crash testing. Third, multi-table consistency (fleet row, child row, attempt row, outbox) has no native answer without two-phase commit or an acceptance window. redb's single write transaction closes all three gaps at once: every write inside one begin_write becomes visible together or not at all, and crash recovery is delegated to the storage engine. The cost is that all access serializes, which is no bottleneck for the fleet kernel: its write rate is set by task lifecycles, not by any hot path. docs/FLEET-KERNEL-V1-SPEC.md names this shape one-write-transaction CAS and records that it was lifted verbatim from octos-swarm's redb persistence layer.

16.4 The State Machine and Recovery Coordination

Three state layers each own one segment: the fleet as a whole is FleetStatus (Active / Draining / Complete / Failed / Cancelled, crates/octos-fleet/src/records.rs:41-47); a child task is ChildStatus (Planned / Ready / Launching / Running / Blocked / Succeeded / Failed / Cancelled, crates/octos-fleet/src/records.rs:64); an attempt is AttemptStatus (Leased / Running / Done / Interrupted, crates/octos-fleet/src/records.rs:94). Blocked is the non-terminal state PR B added: the attempt yields to request a wider grant and waits for the keeper's decision (16.5).

stateDiagram-v2
    [*] --> Planned: add_child(crates/octos-fleet/src/store.rs:503)
    Planned --> Ready: dependencies satisfied (resolve_and_collect_ready:676)
    Ready --> Launching: launch_child CAS (889)
    Launching --> Running: mark_running CAS (1053)
    Running --> Succeeded: complete_child predicate passed (1157)
    Running --> Failed: acceptance failed / goal_deny
    Launching --> Blocked: record_escalation(1336)
    Running --> Blocked: record_escalation(1336)
    Blocked --> Ready: goal_grant (rerun with wider grant)
    Blocked --> Failed: deny_escalation(2025)
    Launching --> Ready: reconcile reclaim (2191)
    Running --> Ready: reconcile reclaim (2191)
    Ready --> Cancelled: cancel_fleet(838)
    Succeeded --> [*]
    Failed --> [*]
    Cancelled --> [*]

Figure 16-3: The child state machine. Every edge lands on one CAS method in crates/octos-fleet/src/store.rs; the reconcile reclaim edges fire only on lease expiry or a foreign epoch.

Recovery coordination is reconcile (crates/octos-fleet/src/store.rs:2191; the report type ReconcileReport is at :160). At startup it scans every Launching / Running child with the current owner_epoch and the clock: a live fleet's attempt is reclaimed only when its lease is invalid (a foreign owner_epoch, or expires_at_ms already past); a terminal fleet's in-flight attempt is settled unconditionally (the #1973 fix round: before it, Cancelled fleets were skipped wholesale, pinning their attempts and budget reservations forever). The reclaim action is one transaction doing three things: the attempt is recorded Interrupted, the attempt's reservation is released from the fleet budget (checked_sub; an underflow means the accounting invariant is broken and errors immediately), and the child's current_attempt_id is cleared. A live fleet's child returns to Ready and waits for this startup to launch it again; a terminal fleet's child is recorded Cancelled and never revives (P2-7). An old attempt never comes back to life; a rerun always opens a new attempt.

Plan revision goes through a revision CAS: replan (crates/octos-fleet/src/store.rs:1512) carries expected_revision, increments the revision, and syncs each task's declared dependencies into the denormalized copy on the child rows; retitle_task (:1804) and set_task_grant (:1898) follow the same shape. The decision log (append_decision:2648, list_decisions:2697) appends by sequence number. DecisionKind is a closed set issued by the kernel, in contrast with the open kind string of Finding (crates/octos-fleet/src/records.rs:447; one falsifiable claim, with the component field as clustering key): kernel decisions are closed, exploration findings are open.

After recovery comes a second question: how does a restarted keeper learn "what happened before"? Reading every worker's transcript is neither feasible nor meaningful, and crates/octos-fleet/src/digest.rs (861 lines) exists as the bounded read side for exactly this. Its front-page doc states the failure mode plainly: the bottleneck of a goal is not a shortage of executors, it is the controller's context window placing a ceiling on problem complexity, and if synthesizing progress means reading every worker's output, the architect degenerates into a clerk relaying messages between workers. So the controller never reads a finding directly; it reads only the output of digest(findings, opts) (crates/octos-fleet/src/digest.rs:175), a view whose size does not grow with the project. The design is a pure function: no store, no LLM, no clock; the watermark (since_seq, the highest sequence the controller has already synthesized), the current configuration, and the character budget are all inputs, and the whole logic can be tested with table-driven tests. The budget is the design: max_chars defaults to 4,000 (crates/octos-fleet/src/digest.rs:56); when over the limit, sections are dropped and the drop is reported honestly (the Dropped structure at crates/octos-fleet/src/digest.rs:126 records which section lost how many entries), because silent truncation reads as "nothing more to see", which is worse than an explicitly cut list. Each section sorts newest first and the budget cuts from the tail; the oldest is what gets sacrificed. The output has five partitions: new findings, overturns, stale entries (a finding whose config has drifted from the current build; the drift function at crates/octos-fleet/src/digest.rs:156 does the comparison), cluster hints (how many paths reference each component; cluster_min_paths defaults to 2), and per-path cost, plus the watermark handed back to the controller as the next round's since_seq. digest's place in recovery follows: reconcile repairs the ledger back to self-consistency, and digest guarantees that afterwards the controller re-enters at constant cost.

16.5 Worker Assembly: The Closed Registry and an Always-On Safety Valve

The worker side's first module answers "which tools can a worker actually use". build_fleet_worker_registry (:92) in crates/octos-fleet-worker/src/closed_registry.rs (705 lines) starts from an empty registry and assembles the closed tool set per WorkerGrant.sorted_tools(); ALLOWED (:43) references octos_fleet::BASE_TOOLS directly (crates/octos-fleet/src/grant.rs:27). Tools outside the grant do not exist in the registry, so a replay assembles the same result. The four grant types live in crates/octos-fleet/src/grant.rs: NetworkGrant (:76, None / Hosts / Full), FsGrant (:127, Workspace / Host), WorkerGrant (:151, network / tools / fs / write_paths / create_only), GrantError (:359); validate() is at :247. These types match Chapter 7 line for line; semantics and validation rules are covered in Chapter 7, and this chapter only consumes their conclusions.

The module docs of crates/octos-fleet-worker/src/lib.rs add a boundary that is easy to misread: the closed registry is a rejection list over tool names, what it removes is docking, fan-out, and web tools; it is not itself a network or process boundary. The surviving shell under a Full grant can still reach the network and can still use shell-internal backgrounding to detach a subprocess, which no string check catches. The real boundary is the sandbox and its process-group reaping, which is why AgentFactory::new requires the sandbox factory to be passed explicitly and provides no silent empty implementation; passing an empty one is flagged by tracing::warn!, and production must supply a network-isolating sandbox. The requirement lives in API documentation; the type system cannot enforce it, and it is the operator's responsibility.

The second module is the escalate valve (crates/octos-fleet-worker/src/escalate.rs, 293 lines). When a closed worker lacks a capability (a host, a tool, filesystem access) it can neither widen its own grant nor dock and wait: it calls the escalate tool, writes an EscalationRequest (the requested grant plus a reason) into a shared slot (EscalationSlot:34, EscalateTool:37), and returns immediately. After the turn ends, run_attempt reads the slot; if it holds a value, it calls record_escalation (crates/octos-fleet/src/store.rs:1336, which likewise checks generation :1409 and lease :1410), the child enters Blocked, and the keeper decides: goal_grant moves the child back to Ready to rerun with the wider grant, while goal_deny pushes Blocked to Failed via deny_escalation (crates/octos-fleet/src/store.rs:2025). The return type of deny_escalation computes fleet_un_completable in the same write transaction as a side effect (the design comment near :2094): whether the fleet can no longer complete automatically is derived directly from the post-deny durable state, so the keeper can skip a read it would otherwise have to make. The tool is always registered and never gated by the grant: a worker on minimal permissions must still be able to say "I am stuck". The request is advisory, and the keeper may grant less than asked.

16.6 run_attempt and the Bounded Pool

run_attempt (:177) in crates/octos-fleet-worker/src/worker.rs (2,575 lines) executes one attempt, with five terminal states (AttemptOutcome:146):

#![allow(unused)]
fn main() {
pub enum AttemptOutcome {
    Completed { verdict: AcceptanceVerdict },
    Superseded,
    Aborted { reason: String },
    RecordError { reason: String },
    Escalated { request: EscalationRequest },
}
}

The first step is mark_running, and its two failure modes are handled separately: Superseded means the attempt is genuinely not this one's, so it returns Aborted and the pool releases its guard; Err is an infrastructure failure, the Launching attempt may still be this one's, so it returns RecordError, the guard stays armed, and cleanup falls to Drop and recovery coordination. This two-path distinction (the round-4 P1 fix) builds directly on the value-versus-error separation of 16.3. The execution body is wrapped in a hard tokio::time::timeout, AgentFactory clamps every per-tool timeout to the deadline, the worker shell has a hard per-command cap, and the acceptance phase is also bound by the remaining time. In worktree mode (WorktreeContext:67), a deliverable is defined as a commit on a branch; an empty branch counts as no deliverable.

FleetWorkerPool (:109) in crates/octos-fleet-worker/src/pool.rs (2,186 lines) is the bounded launcher, configured in PoolConfig (:58): global concurrency, per-fleet concurrency, deadline, owner_epoch, lease TTL, reserved tokens, workspace root, keeper profile, and whether the backend supports repo writes. dispatch (:233) holds a preflight lock on each (fleet, task) pair across the whole span of "liveness check, worktree preparation, launch, spawn"; when two concurrent dispatches target the same Ready task, the loser sees the winner's in-flight attempt and is caught by launch's double-launch rejection. The worktree is a conditional path: only when the grant satisfies both Host filesystem and Full network, the fleet sits on a git repository, and the backend supports .git writes, all three true, does it open a real worktree on the task's stable branch, with resumption starting from the dead worker's last commit; any false falls back to a scratch directory. The reasoning for the full-trust threshold is in dispatch's comments: Host filesystem plus restricted network is not real isolation (a full filesystem can bridge any network fence), so full network is required outright, leaving both escape routes meaningless. Commit anchors: eadee2ae (#1875) introduced WorkerGrant; 8fc66202 (#1881) landed the worktree worker.

The pool's bound is kept by two semaphores: global_sem caps the process-wide total, while the per_fleet HashMap creates per-fleet semaphores on demand and never prunes entries (the ceiling is the number of tasks, not the number of runs). This design puts the truth of concurrency control in the pool rather than the kernel: the store's CAS guarantees no duplicates and no losses, but how many run at once, and how many per fleet, is the host's policy choice, which the kernel does not presuppose. A dispatch that cannot get a permit queues on the semaphore and produces no durable state; only real execution goes through launch's transaction. Conversely, after a restart the pool is empty and every permit is naturally available, and there is no secondary problem of "the permit table also needs recovery": permits are in-memory semaphores, recovery is done by reconcile against durable state, and the two responsibilities do not overlap.

16.7 The Fleet Surface and Boundaries

Fleet (:190) in crates/octos-fleet/src/fleet.rs (3,062 lines) composes the store's CAS operations into whole-plan APIs: create (:210), bind (:300), view (:324), ready_tasks (:375), apply_edit (:402), record_outcome (:542), is_complete (:583), summary (:595). It does not change store semantics; it is the surface that the future keeper and the goal_get / goal_update tools will program against.

The largest file in the crate is not store but crates/octos-fleet/src/sqlite_ledger.rs (6,360 lines, a bit more than a quarter of the two crates' combined 23,730), where GoalLedger (:13) lands. Why do redb and sqlite coexist in one codebase? The first three comment lines of the file give the reason: redb is a single-writer, single-process model, while SQLite via WAL supports multi-process access, which fits the peer architecture where the master and each peer, as independent processes, share one ledger. The split between the two persistence layers follows the readers: the fleet kernel's six tables (fleet, child, attempt, plan, decision, outbox) are written exclusively by the single serve process, and the single-write-transaction CAS shape fits redb's model exactly; the goal ledger (the goals, tasks, findings, and escalations tables, with the findings table indexed on both goal and task at crates/octos-fleet/src/sqlite_ledger.rs:409-410) is read and written by the keeper, workers, and transition sync alike, so SQL's row-level content addressing (append_finding:1623, list_findings_since:2132) and index queries are the more natural shape. The GoalLedger at crates/octos-fleet/src/sqlite_ledger.rs:13 belongs to Chapter 18; we keep one engineering detail here: concurrently opening the same fresh WAL database has a millisecond-scale initialization race (database is locked, not covered by the busy handler), so open (:222) uses rusqlite's default 5-second busy_timeout, while open_with_busy_retry (:245), used only for goal state migration, does 3 bounded retries and squeezes the timeout to 1 second, running only on the blocking thread. The ledger and the store do not replace each other: one owns the multi-process shared goal ledger, the other the single-process exclusive execution state machine.

Swarm's fan-out topology is covered in Chapter 17; the supervisor's event ledger and wake scheduling in Chapter 12; the full WorkerGrant permission model in Chapter 7.

16.8 Chapter Recap

  1. One kernel carries three topologies: the record model (six tables, SCHEMA_VERSION = 3 with drop-higher-version policy), transactional CAS (the predicates and value-style rejections of launch_child / mark_running / complete_child), and recovery coordination (reconcile's lease reclaim and never-revive rule), three pillars that move execution progress out of the conversation context and into redb.
  2. A CAS rejection is a value, not an error: Superseded is control flow, Err is reserved for infrastructure failures, and the worker side distinguishes Aborted from RecordError accordingly.
  3. Budget and outbox both live in the transition's write transaction: reservation, settlement, and event append have no cross-store window; claim/ack uses the claim_token fence to block late acknowledgments from expired consumers.
  4. Workers assemble from an empty registry per grant, replay-consistently; the sandbox is the boundary and the registry is only a tool-name rejection list; escalate is always on, and Blocked waits for the keeper's decision.
  5. The pool is bounded with serialized preflight: concurrent dispatches of one task are caught twice, by the lock and by double-launch; the worktree needs all three full-trust conditions, otherwise scratch is the fallback.

Further reading

  • redb: https://github.com/cberner/redb, the fleet kernel's embedded KV store; single write transactions are the foundation of this chapter's CAS shape
  • docs/FLEET-RUNTIME-ADR.md (176 lines), the architecture decision record for one kernel, two worker kinds, three topologies
  • docs/FLEET-KERNEL-V1-SPEC.md (347 lines), the implementation spec for one-write-transaction CAS and io_gate cancellation safety
  • docs/FLEET-KERNEL-FOUNDATION-SPEC.md (219 lines), the kernel's foundation design, the layer below the ADR

Exercises

  1. SCHEMA_VERSION treats adding fields and adding enum variants differently. To add a Paused variant to AttemptStatus while also adding a paused_by field to Attempt, which changes need a version bump and which are covered by #[serde(default)]? Derive the behavior of an old binary on a new database.
  2. The claim_token fence blocks late acks from expired consumers. If a consumer crashes before acking, how is the event redelivered? How do claimed_by and the token change after redelivery, and what does the old consumer's late ack get in return?
  3. reconcile settles in-flight attempts of terminal fleets unconditionally and records children Cancelled, never to revive. If it instead returned terminal fleets' children to Ready, which paths would violate which invariants?
  4. The worktree path requires Host filesystem and Full network together. To support a network-isolated worktree worker, what attack does the .git docking fence mentioned in the comments have to prevent? Why can a full filesystem bypass a network fence?
  5. The budget's hard = false only rejects the next launch. If it became a hard budget that interrupts in-flight runs, what would complete_child's predicate and run_attempt's terminal enum each need to add?

Version note: This chapter is new in v2; the analysis is based on octos main @ 9c157101 (collected and rechecked 2026-09-03). Both crates are new code: octos-fleet and octos-fleet-worker do not exist in the v1 draft; WorkerGrant entered the kernel with eadee2ae (#1875), and the worktree worker landed with 8fc66202 (#1881). All line numbers and counts come from the facts table assets/ch16-facts.md or from this session's read-only checks against the source; the fleet state machine was forward-referenced by Chapter 12 as "see Chapter 16" in earlier chapters, and this chapter is that destination.

Chapter 17: Swarm: Contract Fan-out and Aggregation Gates

Positioning: This chapter reads crates/octos-swarm and shows how it collapses "a supervisor writes N contracts, distributes them to external agent backends, aggregates the artifacts, and runs them through validation gates" into one re-entrant orchestration primitive: three execution topologies, three gates, one idempotent ledger. Prerequisites: Chapter 10 (validators and the event ABI), Chapter 16 (Fleet). Who should read it: developers who need to delegate a batch of subtasks to external agents such as claude or codex and want results they can trust, costs they can account for, and replays that agree.

The octos harness has always run one pattern by hand: a PM-style supervisor splits work into N pieces, hands them to sub-agents, then compares, merges, and decides re-runs manually. The first line of the octos-swarm crate doc says it plainly: Swarm orchestration primitive for octos (harness M7.5) (crates/octos-swarm/src/lib.rs:1); the next line explains that it formalizes this "PM + swarm supervisor" pattern. The manual pattern hurts in three places: dispatch is unaccountable (no record of who received which task), artifacts are untrusted (a sub-agent says done, and that counts as done), and re-runs diverge (the second execution of the same batch has different boundaries than the first). These three map onto the chapter's three threads: contract fan-out, aggregation gates, idempotency and recovery.

The crate is small: 7 source files at 2,505 lines, 3 integration test files at 2,475 lines, 4,980 lines in total (facts table assets/ch17-facts.md, counted against main @ 9c157101 on 2026-09-03). Test lines run nearly level with source (1:0.99), and 36 integration cases cover topology, gates, idempotency, and recovery. That ratio previews the design signal that recurs throughout the chapter: every invariant has a name and a test.

FileLinesResponsibility
crates/octos-swarm/src/dispatcher.rs1,261Orchestration core: dispatch loop, gates, aggregation, idempotency
crates/octos-swarm/src/result.rs395Typed results: SwarmResult / SubtaskOutcome / AggregateArtifact
crates/octos-swarm/src/persistence.rs275redb persistence: the DispatchStore idempotent ledger
crates/octos-swarm/src/topology.rs229Topology and contracts: SwarmTopology / ContractSpec / FanoutPattern
crates/octos-swarm/src/ledger.rs115Cost ledger adapter (M7.5): CostLedger trait + Noop implementation
crates/octos-swarm/src/lib.rs111Crate facade and re-exports
crates/octos-swarm/src/gate.rs119Gate glue layer: enforce_or_outcome

17.1 Contracts: the smallest unit of fan-out

Everything Swarm knows about "one subtask" fits in one struct. A contract (ContractSpec, crates/octos-swarm/src/topology.rs:37) has four fields:

#![allow(unused)]
fn main() {
pub struct ContractSpec {
    pub contract_id: String,
    pub tool_name: String,
    pub task: serde_json::Value,
    pub label: Option<String>,
}
}

contract_id is the stable key for retry deduplication and persistence; the caller must keep it unique within one dispatch. task is opaque to the primitive and is forwarded verbatim as the arguments of an MCP tools/call. label exists only for human-facing operations interfaces and plays no part in correlation. The design compresses "what the primitive needs to know" to the minimum: identity, target tool, payload. What a contract contains and how it is accepted is an agreement between supervisor and sub-agent, and the primitive does not interpret it.

One dispatch has a hard ceiling on total contracts: MAX_CONTRACTS_PER_DISPATCH: usize = 128 (crates/octos-swarm/src/topology.rs:27), enforced at the dispatch entry point (crates/octos-swarm/src/dispatcher.rs:246). The ceiling guards against unbounded expansion in the fan-out pattern: FanoutPattern (crates/octos-swarm/src/topology.rs:59) clones one seed contract into N siblings, and expand (crates/octos-swarm/src/topology.rs:72) appends a ::variant suffix to each contract_id and injects a variant field into task. The primitive never reads the payload; it stamps it, and the remote agent switches behavior on variant. The expanded contract table is produced uniformly by resolve_contracts (crates/octos-swarm/src/topology.rs:133): the Fanout topology replaces the seed table with the expansion, and the other topologies keep it unchanged.

17.2 Three orchestration primitives: Parallel, Sequential, Pipeline

SwarmTopology (crates/octos-swarm/src/topology.rs:98) has four variants but only three execution shapes (Parallel and Fanout share the fan-out execution path; they differ only in how the contract table is built). These three are the orchestration primitives: fan-out, sequence, pipeline.

  • Parallel: run_parallel_round (crates/octos-swarm/src/dispatcher.rs:428) dispatches retry-pending contracts concurrently on a JoinSet, filling max_concurrency slots first and backfilling the moment one completes. Aggregation follows arrival order. For $n$ contracts at concurrency $c$, total dispatch wall time is roughly $\lceil n/c \rceil$ backend round-trips; when the backend is slow, concurrency is the only tunable lever.
  • Sequential: run_sequential_round (crates/octos-swarm/src/dispatcher.rs:478) runs one contract at a time and stops at the first hard failure (TerminalFailed); the remaining contracts stay not_run. It fits batches that have order dependence but no artifact consumption, chains like "review the facts table, then the draft, then the citations" where an early failure voids everything after it.
  • Pipeline: run_pipeline_round (crates/octos-swarm/src/dispatcher.rs:518) folds contract i's artifact into contract i+1's pipeline_input field; a successor is never dispatched unless its predecessor is Completed. The fold has two shapes (crates/octos-swarm/src/dispatcher.rs:549-558): when the task is itself an object, the pipeline_input key is injected directly; otherwise the task is wrapped as {"original_task": ..., "pipeline_input": <predecessor output>}, with the predecessor output injected as a string that the remote agent reads by convention.
flowchart LR
    subgraph Parallel["Parallel / Fanout (run_parallel_round :428)"]
        A["Contract pool"] -->|"JoinSet fills max_concurrency"| B["Concurrency slots"]
        B -->|"refill on completion"| B
        B -->|"aggregate in arrival order"| PA["Aggregate artifact"]
    end
    subgraph Sequential["Sequential (run_sequential_round :478)"]
        S1["Contract 1"] --> S2["Contract 2"] --> S3["Contract 3"]
        S2 -.->|"TerminalFailed aborts"| SX["Contract 3 stays not_run"]
    end
    subgraph Pipeline["Pipeline (run_pipeline_round :518)"]
        P1["stage-1"] -->|"pipeline_input"| P2["stage-2"] -->|"pipeline_input"| P3["stage-3"]
    end

Figure 17-1: The three execution topologies. Sequential and Pipeline both hold concurrency at 1 (max_concurrency, crates/octos-swarm/src/topology.rs:143); they differ not in concurrency but in failure semantics: Sequential aborts the whole batch, Pipeline cuts the chain and keeps the earlier artifacts.

Why cut three shapes instead of merging them into one parameterized executor? Parallel's design pressure is throughput: the backend round-trip is the batch bottleneck, and the slot-refill model (one finishes, one backfills) keeps slow contracts from blocking fast ones, at the cost of making aggregation order equal arrival order; callers who need a stable order re-sort on contract_id themselves. Sequential's pressure is waste: when later contracts presuppose earlier results (not content consumption but "if the predecessor failed, the successor is meaningless"), concurrency only produces artifacts destined for the trash; concurrency pinned at 1 pushes waste to zero, and abort on the first hard failure moves the decision point to the moment of failure. Pipeline's pressure is data dependence: the successor's input field is the predecessor's output, and any "successor completed with empty input" is silent corruption, so its invariant is the strictest: no dispatch unless the predecessor is Completed; it would rather idle the whole round than risk polluting the chain. Each primitive carries one invariant (tunable throughput, stop on failure, order equals dependency). Merging them into one parameterized executor would turn the three invariants into mutually exclusive configuration combinations, and the misconfigured combination is precisely the silently corrupting one. That is also why SwarmTopology is an enum, not a struct: at the type level the caller can pick only one shape; there is no self-contradictory "Sequential with concurrency 3".

Fanout is a variant of its own rather than callers cloning the contract table themselves, and the reason is idempotency: the ::variant suffix rule is owned by the primitive, every expanded contract_id is stable and reproducible, the same pattern expands to the same set of ids twice, and only then can retry and recovery match rows in redb. A hand-rolled clone that changes the id format strands old state on the recovery path. The test should_expand_fanout_pattern_into_variant_contracts (crates/octos-swarm/tests/swarm_dispatch.rs:707) pins the expansion rule.

Pipeline's failure semantics deserve a paragraph of their own. In an early implementation, a retryable stage-2 failure still dispatched stage-3 in the same round with no input, and stage-3 was then recorded Completed: the chain broke silently. The fix (#1717, test should_stop_pipeline_round_at_retryable_stage_and_resume_with_input, crates/octos-swarm/tests/swarm_dispatch.rs:763; test references below omit the crates/octos-swarm/tests/ prefix) added one precondition: a stage can be dispatched only when its predecessor is Completed, and recovery rounds obey the same rule. The test asserts that both stage-2 attempts link to stage-1's output and that stage-3 runs exactly once, with the recovered stage-2 output.

Sequential's abort semantics also survive a crash. Before processing each retry-pending slot, run_sequential_round scans every subtask ahead of it: on any TerminalFailed, the whole round returns the abort marker immediately (crates/octos-swarm/src/dispatcher.rs:478). The check looks redundant, since the loop already broke when aborting, but it guards the recovery path: when a record carrying a hard-failure marker is re-dispatched by a restarted process, the tail contracts must stay not_run, not get dispatched because "this round just started". The tests should_not_resume_sequential_tail_after_persisted_terminal_failure (crates/octos-swarm/tests/swarm_dispatch.rs:1213) and the Pipeline version (:1163) pin this boundary.

The retry budget is governed by SwarmBudget (crates/octos-swarm/src/dispatcher.rs:66), with the default ceiling MAX_RETRY_ROUNDS: u32 = 3 (crates/octos-swarm/src/dispatcher.rs:60), clamped to 3: a larger value from the caller is pressed back down. Budget consumption was corrected once (#1717 review finding 5): only zero-progress rounds consume budget; a round that completed at least one new contract is free, because such rounds are naturally bounded by the total contract count and the loop still terminates. The budget check also moved from "after the round" to "before the round" (review finding 2): a record parked at the budget ceiling, when recovered, dispatches not even one round; otherwise every crash recovery gifts one extra round, and enough recoveries defeat the ceiling.

17.3 The full sequence of one dispatch

Swarm::dispatch (crates/octos-swarm/src/dispatcher.rs:246) takes five arguments: dispatch_id, the contract table, topology, budget, and context (SwarmContext carries session_id / task_id / workflow / phase for event routing). Construction goes through the SwarmBuilder returned by Swarm::builder (crates/octos-swarm/src/dispatcher.rs:206), which can optionally mount a cost ledger, aggregation validators, an event sink, and a dispatch policy; anything unmounted falls back to Noop defaults. The full sequence:

sequenceDiagram
    participant S as Supervisor
    participant D as Swarm::dispatch (:246)
    participant G as InFlightGuard (:833)
    participant P as DispatchStore (crates/octos-swarm/src/persistence.rs:93)
    participant B as McpAgentBackend
    participant V as Validator (M4.3)
    S->>D: dispatch(id, contracts, topology, budget, ctx)
    D->>G: acquire(id) (reject concurrent same id)
    D->>P: load(id)
    alt record already finalized
        D->>S: return final_result verbatim (#1718)
    else new record or unfinished
        D->>P: store(initial record, crash-recoverable)
        loop until no retry-pending or budget exhausted
            D->>D: enforce_or_outcome (crates/octos-swarm/src/gate.rs:25, gate one)
            D->>B: dispatch(DispatchRequest)
            B-->>D: DispatchResponse
            D->>D: gate_subtask_validators (:593, gate two)
            D->>P: store(entire record)
        end
        D->>V: run_aggregate_validator (:693, gate three)
        D->>D: ledger summarize + finalize + final_result snapshot
        D->>P: store(finalized record)
        D-->>S: SwarmResult + typed events
    end

Figure 17-2: the sequence of one dispatch. Every step lands in a named method of crates/octos-swarm/src/dispatcher.rs or crates/octos-swarm/src/persistence.rs and maps onto a case in crates/octos-swarm/tests/swarm_dispatch.rs: entry idempotency to should_survive_process_restart_mid_dispatch (:560), concurrency rejection to should_reject_concurrent_dispatch_with_same_id (:1100), verbatim replay to should_replay_finalized_result_verbatim_including_validator_verdicts (:821).

At the end of every round, the entire record is written back to redb rather than batched into one final write. The cost is one serialized commit per round; the payoff is that the crash point can sit anywhere and recovery resumes from the most recent round snapshot. Events fire after finalize: HarnessSwarmDispatchEvent carries SWARM_DISPATCH_SCHEMA_VERSION (fixed at 1), and the event for a failed result promotes the first unfinished subtask's error into the message field, so the supervisor gets an actionable clue without paging through the record. The event ABI and schema versioning are covered in Chapter 10.

17.4 The backend abstraction: MCP sub-agents and CLI wiring

The dispatch target is a trait: McpAgentBackend (crates/octos-agent/src/tools/mcp_agent.rs:411), whose core method is dispatch(DispatchRequest) -> DispatchResponse. The request (:266) carries the tool name and the contract task; the response (:218) carries text output plus files_to_send; the single-shot outcome enum DispatchOutcome (:182) distinguishes Success, Timeout, TransportFailure, and kin. Swarm's understanding of backend results compresses into one mapping function (SubtaskStatus::from_dispatch, crates/octos-swarm/src/result.rs:20):

#![allow(unused)]
fn main() {
pub fn from_dispatch(outcome: DispatchOutcome) -> Self {
    match outcome {
        DispatchOutcome::Success => Self::Completed,
        DispatchOutcome::RemoteError | DispatchOutcome::Timeout => Self::RetryableFailed,
        DispatchOutcome::TransportError
        | DispatchOutcome::ProtocolError
        | DispatchOutcome::SsrfBlocked => Self::TerminalFailed,
    }
}
}

The three terminal classes (crates/octos-swarm/src/result.rs:20) map to three dispositions: Completed enters aggregation; RetryableFailed stays in the next round's retry-pending set; TerminalFailed is never redispatched. Remote errors and timeouts are retryable; transport errors, protocol errors, and SSRF blocks are terminal. This line confines "worth retrying" to network jitter and leaves no retry channel for security blocks. The full portrait of a subtask is recorded in SubtaskOutcome (crates/octos-swarm/src/result.rs:58): status, attempt count (starting at 1, first try plus retries within the ceiling), the result label of the last dispatch, output text, file list, and error message; slots never reached before budget exhaustion are recorded as not_run.

The wiring surface is the CLI. octos serve exposes four flags (crates/octos-cli/src/commands/serve.rs:420, :427, :433, :439):

Why an external MCP backend instead of reusing the local spawn of Chapter 12? A locally spawned sub-agent runs in the same process tree, sharing the harness tool registry, context manager, and evidence ledger: zero protocol overhead and naturally visible state. The price is that the sub-agent's failure domain is the host's failure domain: one sub-agent's memory bloat or infinite loop takes down the supervisor, and sub-agents are locked to octos's own runtime. Swarm faces a different problem: the executors may be heterogeneous agents such as claude and codex, each with its own tool surface and billing model; the supervisor must treat them as external systems, with requests passing gates, artifacts passing validation, and every step booked to a ledger. MCP turns this boundary into a protocol: the tools/call request/response shape is the whole coupling, swapping backend implementations does not touch a line of dispatcher code, and timeouts and transport errors have their own result classes that map onto retry semantics. The selection criterion follows directly: local spawn when in-process state must be shared and the executor is an octos agent; swarm when the executors are heterogeneous and a hard trust boundary is required.

--swarm-backend <stdio|cli|http>   backend kind
--swarm-backend-cmd <path>         command for stdio/cli backends
--swarm-backend-arg <arg>          repeatable argument
--swarm-backend-url <url>          http backend endpoint

build_swarm_state_from_flags (crates/octos-cli/src/commands/serve.rs:1867) assembles the flags into Swarm state: stdio attaches an MCP subprocess, cli drives a one-shot agent CLI, http connects a remote MCP endpoint, and an unknown value errors out; omitting --swarm-backend returns Ok(None), and the handler answers swarm requests with 503. This wiring closes the productionization requirement of audit #713; the dependency is declared at crates/octos-cli/Cargo.toml:32. Two details worth knowing: dispatch_once (crates/octos-swarm/src/dispatcher.rs:1053) tags every dispatch with DispatchContextContract (backend_kind=mcp, agent_id taken from contract_id, risk=medium), so the evidence ledger can identify each unmanaged dispatch without parsing free text (#1021/M17-C); and when a dispatch fails with empty output, the error body is copied into the output field so the next retry never receives a stale empty payload. The real dispatch is wrapped by dispatch_with_budget (crates/octos-swarm/src/dispatcher.rs:971): gates first, then budget reserve, then the backend call, then commit attribution; insufficient budget becomes a failed outcome rather than a panic.

Each of the three backends has its own fit. stdio suits hanging a swarm on a local MCP subprocess (for example claude mcp serve) whose lifetime follows the serve process; cli suits one-shot command-line agents (one process per dispatch, a nonzero exit code treated as retryable, test should_dispatch_through_cli_backend_with_retry_on_nonzero_exit, crates/octos-swarm/tests/swarm_dispatch.rs:1462); http suits a shared remote MCP endpoint that multiple serve instances pool. With one of the four flags missing, the assembly function errors outright (stdio/cli missing cmd, http missing url); it never silently falls back to some default backend.

17.5 Three gates

In the manual pattern, "the sub-agent got the task, so it runs"; the first requirement of formalizing the primitive is making "is it allowed to run" an explicit decision. Swarm has three gates, at different positions, over different objects, with different failure dispositions.

The first gate sits before dispatch and rules on "this dispatch itself". The glue layer enforce_or_outcome (crates/octos-swarm/src/gate.rs:25) calls octos-agent's shared check enforce_dispatch_gates (crates/octos-agent/src/dispatch_policy.rs:292, backend-aware variant :303) and folds a GateDenial into a swarm-local SubtaskOutcome (TerminalFailed, with last_dispatch_outcome recording the denial-reason label). The module doc of crates/octos-swarm/src/gate.rs states the motive: Swarm's dispatcher and the agent_mcp branch of SpawnTool go through the same checks, so no single bypass surface exists, which is exactly what audits #701 and #714 required. Internally the check runs five tests in a fixed order: sandbox requirement (cheapest, config only), tool policy (synchronous, no I/O), env denylist, env allowlist (denylist before allowlist, so a permissive allowlist cannot admit a known-bad key), approval (last, because it may block on a user). The five collapse into four policy faces (tool policy, approval, env allow/denylist, sandbox requirement), covering the four risks that external backends most realistically pose.

flowchart TD
    C["Contract reaches dispatch point"] --> G1{"enforce_dispatch_gates<br/>crates/octos-agent/src/dispatch_policy.rs:292"}
    G1 -->|"sandbox_required / policy_denied<br/>env_forbidden / approval_*"| DEN["GateDenial folded into<br/>SubtaskOutcome::TerminalFailed<br/>zero backend calls"]
    G1 -->|pass| B["McpAgentBackend.dispatch"]
    B -->|"Success"| SC["SubtaskStatus::Completed"]
    B -->|"Timeout / RemoteError"| SR["RetryableFailed, retried next round"]
    B -->|"Transport / Protocol / SSRF"| ST["TerminalFailed, never redispatched"]
    SC --> G2{"gate_subtask_validators<br/>crates/octos-swarm/src/dispatcher.rs:593"}
    G2 -->|"required validator failed"| DEMO["demote to TerminalFailed"]
    G2 -->|pass| AG["enter aggregation"]
    AG --> G3{"run_aggregate_validator<br/>crates/octos-swarm/src/dispatcher.rs:693"}
    G3 -->|verdicts| FIN["written into SwarmResult, sent with events"]

Figure 17-3: the decision flow of the three gates. Gate one rules on dispatch eligibility, gate two on individual artifacts, gate three on the merged artifact; denial labels (policy_denied, approval_unavailable, sandbox_required, and so on) flow stably into events and metrics.

The second gate sits at artifact reclamation. gate_subtask_validators (crates/octos-swarm/src/dispatcher.rs:593) runs completion-phase validators only on subtasks whose status is Completed; a failed required validator demotes Completed to TerminalFailed and writes the reason into error. Subtasks that already failed are not punished twice. Pipeline is the most sensitive to this gate: an unvalidated upstream artifact pollutes the pipeline_input of every downstream stage. The test should_run_completion_validators_in_swarm_subtask (crates/octos-swarm/tests/subtask_contracts.rs:123) points a validator requiring required.txt at an empty workspace and asserts every subtask is demoted.

The third gate fires after all subtasks reach a terminal state. run_aggregate_validator (crates/octos-swarm/src/dispatcher.rs:693) runs M4.3's ValidatorRunner on the aggregate artifact, configured by AggregateValidator (crates/octos-swarm/src/dispatcher.rs:92): runner, invocation, and validators. Validation results do not change subtask status; they are written as validator_results into SwarmResult (crates/octos-swarm/src/result.rs:145) and handed to the supervisor with the return value and the events. The validator system itself (declarative specs, evidence ledger, SafePolicy) is covered in Chapter 10; this chapter consumes only its conclusions.

Gate behavior is pinned by 9 cases in crates/octos-swarm/tests/swarm_dispatch_policy.rs: tool-policy denial on local and remote backends (:134, :180), fail-closed when approval lacks a requester (:224), approval denial blocking dispatch (:264), approval passage (:319), env allowlist intercepting a forbidden key (:366), require_sandboxed intercepting an unsandboxed backend (:428), no policy keeping the old behavior (:469), Sequential aborting on gate denial (:506). Case :469 is the regression anchor: under a default build (no policy), the backend dispatches as before and the outcome is Success; introducing the gates changed nothing for callers that configure no policy.

17.6 Idempotency and recovery: one ledger for three things

All idempotent state lives in DispatchStore (crates/octos-swarm/src/persistence.rs:93), a redb database (default file swarm-state.redb), one row per dispatch in DispatchRecord (:36); the record carries every subtask state transition, so after a crash, reopening the ledger is enough to resume. The schema version is DISPATCH_RECORD_SCHEMA_VERSION: u32 = 1 (crates/octos-swarm/src/persistence.rs:27); a row with a higher version is treated as absent: forward compatibility is delegated to "discard" rather than "guess". redb is synchronous, so all reads and writes go through spawn_blocking and are serialized by the io_gate mutex, ensuring that a cancelled write still lands inside the gate before the next read sees it (open/load/store at :110, :147, :178).

Idempotency is guaranteed by three pieces working together:

  1. finalized + final_result (#1718): at finalize, the computed SwarmResult is snapshotted verbatim into the record; replaying a finalized dispatch returns the snapshot directly, with validator verdicts and costs carried back unchanged. Old rows without a snapshot fall back to recomputation from subtask states. The fix motive is concrete: the old implementation recomputed on replay with empty validation results, which promoted a validator-failed Partial into Success on replay.
  2. contracts_fingerprint (#1719): the record stores a fingerprint of the contract table; reusing an id with a changed contract table, changed task payload, or changed topology is rejected by ensure_record_matches_dispatch (near crates/octos-swarm/src/dispatcher.rs:856, defined adjacent to InFlightGuard). Before the fix, such a replay either panicked out of bounds or booked a slot's output against the wrong contract.
  3. InFlightGuard (crates/octos-swarm/src/dispatcher.rs:833): an RAII registry of in-flight dispatch ids, registered on construction and released on every exit path including errors; a second concurrent caller is rejected outright instead of racing the load/store pair.

Each piece has a pinning test: verbatim replay (should_replay_finalized_result_verbatim_including_validator_verdicts, crates/octos-swarm/tests/swarm_dispatch.rs:821), changed payload rejected (should_reject_same_id_with_changed_task_payload, :1364), concurrent same id rejected (should_reject_concurrent_dispatch_with_same_id, :1100, which also asserts the id is reusable after the first run completes). The boundaries of recovery semantics have tests too: fewer contracts on recovery errors rather than panicking (:924), contract id mismatch errors (:1008), Sequential/Pipeline not resuming the tail after a persisted hard failure (:1163, :1213), and a recovery parked at the budget ceiling running no extra round (:1259).

The aggregate verdict comes from build_aggregate (crates/octos-swarm/src/result.rs:228) and SwarmOutcomeKind (crates/octos-swarm/src/result.rs:117): all complete with aggregate validation passing is Success, partial completion is Partial (the aggregate artifact is still usable; the caller may re-dispatch externally at its own discretion), zero completions is Failed, and early abort on a Sequential/Pipeline hard failure is Aborted. The aggregate artifact AggregateArtifact (crates/octos-swarm/src/result.rs:100) holds exactly three things: merged text, a merged file table, and free-form metadata. The primitive does not interpret metadata; routing info and supervisor annotations are stored by the caller as it sees fit.

17.7 The cost ledger: a thin adapter

crates/octos-swarm/src/ledger.rs is only 115 lines, a deliberately thin layer: the CostLedger trait (attribute books one entry, summarize totals them) plus the NoopCostLedger default implementation. The full CostAttributionEvent schema and persistence live in octos-agent's PersistentCostLedger (M7.4); the swarm side keeps only a narrow interface so the dispatcher need not depend on redb or the full attribution-event shape. The persistent ledger is swapped in only at serve wiring time (PersistentCostLedger::open(data_dir) inside crates/octos-cli/src/commands/serve.rs:1867); without it, total_cost_usd stays None. The test should_record_cost_attribution_via_ledger_stub (crates/octos-swarm/tests/swarm_dispatch.rs:1527) uses a spy ledger to verify that attribution records really pass through the trait. Per-subtask budget isolation goes through the reserve/commit API (crates/octos-swarm/tests/subtask_contracts.rs:225, :306).

Engineering decision: why Swarm sits beside Fleet instead of on top of it

Fleet (Chapter 16) is a redb-transactionalized recoverable plan kernel: the attempt/lease/generation state machine, outbox events, workers assembling closed tool sets per grant. Intuitively, swarm fan-out could be built on it: one subtask per attempt. octos declined, for three reasons. First, the failure models differ: a Fleet attempt is a recoverable execution unit with unlimited retries, while a swarm subtask is a contract whose three terminal grades (retryable / terminal failure / abort) map from MCP backend results, with a round-level rather than attempt-level retry budget; forcing one onto the other stirs two semantics together. Second, the trust boundaries differ: a Fleet worker runs in-process over a closed registry, while swarm's executors live out-of-process behind MCP backends, and the gates must handle questions unique to external backends: who receives the dispatch, with what environment, and whether approval is needed. Third, the evolution cadences differ: swarm's contracts, topology, and validation gates evolve independently, and stacking them on the Fleet state machine would drag the plan kernel's schema into every swarm-side change (Fleet's SCHEMA_VERSION is already at 3). The price of running side by side is two persistence files; the payoff is two kernels free to evolve under their own invariants. That is an acceptable trade.

17.8 Boundaries with neighboring chapters

The first gate reuses DispatchPolicy. Its relation to Chapter 6's tool policy (ToolPolicy, deny-wins): Chapter 6 covers the policy surface of an agent's inline tool calls, and this chapter is the same policy system's enforcement point on external MCP backend dispatch; DispatchPolicy bundles tool policy, approval, the env allowlist, and sandbox requirements for swarm to enforce before dispatch. Chapter 12's supervisor layer answers "what happens to orchestration state across a process restart" (event ledger and continuation scheduling), while swarm answers "distribution and aggregation of a batch of external contracts"; the two share the word supervisor but not the mechanism: swarm's ledger is a contract ledger, not an event ledger. Chapter 16's Fleet handles recoverable execution and this chapter handles fan-out and aggregation; the boundary is drawn in the sidebar above. Validators and the event ABI (M4.3, schema versioning) belong to Chapter 10, which this chapter only consumes via ValidatorRunner and HarnessEventPayload::SwarmDispatch. In the crate map of Chapter 1, octos-swarm hangs beside octos-agent and below octos-cli.

17.9 Chapter recap

  1. Scale: 7 source files at 2,505 lines plus 3 test files at 2,475 lines, 36 integration cases; tests run nearly 1:1 with source, every invariant with a name and a test.
  2. The contract is the smallest fan-out unit: ContractSpec has four fields, and task is opaque to the primitive; one dispatch caps at 128 contracts; FanoutPattern expands a seed with ::variant suffixes.
  3. Three primitives: Parallel (JoinSet refill, arrival-order aggregation), Sequential (abort on first hard failure, not_run preserved across recovery), Pipeline (dispatch only after the predecessor is Completed, pipeline_input folding); retry budget 3 rounds, consumed only by zero-progress rounds, checked before the round.
  4. Three gates: pre-dispatch enforce_or_outcome through the shared enforce_dispatch_gates (five checks in fixed order, #701/#714 single bypass surface); at reclamation gate_subtask_validators demotes Completed subtasks that failed validation; after terminal states run_aggregate_validator runs M4.3 validation on the aggregate artifact.
  5. The idempotency trio: finalized + final_result verbatim replay (#1718), contracts_fingerprint rejecting changed payloads (#1719), InFlightGuard rejecting concurrent same-id dispatch; ledger schema version 1, higher-version rows treated as absent.
  6. Cost goes through a thin adapter: CostLedger trait + Noop default, with PersistentCostLedger swapped in only at serve wiring.

Further reading

  • MCP specification (Model Context Protocol): https://modelcontextprotocol.io, the normative source for the tools/call request/response shapes and stdio/http transports
  • redb: https://github.com/cberner/redb, the embedded KV store behind swarm-state.redb, also used in Chapter 15
  • Chapter 10, sections 10.1 to 10.3, the ValidatorRunner five-step sequence, evidence ledger, and schema versioning; the full background of this chapter's third gate
  • Chapter 16, the Fleet kernel's attempt/lease/generation state machine, read alongside this chapter's sidebar

Exercises

  1. SubtaskStatus::from_dispatch classifies SSRF blocks as terminal-without-retry. If a backend with a high SSRF false-positive rate is onboarded, would you add "configurable terminal demotion" or keep the hardcoding? Where does each choice push the operational burden?
  2. Of the idempotency trio, contracts_fingerprint rejects same-id changed payloads. If a supervisor wants to re-run the same batch with slightly tuned parameters, is the right move a new id or an "explicit invalidation" API? A new id bloats the historical ledger; explicit invalidation introduces a new transaction boundary. How do you weigh them?
  3. The retry budget counts only zero-progress rounds. Construct a scenario where a malicious or pathological backend completes exactly one subtask per round, letting a dispatch run far beyond 3 rounds. Is that behavior a defect or a design? If a defect, what is the minimal fix?
  4. When DISPATCH_RECORD_SCHEMA_VERSION goes to 2, old implementations treat existing rows as absent (discarding them). For a deployment that has run a week and holds thousands of finalized records in the ledger, what does the upgrade mean? Would you switch to "migrate" or "read-only retention", and by what criterion?

Version note This chapter's analysis is based on octos main @ 9c157101 (statistics and re-verification 2026-09-03). octos-swarm is a new crate in the harness M7.5 phase: M7.4's persistent cost ledger (PersistentCostLedger) is already wired into serve, while CostLedger inside swarm remains a thin adapter. All line numbers come from the facts table assets/ch17-facts.md or this session's read-only checks against the source; the behavior of the four --swarm-backend* flags follows the assembly function at crates/octos-cli/src/commands/serve.rs:1867.

Chapter 18: Goal and Peer: Moving Objectives Out of the Context Window

Positioning: This chapter analyzes the two new lines added in v2: the goal line, 9 files totaling 52,445 lines (crates/octos-cli/src/goal_tool.rs 3,028, crates/octos-fleet/src/sqlite_ledger.rs 6,360, and others), and the peer line, 9 files totaling 5,969 lines (crates/octos-cli/src/peers/mod.rs 3,186 and others), close to sixty thousand lines of new code in all. Both answer one question: a long-horizon objective left in the model's conversational context rots, so where is it safe to keep it? Prerequisites: Chapter 5 (§5.10 the continuation boundary), Chapter 12 (supervisor and leases), Chapter 16 (the fleet kernel and the crate GoalLedger lives in). Who should read it: developers building multi-agent long-task systems, and architects who care about how an objective survives across sessions. This chapter is also a prerequisite for the outer loop in Part IV (Chapter 20): the outer loop observes and drives the inner loop through these primitives.

18.1 Why Move Objectives Out of the Context Window

The Claude Code style of goal implementation injects the goal text into the context every turn and relies on the model to keep honoring it through micro-level execution. In practice the model often does not: it stops after a few rounds, or gets pulled off course by the tool output in front of it. The goal text hangs on the system prompt while the progress is recorded in a conversational history that rots; one compaction pass can lose the intermediate conclusions. octoscode/docs/PEER_GOAL_ARCHITECTURE.md names this failure mode plainly: the objective survives, progress rots.

octos takes the goal out of the micro context and hands it to a server-side keeper that holds and advances it at the macro level. The keeper periodically dispatches work, collects results, and decides the next step through GoalContinue continuation ticks; each dispatched peer sees only a self-contained task brief in its own micro context, with no goal text inside. The persistence of the goal is guaranteed by structure, and one peer stopping does not stop the goal from advancing.

This design line lands in a division of labor between two systems. The goal line holds and advances objectives: crates/octos-cli/src/goal_tool.rs (3,028 lines, its first-line doc noting that it replaces the fragile prompt-based scheme of #1696), commands/{goal,ledger}.rs (1,116 + 240 lines), autonomy/{goal_loop_runtime,master_continuation_scheduler,supervisor_store,fleet_wake}.rs (1,562 + 1,416 + 3,277 + 1,807 lines), and crates/octos-fleet/src/sqlite_ledger.rs (6,360 lines). The peer line executes: crates/octos-cli/src/peers/mod.rs (3,186 lines), crates/octos-cli/src/peers/host.rs (502 lines), crates/octos-cli/src/commands/peer.rs (211 lines), and six peer tool files in octos-agent (2,070 lines together). The goal line's 9 files total 52,445 lines and the peer line's 9 files total 5,969 lines, a size gap of roughly nine times: the machinery that holds an objective is far more complex than the machinery that executes one. The ledger alone is 6,360 lines because every state transition, every finding, every escalation request, and every decision on an objective must leave an audit trail; the peer's entire protocol is just a dozen small files in one directory.

One detail of the layering is easy to misread: the goal's holder is not a standalone daemon but the keeper role inside crates/octos-cli/src/autonomy/agent_orchestrator.rs (33,639 lines). The continuations field (:11783) holds the scheduler; goal continuation, fleet dispatch, and ledger aggregation all happen in the master session's orchestrator. "Held on the server side" precisely means: the holder is not the model's conversational context, but persistent state in the orchestrator process plus two ledgers on disk. This is also why the outer loop (Chapter 20) can observe it: state that lives on the server has a stable query surface.

LineFilesLinesCore files
goal line952,445crates/octos-fleet/src/sqlite_ledger.rs 6,360, crates/octos-cli/src/goal_tool.rs 3,028, crates/octos-cli/src/autonomy/supervisor_store.rs 3,277
peer line95,969crates/octos-cli/src/peers/mod.rs 3,186, six peer tools 2,070

The division of labor with Chapter 16: the fleet kernel (redb) manages the execution state of plans and attempts, while GoalLedger (SQLite) manages the audit ledger of objectives, findings, and escalations; neither ledger substitutes for the other (the boundary was drawn in Chapter 16 §16.7). The division with Chapter 12: the supervisor manages the survival of in-session subtasks, while a peer is a process-level entity that spans sessions.

18.2 GoalLedger: The First Ledger of an Objective

crates/octos-fleet/src/sqlite_ledger.rs:13 defines pub struct GoalLedger, whose module first-line comment states that it is the persistent ledger for goals, tasks, findings, and escalations. It is a WAL-mode SQLite database: the master, the process manager, and peers are independent processes sharing one <data_dir>/goal-ledgers/<goal_id>.db file. impl GoalLedger runs from :206 to :2241 with 39 pub fns, in five groups by purpose:

GroupRepresentative methodsLines
openopen / open_with_busy_retry:222 / :245
goalcreate_goal :714, upsert_goal :811, cas_goal_status :899, get_goal :976, update_goal_status :1498, stamp_goal_cleared :2009-
taskcreate_task :1066, create_task_if_absent :1124, get_task :1166, update_task_status :1232, settle_task_status :1267, tasks_for_goal :1290-
append eventsappend_finding :1623, append_escalation :1635, resolve_escalation :1702, list_open_escalations :1745, append_decision :1807, commit_state_with_audit :1908-
statslist_findings_since :2132, task_status_counts :2178, total_cost_tokens :2232-

Two methods deserve a closer look. cas_goal_status (:899) is not a bare CAS: the UPDATE statement embeds a budget rule: when the goal is active and tokens_used >= token_budget, the status is written directly to budget_limited instead of whatever new status the caller asked for. The budget check runs at the single point of state transition and does not depend on caller discipline. open_with_busy_retry (:245, #1865) addresses a WAL initialization race observed in practice: when two connections initialize the same new database at the same time, contention on the wal-index recovery lock is not covered by the busy handler, a one-shot open can lose a millisecond-scale race and silently drop audit rows; this variant retries up to 3 times with 50ms between attempts, shortens busy_timeout to 1 second, and retries only when the error classifies as BUSY/LOCKED.

The operator exit from the state machine lives in crates/octos-cli/src/commands/goal.rs (1,116 lines, #25): octos goal reopen admits blocked|paused|budget_limited back to active, and octos goal archive admits any state into archived, with archived as an irreversible terminal state. The observation exit is in crates/octos-cli/src/commands/ledger.rs: octos ledger tail (:80) reads the goal-ledgers directory directly, with zero serve dependencies.

The budget is a soft limit. budget_limited stops only the self-driving GoalContinue tick; peers already running continue to completion, and external wakes still trigger continuation. The architecture document states this tradeoff plainly: do not kill a peer mid-work; let the user see partial results and then decide whether to raise the budget. The cost is that the budget may overshoot; operators must understand that budget limited does not mean stopped.

18.3 The goal Tool Family: The Keeper's Ten Handles

crates/octos-cli/src/goal_tool.rs defines 10 tools: 7 goal_* plus 3 monitor_* (#1977 zero-token monitors, keeper-gated: peers cannot arm them). Each tool's struct and fn name() line numbers are listed in the facts table:

ToolStructLinesResponsibility
goal_getGoalGetTool:350 / :404Read the goal snapshot, folding in findings and escalations
goal_planGoalPlanTool:561 / :575Decompose the goal into a persistent fleet
goal_dispatchGoalDispatchTool:766 / :780Dispatch ready tasks to the worker pool
goal_grantGoalGrantTool:861 / :875Approve a capability-expansion request from a Blocked task
goal_denyGoalDenyTool:1024 / :1050Deny an escalation request, moving the task to Failed
goal_updateGoalUpdateTool:1163 / :1266State transitions; completion claims must pass an independent verifier
goal_createGoalCreateTool:1495 / :1509Create a goal; admission checks serialize across two calls
monitor_create / monitor_list / monitor_delete:1634 / :1824 / :1893-The three event monitors

Wiring lives in crates/octos-cli/src/runtime/profile.rs: GoalGetTool :1323 (with .with_data_dir), GoalCreateTool :1326, GoalUpdateTool :1329-1337 (attaching a verifier lane if one is configured), GoalPlanTool :1341, GoalDispatchTool :1342, GoalGrantTool :1349, GoalDenyTool :1353. On the peer-session side the wiring is in crates/octos-cli/src/commands/chat.rs:859 and :1574-1577: a goal-bound peer gets only goal_get and goal_update, it can see the goal and record findings back to the master's ledger, but it cannot get plan or dispatch and has no authority to rewrite the plan.

goal_get is where the three return channels converge (:357, :491, :501): it first scans the live peers under <data_dir>/peers/ (data_dir.join("peers")), then reads the persistent findings from <data_dir>/goal-ledgers/<goal_id>.db, injecting them into the snapshot under the three keys peer_findings, ledger_findings, and open_escalations (#1967), with a ledger summary attached along the way (#1945). The keeper does not need to know where a peer is; one goal_get call settles the accounts.

The completion verdict lives in crates/octos-cli/src/autonomy/goal_loop_runtime.rs: GoalCompletionVerdict (:282, Done / NotDone) is delivered by an independent cheap-lane verifier. The #1935 comment quotes the loop-engineering principle directly: the agent's own claim of completion is only a claim, the verifier must independently return Done before a transition to Completed is allowed, and NotDone keeps the goal Active. The runtime types sit in the same file: GoalId (:10), GoalRuntimePolicy (:239, cadence plus max_continuations), GoalRuntimeState (:265, Active/Paused/Completed/Failed), and GoalRuntime (:305). The wrap-up instruction for an exhausted budget sits in the wrap_up_prompt field of GoalBudgetResolution (:298), passed through verbatim.

The verifier lane is injected at the wiring point: when crates/octos-cli/src/runtime/profile.rs:1329-1337 registers GoalUpdateTool, it attaches .with_verifier_provider if the profile configures goal_verifier_llm. Without that configuration the completion check falls back to the no-verifier path, which makes this one setting the master switch for "double-verify completion or not" in a production deployment. The plan and dispatch tools are wired in the same batch (:1341, :1342, #1857 PR 5a): goal_plan decomposes the goal into a persistent fleet and goal_dispatch sends ready tasks to the live worker pool; the escalation verdicts goal_grant (:1349) and goal_deny (:1353) consume the exits of the Blocked task state machine, and a deny that leaves the fleet unable to complete also syncs the per-goal ledger (#1964). These four tools connect Chapter 16's fleet kernel into the keeper's tool surface; this chapter only covers their place in the goal narrative, and the state machine details return to Chapter 16.

18.4 Continuation: GoalContinue and GoalWrapUp

Chapter 5 §5.10 examined MasterContinuationScheduler from the loop's point of view; this section completes the goal side. The MasterContinuationReason (:137) in crates/octos-cli/src/autonomy/master_continuation_scheduler.rs (1,416 lines) has six variants, two of which belong to goal: GoalContinue (:141) is the self-driving continuation, and GoalWrapUp (:147, #1131) is the final turn after the budget runs out. It carries a wrap_up_prompt that must be rendered verbatim, not through the standard advancement template.

priority() (:152) maps both variants to the same lane (:161), and the comment gives the reason: a wrap-up is the last goal turn before the session pauses, not a privileged turn. The priority ranks (:190-199) come in four grades: External=0, GoalContinue=10, ChildOrScatterJoinComplete=20, LoopFire=30, smaller values dequeue first. stable_name() (:169-176) gives deduplication and persistence a stable string: goal_continue (:171) and goal_wrap_up (:172).

The enqueue point is crates/octos-cli/src/autonomy/agent_orchestrator.rs:12963: it constructs MasterContinuationRequest::new("coding-autonomy-goal", ...) with .with_goal_id carrying the goal's identity, and metadata carrying objective and status. The scheduler itself, MasterContinuationScheduler (:477), is held by the continuations field at crates/octos-cli/src/autonomy/agent_orchestrator.rs:11783; enqueue_at (:532) enqueues, and drain_ready (:687) and drain_ready_for_session (:706) dequeue by priority. One detail: the 30-second RECENT_CLAIM_GUARD_WINDOW (:33-35) exists to block duplicate deliveries of the same-key External, while LoopFire, GoalContinue, and ChildCompleted, loop reasons that re-enqueue every tick, are deliberately excluded from the guard and never rejected.

External events can wake the keeper too. crates/octos-cli/src/autonomy/fleet_wake.rs (1,807 lines) is the consumer of the fleet kernel's outbox (PR 4a): a background task claims persistent outbox events and converts them into continuation requests for the keeper. The durability rule is written into the module doc: an event is acked only after the wake has been persisted (WakeCommit::Durable); an unpersisted event stays in the claimed state and is redelivered when its lease expires, so a crash in between loses no wake. The doc is also honest about scope: as of this commit no real fleet events are written on the production path, and the consumer proves its correctness with synthetic events from unit tests, dormant but correct. Its wake precondition is narrow: the keeper's workspace is already loaded, meaning an interactive or connected goal session; rehydrating headless sessions is left to PR 4b. The pure-function core drain_fleet_outbox_once (:235) holds no singleton, the process loop spawn_fleet_outbox_consumer (:343) calls the orchestrator's drain_fleet_outbox, and the commit callback the latter supplies persists only for the instant the runtime state is locked.

Supervisor-side support comes from crates/octos-cli/src/autonomy/supervisor_store.rs (3,277 lines): SupervisorStore (:697) persists the state of supervised agent groups, and load_state (:780) reads it back on restart. Chapter 12 covered its division of labor with leases; here it is enough to remember that goal continuation requests travel the same persistent path, the fleet_wake doc states plainly that its commit callback reuses the persistence pipeline shared by peer and goal wakes.

Taken together, this section's states show the goal state machine running at two levels. At the ledger level: cas_goal_status and update_goal_status (:1498) manage the string states active, complete, blocked, budget_limited, paused, cleared (the state set is documented in the comment at crates/octos-fleet/src/sqlite_ledger.rs:39, with terminal-state protection for complete and cleared, provable from the WHERE clauses at :914/:1512). archived is not in the ledger's state set; it is a terminal marker on the supervisor event-stream side (the comment at crates/octos-cli/src/commands/goal.rs:12-14 states outright that the authoritative source of goal state is the supervisor event stream, not the SQLite goals table), the two ledgers' state sets must not be conflated, and transition rules split into operator-reachable and model-reachable classes: the comments in crates/octos-cli/src/commands/goal.rs state that complete and blocked are reachable only by the model, archived only by the operator, and reopen admits exactly three source states: blocked, paused, budget_limited. At the runtime level: the four states of GoalRuntimeState (Active, Paused, Completed, Failed) are the in-memory advancement view, and the two constructors of GoalRuntimePolicy give two cadences: fixed_interval heartbeats at a fixed interval while self_paced is signal-driven, both capped by max_continuations. The keeper aligns the two levels: every GoalContinue tick reads the ledger, compares the budget, and decides whether to enqueue the next tick or switch to wrap-up. The goal-side enqueue tests (:1185) also verify that the dedup key carries the goal_id, so two different goals in the same session cannot crowd each other out of the queue.

18.5 The Peer Lifecycle: Six Stages

The peer's mental model comes from operating systems: a subagent (SpawnTool/DelegateTool) is like a thread, spawned within the parent turn, sharing the parent's context and workspace, terminated when the parent turn ends. A peer is like a forked process: it has its own session, working directory, turn loop, and budget, and it keeps running even if the parent dies. The two share no memory and communicate through blackboard files, the equivalent of IPC.

sequenceDiagram
    participant H as Operator
    participant M as Master agent
    participant S as octos server
    participant C as octoscode client
    participant P as Peer session
    H->>M: macro instruction (/goal or prompt)
    M->>S: peer_handoff(brief, name, worktree?, goal_id?)
    S->>S: persist peers/<slug>/{wt?, originator, goal?, brief.md}
    S-->>C: peer/staged notification
    C->>S: open peer-<slug> session in the background
    S->>P: boot: read back brief/goal/originator
    loop peer autonomous execution
        P->>P: turn loop (own tools and budget)
    end
    P-->>S: result.md (+ goal-ledgers if goal-scoped)
    S-->>C: peer/closed notification
    M->>S: peer_gather / goal_get

The six stages each have a landing point:

  1. Stage. stage_peer (crates/octos-cli/src/peers/mod.rs:1563) writes under peers/<slug>/ in a fixed order: worktree (:1598), originator (:1702), goal (:1729), brief.md (:1738), name (:1752). The order is itself the publication invariant, expanded in 18.6. The model-side entry is the peer_handoff tool (crates/octos-agent/src/tools/peer_handoff.rs:133), which only validates parameters (brief cap, name cap of 64 characters, duplicate names rejected outright rather than auto-suffixed); the staging writes are performed by the host callback.
  2. Staged notification. The server only stages; the session is opened by the client (session and client connection are coupled). The peer/staged notification means "persisted, please open it": on receipt the client opens a peer-<slug> session in the background. This division of responsibility is deliberate: the server does not know the client's window management, and the client does not know the staging file protocol.
  3. Client opens. The peer session is established under its own topic, its session key identified by the peer-<slug> prefix, a prefix later reused by depth-1 governance.
  4. Boot read-back. read_peer_boot at crates/octos-cli/src/peers/host.rs:96 reads the execution context back from the blackboard: :99-116 parses the goal file (line one goal_id, line two task_id; an empty goal_id discards the orphaned task_id so the agent is never handed a dangling subtask), originator is read once at boot to prevent rebinding mid-run, and the brief is read under the 1 MiB cap. Every field is independently optional: a peer with no goal or no brief is degraded, not dead, only a slug that is not a real staged directory returns empty.
  5. Run. The peer has a full turn loop and toolset. The terminal artifact is written back to the blackboard by write_peer_result_if_peer_session at crates/octos-cli/src/api/ui_protocol_transport.rs:14279: four frontmatter fields (slug/outcome/updated_unix/turn, :14334), with the turn number derived by counting the existing result-<n>.md files plus one (:14328-14329) and the body capped at 256 KiB (:14306). A peer whose budget ran out writes a different five-field checkpoint copy (crates/octos-agent/src/agent/budget.rs:584: status/completed/iteration_budget/iterations_used/checkpoint_commit); work-in-progress survives as a commit on the branch, "not completed" is stated in plain words, and the prompt says to raise the cap or split the task on re-dispatch. If the peer holds write ownership (.result-owner: peer sidecar, #27f/#27h), the runtime must not overwrite its terminal state; the peer's handwritten content is free-form, unconstrained by the four-field template.
  6. Closed and gather. The closed tombstone file marks the terminal state (peer_is_closed, :1317), and the peer/closed notification tells the client to update its UI; the master pulls result.md with peer_gather, or settles accounts directly with goal_get. The command-line observation surface is octos peer list (crates/octos-cli/src/commands/peer.rs:54), which likewise reads the blackboard directory directly, with zero serve dependencies.

18.6 The Blackboard: The File Layout Is the Protocol

There is no shared memory between peer and master; the files under peers/<slug>/ are the protocol itself:

<data_dir>/
├── peers/<slug>/
│   ├── brief.md          # task contract, ≤64KB, the peer's entire input
│   ├── name              # display name, primary addressing key
│   ├── originator        # master session key, read once at boot
│   ├── goal              # two lines: goal_id and task_id, goal-scoped only
│   ├── result.md         # live result, will be overwritten
│   ├── result-<n>.md     # versioned copy (#435), count_peer_result_versions :2592
│   ├── result.checkpoint.md  # budget-checkpoint copy (#27e)
│   ├── turns.txt         # line-oriented turn index, parse_peer_turns_index :2649
│   ├── closed            # tombstone, peer_is_closed :1317
│   ├── model             # lane key, read_peer_model_lane :2189
│   └── wt/               # isolated clone in worktree mode
└── goal-ledgers/<goal_id>.db  # persistent ledger: findings and state transitions

The write order of stage_peer carries two invariants. First, brief.md is the visibility gate: staged_peer_dir (:417) decides whether a peer exists by the presence of brief.md, so brief.md must be written last; the peer "exists" only after it lands. Any failure before that goes through cleanup_staged_peer for wholesale recovery, never leaving a visible but incomplete peer. Second, originator is written before brief.md, guaranteeing that any fleet ownership scan that can see the peer can also read its owner; there is no "visible but unowned" window, whose harm is concrete: the synthesis triggered when a sibling peer completes would silently omit this peer. The goal file (:1729) likewise lands before brief.md. name (:1752) is the display name and primary addressing key; the staging brief is also recorded as the first entry of instruction history so that history starts where the work starts, while brief.md itself stays authoritative.

Those are not the only leaves. result-<n>.md is the versioned copy (#435): count_peer_result_versions (:2592) counts the result- prefixed files and the count is the version number, so a persistent peer running multiple rounds never silently overwrites old results. result.checkpoint.md is the sidecar of the #27e budget checkpoint, written by the peer itself when it holds write ownership; turns.txt is the line-oriented turn index, parsed line by line by parse_peer_turns_index (:2649); closed is the tombstone (peer_is_closed, :1317); model records the lane key (read_peer_model_lane, :2189).

The read path has symmetric defenses. All file reads are anchored on fds (openat plus atomic writes via renameat) and refuse symlinks; read caps are tiered: 64 KiB for small files (PEER_FILE_READ_CAP_SMALL, :462), 1 MiB for brief and result (PEER_FILE_READ_CAP_LARGE, :457); the brief write cap is 64 KB (PEER_BRIEF_MAX_BYTES, :1422). Addressing is keyed on name: resolve_peer_name_to_slug (:1329) resolves a human-readable name to a slug, case-insensitively. The blackboard's row view is PeerBlackboardRow (:2676: slug, name, brief, result, turn history, lane, closed, worktree presence), assembled by read_peer_blackboard (:2714) enumerating the directory, and rendered into peer_list output by compose_peer_list_text (:2802). Every read and write in this file protocol has a cap, atomicity, and versioning, that is the entire justification for the word "blackboard" carrying inter-process communication duty.

18.7 The Truth About Worktree: It Is a Clone, Not a Worktree

--worktree is nominally a worktree; the implementation is git clone --no-hardlinks (crates/octos-cli/src/peers/mod.rs:1638 and :1640, with clone and --no-hardlinks as two arguments on their own lines). The source comment (from :1624) records why it must be so: the .git created by git worktree add is a file pointing at <repo>/.git/worktrees/<name>, a directory outside the peer's sandbox, so any git command run inside the peer reports fatal: not a git repository. The model will then "rescue" itself with git init, destroying the fence branch entirely, and the deliverable never lands on disk. A clone puts a complete .git inside peers/<slug>/wt: git works normally, the sandbox needs no widening, and one peer cannot reach another's refs.

The case for --no-hardlinks is likewise in the comment: the default local-clone optimization shares the object files' inodes between the child repository and the source, and a peer writing its own .git can corrupt the source repository's objects; isolation is the entire point of the feature, so the cost of one real object copy per peer is accepted. The cost is stated openly: if staging latency becomes a problem, revisit with evidence. After the clone, the peer's fence branch is checked out in its own clone (the peer/<slug> branch), and the clone inherits none of the source repository's LOCAL config.

18.8 Binding and the Three Return Channels

The connection between goal and peer lives in the handoff parameters and the goal file. PeerHandoffRequest (crates/octos-agent/src/tools/peer_handoff.rs:35) carries optional goal_id and task_id; the master passes them when handing off under an active goal, and the server writes them atomically into the two-line peers/<slug>/goal file. A peer without a goal file behaves exactly like an ordinary peer. The peer does not own the goal: after boot reads back the binding, its goal_get resolves directly by id to the master's goal via the recorded goal_id and originator session, and records its findings into the master's ledger.

flowchart LR
    subgraph MASTER["Master session (keeper)"]
        GG["goal_get :350"]
    end
    subgraph PEERDIR["peers/&lt;slug&gt;/"]
        RM["result.md<br/>(live, will be overwritten)"]
        GF["goal (two-line binding)"]
    end
    subgraph LEDGER["goal-ledgers/&lt;goal_id&gt;.db"]
        LF["append_finding :1623"]
        ES["append_escalation :1635"]
    end
    PEER["goal-scoped peer"]
    PEER -- "Channel 1 peer_findings" --> RM --> GG
    PEER -- "Channel 2 ledger_findings" --> LF --> GG
    PEER -- "Channel 3 open_escalations<br/>(written when parked)" --> ES --> GG
    GF -. "boot read-back" .-> PEER

The three return channels converge at goal_get: the live channel reads peers/<slug>/result.md, fast but overwritten; the durable channel goes through GoalLedger::append_finding (:1623), persisted every time a goal-scoped peer finishes a turn, surviving restarts as the authoritative history; the escalation channel writes append_escalation (:1635) when a peer parks on an approval or a question, so a master that missed the real-time notification can still see in goal_get's open_escalations who is waiting, with approval via peer_respond or goal_grant. The design intent turns "missed the notification" from an exceptional path into an ordinary read path.

One trap found in engineering practice must go into the docs: the model does not pass goal_id automatically. When the master has no active goal, or the prompt does not ask for binding, the handoff produces an ordinary peer whose output never enters the goal ledger. Testing the return chain requires explicitly requesting the binding. That is why the architecture document flags it as an observed trap: the tool's default is "not bound," and the benefits of binding (durable history, goal_get accounting) exist only after the parameter is passed explicitly.

The lane parameter rides in the same request: model (crates/octos-agent/src/tools/peer_handoff.rs:59) is a key of the master profile's sub_provider (cross-referenced with Chapter 9); the host validates that the key exists, an unknown lane degrades to the primary model and is reported faithfully via PeerHandoffStaged.model_note (:86); a matching key is recorded in the model file (record_peer_model_lane, :2205), and the peer's turns resolve providers by that lane.

18.9 Governance: Three Hard Constraints

The peer mechanism gives the model the power to fork; the governance constraints are all enforced at the serve wiring point, not by prompt:

  • Depth-1: a peer session's topic is identified by the peer- prefix, and peer_handoff_allowed_for_session (crates/octos-cli/src/peers/mod.rs:1934) rejects on sight; peer_handoff is absent from the peer's tool registry, the model cannot even see it. A peer cannot fork another peer; recursion is cut off at the tool-visibility layer (the comment at crates/octos-agent/src/tools/peer_handoff.rs:12-13 says as much).
  • Per-turn cap: PEER_HANDOFFS_PER_TURN_MAX = 4 (:1928), enforced at :2062; exceeding it returns an error. At most four peers dispatched per turn, so fan-out never runs away.
  • Brief cap: PEER_HANDOFF_BRIEF_MAX_BYTES = 64 * 1024 (crates/octos-agent/src/tools/peer_handoff.rs:27); the comment's framing is that a brief is a task contract, not blob storage; the server-side PEER_BRIEF_MAX_BYTES (crates/octos-cli/src/peers/mod.rs:1422) mirrors the same value.

The master-side tool family has six members covering the peer's full operating surface: peer_handoff (staging, :133), peer_list (roster, :56), peer_gather (collecting results, :64), peer_respond (answering a parked peer, :148, control channel), peer_close (:62), and peer_send_input (:90).

Engineering decision: peers are processes, subagents are threads A subagent spawns inside the parent turn, shares context and workspace, and returns its result directly into the parent context as a tool result, dying with the parent turn if it is interrupted: thread semantics, lightweight, fate bound to the parent process. A peer has an independent session, an isolatable working directory, its own turn loop and token budget, and keeps running if the parent dies: process semantics, isolation bought with overhead. The selection criterion is the failure domain: should a crashed task take the parent session down with it, and should the deliverable still be on disk after a restart? Blackboard files are the IPC between the two: no shared memory, contract (brief) and result both plain files, readable by either side after the other crashes. PeerTaskBinding (crates/octos-cli/src/peers/mod.rs:166) ties a peer to a supervisor lease (bind_peer_supervised_task, :241; retire_peer_supervised_task, :264), so peer liveness rides on supervisor lease semantics, Chapter 12's lease semantics reused here.

18.10 Boundaries and Recap

With Chapter 5: the data structures of MasterContinuationScheduler were covered from the loop's perspective in Chapter 5 §5.10; this chapter adds the full set of goal-side variants and the external wake. The forward reference at the end of Chapter 5, "Chapter 18: the consumer side of MasterContinuationScheduler and the full picture of goal continuation", is hereby redeemed. With Chapter 12: the supervisor's event ledger and SupervisorStore (:697/:780) manage in-session subtasks, and PeerTaskBinding is the lifeline by which a peer borrows that machinery; the full lease state machine stays in Chapter 16. With Chapter 16: the fleet kernel's six redb tables manage plan execution, GoalLedger manages goal auditing, and goal_plan/goal_dispatch connect the two on top of the keeper; the grant verdicts on escalation (goal_grant/goal_deny) consume the exits of Chapter 16's Blocked state machine. The outer-loop protocol itself (Chapter 20) and TUI display (Chapter 19) are out of scope here.

Chapter recap:

  1. Goals persist server-side: GoalLedger's 39 pub fns in five groups manage objectives, tasks, events, and statistics; cas_goal_status embeds the budget rule into the single state-transition point, and budget_limited is a soft limit.
  2. The keeper's ten handles: 7 goal_* tools plus 3 monitor_*; the peer side wires only goal_get and goal_update, planning authority is not delegated.
  3. Continuation has priorities: GoalContinue and GoalWrapUp share a lane, wrap-up is the last turn, not a privileged one; fleet_wake persists a wake before acking it, losing no events.
  4. The peer protocol is files: the write order (brief.md last) carries the visibility invariant, result exists as both a live copy and versioned copies, the terminal state has four frontmatter fields, the checkpoint five.
  5. Worktree is git clone --no-hardlinks under the hood: .git must land whole inside the sandbox, shared inodes would corrupt the source repository, and isolation outranks staging latency.
  6. Binding is explicit and returns flow through three channels: the two-line goal file plus an explicitly passed goal_id; results converge on goal_get via peer_findings, ledger_findings, and open_escalations.
  7. The three governance constraints are enforced at the wiring point: depth-1 via tool invisibility, a per-turn cap of 4, a brief cap of 64KB.

The database file goal_ledger.sqlite is held exclusively by the keeper process; workers and transitions read and write only through the WAL side. This holding relationship is the foundation of the recovery semantics.

Further reading

  • octoscode/docs/PEER_GOAL_ARCHITECTURE.md: the original architecture document, design lineage, binding and return channels, the soft budget limit; several figures in this chapter are drawn from it and verified against source.
  • crates/octos-fleet/src/sqlite_ledger.rs: all 39 public methods of GoalLedger and the #1865 race-condition comment.
  • crates/octos-cli/src/peers/mod.rs:1624-1640: the complete commented argument for clone instead of worktree.
  • Chapter 16's docs/FLEET-RUNTIME-ADR.md: the architecture decision record for the goal/fleet layering.

Exercises

  1. cas_goal_status embeds the budget verdict in the UPDATE's CASE expression. If the same check moved to the tool layer (read tokens_used, then write status), which concurrency window would let an over-budget goal keep turning? What happens when two processes execute this UPDATE simultaneously under WAL?
  2. brief.md is the visibility gate and must be written last. If the name file were written after brief.md and the process crashed before the staged notification, what state of peer would appear? How would resolve_peer_name_to_slug handle it?
  3. --no-hardlinks pays one full object copy per peer. With 2 GB of objects in the source repository and 20 peers to dispatch, how do you estimate the staging cost? What scheme would cut that cost without reintroducing the inode-sharing corruption risk?
  4. The model not passing goal_id automatically is an observed trap. Suppose peer_handoff added a policy of "bind by default when the master has an active goal": which validations would change? Which class of goal-agnostic delegation would this default hurt?
  5. GoalWrapUp and GoalContinue share a priority lane. If wrap-up got its own higher priority, in what order would the closing turn at the moment of budget exhaustion compete with other sessions' GoalContinue? Why did the designers decide it should not be a privileged turn?

Version note: This chapter is new in v2; the analysis baseline is octos main @ 9c157101 (collected and re-verified 2026-09-03). The goal and peer lines are both new code: the goal tool family comes from #1696 (replacing the prompt-based scheme), the peer mechanism from #1801 v3, continuation scheduling from M15, budget wrap-up from #1131, the monitor family from #1977, and peer-goal binding and return channels from #1967 and #1945. All line numbers and line counts come from the facts table assets/ch18-facts.md (committed in the same batch as 8a008e5) or from this session's read-only verification against the source; the forward references from Chapter 5 §5.10 and Chapter 12 land here. The measured shape of the result.md frontmatter (four fields on the runtime copy, five on the checkpoint copy) follows the source and does not carry over the six-field wording of the early spec.

Chapter 19: octoscode: Terminal Client and the UI Protocol

Positioning: This chapter dissects octoscode, the terminal client of octos: it runs no agent, executes no tools, holds no ledger, and talks to octos serve only through the UI Protocol. The startup chain, the transport layer, the reducer, the protocol contract, the client side of goal/peer, and the observation surface for the outer loop all converge here into a single line. Prerequisites: Chapter 14 (the serve control plane and the stdio mount surface), Chapter 18 (the server-side goal/peer machinery). Who should read it: developers writing a client for octos, wiring the TUI into their own observation stack, or asking how thin a client can be.

19.1 The Client Boundary: A Terminal That Executes Nothing

Start with the conclusion. In protocol mode, octoscode is a dumb client. The Scope section of octoscode/docs/ARCHITECTURE.md:3 draws the boundary in one sentence:

octoscode is a standalone terminal client for the Octos UI Protocol. In protocol mode it does not run the Octos agent, execute tools, approve commands, maintain the durable ledger, or own provider/model configuration. Those responsibilities belong to the octos serve process.

As a checklist: it runs no agent, executes no tools, makes no approval decisions, maintains no durable ledger, holds no provider/model configuration; all five of those belong to the octos serve process. What the TUI owns is presentation only: terminal rendering and keyboard handling, local view state (focus, scrolling, expansion, composer drafts), optimistic display of user prompts, local slash commands (/ps, /stop, /help), and the translation of user interactions into stable AppUiCommand values. The server owns session creation and cwd validation, the agent runtime, shell/tool execution and sandbox policy, approval requests and decisions, the task supervisor and the background-task registry, the durable UI event ledger and replay, and the diff-preview and task-output data sources.

Architectural invariants back this boundary (the Architectural Invariants section starting at octoscode/docs/ARCHITECTURE.md:713): octoscode must not call Octos runtime internals directly; it must not depend on M9 server internals beyond AppUI; it must treat the server as the authority on tasks, approvals, diffs, tool results, cwd policy, sandbox policy, and replay; the server must not require TUI-specific behavior for protocol correctness; any new client-visible capability must first land in the UI Protocol types in crates/octos-core and only then in TUI rendering; prompt shaping for the coding experience belongs to the server-side profile or the harness prompt contract, not to the client. In other words, only one contract is allowed to exist between client and runtime: the protocol.

By size, octoscode's top-level src/ holds 26 files totaling 96,124 lines (embedded tests included). The largest is octoscode/src/store.rs (43,935 lines, the reducer, with embedded tests), followed by octoscode/src/model.rs (12,884 lines), octoscode/src/transport.rs (12,214 lines), octoscode/src/event_loop.rs (8,655 lines), and octoscode/src/app.rs (6,286 lines); the subdirectories add app/ with 5 files, cmd/ with 8, and menu/ with 10. Beyond the entry point there are a few peripheral facilities: octoscode/src/backend_ensure.rs (1,317 lines) manages automatic backend installation, octoscode/src/autonomy.rs (1,192 lines) parses the client side of goal/peer, octoscode/src/tui_terminal.rs (1,171 lines) is an inline-viewport terminal trimmed and ported from codex-rs, and octoscode/src/insert_history.rs (1,602 lines) writes finalized output back into the terminal's native scrollback. A client that "executes nothing" yet weighs in at nearly a hundred thousand lines — that contrast is what this chapter explains: the thin part is the responsibility, not the code volume. Making interaction thick and permissions thin is itself heavy work.

A comparison helps locate where this boundary sits. The comparison model at the end of the architecture document (octoscode/docs/ARCHITECTURE.md:666) places the Codex-style local CLI and Octos's split side by side in one table: a Codex-style client process owns the runtime itself (tool execution in a local sandbox, approval policy local, sessions and replay local), and the model service provides inference only; Octos moves all of that into octos serve, leaving the client with rendering and interaction. Both can deliver a good coding experience. The difference is replaceability and observability: Octos's terminal application can be swapped out wholesale, every client speaks the same AppUI API, and runtime state concentrates on the server, where an external observer can read the ground truth without touching the client.

Engineering decision: the price of a dumb client A dumb client gives up local autonomy: without a server, octoscode cannot run a single shell command for you (mock mode only renders test fixtures). What it buys is three things. First, a single security boundary: tool execution, sandboxing, and approvals are all enforced server-side; a compromised client holds no execution power, and policy does not need to be implemented twice at both ends. Second, a replaceable client: the comparison model at octoscode/docs/ARCHITECTURE.md:666 sets the Codex-style local CLI (runtime inside the CLI process) against Octos's split, concluding that the terminal application can be replaced wholesale and every client speaks the same AppUI API. Third, externalized observation: state lives in the server and the protocol stream, so external processes can observe without intruding on the client (herdr in Chapter 21 exploits exactly this). The price is that the protocol itself must be thick enough — the 7,221 lines of wire types (see §19.5) are the bill for it.

19.2 The Startup Chain: From a 57-Line main to a 44,000-Line Reducer

The binary entry of octoscode is tiny. octoscode/src/main.rs is 57 lines in full, with fn main() at octoscode/src/main.rs:4:

fn main() -> Result<()> {
    color_eyre::install()?;
    install_terminal_restoring_panic_hook();
    // 拦截 update/doctor 子命令,命中则直接退出
    if let Some(code) = cmd::dispatch(std::env::args())? {
        std::process::exit(code);
    }
    let mut cli = Cli::parse()?;
    // 本地 stdio 启动且未安装 octos 时,先装好后端
    backend_ensure::ensure_octos_backend(&mut cli)?;
    octoscode::splash::play(&cli);
    event_loop::run(cli)
}

The order of the four steps is deliberate. Step one intercepts the update/doctor subcommands (octoscode/src/main.rs:10): these two must print while the terminal is still in normal mode, so they cannot enter the event loop. Step two, ensure_octos_backend (called at octoscode/src/main.rs:22, implemented at octoscode/src/backend_ensure.rs:113), must run before raw mode, and a comment states why: the installer's output needs to print cleanly to the terminal. Step three plays the startup splash. Step four finally enters event_loop::run (octoscode/src/event_loop.rs:192).

The conditions of ensure_octos_backend are deliberately restrained. Reading the implementation from octoscode/src/backend_ensure.rs:113 yields four early returns: non-Protocol mode (mock spawns no subprocess) returns immediately; an empty stdio_command (WebSocket startup, no local backend to install) returns; a command other than a bare octos (user-managed path, PATH override, or a non-octos command, left alone) returns; a command already resolvable on PATH also returns. Only "protocol mode + bare octos + not installed locally" triggers the install, and after a fresh install the cli.stdio_command is rewritten to the explicit path ~/.octos/bin/octos. That is what wires up the first-run experience: a user gets a new octoscode, types, and it installs the server itself.

The default spawn command is a constant, octoscode/src/cli.rs:118:

#![allow(unused)]
fn main() {
pub const DEFAULT_STDIO_COMMAND: &str = "octos serve --stdio --solo";
}

Default backfill happens at octoscode/src/cli.rs:415 and octoscode/src/cli.rs:849. Chapter 14 already unpacked this command's semantics: --stdio keeps serve from binding HTTP and runs the UI Protocol's JSON-RPC over stdin/stdout; --solo pins the single-session posture. The full startup chain:

sequenceDiagram
    participant U as 用户终端
    participant M as octoscode/src/main.rs
    participant BE as octoscode/src/backend_ensure.rs
    participant EL as octoscode/src/event_loop.rs
    participant T as octoscode/src/transport.rs
    participant S as octos serve 子进程
    U->>M: octoscode
    M->>M: 拦截 update 或 doctor
    M->>BE: ensure_octos_backend
    BE->>BE: 必要时装 octos 并改写命令
    M->>EL: run
    EL->>T: build_backend
    T->>S: 拉起 octos serve --stdio --solo
    S-->>T: AppUiSnapshot
    T-->>EL: bootstrap 返回快照
    EL->>EL: Store::from_snapshot 后进渲染循环

19.3 The Transport Layer: One Trait, Two Drivers

The whole abstraction of the transport layer is three methods, octoscode/src/transport.rs:238:

#![allow(unused)]
fn main() {
pub trait AppUiBackend {
    fn bootstrap(&mut self) -> Result<AppUiSnapshot>;
    fn send(&mut self, command: AppUiCommand) -> Result<()>;
    fn next_event(&mut self) -> Result<Option<ClientEvent>>;
}
}

build_backend (octoscode/src/transport.rs:244) picks one of two modes: mock goes to MockAppUiBackend (octoscode/src/transport.rs:4542, implemented at octoscode/src/transport.rs:4699); protocol goes to ProtocolAppUiBackend (octoscode/src/transport.rs:311, implemented at octoscode/src/transport.rs:1585, with the AppUiBackend impl block at octoscode/src/transport.rs:2235). The architecture document is blunt about mock's role: a deterministic rendering fixture, not to be used to validate server policy, sandboxing, provider configuration, ledger persistence, or tool execution.

The connection target is expressed by AppUiEndpoint (octoscode/src/transport.rs:192), two variants: WebSocket { url, auth_token, profile_id } and Stdio { command }. The corresponding drivers are WebSocketTransportDriver (octoscode/src/transport.rs:556) and StdioTransportDriver (octoscode/src/transport.rs:566). The CLI holds the choice: --endpoint names a UI Protocol v1 WebSocket endpoint (octoscode/src/cli.rs:126, parsed in the argument definitions starting at octoscode/src/cli.rs:204); without it, the stdio subprocess path is taken. The difference between the two paths goes beyond the medium. A WebSocket reconnect is only a reconnect: the server and its sessions stay alive; a stdio "reconnect" means respawning the subprocess. Fortunately the solo-mode data directory is anchored by the OCTOSCODE_SHARED_INSTANCE environment variable, so a respawn reattaches to the same directory instead of forking a new database (see the comment around octoscode/src/transport.rs:997). When the data directory is occupied, the server emits the OCTOS_DATA_DIR_LOCKED marker; the client recognizes this token and stops the restart loop. Chapter 14 covered the replay of this same mechanism from the serve side.

Reconnect backoff is exponential: a base delay before the first retry, doubling on each consecutive failure, capped at a limit (constants and comments from octoscode/src/transport.rs:354). Every stopped-driver error message carries the same phrasing, "reconnect will retry on next send/read", deferring the reconnect to the next read or write instead of spinning in the background.

What bootstrap does, in order, is informative (implementation from octoscode/src/transport.rs:2235): it connects first: with --readonly, a failed connection is not an error but a read-only offline snapshot for inspection; then sends the capabilities request (the protocol handshake, §19.5); with a profile attached, sends ProfileLlmList; with a session_id, sends OpenSession (SessionOpenParams carries session_id, profile_id, the requested cwd, and the known replay cursor); finally assembles the first-frame AppUiSnapshot from the startup arguments. The event loop takes the snapshot, and Store::from_snapshot (called at octoscode/src/event_loop.rs:230) completes the cold-start hydration.

19.4 Store: The 44,000-Line Reducer

The client's state machine is a functional reducer: octoscode/src/store.rs:287 defines pub struct Store with a single field, AppState; from_snapshot at octoscode/src/store.rs:423 folds the server snapshot into the initial state. Every state change afterwards goes through one of two entries, both returning Option<AppUiCommand>:

  • apply_client_event (octoscode/src/store.rs:8241): consumes ClientEvent, the event as decoded by the transport layer;
  • apply_event (octoscode/src/store.rs:9063): consumes AppUiEvent, the unified shape of server notifications and local events.

This is the largest single source file in the repository, 43,935 lines, thirty thousand lines more than the runner-up octoscode/src/model.rs, and the size is structural, not accumulated debt. Split its responsibilities by AppState's field families and the reducer's fold covers the entire client-visible world: sessions and the thread tree, verbatim accumulation of messages and reasoning deltas, tool cards and diff previews, approval requests waiting and resolving, the background-task registry and output streams, composer drafts and multiple pending messages, the menu stack and Dock layout, the capability set and permission profile, the goal panel and peer roster. Each family corresponds to a group of notifications in the full UiNotification set; however many shapes the server emits, that is how many match arms apply_event has. This is why the reducer cannot be small: it is the complete consumer of the wire contract. The protocol is as thick as the state machine.

Beyond folding events, the store also translates raw user input into commands. The Client Layers table in the architecture document describes its job as "snapshots, RPC results, notifications, local commands, approvals, diffs, task output and queued prompts folded into AppState": eight classes of input, two entries. The slash-command dispatch chain also lives here: Store::dispatch_slash_command fans out to dispatch_command_entry and dispatch_autonomy_slash, and the doc comment around octoscode/src/store.rs:291 defines the dispatch result SlashCommandOutcome: a command can parse into a known verb and still be rejected at dispatch (readonly mode blocks mutating methods, /turn is refused without an active turn, autonomy parsing errors out), and history is written only after genuine acceptance, the correctness precondition for composer command history. Queued prompts (pending messages) are enqueued and released inside the reducer as well: user input is not lost when the network drops, and after reconnect hydration it is resent in order.

One architectural constraint deserves a name. The store's two entries do not just mutate state; they produce follow-up commands, which makes the reducer both a state machine and a follow-up command constructor. The designers were well aware of the risk of 44,000 lines, and their answer was not to split the file but to converge all state transitions into a single point: any bypass that mutates AppState directly creates a second source of truth for replay and reconnect hydration. Chapter 18's server-side GoalLedger gathering state transitions into one impl block through 39 methods is the same discipline mirrored on the server: the entry to state transition must be unique, even if the impl block grows enormous as a result.

The follow-up-capable return value is the key to this design: the reducer is not a pure fold; it can also produce the next action. The Turn Flow in the architecture document gives the canonical example: the user presses Enter in the composer, compose_command generates a new turn_id, optimistically appends the user message locally, and returns AppUiCommand::SubmitPrompt; the transport sends turn/start; the server streams turn, message, tool, approval, task, progress, and warning events; each event folds through apply_client_event, and a fold can trigger further commands; for example, when a diff approval request arrives, a diff/preview/get is sent automatically.

ClientEvent (octoscode/src/client_event.rs:25) is the client's internal event universe. Its first variant, App(Box<AppUiEvent>), carries the AppUiEvent from crates/octos-core/src/app_ui.rs:172 (five variants: Snapshot, Protocol, Progress, Status, Error); the remaining variants are RPC results decoded locally by the transport: capabilities, diff previews, the model list, MCP status, permission profile, session hydration, session list, launch resolution, and so on. From<AppUiEvent> for ClientEvent (octoscode/src/client_event.rs:132) connects the two. A division worth noting is that the wire-layer UiNotification is decoded in the transport and never appears inside ClientEvent; server notifications uniformly enter the store as AppUiEvent::Protocol, and the client state machine is blind to the transport medium.

The event loop drives these two entries in one shape (drain_backend_events at octoscode/src/event_loop.rs:755): each tick drains at most MAX_BACKEND_EVENTS_PER_TICK events, handing each to apply_client_event_and_send_followup (octoscode/src/event_loop.rs:816): fold, then send_command if there is a follow-up. After draining, it calls drain_pending_autonomy_hydration (around octoscode/src/event_loop.rs:830) to resend, within the queue cap, the hydration commands the store parked during the disconnect (such as a session reopen). A send failure is never silent (send_command from octoscode/src/event_loop.rs:833): the #27 outer review concluded that failures must be reported to the user by method name; otherwise the TUI shows "reconnected" while input goes nowhere.

Before the first frame there is a single one-time wait: drain_initial_startup_events (around octoscode/src/event_loop.rs:786) gives the capabilities handshake a bounded chance on first startup, because first-run onboarding is capability-gated and drawing the first frame before the handshake arrives flashes an empty composer; a regular startup (a local profile already exists, or --profile-id pins one) skips the wait and draws immediately. This detail shows how much the event loop trusts "server authority": it prefers a short wait to faking a known-capability illusion locally.

flowchart LR
    K[键盘与 composer] --> CE[ClientEvent]
    N[服务端 UiNotification] --> AE[AppUiEvent]
    CE --> AC["apply_client_event :8241"]
    AE --> AP["apply_event :9063"]
    AC --> ST[(Store 与 AppState)]
    AP --> ST
    ST --> FU[续发 AppUiCommand]
    ST --> RD[ratatui 渲染]
    FU --> TR[transport.send]

The easiest thing to miss in the reducer is the preservation of local state across replay. The Snapshot branch of apply_event (from octoscode/src/store.rs:9063), before rebuilding state from the new snapshot, explicitly clones and carries a batch of purely local fields: command history is a client-side ring buffer the server never echoes; the sub_providers list (the research lane) is not re-pushed by the server on reconnect, and omitting it would clear it after replay; composer drafts and pending messages likewise. The server is the authority, but what the authority does not own must be remembered by the client itself across replay: the dumb-client boundary mirrored inside the reducer.

One caution: the Client Layers table in octoscode/docs/ARCHITECTURE.md lists a line count per source file (event_loop 7,047 lines, store 37,021 lines), but that table lags the measured reality (8,655 lines, 43,935 lines; see assets/ch19-facts.md). Cite line counts from the facts table and repository measurements; the document table reflects its moment of writing.

19.5 The UI Protocol: A 7,221-Line Wire Contract

The entire contract shared by client and server lives in the main octos repository, crates/octos-core/src/ui_protocol.rs (7,221 lines, first-line doc "Draft client/runtime protocol types for M9"), at a scale of 24 pub enums, 223 pub structs, and 47 pub consts. This section reads it from the client's point of view; the full type-system analysis is in Chapter 2.

The on-wire envelope is standard JSON-RPC 2.0: RpcRequest<T> (crates/octos-core/src/ui_protocol.rs:684), RpcResponse<T> (crates/octos-core/src/ui_protocol.rs:708), RpcNotification<T> (crates/octos-core/src/ui_protocol.rs:730), RpcError (crates/octos-core/src/ui_protocol.rs:752); the event side has a unified envelope EventEnvelope<P> (crates/octos-core/src/ui_protocol.rs:68) carrying session_id, topic, thread_id, a monotonically increasing event_seq, event_type, and the payload; that monotonic sequence is the precondition that makes the replay cursor possible. The protocol identifier is the constant UI_PROTOCOL_V1, value octos-ui/v1alpha1 (crates/octos-core/src/ui_protocol.rs:20).

By direction, UiCommand (crates/octos-core/src/ui_protocol.rs:4197) is the full set of client-to-server methods, variants running from ProfileLocalCreate, SessionOpen, TurnStart, TurnInterrupt, ApprovalRespond through task read/write, permission profile, diff preview, snapshot, thread, and goal-related methods, with serde tagging on kind in snake case; UiNotification (crates/octos-core/src/ui_protocol.rs:6616) is the full set of server-to-client notifications: SessionOpened, TurnStarted, message and reasoning deltas, visualized tasks, voice events, and more; UiRpcResult (crates/octos-core/src/ui_protocol.rs:4760) collects the replies. The octoscode side does not assemble these wire values directly: it holds its own stable value type AppUiCommand (octoscode/src/model.rs:790), whose variant shapes correspond to the wire side (OpenSession, SubmitPrompt, InterruptTurn, RespondApproval, and so on), converted to UiCommand via into_protocol at crates/octos-core/src/app_ui.rs:146 and sent; AppUiCommand::method() (octoscode/src/model.rs:915) gives every command a stable method-name string. This indirection lets the client value type carry local semantics (for instance LocalShellExec, a method that never goes on the wire; the transport intercepts it first in the implementation at octoscode/src/transport.rs:2280), while the on-wire method set is defined entirely by octos-core.

Version and capability negotiation is the protocol's self-preservation mechanism. UiProtocolVersion (crates/octos-core/src/ui_protocol.rs:1553) carries the protocol family, schema version, and jsonrpc version, and is_supported_by_current_runtime validates all three; UiProtocolCapabilities (crates/octos-core/src/ui_protocol.rs:1577) declares supported_methods, supported_notifications, and supported_features in the handshake, and the full_protocol constructor additionally carries a whole string of feature constants (approval typed, pane snapshots, session cwd, sandbox, harness task control, artifacts, hydrate, thread graph, coding autonomy, goal runtime, and more); the comparator compare_protocol (crates/octos-core/src/ui_protocol.rs:1814) outputs the three-state ProtocolCompat (crates/octos-core/src/ui_protocol.rs:1777): different protocol families, or an older server schema, yields SchemaIncompatible (a newer server is allowed, additive forward compatibility); family and version compatible but a required feature missing yields MissingFeatures; only full satisfaction yields Compatible. A comment stresses that the comparator is a pure function, shared unchanged by client and server, so skew verdicts cannot fork into two logics; octos-diagnostics merely wraps the result into report lines.

flowchart TD
    subgraph C[octoscode 进程]
        A[AppUiCommand 稳定值] -->|into_protocol| W[UiCommand wire 值]
        R[capabilities 握手 compare_protocol]
    end
    subgraph S[octos serve 进程]
        N[UiNotification 通知]
        L[(持久事件 ledger)]
    end
    W -->|JSON-RPC 帧 stdio 或 WebSocket| N
    N --> L
    L -->|replay 游标 event_seq| C

Persistence and replay responsibilities are cut along the same boundary; the Durability and Replay section of the architecture document writes them as two checklists. The server must: write to the ledger before emitting the event; replay missed durable events by the client's cursor; never overwrite a fresher live snapshot with a stale disk replay; report lossy delivery honestly via protocol/replay_lossy. The client must: request replay with the latest known cursor when opening a session; tolerate duplicate durable notifications; treat protocol/replay_lossy as a refresh signal, not a chat message; and, after reconnect, never infer runtime truth from local optimistic UI state. These four client disciplines and the reducer's local-state preservation in the previous section are two sides of the same coin.

19.6 The Client Side of goal and peer: autonomy Parsing

Chapter 18 covered the server-side goal/peer machinery; this section looks only at the client half: octoscode/src/autonomy.rs (1,192 lines, first-line doc "M15-E autonomy command parsing for /agents, /goal, and /loop"). It is a pure parsing layer that turns slash commands typed into the composer into structured values: parse_autonomy_slash (octoscode/src/autonomy.rs:248) accepts input with an optional leading slash and dispatches by header into six command families, with all enums defined in the same file: AgentsCommand (:35), TaskCommand (:66), ThreadCommand (:83), TurnCommand (:90), GoalCommand (:97), and LoopCommand (:131, with the cadence parameter LoopCadence at :120), converging into AutonomyCommand (:158); parse failures yield AutonomyParseError (:170).

The parse products ultimately become AppUiCommand values sent to the server; goal advancement, peer dispatch, and collection all execute server-side (Chapter 18). The client additionally owns two presentations: the goal panel showing the objective and budget state, and the Peer Dock showing each peer's liveness and latest output, all fed by the peer family of UiNotification notifications. The selector enums (AgentArtifactSelector :59, TaskArtifactSelector :76) support named references to artifacts, letting /agents and /task commands target exactly one artifact of one peer.

19.7 Being Seen by herdr: The Detection Contract

herdr, the protagonist of Chapter 21, reconstructs agent state from the terminal screen. Its detection contract for octoscode is a 40-line manifest file, herdr/src/detect/manifests/octoscode.toml, with three rules:

  1. approval_blocked (state=blocked, priority=1100, region=whole_recent) at herdr/src/detect/manifests/octoscode.toml:8: keywords include Approval | y once | s session | n deny, Waiting on you, Ctrl+R/Alt+A answer, and the Chinese variant (shenpi, y for this time, s for this session);
  2. statusbar_working (state=working, priority=1000, region=bottom_non_empty_lines(6)) at :21: a regex matching state·Working or containing Esc interrupt;
  3. statusbar_idle (state=idle, priority=900, same region) at :32: a regex matching state Idle or Done, or containing Tab agents | Ctrl+O expand, Ask Octos to change code.

These prompt strings share one source with the pub const HELP at octoscode/src/keymap.rs:1 ("Tab agents | Esc chat | PgUp/PgDn scroll | y/s/n approval ..."). The status-bar copy is written for humans and doubles as the observation interface for the outer-loop machine. The dumb-client architecture has a knock-on effect here: since the client is only a renderer of protocol state, stable on-screen copy faithfully reflects server state, and the outer loop can observe through OCR-style text matching without intruding on any process. The full semantics of the three rules and the general mechanisms of the herdr engine are left to Chapter 21.

19.8 Boundaries and Recap

With Chapter 10: the harness event ABI (HarnessEvent and its schema constants) is an event contract internal to the server runtime; what the client sees are only the notifications projected through UiNotification. The two layers version differently, and this chapter does not repeat that analysis. With Chapter 14: the serve-side stdio mount, stdout ownership, and the data-directory lock are referenced here only from the client side. With Chapter 18: the server-side goal/peer machinery (ledger, keeper, return channels) is entirely in Chapter 18; here there is only client-side parsing and presentation. With Chapters 20 and 21: the OLP protocol and herdr operations each have their own chapter.

Chapter recap:

  1. The boundary precedes everything: octoscode runs no agent, executes no tools, makes no approvals, holds no ledger, manages no provider configuration; all five sit in octos serve, enforced by architectural invariants.
  2. The startup chain has five ordered steps: intercept subcommands, ensure the backend (before raw mode), splash, event_loop::run; DEFAULT_STDIO_COMMAND is octos serve --stdio --solo (octoscode/src/cli.rs:118).
  3. The transport layer is one trait with three methods and two drivers: the stdio subprocess and WebSocket, with exponential reconnect backoff and send failures reported by method name.
  4. The state machine is a two-entry reducer: apply_client_event (octoscode/src/store.rs:8241) and apply_event (:9063) both produce follow-up commands; purely local state is preserved by the client itself across replay.
  5. The 7,221-line protocol contract lives in octos-core: JSON-RPC envelopes, the two full sets UiCommand/UiNotification, three-state ProtocolCompat capability negotiation, and one comparator shared by client and server.
  6. The client side of goal/peer is a pure parsing layer (parse_autonomy_slash); execution authority is never delegated.
  7. The outer-loop observation surface: status-bar copy shares one source with herdr's three detection rules; the dumb client turns the screen into a machine-readable interface.

One more point worth spelling out within the word budget: what this dumb-client architecture means for multi-client collaboration. Every client consumes the same UiNotification universe, so a new server capability only has to extend the octos-core types first and project the notifications, and the TUI, a future web client, and outer-loop observers all benefit at once, with no per-client releases. Conversely, if any execution logic leaks into the client, the first alternative client forces a reimplementation of that logic, and the protocol boundary exists in name only. docs/ARCHITECTURE.md lists "new client-visible capabilities land in octos-core first" as an invariant precisely to guard against that erosion. This is also the thesis of Part IV: the outer loop (Chapters 20 and 21) can observe and drive the inner loop only because all inner-loop state already lives in the protocol and the ledger, not in some client's memory.


The thickness of a dumb client is all in the reducer and the protocol layer: permissions thin to zero, interaction thick to a hundred thousand lines.

Further reading

  • octoscode/docs/ARCHITECTURE.md (724 lines): the original statements of Scope, Runtime Topology, the Flows, and Architectural Invariants; this chapter paraphrases them in several places and verifies each against source
  • assets/ch19-facts.md: the facts source for every line count and line number in this chapter, each with a replayable command
  • crates/octos-core/src/ui_protocol.rs: the full wire contract; for the type-design perspective see Chapter 2
  • Chapter 14 §14.4: the serve-side stdio mount surface and stdout ownership
  • Chapter 18: the full server-side goal/peer machinery

Exercises

  1. ensure_octos_backend returns untouched when it sees a user-managed octos path. If it instead also detected and upgraded such installations, in what scenarios would it break the user's deployment? How does this restraint coexist with "install on first run"?
  2. The Snapshot branch of apply_event must hand-clone command history and sub_providers to survive replay. If a new kind of purely local state were added but forgotten in the carry list, what symptoms would the user see? How would you lock the list down with a test?
  3. compare_protocol allows the server schema to be newer than the client's (additive forward compatibility). If the client depends on a notification that only the new version has while the server is actually older, does the defect surface at the handshake or fail silently at runtime? Can MissingFeatures catch this case?
  4. A stdio-driver reconnect respawns the subprocess; a WebSocket reconnect only reconnects the socket. What differs in their replay semantics? Why is anchoring the data directory with OCTOSCODE_SHARED_INSTANCE necessary in the stdio scenario?
  5. herdr recognizes state from status-bar copy. If a refactor changed state·Working to state: Working, which links would break? How do the three copies (client, herdr manifest, and the keymap help string) stay in sync?

Version note: This chapter is new in v2; the analysis baselines are octoscode main @ 1129fa33 (2026-09-03), octos main @ 9c157101 (2026-09-03), and herdr referenced only at the detection manifest @ fefe5c4f. All line counts and line numbers come from assets/ch19-facts.md and were re-verified by the author against those baselines; the line-count table embedded in octoscode/docs/ARCHITECTURE.md lags the measured values, as noted in the text. octoscode and the UI Protocol are both under active development, so line numbers drift with versions; anchor citations to symbol names.

Chapter 20: OctoLoop: The Outer-Loop Protocol OLP v2

Positioning: This chapter analyzes every artifact of OLP (OctoLoop), the outer-loop protocol added in v2: 30 files in total, of which 7 are protocol documents (octoscode/docs/OUTER_LOOP_PROTOCOL.md, 403 lines, among others), 2 are workspace scaffolding, 9 are Rust sources (octoscode/src/olp_mcp.rs 406, octoscode/src/outer_duty.rs 476, among others), 3 are contract test files (25 cases), 5 are scripts and skills, and 4 cover the crossing surface into the octos main repo. One thesis carries the chapter: most of this protocol has no runtime implementation. It is a stack of three layers, protocol clauses plus Markdown conventions plus contract tests, and the few parts that do have code (the fifth channel, the reviewer duty lock) are exactly the parts that documentation alone cannot pin down. Prerequisite: Chapter 18 (the server-side mechanisms of goals and peers; this chapter only observes them from the outer loop's vantage point). Who should read it: builders who want an external strong model to supervise, coach, and accept the work of a fleet of cheaper models over the long run.

20.1 The Dual Loop: Spend the Expensive Model Only on Judgment

OctoLoop splits a long-horizon task across two rings of agents plus one human, and the model tiers of the three are deliberately mismatched. The role table at octoscode/docs/OUTER_LOOP_PROTOCOL.md:19: the operator (a human) owns macro directives and final review; the runtime (octos serve + master/peers) owns long-horizon execution on the cheap lane; the outer agent, the subject of this protocol (Claude Code, Codex, or any scriptable agent), owns planning, event-driven monitoring, delivery review, and coaching, on the strong lane. The design motive is written at octoscode/docs/OCTOLOOP_GUIDE.md:248: the inner loop is cheap and can be re-run again and again, so mistakes cost little; the outer loop is expensive and spends its budget on judgment only. Every commit passes two pairs of eyes, and push rights live only in the outer loop's hands. The protocol is indifferent to model brands: swap the outer-loop CLI or replace the whole set of inner lanes, and the protocol stays as it is.

The two rings share no memory; every collaboration goes through auditable, persistent channels. Downlink (outer to runtime), five of them: AGENTS.md standing constraints (injected automatically by the prompt layer at every session boot), task-level guidance on the blackboard, atomic git commits as accomplished facts, the inbox doorbell (read-once-destroyed, carrying only event notices and blackboard pointers), and herdr TUI injection (text lands in the composer at user-message level, equivalent to the operator typing it by hand). Uplink (runtime to outer), six: the serve log event stream, the peers/<slug>/result.md deliverables, the authoritative goal-ledgers/<goal_id> ledger, escalation requests, git log/diff, and the reverse-direction channel of Section 20.4, the fifth channel. The full matrix is at octoscode/docs/OUTER_LOOP_PROTOCOL.md:27 (downlink :29, uplink :39).

flowchart TB
    OP["operator (human)<br/>macro directives / final review / approval"]
    subgraph OUTER["outer agent (strong lane)"]
        PLAN["plan / monitor / review / coach"]
    end
    subgraph INNER["runtime (octos serve + master/peers, cheap lane)"]
        KEEPER["goal keeper"]
        PEERS["peers working in parallel"]
    end
    BB[("&nbsp;.octos/OUTER_LOOP_REVIEW.md&nbsp;")<br/>blackboard: authoritative ledger]
    MCP["~/.octos/outer/mcp/<br/>fifth-channel mailbox"]
    OP -->|"/goal directives"| OUTER
    OP -->|"approval / final review"| OUTER
    OUTER -- "downlink 1 AGENTS.md, 2 blackboard, 3 commit, 4 doorbell, 5 TUI injection" --> INNER
    INNER -- "uplink 1 event stream, 2 result.md, 3 ledger, 4 escalation, 5 ask_outer, 6 git diff" --> OUTER
    OUTER <--> BB
    INNER <--> MCP <.-> OUTER

Observation itself comes in three layers, and this is where the outer loop misjudges most easily. The rule at octoscode/docs/OLP_OUTER_BOOT.md:60: delivery is not consumption is not execution: delivery means the notes file is emptied, consumption means the turn prompt reads it, execution means the deliverable or ACK lands. Watch any single layer and you will misjudge. Two "read but never executed" incidents in the field record settled the doorbell pattern into its final shape: the inbox carries pointers only, and content is always fetched from the blackboard.

This chapter reads the 30 artifacts through those three layers: the clause layer (roles, channels, the R rules; pure documentation), the Markdown convention layer (the blackboard, ACK, loop.md; not one line of Rust), and the contract test layer (three test files, 25 cases; the only mechanical enforcement). A few mechanisms span layers: ACK is clauses plus contract tests, and the duty lock is clauses plus implementation plus contract tests.

20.2 R1–R7: Seven Disciplines and the Lessons Behind Them

The semantic core of the protocol is seven rules, octoscode/docs/OUTER_LOOP_PROTOCOL.md:52-103. Behind each rule sits one real incident, and the protocol document writes the incident and the rule in the same file. That is what most separates it from the usual "spec first, implementation someday" documents.

R1 ACK obligation (:52). Every entry in the blackboard's Active section must be answered by the runtime with an ACK line appended under that entry. No ACK means the entry counts as unread, and the outer loop has the right to return the delivery. Since v1, ACK lines follow fixed grammar, ACK(done|wontdo|blocked): <explanation>, and each of the three states has its own semantics: done records what was done and the evidence (a commit hash or test results); wontdo is an objection backed by evidence, and the disagreement rule limits the outer loop to either accepting a wontdo or escalating it to the operator, never returning the same entry a second time; blocked records the blocking cause and the unblocking condition. Case: in the 2026-08-23 v0 experiment (from :196), all ten review entries on the blackboard closed with ACKs, and in entry 9 the inner loop declined a re-dispatch order with evidence (ACK wontdo); the outer loop reviewed it, accepted, and the inner loop turned out to be right. This rule is pure clauses plus contract tests: the grammar is pinned by olp_ack_lines_match_v1_grammar at octoscode/tests/olp_contract.rs:96, and the exemption boundary is pinned by olp_ack_exemption_is_bounded_whitelist at :120 (the v1 grammar constrains only ACK lines written on or after 2026-08-24; historical lines are not rewritten) together with olp_ack_rejects_unknown_status at :159.

R2 Honest verification claims (:67). Every delivery must declare one of three levels: verified (ran cargo test --all-targets plus clippy plus fmt), partially-verified (list what actually ran), or unverified (state why). Claiming verified when a re-check disagrees is a protocol violation. The cases come from the v0 experiment and the performance campaign that followed (from :212), two kinds of counterexample: first, a peer declared "no toolchain on this machine" from inside its sandbox, when the truth was that the permission tiers 1-4 bwrap sandbox does not mount ~/.cargo or ~/.rustup, so every build command returns command not found; second, all-green tests do not mean correct on a real machine, as the snapshot mechanism passed every unit test yet bought nothing on the legacy big ledger, and the writer timeout re-drive passed the in-memory duplex tests while the real pipe corrupted the byte stream. The field amendment to R2 therefore reads: for anything touching IO or concurrency, outer-loop final review demands re-verification on real OS primitives (real pipes, real files); in-memory stand-ins qualify as smoke tests only.

R3 Escalation tiers (:71). Escalation has three levels: runtime decides alone (retry, change approach), the outer loop adjudicates (technical tradeoffs, approve or reject a plan), the operator adjudicates (permission approvals, scope changes, outward-facing actions). The outer loop must not press an approval in the operator's place; when the operator is absent, an escalation stays parked. Case: entry 10 of the v0 experiment, where the new dependency signal-hook went through an escalation request. The bigger lesson is the adjudication audit surface (from :322): in goal mode the master does not come back to the outer loop for things it believes it has resolved; in the historical sample, goal_03 had a wrong measurement methodology, neither master nor peer noticed, and nothing was reported, and it was the outer loop's document review that caught it. So the outer loop must actively audit the decisions and escalations tables of the ledger.

R4 Workspace coexistence (:74). When multiple writers share one workspace, each stages only the files it changed; git add -A is forbidden; a change becomes an atomic commit as it happens; dirty files of unknown origin are kept and reported, never cleaned up automatically. Case: during the performance campaign the outer loop ran probe experiments in the shared workspace, mixed compile breaks with the inner loop's fixes, and hit a SIGBUS race in diff-preview; from then on the rule settled that outer-loop diagnostics always use a separate git worktree.

R4b Tree ownership and auto-fencing (:77). When multiple goals collide on the same tree, the main working tree belongs to exactly one goal: the auto-fencing predicate (more than one active goal, a peer's target branch disagreeing with the main tree's branch, or an unfenced in-flight peer on the main tree) triggers an automatic worktree; tree ownership, granted to the first goal that lands on a non-default branch, persists into the goal-ledger and survives restarts; a session that does not own the tree is refused a cross-branch checkout on the main tree and told to open a fence. This demotes collision avoidance from "the outer loop watching and steering" to a system default, with the outer loop covering only the edges the predicate misses (handed over via octos #20-20c, as a sub-clause of R4, without a protocol version bump).

R5 Idempotent guidance (:89). Outer-loop opinions carry a date and a unique number and are executable only in the Active section; once ACKed they move into the history section and are never replayed, and duplicate deliveries are deduplicated by their ACK. This answers the known limitation (see :339) that the inbox's read-once-destroyed semantics once swallowed guidance: none of the R rules depends on the inbox.

R6 Version negotiation (:103). The protocol document header declares protocol: olp/v2 (octoscode/docs/OUTER_LOOP_PROTOCOL.md:7), octoscode/AGENTS.md:3 references the same version, and any change to channel semantics requires a version bump. Cross-document consistency is pinned by olp_version_consistent_across_docs at octoscode/tests/olp_contract.rs:215, the only version discipline among the rules that has mechanical verification behind it.

R7 OS-exclusive reviewer duty lock (:91, from olp/v2, #38-r1). When multiple outer loops coexist, reviewer authority is decided by a per-project, session-lifetime OS lock; see Section 20.5. The clause itself states the scope: Linux-only, single-machine flock plus PDEATHSIG plus /proc, not applicable on NFS, and Windows LockFileEx is a separate future item.

Beyond the clauses, the protocol document also fixes the rules for multiple coexisting outer loops: blackboard annotations always carry a signature (an unsigned annotation reads as the legacy-compatible default outer loop); each in-progress entry has exactly one reviewing outer loop, and everyone else can only leave signed comments; when two outer loops disagree they do not return each other's entries on the blackboard but each writes a signed comment and escalates to the operator (from :253). The v1-to-v2 change record is at :12-15; Appendix A fixes the six result.md frontmatter v1 fields (:348); Appendix B fixes the sub_providers lane templates and the dual-loop pairing matrix (:369/:387): analysis and verification run on the cheap lane while implementation and the keeper stay on the main tier, on the reasoning that the former's output is backstopped by outer review while the latter's output goes straight into the mainline and the ledger.

20.3 The Blackboard and ACK: Protocol Core with No Runtime

The blackboard is OLP's most central and most easily misunderstood mechanism. Start with what it is: one Markdown file per repository (<repo>/.octos/OUTER_LOOP_REVIEW.md), with numbered review entries in the Active section and ACKed history in the Historical section. It has no Rust implementation, no database, no server process. The only sanctioned way to append is octoscode/scripts/olp-board-append.sh (24 lines), whose core is three lines: exec 9>"$LOCK" (:20) opens the lock file, flock -x 9 (:21) takes mutual exclusion, and the whole entry is appended in one shot with cat >> "$BOARD" (:22), the entry body fed in from stdin. flock keeps concurrent appends by multiple outer loops from tearing each other; the single-shot append makes an entry atomically visible.

The inner-loop counterpart is the .octos/loop.md maintenance loop contract: read the blackboard's Active section, take the lowest-numbered un-ACKed entry, execute it to completion, commit but never push, and append the ACK(done|wontdo|blocked) line. The copy of this loop contract in this book's own repository is 13 lines (octos-book/.octos/loop.md), and at the moment the book's v2 was started the outer review blackboard stood at 465 lines, 29 numbered entries, and 71 ACK lines (a living document; the numbers grow with each batch, and .octos/OUTER_LOOP_REVIEW.md is the real-time authority). The v2 rewrite of this book was driven exactly by this protocol: the outer loop posted numbered rectification entries per chapter, the inner loop executed them by number and ACKed, and the outer reviewer re-verified and pushed on behalf of the runtime. The blackboard's content does not belong in this chapter; the mechanism makes the point on its own.

The three ACK states form a small state machine: an entry is pending once posted, and after the inner loop executes it the ACK lands it in a terminal done, wontdo, or blocked state; on the wontdo branch the outer loop can only accept or escalate to the operator, and there is no edge for returning the entry again. All of the state machine's enforcement comes from contract tests: octoscode/tests/olp_contract.rs (367 lines, 8 cases) runs grep-style validation against the committed blackboard snapshot. olp_ack_lines_match_v1_grammar (:96) checks that ACK lines follow the v1 grammar, the exemption whitelist (:120) hard-codes the effective-date boundary, and unknown statuses are rejected (:159). In other words, a protocol violation is never intercepted at runtime; it simply turns into a red light the next time the tests run.

stateDiagram-v2
    [*] --> Pending: outer posts (numbered + dated)
    Pending --> Done: ACK(done): what was done + evidence
    Pending --> Wontdo: ACK(wontdo): evidence-backed objection
    Pending --> Blocked: ACK(blocked): cause + unblock condition
    Wontdo --> Accepted: outer accepts
    Wontdo --> Operator: escalate to operator
    Done --> Historical: moves to history after ACK, never replayed
    Accepted --> Historical
    Operator --> Historical
    Blocked --> Pending: executable again once the unblock condition is met
    Historical --> [*]

R5's idempotency semantics rely on ACK lines as the dedup key: when the same number is delivered again, an existing ACK makes the runtime skip it. This explains why the ACK must be fixed grammar while the explanation only needs to be non-empty free text: the machine greps the status word and the number, and never parses natural language.

The value of this convention shows up in incidents. The protocol's known-limitations section (octoscode/docs/OUTER_LOOP_PROTOCOL.md:339) records that the inbox's read-once-destroyed notes measurably swallowed guidance, which is why the R rules never depend on it; logs rotate by process start date rather than natural day, so a tail has to follow two days' files at once; and the session hash uses DefaultHasher, which is not stable across Rust versions, so the outer loop must not use it for durable addressing. All three limitations point to the same design conclusion: a channel that can silently drop things cannot carry protocol obligations. Obligations live only on the three carriers that survive a restart, the blackboard, git, and the ledger.

20.4 The Fifth Channel: The Inner Loop Calls Outward, Inside a Turn

The first four uplink channels (event stream, result.md, ledger, escalation) and the sixth, the code channel, all follow a pull model: the inner loop leaves a trace and the outer loop reads along the events. The fifth channel runs the other way; the inner loop pushes. It is one of the few OLP mechanisms with a complete Rust implementation: octoscode/src/olp_mcp.rs (406 lines, standard library only; the Python prototype from #31 onward is archived under octoscode/scripts/reference/) exposes exactly two MCP tools (tools_schema at :328): ask_outer(question, context, tried) (:174) and report_blocked (:255).

Three anti-abuse parameters are hard-coded constants. ASK_TIMEOUT_SECS = 90.0 (octoscode/src/olp_mcp.rs:25): the question is synchronous within the turn, and on timeout the tool returns DEGRADED_GUIDANCE (:30), degraded guidance instead of a frozen turn, polling at ASK_POLL_INTERVAL_SECS = 0.5 (:26). ASK_QUOTA_PER_SLICE = 3 (:27): at most three questions per slice, and beyond that QUOTA_REFUSAL (:31) comes back, a guard against outsourcing the thinking. tried is mandatory: an empty tried is refused on the spot (:184-187 returns TRIED_REFUSAL, :32); the model must first write down what it tried before it earns the right to ask. Transport runs through the mailbox directory ~/.octos/outer/mcp/ (outer_root at :36, overridable via OLP_MCP_OUTER_ROOT) with a three-stage flow through questions, answers, and consumed; the answer is archived to consumed once taken, the whole exchange is audited into OUTER_LOOP_MCP.md (BOARD_RELATIVE at :28), and the signature is fixed at MCP(ask_outer) (SIGNATURE at :24).

sequenceDiagram
    participant I as inner-loop turn (model)
    participant S as olp-mcp-serve<br/>(octoscode/src/olp_mcp.rs:46 serve)
    participant Q as ~/.octos/outer/mcp/
    participant O as outer loop (strong lane)
    I->>S: ask_outer(question, context, tried)
    S->>S: tried empty? refuse (:184-187)
    S->>S: already asked 3+ this slice? refuse (:189-196)
    S->>Q: write question (flock)
    O->>Q: poll, finds question, writes answers/
    S->>Q: 0.5s polling (:26), archives answer to consumed/
    S-->>I: answer (within 90s, :25)
    S-->>I: timeout → degraded guidance (:30)
    S->>Q: OUTER_LOOP_MCP.md audited, signed MCP(ask_outer) (:24)

Mounting goes through the inner profile (~/.octos/profiles/<id>.json) at config.mcp_servers: command points at the octoscode binary and args is ["olp-mcp-serve"]. The protocol's integration checklist (octoscode/docs/OUTER_LOOP_PROTOCOL.md:131-137) records three pitfalls found in practice: the config lives in the profiles JSON, not in the instances config.toml (nothing loads the latter); profile JSON timestamps must be RFC3339 with a Z, and without a timezone every parse fails; and the tool registry is snapshotted when a session is established, so after changing config or binary you must open a new session to see new tools. The CLI wiring sits at octoscode/src/cmd/olp_mcp.rs:6 (the OLP_MCP_TIMEOUT_SECS environment variable overrides the default timeout, :8-10), with the subcommand registered at octoscode/src/cmd/mod.rs:28. The behavior contract is pinned by octoscode/tests/olp_mcp_contract.rs (290 lines, 7 cases, real subprocess stdio): handshake (:98), exactly two tools (:115), round trip (:144), timeout degradation (:209), quota refusal (:227), tried mandatory (:246), and report_blocked only landing on the board (:266).

20.5 The Reviewer Duty Lock: Linux-Only Honest Shrink

The biggest risk with multiple coexisting outer loops is two-headed command: a single outer loop's injections already land one turn late, so two of them will inevitably fight. olp/v2's answer is the R7 reviewer duty lock, implemented in octoscode/src/outer_duty.rs (476 lines). The first statement in the module is a compile-time one, #![cfg(target_os = "linux")] (:23): the whole module does not compile on macOS, and the CLI on non-Linux platforms exits with an explicit unsupported error. The code comment calls this honest shrink. Better to be honestly unavailable than to pretend the lock exists on macOS.

The lock's design density rewards a symbol-by-symbol read. DutyState (:34) is a three-state enum, Vacant/Held/Error; as_str (:43) emits the single-line machine-readable VACANT/HELD/ERROR, and the contract is explicit that Error never masquerades as VACANT. On bad input it would rather report an error than let the caller believe the duty is open. The lock file path is ~/.octos/outer/duty/<sha256>.lock (lock_path at :63; a missing HOME fails closed), the digest is SHA-256 via lock_digest (:83), and the domain prefix is LOCK_DOMAIN = "octoscode/outer-duty/v1" (:55); the comment rules out DefaultHasher explicitly because it is unstable across Rust versions (the same root cause as the known limitation at octoscode/docs/OUTER_LOOP_PROTOCOL.md:343-345). DutyHold (:99) makes the fd the lock: a single holder, CLOEXEC stays set, no fd leaks. acquire (:162) flocks the file and tightens its permissions; check (:220) only observes and never seizes. The metadata sidecar (write_metadata/read_metadata at :259/:311) and every TTL serve diagnostics only and never adjudicate ownership, which prevents the split verdict of "the lock is still held but the sidecar says it expired".

Death coupling is the soul of this lock: spawn_holder_child (:345) binds agent to wrapper with setpgid plus PR_SET_PDEATHSIG(SIGKILL) and handles the race between fork and prctl (:345-380). The wrapper is the sole holder of the lock fd; if the wrapper dies, the agent must die with it and the lock goes VACANT. There is no split-brain where the agent lives while the lock reads idle; conversely, if the agent exits but a grandchild process lingers, the lock still goes VACANT, because the grandchild holds no fd. Live-lock takeover belongs to the operator alone: kill the old holder, then acquire again; no agent can grab the lock by itself.

flowchart LR
    A["octoscode outer-duty hold<br/>--project P --signature S --<br/>&lt;agent&gt;(octoscode/src/cmd/outer_duty.rs:45)"] --> B["acquire(:162)<br/>flock + CLOEXEC fd"]
    B --> C["wrapper (sole fd holder)"]
    C -->|"setpgid + PDEATHSIG(SIGKILL)<br/>spawn_holder_child(:345)"| D["agent child process"]
    B --> E["metadata sidecar(:259)<br/>diagnostics only, never adjudicates"]
    F["octoscode outer-duty check<br/>(:220 observe only, never seize)"] -.->|"stdout exactly one state<br/>VACANT/HELD/ERROR(:34)"| C
    C -->|"wrapper dies ⇒ agent must die"| G["lock VACANT"]
    D -->|"agent dies, lingering grandchild holds no fd"| G

Ten contract tests (octoscode/tests/outer_duty_contract.rs, 745 lines) pin this invariant set down: of two contenders exactly one wins (:174), wrapper death kills the agent and releases the lock (:288), a lingering grandchild still leaves VACANT (:371), check never disturbs the holder (:446), corrupted metadata does not affect ownership (:475), permission tightening (:526), bad input is never VACANT (:579), stdout stays a single line even under hostile metadata (:605), the digest golden value converges (:650), and a directory-creation failure is an Error (:709). Wiring consistency across the three surfaces (protocol, boot doc, skill) is guarded by the two cases at octoscode/tests/olp_contract.rs:303 and :329.

The platform boundary is not hidden: the matrix at octoscode/docs/OCTOLOOP_GUIDE.md:221 states full power on Linux (:227) and two gaps on macOS (:229), one of which is outer-duty being unavailable, so multi-outer-loop collaboration falls back to the duty-book discipline layer plus operator adjudication; the duty book on any platform is only an advisory directory and constitutes no ownership. A macOS process-reaper plan is already scoped, with the requirement file at knowledge/requirements/req-olp-duty-macos.md in the octoscode repo. In the current slice, fencing stops at the documentation-discipline layer; the hard gate that validates the lease on the write path is a later item.

Once you fall back to the duty book, the operating procedure changes with it. On Linux, running outer-duty check before going on duty gives you a machine-adjudicated VACANT or HELD; on macOS that action disappears, and the substitutes are three weak signals: signatures on recent blackboard entries, the process and idle state of the herdr pane, and the registration time in the duty book. All three can be stale, and octoscode/docs/OCTOLOOP_GUIDE.md:233 closes the door: the duty book on any platform is only an advisory directory and constitutes no ownership. Multi-outer-loop collaboration on macOS therefore actually rests on two disciplines: every in-progress entry has a single reviewing outer loop and everyone else only signs comments, and shift handover must be explicitly confirmed by the operator, with the outgoing reviewer writing their exit and successor on the blackboard before the incoming one takes over. With the lock gone, adjudication authority moves up from the OS layer to the operator layer, and that is the full meaning of R7's platform matrix.

20.6 Where It Lands in octos: Budgets and Four Observation CLIs

Most of the protocol text lives in the octoscode repo, but what the outer loop actually observes and drives lives in the octos main repo. The crossing surface is four CLIs plus one budget touchpoint. The header comment of crates/octos-cli/src/commands/steer.rs:1 identifies itself: octos steer — external reviewer steer channel (OLP P2, slice 1). STEER_MAX_BYTES (:22) caps the payload at 64KB, and over the cap the enqueue is refused; delivery goes through the .reviewer-notes sidecar at user-message level, not as a system instruction. The header of crates/octos-cli/src/commands/ledger.rs:1 likewise self-identifies: octos ledger tail — read-only goal-ledger tail (OLP L1, slice 4), which the outer loop uses to audit the master's decisions and escalations tables (the R3 adjudication audit surface). list_peers in crates/octos-cli/src/commands/peer.rs (:54) and GoalStatusArgs in crates/octos-cli/src/commands/goal.rs (:340) complete the L1 read-only observation trio.

Goal budgets are a combination of convention and implementation: the outer loop sets per-entry budgets by tier in the task brief (revisions 5-10M, slices 10-20M, campaigns 30-50M tokens, octoscode/docs/OLP_OUTER_BOOT.md:44), and the octos side lands in crates/octos-cli/src/autonomy/goal_loop_runtime.rs: GoalRuntimeState (:265) is a four-state enum (Active/Paused/Completed/Failed), and budget_limited is not in the runtime enum. It is a string status on the SQLite ledger side, written by the budget rules of cas_goal_status; when the budget runs out, the runtime goes through GoalBudgetResolution (:298) into GoalWrapUp to close out (consistent with the ledger-versus-runtime two-layer state machine boundary drawn in Chapter 18) (crates/octos-cli/src/autonomy/master_continuation_scheduler.rs:147). The internals of these mechanisms belong to Chapter 18; this chapter keeps only one outer-loop consequence: budget exhaustion is not an incident. It is a named, recoverable state, and when the outer loop comes back online it settles accounts against the ledger.

The protocol also fixes the choice of driving mechanism (octoscode/docs/OUTER_LOOP_PROTOCOL.md:289 onward): when the outer loop is online and watching an interactive push, it drives the master directly, injecting user messages through herdr, one turn per slice after slicing, which saves two hops compared with handing off to a peer and gathering; when the outer loop is offline on a long-horizon task, /goal carries it, with the keeper advancing across turns and escalation falling back on the durable goal ledger. Both shapes share the blackboard and ACK contract layer, and the choice depends only on whether the outer loop is online.

Engineering decision: why the blackboard is Markdown and not a database

The blackboard's requirement list: multiple writers appending concurrently without tearing, entries that are numbered and deduplicatable, an auditable history, git-versionability, and read/write access for any agent with zero dependencies to install. A Markdown file plus a flock append script satisfies all five, and Chapter 18's GoalLedger (crates/octos-fleet/src/sqlite_ledger.rs:13, 6,360 lines) has already shown what a structured ledger costs: 39 public methods, WAL for multi-process concurrency, and a state machine embedded in SQL. The blackboard's consumer is one strong outer model; it reads natural language and needs no query plan. The only mechanical properties needed are append atomicity and grep-verifiability; the first is solved by a 24-line shell script (octoscode/scripts/olp-board-append.sh:22-24), the second by the snapshot grep at octoscode/tests/olp_contract.rs:96. Turning the blackboard into a database would mean giving a file with a few dozen writes a day and exactly one model reader a storage layer that needs migrations, needs backups, and whose diffs git cannot see. The protocol document leaves this tradeoff implicit in the design: structured facts (goal state, findings, escalations) go into the ledger, narrative judgments (review opinions, objections, verdicts) stay on the blackboard, and each class of data keeps its own store.

20.7 Boundaries and Recap

Boundary with Chapter 18: the server-side mechanisms of goals and peers (GoalLedger, the keeper, continuation scheduling, the peer lifecycle) are Chapter 18's material; this chapter only takes their observation surfaces (ledger tail, peer list, goal status) and the budget touchpoint from the outer loop's vantage point, and the peer_handoff and worktree mechanisms that R4b's auto-fencing depends on were covered in Chapter 18, so only the protocol-layer semantics are discussed here. Boundary with Chapter 21: herdr's installation, cockpit configuration, and the operational details of the injection channel belong to the next chapter; herdr appears here only as one of the downlink channels. Boundary with Chapter 19: octoscode's UI Protocol and terminal-client architecture were covered in Chapter 19; this chapter takes from octoscode only its three OLP carriers (olp_mcp, outer_duty, the protocol documents).

Chapter recap:

  1. OLP v2 is a three-layer stack: protocol clauses (roles, channels, R1-R7) are pure documentation; the blackboard, ACK, and loop.md are Markdown conventions with no Rust implementation; the only mechanical enforcement is three contract test files with 25 cases doing grep over snapshots and real-subprocess verification.
  2. The only sanctioned blackboard append is the three flock lines at octoscode/scripts/olp-board-append.sh:22-24; the ACK grammar has three states, done/wontdo/blocked, and a wontdo can only be accepted or escalated, never returned again.
  3. The fifth channel is the inner loop's only outward call: octoscode/src/olp_mcp.rs exposes exactly two tools, with a 90-second timeout that degrades (:25), a three-per-slice quota (:27), and tried mandatory (:184-187).
  4. The reviewer duty lock shrinks honestly: the whole module at octoscode/src/outer_duty.rs:23 is Linux-only, the fd is the lock, PDEATHSIG death coupling eliminates the split-brain of a live agent with an idle lock, check only observes and never seizes, and live-lock takeover belongs to the operator; macOS falls back to the duty-book discipline layer.
  5. The expensive model spends itself on judgment: every channel of the dual loop is files, git, and CLIs, and the protocol is indifferent to model brands. Change the vendor and the protocol stays.

Further reading

  • octoscode/docs/OUTER_LOOP_PROTOCOL.md: the single authoritative protocol text, with the R1-R7 clauses, appendices A/B, and every lesson from the v0 experiment and both campaigns
  • octoscode/docs/OLP_OUTER_BOOT.md: the outer loop's onboarding card, with the hard restart checklist, the three observation layers, safety red lines, and inner-loop selection
  • octoscode/docs/OCTOLOOP_GUIDE.md: a guide and a mechanism manual in one, covering the platform support matrix and the goal state machine
  • octoscode/tests/outer_duty_contract.rs: the ten invariants of lock semantics; reading it is faster than reading the docs for understanding the design intent

Exercises

  1. The ACK grammar greps the status word and never parses the explanation. If the inner loop writes "executed but the tests did not run" in the explanation yet tags done, can the current contract tests catch it? To get R2's verification level into the ACK line, how would the grammar and the exemption boundary have to change without breaking historical entries?
  2. Is the "slice" in ASK_QUOTA_PER_SLICE = 3 a turn or a slice from the task brief? If the count is per turn, how many times can the inner loop ask at most across a long task that spans many turns? What form of abuse does this quota guard against, and why is a 90-second timeout with degradation safer than waiting forever?
  3. lock_digest dropped DefaultHasher for SHA-256 because it is unstable across Rust versions. Suppose every lock file mismatches after a Rust upgrade: what does the scene look like, the old holder still alive while the new check computes a different path? How would you use the approach of duty_lock_digest_golden_and_convergence to prevent this class of accident?
  4. What extra machinery would replacing the blackboard with SQLite need to preserve its five current properties (concurrent append, numeric dedup, auditable history, git versioning, dependency-free read/write)? Estimate the engineering effort item by item, then judge whether it is worth it.
  5. There is no outer-duty lock on macOS, and multiple outer loops coexist through the duty-book discipline layer. Design a flock-equivalent scheme that changes no Rust code (a shell script is enough), and explain why it cannot reach the death-coupling guarantee of PDEATHSIG.

Version note: This chapter is based on octos main @ 9c157101, octoscode main @ 1129fa33, and herdr feat/octoscode-agent @ fefe5c4f (baselines taken 2026-09-03; every line number and constant re-verified against assets/ch20-facts.md and its generation commands). OLP v2 took effect on 2026-08-30 (#38-r1 added R7); the v1 ACK grammar and the six frontmatter v1 fields have been in effect since 2026-08-24. Protocol evolution is governed authoritatively by the version header at octoscode/docs/OUTER_LOOP_PROTOCOL.md:7 and the reference at octoscode/AGENTS.md:3, with cross-document consistency guarded by octoscode/tests/olp_contract.rs:215; the hard gate (lease validation on the write path) and the macOS reaper (knowledge/requirements/req-olp-duty-macos.md) are in-flight items, and Section 20.5 will need an update once they land.

Chapter 21: herdr and Outer-Loop Operations

Positioning: This chapter covers herdr, the outer loop's cockpit: a background terminal-workspace service where the inner loop's panes live, discovered, injected into, and observed by the outer loop through a CLI and a socket API. The detection contract, the three primitives, the onboarding and restart checklists, the dual-sentinel recipe, platform pitfalls, and degraded modes come together here as one executable operations manual. Prerequisites: Chapter 19 (the octoscode client, the source of the text the detector matches) and Chapter 20 (the OLP protocol clauses). Who should read it: engineers building or operating a dual-loop system, writing toolchains that drive terminals with agents, or evaluating the "let an agent operate the terminal" route.

21.1 The Cockpit: Terminals Live Inside a Server

The previous two chapters covered both ends of the dual loop: Chapter 19's octoscode is the inner loop's terminal client, and Chapter 20's OLP v2 is the outer loop's behavioral contract. One piece is still missing. The outer loop is itself an agent process, with no eyes and no keyboard; how does it see what is on the inner loop's pane, and how does it type a prompt into the inner loop's input box? The answer is to give the terminal a server, so the terminal stops being an appendage of a process and becomes a resident of a service.

herdr's README defines itself as the runtime your coding agents live on (herdr/README.md:29). Unpacked, that definition is four promises (herdr/README.md:31 through herdr/README.md:34):

  1. always running: herdr is a background server, and terminals live inside it. Close the laptop, drop the network, reboot the machine; the agent keeps working, the session survives, and you reattach from any terminal or over ssh.
  2. never hunt for the stuck one: every pane is marked working / blocked / idle; when an agent stops and waits for an answer, herdr flags it instead of making you hunt pane by pane.
  3. agent-native: agents drive herdr through the CLI and the socket API, opening panes, prompting each other, waiting until another agent is genuinely blocked.
  4. runs what you already run: herdr neither wraps nor replaces claude code, codex, cursor, opencode, grok, or any other tool; it only owns their terminals.

The fourth promise matters most for this book. herdr knows nothing about octos goals, ledgers, or blackboards; it hosts terminals, nothing more. Its entire understanding of an agent reduces to two questions: what is running in this pane, and what state is it in? The answers live in the detect module and a 40-line recognition manifest, the protagonists of the next two sections. Keyboard and mouse are both first-class citizens (herdr/README.md:35), the whole program is one rust binary, no electron (herdr/README.md:37); source builds use cargo build --release, unit tests run with just test, and maintenance checks with just check (the development section starting at herdr/README.md:71).

Set the size on the table first: herdr's src/ holds 245 .rs files and 229,696 lines; the top level has 37 files and 29,927 lines. The largest subdirectory is app (54 files, 65,400 lines, among them herdr/src/app/mod.rs at 6,606 lines, herdr/src/app/actions.rs at 6,155, and herdr/src/app/api.rs at 2,303), followed by server (16 files, 19,166 lines, including the headless mode herdr/src/server/headless.rs), ui (17 files, 12,416 lines), pane (9 files, 10,540 lines), integration (13 files, 9,822 lines), and api (22 files, 8,957 lines). The CLI layer the outer loop talks to is thin by comparison: herdr/src/cli/agent.rs is 949 lines and herdr/src/cli/pane.rs is 2,108. The thinness is deliberate: the CLI does no business logic, only argument parsing and forwarding. Each subcommand function packs its arguments into a schema type, sends it through send_request (herdr/src/cli.rs:762) to the unix socket, and waits for the server to answer.

The topology:

flowchart LR
    subgraph outer["Outer-loop side"]
        OP["Outer-loop agent (Claude Code / Codex)"]
    end
    subgraph herdrbox["herdr (resident server)"]
        CLI["herdr CLI: agent / pane subcommands"]
        SRV["server event loop + detect engine"]
        SOCK["unix socket (HERDR_SOCKET_PATH)"]
    end
    subgraph panes["Panes (PTY)"]
        P1["octoscode inner loop (standard shape)"]
        P2["claude fast-lane inner loop"]
        P3["codex fast-lane inner loop"]
    end
    OP -->|"spawn calls"| CLI
    CLI -->|"Method enum request"| SOCK
    SOCK --- SRV
    SRV -->|"write text + Enter"| P1
    SRV -->|"write text + Enter"| P2
    SRV -->|"write text + Enter"| P3
    P1 -->|"periodic sampling of tail text"| SRV

Socket addressing has a fallback chain: active_api_socket_path (herdr/src/session.rs:173) reads the environment variable HERDR_SOCKET_PATH first (the constant is defined at herdr/src/api/mod.rs:20); if unset, it derives <config_dir>/sessions/<name>/herdr.sock from the session name (api_socket_path_for, herdr/src/session.rs:169); and the config directory respects XDG_CONFIG_HOME (herdr/src/config/io.rs:30). This chain explains how multiple instances coexist: one socket per session, and any outer-loop script that can name the session can find the channel. Thin-client mode has a dedicated herdr-client.sock (client_socket_path_for, herdr/src/session.rs:183); the client module describes itself as connects to the server's client socket (herdr/src/client/mod.rs:1).

Inside the server, the module first lines assemble the event flow: background tasks never touch the UI directly, they hand events over a channel to the main loop (herdr/src/events.rs:1, internal app events delivered via channel). The event enum AppEvent is defined at herdr/src/events.rs:56; the four variants that concern the outer loop are PaneDied (:58), AgentProcessDetected (:60), StateChanged (:66), and HookStateReported (:76). Pane layout is a BSP tree (herdr/src/layout.rs:1, BSP tree layout for tiling panes), and headless mode runs the event loop without a real terminal (herdr/src/server/headless.rs:1). Read these modules together and one event bus sits behind everything: the screen herdr pane read returns, the status agent list reports, and the completion signal of agent wait all ride the same stream; StateChanged fires on the detect engine's verdict, and the wait family (Section 21.3) subscribes to it to decide when a wait is satisfied.

The boundary with the neighboring chapters is drawn here: Chapter 19 covers octoscode itself, the thing being observed; this chapter only consumes its on-screen text. Chapter 20 covers the protocol clauses (R1 through R7, ACK syntax, the blackboard, the outer-reviewer lock); this chapter does not restate them, it covers the operational surface where those clauses are executed through herdr. herdr's plugin system and remote ssh are out of scope.

21.2 The Detection Contract: Inferring State from the Screen

Everything herdr knows about an agent comes from the screen. The detect module's documentation says it plainly (herdr/src/detect/mod.rs:1): the tail text of each pane's active buffer is read periodically and matched against the output patterns of known agents to produce a state. The state machine is the four-state AgentState (herdr/src/detect/mod.rs:13): Idle (:15), Working (:17), Blocked (:18), Unknown (:19). The first three deliver the README's promise; the fourth is reserved for plain shells and unrecognized programs.

The recognized programs are enumerated in Agent, 24 in all (Agent::ALL, starting at herdr/src/detect/mod.rs:71), and octoscode is one of them: Agent::Octoscode (herdr/src/detect/mod.rs:67). Note the version fact that this variant exists only on herdr's feat/octoscode-agent branch (this chapter's baseline fefe5c4f, whose commit title is exactly feat(detect): add octoscode as a supported agent); upstream master has not merged it yet. The agents matched through screen manifests number 22 (SCREEN_MANIFEST_AGENTS, herdr/src/detect/mod.rs:98, with Self::Octoscode at :120); each manifest is an embedded TOML compiled into the binary at herdr/src/detect/manifest.rs:256 as ("octoscode", include_str!("manifests/octoscode.toml")). Labels and executable names each have a mapping: agent_label renders the variant as octoscode (herdr/src/detect/mod.rs:124, :149), interactive_agent_executable returns the launch executable (:153, :184), and parse_agent_label parses labels back, with octoscode and the alias octos-tui both resolving to the same variant (herdr/src/detect/mod.rs:188, :225).

Manifests also solved an engineering problem: recognition rules are data, not code. Supporting a new agent requires no change to the detect engine, only a new TOML file plus one enum variant hung on the list. The rules carry their own version (octoscode's is 2026.08.23.1) and min_engine_version (1), and the manifest update module (herdr/src/detect/manifest_update.rs) can evolve independently of the engine. The side that matters more to this book's readers is that recognition rules live on the opposite end from the thing recognized. If the octoscode team rewords its status bar once, herdr, and any tool doing the same thing, must follow with a rule change; nothing at compile time protects this coupling. The only guard is the single herdr agent list step in the smoke checklist.

The full octoscode detection contract is 40 lines (herdr/src/detect/manifests/octoscode.toml): the first 5 lines are manifest metadata, and the body is three rules:

id = "octoscode"
version = "2026.08.23.1"
min_engine_version = 1
updated_at = "2026-08-23T00:00:00Z"
aliases = ["octos-tui"]

[[rules]]
id = "approval_blocked"
state = "blocked"
priority = 1100
region = "whole_recent"
visible_blocker = true
any = [
  { contains = ["Approval | y once | s session | n deny"] },
  { contains = ["Waiting on you"] },
  { contains = ["Ctrl+R/Alt+A answer"] },
  { contains = ["审批 | y 本次 | s 本会话"] },
]

[[rules]]
id = "statusbar_working"
state = "working"
priority = 1000
region = "bottom_non_empty_lines(6)"
visible_working = true
any = [
  { line_regex = ['state\s*[·,]\s*Working'] },
  { contains = ["Esc interrupt"] },
]

[[rules]]
id = "statusbar_idle"
state = "idle"
priority = 900
region = "bottom_non_empty_lines(6)"
any = [
  { line_regex = ['state\s*[·✓,⚠]*\s*(Idle|Done)'] },
  { contains = ["Tab agents | Ctrl+O expand"] },
  { contains = ["Ask Octos to change code"] },
]

The three rules are worth taking apart field by field. id is the rule's stable identifier; state is what gets written to the pane when the rule hits; priority arbitrates when several rules hit at once, and blocked's 1100 outweighs working's 1000 and idle's 900, which matches intuition: an approval dialog on screen is more urgent than a status bar. region bounds where matching happens: the blocked rule watches whole_recent (the whole recent buffer, because an approval box can appear anywhere), while the two status-bar rules watch only bottom_non_empty_lines(6) (the bottom six non-empty lines, where the status bar lives). The any array is or-semantics: any clause matching makes the rule true. Two of the three booleans are arbitration signals: visible_blocker and visible_working assert that this state is genuinely visible on screen, and they feed the detect engine's source arbitration (the AgentDetection structure, starting at herdr/src/detect/mod.rs:25); screen evidence can override a non-blocked state reported by an integration.

Why can octoscode's detection be this thin? Chapter 19 gave the answer: the dumb-client architecture makes the on-screen text faithfully reflect server state, so the status bar is both a human interface and a machine observation surface. The same Working string reads as "busy" to a human eye and as state=working to herdr's regex. The maintenance duty follows from this: any status-bar rework on the octoscode side must update this manifest in the same change, or the outer loop's eyes go blind at once. The quick-verification manual depends on exactly this: the smoke section requires herdr agent list to show octoscode | <pane> | idle (octoscode/docs/OLP_QUICKSTART.md:151), and that idle is the statusbar_idle rule hitting; if the rule stops matching, the smoke test fails at step one.

21.3 The Outer Loop's Three Primitives: Discover, Inject, Observe

The CLI's dispatch structure is short. The top entry maybe_run (herdr/src/cli.rs:95) routes on the first argument: "agent" at herdr/src/cli.rs:125, "pane" at herdr/src/cli.rs:127. run_agent_command (herdr/src/cli/agent.rs:12) then dispatches 11 subcommands: list, get, read, send-keys, prompt, rename, focus, wait, attach, start, explain (:19 through :29); run_pane_command (herdr/src/cli/pane.rs:12) dispatches list, get, read, split, send-keys, wait-output, run, and others. The outer loop's daily work sits on three to five of these commands, and they reduce to three primitives.

Discovery: herdr agent list, implemented by agent_list (herdr/src/cli/agent.rs:438, usage line :440), sends Method::AgentList (herdr/src/api/schema.rs:107). It returns each pane's agent label, pane number, and state. The outer loop's first act on shift is to run it, turning "which pane is my inner loop" into one line of output.

Injection: herdr agent prompt <target> <text> [--wait] [--until STATUS]... [--timeout MS], implemented by agent_prompt (herdr/src/cli/agent.rs:771, usage line :774). --until and --timeout require --wait (a check at :825 and another at :828); the request enters the server via Method::AgentPrompt (herdr/src/api/schema.rs:127), and the parameter type AgentPromptParams has three fields: target, text, and optional wait options (herdr/src/api/schema/agents.rs:176, fields at :177 through :180).

Observation: herdr pane read <pane_id> [--source visible|recent|recent-unwrapped|detection] [--lines N] ..., implemented by pane_read (herdr/src/cli/pane.rs:455, USAGE constant :473), via Method::PaneRead (herdr/src/api/schema.rs:175). --source detection returns the detect engine's verdict directly, the first place to look when recognition misbehaves.

Beyond the three primitives there are three supporting commands. herdr pane split ... --direction right|down --cwd PATH (pane_split, herdr/src/cli/pane.rs:623, usage :733) opens a new pane; the function head also reads the HERDR_PANE_ID environment variable (:624), letting a program running inside a pane split relative to itself. herdr pane run <pane_id> <command> (pane_run, herdr/src/cli/pane.rs:1047, usage :1049) executes a command in a pane, with an implementation that is almost transparent: it packs the command text plus one Enter key into Method::PaneSendInput and sends it down (:1050 through :1056). herdr agent wait <target> [--until STATUS]... [--timeout MS] (agent_wait, herdr/src/cli/agent.rs:506, usage :508) blocks until the state is reached; the server side is wait_for_agent (herdr/src/api/wait.rs:132), and the same family holds wait_for_output (:22), prompt_agent (:177), and wait_for_event (:661).

The full sequence of one injection, with the server's four gates in focus:

sequenceDiagram
    participant O as Outer-loop agent
    participant C as herdr CLI
    participant S as herdr server
    participant T as Inner-loop terminal (octoscode)

    O->>C: herdr agent prompt <pane> '<text>' --wait --until idle
    C->>S: agent.prompt(AgentPromptParams)
    S->>S: Gate 1 empty text → empty_agent_prompt
    S->>S: Gate 2 blocked → agent_blocked (interactive input required)
    S->>S: Gate 3 unrecognized or startup not ready → agent_not_ready
    S->>S: Gate 4 foreground process name mismatch → agent_not_ready
    alt all four gates pass
        S->>T: write text (encoded per terminal mode)
        S-->>T: Enter sent 300ms later
        T-->>S: status bar changes, detect matches the new state
        S-->>C: AgentPrompted; wait_for_agent satisfied
        C-->>O: success return
    else any gate rejects
        S-->>C: corresponding error code
        C-->>O: non-zero exit
    end

The four gates are what handle_agent_prompt (herdr/src/app/api/agents.rs:62) executes in order: empty text is rejected (:63 through :65, error code empty_agent_prompt); a blocked target pane is rejected (:81 through :89, error code agent_blocked, on the grounds that it wants interactive input, not a new task); an unrecognized agent or an unready managed start returns agent_not_ready (:95 through :98); the fourth gate deserves the most attention. runtime_hosts_agent checks the pane's foreground process name (herdr/src/app/api/agents.rs:105 through :112), and a mismatch reports agent is no longer the pane foreground process. That function lives at herdr/src/app/agents.rs:421; its implementation takes the pane child process's foreground job (foreground_job), recognizes the agent inside it, and compares against the expectation. This fourth gate is the second half of the double gate behind "silent injection loss" in the outer-loop docs: the first half requires the pane to be on the named-agent list (a known agent), the second requires that the foreground process right now is that agent (octoscode/docs/OLP_QUICKSTART.md:162). Miss either one and the injection is dropped, and dropped without a sound.

With all four gates passed, the write happens in two steps: the text is encoded per terminal mode and written, then an Enter follows after a 300 ms delay (the AGENT_PROMPT_SUBMIT_DELAY constant at herdr/src/app/api/agents.rs:13, used at :126). The delay gives the TUI one beat to take the text into its input box; an immediate Enter could race ahead of the render. One Copilot edge case proves what this machinery is made of: after losing focus it ignores synthetic Enter, so before injecting into it herdr sends a focus gained event first and then writes the text (starting at herdr/src/app/api/agents.rs:112). octoscode needs no such step, but the edge case shows that herdr's injection channel carries fine-grained, per-agent adaptations for specific TUI behaviors, with the switches dispatched server-side by agent.

Engineering decision: why injection goes through the TUI's user-message layer instead of giving octoscode an API Chapter 19's conclusion pays off here: octoscode is a dumb client with no server-side API for "receive external text"; its input box is the only public entrance. If herdr built a bespoke API for octos, it would have to understand sessions, cursors, and replay, breaking the runs what you already run promise; going through the TUI input box treats claude, codex, and octoscode alike, and herdr's knowledge of any agent stops at the screen forever. The contrast with the other downstream channel makes this clearer: octos steer also injects outer-loop text as a standalone user message, but it targets sessions and goes through serve's internal channel (octoscode/docs/OLP_OUTER_BOOT.md section 2), suited to interjecting while the inner loop's turn is in progress; herdr prompt targets panes and goes through the screen, suited to waking an idle inner loop. Same user-message layer, different direction and timing; the two complement rather than replace each other. The price must also be stated: this channel depends on the detection contract's text staying stable and must clear the double gate; when either end drifts, injection turns from "success" into "silence".

The legal state values differ between the two layers, a trap when debugging. AgentStatus at the CLI and API layer (herdr/src/api/schema/common.rs:151) has five states: idle, working, blocked, done, unknown (:152 through :156), and the CLI parse function accepts the same five (herdr/src/cli.rs:897, branches at :899 through :903); the detect layer's AgentState has four, with no done. The pane-report-side parse parse_pane_agent_state (herdr/src/cli.rs:910 through :915) also accepts only four. Waiting with --until done for a state the detect layer never produces can only end in a timeout.

21.4 From Primitives to Operations: Onboarding, Restarts, Opening Inner Loops

The three primitives are parts; the OLP documents assemble them into checklists. Start with the opening principle of the outer-loop onboarding card (octoscode/docs/OLP_OUTER_BOOT.md): environment details drift, so never hardcode pane numbers, instance hashes, or session keys; the checklists teach discovery methods, not fixed values.

The onboarding checklist (combining octoscode/docs/OLP_QUICKSTART.md sections 1 and 2 with OLP_OUTER_BOOT.md section 0):

  1. Dependency check: herdr is a "no, recommended" level dependency (octoscode/docs/OLP_QUICKSTART.md:35); without it you can fall back to tmux send-keys, and to get octoscode pane recognition you currently build from the feat/octoscode-agent branch.
  2. Run the olp-init scaffold in the project directory, which generates .octos/loop.md and the blackboard template.
  3. serve is always started by the operator's own hand; sandbox-exempt authorization is a trust decision that is never delegated to an agent.
  4. /loop resume is the outer loop's job: run /loop list first to get the id, then resume with it; a bare resume is rejected.
  5. Mount the dual sentinels (expanded in the next section).
  6. Verify the fallbacks configuration and confirm the new session has been snapshotted: changing configuration without restarting is insurance on paper only.

The post-restart inspection of the inner loop is a four-step hard checklist (octoscode/docs/OLP_OUTER_BOOT.md section 0b, :16 through :32), and "note it down and patch later" is forbidden: step one, serve comes up, by the operator's hand; step two, /loop resume, always done by the outer loop; step three, mount the dual sentinels; step four, verify fallbacks and the new-session snapshot. Behind the checklist stands a real incident: the maintenance heartbeat sat paused for a full day unnoticed, exposed only when the nightly main lane broke supply, the goal circuit-breaker tripped, and the sentinel blind spot all failed at once, an outage of 8 hours. The lesson is written into the checklist itself: while the main mechanism is healthy, a dead fallback layer is completely invisible; a fallback's health can only be established by inspection, never by accident.

Opening an inner loop is agent-agnostic. The inner-loop contract has four clauses (octoscode/.octos/loop.md:5 onward): read the blackboard's Active section, execute the lowest-numbered un-ACKed entry, commit but never push, and finish by writing the ACK (done|wontdo|blocked) formula. Any agent that can read files, run commands, and be driven by herdr can serve as the inner loop. Three shapes to choose from as needed (octoscode/docs/OLP_OUTER_BOOT.md section 6): octoscode plus a cheap model is the standard shape, with the full goal, peer, ledger, steer, and event-stream machinery; Claude Code panes with approval exemption are high quality, suited to hard fast-lane slices; codex panes are isolated from the main reviewer's brand, which helps cross review. The opening action is just herdr pane run:

# Standard shape: octoscode on octos serve
herdr pane run <pane> 'cd <repo> && octoscode --stdio-command "octos serve --stdio --solo --danger-full-access"'
# Fast-lane shape: claude with approval exemption (executed by the operator's own hand)
herdr pane run <pane> 'cd <repo> && claude --dangerously-skip-permissions'

After opening, send the inner loop's onboarding prompt, pointing at loop.md and the blackboard's Active section. From then on the inner loop's maintenance cycle is triggered entirely by herdr-injected prompts: one prompt is one round of "read the board, take a task, execute, write the ACK". The outer loop never polls the inner loop's internal state; it wakes the inner loop only when the outer loop itself needs progress.

The division of labor between waking and course correction (octoscode/docs/OLP_OUTER_BOOT.md section 2, :47 through :58): when the inner loop is idle, wake it with herdr agent prompt, one sentence pointing at the new blackboard entry number; while the inner loop is mid-turn, interject with octos steer instead, which does not interrupt the action and is consumed on the next beat. steer locates the instance by cwd, so it must run inside the project directory, and the session key is decoded from the URL in the filenames under ls <repo>/.octos/octos/sessions/. The criterion for which channel to use is a single lookup: the state reported by herdr agent list.

21.5 The Sentinel Recipe: Three Layers of Observation and the Dual Sentinels

Observation upstream has three layers, and none can be skipped (octoscode/docs/OLP_OUTER_BOOT.md section 3, :60 through :72): layer one is the live screen, herdr pane read <pane>; layer two is the event stream, tail -f .../data/events.jsonl, watching for steer_consumed, escalation, goal_transition, and other events; layer three is the structural surface, octos goal status and octos peer list. The documents' tone comes from scars: delivery is not consumption, and consumption is not execution; watching one layer guarantees a misjudgment. The three layers answer three questions: the screen says what it looks like right now, the event stream says what happened at the protocol level, and the structural surface says whether the goal and peer books balance.

The dual sentinels are step three of the restart hard checklist: a positive sentinel watches for ACKs landing on the board, and a negative sentinel watches events.jsonl for goal_transition blocked and escalation. With only the positive sentinel, the silence of a tripped goal circuit-breaker is indistinguishable from "still working"; the negative sentinel covers exactly that blind spot. The negative sentinel chain over events.jsonl carries one more operational fact: the files are laid out per instance and per profile (paths like ~/.octos/instances/<instance>/profiles/<profile>/data/events.jsonl), the instance name is a hash of the project cwd, and if you do not want it, ls -t ~/.octos/instances/ matches directories by modification time. Nobody restarts a dead sentinel process for you, and the files are not guaranteed to persist forever, so the right shape for the negative sentinel is a "re-acknowledgeable on remount" tail, not a "no-gap-assumed" parser; the outer loop's own liveness belongs on the restart hard checklist too. The dual sentinels' state space:

stateDiagram-v2
    [*] --> mounted
    mounted : dual sentinels mounted (positive + negative)
    mounted --> healthy : positive sees ACK, negative silent
    mounted --> visible_stall : positive silent, negative reports blocked
    mounted --> blind : both sentinels silent
    visible_stall --> healthy : outer loop wakes or course-corrects per section 2
    blind --> mounted : rerun the restart hard checklist, remount sentinels

Of the three states, the most dangerous is both sentinels silent: the inner loop may simply have nothing to do, or the entire observation chain may be broken, and from the outer loop the two look identical. Combining the sentinels with the three observation layers is the only way out: when the sentinels go quiet, read the third layer, the structural surface; octos goal status tells you whether the goal is active or long since blocked, and octos peer list tells you whether dispatched workers still exist. Writing this recipe into step three of the restart hard checklist is the cheapest way to never repeat the 8-hour lesson that a dead fallback layer is invisible.

21.6 Common Pitfalls and Degraded Modes

An operations chapter closes with the pitfalls. The first is the fourth gate from Section 21.3: silent injection loss. The symptom is that herdr agent prompt goes out, the inner loop shows no reaction, and the command may not even report an error. Two causes: the pane is not on the named-agent list, or the foreground process name does not match the expected agent (octoscode/docs/OLP_QUICKSTART.md:162). The typical timing is the inner loop running a shell command at that moment, so the foreground process is transiently bash rather than octoscode, and the injection lands inside that window. The fix has two layers: before retrying, run herdr agent list to confirm the state; when herdr is absent from the environment or the gates keep rejecting, degrade to tmux send-keys, with -- separating text whose first character is -. Degrade with eyes open: send-keys is ungated raw keystrokes. The double gate, state waiting, and --until semantics are all gone; you have stepped down from the cockpit to a remote control.

The second pitfall is platform divergence: OLP's outer-reviewer lock (outer-duty) depends on flock and PDEATHSIG, is Linux-only, does not compile on macOS, and multiple coexisting outer loops fall back to the duty-roster discipline layer (covered in Chapter 20; octoscode/docs/OLP_OUTER_BOOT.md section 3.5). This is not a herdr defect but the platform boundary of the whole toolchain: running the dual loop on a mac, the main-reviewer mutex is a convention, not a lock.

The third pitfall is on the install side: when the first-launch automatic download of the octos server fails, it is usually offline or proxy trouble; install manually with npm i -g @octos-org/octos, and set OCTOSCODE_NO_AUTO_INSTALL=1 to disable auto-install (octoscode/docs/OLP_QUICKSTART.md section 6 fault table; the source is OPT_OUT_ENV at octoscode/src/backend_ensure.rs:60). The same table has one Linux-only entry: a linker SIGBUS or EDQUOT while building a large project is a tmpfs quota problem; point TMPDIR at a home-disk path. The fourth pitfall is the version one: octoscode recognition lives on the fork branch, and a herdr built from upstream master silently fails to recognize --kind octoscode; the pane state stays unknown forever, the smoke step octoscode | <pane> | idle fails, and tracing back from that symptom is fastest. The lesson of this pitfall is the price of silent degradation: an upstream-built herdr still allocates a PTY for the octoscode pane and still echoes the screen; the only thing missing is recognition, with no install warning, no version negotiation, and no alarm flag on the unknown state. An operator who runs herdr agent prompt before herdr agent list gets agent_not_ready as the first feedback and easily misdiagnoses it as the fourth gate's process-match problem, burning triage time on the wrong gate. The avoidance is to copy the dependency-table sentence "build from the feat/octoscode-agent branch" (octoscode/docs/OLP_QUICKSTART.md:35) into the environment-preparation checklist, and to agree that the day it merges into master is the day every machine reinstalls herdr.

When triaging these pitfalls, herdr agent explain (herdr/src/cli/agent.rs:41, usage :91) and pane read --source detection are the two handy tools: the former explains why a pane was judged into its current state, and the latter returns the detect engine's raw verdict, separating "misrecognized" from "the screen really changed". The full CLI entry table prints on demand with herdr agent help; the help table is hardcoded in print_agent_help (herdr/src/cli/agent.rs:922, body :923 through :941). Error messages also lead the way: mistype any subcommand argument and the usage string is echoed verbatim (usage lines match the source word for word; every usage quoted in this chapter comes from sed spot-checks against the facts table), so fix accordingly.

21.7 Boundaries and Recap

With Chapter 19: octoscode's status-bar text is the source of the detection contract, and the client architecture is what makes the screen observable; this chapter only consumes that contract and does not repeat the client's internals. With Chapter 20: the semantics of the blackboard, ACK, R1 through R7, and the outer-reviewer lock all live in that chapter; this chapter covers only the operational surface, meaning which herdr commands put those clauses into effect. With Chapter 18: the server-side mechanisms of goal and peer are not here; observation uses only the two read-only commands octos goal status and octos peer list.

The chapter's thread: herdr is a terminal host, not an agent framework, and its knowledge of agents reduces to the detect engine plus one manifest; the outer loop's three primitives (discover, inject, observe) map to the three CLI subcommands agent list, agent prompt, and pane read, with the server's four gates deciding whether an injection lands; onboarding, restart, the dual sentinels, and the three inner-loop shapes assemble the parts into an executable operations manual; silent loss and platform divergence are the two most expensive tuition payments in this practice. The full picture of the dual loop closes here: the inner loop's every state lives in the protocol and on the screen (Chapter 19), the outer loop's every behavior lives in the clauses (Chapter 20), and the hand that connects them is herdr (this chapter).

Further reading

  • herdr/README.md: the original statements of the positioning promises and the development workflow
  • herdr/src/detect/mod.rs: the detect engine: AgentState, the Agent enum, manifest wiring
  • herdr/src/detect/manifests/octoscode.toml: this chapter's detection contract in full, 40 lines
  • octoscode/docs/OLP_OUTER_BOOT.md: the outer-loop onboarding card: restart hard checklist, three observation layers, opening inner loops
  • octoscode/docs/OLP_QUICKSTART.md: dependency table, smoke verification, fault quick-reference
  • assets/ch21-facts.md: the facts source for every number and line reference in this chapter, each with a replay command

Exercises

  1. If an octoscode revision changed the status-bar text from state·Working to state: Working, which links in this chapter's chain would break, and at what moment? Propose an engineering scheme that keeps the text and the manifest from drifting apart.
  2. Why must the second half of the double gate (foreground process name matching) exist? Sketch an attack or accident without it: could a malicious or buggy shell loop that prints a fake status bar fool a system with only the first gate?
  3. AgentStatus has done and AgentState does not. Find in the herdr source where done comes from (integration reports or screen inference), and argue the design cost of the two layers disagreeing.
  4. What three things does the tmux send-keys fallback lose? If you had to add a minimal liveness check to the fallback channel, which primitive from this chapter would you reuse?
  5. The blind state where both sentinels are silent cannot, from the outer loop alone, be distinguished from "the inner loop is idle". If you could add one low-cost periodic signal on the inner-loop side, which layer (screen, event stream, structural surface) would be cheapest and hardest to forge?

Version note: This chapter is new in v2; the analysis baseline is herdr feat/octoscode-agent @ fefe5c4f (version 0.8.2,2026-08-29) and octos main @ 9c157101 (2026-09-02). All line counts, line numbers, and usage strings come from assets/ch21-facts.md (2026-09-03) and were re-verified by the author against the above baselines; octoscode document references cite relative paths. octoscode pane recognition (Agent::Octoscode and herdr/src/detect/manifests/octoscode.toml) currently lives only on the fork branch; once it merges into upstream master, master becomes authoritative. herdr iterates quickly, and CLI usage and manifest rules may shift between versions; anchor citations to symbol names and rule ids.

Appendix A: The Complete Crate Dependency Graph

Positioning: This appendix is the map page shared by all 21 chapters of the book. It gives the complete dependency picture of the octos workspace: 26 top-level entries, 23 octos-* crates, the full 63-edge internal dependency graph, a per-crate table of layer, line count, and dependency matrix, and an external-dependency inventory with feature-gate annotations. Prerequisite: Chapter 1 (1.3, workspace topology and the three fact corrections). When to come here: any time a chapter names a crate and you want to know where it sits globally, what it depends on, and what depends on it; and before contributing code to octos, to confirm dependency direction.

The data here shares its source and methodology with Chapter 1: the baseline is octos main @ 9c157101, and the single data source is the repository facts table assets/appendixA-facts.md (its six summary numbers cross-check exactly against assets/ch01-facts.md; see A.1). Dependency edges count only the octos-* entries in each crate's [dependencies] section of its Cargo.toml, excluding [dev-dependencies] and [build-dependencies]; line counts follow find crates/<name> -name '*.rs' | xargs wc -l | tail -1. Both methodology sections include full reproduction commands, recorded in assets/appendixA-facts.md; this appendix does not repeat them, only states the conclusions.

A.1 Summary numbers

MetricValue
Total dependency edges (octos-* in [dependencies])63
Top-level entries from ls crates | wc -l26
Of which octos-* crates23
Workspace members in the root Cargo.toml38
Layers (strict longest path, L0–L7)8
Total lines of Rust (26 top-level entries)700,915

Machine-check commands (run at the root of the octos source repository):

awk '/^\[dependencies\]/{f=1;next} /^\[/{f=0} f && /^octos-/' crates/*/Cargo.toml | wc -l   # 63
ls crates | wc -l                              # 26
find crates -name '*.rs' | xargs wc -l | tail -1   # 700915 total

All six numbers match assets/ch01-facts.md sections 1/3/4/5 item by item; this appendix is the full expansion built on top of them.

A.2 The internal dependency graph: 63 edges

graph BT
  subgraph L0["L0 Foundation"]
    core[octos-core]
    plugin[octos-plugin]
    sandbox[octos-sandbox<br/>platform helper binary]
  end
  subgraph L1["L1 Primitives"]
    bus[octos-bus]
    llm[octos-llm]
    memory[octos-memory]
    diag[octos-diagnostics]
    store[octos-store]
    fleet[octos-fleet]
    wasm[octos-wasm]
  end
  subgraph L2["L2 Runtime"]
    agent[octos-agent]
    services[octos-services]
    embed[octos-embed-llama]
  end
  subgraph L3["L3 Orchestration"]
    swarm[octos-swarm]
    dora[octos-dora-mcp]
    fworker[octos-fleet-worker]
    pipeline[octos-pipeline]
  end
  subgraph L4["L4 Workflows"]
    workflows[octos-workflows]
  end
  subgraph L5["L5 Integration"]
    server[octos-server]
    cli[octos-cli]
  end
  subgraph L67["L6/L7 Embedding and bindings"]
    ffi[octos-ffi]
    uniffi[octos-uniffi]
    pyo3[octos-pyo3]
  end
  subgraph CAP["Capability layer / frontend (isolated, unlayered)"]
    appskills[app-skills<br/>14 capability binaries]
    platskills[platform-skills/voice<br/>capability binary]
    web[octos-web<br/>TypeScript frontend<br/>not in the dependency graph]
  end

  bus --> core
  llm --> core
  memory --> core
  diag --> core
  store --> core
  fleet --> core
  wasm --> core
  agent --> core
  agent --> bus
  agent --> memory
  agent --> llm
  agent --> plugin
  services --> core
  services --> llm
  services --> bus
  embed --> llm
  swarm --> agent
  dora --> agent
  fworker --> agent
  fworker --> core
  fworker --> fleet
  fworker --> llm
  fworker --> memory
  pipeline --> core
  pipeline --> agent
  pipeline --> plugin
  pipeline --> llm
  pipeline --> memory
  workflows --> core
  workflows --> agent
  workflows --> pipeline
  server --> core
  server --> agent
  server --> llm
  server --> bus
  server --> store
  server --> services
  server --> workflows
  server --> pipeline
  server --> plugin
  cli --> core
  cli --> bus
  cli --> llm
  cli --> memory
  cli --> agent
  cli --> diag
  cli --> store
  cli --> services
  cli --> workflows
  cli --> pipeline
  cli --> swarm
  cli --> plugin
  cli --> fleet
  cli --> fworker
  cli --> embed
  ffi --> core
  ffi --> agent
  ffi --> llm
  ffi --> memory
  ffi --> cli
  ffi --> embed
  uniffi --> ffi
  pyo3 --> ffi

The graph is isomorphic to the one in 1.3.4 of Chapter 1, and its 63 edges match the edge list in section 3 of assets/appendixA-facts.md one for one, no more, no fewer. An edge A --> B means A depends on B; read graph BT bottom-up, so crates closer to the top sit closer to the user. Edges per crate: octos-cli 15, octos-server 9, octos-ffi 6, octos-agent 5, octos-pipeline 5, octos-fleet-worker 5, octos-services 3, octos-workflows 3, and 1 each for the rest. The short names are mermaid node aliases; real package names all start with octos- (for example diag is octos-diagnostics).

Four reading notes. First, octos-core is depended on by 15 crates; it is the unique root and itself has zero internal dependencies (Chapter 2). octos-agent is depended on by 8 crates and is the second hub (Chapters 5 through 10). Second, every dependency points downward and the graph is acyclic; the layering is an invariant that cargo enforces at compile time, not a documentation convention. Third, the four isolated nodes, octos-sandbox, app-skills, platform-skills/voice, and octos-web, are outside the 63 edges: capability binaries and the frontend attach to the platform across process boundaries, not through Cargo dependencies. Fourth, two points the spec goes out of its way to clarify: app-skills and platform-skills are workspace members (counted in the 38 as directory members) but they are collections of capability binaries, not nodes expanded into the core crate graph; and the recent goal/peer/agent orchestration modules live in the tool layers under crates/octos-cli/src/autonomy/ and crates/octos-agent/src/, so a crate node named octos-autonomy does not exist and must not be drawn (Chapter 18).

A.3 Per-crate data table

"Layer" is the strict longest-path layer: 1 + max(layer of its octos-* dependencies), with zero internal dependencies meaning L0. "External deps" counts the non-octos-* entries in the [dependencies] section, feature-gated entries included; entries written as name.workspace = true are normalized and counted by package name.

crateLayerRust linesoctos-* dependencies ([dependencies])External deps
octos-coreL022,313(zero internal dependencies)7
octos-pluginL05,165(zero internal dependencies)7
octos-sandboxL01,468(zero internal dependencies)2
octos-busL142,767octos-core31
octos-llmL135,087octos-core14
octos-memoryL16,428octos-core11
octos-diagnosticsL12,243octos-core4
octos-storeL12,664octos-core12
octos-fleetL116,888octos-core8
octos-wasmL1883octos-core5
octos-agentL2191,985octos-core, octos-bus, octos-memory, octos-llm, octos-plugin47
octos-servicesL23,223octos-core, octos-llm, octos-bus11
octos-embed-llamaL2911octos-llm5
octos-pipelineL332,799octos-core, octos-agent, octos-plugin, octos-llm, octos-memory10
octos-swarmL34,980octos-agent11
octos-dora-mcpL311octos-agent0
octos-fleet-workerL36,842octos-agent, octos-core, octos-fleet, octos-llm, octos-memory5
octos-workflowsL41,059octos-core, octos-agent, octos-pipeline6
octos-serverL521octos-core, octos-agent, octos-llm, octos-bus, octos-store, octos-services, octos-workflows, octos-pipeline, octos-plugin22
octos-cliL5307,299octos-core, octos-bus, octos-llm, octos-memory, octos-agent, octos-diagnostics, octos-store, octos-services, octos-workflows, octos-pipeline, octos-swarm, octos-plugin, octos-fleet, octos-fleet-worker, octos-embed-llama55
octos-ffiL61,372octos-core, octos-agent, octos-llm, octos-memory, octos-cli, octos-embed-llama4
octos-uniffiL7465octos-ffi1
octos-pyo3L7756octos-ffi1

The three non-octos-* top-level entries are not in the table above; the conclusions are stated in prose instead (details in sections 1.3/3.2 of assets/ch01-facts.md): crates/app-skills is a directory of 14 capability binaries totaling 12,098 lines, with no top-level Cargo.toml; crates/platform-skills is a single skill binary, voice, at 1,188 lines; crates/octos-web is the TypeScript frontend, with 0 .rs files, and not a workspace member either. All three have 0 octos-* entries in [dependencies]. One example shows how to reproduce the per-crate line counts; the rest follow the same form: find crates/octos-core -name '*.rs' | xargs wc -l | tail -1 → 22313.

A.4 A guided tour of layers L0–L7

Layers are not a subjective classification by module size or importance; they are mechanically derived from the 63 edges as strict longest paths: a crate's layer equals the length of its longest dependency chain down to L0. This section tours the layers one by one, flagging the chapters that expand each.

L0 Foundation: octos-core, octos-plugin, octos-sandbox

Three crates with zero internal dependencies, the roots of the whole dependency tree. octos-core defines the platform's domain language in the type system: the unified data contracts for sessions, messages, memory, and configuration (Chapter 2). It is depended on by 15 crates, so any interface change ripples through the entire repository, and its stability discipline is the strictest. octos-plugin defines the plugin contract and executable discovery (Chapter 9) and also keeps zero internal dependencies, so the extension mechanism can evolve independently of the core. octos-sandbox is a standalone Windows AppContainer helper binary that no crate depends on; it is a platform helper tool, not the sandbox subsystem, and the real sandbox implementation lives inside octos-agent (Chapter 7). This is one common misreading the v2 rewrite explicitly corrects.

L1 Primitives: octos-bus, octos-llm, octos-memory, octos-diagnostics, octos-store, octos-fleet, octos-wasm

Seven domain primitives that depend only on L0, each wrapping one slice of the outside world: octos-bus is the multi-channel messaging abstraction built from 17 channel source files (Chapter 11) and the L1 crate with the most external dependencies in the repository (31 entries, including 11 gated channel integrations); octos-llm tames the chaos of LLM providers, unifying completion, streaming, and credential management (Chapter 3); octos-memory implements working and long-term memory with hybrid search (Chapter 4); octos-store provides session persistence (Chapter 15); octos-diagnostics handles diagnostics reporting (Chapter 15); octos-fleet is the persistence and plan-data layer of the Fleet kernel (Chapter 16); octos-wasm provides wasm bindings for the browser. What this layer shares: no crate here depends on another; all seven sit side by side, and changing one never ripples into the other six.

L2 Runtime: octos-agent, octos-services, octos-embed-llama

The first vertical aggregation point. octos-agent is the largest crate in the repository (191,985 lines), aggregating the agent loop, 59 tool source files, the sandbox, context management, and the harness modules (the whole subject of Chapters 5 through 10); its 5 internal dependencies pull in core/bus/memory/llm/plugin. octos-services depends on core/llm/bus and provides production server-side capabilities (Chapter 15). octos-embed-llama depends only on octos-llm, wiring local llama.cpp embedded inference behind the unified LLM trait, and is not compiled by default (gated). The boundary matters: above L1, code that combines multiple primitives appears for the first time, but it still has no awareness of any concrete product shape.

L3 Orchestration: octos-pipeline, octos-swarm, octos-dora-mcp, octos-fleet-worker

All four crates depend directly on octos-agent and compose single agents into larger execution structures. octos-pipeline is the DOT-driven pipeline engine with 12 IR node kinds (Chapter 13); octos-swarm implements contract fan-out and aggregation gates (Chapter 17); octos-fleet-worker is the worker side of the Fleet plan-execution kernel, with all 5 internal dependencies written as workspace inheritance (Chapter 16); octos-dora-mcp is the Dora/MCP tool bridge, at 11 lines of Rust with zero external dependencies, the smallest crate in the repository. Orchestration-layer code never faces the user directly; it is the raw material for L4/L5.

L4 Workflows: octos-workflows

A single-node layer depending on core/agent/pipeline, wrapping pipeline execution into a reusable workflow unit. It exists so that octos-server and octos-cli can consume pipeline capability the same way instead of each orchestrating its own handlers. This is a classic "add a layer to buy decoupling" decision: the layer costs one more hop, and saves each integrator a duplicate.

L5 Integration: octos-server, octos-cli

The two entry points where users and the outside world touch the system. octos-cli is the second-largest crate in the repository (307,299 lines); its 15 internal dependencies span every layer, and the runtime modules for goal/peer orchestration (Chapter 18), coding autonomy (Chapter 19), and the outer-loop OctoLoop (Chapter 20) live under its src/autonomy/ and src/peers/; its 55 external dependencies are also the repository maximum. octos-server is just 21 lines of Rust: a thin HTTP/WebSocket server shell split out from cli, whose core capabilities still live in the crates it depends on, with the entire HTTP layer tucked behind the api feature gate (Chapter 15).

L6 Embedding core: octos-ffi

The stable C ABI layer. It depends on 6 crates (core/agent/llm/memory/cli/embed-llama) and distills the platform's commonly used capability surface into one set of cross-language function boundaries. Note that it depends on L5's octos-cli rather than anything lower: embedders get "the full product capability," not "a kit of raw primitives." That trade makes the binding layer thinner and the ffi layer heavier, by design.

L7 Bindings: octos-uniffi, octos-pyo3

The two outermost leaves, each depending only on octos-ffi: octos-uniffi targets Swift/Kotlin mobile, octos-pyo3 targets Python (pyo3@0.23, configured in crates/octos-pyo3/Cargo.toml, gated as a whole). Adding a new language binding means adding one leaf crate at L7 and touching nothing inner. Splitting L6/L7 into two layers exists precisely to keep the blast radius of binding expansion minimal.

The capability layer (unlayered)

app-skills (14 capability binaries), platform-skills/voice, and octos-web attach across process boundaries or as static assets, carry zero octos-* dependency edges, and therefore appear neither in the A.3 table nor among the 63 edges in A.2. They enjoy the workspace's unified toolchain and lint configuration without entering the core compile graph, so releases and builds never drag each other down.

A.5 External dependency inventory

The table below lists every external dependency in each crate's [dependencies] section, in name@version-requirement form; a trailing * means feature-gated (optional = true, controlled by that crate's [features], not compiled in the default build). Version requirements are quoted verbatim from the baseline commit's [workspace.dependencies] inheritance or the crate's inline declarations; name.workspace = true entries are resolved to their actual version requirements. The repository-wide external dependency total is 279 entries, consistent with the sum of the "External deps" column in A.3.

crateExternal dependencies (name@version, * = gated)
octos-coreserde@1, serde_json@1, chrono@0.4, uuid@1, eyre@0.6, tracing@0.1, sha2@0.10
octos-pluginserde@1, serde_json@1, eyre@0.6, tracing@0.1, which@7, tokio@1, metrics@0.24
octos-sandboxclap@4, eyre@0.6
octos-bustokio@1, lru@0.16, async-trait@0.1, serde@1, serde_json@1, chrono@0.4, chrono-tz@0.10, uuid@1, cron@0.15, eyre@0.6, tracing@0.1, metrics@0.24, futures@0.3, reqwest@0.12, serde_yml@0.0.12, subtle@2, sha2@0.10, aes@0.8, cbc@0.1, base64@0.22; gated: teloxide@0.17*, serenity@0.12*, tokio-tungstenite@0.26*, axum@0.8*, async-imap@0.11*, tokio-rustls@0.26*, rustls@0.23*, rustls-native-certs@0.8*, webpki-roots@0.26*, lettre@0.11*, mailparse@0.16*
octos-llmasync-trait@0.1, reqwest@0.12, tokio@1, serde@1, serde_json@1, eyre@0.6, futures@0.3, secrecy@0.10, tracing@0.1, base64@0.22, chrono@0.4, redb@2, metrics@0.24, jsonwebtoken@9
octos-memoryregex@1, redb@2, tokio@1, serde@1, serde_json@1, chrono@0.4, uuid@1, eyre@0.6, tracing@0.1, hnsw_rs@0.3, bincode@1
octos-diagnosticsserde@1, serde_json@1, eyre@0.6; gated: reqwest@0.12*
octos-storechrono@0.4, eyre@0.6, serde@1, serde_json@1, sha2@0.10, base64@0.22, tracing@0.1, redb@2, uuid@1, tokio@1, getrandom@0.2, constant_time_eq@0.3
octos-fleeteyre@0.6, redb@2, rusqlite@0.32, serde@1, serde_json@1, tokio@1, tracing@0.1, uuid@1
octos-wasmserde@1, serde_json@1, wasm-bindgen@0.2, serde-wasm-bindgen@0.6, js-sys@0.3
octos-agentasync-trait@0.1, tokio@1, serde@1, serde_json@1, toml@0.8, chrono@0.4, eyre@0.6, tracing@0.1, metrics@0.24, glob@0.3, globset@0.4, shlex@1, which@7, dunce@1, regex@1, ignore@0.4, futures@0.3, reqwest@0.12, rmcp@1.8, tokio-util@0.7, oauth2@5, reqwest_rmcp@0.13 (inline entry, package = "reqwest" rename, default-features = false + features = ["rustls"]), tiny_http@0.12, webbrowser@1, keyring@3, url@2, htmd@0.5, dirs@5, sha2@0.10, flate2@1, tar@0.4, libc@0.2, base64@0.22, chromiumoxide@0.9, pdf-extract@0.9, tempfile@3, lettre@0.11, redb@2, hound@3; gated: gix@0.79*, similar@2*, tree-sitter@0.24*, tree-sitter-rust@0.23*, tree-sitter-python@0.23*, tree-sitter-javascript@0.23*, tree-sitter-typescript@0.23*, symphonia@0.5*
octos-serviceschrono@0.4, eyre@0.6, serde@1, serde_json@1, tokio@1, tracing@0.1, reqwest@0.12, flate2@1, tar@0.4, dirs@5, futures@0.3
octos-embed-llamaeyre@0.6, async-trait@0.1, tracing@0.1; gated: llama-cpp-2@0.1*, self_cell@1*
octos-pipelineasync-trait@0.1, tokio@1, serde@1, serde_json@1, eyre@0.6, futures@0.3, tracing@0.1, chrono@0.4, regex@1, glob@0.3
octos-swarmasync-trait@0.1, chrono@0.4, eyre@0.6, metrics@0.24, redb@2, serde@1, serde_json@1, tokio@1, tracing@0.1, uuid@1, sha2@0.10 (sha2.workspace = true inheritance, crates/octos-swarm/Cargo.toml:21)
octos-dora-mcpnone (only octos-agent)
octos-fleet-workerasync-trait, eyre, serde_json, tokio, tracing; all five written as name.workspace = true inheritance (crates/octos-fleet-worker/Cargo.toml:12-16), with version requirements in the root [workspace.dependencies]
octos-workflowschrono@0.4, eyre@0.6, serde@1, serde_json@1, tokio@1, tracing@0.1
octos-serverasync-trait@0.1, serde@1, serde_json@1, tokio@1, tracing@0.1, chrono@0.4, eyre@0.6, uuid@1, metrics@0.24; gated (HTTP layer, api feature): axum@0.8*, tower-http@0.6*, tokio-util@0.7*, futures@0.3*, tokio-tungstenite@0.26*, rustls@0.23*, rustls-native-certs@0.8*, rust-embed@8*, metrics-exporter-prometheus@0.16*, lettre@0.11*, rand@0.8*, sysinfo@0.34*, subtle@2*
octos-cliasync-trait@0.1, clap@4, clap_complete@4, dirs@5, serde@1, serde_json@1, colored@2, chrono@0.4, iana-time-zone@0.1, tokio@1, eyre@0.6, uuid@1, color-eyre@0.6, tracing@0.1, tracing-subscriber@0.3, tracing-appender@0.2, rustyline@15, reqwest@0.12, url@2, sha2@0.10, fs2@0.4, getrandom@0.2, constant_time_eq@0.3, percent-encoding@2, open@5, zip@2, quick-xml@0.37, image@0.25, regex@1, tempfile@3, base64@0.22, toml@0.8, agent-client-protocol@1.2.0, keyring@3, flate2@1, qrcode@0.14, chacha20poly1305@0.10, argon2@0.5, tar@0.4, metrics@0.24, redb@2 (redb.workspace = true inheritance, crates/octos-cli/Cargo.toml:112); gated: subtle@2*, axum@0.8*, tower-http@0.6*, tokio-util@0.7*, futures@0.3*, tokio-tungstenite@0.26*, rustls@0.23*, rustls-native-certs@0.8*, rust-embed@8*, metrics-exporter-prometheus@0.16*, lettre@0.11*, rand@0.8*, teloxide@0.17*, sysinfo@0.34*
octos-ffitokio@1, serde@1, serde_json@1, libc@0.2
octos-uniffiuniffi@0.29
octos-pyo3gated: pyo3@0.23* (features = ["abi3-py39"])

Across the repository, feature-gated dependencies total 50 external entries, distributed as: octos-agent 8, octos-bus 11, octos-cli 14, octos-server 13, octos-diagnostics 1, octos-embed-llama 2, octos-pyo3 1, and 0 for every other crate (a repository-wide optional = true search hits 52 lines; the one extra line each in cli and ffi is the optional entry for the internal dependency octos-embed-llama, not counted as external gated). Three gate designs worth remembering: octos-bus's 11 gated entries are all channel integrations, so the default build pulls in none of the chat network stacks; octos-server's 13 gated entries form the complete HTTP layer behind the api feature, keeping server-core ungated (see the description at crates/octos-server/Cargo.toml:7); and octos-agent's gix/tree-sitter families turn Git and AST capability into explicit switches (Chapter 6). The full feature-flag propagation map is in Appendix D.

A.6 Using this appendix as a tool

Three typical uses. Locate: given a crate name, look up its layer and dependency list in A.3 first, then its upstream and downstream in the A.2 graph, and you can size the blast radius of a change in 30 seconds. Check dependencies: before wiring in a new channel, check A.5 for which crate it lands in, whether it is gated, and whether the default build will pull it in. Settle disputes: whenever a chapter cites numbers about crates, this appendix and assets/appendixA-facts.md are the authority; when prose in a chapter disagrees with these numbers, first compare methodologies (dev-dependencies excluded or not, gated entries counted or not) before deciding which is wrong.


Further reading

  • Cargo Workspaces, official documentation: https://doc.rust-lang.org/cargo/reference/workspaces.html; the members inheritance and [workspace.dependencies] mechanisms.
  • Cargo Features, official documentation: https://doc.rust-lang.org/cargo/reference/features.html; optional = true and the feature unification rules, read against the gated annotations in A.5.
  • The UniFFI user guide: https://mozilla.github.io/uniffi-rs/; how the L7 binding layer generates its bindings.
  • The pyo3 user guide: https://crates.io/crates/pyo3 (the entry page links the docs); the stable-ABI tradeoff of abi3-py39.
  • Section 1.3 of Chapter 1 in this book: how the workspace topology was derived, and the three fact corrections.

Exercises

  1. In A.3, octos-cli at 307,299 lines and 55 external dependencies is more than ten thousand times the size of octos-server. If cli were split tomorrow into octos-cli-core and octos-cli-app, which of the 63 edges in A.2 would move, and how many layers would the stack become?
  2. octos-server holds L5 with 21 lines. Defining "layer" as dependency depth rather than code volume: what does that buy a reader of architecture diagrams, and where does it mislead?
  3. octos-bus gates all 11 channel dependencies, while octos-llm's reqwest stays ungated. What is your criterion for deciding whether a dependency belongs in the default build?
  4. Suppose a new Kotlin binding crate octos-kotlin is added: should it sit at L7 depending on octos-ffi, or depend on octos-core directly? What does each choice change among the 63 edges?

Version note

Version note: This appendix analyzes octos main @ 9c157101 (measured 2026-09-03). Every number (63 edges, 26 top-level entries, 23 octos-* crates, 38 members, 8 layers, 700,915 lines, 279 external dependencies, 52 optional lines) comes from assets/appendixA-facts.md, measured at that commit, with reproduction commands recorded alongside the data.

Relative to the v1 draft, this appendix makes three classes of updates. First, the dependency graph grew from v1's 11-crate core diagram to the full 23 octos-* crates: fleet, swarm, workflows, diagnostics, services, and store became standalone nodes after the old text was written, so the old edge count and node set are obsolete. Second, fact corrections: octos-sandbox is a platform helper binary, not the sandbox subsystem; app-skills/platform-skills are workspace-member collections of capability binaries, not nodes expanded into the core graph; the newest goal/peer/autonomy modules live inside octos-cli and octos-agent, no octos-autonomy crate exists, and the graph draws no node for it. Third, methodology upgrades: the external dependency table went from "key dependencies as examples" to the full 279-entry inventory with per-entry feature-gate annotations, and line counts and layers were recomputed under the same methodology as Chapter 1.

Appendix B: Tool Quick Reference

Positioning: This appendix is the data plane of the tool system in Chapter 6: it enumerates all 80 registered tool names visible to models on the current octos main branch (60 core + 20 admin), gives a guided tour across 10 capability domains, and pairs the P0 coding contract's ten required tools with their corresponding coding shims, the fleet worker's two tool subtables, and the 4 feature gates. Prerequisites: Chapter 6 (the tool system) and Chapter 7 (group policy and the sandbox). Who should read it: readers B/C/D configuring profiles or WorkerGrants, or debugging "why is this tool invisible": use it as an index, not a tutorial.

B.0 Methodology: organized by registered name, not by fixed total

octos has no stable "total number of tools." The same crates/octos-agent/src/tools/ directory yields three different counts under three measurement conventions, and this appendix uses the measured one throughout (commit 9c157101, measured 2026-09-03):

  • Directory convention: crates/octos-agent/src/tools/ holds 58 entries (57 .rs files plus one admin/ subdirectory), matching Chapter 6;
  • Registered-name convention: under different construction paths, those 58 entries register 80 model-visible names: the 60 core + 20 admin of this table. crates/octos-agent/src/tools/coding_tools.rs alone carries 15 registered names, while support modules like crates/octos-agent/src/tools/replacer.rs and crates/octos-agent/src/tools/write_grant.rs carry none at all, so "file count equals tool count" fails in both directions;
  • Grouping convention: policy grouping follows TOOL_GROUPS (10 groups) at crates/octos-agent/src/tools/policy.rs:186.

The old draft's approach of listing built-in tools by fixed count is retired: profile filtering, compile-time feature gates, the spawn_only marker, and chat-gateway registration all change which tool set a session actually sees, and remembering the layered registration model beats remembering a number. The "one-line duty" column in the table comes from each file's first //! doc line or its fn description() return string, verifiable row by row.

B.1 Main table: the 80 registered names

Each row gives the registered name, a one-line duty, its capability domain, and its gate. The "Gate" column is filled only when the tool is constrained by a compile-time feature or a runtime environment variable; - means visible in a default build (still subject to profile and policy filtering). Capability domains follow the 10 domains of Chapter 6.

Registered nameOne-line dutyDomainGate
read_fileRead file contentsFilesystem-
write_fileCreate or overwrite a fileFilesystem-
edit_fileExact string-replacement editingFilesystem-
diff_editApply unified-diff patchesFilesystem-
apply_patchCodex-style multi-file patch (#1773), P0 memberFilesystem-
list_dirList directory contentsFilesystem-
globFind file paths by patternFilesystem-
grepSearch file contents by regexFilesystem-
workspace_logRead-only view of workspace git historyFilesystem-
workspace_showRead a file's historical version at a commitFilesystem-
workspace_diffView the diff between two commitsFilesystem-
shellExecute shell commands under policy and sandbox constraintsShell & execution-
exec_commandLong-running execution with sessionized stdin and incremental output recovery, P0 memberShell & execution-
write_stdinWrite stdin to a running exec session and recover output, P0 memberShell & execution-
bashCodex naming-aligned one-shot shell alias (#1172)Shell & execution-
checkProject static check (#1772, lite scope)Shell & execution-
web_searchMulti-provider web searchWeb & research-
web_fetchFetch a URL and extract textWeb & research-
browserchromiumoxide-based headless browser automationWeb & research-
searchDeep search: web search plus parallel crawling, persisted to diskWeb & research-
synthesize_researchRead search artifact files and produce a synthesisWeb & research-
deep_crawlCDP-based recursive site crawlingWeb & research-
memory_noteAppend an observation worth rememberingMemory-
record_memory_useReport which memory entries actually informed the answerMemory-
recallRetrieve tool outputs displaced by context compaction (#2131)Memory-
recall_memoryLoad a full entity page from the memory bankMemory-
save_memoryWrite or update a memory-bank entity pageMemory-
messageSend messages across channelsMessaging & interaction-
send_fileDeliver files to a chat channelMessaging & interaction-
send_app_cardDeliver structured mini-app card payloadsMessaging & interaction-
ask_user_questionStructured mid-turn user question (UPCR-2026-023)Messaging & interaction-
spawnSpawn a subagent, sync-wait or run in backgroundPeer & background tasks-
delegate_taskSynchronous delegation tool (delegate is the coding-side alias)Peer & background tasks-
peer_handoffLLM-initiated peer staging (#1801 v3)Peer & background tasks-
peer_send_inputMaster injects cross-session input to a peer (#436)Peer & background tasks-
peer_gatherRead the peer blackboard (#1801 v3 fan-in)Peer & background tasks-
peer_listCompact status index of the caller's peersPeer & background tasks-
peer_respondAnswer a BLOCKED peer (human in the loop)Peer & background tasks-
peer_closeRetire a peer you createdPeer & background tasks-
check_background_tasksSession-scoped background task checkPeer & background tasks-
read_task_outputSelectively inspect background task outputPeer & background tasks-
code_structuretree-sitter-based code structure analysisCode & structurefeature = "ast" (compile time)
spawn_agentLaunch a supervised Codex-compatible subagent, P0 memberCode & structure-
delegateOne-stop wrapper of spawn_agent plus wait_agent (#1172)Code & structure-
view_imageImage metadata inspection within the workspace (#972)Code & structure-
tool_searchDynamically discover tools from the live catalog (#1148)Code & structure-
tool_suggestRecommend tools by task description (#1148)Code & structure-
image_generationImage generation entry, currently returns typed coding_tool_unsupported (#1149)Code & structure-
update_planUpdate the visible task plan, P0 memberCode & structure-
request_user_inputRequest structured input from the host UI, P0 memberCode & structure-
send_inputSend input to a subagent, P0 member (not real-time conversation delivery)Code & structure-
resume_agentResume a subagent handle, P0 memberCode & structure-
wait_agentInspect or wait on subagents, P0 memberCode & structure-
close_agentClose a subagent handle, P0 memberCode & structure-
gitPure-Rust (gix) native git integrationGitfeature = "git" (compile time)
manage_skillsSkill management on the regular gatewaySkills & platform-
mofa_makeContent-generation dispatcher (RFC-1, #1290), registered spawn_onlySkills & platform-
check_workspace_contractRead-only inspection of workspace contract stateSkills & platform-
configure_toolPersistent per-tool configuration accessSkills & platform-
model_checkModel and provider inventory (registered by the chat gateway)Skills & platform-
admin_platform_skillsServer-level ASR/TTS engine management (ominix-api)admin-
admin_list_profilesList profilesadmin-
admin_profile_statusQuery profile statusadmin-
admin_start_profileStart a profileadmin-
admin_stop_profileStop a profileadmin-
admin_restart_profileRestart a profileadmin-
admin_enable_profileEnable a profileadmin-
admin_update_profileUpdate a profileadmin-
admin_manage_skillsInstall or remove GitHub skills per profileadmin-
admin_list_sub_accountsList sub-accountsadmin-
admin_create_sub_accountCreate a sub-accountadmin-
admin_view_logsView server logsadmin-
admin_system_healthSystem health checkadmin-
admin_provider_metricsProvider metricsadmin-
admin_manage_watchdogWatchdog managementadmin-
admin_system_metricsSystem metricsadmin-
admin_view_sessionsView sessionsadmin-
admin_cron_statusScheduled-job statusadmin-
admin_check_configConfiguration checkadmin-
admin_update_octosCheck and apply octos updates via the serve APIadmin-

Count reconciliation: Filesystem 11 + Shell & execution 5 + Web & research 6 + Memory 5 + Messaging & interaction 4 + Peer & background tasks 10 + Code & structure 13 + Git 1 + Skills & platform 5 = 60 core, plus 20 admin, 80 total.

B.2 A guided tour of the ten capability domains

B.2.1 Filesystem (fs)

The filesystem domain is the foundation of every writing and repository-reconnaissance capability: from the byte-level read_file/write_file, through exact-replacement edit_file and the patch-style diff_edit/apply_patch, to the directory-and-content trio (list_dir/glob/grep) and the read-only workspace-history trio. The policy group group:fs covers the 5 write-side tools among them (read_file, write_file, apply_patch, edit_file, diff_edit, crates/octos-agent/src/tools/policy.rs:191-196).

B.2.2 Shell & execution (runtime)

The four registered names in the execution domain share one command policy and sandbox, so when any one path is denied, the rest die with it; group:runtime therefore always contains shell, exec_command, write_stdin, bash (crates/octos-agent/src/tools/policy.rs:206), and check is the parallel static-checking entry, sharing the shell session sandbox.

B.2.3 Web & research (web/search/research)

This domain maps to three policy groups: the search-fetch-browser trio of group:web (crates/octos-agent/src/tools/policy.rs:211), the local-retrieval trio of group:search (crates/octos-agent/src/tools/policy.rs:216), and the multi-round deep-research trio search, synthesize_research, deep_crawl of group:research (crates/octos-agent/src/tools/policy.rs:251).

B.2.4 Memory (memory)

The four tools of group:memory (recall_memory, save_memory, memory_note, record_memory_use) form the read-write loop of cross-session memory (crates/octos-agent/src/tools/policy.rs:239-246); recall is the same domain's tool pointing the other way: it re-materializes in-session tool output that compaction threw away.

B.2.5 Messaging & interaction

The messaging domain boils the agent's outward-facing surface down to four openings: cross-channel text (message), file delivery (send_file), structured cards (send_app_card), and structured questioning (ask_user_question); the last is the synchronous, route-answers superset of request_user_input (UPCR-2026-023).

B.2.6 Peer & background tasks (sessions)

group:sessions collects every subagent entry: spawn, spawn_agent, send_input, resume_agent, wait_agent, close_agent, delegate (crates/octos-agent/src/tools/policy.rs:228-236); add the five peer-lifecycle tools and the two background-task checks, and this domain is the complete index of multi-agent collaboration.

B.2.7 Code & structure (coding)

This domain is the bulk of the Codex-compatible tool surface: crates/octos-agent/src/tools/coding_tools.rs carries 15 registered names in a single file, 9 of which enter the P0 contract, the other 6 being extension entries from #972/#1148/#1149; add the feature-gated code_structure and the domain totals 13 registered names; all 15 are registered in with_builtins_and_permissions at crates/octos-agent/src/tools/registry.rs:1254 (registration body from 1283).

B.2.8 Git

git is the only VCS registered name, using the pure-Rust gix implementation instead of shelling out, gated at compile time by feature = "git" (crates/octos-agent/src/tools/mod.rs:861), and rebound with the CWD binding list at crates/octos-agent/src/tools/registry.rs:1466-1469.

B.2.9 Skills & platform

The skills-and-platform domain mixes two registration classes: the regular gateway's manage_skills, configure_tool, and the chat-gateway-registered model_check (the three forming group:admin, crates/octos-agent/src/tools/policy.rs:253-257), plus the spawn_only-registered content-generation dispatcher mofa_make and the workspace-contract inspection check_workspace_contract.

B.2.10 The admin subdirectory

All 20 admin-domain registered names come from the 7 files of crates/octos-agent/src/tools/admin/, facing the operations surface of the Serve/Admin API: seven profile-lifecycle tools, eight system-observability tools, two sub-account tools, and three skills-and-platform update tools; ordinary profiles do not see them by default.

B.3 The P0 required ten and their coding shims

The P0 required set declared by the Codex-compatible contract is defined in CODING_P0_REQUIRED_TOOL_NAMES at crates/octos-cli/src/api/coding_tool_contract.rs:85, ten names in all: apply_patch, exec_command, write_stdin, update_plan, request_user_input, spawn_agent, send_input, resume_agent, wait_agent, close_agent. Nine of the ten come from crates/octos-agent/src/tools/coding_tools.rs; the sole exception, apply_patch, is a native file tool (crates/octos-agent/src/tools/apply_patch.rs), outside coding_tools.rs.

graph LR
    subgraph P0["P0 required 10(crates/octos-cli/src/api/coding_tool_contract.rs:85)"]
        AP["apply_patch<br/>crates/octos-agent/src/tools/apply_patch.rs"]
        C9["crates/octos-agent/src/tools/coding_tools.rs 内 9 名:exec_command、write_stdin、update_plan、request_user_input、spawn_agent、send_input、resume_agent、wait_agent、close_agent"]
    end
    OUT["P0 之外的 6 个 headline shim:bash、delegate、view_image、tool_search、tool_suggest、image_generation"]
    AP --> P0
    C9 --> P0
    OUT -.->|不属于 P0| P0

The row-by-row relation between the ten headline shims (nine under the briefing convention, plus representatives of the six macro-registered ones) and P0 is tabulated below; the first three are P0 members, and each of the remaining six has a stated reason for exclusion:

Registered nameRelation to P0Evidence (full path)
exec_commandP0 membercrates/octos-agent/src/tools/coding_tools.rs:382;crates/octos-cli/src/api/coding_tool_contract.rs:85
write_stdinP0 membercrates/octos-agent/src/tools/coding_tools.rs:739
spawn_agentP0 membercrates/octos-agent/src/tools/coding_tools.rs:1284
bashOutside P0, #1172 naming-aligned alias, shares policy and sandbox with shell/exec_command; deny one of the three and all three are deniedcrates/octos-agent/src/tools/coding_tools.rs:1946;crates/octos-agent/src/tools/registry.rs:1281-1290
delegateOutside P0, #1172 one-stop wrapper (DelegateAliasTool, bound to spawn_agent, group:sessions member)crates/octos-agent/src/tools/coding_tools.rs:2429;crates/octos-agent/src/tools/registry.rs:548,566,1284
view_imageOutside P0, #972/M14-B P1 image inspection, read-only and constrained by filesystem_scopecrates/octos-agent/src/tools/coding_tools.rs:2801;crates/octos-agent/src/tools/registry.rs:1461-1464
tool_searchOutside P0, #1148 dynamic-discovery entry, reads the live catalogcrates/octos-agent/src/tools/coding_tools.rs:3150
tool_suggestOutside P0, #1148 recommend-by-task entrycrates/octos-agent/src/tools/coding_tools.rs:3251
image_generationOutside P0, #1149/M14-B P2; currently returns typed coding_tool_unsupported (wire contract complete, no generation backend bound yet)crates/octos-agent/src/tools/coding_tools.rs:3391;crates/octos-agent/src/tools/registry.rs:1368-1370 comment verbatim

Two contract semantics deserve separate note. First, although send_input is listed in P0, it is not real-time conversation delivery today: it registers through the simple_codex_tool! macro (crates/octos-agent/src/tools/coding_tools.rs:1839-1842) and writes to a supervised task's input channel, not an interactive session. Second, image_generation's typed unsupported is a deliberate contract posture: the caller receives a structured "not supported in this environment" envelope rather than a tool-not-found error, so a frontend can degrade its UI without breaking the protocol.

Engineering decision: why aliases must join groups (#1172) The deny-wins policy matches by "registered name or group name." If aliases like bash and delegate stayed out of group:runtime/group:sessions, a profile that disabled execution or subagents could still loop back to the original capability through the alias. The fix writes the aliases into the group definitions (verbatim comment at crates/octos-agent/src/tools/policy.rs:201-205) and makes the fact that delegate holds an Arc handle to the bound spawn_agent part of the group comment as well: the policy layer covers "every entry point," not "every implementation file."

B.4 The fleet worker's two subtables

The tool surface of a fleet worker (Chapter 16) is bounded by the constant tables in crates/octos-fleet/src/grant.rs; what the master can grant is capped by the allowlist:

SubtableMembersEvidence (full path)
BASE_TOOLS (default 7)read_file, write_file, edit_file, glob, grep, list_dir, shellcrates/octos-fleet/src/grant.rs:27
GRANTABLE_TOOLS (grantable 9)the above 7 plus web_fetch, web_searchcrates/octos-fleet/src/grant.rs:41
WEB_TOOLS (network 2)web_fetch, web_search (grantable only under a network grant)crates/octos-fleet/src/grant.rs:56

Verification command: sed -n '27,60p' crates/octos-fleet/src/grant.rs.

The lean coding profile's tool surface is decided by the allow_list of crates/octos-agent/src/assets/profiles/coding.json, 12 entries in all (4 single names plus three groups plus 5 single names), which expand against TOOL_GROUPS to 20 registered names:

allow_list entryExpanded registered names
read_file, write_file, edit_file, diff_editthe same 4 names
group:runtimeshell, exec_command, write_stdin, bash
group:searchglob, grep, list_dir
group:memoryrecall_memory, save_memory, memory_note, record_memory_use
spawn, ask_user_question, check, update_plan, tool_searchthe same 5 names

The design intent is written verbatim in the json description: add the three previously missing loop tools check, update_plan, tool_search, and drop only apply_patch (edit_file/diff_edit cover its duty); when the excluded tools are needed again, restore with --profile coding-full rather than discovering at runtime. run_pipeline is registered spawn_only and is not in the allow_list (crates/octos-agent/src/profile/mod.rs:874). One convention discrepancy needs stating: the facts-table label says "19 names after expansion," but group-by-group expansion measures 20 (the table above totals 4+4+3+4+5); this table follows the group-by-group expansion.

B.5 Feature gates: 2 compile-time + 2 runtime

Only 4 of the 80 registered names are gated, two in each class:

Gate typeRegistered nameSwitchEvidence (full path)
Compile-time featuregitfeature = "git"crates/octos-agent/src/tools/mod.rs:861
Compile-time featurecode_structurefeature = "ast"crates/octos-agent/src/tools/mod.rs:864
Runtime environment variableread_window (internal, not a registered name)OCTOS_READ_WINDOW=1, default offcrates/octos-agent/src/tools/read_window.rs:177-179
Runtime environment variableread_paging_probe (internal, not a registered name)OCTOS_READ_PAGING_PROBE=1, not armed, not recordedcrates/octos-agent/src/tools/read_paging_probe.rs:131

Both runtime gates act on "internal components" rather than standalone registered names, consistent with Chapter 6's conclusion: tightening the read path starts with probes collecting data, then decides whether to become default behavior. The compile-time gates appear in the CWD binding list at crates/octos-agent/src/tools/registry.rs:1466-1469 behind #[cfg]; without the feature enabled, even the rebinding list omits these two names.

B.6 Further reading and exercises

Further reading: Chapter 6 (the capability-domain division of the 58 entries and the registration layers), Chapter 7 (group policy evaluation, the sandbox, and write_grant), Chapter 16 (fleet's WorkerGrant and its relation to this appendix's two subtables).

Exercises:

  1. group:delegated is a deny table, not an allow table (crates/octos-agent/src/tools/policy.rs:307-331), yet it explicitly does not restrict command execution. Why is "recursive delegation breaks, command execution doesn't" a coherent boundary choice?
  2. coding.json's allow_list has only 12 entries but expands to 20 names. When you want to add or remove a tool from the lean profile, which downstream effects differ between editing an allow_list entry and editing a TOOL_GROUPS member?
  3. image_generation chose to return typed unsupported instead of being removed from the registry. If it were removed, what would frontend contract validation and user messaging each lose?

Version note: This appendix's baseline is octos main @ 9c157101 (measured 2026-09-03). Data source: assets/appendixB-facts.md (commit ad387d1, same batch); all line numbers were re-verified by hand this session. Against the old draft: the retired convention listed "core built-in tools" by fixed count; the current registered-name total is 80 (60 core + 20 admin) across 10 capability domains, and the shim attribution of the P0 contract's ten, the fleet's two subtables, and the 4 feature gates were all newly collected this round; bash/delegate joining groups (#1172) and image_generation's typed unsupported (#1149) are behavior changes that postdate the old draft.

Appendix C: Configuration Reference

Positioning: This appendix is the complete field reference for config.json and profile files: one table per top-level config section, with field path, type, default, one-line purpose, and source line, all verified against octos 9c157101 (crates/octos-cli/src/config.rs runs 3,790 lines, crates/octos-cli/src/profiles.rs runs 7,003 lines). For behavioral semantics (how the sandbox picks a backend, how MCP performs its handshake, how the goal three-tier inheritance works) see the corresponding chapters; this appendix answers only "what is this field, what is its default, where is it defined." mcp_servers and sub_providers, which overlap with Chapter 9 (extension mechanisms), get field tables only.

C.1 Config file locations and load order

Resolution order for the top-level config.json (crates/octos-cli/src/config.rs:1715 resolve_config_file_path): an explicit --config <FILE> overrides everything, then (under the default install) project-local <cwd>/.octos/config.json, then <config_home>/config.json, then (under the default install) the legacy ~/.octos/config.json. When no file exists, the write location falls back to config_home/config.json.

Profile files live at ~/.octos/profiles/<id>.json (crates/octos-cli/src/profiles.rs:5); their data directory defaults to ~/.octos/profiles/{id}/data (crates/octos-cli/src/profiles.rs:164).

C.2 Top-level Config (crates/octos-cli/src/config.rs:26)

Field pathTypeDefaultPurposeSource
versionu32?null (constant currently 1)config migration versioncrates/octos-cli/src/config.rs:29
providerstring?nullLLM provider name ("anthropic" / "openai" / "gemini")crates/octos-cli/src/config.rs:33
modelstring?nullmodel IDcrates/octos-cli/src/config.rs:37
context_windowu32?nulleffective context window override for the primary model (tokens), outermost wrapper, beats catalog and probingcrates/octos-cli/src/config.rs:46
model_temperaturef32?nulltyped sampling temperature projection for the primary model (#2166)crates/octos-cli/src/config.rs:56
model_top_pf32?nulltop_p projection for the primary model; overrides the same-named key in the sampling params table at runtimecrates/octos-cli/src/config.rs:61
model_reasoning_effortenum?nulldefault reasoning effort for the primary model (low/medium/high)crates/octos-cli/src/config.rs:65
base_urlstring?nullAPI endpoint overridecrates/octos-cli/src/config.rs:69
api_key_envstring?provider defaultAPI key environment variable namecrates/octos-cli/src/config.rs:73
env_varsmap<string,string>{}profile-scoped environment variables (including keys persisted by the dashboard)crates/octos-cli/src/config.rs:77
bypass_auth_storeboolfalseinternal field (#[serde(skip)], not serialized): skip the global AuthStore key lookupcrates/octos-cli/src/config.rs:86
model_hintsobject?nullcustom model behavior hints for OpenAI-compatible proxiescrates/octos-cli/src/config.rs:91
api_typestring?provider defaultprotocol override ("openai" / "anthropic")crates/octos-cli/src/config.rs:97
auth_tokenstring?nulldashboard/admin token; also --auth-token or OCTOS_AUTH_TOKENcrates/octos-cli/src/config.rs:102
gatewayobject?nullgateway mode configuration (see C.3)crates/octos-cli/src/config.rs:106
mcp_serversarray[]MCP server list (see C.9)crates/octos-cli/src/config.rs:110
sandboxobjectSandboxConfig::default()tool sandbox (see C.5)crates/octos-cli/src/config.rs:114
snapshotsobject?null (= off)workspace snapshot-rollback (#1768, off by default)crates/octos-cli/src/config.rs:123
tool_policyobject?nullglobal tool allow/deny/tag policy (see C.5)crates/octos-cli/src/config.rs:127
tool_policy_by_providermap<string,ToolPolicy>{}per-model/provider-prefix tool policycrates/octos-cli/src/config.rs:132
embeddingobject?nullhybrid memory embedding (see C.6)crates/octos-cli/src/config.rs:136
memoryobject?nullmemory subsystem (see C.6)crates/octos-cli/src/config.rs:140
fallback_modelsarray[]fallback models for the provider failover chain (see C.4)crates/octos-cli/src/config.rs:145
max_iterationsu32?nullmax agent iterations per message (--max-iterations can override)crates/octos-cli/src/config.rs:149
format_after_editboolfalserun a language formatter after a successful edit (rustfmt/prettier etc., 5s timeout, #1774)crates/octos-cli/src/config.rs:158
hooksarray[]lifecycle hooks (see C.7)crates/octos-cli/src/config.rs:162
approval_policyobject?nullhuman approval rules for tool calls (see C.7)crates/octos-cli/src/config.rs:168
context_filterstring[][]tool tag filter; only tools with matching tags are visible to the LLMcrates/octos-cli/src/config.rs:173
sub_providersarray[]provider lanes selectable by spawned sub-agents (see C.10)crates/octos-cli/src/config.rs:184
adaptive_routingobject?nulladaptive routing (see C.8)crates/octos-cli/src/config.rs:189
emailobject?nullsend_email tool configuration (see C.6)crates/octos-cli/src/config.rs:193
voiceobject?nullASR/TTS (see C.6)crates/octos-cli/src/config.rs:198
modeenum"local"deployment mode: local / tenant / cloudcrates/octos-cli/src/config.rs:206
tunnel_domainstring?nullcloud/tenant tunnel domaincrates/octos-cli/src/config.rs:211
base_domainstring?compatible crew.ominix.iobase domain for public profiles (OCTOS_BASE_DOMAIN takes precedence)crates/octos-cli/src/config.rs:222
frps_serverstring?nullfrps server address (FRPS_SERVER env can override)crates/octos-cli/src/config.rs:227
allow_admin_shellboolfalsewhether /api/admin/shell is enabled; keep off in productioncrates/octos-cli/src/config.rs:233
dashboard_authobject?nullemail OTP login (api feature, see C.8)crates/octos-cli/src/config.rs:239
monitorobject?nullwatchdog/alert (api feature, see C.8)crates/octos-cli/src/config.rs:244
credential_poolobject?nullcredential pool (M6.5, see C.8)crates/octos-cli/src/config.rs:251
content_routingobject?nullcontent-classifier Cheap/Strong routing (M6.6)crates/octos-cli/src/config.rs:257
appuiobjectAppUiConfig::default()AppUI session defaults (see C.8)crates/octos-cli/src/config.rs:269
pluginsobjectPluginsConfig::default()plugin signature check switch (see C.8)crates/octos-cli/src/config.rs:277
climap<string,json>{} (skip serializing)per-subcommand persisted CLI flag defaults, e.g. {"serve": {"port": 50080}}crates/octos-cli/src/config.rs:292

The mode enum is defined at crates/octos-cli/src/config.rs:14: Local (standalone install, no tunnel, dashboard at /admin/), Tenant (frpc tunnel into the cloud), Cloud (VPS relay plus tenant management plus landing pages).

C.3 The gateway section (crates/octos-cli/src/config.rs:1524 GatewayConfig)

Field pathTypeDefaultPurposeSource
gateway.channels[]array<ChannelEntry>[{"type":"cli",…}]list of enabled channelscrates/octos-cli/src/config.rs:1527
gateway.channels[].typestringrequiredchannel type: "cli" / "telegram" / "discord"crates/octos-cli/src/config.rs:1642
gateway.channels[].allowed_sendersstring[][] (= everyone allowed)allowed sender IDscrates/octos-cli/src/config.rs:1646
gateway.channels[].settingsjson{}channel-specific settingscrates/octos-cli/src/config.rs:1650
gateway.max_historyusize50max history messages injected into the LLMcrates/octos-cli/src/config.rs:1531
gateway.system_promptstring?nullcustom system prompt for gateway modecrates/octos-cli/src/config.rs:1535
gateway.queue_modeenum"collect"how messages received mid-run are queuedcrates/octos-cli/src/config.rs:1541
gateway.max_sessionsusize1000max sessions in memory (LRU eviction)crates/octos-cli/src/config.rs:1545
gateway.max_concurrent_sessionsusize10max concurrently processed sessionscrates/octos-cli/src/config.rs:1549
gateway.browser_timeout_secsu64?null (300s in code)timeout for a single browser actioncrates/octos-cli/src/config.rs:1554
gateway.llm_timeout_secsu64?null (default 120)total LLM HTTP request timeoutcrates/octos-cli/src/config.rs:1558
gateway.llm_connect_timeout_secsu64?null (default 30)LLM HTTP connect timeoutcrates/octos-cli/src/config.rs:1562
gateway.tool_timeout_secsu64?null (default 300)cap on completing parallel tool callscrates/octos-cli/src/config.rs:1566
gateway.session_timeout_secsu64?null (default 600)cap on processing one session messagecrates/octos-cli/src/config.rs:1570
gateway.max_output_tokensu32?nulldefault max output tokens per call (beats model_limits.json)crates/octos-cli/src/config.rs:1575
gateway.reasoning_effortenum?nullreasoning effort for thinking models (low/medium/high), ignored by non-thinking modelscrates/octos-cli/src/config.rs:1582
gateway.llm_temperaturef32?null (= greedy 0.0)sampling temperature override, mainly to rescue repetition collapse on local models (#2172)crates/octos-cli/src/config.rs:1592
gateway.llm_sampling_paramsmap<string,json>?nullpass-through sampling params table, e.g. {"repeat_penalty":1.1} (#2172)crates/octos-cli/src/config.rs:1600

The queue_mode enum (crates/octos-cli/src/config.rs:1499): followup (FIFO, one by one), collect (default, concatenates within a session), latest (keep only the newest, alias steer), interrupt (cancel current), speculative (a slow call continues while a new agent starts).

The default port for octos serve is 50080 (documented example at crates/octos-cli/src/config.rs:283).

C.4 fallback_models[] (crates/octos-cli/src/config.rs:460 FallbackModel)

Field pathTypeDefaultPurposeSource
providerstringrequiredprovider namecrates/octos-cli/src/config.rs:462
modelstring?nullmodel namecrates/octos-cli/src/config.rs:465
base_urlstring?nullbase URL for this fallbackcrates/octos-cli/src/config.rs:468
api_key_envstring?nullkey environment variable for this fallbackcrates/octos-cli/src/config.rs:471
model_hintsobject?nullmodel behavior hintscrates/octos-cli/src/config.rs:474
api_typestring?nullprotocol overridecrates/octos-cli/src/config.rs:477
cost_per_mf64?nulloutput price per million tokens (for cost-aware routing)crates/octos-cli/src/config.rs:480
strongbooltruewhether it is a strong model (reliable with 30+ tools / large payloads)crates/octos-cli/src/config.rs:485
context_windowu32?nullcontext window override for this fallback (#2142)crates/octos-cli/src/config.rs:492

C.5 sandbox / tool_policy / snapshots

sandbox (crates/octos-agent/src/sandbox/mod.rs:37 SandboxConfig)

Field pathTypeDefaultPurposeSource
sandbox.enabledbooltruewhether the sandbox is enabledcrates/octos-agent/src/sandbox/mod.rs:40
sandbox.modeenum"auto"auto / bwrap / landlock / macos / docker / appcontainer / nonecrates/octos-agent/src/sandbox/mod.rs:44, enum crates/octos-agent/src/sandbox/mod.rs:423
sandbox.fail_closedboolfalserefuse execution when auto finds no backend, rather than degrade to bare executioncrates/octos-agent/src/sandbox/mod.rs:58
sandbox.allow_networkboolfalseallow network inside the sandboxcrates/octos-agent/src/sandbox/mod.rs:62
sandbox.workspace_writebooltruewhether shell can write the cwd (false = workspace mounted read-only)crates/octos-agent/src/sandbox/mod.rs:75
sandbox.repo_git_writepath?nulladditionally grant write access to <repo>/.gitcrates/octos-agent/src/sandbox/mod.rs:92
sandbox.docker.imagestring"ubuntu:24.04"image for docker modecrates/octos-agent/src/sandbox/mod.rs:361
sandbox.docker.cpu_limitstring?nullCPU limit such as "1.0"crates/octos-agent/src/sandbox/mod.rs:365
sandbox.docker.memory_limitstring?nullmemory limit such as "512m"crates/octos-agent/src/sandbox/mod.rs:369
sandbox.docker.pids_limitu32?nullmax process countcrates/octos-agent/src/sandbox/mod.rs:373
sandbox.docker.mount_modeenum"rw"none / ro / rw workspace mountcrates/octos-agent/src/sandbox/mod.rs:377, enum crates/octos-agent/src/sandbox/mod.rs:408
sandbox.docker.extra_bindsstring[][]extra bind mounts (host:container[:ro])crates/octos-agent/src/sandbox/mod.rs:381
sandbox.read_allow_pathsstring[][] (= everything allowed)restrict readable paths (whitelist outside the cwd)crates/octos-agent/src/sandbox/mod.rs:102
sandbox.write_allow_globsstring[]?null#1976 shell write fence: workspace-relative globscrates/octos-agent/src/sandbox/mod.rs:125
sandbox.profile_namestring?nullsandbox profile name (Windows AppContainer ID)crates/octos-agent/src/sandbox/mod.rs:129
sandbox.allow_toolchainsbooltruegrant write paths a language toolchain needs (cargo cache and the like)crates/octos-agent/src/sandbox/mod.rs:149

tool_policy (crates/octos-agent/src/tools/policy.rs:28 ToolPolicy)

Field pathTypeDefaultPurposeSource
tool_policy.allowstring[][] (= allow all)allowed tools/groups/wildcardscrates/octos-agent/src/tools/policy.rs:31
tool_policy.denystring[][]deny list, always beats allowcrates/octos-agent/src/tools/policy.rs:34
tool_policy.require_tagsstring[][]expose only tools whose declared tags match (fail closed)crates/octos-agent/src/tools/policy.rs:40
tool_policy.bash_file_writesenum"allow"allow / warn / deny: three tiers for shell file writescrates/octos-agent/src/tools/policy.rs:49

tool_policy_by_provider is a map of the same structure (crates/octos-cli/src/config.rs:132); its keys are exact model IDs (preferred) or provider prefixes.

snapshots (crates/octos-agent/src/snapshot.rs:122 SnapshotConfig)

Field pathTypeDefaultPurposeSource
snapshots.enabledboolfalsemaster snapshot switch (git-backed, stored under <data_dir>/snapshots/)crates/octos-agent/src/snapshot.rs:124
snapshots.keep_lastusize20retained snapshots per workspace (<1 clamps to 1)crates/octos-agent/src/snapshot.rs:127

C.6 embedding / memory / email / voice

embedding (crates/octos-cli/src/config.rs:655 EmbeddingConfig)

Field pathTypeDefaultPurposeSource
embedding.providerstring"openai"embedding provider (including local llamacpp)crates/octos-cli/src/config.rs:658
embedding.api_key_envstring?nullkey environment variable namecrates/octos-cli/src/config.rs:662
embedding.base_urlstring?nullAPI base URLcrates/octos-cli/src/config.rs:666
embedding.modelstring?text-embedding-3-smallembedding model IDcrates/octos-cli/src/config.rs:672
embedding.dimensionsu32?nulldimensions field in requests (episodic HNSW is fixed at 1536)crates/octos-cli/src/config.rs:678
embedding.model_pathstring?nullpath to a local .gguf (feature embed-llama)crates/octos-cli/src/config.rs:685

memory (crates/octos-cli/src/config.rs:694 MemoryConfig)

Field pathTypeDefaultPurposeSource
memory.max_inject_tokensusize?DEFAULT_MAX_INJECT_TOKENStoken budget for memory blocks injected into the system promptcrates/octos-cli/src/config.rs:701
memory.refresh.enabledbool?null (= on)master switch for automatic memory refresh (default product behavior is on)crates/octos-cli/src/config.rs:719
memory.refresh.extract_modelstring?null (= profile provider)model key for extractioncrates/octos-cli/src/config.rs:723
memory.refresh.consolidate_modelstring?null (= profile provider)model key for consolidationcrates/octos-cli/src/config.rs:726
memory.refresh.min_idle_minutesu64?30how long a session must idle before it can be scannedcrates/octos-cli/src/config.rs:729
memory.refresh.max_session_age_daysu64?10sessions older than this are never scannedcrates/octos-cli/src/config.rs:732
memory.refresh.max_sessions_per_passusize?2sessions scanned per passcrates/octos-cli/src/config.rs:735
memory.refresh.max_extractions_per_dayu32?20daily extraction budget per profilecrates/octos-cli/src/config.rs:738
memory.refresh.max_consolidations_per_dayu32?12daily consolidation budget per profilecrates/octos-cli/src/config.rs:742
memory.refresh.max_daily_tokensu64?200000daily token budget (shared by extraction and consolidation)crates/octos-cli/src/config.rs:745
memory.refresh.consolidate_interval_minutesu64?30background scan interval (minutes)crates/octos-cli/src/config.rs:748
memory.refresh.debounce_secondsu64?90fast-lane debounce after a user notecrates/octos-cli/src/config.rs:751
memory.refresh.unused_daysu32?nullhow long unused entries become archive candidatescrates/octos-cli/src/config.rs:755
memory.refresh.max_memory_file_tokensusize?nullMEMORY.md size cap (enforced at consolidation)crates/octos-cli/src/config.rs:758
memory.refresh.pending_confirm_daysu32?nulldays before a pending forget request expirescrates/octos-cli/src/config.rs:762
memory.refresh.max_extract_input_tokensusize?24000hard input budget for a single extraction callcrates/octos-cli/src/config.rs:767

Design defaults come from MemoryRefreshConfig::knobs at crates/octos-cli/src/config.rs:772.

email (crates/octos-cli/src/config.rs:856 EmailConfig)

Field pathTypeDefaultPurposeSource
email.providerstringrequired"smtp" or "feishu"/"lark"crates/octos-cli/src/config.rs:858
email.smtp_hoststring?nullSMTP hostcrates/octos-cli/src/config.rs:862
email.smtp_portu16?nullSMTP portcrates/octos-cli/src/config.rs:864
email.usernamestring?nullSMTP usernamecrates/octos-cli/src/config.rs:866
email.password_envstring?nullSMTP password environment variable (legacy)crates/octos-cli/src/config.rs:869
email.passwordstring?nullSMTP password in plaintext (takes precedence over password_env)crates/octos-cli/src/config.rs:872
email.from_addressstring?nullsender addresscrates/octos-cli/src/config.rs:874
email.feishu_app_idstring?nullFeishu app IDcrates/octos-cli/src/config.rs:878
email.feishu_app_secret_envstring?nullFeishu secret environment variable (legacy)crates/octos-cli/src/config.rs:881
email.feishu_app_secretstring?nullFeishu secret in plaintext (takes precedence)crates/octos-cli/src/config.rs:884
email.feishu_from_addressstring?nullFeishu sendercrates/octos-cli/src/config.rs:886
email.feishu_regionstring?"cn""cn" / "global"crates/octos-cli/src/config.rs:889

voice (crates/octos-cli/src/config.rs:936 VoiceConfig)

Field pathTypeDefaultPurposeSource
voice.api_urlstring?n/a (legacy, ignored)OminiX URL moved to platform-level OMINIX_API_URLcrates/octos-cli/src/config.rs:939
voice.auto_asrbooltrueautomatically transcribe voice messagescrates/octos-cli/src/config.rs:942
voice.auto_ttsbooltrueautomatically synthesize replies in voice sessionscrates/octos-cli/src/config.rs:945
voice.default_voicestring"vivian"default TTS voicecrates/octos-cli/src/config.rs:948
voice.asr_languagestring?null (auto-detect)ASR language hintcrates/octos-cli/src/config.rs:951
voice.tts_providerstring"auto"TTS routing: auto / local / cloudcrates/octos-cli/src/config.rs:964
voice.cloudobject?nullnon-secret Volcano cloud TTS settingscrates/octos-cli/src/config.rs:969
voice.cloud.appidstring?nullcloud TTS app IDcrates/octos-cli/src/config.rs:904
voice.cloud.voicestring?nullcloud TTS voicecrates/octos-cli/src/config.rs:906
voice.cloud.clusterstring?nullcloud TTS clustercrates/octos-cli/src/config.rs:908
voice.cloud.encodingstring?nullcloud TTS encodingcrates/octos-cli/src/config.rs:910
voice.cloud.endpointstring?nullcloud TTS endpointcrates/octos-cli/src/config.rs:912

Cloud TTS secrets never land in this section: the token goes through env_vars["VOLC_TTS_TOKEN"] (crates/octos-cli/src/config.rs:1040 with_cloud_token_from_env).

C.7 hooks and approval_policy

hooks[] (crates/octos-agent/src/hooks.rs:77 HookConfig)

Field pathTypeDefaultPurposeSource
hooks[].eventenumrequiredtrigger event (see below)crates/octos-agent/src/hooks.rs:79
hooks[].commandstring[]requiredargv array executed directly (no shell interpretation)crates/octos-agent/src/hooks.rs:81
hooks[].timeout_msu645000timeout in millisecondscrates/octos-agent/src/hooks.rs:84, default crates/octos-agent/src/hooks.rs:112
hooks[].tool_filterstring[][] (= all tools)fire only for these tool names (tool events)crates/octos-agent/src/hooks.rs:87
hooks[].path_filterstring[][] (= no filter)fire only when the tool argument path matches a globcrates/octos-agent/src/hooks.rs:103
hooks[].requires_binstring?nullfire only if this binary exists on PATHcrates/octos-agent/src/hooks.rs:109

Allowed event values (crates/octos-agent/src/hooks.rs:58 as_str): user_prompt_submit, before_tool_call, after_tool_call, before_llm_call, after_llm_call, on_resume, on_turn_end, before_spawn_verify, on_spawn_verify, on_spawn_complete, on_spawn_failure.

approval_policy (crates/octos-cli/src/config.rs:545 ApprovalPolicyConfig)

Field pathTypeDefaultPurposeSource
approval_policy.defaultenum"allow"disposition for tools matching no rule (v1: allow only)crates/octos-cli/src/config.rs:547
approval_policy.rules[]array[]list of human approval rulescrates/octos-cli/src/config.rs:549
approval_policy.rules[].toolsstring[]required, non-emptytool names this rule interceptscrates/octos-cli/src/config.rs:530
approval_policy.rules[].require_approvalboolmust be trueexplicit intent declarationcrates/octos-cli/src/config.rs:532
approval_policy.rules[].risk_levelenumn/anormal / criticalcrates/octos-cli/src/config.rs:533
approval_policy.rules[].authorized_approversstring[]required, non-emptychannel user IDs allowed to answercrates/octos-cli/src/config.rs:535
approval_policy.rules[].expires_in_secsu64required, >0seconds before a request expirescrates/octos-cli/src/config.rs:537
approval_policy.rules[].on_timeoutenumn/av1: notify onlycrates/octos-cli/src/config.rs:538

Validation lives in validate at crates/octos-cli/src/config.rs:587: non-empty tools, require_approval == true, non-empty approvers, expires_in_secs > 0; otherwise it fails fast.

C.8 Adaptive routing and operations sections

adaptive_routing (crates/octos-cli/src/config.rs:1085 AdaptiveRoutingConfig)

Field pathTypeDefaultPurposeSource
adaptive_routing.enabledboolfalsemaster switchcrates/octos-cli/src/config.rs:1088
adaptive_routing.latency_threshold_msu6410000soft-penalty latency thresholdcrates/octos-cli/src/config.rs:1092, default crates/octos-cli/src/config.rs:1253
adaptive_routing.error_rate_thresholdf640.3error-rate threshold for de-prioritizationcrates/octos-cli/src/config.rs:1096, default crates/octos-cli/src/config.rs:1256
adaptive_routing.probe_probabilityf640.1probability of probing a non-primary providercrates/octos-cli/src/config.rs:1100, default crates/octos-cli/src/config.rs:1259
adaptive_routing.probe_interval_secsu6460minimum interval between probes of the same providercrates/octos-cli/src/config.rs:1104, default crates/octos-cli/src/config.rs:1262
adaptive_routing.failure_thresholdu323consecutive failures before the circuit breaker openscrates/octos-cli/src/config.rs:1108, default crates/octos-cli/src/config.rs:1265
adaptive_routing.modeenum"off"off / hedge / lanecrates/octos-cli/src/config.rs:1114, enum crates/octos-cli/src/config.rs:1053
adaptive_routing.qos_rankingboolfalseinclude response quality in scoringcrates/octos-cli/src/config.rs:1120
adaptive_routing.weight_latencyf640.3latency score weightcrates/octos-cli/src/config.rs:1124, default crates/octos-cli/src/config.rs:1268
adaptive_routing.weight_error_ratef640.3error-rate weightcrates/octos-cli/src/config.rs:1127, default crates/octos-cli/src/config.rs:1271
adaptive_routing.weight_priorityf640.2configured-priority weightcrates/octos-cli/src/config.rs:1130, default crates/octos-cli/src/config.rs:1274
adaptive_routing.weight_costf640.2token cost weightcrates/octos-cli/src/config.rs:1133, default crates/octos-cli/src/config.rs:1277
adaptive_routing.auto_escalation.enabledbooltrueauto-escalate to hedge on latency degradationcrates/octos-cli/src/config.rs:1169+, default crates/octos-cli/src/config.rs:1214
adaptive_routing.auto_escalation.window_sizeusize5observation window samplescrates/octos-cli/src/config.rs:1217
adaptive_routing.auto_escalation.baseline_samplesusize5baseline samplescrates/octos-cli/src/config.rs:1220
adaptive_routing.auto_escalation.degradation_thresholdf643.0degradation multiple for the verdictcrates/octos-cli/src/config.rs:1223
adaptive_routing.auto_escalation.slow_triggeru323consecutive slow samples to triggercrates/octos-cli/src/config.rs:1226
adaptive_routing.auto_escalation.latency_ceiling_msu648000latency ceilingcrates/octos-cli/src/config.rs:1229
adaptive_routing.auto_escalation.recovery_factorf640.6recovery factorcrates/octos-cli/src/config.rs:1232

monitor (crates/octos-cli/src/config.rs:1284 MonitorConfig, api feature)

Field pathTypeDefaultPurposeSource
monitor.alerts_enabledbooltrueproactive alerting switchcrates/octos-cli/src/config.rs:1287
monitor.watchdog_enabledbooltruewatchdog auto-restartcrates/octos-cli/src/config.rs:1290
monitor.health_check_interval_secsu6460health check intervalcrates/octos-cli/src/config.rs:1293
monitor.max_restart_attemptsu323max restart attempts before giving upcrates/octos-cli/src/config.rs:1296
monitor.telegram_token_envstring?nullTelegram bot token environment variable namecrates/octos-cli/src/config.rs:1299
monitor.telegram_alert_chat_idsi64[][]Telegram chat IDs for alertscrates/octos-cli/src/config.rs:1302
monitor.feishu_app_id_envstring?nullFeishu app ID environment variablecrates/octos-cli/src/config.rs:1305
monitor.feishu_app_secret_envstring?nullFeishu secret environment variablecrates/octos-cli/src/config.rs:1308
monitor.feishu_alert_user_idsstring[][]Feishu user IDs for alertscrates/octos-cli/src/config.rs:1311

dashboard_auth (crates/octos-cli/src/otp.rs:46 DashboardAuthConfig)

Field pathTypeDefaultPurposeSource
dashboard_auth.smtp.hoststringrequiredSMTP hostcrates/octos-cli/src/otp.rs:23
dashboard_auth.smtp.portu16465SMTP port (465 implicit TLS / 587 STARTTLS)crates/octos-cli/src/otp.rs:26, default crates/octos-cli/src/otp.rs:40
dashboard_auth.smtp.usernamestringrequiredSMTP usernamecrates/octos-cli/src/otp.rs:28
dashboard_auth.smtp.password_envstringrequiredSMTP password environment variable (legacy; new installs use smtp_secret.json)crates/octos-cli/src/otp.rs:35
dashboard_auth.smtp.from_addressstringrequiredsender addresscrates/octos-cli/src/otp.rs:37
dashboard_auth.session_expiry_hoursu6424session expiry in hourscrates/octos-cli/src/otp.rs:59
dashboard_auth.allow_self_registrationboolfalseauto-create accounts for unknown emailscrates/octos-cli/src/otp.rs:62
dashboard_auth.static_tokensstring[][]static tokens that bypass OTP (for E2E)crates/octos-cli/src/otp.rs:67

The dashboard_auth.smtp block is optional as a whole (crates/octos-cli/src/otp.rs:56); when absent, OTP goes to console output.

credential_pool (crates/octos-cli/src/config.rs:415 CredentialPoolConfig)

Field pathTypeDefaultPurposeSource
credential_pool.state_pathstring?<data_dir>/credential_pool.redbpersistent state file overridecrates/octos-cli/src/config.rs:419
credential_pool.namestring"default"pool name used as a metrics labelcrates/octos-cli/src/config.rs:423
credential_pool.strategystring"round_robin"fill_first/round_robin/random/least_usedcrates/octos-cli/src/config.rs:427
credential_pool.credential_idsstring[][]credential IDs in the pool (env_vars supplies the keys at runtime)crates/octos-cli/src/config.rs:431
credential_pool.default_cooldown_msu64?nulldefault cooldown when a 429 carries no reset hintcrates/octos-cli/src/config.rs:435

appui (crates/octos-cli/src/config.rs:339 AppUiConfig) and plugins (crates/octos-cli/src/config.rs:315 PluginsConfig)

Field pathTypeDefaultPurposeSource
appui.allowed_originsstring[][]extra allowed REST/WS browser origins (exact http(s)://)crates/octos-cli/src/config.rs:348
appui.default_session_cwdpath?nullTier-2 fallback directory when an AppUI session declares no cwd capability (must be absolute)crates/octos-cli/src/config.rs:360
appui.sessions_in_cwdbooltruestore sessions by project directory (<cwd>/.octos/sessions/)crates/octos-cli/src/config.rs:388
plugins.require_signedboolfalseenforce plugin manifest.sha256 signatures (default: warn and allow)crates/octos-cli/src/config.rs:325

C.9 The mcp_servers[] section (crates/octos-agent/src/mcp.rs:53 McpServerConfig)

The field table follows; for protocol behavior (handshake, DNS anti-loopback, OAuth flow) see Chapter 9, not repeated here.

Field pathTypeDefaultPurposeSource
mcp_servers[].commandstring?nullstdio transport: command to spawncrates/octos-agent/src/mcp.rs:56
mcp_servers[].argsstring[][]stdio transport: command argumentscrates/octos-agent/src/mcp.rs:58
mcp_servers[].envmap<string,string>{}stdio transport: child process environment variablescrates/octos-agent/src/mcp.rs:60
mcp_servers[].urlstring?nullHTTP transport: server endpoint URLcrates/octos-agent/src/mcp.rs:63
mcp_servers[].headersmap<string,string>{}HTTP transport: extra headers (e.g. a static bearer); ignored when oauth is setcrates/octos-agent/src/mcp.rs:67
mcp_servers[].oauthboolfalseuse the OAuth 2.1 authorization-code flow with this server (requires url)crates/octos-agent/src/mcp.rs:72
mcp_servers[].scopesstring[][]OAuth scopes requested by octos mcp logincrates/octos-agent/src/mcp.rs:75
mcp_servers[].concurrency_classstring?null (= safe)concurrency class for all tools of this server: safe/exclusive; unknown values are treated conservatively as exclusivecrates/octos-agent/src/mcp.rs:84

Non-configurable hard limits (constants): 30s handshake timeout (crates/octos-agent/src/mcp.rs:43), 60s per tools/call (crates/octos-agent/src/mcp.rs:45), tool input schema nesting ≤10 levels (crates/octos-agent/src/mcp.rs:47), schema serialization ≤64KB (crates/octos-agent/src/mcp.rs:49).

C.10 The sub_providers[] section (crates/octos-cli/src/config.rs:618 SubProviderConfig)

Model lanes that spawned sub-agents can reference. Reserved key: goal_verifier (#1935): when present, that lane becomes a dedicated goal-completion verifier; otherwise the old behavior applies (verifying with the scoring session's own provider). Division of labor with Chapter 9: that chapter covers how the spawn tools consume these lanes; this one gives fields only.

Field pathTypeDefaultPurposeSource
sub_providers[].keystringrequiredshort key referenced by the LLM (e.g. cheap / strong / goal_verifier)crates/octos-cli/src/config.rs:620
sub_providers[].providerstringrequiredprovider namecrates/octos-cli/src/config.rs:622
sub_providers[].modelstring?nullmodel namecrates/octos-cli/src/config.rs:625
sub_providers[].api_key_envstring?provider defaultkey environment variable namecrates/octos-cli/src/config.rs:629
sub_providers[].base_urlstring?nullbase URLcrates/octos-cli/src/config.rs:632
sub_providers[].descriptionstring?nullstatement of when to use this model (goes into the spawn tool schema)crates/octos-cli/src/config.rs:636
sub_providers[].default_context_windowu32?nulldefault context budget for a sub-agent that selects this lanecrates/octos-cli/src/config.rs:642
sub_providers[].max_output_tokensu32?auto-detectedper-call max output tokens overridecrates/octos-cli/src/config.rs:647
sub_providers[].api_typestring?provider defaultprotocol overridecrates/octos-cli/src/config.rs:650

C.11 validators (declarative validators, workspace policy layer)

validators does not live in config.json: it is a subkey of the validation section in the workspace policy file .octos-workspace.toml (crates/octos-agent/src/workspace_policy.rs:13 WORKSPACE_POLICY_FILE). The top-level policy struct WorkspacePolicy is at crates/octos-agent/src/workspace_policy.rs:22; the validation section (crates/octos-agent/src/workspace_policy.rs:115 ValidationPolicy):

Field pathTypeDefaultPurposeSource
validation.on_turn_endstring[][]Tier 1: cheap checks at end of each turn (<100ms)crates/octos-agent/src/workspace_policy.rs:118
validation.on_source_changestring[][]Tier 2: mid-weight checks on source changes (1-5s)crates/octos-agent/src/workspace_policy.rs:121
validation.on_completionstring[][]Tier 3: expensive checks at completion/release (10-30s)crates/octos-agent/src/workspace_policy.rs:124
validation.validators[]array<Validator>[]typed declarative validators (M4.3)crates/octos-agent/src/workspace_policy.rs:127

Each Validator (crates/octos-agent/src/workspace_policy.rs:143):

Field pathTypeDefaultPurposeSource
validators[].idstringrequiredstable unique identifiercrates/octos-agent/src/workspace_policy.rs:145
validators[].requiredbooltruewhether a failure blocks terminal successcrates/octos-agent/src/workspace_policy.rs:149
validators[].soft_failboolfalsewhen true, failures only warn instead of downgrading (Wave-3a soft tier)crates/octos-agent/src/workspace_policy.rs:157
validators[].timeout_msu64?nullper-validator timeout (command/tool kinds)crates/octos-agent/src/workspace_policy.rs:161
validators[].phaseenum"completion"turn_end / completioncrates/octos-agent/src/workspace_policy.rs:164, enum crates/octos-agent/src/workspace_policy.rs:290
validators[].specenum (tagged kind)requiredthe validation body, see belowcrates/octos-agent/src/workspace_policy.rs:166

spec variants (crates/octos-agent/src/workspace_policy.rs:301 ValidatorSpec, serde tag kind, snake_case):

  • command: cmd (required), args (default []): subprocess command, goes through the shell safety layer (crates/octos-agent/src/workspace_policy.rs:306)
  • tool_call: tool (required), args (default {}): calls a registered agent tool (crates/octos-agent/src/workspace_policy.rs:313)
  • file_exists: path (required), min_bytes (default null): asserts the file exists / minimum bytes (crates/octos-agent/src/workspace_policy.rs:318)
  • http_probe: url_template (required), expected_status (default 200), expected_contains (default null): HTTP probe, default 5s timeout (crates/octos-agent/src/workspace_policy.rs:325)
  • ominix_voice_exists: name_arg (required): looks up a custom voice registered with ominix-api (crates/octos-agent/src/workspace_policy.rs:336)
  • audio_non_silent: glob (default ""), min_ratio (default 0.3), source (default glob mode), extension (default null): non-silent audio ratio (crates/octos-agent/src/workspace_policy.rs:344)
  • per_file_non_silent: per-file non-silent validation over whole files, with an require_at_least count (crates/octos-agent/src/workspace_policy.rs:368 vicinity)
  • magic-byte assertion MagicByteKind: mp3/wav/png/jpeg/pdf/mp4/webm/pptx (crates/octos-agent/src/workspace_policy.rs:469)

Runtime constants: default timeout 30s for command kinds (crates/octos-agent/src/validators.rs:55 DEFAULT_COMMAND_TIMEOUT_MS), default 5s for HTTP probes (crates/octos-agent/src/validators.rs:60 DEFAULT_HTTP_PROBE_TIMEOUT_MS), evidence files under <workspace_root>/.octos/validator-evidence/ (crates/octos-agent/src/validators.rs:53), each evidence item ≤512KB (crates/octos-agent/src/validators.rs:62 MAX_EVIDENCE_BYTES).

C.12 Profile system in brief

The config.llm of a profile file ~/.octos/profiles/<id>.json is a first-class structured LLM selection contract, not the flat provider/model keys of the top-level config.json. Three layers:

config.llm (crates/octos-cli/src/profiles.rs:814 LlmProfileConfig)

FieldTypeDefaultPurpose
primaryLlmModelSelectionConfig?nullprimary model selection
fallbacksarray[]fallback model chain

config.llm.primary / each fallback (crates/octos-cli/src/profiles.rs:824 LlmModelSelectionConfig, #[serde(deny_unknown_fields)])

FieldTypeDefaultPurpose
family_idstring?nullmodel family (e.g. moonshot / deepseek)
model_idstring?nullconcrete model ID (e.g. kimi-k2.5)
routeLlmRouteConfig?nullprovider route for this model
model_hintsobject?nullbehavior hints for custom/proxied models
cost_per_mf64?nulloutput price per million tokens (for routing)
strongbool?nullwhether it is reliable for large tool counts
temperaturef32?nulltyped sampling temperature (#2166, AppUI validates 0.0..=2.0)
top_pf32?nullnucleus sampling (#2166, validates 0.0..=1.0)
reasoning_effortenum?nulldefault reasoning effort for thinking models (#2166)
context_windowu32?nullcontext window override (#2135/#2142, beats probing and catalog)

config.llm.primary.route (crates/octos-cli/src/profiles.rs:881 LlmRouteConfig)

FieldTypeDefaultPurpose
route_idstring?nullstable route ID in the catalog (e.g. official / wisemodel)
labelstring?nullhuman-readable route label
base_urlstring?nullendpoint for this route
api_key_envstring?nullkey environment variable for this route
api_typestring?nullprotocol override

Three-tier inheritance (crates/octos-cli/src/profiles.rs:2403 resolve_effective_profile): when a child profile carries parent_id, the parent's LLM contract is inherited as a whole, overriding (ec.llm = pc.llm), while structural sections such as review/search/deep_crawl/apps/email/tool_policy are inherited only when the child's are empty; with no parent, the profile returns unchanged. This is the profile-side mechanism of the goal three tiers (operator default → queue → worker override); the full three-tier semantics are in Chapter 15.

A minimal usable profile JSON example (keys appear only as environment variable names, no key values):

{
  "id": "writer",
  "display_name": "Writer",
  "config": {
    "llm": {
      "primary": {
        "family_id": "deepseek",
        "model_id": "deepseek-v4-pro",
        "route": {
          "route_id": "wisemodel",
          "base_url": "https://api.wisemodel.cn/v1",
          "api_key_env": "WISEMODEL_API_KEY"
        },
        "temperature": 0.3,
        "context_window": 131072
      },
      "fallbacks": [
        {
          "family_id": "moonshot",
          "model_id": "kimi-k2.5",
          "route": { "api_key_env": "MOONSHOT_API_KEY" },
          "strong": true
        }
      ]
    },
    "memory": { "max_inject_tokens": 4000 }
  }
}

C.13 A complete config.json example (JSONC comments)

{
  // migration version, currently 1
  "version": 1,
  // primary LLM (flat keys; for serve multi-tenancy use the profile's config.llm)
  "provider": "anthropic",
  "model": "claude-sonnet-4",
  "api_key_env": "ANTHROPIC_API_KEY",
  "env_vars": {},
  "context_window": 200000,          // #2142 overrides catalog/probing
  // failover chain
  "fallback_models": [
    { "provider": "openai", "model": "gpt-4o", "strong": true, "cost_per_m": 2.5 }
  ],
  // sessions and tools
  "max_iterations": 50,
  "format_after_edit": true,         // #1774 auto-format after edits
  "context_filter": [],
  "tool_policy": { "deny": [], "allow": [] },
  "sandbox": {
    "enabled": true,
    "mode": "auto",
    "allow_network": false,
    "workspace_write": true
  },
  "snapshots": { "enabled": false, "keep_last": 20 },
  // MCP server (see C.9; protocol details in Chapter 9)
  "mcp_servers": [
    {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      "env": {},
      "concurrency_class": "safe"
    }
  ],
  // sub-agent lanes (see C.10; goal_verifier is a reserved key)
  "sub_providers": [
    { "key": "cheap", "provider": "openai", "model": "gpt-4o-mini", "api_key_env": "OPENAI_API_KEY" }
  ],
  // lifecycle hooks (C.7)
  "hooks": [
    { "event": "after_tool_call", "command": ["cargo", "check"], "timeout_ms": 5000, "tool_filter": ["edit_file"], "path_filter": [] }
  ],
  // gateway (C.3)
  "gateway": {
    "channels": [{ "type": "cli", "allowed_senders": [], "settings": {} }],
    "max_history": 50,
    "queue_mode": "collect",
    "llm_timeout_secs": 120
  },
  // adaptive routing (C.8)
  "adaptive_routing": { "enabled": false, "mode": "off" },
  // memory and embedding (C.6)
  "memory": { "max_inject_tokens": 4000, "refresh": { "enabled": true } },
  "embedding": { "provider": "openai", "model": "text-embedding-3-small", "api_key_env": "OPENAI_API_KEY" },
  // operations (C.8)
  "mode": "local",
  "allow_admin_shell": false,
  "appui": { "allowed_origins": [], "sessions_in_cwd": true },
  "plugins": { "require_signed": false },
  "cli": { "serve": { "port": 50080 } }
}

C.14 Version note

The data baseline of this appendix is octos main 9c157101 (docs(guide): document mcp_servers stdio fields, env sanitization, timeouts, #2211/#2212). Main changes from earlier baselines:

  • typed LLM schema (3a567a4c / #2166): LlmModelSelectionConfig gained temperature / top_p / reasoning_effort / context_window (#2142, split from #2127); the top-level Config mirrors them as model_temperature / model_top_p / model_reasoning_effort (crates/octos-cli/src/config.rs:56-65), forming an explicit precedence chain with gateway.llm_temperature / gateway.llm_sampling_params (#2172).
  • mcp_servers: profile-level [[mcp_servers]] registers no tools before OLP #29 S2b (comment at crates/octos-cli/src/profiles.rs:198); stdio fields, env sanitization, and timeouts documented in #2211/#2212.
  • sub_providers reserved key goal_verifier (#1935): when absent, goal completion verification falls back to the scoring session's own provider (old behavior).
  • hooks schema: the current shape is hooks[] + event + command (argv) + timeout_ms (default 5000) + tool_filter: string[], plus the newer path_filter and requires_bin.
  • queue_mode: steer renamed to latest (crates/octos-cli/src/config.rs:1507-1512, serde alias kept for compatibility).
  • snapshots (#1768), approval_policy, appui.sessions_in_cwd, plugins.require_signed, and the cli section are later additions; sandbox.write_allow_globs (#1976) and tool_policy.bash_file_writes (#28b) are recent tightenings.

Numbers and field tables from older versions of this appendix are obsolete; this appendix is authoritative.

Appendix D: Feature Flags Overview

Positioning: This appendix is the complete mapping of every Cargo feature in the octos workspace: all 79 feature definitions across 12 crates, row by row (crate, dependencies pulled in, one-line purpose, whether it is on by default, source lines), plus the 14 message channel gates with their definitions and mirrored forwarding, the default chains, and the feature propagation graph. Prerequisites: Section 14.7 of Chapter 14 (the concept of the compile-time runtime surface) and Appendix A (the feature-gated dependency annotations in A.5). When to use it: deciding which features to enable before a deployment; diagnosing "why didn't this capability get compiled in"; locating the exact touch points before adding a channel or tool to octos.

This appendix shares its source and counting rules with Chapter 14 and Appendix A: the baseline is octos main @ 9c157101, and the single data source is the repository facts table assets/appendixD-facts.md. Of the workspace's 38 members, 12 crates have a [features] section in their Cargo.toml, defining 79 features in total: 70 non-default features plus 9 explicit default lines (octos-embed-llama, octos-store, and octos-services carry no explicit default line). One command reproduces the full inventory; run it at the root of the octos source repository:

awk '/^\[features\]/{f=1;next} /^\[/{f=0} f&&/^[a-z]/' crates/*/Cargo.toml

Division of labor: Section 14.7 answers "why runtime-surface selection and capability trimming belong to two different stages"; this appendix answers "what each gate is, what it pulls in, and whether it is on by default". The two do not repeat each other; their meeting point is discussed in D.6.

D.1 Master table: all 79 features

A "yes" in the default column means the feature appears in its crate's explicit default line. The source column points to the line range of the [features] section in that crate's Cargo.toml.

cratefeaturedependencies / downstream features pulled inwhat it doesdefaultsource
octos-clidefault[]Minimal default set: no API, channels, or toolsyescrates/octos-cli/Cargo.toml:142-177
octos-cliembed-llamadep:octos-embed-llama, octos-embed-llama/embed-llamaIn-process llama.cpp GGUF embedding provider (for embedding.provider = "llamacpp"), CPU backend by defaultnocrates/octos-cli/Cargo.toml:142-177
octos-cliembed-llama-metalembed-llama, octos-embed-llama/metalAdds Apple Metal acceleration on top of embed-llamanocrates/octos-cli/Cargo.toml:142-177
octos-cliembed-llama-cudaembed-llama, octos-embed-llama/cudaAdds NVIDIA CUDA acceleration on top of embed-llamanocrates/octos-cli/Cargo.toml:142-177
octos-cliapidep:axum, dep:tower-http, dep:tokio-util, dep:futures, dep:tokio-tungstenite, dep:rustls, dep:rustls-native-certs, dep:rust-embed, dep:metrics-exporter-prometheus, dep:lettre, dep:rand, dep:sysinfo, dep:subtle, octos-bus/api, matrixREST API/dashboard/SSE/WS control plane; the serve subcommand depends on it, and without it octoscode cannot start (Command::Serve carries #[cfg(feature = "api")], crates/octos-cli/src/commands/mod.rs:398-399; the octoscode default command is octos serve --stdio --solo, octoscode/src/cli.rs:118); matrix rides along unconditionally because API handlers and the admin console reference matrix-only types such as octos_bus::MatrixInviteStorenocrates/octos-cli/Cargo.toml:142-177
octos-cliadmin-botdep:teloxide, dep:futures, apiTelegram admin bot; depends explicitly on apinocrates/octos-cli/Cargo.toml:142-177
octos-clitelegramoctos-bus/telegramTelegram channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clidiscordoctos-bus/discordDiscord channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clidingtalkoctos-bus/dingtalkDingTalk callback channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clislackoctos-bus/slackSlack WebSocket channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliwhatsappoctos-bus/whatsappWhatsApp WebSocket channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliemailoctos-bus/emailEmail (IMAP/SMTP) channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clifeishuoctos-bus/feishuFeishu channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clitwiliooctos-bus/twilioTwilio webhook channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliwecomoctos-bus/wecomWeCom callback channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-clilineoctos-bus/lineLINE webhook channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-climatrixoctos-bus/matrixMatrix channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliwecom-botoctos-bus/wecom-botWeCom Bot WebSocket channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliqq-botoctos-bus/qq-botQQ Bot WebSocket channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cliwechatoctos-bus/wechatWeChat bridge WebSocket channel gatenocrates/octos-cli/Cargo.toml:142-177
octos-cligitoctos-agent/gitGit tool capability gate (gix + similar)nocrates/octos-cli/Cargo.toml:142-177
octos-cliastoctos-agent/astAST parsing tool capability gate (tree-sitter, five languages)nocrates/octos-cli/Cargo.toml:142-177
octos-cliaudio_mp3octos-agent/audio_mp3mp3 decoding for the AudioNonSilent workspace contract validator; without it, .mp3 artifacts fail with an error suggesting audio_mp3 or a switch to .wav (crates/octos-agent/src/validators.rs:2441-2445)nocrates/octos-cli/Cargo.toml:142-177
octos-busdefault[]Pure bus core (sessions/scheduling/dedup), zero channelsyescrates/octos-bus/Cargo.toml:9-26
octos-busapiaxumBus types needed by API/SSE/WS access (ApiChannel and friends)nocrates/octos-bus/Cargo.toml:9-26
octos-bustelegramteloxideTelegramChannel implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busdiscordserenityDiscordChannel implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busdingtalkaxumDingTalkChannel callback implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busslacktokio-tungsteniteSlackChannel WS implementationnocrates/octos-bus/Cargo.toml:9-26
octos-buswhatsapptokio-tungsteniteWhatsAppChannel WS implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busfeishutokio-tungstenite, axum, rustls, rustls-native-certsFeishuChannel WS + callback implementationnocrates/octos-bus/Cargo.toml:9-26
octos-buslineaxumLineChannel webhook implementationnocrates/octos-bus/Cargo.toml:9-26
octos-bustwilioaxumTwilioChannel webhook implementationnocrates/octos-bus/Cargo.toml:9-26
octos-buswecomaxumWeComChannel callback implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busmatrixaxumMatrixChannel + MatrixUserChannel (including MatrixInviteStore) implementationnocrates/octos-bus/Cargo.toml:9-26
octos-buswecom-bottokio-tungstenite, rustls, rustls-native-certsWeComBotChannel WS implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busqq-bottokio-tungstenite, rustls, rustls-native-certsQQBotChannel WS implementationnocrates/octos-bus/Cargo.toml:9-26
octos-buswechattokio-tungsteniteWeChatChannel WS bridge implementationnocrates/octos-bus/Cargo.toml:9-26
octos-busemailasync-imap, tokio-rustls, rustls, webpki-roots, lettre, mailparseEmailChannel IMAP/SMTP implementationnocrates/octos-bus/Cargo.toml:9-26
octos-agentdefault["browser"]browser on by defaultyescrates/octos-agent/Cargo.toml:117-131
octos-agentbrowser[] (chromiumoxide compiled unconditionally)Toggles only the headless-Chrome (CDP) fallback provider of web_search; off, the HTTP-only behavior is byte-for-byte identical to the old versionyescrates/octos-agent/Cargo.toml:117-131
octos-agentgitdep:gix, dep:similarGit operations and diff capabilitynocrates/octos-agent/Cargo.toml:117-131
octos-agentastdep:tree-sitter plus the four rust/python/javascript/typescript grammarsAST code-structure analysisnocrates/octos-agent/Cargo.toml:117-131
octos-agentaudio_mp3dep:symphoniamp3 decoding for the AudioNonSilent validator (WAV goes through the always-on hound)nocrates/octos-agent/Cargo.toml:117-131
octos-serverdefault[]Minimal server libraryyescrates/octos-server/Cargo.toml:46-81
octos-serverapidependency list identical to octos-cli api (13 optional dependencies plus octos-bus/api and matrix)HTTP/WS API layer, mirroring octos-cli api; matrix is mandatory (handlers reference matrix types)nocrates/octos-server/Cargo.toml:46-81
octos-servertelegramoctos-bus/telegramchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverdiscordoctos-bus/discordchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverdingtalkoctos-bus/dingtalkchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverslackoctos-bus/slackchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverwhatsappoctos-bus/whatsappchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serveremailoctos-bus/emailchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverfeishuoctos-bus/feishuchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-servertwiliooctos-bus/twiliochannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverwecomoctos-bus/wecomchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverlineoctos-bus/linechannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-servermatrixoctos-bus/matrixchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverwecom-botoctos-bus/wecom-botchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverqq-botoctos-bus/qq-botchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-serverwechatoctos-bus/wechatchannel gate forwardingnocrates/octos-server/Cargo.toml:46-81
octos-embed-llamaembed-llamadep:llama-cpp-2, dep:self_cellCompiles llama.cpp from source (CMake plus a C++ toolchain) for in-process GGUF embeddings; without it the crate is nearly emptynocrates/octos-embed-llama/Cargo.toml:14-20
octos-embed-llamametalllama-cpp-2/metalApple Metal accelerationnocrates/octos-embed-llama/Cargo.toml:14-20
octos-embed-llamacudallama-cpp-2/cudaNVIDIA CUDA accelerationnocrates/octos-embed-llama/Cargo.toml:14-20
octos-ffidefault[]Keeps the FFI surface pure Rustyescrates/octos-ffi/Cargo.toml:37-47
octos-ffiembed-llamadep:octos-embed-llama, octos-embed-llama/embed-llamaCompiles the GGUF backend into octos_embed; otherwise it reports embedding support not compiled innocrates/octos-ffi/Cargo.toml:37-47
octos-ffiembed-llama-metalembed-llama, octos-embed-llama/metalMetal acceleration on the FFI sidenocrates/octos-ffi/Cargo.toml:37-47
octos-ffiembed-llama-cudaembed-llama, octos-embed-llama/cudaCUDA acceleration on the FFI sidenocrates/octos-ffi/Cargo.toml:37-47
octos-uniffidefault[]Keeps the uniffi bindings pure Rustyescrates/octos-uniffi/Cargo.toml:36-42
octos-uniffiembed-llamaoctos-ffi/embed-llamaForwards Runtime::embed through ffi; otherwise returns NoEmbeddernocrates/octos-uniffi/Cargo.toml:36-42
octos-pyo3default[]Keeps cargo build --workspace unbroken on Python-less CIyescrates/octos-pyo3/Cargo.toml:42-52
octos-pyo3pythondep:pyo3Compiles the pyo3 surface (pulls libpython)nocrates/octos-pyo3/Cargo.toml:42-52
octos-pyo3extension-modulepython, pyo3/extension-moduleWheel builds: python plus no libpython linking (the host interpreter resolves symbols)nocrates/octos-pyo3/Cargo.toml:42-52
octos-pyo3embed-llamaoctos-ffi/embed-llamaRuntime.embed returns real vectors instead of NoEmbeddernocrates/octos-pyo3/Cargo.toml:42-52
octos-diagnosticsdefault[]Stage 1 with zero network dependenciesyescrates/octos-diagnostics/Cargo.toml:22-26
octos-diagnosticsgithubdep:reqwest (workspace-pinned, rustls-tls)GitHub Releases client for update --check (Stage 2; self-update is Stage 3, not here)nocrates/octos-diagnostics/Cargo.toml:22-26
octos-llmdefault[]Production builds expose no test surfaceyescrates/octos-llm/Cargo.toml:9-15
octos-llmtest-utils[]Exposes test helpers such as AdaptiveRouter::publish_failover_for_subscribers; keep off in productionnocrates/octos-llm/Cargo.toml:9-15
octos-storetest-util[]Exposes test helpers such as approvals_audit::read_audit_lines; keep off in productionno (no explicit default line)crates/octos-store/Cargo.toml:26-30
octos-servicestest-util[]Exposes the crate-level env-test lock config_context::TEST_ENV_LOCK for serializing downstream tests; keep off in productionno (no explicit default line)crates/octos-services/Cargo.toml:26-31

Per-crate counts for the master table: octos-cli 23, octos-bus 16, octos-server 16, octos-agent 5, octos-embed-llama 3, octos-ffi 4, octos-uniffi 2, octos-pyo3 4, octos-diagnostics 2, octos-llm 2, octos-store 1, octos-services 1, totaling 79. The spec facts boundary for octos-cli previously listed 22 features (without audio_mp3); the current measurement takes 23, with audio_mp3 (crates/octos-cli/Cargo.toml:177) added after the boundary was set.

D.2 A guided tour of the twelve crates

Grouping the 79 features by crate reveals a clear layering discipline. The first group is the two entry points. octos-cli tops the workspace with 23 features, yet it implements almost none of the channels or tools itself: the 14 channel gates forward one by one to octos-bus, the three tool gates git, ast, and audio_mp3 forward to octos-agent, and the embed-llama trio forwards to octos-embed-llama. The one heavyweight gate that unfolds inside the crate is api, which pulls in 13 optional dependencies and drags two downstream gates along: octos-bus/api and matrix. octos-server is cli's library-level mirror: its 16 features share names and meanings with cli's, with api and the 14 channel gates each forwarding a copy, so host programs that bypass the CLI reuse the same assembly.

The second group is the runtime and the bus. Of octos-bus's 16 features, everything except default and api is a channel implementation body: network stacks such as teloxide, serenity, tokio-tungstenite, and async-imap enter compilation only when their channel gate is on; the default build contains no chat protocol stack at all. octos-agent has only 5 features but is the only business crate with a non-empty default: default = ["browser"] makes the headless-Chrome fallback the default behavior, while the browser gate itself adds and removes no dependency. chromiumoxide is compiled unconditionally; the gate only decides whether web_search uses it.

The third group is the embedding chain and the binding chain, five crates in all. octos-embed-llama's 3 features all revolve around llama.cpp: the base gate compiles C++ from source, while metal and cuda are backend overlay switches. octos-ffi's 4 features decide whether the FFI surface has GGUF embedding; octos-uniffi and octos-pyo3 each hold one embed-llama, proxying layer by layer to octos-ffi, and return NoEmbedder when it is off. The last group is four small crates: octos-diagnostics uses the github gate to keep reqwest, needed only for the Releases check, out of the default build; octos-llm's test-utils and octos-store's and octos-services' test-util are pure test surfaces, kept off in production builds; and the three crates embed-llama, store, and services have no explicit default line, zero features being their normal state.

D.3 Channel gates: one definition, two forwards

octos-bus is the single definition point of the 14 channel gates (crates/octos-bus/Cargo.toml:9-26), and runtime exports map to the gates one to one: crates/octos-bus/src/lib.rs:17-49 gates type exports feature by feature with #[cfg], and crates/octos-bus/src/lib.rs:71-107 gates the mod declarations, aligning one to one with the 14 channels (the file's cfg(feature hits 33 places: 17 type-export lines plus 16 mod lines, with the api gate one short on non-mod lines). octos-cli (crates/octos-cli/Cargo.toml:142-177) and octos-server (crates/octos-server/Cargo.toml:46-81) each forward the 14 gates once more: CLI for binary builds, server for library-level reuse, so a gateway runtime can dispatch channels without going through the HTTP api layer.

channel gatedependencies pulled in by octos-busaccess shape
telegramteloxideBot API
discordserenityBot API
dingtalkaxumcallback
slacktokio-tungsteniteWebSocket
whatsapptokio-tungsteniteWebSocket
emailasync-imap, tokio-rustls, rustls, webpki-roots, lettre, mailparseIMAP/SMTP
feishutokio-tungstenite, axum, rustls, rustls-native-certsWebSocket plus callback
twilioaxumwebhook
wecomaxumcallback
lineaxumwebhook
matrixaxumwebhook plus MatrixInviteStore
wecom-bottokio-tungstenite, rustls, rustls-native-certsWebSocket
qq-bottokio-tungstenite, rustls, rustls-native-certsWebSocket
wechattokio-tungsteniteWebSocket bridge

Three similarly named gates are easy to confuse: wecom and wecom-bot are two separate implementations (callback versus WebSocket), qq-bot is QQ's WebSocket implementation, and wechat is WeChat's WebSocket bridge. Each has a same-named forwarding gate in both cli and server; a channel counts as open only when the switch agrees in all three places.

D.4 The default chains: one counterintuitive default and two proxy chains

Of the workspace's 9 explicit default lines, 8 are default = [] (minimal set). The one non-empty case is octos-agent's default = ["browser"] (crates/octos-agent/Cargo.toml:117-131). The counterintuitive part: chromiumoxide is not gated and is always compiled; the browser gate only decides whether web_search falls back to headless Chrome after HTTP retrieval fails. To get pure HTTP behavior you must turn it off explicitly with default-features = false when depending on octos-agent, rather than assuming "no feature enabled means no browser code".

The embedding chain has four hops from outside in. The first hop sits in octos-cli and octos-ffi: both embed-llama features point at octos-embed-llama/embed-llama, which is what actually pulls in llama-cpp-2 and self_cell and requires CMake and a C++ toolchain on the build machine; metal and cuda are backend overlays on top, which is why embed-llama-metal and embed-llama-cuda both imply embed-llama. The second hop is octos-ffi's mirror trio, copying the same switches onto the FFI surface. The third and fourth hops are octos-uniffi's and octos-pyo3's single embed-llama each: neither touches llama.cpp directly, they only forward the switch to octos-ffi. If any layer is off, Runtime.embed returns NoEmbedder instead of a vector.

D.5 Feature propagation

flowchart LR
    subgraph CLI["octos-cli"]
      API["api"]
      CH["14 channel gates<br/>telegram discord dingtalk slack whatsapp<br/>email feishu twilio wecom line matrix<br/>wecom-bot qq-bot wechat"]
      TOOL["git / ast / audio_mp3"]
      EMB["embed-llama / -metal / -cuda"]
      AB["admin-bot"]
    end
    subgraph BUS["octos-bus"]
      BAPI["api = axum"]
      BCH["same-named channel gates = per-channel dependencies"]
    end
    subgraph AGENT["octos-agent"]
      AG["git = gix + similar<br/>ast = tree-sitter x5<br/>audio_mp3 = symphonia<br/>browser on by default"]
    end
    EL["octos-embed-llama<br/>embed-llama / metal / cuda"]
    API -->|octos-bus/api plus matrix| BAPI
    CH -->|octos-bus same-named gates| BCH
    API -->|drags in the matrix gate| BCH
    TOOL --> AG
    EMB --> EL
    AB -->|dep:teloxide plus api| API

Three layers: octos-cli is the only binary entry; channel and tool features all forward to octos-bus and octos-agent (consistent with Section 14.7's "CLI only forwards features"); octos-server's api and 14 channel gates mirror the same forwarding for library-level reuse. Three implicit dependency edges in the graph are worth memorizing: api drags in octos-bus/api and matrix; admin-bot depends explicitly on api; embed-llama-metal and embed-llama-cuda both imply embed-llama. Missing an implicit edge is a common source of feature-trimming mistakes: turning off matrix without turning off api does not work, because the API layer's handlers reference matrix-only types.

D.6 Division of labor with Section 14.7 of Chapter 14

Section 14.7 covers the two-layer relationship: runtime-surface selection happens at runtime (subcommand dispatch), capability trimming at compile time (feature gates), with three cli-side examples (api, channel gates, embed-llama) and the compile gate of the serve subcommand. This appendix does not repeat those arguments; it supplies the full data: 79 definitions, the dependency details of the 14 gates, the default chains, and the propagation graph. For "which gates should be on for a given runtime surface", see Section 14.7 and Chapter 13; for "what a gate pulls in and whether it is on by default", see D.1 here; for "the version and owning crate of a gated dependency", see A.5 of Appendix A.

D.7 Crates without [features]: 26

The remaining 26 top-level entries have no [features] section in their Cargo.toml; their compile surface is fixed, with no gates to open:

  • Core libraries (11): octos-core, octos-memory, octos-workflows, octos-pipeline, octos-plugin, octos-sandbox, octos-swarm, octos-fleet, octos-fleet-worker, octos-dora-mcp, octos-wasm (the Cargo.toml of the same-named directories under crates/).
  • App skills (14): news, deep-search, deep-crawl, send-email, account-manager, time, weather, smart-home, wechat-bridge, skill-evolve, harness-starter-generic, harness-starter-report, harness-starter-audio, harness-starter-coding (the Cargo.toml of the same-named directories under crates/app-skills/).
  • Platform skills (1): voice (crates/platform-skills/voice/Cargo.toml).

Capability binaries are not trimmed through Cargo features; they manage their distribution boundary with workspace members and skill manifests (see Chapter 9). Readers who previously debugged this list, note: the old draft counted 19 entries including the since-removed pipeline-guard; this edition re-lists them from the 9c157101 measurement.

D.8 Build examples

# Minimal CLI: no API, channel integrations, or Git/AST tools
cargo build -p octos-cli --release

# CLI + Web API / dashboard (the serve subcommand becomes usable)
cargo build -p octos-cli --release --features api

# API + admin bot
cargo build -p octos-cli --release --features admin-bot

# A common gateway multi-channel combination
cargo build -p octos-cli --release --features "telegram,slack,email,feishu,wecom-bot,qq-bot,wechat"

# Let the AudioNonSilent validator accept .mp3 (effective via octos-agent/audio_mp3)
cargo build -p octos-cli --release --features audio_mp3

Further reading

  • The official Cargo features documentation: https://doc.rust-lang.org/cargo/reference/features.html — unified inference rules for optional dependencies and features, to read against the dependency column of D.1.
  • Section 14.7 of Chapter 14: the two-layer relationship between the compile-time and runtime surfaces.
  • Section A.5 of Appendix A: the full annotation of feature-gated external dependencies (50 entries) and the gate design of three crates.
  • Appendix C: configuration field reference, for the runtime configuration that follows once a feature gate is open.

Exercises

  1. octos-agent's default = ["browser"] compiles chromiumoxide unconditionally and uses the browser gate only to switch behavior. If chromiumoxide became a truly gated dependency, how would the default build's dependency tree and semantics each change? Which approach better fits "a gate is a dependency boundary"?
  2. api dragging in matrix is an implicit edge hard-coded in Cargo.toml. If the API layer had to compile without matrix, what would the code pay (handler splitting, type abstraction), and would it be worth it?
  3. octos-server mirrors the 14 channel gates with its own forwarding. Imagine deleting server's channel gates and requiring host programs to depend on octos-bus directly to open them: what would happen to the assembly code? That explains what "mirrored forwarding" buys.
  4. The three test-surface gates (octos-llm's test-utils, octos-store's and octos-services' test-util) all rely on discipline to stay off. Could a Cargo mechanism (say, doc(sqrt) or a feature naming convention) make accidental enabling in production builds harder?

Version note

This appendix analyzes octos main @ 9c157101 (full hash 9c1571016e5ea86955b4b3486c04f0359dfff339, committed 2026-09-02, measured 2026-09-03); every number (79 features, 12 crates, 14 channel gates, 26 feature-less entries) comes from assets/appendixD-facts.md, with reproduction commands recorded alongside the data.

Relative to the v1 draft, this appendix makes three classes of updates. First, coverage grows from 3 crates to 12: octos-diagnostics, octos-llm, octos-store, octos-services, octos-ffi, octos-uniffi, octos-pyo3, octos-server, and octos-embed-llama, nine crates with features, are added; the old draft's feature list contained none of them. Second, fact corrections: octos-cli gains six missing entries, embed-llama, embed-llama-metal, embed-llama-cuda, dingtalk, line, and audio_mp3 (23 features against the old draft's 17); octos-agent's browser and default = ["browser"] are added; the "crates without [features]" list drops the since-removed pipeline-guard, adds octos-fleet, octos-fleet-worker, and octos-workflows, and moves octos-diagnostics back to the feature side. Third, structural completion: a dedicated section on the 14 channel gates, default-chain notes, and a propagation graph are new, and the api row now states the serve subcommand dependency (crates/octos-cli/src/commands/mod.rs:398-399).

Appendix E: Building from Source and Contributing

This appendix is for contributors who want to modify octos directly from source. It reflects the current ../octos main branch and aligns with the root Cargo.toml, the Build & Test Commands in CLAUDE.md, the source-build notes in README, and the CI sharding strategy in .github/workflows/ci.yml.

Environment Requirements

ToolRequirementNotes
Rust≥ 1.85.0Root Cargo.toml rust-version
Edition2024Workspace edition in root Cargo.toml
Cargo resolver2Workspace uses resolver v2
Git2.x+clone, branch, commit
Node.js / npmOnly for dashboard changesscripts/build-dashboard.sh builds the embedded admin SPA
Chrome / ChromiumOnly for browser/deep-crawl workCDP/browser tools and the deep-crawl skill use it

The current repository has no rust-toolchain.toml, so do not assume automatic toolchain pinning. Your local Rust toolchain must at least satisfy rust-version = "1.85.0".

Minimal Build Path

# 1. Clone
git clone https://github.com/octos-org/octos.git
cd octos

# 2. Check the toolchain
rustc --version
cargo --version

# 3. Build the whole workspace
cargo build --workspace

# 4. Run workspace tests
cargo test --workspace

# 5. Format and lint
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings

These commands match CLAUDE.md and the baseline CI checks. cargo build --workspace builds workspace members but does not automatically enable octos-cli/api. To run octos serve, build or install the CLI with the api feature enabled.

Local CLI Install

The README and CLAUDE.md currently recommend this local install command:

cargo install --path crates/octos-cli \
    --features "api,telegram,discord,whatsapp,feishu,twilio,wecom,wecom-bot"

This is the repository's canonical default install set:

  1. api is required by octos serve; a binary without api is missing serve-related capability.
  2. Channel features compile only the transports you select, so remove channels you do not need.
  3. This command only installs the CLI into ~/.cargo/bin; it does not rebuild the dashboard or replace a system service installed by install.sh.

For local chat/serve only, this smaller install is enough:

cargo install --path crates/octos-cli --features api

If you changed the dashboard or need to validate the full installer flow, use the local bundle script described in the README:

./scripts/build-local-bundle.sh --install
./scripts/build-local-bundle.sh --install --tunnel
./scripts/build-local-bundle.sh --skip-dashboard

build-local-bundle.sh calls scripts/build-dashboard.sh, delegates the release build to scripts/milestone-ci.sh release-bundle to reuse the release FEATURES / SKILL_CRATES set, and produces a local tarball that install.sh can consume.

CI-Equivalent Test Matrix

Current CI does not rely on one large cargo test --workspace --all-features. To control memory and link pressure, heavy crates are split into dedicated jobs. Local contributors can use the same structure to narrow failures:

ScenarioCommand
Format checkcargo fmt --all -- --check
Clippycargo clippy --workspace --all-targets -- -D warnings
Full workspace buildcargo build --workspace
Compile test binaries onlycargo test --workspace --no-run
Core typescargo test -p octos-core
Memory systemcargo test -p octos-memory
LLM lib testscargo test -p octos-llm --lib
LLM integration testscargo test -p octos-llm --tests
Message buscargo test -p octos-bus
Pipelinecargo test -p octos-pipeline
Plugin SDKcargo test -p octos-plugin
Swarmcargo test -p octos-swarm
Agent libcargo test -p octos-agent --lib
Agent integrationcargo test -p octos-agent --tests
CLI libcargo test -p octos-cli --lib
CLI integrationcargo test -p octos-cli --tests
CLI API authcargo test -p octos-cli --features api api::auth_handlers
Gateway runtimecargo test -p octos-cli gateway_runtime::tests --features api -- --nocapture
Harness starter skillscargo test -p harness-starter-generic and the other three starter crates
Doc testscargo test --workspace --doc

For a single failing test, prefer a narrow selector first:

cargo test -p octos-agent test_name -- --nocapture
cargo test -p octos-cli gateway_runtime::tests --features api -- --nocapture

Code Conventions

Rust And Lints

  • Workspace edition: 2024
  • Minimum Rust: 1.85.0
  • Workspace lint: unsafe_code = "deny"
  • Formatting: cargo fmt --all
  • Lint gate: cargo clippy --workspace --all-targets -- -D warnings

Error Handling

  • The project uses eyre / color-eyre; do not introduce anyhow.
  • Library functions commonly return eyre::Result<T>; CLI binaries initialize color_eyre::install().
  • Avoid unexplained .unwrap() calls. If a value is an invariant, use .expect("...") and state the invariant.

Concurrency And Platform Boundaries

  • Async code uses Tokio; shared trait objects commonly use Arc<dyn Trait>.
  • Shutdown signaling uses AtomicBool; keep store/load ordering semantics consistent.
  • Cross-platform command execution must account for Unix sh -c and Windows cmd /C.
  • Security-sensitive paths must reuse existing sandbox, SSRF, symlink-safe I/O, and environment-sanitization code instead of bypassing shared implementations.

Test Placement

  • Prefer inline unit tests in #[cfg(test)] mod tests.
  • Put integration tests under each crate's tests/ directory.
  • Tests requiring external services should use #[ignore] or a clear environment-variable gate.
  • Use tempfile for temporary directories; do not write to a user's real home directory or fixed system paths.

TDD Workflow

CLAUDE.md requires code changes to follow RED → GREEN → REFACTOR:

  1. RED: Write a failing test that exposes the behavior; use names like should_<expected>_when_<condition>.
  2. GREEN: Implement the smallest change that passes the target test.
  3. REFACTOR: Clean up under test coverage, then run the relevant crate tests and CI subset.

In practice, do not start with full CI. Use the smallest selector first, then expand:

cargo test -p octos-core should_do_x_when_y
cargo test -p octos-agent --lib
cargo test -p octos-agent --tests
cargo clippy --workspace --all-targets -- -D warnings

Pull Request Guide

Branch Names

feature/add-wechat-channel
fix/ssrf-ipv6-bypass
refactor/tool-registry-lru
docs/update-feature-flags
test/add-gateway-regression

Commit Message

Prefer conventional commit style:

feat(bus): add WeChat channel integration

- Implement WeChatChannel with encryption support
- Add message coalescing for channel limits
- Include session fork handling

Common types include feat, fix, refactor, docs, test, and chore. Before submitting, confirm:

  1. The diff only contains changes related to the task.
  2. Tests matching the change scope have been run.
  3. Documentation, specs, example config, and code behavior agree.
  4. Security-sensitive changes include dedicated tests or clear review notes.

Project Structure Quick Reference

octos/
├── Cargo.toml                 # Workspace: 26 members, Rust 2024, rust-version 1.85.0
├── crates/
│   ├── octos-core/            # Core types and UTF-8 helpers
│   ├── octos-llm/             # LLM providers, failover, adaptive routing, credential pool
│   ├── octos-memory/          # episodic memory, MEMORY.md, hybrid search
│   ├── octos-agent/           # agent loop, tools, sandbox, MCP, plugins, hooks
│   ├── octos-bus/             # sessions, channels, coalescing, cron, heartbeat
│   ├── octos-cli/             # CLI, config, serve/gateway, profiles, auth, monitor
│   ├── octos-pipeline/        # DOT workflow engine
│   ├── octos-plugin/          # plugin/skill manifest and gating
│   ├── octos-swarm/           # swarm orchestration primitive
│   ├── octos-dora-mcp/        # Dora-RS to MCP tool bridge
│   ├── octos-sandbox/         # Windows AppContainer helper
│   ├── app-skills/            # news, deep-search, deep-crawl, send-email, harness starters, etc.
│   └── platform-skills/voice/ # voice platform skill
├── dashboard/                 # admin dashboard frontend
├── scripts/                   # install, bundle, release, dashboard build scripts
├── docs/                      # user documentation
└── .github/workflows/         # CI, release, platform build workflows

Appendix F: OLP v2 Protocol Cheat Sheet

Positioning: This appendix is the one-page cheat sheet for OLP (the octos outer-loop protocol, OctoLoop, current version olp/v2): the R-series rules, the ACK grammar, result.md frontmatter, the blackboard entry format, outer-loop onboarding and the post-restart checklist, fifth-channel parameters, and lane templates. Why the protocol is designed this way, the full carrier landscape, and the empirical analysis are in Chapter 20 and are not repeated here. This appendix does exactly one thing: it compresses the executable rules scattered across the protocol docs, the onboarding card, and the source into tables you can check against directly, each row carrying its source path and line numbers so every claim can be re-verified.

Terminology, defined once here and used without comment below: the outer loop (outer agent) is the external strong model that joins as planner, monitor, reviewer, and advisor; the inner loop (runtime) is the master/peers execution body driven by octos serve; the operator is the human; the blackboard is the Active section of each repo's .octos/OUTER_LOOP_REVIEW.md, the authoritative carrier of task-level guidance; the fifth channel is the MCP channel through which the inner loop questions the outer loop mid-turn. Data baseline: octoscode repo main @ 1129fa33.

Guide: F.1 is the R-series quick reference in R1-to-R7 order (R4b rides along as an R4 subclause); F.2 gives the ACK grammar and the rules for writing blackboard entries; F.3 is the six-field table for result.md frontmatter v1; F.4 is the outer-loop onboarding flow plus the hard checklist for the walk-through after an inner-loop restart; F.5 covers the fifth channel's parameters, anti-abuse constants, and the sub_providers lane templates. Suggested use: walk F.4 in order before your first shift as an outer loop; check F.2's entry elements before writing guidance; when reviewing a delivery, validate frontmatter against F.3 and re-check verification claims with R2 in F.1; consult F.5's pairing matrix when picking a model tier for a task.

F.1 R-Series Rules Quick Reference

RuleKey semanticsSource lines
R1 ACK dutyEvery item in the blackboard Active section must gain an ACK line under the entry once the inner loop has acted on it; no ACK counts as unread and the outer loop may return the delivery. Since v1 the grammar is pinned by the contract test olp_ack_lines_match_v1_grammaroctoscode/docs/OUTER_LOOP_PROTOCOL.md:52-58
R2 honest verification claimsEvery delivery must claim one of three verification levels: verified (ran cargo test --all-targets + clippy + fmt), partially-verified (list what ran), unverified (say why); a verified claim that fails re-verification is a protocol violation, returned and recorded on the blackboardsame, :67-70
R3 escalation tiersEscalation has three tiers: inner-loop self-resolution (retry, different approach) → outer-loop ruling (technical tradeoffs, plan approval) → operator ruling (permission approval, scope change, external action); the outer loop never approves on the operator's behalf, and an escalation stays parked while the operator is absentsame, :71-73
R4 workspace coexistenceMultiple writers each git add only the files they changed; git add -A is forbidden; every change lands as an atomic commit; dirty files of unknown origin must be preserved and reported, never auto-cleaned or committedsame, :74-76
R4b tree sovereignty and auto-fencingWith multiple goals in flight the main worktree belongs to exactly one goal: when a collision predicate hits (more than one active goal / a peer's target branch disagreeing with the main tree / the main tree holding an unfenced in-flight peer), a worktree fence opens automatically; the main-tree owner is persisted into the goal-ledger, and a non-owner session is always refused a cross-branch checkout on the main tree; collision protection is the system default, and outer-loop steer only patches the edges. Recorded as an R4 subclause, no protocol version bumpsame, :77-88
R5 guidance idempotenceOuter-loop items carry a date and a unique number and are actionable only in Active; once ACKed they move to the history section and are never replayed; duplicate delivery is deduplicated by the ACKsame, :89-90
R6 version negotiationThe protocol doc header carries protocol: olp/vN; AGENTS.md references the same version; any change to channel semantics must bump the versionsame, :103-104
R7 lead-review OS exclusive lockWith multiple outer loops, lead-review authority is held by a per-project, session-lifetime OS lock: going on shift requires starting wrapped in octoscode outer-duty hold --project P --signature S --duties D -- <agent>; the lock is the authority; check only observes and never seizes; takeover of a live lock belongs to the operator alone (terminate the old holder, then acquire), with no agent self-service seizure; the metadata sidecar and every TTL are diagnostic only and never decide; Linux-only (non-Linux platforms exit 2 with an explicit unsupported error; Windows LockFileEx is a separate item), NFS excluded. Added in v2 (#38-r1)same, :91-102

The source document orders these R1, R2, R3, R4, R4b, R5, R7, R6 (R7 sits before R6); this table re-sorts by number so the line numbers trace straight back.

F.2 ACK Grammar and Blackboard Entry Format

ACK grammar (since v1, the ACK line is written under the blackboard entry the inner loop has just executed):

ACK(done|wontdo|blocked): <说明>

Source: octoscode/docs/OUTER_LOOP_PROTOCOL.md:56-58.

GrammarSemanticsExplanation field requirementsSource lines
ACK(done): …ExecutedWhat was done and the evidence (commit hash / test results)same, :60
ACK(wontdo): …A reasoned objection; not executedWhy it will not be done; disagreement rule: the outer loop can only accept a wontdo or escalate to the operator, and may not return the same item a second timesame, :61-62
ACK(blocked): …Blocked, cannot executeThe blocking cause and what would unblock itsame, :63

Scope: the v1 grammar binds only ACK lines written on or after 2026-08-24; historical lines are not rewritten and are exempted by the contract test's effective-date boundary; the explanation is free text, it only has to be non-empty (same, :65-66).

Blackboard entry rules (source: octoscode/docs/OLP_OUTER_BOOT.md §1):

ElementRuleSource lines
Board locationOne board per repo at <repo>/.octos/OUTER_LOOP_REVIEW.md; the same-named file under docs/ is a frozen snapshot and must never be writtenoctoscode/docs/OLP_OUTER_BOOT.md:36-37
Write pathAlways through the atomic append helper scripts/olp-board-append.sh <board-path> (body fed on stdin), flock mutual exclusion plus self-write registrationsame, :38-41
NumberingFirst grep -oE '^### [0-9]+' <board> | tail -1 for the current maximum number, then use the next onesame, :42
Entry contentSelf-contained: context, exact files and line numbers, fix direction, acceptance criteria, branch name (based on main)same, :43-44
Budget tierRevision 5-10M / slice 10-20M / campaign 30-50M, stated in the entrysame, :44
Push disciplineThe entry states "commit only, never push; the lead reviewer pushes after re-verification"same, :45

F.3 result.md Frontmatter v1: The Six Fields

peers/<slug>/result.md is the inner loop's per-turn deliverable to the outer loop; since v1 its YAML frontmatter must contain exactly six fields, with the list pinned by the contract test olp_result_schema_fields_documented (source: octoscode/docs/OUTER_LOOP_PROTOCOL.md:354-358).

FieldTypeMeaningSource lines
slugstringThe peer's unique identifier (directory name)same, :362
outcomestringDelivery outcome, one of complete / partial / blocked / failedsame, :363
updated_unixintegerUnix timestamp (seconds) of the most recent updatesame, :364
turnintegerNumber of turns this peer has runsame, :365
verifiedstringR2 verification level: verified / partially-verified / unverifiedsame, :366
protocolstringProtocol version in force when writing, currently olp/v2same, :367

Consumer side: unknown fields must be ignored (forward compatibility); consumers read exactly the six fields above and neither interpret nor error on anything else; verified and protocol are written by the octos side (same, :369-373).

F.4 Outer-Loop Onboarding and the Restart Hard Checklist

Onboarding flow (data sources: octoscode/docs/OLP_OUTER_BOOT.md and the OUTER_LOOP_PROTOCOL.md access checklist):

StepContentSource lines
SignaturePick a signature outer(<name>); every blackboard write must carry it; with multiple outer loops in play each entry has exactly one lead reviewer, others may only sign annotations, and disagreements escalate to the operatoroctoscode/docs/OLP_OUTER_BOOT.md:10-14
Take the lead-review lockStart wrapped in octoscode outer-duty hold --project <project> --signature <signature> --duties <duties> -- <agent start command>; check only observes, and its stdout is exactly one of VACANT/Held/ERRORsame, :74-81
Fix the data root and tail the logsData root ~/.octos/instances/<cwd-hash>/profiles/<profile>/data; tail the serve log filtered on peer-goal:|escalation|transitioned goal|ERROR; observation splits into delivery, consumption, and execution layers, and watching one layer alone guarantees a misreadoctoscode/docs/OUTER_LOOP_PROTOCOL.md:126-134
Read the protocol and the boardRead the full protocol and the blackboard Active section for current guidance; the history section is for audit onlysame, :135-136

The outer loop's hard checklist after an inner-loop restart, four steps checked item by item; "note it and patch it later" is forbidden (source: octoscode/docs/OLP_OUTER_BOOT.md:16-19):

StepContentSource lines
1. serve upThe operator runs it personally; starting serve without a sandbox is a trust decision and is never delegated to an agentsame, :20-21
2. /loop resume is the outer loop's to runFirst /loop list for the id, then /loop resume <id>; a bare resume without an id is refused. While the maintenance heartbeat is paused the main machinery is still healthy, and the crippled fallback stays invisible until this walk-through finds itsame, :22-27
3. Mount both sentinelsThe positive sentinel (ACK lines landing on the board) plus the negative sentinel (goal_transition blocked and escalation in events.jsonl); watching only the positive signal makes a fused goal's silence indistinguishable from "still working"same, :28-30
4. Verify fallbacks and the session snapshotFallbacks are configured and the new session has taken its snapshot; changing config without a restart is paper insurance, because the tool table is snapshotted when the session is built and never backfilledsame, :31-32

F.5 Fifth-Channel Parameters and Lane Templates

The fifth channel is served by the octoscode olp-mcp-serve subcommand (a pure Rust standard-library implementation since #31, source file octoscode/src/olp_mcp.rs, 406 lines total). It exposes exactly two MCP tools, letting the inner loop question the outer loop synchronously mid-turn or land a report on the board directly. The tool registry is at octoscode/src/olp_mcp.rs:328-352.

ask_outer parameters (all three required; the required declaration sits at octoscode/src/olp_mcp.rs:340):

ParameterMeaningValidationSource lines
questionThe question for the outer loopRejected outright if emptysame, :197-198
contextWhere you are stuck, relevant stateNo extra validationsame, :183, :336
triedWhat you already tried on your ownRejected if empty (anti-outsourcing of thought: try first, then ask)same, :186-188, :32

Anti-abuse constants and behavior:

ItemValueBehaviorSource lines
Timeout90 seconds (ASK_TIMEOUT_SECS)On timeout returns a degraded directive: proceed on the blackboard's existing guidance, and if you cannot proceed, close with ACK(blocked) noting the inquiry idsame, :25, :30, :248-251
Quota3 per slice (ASK_QUOTA_PER_SLICE)Beyond quota returns a refusal telling you to proceed on your own or switch to report_blockedsame, :27, :31, :193-195
Poll interval0.5 seconds (ASK_POLL_INTERVAL_SECS)The polling cadence for the answer filesame, :26
MailboxUnder ~/.octos/outer/mcp/, a questions / answers / consumed three-stage flowOnce the answer is taken, the pair is archived to consumed and the originals deletedsame, :109-111, :231-241
AuditWritten to OUTER_LOOP_MCP.md with the fixed signature MCP(ask_outer)Full trailsame, :24, :28

report_blocked parameters: reason (why blocked) and needs (what would unblock), both required, empty reason refused; it lands on the board directly, with no mailbox round-trip (same, :255-272, :344-352).

The sub_providers lane templates (v1 ships out-of-the-box templates, pinned by the contract test olp_lane_template_parses; source: octoscode/docs/OUTER_LOOP_PROTOCOL.md:375-391):

Lanemodeldescription highlightsSource lines
cheapkimi/kimi-k2-turboLow cost, high throughput: mechanical, low-risk, strongly rollback-able tasks (docs, test triage, log classification, formatting); the cost of getting it wrong is one re-runsame, :384-386
stronganthropic/claude-opusLong reasoning chains and cross-file architecture judgment (review grading, wontdo re-checks, multi-step debugging); getting it wrong pollutes the mainline judgmentsame, :388-390

Dual-loop pairing matrix (same, :393-400):

Work typeLane
Analysis (reading code, writing summaries, classification inventories)cheap
Verification (running tests, re-checking R2 claims, mechanical assertions)cheap
Implementation (production code, contract tests, schema changes)primary (the main tier, no routing)
keeper (goal advancement, ledger bookkeeping, state judgment)primary

Why the matrix splits this way: analysis and verification output is caught by the outer review layer, so a mistake costs a re-run; implementation and keeper output goes straight into the mainline and the ledger, where errors are expensive, so they stay on the primary tier with quality held by R2 and the outer review (same, :402-403).

F.6 End-to-End Traces (Across the Whole Book)

The first five sections are the protocol-side static reference; this section switches dimensions: two cross-cutting paths drawn from the book's 21 chapters, each following one user-visible action from entry to exit, to verify how the mechanisms covered chapter by chapter mesh in real execution order. The format is uniform: a sequence diagram first, then a stage-by-stage expansion, each stage labeled with its chapter and source paths; every line number reuses a citation already present in that chapter's body, none are new (the baseline is in the version note at the end of this section). The protocol mechanisms (R1 ACK, frontmatter, the lane matrix) already have quick-reference tables in F.1 through F.5 and are cited here, not re-expanded.

Trace 1: How One Matrix User Message Becomes a Reply in the Channel

Chapters crossed: Chapter 11 (the message bus, inbound and sessions) → Chapter 5 (the Agent Loop's six stages) → Chapter 6 (tool-system execution) → Chapter 8 (context compaction), with the return leg through Chapter 11's outbound splitting. Scene: a user types "re-check the ch07 references" in a Matrix room and expects the agent to read the files, run the checks, and land the conclusion back in the same room.

sequenceDiagram
    participant U as 用户 Matrix
    participant B as octos-bus 总线
    participant L as agent-loop 循环
    participant T as 工具层
    U->>B: 发送一条消息
    B->>B: 长轮询 sync 收事件并鉴权
    B->>B: SessionActor 追加写 JSONL
    B->>L: AgentHandle 交付 InboundMessage
    loop 六阶段循环, stop_reason 为 ToolUse
        L->>L: 消息准备与预算检查
        L->>L: 调用 LLM 流式消费
        L->>T: execute_tools 派发工具批
        T->>T: execute_with_context 执行
        T-->>L: ToolResult 消息回填
        L->>L: turn 状态更新
    end
    L->>L: 窗口逼近上限, 压缩历史
    L-->>B: OutboundMessage 最终回复
    B->>B: split_message 按平台限额切块
    B-->>U: 分块回复送达 Matrix 房间

Stage one, inbound and the session ledger (Chapter 11). In user-account mode the Matrix channel long-polls the homeserver's Client-Server /sync API with a 30-second timeout (SYNC_TIMEOUT_MS, crates/octos-bus/src/matrix_user_channel.rs:44): the request hangs open, returns only when an event arrives, and is re-issued immediately, so self-hosted servers without push permission still receive messages near-real-time. The message then passes two channel-layer gates: sender authorization is_allowed() runs before routing to the agent, allow-by-default with per-channel overrides (crates/octos-bus/src/channel.rs:27-30); inbound deduplication targets webhook-style platforms' timeout resends, with MessageDedup caching seen message IDs in an LRU of capacity 1,000 and TTL 60 seconds (crates/octos-bus/src/dedup.rs:12-25); Discord gateway-reconnect replays hang off the same instance (crates/octos-bus/src/discord_channel.rs:32). Every channel implements the same Channel trait, and of its 26 methods only name(), start(), and send() lack default implementations (crates/octos-bus/src/channel.rs:17-265), so a new channel can start running with just three methods.

The message then enters the session layer: SessionActor holds an independent SessionHandle per session, prefers the per-user layout, and migrates old files on open (crates/octos-bus/src/session.rs:1611-1819); the JSONL file's first line is SessionMeta metadata rather than a message, and every following line is a message (crates/octos-bus/src/session.rs:560); appends go through append_to_disk(), full rewrites through write-then-rename rewrite(), and a single session file caps at 10MB so runaway history cannot eat the disk (crates/octos-bus/src/session.rs:792); the durable commit observer after the write is best-effort fan-out, and failures do not roll back (crates/octos-bus/src/session.rs:71). Same-key writes are serialized through persist_message_through_canonical_path() under a per-key Tokio mutex (crates/octos-bus/src/session.rs:2332-2420), so multiple write entry points cannot double-count (crates/octos-bus/src/session.rs:2332). The bus and the processing layer decouple through the symmetric channels AgentHandle / BusPublisher (crates/octos-bus/src/bus.rs:8-77): once every channel's inbound sender is dropped, the receiving end's recv() returns None, the processing layer senses it and exits gracefully, with no separate shutdown signal needed.

Stage two, entering the loop (Chapter 5). The processing layer hands the message to the process_message family, and one turn advances through ① message preparation, ② budget check, ③ LLM call, ⑤ tool dispatch, ⑥ state update. Before ①, history goes through a repair pipeline whose entry is prepare_conversation_messages (crates/octos-agent/src/agent/loop_compaction.rs:27), unifying tool_call_id, fixing message order and tool pairing, so broken history does not trip provider validation. At the top of every iteration, ② runs check_budget (crates/octos-agent/src/agent/budget.rs:100), five gates in a fixed order, any hit returning BudgetStop (crates/octos-agent/src/agent/budget.rs:13); the order itself is the design: the atomic shutdown load answers first, the iteration cap next, the two timeouts depend on activity tracking (crates/octos-agent/src/agent/activity.rs:16), the token budget last. The whole call orchestration of ③ converges in the single main function call_llm_with_hooks (crates/octos-agent/src/agent/llm_call.rs:22), with tokens from retry attempts folded into the final usage accounting; streaming consumption is done by pub(super) consume_stream_with_input_estimate (crates/octos-agent/src/agent/streaming.rs:73). The error path is not scattered unwraps: errors first go through classify_loop_error (crates/octos-agent/src/agent/loop_runner.rs:313) into a typed retry-bucket state machine, and callers receive only two coarse actions, Retry or Bail. The response's stop_reason decides the next hop: EndTurn returns, MaxTokens takes the continuation and self-healing path (the conversation loop's continuation branch sits near crates/octos-agent/src/agent/loop_runner.rs:2171, with a nudge continuation cap of 2), ToolUse goes back to tool dispatch.

Stage three, intent becomes side effects (Chapter 6). The tool-dispatch main entry execute_tools is pub(super) (crates/octos-agent/src/agent/execution.rs:2483); it decides serial versus parallel, computes the batch timeout, and runs pre- and post-hooks; cancellation and panic are both projected into a tool-result message the LLM can read rather than crashing the loop. Tool bodies implement the Tool trait (crates/octos-agent/src/tools/mod.rs:609); the execution layer goes through the typed entry execute_with_context introduced in M8.1 (crates/octos-agent/src/tools/mod.rs:11-28), with the legacy execute and the typed entry delegating to each other and one tool overriding at most one of them. Registration and lookup live in ToolRegistry (register at crates/octos-agent/src/tools/registry.rs:536, register_arc at :558), and the dispatch boundary stacks four defenses: provider policy refusal, an argument-size cap, catch_unwind panic isolation (a tool panic degrades to a failed ToolResult instead of killing the session actor), and a global execution timeout. Tools marked spawn_only are intercepted at the dispatch point and turned into background tasks (around crates/octos-agent/src/agent/execution.rs:775); the LLM receives a small task_handle envelope whose five read modes check intermediate output on demand without bloating context. In this scene, read_file and bash results are back-filled as ToolResult messages and the loop returns to ⑥: LoopTurnState (crates/octos-agent/src/agent/turn_state.rs:59) accumulates usage and stop reasons, and the next iteration continues.

Stage four, window reclamation (Chapter 8). After a dozen tool iterations the window nears its limit, and the loop triggers CompactAndRetry at the error-classification point, in-band, without the caller threading through compaction state (crates/octos-agent/src/agent/loop_runner.rs:313). Compaction cuts in layers: local placeholders, server-side cleanup, and a full summary, three tiers; the most recent messages are always kept, a full six of them, and the cut point never lands on a Tool message, falling back to tail truncation fallback_truncate() when it does not fit (crates/octos-agent/src/agent/compaction.rs:319). Compacted output is not lost: bytes are recallable by id, semantic summaries are archived as retrievable episodes, and entry compaction and intra-turn compaction each store once (crates/octos-agent/src/agent/loop_runner.rs:1215). After compaction the loop continues until stop_reason is EndTurn. In this scene, re-checking ch07's references means reading several facts-table files; without recall, the same source file would cycle through enter-window, truncate, compact, read-again; the three-tier reclamation turns this into one read plus many id-based retrievals.

Stage five, the return leg (Chapter 11 outbound). The final reply returns to the channel layer as an OutboundMessage; over the platform character limit, long messages go to coalescing: split_message() hunts breakpoints through five priority levels, paragraph, period, space, hard cut, first building a UTF-8-safe window then rfind-ing inside it (the two-step cut starting at crates/octos-bus/src/coalesce.rs:68), and MAX_CHUNKS = 50 keeps an extremely long message from fragmenting into a flood of small ones (crates/octos-bus/src/coalesce.rs:47); a breakpoint equal to 0 is skipped, guaranteeing forward progress instead of cutting empty chunks at the same spot. Chunks are rendered by the channel and delivered to the Matrix room; channel health is exposed uniformly by health_check() for the admin panel (crates/octos-bus/src/channel.rs:245) rather than scattered across each channel's own admin interface. The message has now completed its full round trip from platform event to chunked reply: inbound dedup, session ledger, the six-stage loop, tool execution, context reclamation, outbound splitting, and every station carries its own failure projection.

The systemic facts this trace surfaces: entry and exit each hold an independent defense line (inbound dedup, outbound splitting), so a bad message neither gets in nor gets out; every organ of the loop is pub(super), and the crate boundary exposes only the loop itself; context is managed as a fluid, with compaction, recall, and episodes as three tiers guaranteeing information only loses density, never disappears; every layer's failure (duplicate delivery, oversized messages, tool panic) has a degraded projection instead of breaking the chain.

Trace 2: A Goal from Creation to Dual-Loop Closure

Chapters crossed: Chapter 18 (the goal/peer two threads) → Chapter 12 (the three concurrency layers and leases) → Chapter 18 (the three return channels) → Chapter 20 (outer-loop OLP observation and verdicts). Scene: the operator gives master one macro instruction, "add two end-to-end traces to Appendix F," and we follow it from goal creation through goal_update complete and the outer-loop ACK to closure.

sequenceDiagram
    participant O as operator
    participant M as master keeper
    participant G as GoalLedger 账本
    participant P as peer worker
    participant W as 外环 outer
    O->>M: 宏观指令
    M->>G: goal_create 建目标 status 为 active
    M->>G: goal_plan 分解, goal_dispatch 派任务
    M->>P: peer_handoff 落盘 brief 与 goal
    P->>P: boot 读回, turn 循环, 租约保活
    P->>G: append_finding 落权威历史
    P-->>W: result.md 与事件流上行
    W->>W: R1 ACK 与 R2 复验
    W-->>M: 黑板指导下行
    M->>G: goal_update complete 过 verifier
    G-->>O: 账本即审计事实, 双环收口

Stage one, opening the ledger (Chapter 18). The keeper-side goal_create (GoalCreateTool, crates/octos-cli/src/goal_tool.rs at :1495/:1509, with the admission check serialized across both calls) is wired at crates/octos-cli/src/runtime/profile.rs:1326. The ledger is GoalLedger (crates/octos-fleet/src/sqlite_ledger.rs:13): a WAL-mode SQLite where master, the process manager, and peers are separate processes sharing the one goal-ledgers/<goal_id>.db; the 39 pub fns of impl GoalLedger fall into five groups by purpose, and every state transition, every finding, every escalation request, and every decision leaves an audit trail, which is how one ledger file reaches 6,360 lines. The ledger's state set is the six string states active, complete, blocked, budget_limited, paused, cleared (comment at crates/octos-fleet/src/sqlite_ledger.rs:39; terminal-state protection covers complete and cleared); archived is not in the ledger's state set, it is the supervisor event stream's terminal marker, and the two books never mix state sets. Then goal_plan decomposes the goal into a durable fleet and goal_dispatch ships ready tasks to the live worker pool (wired at crates/octos-cli/src/runtime/profile.rs:1341 and :1342). The machine state of planning and execution lives in the fleet kernel (redb), goals and audit in GoalLedger (SQLite), two books that do not substitute for each other; the keeper putting goals into a ledger instead of the conversation context is the answer to this chapter's opening question, that long-horizon goals left in context rot.

Stage two, dispatching the peer (Chapter 18 entry, on Chapter 12's concurrency base). The model-side entry peer_handoff only validates arguments (crates/octos-agent/src/tools/peer_handoff.rs:133); staging is done by stage_peer (crates/octos-cli/src/peers/mod.rs:1563), writing worktree, originator, goal, brief, and name to disk in a fixed order; at peer boot, read_peer_boot (crates/octos-cli/src/peers/host.rs:96) reads the execution context back, and the originator is read exactly once so it cannot be rebound mid-run. Liveness semantics rest on Chapter 12's three-layer concurrency model: the peer/lease layer's PeerTaskBinding (crates/octos-cli/src/peers/mod.rs:166) binds the peer to the supervisor's TaskLivenessLease; the fleet-side Lease (crates/octos-fleet/src/records.rs:250) has only owner_epoch and expires_at_ms as its two fields, a daemon restart takes a new epoch and the old owner loses authority automatically; the supervisor event ledger SupervisorStore (crates/octos-cli/src/autonomy/supervisor_store.rs at :697) persists the supervised agent-group state, and load_state (:780) reads it back at restart. The peer session's tool surface is deliberately narrow: a goal-bound peer wires up only goal_get and goal_update (crates/octos-cli/src/commands/chat.rs:859), it can see the goal and record findings back into master's ledger, but it cannot reach plan or dispatch and has no authority to rewrite the plan.

Stage three, execution and return flow (Chapter 18). The peer has its own turn loop and token budget; Trace 1's six-stage loop is its baseline variant, differing only in the tool surface and the budget cap. The final deliverable is written back to the board by write_peer_result_if_peer_session (crates/octos-cli/src/api/ui_protocol_transport.rs:14279), with the runtime landing the four frontmatter fields slug/outcome/updated_unix/turn (:14334), the turn number derived from the result-<n>.md count plus one; a budget-exhausted peer writes an additional five-field checkpoint copy (crates/octos-agent/src/agent/budget.rs:584), with status/completed/iteration_budget/iterations_used/checkpoint_commit leaving "how far it got, how much was missing" for the next dispatch. There are three return channels, converging in goal_get: the live channel reads peers/<slug>/result.md, fast but overwritable; the durable channel goes through GoalLedger::append_finding (crates/octos-fleet/src/sqlite_ledger.rs at :1623), landed on disk the moment a goal-scoped peer finishes a turn, surviving restart, the authoritative history; the escalation channel writes append_escalation (:1635) when a peer parks, so even if master misses the live notification it sees who is waiting in goal_get's open_escalations. External events are consumed by fleet_wake (crates/octos-cli/src/autonomy/fleet_wake.rs), which drains the fleet outbox into continuation requests, acks only after persistence succeeds (WakeCommit::Durable), and re-delivers unpersisted events after their lease expires; the request enqueue point is crates/octos-cli/src/autonomy/agent_orchestrator.rs:12963, and the GoalContinue and GoalWrapUp variants (crates/octos-cli/src/autonomy/master_continuation_scheduler.rs at :141/:147) drive the keeper's next tick, the latter being the wrap-up turn after budget exhaustion. A peer's end is marked with a closed tombstone (peer_is_closed, :1317); master collects accounts via peer_gather pulling result.md; the CLI observation surface octos peer list likewise reads the board directory directly, with zero serve dependency.

Stage four, the outer verdict (Chapter 20). The dual loop shares no memory; all collaboration runs over auditable persistent channels: upstream there are the event stream, result.md, goal-ledgers, escalation, git diff, and active inquiry; downstream there are AGENTS.md, the blackboard, atomic commits, the inbox doorbell, and TUI injection. Before going on shift the outer loop takes the lead-review lock, starting wrapped in octoscode outer-duty hold; the lock is the authority. Observation splits into three layers, delivery, consumption, execution, and watching one layer alone guarantees a misread, which is also the outer loop's most common mistake. The verdict's carrier is the ACK line under each item of the blackboard's Active section: a line must be added after execution, no ACK counts as unread, and the outer loop may return the delivery (from octoscode/docs/OUTER_LOOP_PROTOCOL.md:52, with the v1 grammar pinned by octoscode/tests/olp_contract.rs:96); delivery review re-checks result.md's verified claim against R2's three verification levels, and a verified claim that fails re-verification is a protocol violation, returned and recorded on the blackboard. The frontmatter's protocol schema is six fields (octoscode/docs/OUTER_LOOP_PROTOCOL.md:354, field list :362 through :367), consumers ignore unknown fields for forward compatibility, and the verified and protocol fields are written by the octos side. The inner loop's mid-turn inquiry goes through the fifth channel ask_outer (octoscode/src/olp_mcp.rs:174); timeout and quota behavior are in the F.5 table: on timeout, degrade by proceeding on the blackboard's existing guidance, and if you cannot proceed, close with ACK(blocked) noting the inquiry id; beyond quota the call is refused outright with a pointer to report_blocked. In this scene, the outer loop's review of the two F.6 draft sections traveled down through the blackboard and up through ACK, running in parallel with the goal ledger's state machine, neither blocking the other.

Stage five, closure (Chapter 18). master calls goal_update claiming complete (GoalUpdateTool, crates/octos-cli/src/goal_tool.rs at :1163/:1266, wired at crates/octos-cli/src/runtime/profile.rs:1329, hooking an independent verifier lane if one is configured), and the completion claim must pass the verifier to take effect. The single entry for state transitions, cas_goal_status (crates/octos-fleet/src/sqlite_ledger.rs at :899), embeds the budget rule inside the UPDATE statement: when a goal is active and tokens_used >= token_budget, it writes budget_limited directly instead of the caller's intended terminal state; update_goal_status (:1498) is the other, non-CAS transition path; complete and blocked are reachable only by the model, reopen accepts only the three entries blocked, paused, and budget_limited, and the ledger-side terminal-state protection covers complete and cleared. What the outer loop does after this step: go through the blackboard Active section's review items item by item, checking that ACKs landed and that the R2 claim's verification level matches the commands actually run, and only agree to let the operator push the branch after the re-check passes; on a wontdo disagreement, the F.1 disagreement rule allows only accepting or escalating to the operator, never returning the same item again. After goal_update complete, the ledger is the audit fact, and the outer loop's ACK and the blackboard history section are the human-readable counterpart, each loop keeping its own trace without overwriting the other; if the operator ever reopens the goal, the three reopen entries are all traceable in the ledger's transition records.

The systemic facts this trace surfaces: a goal's state lives in exactly one SQLite ledger, humans read the blackboard, the model reads tools, the outer loop reads files, three projections of one fact; ownership is expressed through leases and epochs, not in-process locks, and a restart self-corrects; "complete" is a claim that must pass independent verification, not a write; a missed notification is moved from the exception path to the ordinary read path, one goal_get call gathering the accounts of all three channels.

Version note

  • v0 to v1 (effective 2026-08-24): the R1 ACK grammar formalized (done/wontdo/blocked and the wontdo disagreement rule); the result.md frontmatter v1 schema fixed; the sub_providers lane templates (Appendices A and B finalized alongside). The v1 grammar binds only ACK lines written on or after the effective date (octoscode/docs/OUTER_LOOP_PROTOCOL.md:9-12).
  • v1 to v2 (effective 2026-08-30, #38-r1): adds the R7 lead-review OS exclusive lock (outer-duty hold/check; the lock is the authority, check only observes, live-lock takeover belongs to the operator, metadata/TTL are diagnostic only; Linux-only single-machine flock plus PDEATHSIG, Windows is a separate item, NFS excluded); the AGENTS.md reference updated to v2 in sync (same, :14-17).
  • R4b tree sovereignty and auto-fencing is a port of octos #20-20c, recorded as an R4 subclause with no protocol version bump (same, :88).
  • What's next: the L3 platform extension (R7 lead-review lock on macOS) was approved on 2026-09-02, a guardian reaper process plus kqueue replicating the death coupling, channel semantics unchanged, no protocol version bump (same, :167-172).
  • Every line number in this appendix is baselined on octoscode repo main @ 1129fa33; for later protocol evolution, defer to the docs in that repo. The F.6 traces share the book-wide baseline, octos main @ 9c157101.