# Technical Documentation: campfirein/byterover-cli

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/campfirein/byterover-cli)

### Overview (`README.md`)

# ByteRover CLI

<div align="center">

<img src="./assets/images/logo/byterover-logo.svg" alt="ByteRover Logo" width="280" />

<p align="center">
<em>Interactive REPL CLI for AI-powered context memory</em>
</p>

<p align="center">
<a href="LICENSE"><img src="https://img.shields.io/badge/License-Elastic%202.0-blue.svg" alt="License" /></a>
<a href="https://npmjs.org/package/byterover-cli"><img src="https://img.shields.io/npm/v/byterover-cli.svg" alt="Version" /></a>
<a href="https://npmjs.org/package/byterover-cli"><img src="https://img.shields.io/npm/dw/byterover-cli.svg" alt="Downloads" /></a>
<a href="https://docs.byterover.dev"><img src="https://img.shields.io/badge/Docs-Documentation-green.svg" alt="Documentation" /></a>
<a href="https://discord.com/invite/UMRrpNjh5W"><img src="https://img.shields.io/badge/Discord-Join%20Community-7289da" alt="Discord" /></a>
</p>

</div>

## Overview

ByteRover CLI (`brv`) gives AI coding agents persistent, structured memory. It lets developers curate project knowledge into a context tree, sync it to the cloud, and share it across tools and teammates.

Run `brv` in any project directory to start an interactive REPL powered by your choice of LLM. The agent understands your codebase through an agentic map, can read and write files, execute code, and store knowledge for future sessions.

📄 Read the [paper](https://arxiv.org/abs/2604.01599) for the full technical details.

Or download our self-hosted PDF version of the paper [here](https://byterover.dev/paper).

**Key Features:**

- 🌐 Web dashboard for curating and querying context (`brv webui`)
- 🖥️ Interactive TUI with REPL interface (React/Ink)
- 🧠 Context tree and knowledge storage management
- 🔀 Git-like version control for the context tree (branch, commit, merge, push/pull)
- 🤖 20 LLM providers (Anthropic, OpenAI, Google, Groq, Mistral, xAI, DeepSeek, and more)
- 🛠️ 24 built-in agent tools (code exec, file ops, knowledge search, memory management)
- 🔄 Cloud sync with push/pull
- 👀 Review workflow for curate operations (approve/reject pending changes)
- 🔌 MCP (Model Context Protocol) integration
- 📦 Hub and connectors ecosystem for skills and bundles
- 🤝 Works with 22+ AI coding agents (Cursor, Claude Code, Windsurf, Cline, and more)
- 🏢 Enterprise proxy support

## Benchmark Results

All benchmarks are run using the production `byterover-cli` codebase in this repository - no separate research prototype.

We evaluate on two long-term conversational memory benchmarks:

- **LoCoMo** - ultra-long conversations (~20K tokens, 35 sessions) testing single-hop, multi-hop, temporal, and open-domain retrieval.
- **LongMemEval-S** - large-scale benchmark (23,867 docs, ~48 sessions per question) testing 6 memory abilities including knowledge update, temporal reasoning, and multi-session synthesis.

**LoCoMo** - 96.1% overall accuracy (1,982 questions, 272 docs).

**LongMemEval-S** - 92.8% overall accuracy (500 questions, 23,867 docs).

<p align="center">
<img src="assets/images/benchmarks/longmemeval-s-by-category.png" alt="LongMemEval-S Benchmark by Category" width="700" />
</p>

All metrics are LLM-as-Judge accuracy (%). See the [paper](https://arxiv.org/abs/2604.01599), or self-hosted [PDF](https://byterover.dev/paper) for full details.

## Quick Start

### Shell Script (macOS & Linux)

No Node.js required - everything is bundled.

```bash
curl -fsSL https://byterover.dev/install.sh | sh
```

Supported platforms: macOS ARM64, macOS x64 (Intel), Linux x64, Linux ARM64.

### npm (All Platforms)

Requires Node.js >= 20.

```bash
npm install byterover-cli
```

### Verify

```bash
brv --version
```

### First Run

```bash
cd your/project
brv
```

The REPL auto-configures on first run - no setup needed. Type `/` to discover all available commands:

```
/curate "Auth uses JWT with 24h expiry" @src/middleware/auth.ts
/query How is authentication implemented?
```

## ByteRover Cloud

ByteRover Cloud is a hosted platform for teams to sync, share, and manage context knowledge across projects and machines.
Everything works locally by default - Cloud adds collaboration and persistence without changing your workflow.

<p>
<a href="https://app.byterover.dev"><img src="https://img.shields.io/badge/Try%20ByteRover%20Cloud-Free-blue?style=for-the-badge" alt="Try ByteRover Cloud" /></a>
</p>

Sign in from the dashboard, or run `brv login` with an [API key](https://app.byterover.dev/settings/keys).

- 🔄 **Team context sync** — push and pull shared knowledge across teammates
- 📂 **Shared spaces** — organize context across multiple projects and teams
- 💻 **Multi-machine access** — sync your context tree across devices with cloud backup
- 💻 **Multi-machine access** — sync your context tree across devices
- 🧠 **Built-in hosted LLM** — start immediately with limited free usage
- 👥 **Team management** — manage members, spaces, and permissions via the web app
- 📊 **Usage analytics** — track seat allocation and monthly credit consumption
- 🔒 **SOC 2 Type II** certified infrastructure with privacy mode

<details>
<summary><h2>CLI Usage</h2></summary>

Most users only need `brv webui`. The commands below are for advanced users and automation. Run `brv --help` for the full, up-to-date reference.

### Core Workflow

```bash
brv                  # Start interactive REPL
brv webui            # Open the ByteRover dashboard (primary UI)
brv status           # Show project and daemon status
brv curate           # Add context to knowledge storage
brv curate view      # View curate history
brv query            # Query context tree and knowledge
brv review pending   # List pending review operations
brv review approve   # Approve curate operations
brv review reject    # Reject curate operations
```

### Sync (Legacy)

```bash
brv push             # Legacy — migrate or snapshot context to cloud
brv pull             # Legacy — restore context from cloud snapshot
```

> Use `brv vc push` / `brv vc pull` for version-controlled sync going forward.

### Version Control

```bash
brv vc init              # Initialize version control for context tree
brv vc status            # Show version control status
brv vc add               # Stage files for the next commit
brv vc commit            # Save staged changes as a commit
brv vc log               # Show commit history
brv vc branch            # List, create, or delete branches
brv vc checkout          # Switch branches
brv vc merge             # Merge a branch into the current branch
brv vc clone             # Clone a ByteRover space repository
brv vc push              # Push commits to ByteRover cloud
brv vc pull              # Pull commits from ByteRover cloud
brv vc fetch             # Fetch refs from ByteRover cloud
brv vc remote            # Show current remote origin
brv vc remote add        # Add a named remote
brv vc remote set-url    # Update a remote URL
brv vc config            # Get or set commit author
brv vc reset             # Unstage files or undo commits
```

### Providers & Models

```bash
brv providers list       # List available LLM providers
brv providers connect    # Connect to an LLM provider
brv providers switch     # Switch active provider
brv providers disconnect # Disconnect a provider
brv model list           # List available models
brv model switch         # Switch active model
```

### Hub & Connectors

```bash
brv hub list             # List available hub packages
brv hub install          # Install a hub package
brv hub registry add     # Add a custom registry
brv hub registry list    # List registries
brv hub registry remove  # Remove a registry
brv connectors list      # List connectors
brv connectors install   # Install a connector
```

### Spaces (Deprecated)

```bash
brv space list       # Deprecated — use web dashboard
brv space switch     # Deprecated — use brv vc clone
```

### Settings

`brv` ships with operational defaults that suit most users. The `brv settings` command group lets you inspect and override these values.

```bash
brv settings                    # List all settings with current and default values
brv settings list               # Alias for `brv settings`
brv settings get <key>          # Show current and default for one key
brv settings set <key> <value>  # Update one key (restart required)
brv settings reset <key>        # Restore one key to its default (restart required)
```

Available keys:

| Key | Default | What it controls |
|---|---|---|
| `agentPool.maxSize` | 10 | Maximum concurrent active projects (one agent process per project) |
| `agentPool.maxConcurrentTasksPerProject` | 5 | Parallel `brv curate` / `brv query` tasks within a single project |
| `llm.iterationBudgetMs` | 600000 | Wall-clock budget for the agentic loop on one task, in milliseconds |
| `llm.requestTimeoutMs` | 120000 | Wall-clock budget for one direct LLM HTTP request, in milliseconds |
| `taskHistory.maxEntries` | 1000 | Number of task records `brv query-log view` retains per project |

Raise `llm.iterationBudgetMs` when a single `brv curate` or `brv query` on a slow local LLM (Ollama on CPU, heavy quantization, cold model load) routinely hits the default 10-minute cap on legitimate work. Lower it on cloud providers when you want a stuck task to surface as an error faster instead of waiting out the full budget. The cap is enforced per task, not per request.

`llm.requestTimeoutMs` bounds one HTTP request to the LLM. A frozen Ollama or LM Studio connection aborts at this boundary and the retry layer treats it as a transient error rather than wasting the full iteration budget. The setting must satisfy `llm.requestTimeoutMs <= llm.iterationBudgetMs`; the daemon rejects writes that violate the rule and falls back to defaults for both keys when the file violates it at startup. Suggested presets:

| Profile | `llm.requestTimeoutMs` | `llm.iterationBudgetMs` |
|---|---|---|
| Cloud | 120000 (2 min) | 600000 (10 min) |
| Local LLM, fast GPU | 300000 (5 min) | 1200000 (20 min) |
| Local LLM, CPU / heavy quantization | 900000 (15 min) | 3600000 (60 min) |

Settings persist in `settings.json` under the `brv` global data directory:

- Linux: `$XDG_DATA_HOME/brv/settings.json` (defaults to `~/.local/share/brv/settings.json`)
- macOS: `~/Library/Application Support/brv/settings.json`
- Windows: `%LOCALAPPDATA%/brv/settings.json`

Set the `BRV_DATA_DIR` environment variable to override the directory.

Changes apply after `brv restart`. The daemon reads the file once at startup and does not observe file changes during runtime. This keeps every running agent on the same configuration for the lifetime of the daemon.

Example session:

```bash
$ brv settings list
KEY                                       CURRENT  DEFAULT  RESTART?
agentPool.maxSize                         10       10       yes
agentPool.maxConcurrentTasksPerProject    5        5        yes
taskHistory.maxEntries                    1000     1000     yes

$ brv settings set agentPool.maxSize 20
Setting saved. Run `brv restart` to apply.

$ brv settings get agentPool.maxSize
20  (default: 10)
```

Every command supports `--format json` for scripting. Validation errors (unknown key, value out of range) exit with code 1 and a message naming the key.

### Other

```bash
brv mcp              # Start MCP server
brv login            # Authenticate to ByteRover
brv logout           # Disconnect and clear credentials
brv locations        # List registered projects
brv restart          # Restart daemon
brv debug            # Debug mode
```

Run `brv --help` for the full command reference.

</details>

<details>
<summary><h2>Supported LLM Providers</h2></summary>

ByteRover CLI supports 20 LLM providers out of the box. Connect and switch providers from the dashboard, or use `brv providers connect` / `brv providers switch`.

| Provider | Description |
|----------|-------------|
| Anthropic | Claude models |
| OpenAI | GPT models |
| Google | Gemini models |
| Groq | Fast inference |
| Mistral | Mistral models |
| xAI | Grok models |
| Cerebras | Fast inference |
| Cohere | Command models |
| DeepInfra | Open-source model hosting |
| DeepSeek | DeepSeek V3 and R1 reasoning models |
| OpenRouter | Multi-provider gateway |
| Perplexity | Search-augmented models |
| TogetherAI | Open-source model hosting |
| Vercel | AI SDK provider |
| Minimax | Minimax models |
| Moonshot | Kimi models |
| GLM | GLM models |
| GLM Coding Plan | GLM models on Z.AI Coding Plan subscription |
| OpenAI-Compatible | Any OpenAI-compatible API |
| ByteRover | ByteRover's hosted models |

</details>

## Worktrees and Knowledge Sources

> **Vocabulary**
> - **Worktree link** — a subdirectory pointer to a parent project (`brv worktree`)
> - **Source** — a read-only reference to another project's knowledge (`brv source`)
> - **Origin** — where an indexed search result came from (`local` vs `shared`)

ByteRover can run from a linked subdirectory without creating a nested `.brv/`.

- `projectRoot`: the directory that owns `.brv/config.json`
- `worktreeRoot`: the linked worktree directory, or `projectRoot` when unlinked
- `clientCwd`: the shell cwd where you ran `brv`

When you run `brv query` or `brv curate` from a linked worktree, implicit defaults use `worktreeRoot` so scope stays stable even if `clientCwd` drifts deeper into the package. Explicit relative paths that you pass yourself, such as `brv curate -f ./src/auth.ts`, still resolve from `clientCwd` to match normal shell behavior.

Use `brv worktree add` from the project root to register a subdirectory (or sibling) as a worktree. This creates a `.brv` pointer file in the target directory that redirects to the parent project — the same pattern git uses for `git worktree`. Use `brv worktree remove` to unregister, and `brv worktree list` to inspect. To search another project's knowledge from here, use `brv source add <path>` (with `brv source list` / `brv source remove` to inspect or detach).

## Documentation

Visit [**docs.byterover.dev**](https://docs.byterover.dev) for full guides on setup, integrations, and advanced usage.

| Topic | Description |
|-------|-------------|
| [Getting Started](https://docs.byterover.dev) | Installation, first run, and basic usage |
| [Cloud Sync](https://docs.byterover.dev) | Push/pull workflows and team sharing |
| [Version Control](https://docs.byterover.dev) | Context tree branching, commits, and collaboration |
| [LLM Providers](https://docs.byterover.dev) | Provider setup and model configuration |
| [AI Agent Integrations](https://docs.byterover.dev) | Using ByteRover with Cursor, Claude Code, Windsurf, etc. |
| [Hub & Connectors](https://docs.byterover.dev) | Skills, bundles, and the connector ecosystem |
| CLI Reference | Run `brv --help` |

## Contributing

We welcome contributions! See our [Contributing Guide](CONTRIBUTING.md) for development setup, coding standards, and the PR workflow.

## Community & Support

ByteRover CLI is built and maintained by the [ByteRover team](https://byterover.dev/).

- Join our [Discord](https://discord.com/invite/UMRrpNjh5W) to share projects, ask questions, or just say hi
- [Report issues](https://github.com/campfirein/byterover-cli/issues) on GitHub
- If you enjoy ByteRover CLI, please give us a star on GitHub — it helps a lot!
- Follow [@kevinnguyendn](https://x.com/kevinnguyendn) on X

## Contributors

[](https://github.com/campfirein/byterover-cli/graphs/contributors)

## Star History

<a href="https://star-history.com/#campfirein/byterover-cli&Date">
  <img width="500" alt="Star History Chart" src="https://api.star-history.com/svg?repos=campfirein/byterover-cli&type=Date&v=2">
</a>

## License

Elastic License 2.0. See [LICENSE](LICENSE) for full terms.

---

### Overview (`paper/README.md`)

# ByteRover: Agent-Native Memory Through LLM-Curated Hierarchical Context

Research paper for [ByteRover](https://www.byterover.dev/) - an agent-native memory architecture where the LLM itself curates, structures, and retrieves knowledge through a hierarchical Context Tree, requiring zero external infrastructure.

All benchmarks are run using the production `byterover-cli` codebase in this repository - no separate research prototype.

## Results

We evaluate on two long-term conversational memory benchmarks:

- **LoCoMo** - ultra-long conversations (~20K tokens, 35 sessions) testing single-hop, multi-hop, temporal, and open-domain retrieval.
- **LongMemEval-S** - large-scale benchmark (23,867 docs, ~48 sessions per question) testing 6 memory abilities including knowledge update, temporal reasoning, and multi-session synthesis.

**LoCoMo** - 96.1% overall accuracy (1,982 questions, 272 docs).

**LongMemEval-S** - 92.8% overall accuracy (500 questions, 23,867 docs).

All metrics are LLM-as-Judge accuracy (%).

## Building the PDF

```bash
# Requires BasicTeX or MacTeX
# Install: brew install --cask basictex
# Then: sudo tlmgr install multirow algorithms algorithmic enumitem float tcolorbox environ trimspaces listings subcaption natbib tabularx

bash build.sh    # Build PDF
make clean       # Remove build artifacts
```

## File Structure

| File | Description |
|------|-------------|
| `main.tex` | Full paper source (~1,300 lines) |
| `references.bib` | Bibliography (32 entries) |
| `build.sh` | Build script (pdflatex + bibtex) |
| `Makefile` | Build automation |
| `.gitignore` | Excludes PDF and LaTeX build artifacts |

---

### Overview (`src/server/templates/README.md`)

# ByteRover CLI Template System

This directory contains template files used to generate agent instructions via the `brv gen-rules` command.

## Directory Structure

```
src/templates/
├── base.md                      # Main template structure
├── sections/                    # Reusable content sections
│   ├── workflow.md               # workflow guide
│   └── command-reference.md     # All BR CLI commands documentation
└── README.md                    # This file
```

## Template Files

### `base.md`
The main template structure that combines all sections into the final output.

**Variables:**
- `{{agent_name}}` - Name of the agent (e.g., "Claude Code", "Cursor")
- `{{workflow}}` - Content from `sections/workflow.md`
- `{{command_reference}}` - Content from `sections/command-reference.md`

### `sections/workflow.md`
Complete guide to the context tree workflow:
- Quick start examples
- Command reference for context management
- Best practices for using context tree
- Examples with real use cases

### `sections/command-reference.md`
Comprehensive documentation of all BR CLI commands:
- Root commands (login, init, status, add, gen-rules, push, watch, cipher-agent)
- Space commands (list, switch)

Each command includes:
- Description
- Arguments (if any)
- Flags with defaults
- Examples

## How It Works

1. User runs `brv gen-rules`
2. User selects an agent (e.g., "Claude Code")
3. `RuleTemplateService` loads templates via `FsTemplateLoader`
4. Templates are assembled:
   - Load section templates (workflow, command-reference)
   - Substitute variables in base template
   - Combine all content
5. Output written to `.clinerules/byterover-rules.md`

## Variable Substitution

The template system supports simple variable substitution using `{{variable_name}}` syntax.

**Available Variables:**
- `{{agent_name}}` - Agent name selected by user
## Updating Templates

### To Update Command Documentation:
Edit `sections/command-reference.md` - changes will be reflected next time `brv gen-rules` runs.

### To Update Context Tree Workflow Guide:
Edit `sections/workflow.md` - changes will be reflected next time `brv gen-rules` runs.

### To Change Output Structure:
Edit `base.md` - modify how sections are combined.

## Best Practices

1. **Keep templates in sync with code**: When adding/modifying commands, update `command-reference.md`
2. **Use clear examples**: Show realistic use cases in examples
3. **Maintain markdown formatting**: Ensure proper headers, code blocks, and lists
4. **Test after changes**: Run `brv gen-rules` and verify output in `.clinerules/byterover-rules.md`

## Future Enhancements

This template system is designed to support future improvements:
- Context-aware content (show different sections based on project state)
- Agent-specific customizations (per-agent template overrides)
- Conditional sections (e.g., show memory commands only if authenticated)
- Dynamic variable injection (project status, context tree stats, etc.)

## Technical Details

**Template Loader:** `src/infra/template/fs-template-loader.ts`
- Loads templates from filesystem
- Performs variable substitution
- Returns assembled content

**Template Service:** `src/infra/rule/rule-template-service.ts`
- Orchestrates template loading
- Builds final instruction content
- Injects agent-specific values

**Command:** `src/commands/gen-rules.ts`
- User-facing command
- Prompts for agent selection
- Writes output to `.clinerules/byterover-rules.md`

---

### Curate Protocol (`docs/curate-protocol.md`)

# `brv curate` tool-mode session protocol

The session protocol lets a calling agent (Claude Code, Cursor, etc.) drive `brv curate` without byterover holding any LLM provider config. ByteRover orchestrates the multi-step flow; the calling agent supplies LLM completions across multiple CLI invocations.

This document defines the wire contract: CLI surface, JSON envelope, lifecycle. SKILL.md authors and other tool consumers key off the shapes documented here.

## CLI surface

### Kickoff

```bash
brv curate "<user intent>" --format json
```

Tool mode is the only path for `brv curate` — no provider configuration, no env-var opt-in.

### Continuation — `--session` carries the prior call's id

The continuation payload is always a JSON envelope of the form `{"html": "...", "meta": {...}}`. Two equivalent ways to deliver it:

```bash
# Inline envelope on --response
brv curate --session <sessionId> --response '{"html":"<bv-topic>...</bv-topic>","meta":{...}}' --format json

# Envelope from a JSON file via --response-file (mutually exclusive with --response)
brv curate --session <sessionId> --response-file envelope.json --format json

# Same, with opt-in cleanup once the daemon dispatch returns
brv curate --session <sessionId> --response-file envelope.json --delete-response-file --format json
```

Presence of `--session` resumes an in-flight session created by a prior kickoff. `--response-file -` (stdin) is not supported in v1.

**`--delete-response-file` lifecycle.** The file is unlinked **after** the daemon dispatch returns, not before. A daemon-error throw (transport timeout, daemon down) skips the unlink entirely so the agent retains the envelope for retry. A non-throw return (`done`, `correct-html`, or any other status) honors the unlink. One consequence: on a `correct-html` continuation the source file is gone but the session is still live — the calling agent must re-author a fresh envelope and write a new file before the next continuation. The inline `--response` flow has no equivalent re-authoring tax.

### Overwrite intent — `--overwrite` on continuation

```bash
brv curate --session <sessionId> --response-file envelope.json --overwrite --format json
```

Default behavior: the writer refuses to clobber an existing topic at the resolved path and returns a `path-exists` correction step carrying the prior file's content. Pass `--overwrite` only when the calling agent has consciously decided to replace prior content. The flag is consumed on the continuation it appears on; subsequent continuations in the same session must repeat it if they still want to overwrite.

### `--format text` fallback

Both kickoff and continuation accept `--format text` for shell users. The output is a terse human digest. The primary consumer (the calling agent) uses `--format json`.

## Wire envelope

Every kickoff and continuation call returns the same JSON envelope under the standard CLI wrapper:

```json
{
  "command": "curate",
  "success": <ok>,
  "data": {
    "ok": <bool>,
    "status": "done" | "needs-llm-step" | "failed",
    "sessionId": "<uuid>",       // present on needs-llm-step AND on transient failed (see below)
    "step": "generate-html" | "correct-html",
    "prompt": "<free-text>",      // free-text instruction for the calling agent's LLM
    "schema": { ... },            // optional per-step schema slice
    "errors": [                   // present on correct-html, on failed, AND on done envelopes that carry a non-fatal companion error (today only --delete-response-file cleanup failure — see response-file-delete-error row below)
      {
        "kind": "<machine-readable>",
        "tag": "<bv-element>?",
        "attribute": "<attribute-name>?",
        "message": "<human-readable>"
      }
    ],
    "filePath": "<relative-path>",  // relative to .brv/context-tree/; present when status = done
    "warnings": [ "<advisory>" ]    // optional, only on done envelopes; non-fatal post-write notes from the writer
  },
  "timestamp": "<iso>"
}
```

### Status values

| `status` | Meaning | Next action for calling agent |
|---|---|---|
| `needs-llm-step` | Byterover wants an LLM completion. `prompt` + `step` describe what. | Run the calling agent's own LLM on `prompt`, then `brv curate --session <sessionId> --response '{"html":"...","meta":{...}}'` or `--response-file envelope.json`. |
| `done` | Curate complete. `filePath` is the location of the written topic. May also carry a non-empty `errors[]` for non-fatal companion failures — today only `response-file-delete-error` from `--delete-response-file` cleanup. Treat as success; surface the companion error to the user but don't abandon the result. | Report success to user. Session is cleaned up. |
| `failed` | Terminal error. `errors[]` explains why. | Report failure to user; abandon session. |

### `step` values (when `status === 'needs-llm-step'`)

| `step` | Meaning | Expected `--response` payload |
|---|---|---|
| `generate-html` | First call asking the calling agent to author a `<bv-topic>` document. | The generated HTML. |
| `correct-html` | A previous response failed validation. `errors[]` enumerates what to fix. | Corrected HTML. |

### Error `kind` values

| `kind` | Lifecycle | Terminal? | Notes |
|---|---|---|---|
| `missing-content` | Kickoff | **terminal** | Kickoff invoked without a context argument; no session created |
| `missing-response` | Continuation | **terminal** | `--session` invoked without `--response` or `--response-file`; session unaffected |
| `invalid-flag-combination` | Continuation | **terminal** | Emitted before any session lookup when a flag is used outside its supported call shape. Producers: `--overwrite`, `--response`, `--response-file`, or `--delete-response-file` without `--session`; `--response` and `--response-file` together; `--delete-response-file` without `--response-file`. |
| `invalid-response-format` | Continuation | **terminal** | `--response` / `--response-file` body did not parse as a `{html, meta?}` envelope. Detected locally before any daemon I/O; the file (if any) is preserved so the agent can fix and retry. |
| `response-file-not-regular` | Continuation | **terminal** | `--response-file` target is a directory, symlink, device, fifo, or socket. brv refuses to read or unlink non-regular files. |
| `response-file-read-error` | Continuation | **terminal** | `lstat` or `readFile` on `--response-file` failed (e.g. ENOENT, EACCES). |
| `response-file-delete-error` | Continuation | **non-terminal companion** | `--delete-response-file` was requested but `unlink` failed AFTER the daemon dispatch returned. The CLI emits the daemon's envelope verbatim (preserving its `status`, `ok`, `filePath`, etc.) and APPENDS this entry to `errors[]` so consumers can detect cleanup failure programmatically — `{ok: true, status: 'done', errors: [{kind: 'response-file-delete-error', …}]}` is the success-with-cleanup-hiccup shape. On a `status: 'failed'` dispatch, this entry joins the existing validation errors. |
| `unknown-session` | Continuation | **terminal** | Session id doesn't exist, was already completed, or fails uuid validation |
| `empty-response` | Continuation | **transient** (session kept live) | Continuation received an empty `--response`; caller retries with the same `sessionId` |
| `retry-cap-exceeded` | Continuation | **terminal** | `MAX_ATTEMPTS = 4` (1 generate + 3 corrections) reached without valid HTML; session cleared. Accompanied by the validation errors that pushed the session over the cap. |
| `missing-bv-topic` | Continuation | **transient** (correction) | Response had zero `<bv-topic>` root elements |
| `multiple-bv-topic` | Continuation | **transient** (correction) | Response had more than one `<bv-topic>` root |
| `missing-path-attribute` | Continuation | **transient** (correction) | `<bv-topic>` is missing a non-empty `path` attribute |
| `unsafe-path` | Continuation | **transient** (correction) | `<bv-topic path>` contains `..` or `.` segments |
| `unknown-element` | Continuation | **transient** (correction) | Response contains a `<bv-*>` tag outside the closed registry; `tag` field carries the offending name |
| `attribute-validation` | Continuation | **transient** (correction) | An element's attributes failed its registered validator. `tag` carries the element, `attribute` the offending field. |
| `path-exists` | Continuation | **transient** (correction) | A topic already exists at the resolved path and `--overwrite` was not passed. The envelope error carries `existingContent` (the prior file's bytes); the correction prompt inlines the same content inside an `<existing-topic path="…">…</existing-topic>` block so the calling agent can merge new content into existing structure. The guard does not clear by re-emitting different content — `--overwrite` is required to write at this path. Default workflow: merge `existingContent` with the new content and re-emit with `--overwrite`. Alternative: choose a different `<bv-topic path>` (no `--overwrite` needed). |

**Terminal vs transient.** Terminal failures end the session — the caller cannot retry the same `sessionId` and must start a new kickoff. Transient failures keep the session alive on disk; the envelope echoes the `sessionId` back and the caller is expected to issue a corrected continuation against it.

**Retry cap.** Each transient correction increments an internal `attempts` counter on the session. After `MAX_ATTEMPTS = 4` consecutive invalid responses (the initial generate plus three corrections) the orchestrator terminates with `retry-cap-exceeded` and clears the session. Calling agents should surface this as "I couldn't produce valid HTML after several attempts; want to try a different framing?".

Calling agents should switch on `kind`, fall back gracefully on unknown kinds, and surface the `message` text to the user.

## Lifecycle — worked example

A complete tool-mode curate session, end-to-end:

### 1. Kickoff

```bash
brv curate "remember we decided to use RS256" --format json
```

Response (placeholder):

```json
{
  "command": "curate",
  "success": true,
  "data": {
    "ok": true,
    "status": "needs-llm-step",
    "sessionId": "8c3f9e2a-...",
    "step": "generate-html",
    "prompt": "Generate a <bv-topic>...</bv-topic> HTML document for the following user intent:\n\nremember we decided to use RS256\n\n..."
  },
  "timestamp": "2026-05-11T12:00:00.000Z"
}
```

### 2. Calling agent's LLM produces HTML

```html
<bv-topic path="security/auth" title="JWT signing algorithm">
  <bv-decision id="d-rs256">Use RS256 over HS256.</bv-decision>
</bv-topic>
```

### 3. Continuation

```bash
brv curate --session 8c3f9e2a-... --response '{"html":"<bv-topic ...>...</bv-topic>","meta":{"type":"ADD","impact":"high","reason":"Locks JWT alg.","summary":"JWT: RS256."}}' --format json
# Or with the envelope on disk:
brv curate --session 8c3f9e2a-... --response-file envelope.json [--delete-response-file] --format json
```

Response on a valid HTML topic:

```json
{
  "command": "curate",
  "success": true,
  "data": {
    "ok": true,
    "status": "done",
    "filePath": "security/auth.html"
  },
  "timestamp": "2026-05-11T12:00:01.000Z"
}
```

If validation fails (e.g. the agent forgot `path=` on `<bv-topic>`), the envelope instead carries `status: "needs-llm-step"`, `step: "correct-html"`, and `errors[]` for the calling agent to fix. Up to 3 corrections (MAX_ATTEMPTS = 4 total) before terminal `status: "failed"` with `kind: retry-cap-exceeded`.

## Session storage

CLI-side. Per-project, on disk at `<projectRoot>/.brv/sessions/curate-<sessionId>/state.json`. State carries `attempts`, `step` (`awaiting-generate` vs `awaiting-correct`), and the last response (for the correction prompt). State is removed when the session reaches terminal `done` or terminal `failed` (including `retry-cap-exceeded`).

Abandoned sessions are not yet pruned — a 1-hour TTL is a planned follow-up that pairs with moving state into the daemon's existing task-session lifecycle.

## Stability promise

SKILL.md ships against this envelope, so renaming any key here is a breaking change. New error kinds and new step values can be added without breaking existing consumers — calling agents are expected to gracefully ignore unknown values.

## What's not the protocol's job

- **HTML generation.** Calling agent's LLM authors the HTML per the `prompt`. Byterover never touches an LLM in tool mode.
- **Schema knowledge.** Embedded in the `prompt` (the prompt builder condenses the bv-* spec). Calling agent doesn't pre-load any schema.
- **Retry strategy beyond the protocol's correct-html loop.** If the calling agent's LLM keeps producing invalid HTML for 3 rounds, the session terminates `failed` — the calling agent surfaces this and falls back to asking the user for clarification.

---

--- METRICS ---
- Files Extracted: 4
- Estimated Token Budget: ~8464 tokens
- Canonical Reference: https://codewiki.google/github.com/campfirein/byterover-cli
