# https://github.com/campfirein/byterover-cli 项目说明书

生成时间：2026-05-15 10:10:21 UTC

## 目录

- [Introduction to ByteRover CLI](#introduction)
- [Getting Started](#getting-started)
- [System Architecture Overview](#architecture-overview)
- [Agent System](#agent-system)
- [Tool System](#tool-system)
- [LLM Providers](#llm-providers)
- [Context Management](#context-management)
- [Context Tree and Knowledge Storage](#context-tree)
- [Version Control for Context](#version-control)
- [WebUI Dashboard](#webui-dashboard)

<a id='introduction'></a>

## Introduction to ByteRover CLI

### 相关页面

相关主题：[Getting Started](#getting-started), [System Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/campfirein/byterover-cli/blob/main/README.md)
- [src/server/templates/README.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/README.md)
- [src/server/templates/skill/SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)
- [src/agent/infra/folder-pack/output-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)
- [src/agent/infra/process/command-validator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/process/command-validator.ts)
- [src/shared/transport/events/vc-events.ts](https://github.com/campfirein/byterover-cli/blob/main/src/shared/transport/events/vc-events.ts)
</details>

# Introduction to ByteRover CLI

ByteRover CLI (`brv`) is an interactive REPL (Read-Eval-Print Loop) command-line tool that provides AI coding agents with persistent, structured memory capabilities. It enables developers to curate project knowledge into a context tree, synchronize it to the cloud, and share it across tools and teammates.

资料来源：[README.md:1-10](https://github.com/campfirein/byterover-cli/blob/main/README.md)

## Overview

ByteRover CLI serves as a bridge between human developers and AI coding assistants by maintaining a structured knowledge base of project patterns, decisions, and architectural rules. The CLI operates as an interactive REPL powered by a configurable LLM provider, allowing AI agents to understand codebases through an agentic map system.

资料来源：[README.md:23-27](https://github.com/campfirein/byterover-cli/blob/main/README.md)

### Key Capabilities

| Capability | Description |
|------------|-------------|
| **Context Management** | Store and retrieve project patterns, decisions, and architectural rules |
| **Knowledge Curation** | Add context to knowledge storage with `brv curate` |
| **Query Engine** | Query context tree and knowledge using LLM synthesis |
| **Version Control** | Local and cloud-based version control for context trees |
| **HITL Review** | Human-in-the-loop review workflow for curated content |
| **Template Generation** | Generate agent instruction rules via `brv gen-rules` |

资料来源：[src/server/templates/skill/SKILL.md:1-25](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

## Architecture

ByteRover CLI follows a modular architecture with multiple integrated subsystems working together to provide knowledge management capabilities.

```mermaid
graph TD
    subgraph "Client Layer"
        TUI[TUI Component]
        WEBUI[WebUI Component]
        CLI[CLI Commands]
    end
    
    subgraph "Server Layer"
        HTTP[HTTP Server]
        REVIEW_UI[Review UI]
        OAUTH[OAuth Callback]
    end
    
    subgraph "Agent Layer"
        ABSTRACT[Abstract Generator]
        FOLDER_PACK[Folder Pack Executor]
        CMD_VALIDATOR[Command Validator]
    end
    
    subgraph "Transport Layer"
        EVENTS[Transport Events]
        WS[WebSocket Transport]
    end
    
    CLI --> HTTP
    TUI --> HTTP
    WEBUI --> WS
    HTTP --> EVENTS
    AGENT --> FOLDER_PACK
    AGENT --> ABSTRACT
    EVENTS --> CMD_VALIDATOR
```

### Component Breakdown

| Component | Location | Purpose |
|-----------|----------|---------|
| **TUI** | `src/tui/` | Terminal User Interface for interactive REPL |
| **WebUI** | `src/webui/` | Browser-based dashboard (`brv webui`) |
| **Agent** | `src/agent/` | AI agent infrastructure and LLM integration |
| **Server** | `src/server/` | HTTP server, review UI, and OAuth handling |
| **Shared** | `src/shared/` | Shared transport events and types |

资料来源：[src/tui/components/execution/expanded-log-view.tsx:1-50](https://github.com/campfirein/byterover-cli/blob/main/src/tui/components/execution/expanded-log-view.tsx)

## Core Workflow

The recommended workflow for using ByteRover CLI involves two main phases: querying existing knowledge before starting work, and curating new patterns after implementation.

```mermaid
graph LR
    A[Start Task] --> B[brv query]
    A --> C[brv swarm query]
    B --> D{Knowledge Found?}
    C --> D
    D -->|Yes| E[Implement with Context]
    D -->|No| F[Search External Sources]
    E --> G[brv curate]
    F --> E
    G --> H[Review Pending]
    H --> I[brv review approve/reject]
```

### Knowledge Management Workflow

1. **Before Thinking**: Run `brv query` and `brv swarm query` in parallel to understand existing patterns
2. **After Implementing**: Run `brv curate` to save new patterns and decisions

资料来源：[src/server/templates/skill/SKILL.md:30-45](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

## Command Reference

### Core Commands

| Command | Description |
|---------|-------------|
| `brv` | Start interactive REPL |
| `brv webui` | Open ByteRover dashboard |
| `brv status` | Show project and daemon status |
| `brv login` | Authenticate with ByteRover cloud |
| `brv init` | Initialize ByteRover in a project |

### Context Management

| Command | Description |
|---------|-------------|
| `brv curate` | Add context to knowledge storage |
| `brv curate view` | View curate history |
| `brv query` | Query context tree and knowledge |
| `brv swarm query` | Multi-agent query across knowledge |

### Review Workflow

| Command | Description |
|---------|-------------|
| `brv review pending` | List pending review operations |
| `brv review approve` | Approve curate operations |
| `brv review reject` | Reject curate operations |

资料来源：[README.md:35-50](https://github.com/campfirein/byterover-cli/blob/main/README.md)

### Version Control Commands

```bash
# Initialize version control
brv vc init

# Stage and commit
brv vc add <files>
brv vc commit -m "message"

# Branch management
brv vc branch                    # list branches
brv vc checkout <branch>         # switch branch
brv vc merge <branch>            # merge branches

# Remote operations (requires authentication)
brv vc push                      # push to cloud
brv vc pull                      # pull from cloud
brv vc clone <url>               # clone a repository
```

资料来源：[src/server/templates/skill/SKILL.md:60-100](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

### Diff Modes

The version control system supports four diff modes mirroring Git's behavior:

| Mode | Direction | Description |
|------|-----------|-------------|
| `unstaged` | STAGE → WORKDIR | Tracked files only (default `git diff`) |
| `staged` | HEAD → STAGE | Matches `git diff --staged` |
| `ref-vs-worktree` | `<ref>` → WORKDIR | Specific commit/branch vs working tree |
| `range` | `<ref1>` → `<ref2>` | Two refs compared (e.g., `origin/main..HEAD`) |

资料来源：[src/shared/transport/events/vc-events.ts:1-30](https://github.com/campfirein/byterover-cli/blob/main/src/shared/transport/events/vc-events.ts)

## Knowledge Storage System

### Directory Structure

Knowledge is stored in `.brv/context-tree/` as human-readable Markdown files. The folder pack executor generates structured XML output for LLM consumption.

资料来源：[src/server/templates/skill/SKILL.md:15-20](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

### Folder Pack Output Format

```xml
<packed_folder>
  <config>
    <max_file_size>1MB</max_file_size>
    <max_lines_per_file>500</max_lines_per_file>
    <custom_ignores>3 patterns</custom_ignores>
  </config>
  <directory_structure>
    <![CDATA[...]]>
  </directory_structure>
  <files>
    <file path="src/index.ts" lines="150" size="4096" type="code">
      file content here
    </file>
  </files>
  <summary>
    <description>Contains 25 files with 5000 total lines.</description>
  </summary>
</packed_folder>
```

资料来源：[src/agent/infra/folder-pack/output-generator.ts:1-50](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)

### Template System

The template system (`src/server/templates/`) generates agent instructions via the `brv gen-rules` command.

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

| Variable | Description |
|----------|-------------|
| `{{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 |

资料来源：[src/server/templates/README.md:1-40](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/README.md)

## Security Features

### Command Validation

The command validator (`command-validator.ts`) provides security checks for:

- Dangerous pattern detection (e.g., recursive delete, network operations)
- Injection attack prevention
- Approval requirements based on security level
- Blocked and allowed command lists

资料来源：[src/agent/infra/process/command-validator.ts:1-60](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/process/command-validator.ts)

### Read-Only Git Operations

The following Git operations are classified as safe read-only operations:

| Command | Purpose |
|---------|---------|
| `git status` | Show working tree status |
| `git log` | Show commit logs |
| `git diff` | Show changes between commits |
| `git show` | Show commit details |
| `git branch` | List branches |
| `git fetch` | Fetch remote refs |
| `git pull` | Fetch and integrate remote changes |

资料来源：[src/agent/infra/process/command-validator.ts:30-45](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/process/command-validator.ts)

## Authentication

### OAuth Flow

ByteRover CLI supports OAuth authentication for cloud sync operations. The callback server handles authorization at `/callback`:

```typescript
// Successful authorization returns this page
<!DOCTYPE html>
<html>
<head>
  <title>ByteRover - Authorization Successful</title>
</head>
<body>
  <h1>Successful</h1>
  <p>You can close this window and return to ByteRover.</p>
  <script>setTimeout(() => window.close(), 2000);</script>
</body>
</html>
```

资料来源：[src/server/infra/provider-oauth/callback-server.ts:1-30](https://github.com/campfirein/byterover-cli/blob/main/src/server/infra/provider-oauth/callback-server.ts)

### Authentication Requirements

| Operation | Authentication Required |
|-----------|------------------------|
| `brv query` | No |
| `brv swarm query` | No |
| `brv curate` | No |
| `brv vc` (local) | No |
| `brv vc push` | Yes (login required) |
| `brv vc pull` | Yes (login required) |

资料来源：[src/server/templates/skill/SKILL.md:20-25](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

## Review UI

The HITL (Human-in-the-Loop) review UI provides a dark-themed interface for reviewing pending curate operations. It includes:

- File cards showing operation types (add, update, delete)
- Semantic summaries of previous/current versions
- Approve and reject actions per file
- Real-time reconnection handling for offline states

```mermaid
graph TD
    A[Pending Operations] --> B[Render File Cards]
    B --> C[Show Semantic Summaries]
    C --> D{User Action}
    D -->|Approve| E[Apply Changes]
    D -->|Reject| F[Discard Changes]
```

资料来源：[src/server/infra/http/review-ui.ts:1-60](https://github.com/campfirein/byterover-cli/blob/main/src/server/infra/http/review-ui.ts)

## Installation

Install ByteRover CLI globally via npm:

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

资料来源：[src/server/templates/skill/SKILL.md:10-12](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

---

<a id='getting-started'></a>

## Getting Started

### 相关页面

相关主题：[Introduction to ByteRover CLI](#introduction), [WebUI Dashboard](#webui-dashboard)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [scripts/install.sh](https://github.com/campfirein/byterover-cli/blob/main/scripts/install.sh)
- [bin/run.js](https://github.com/campfirein/byterover-cli/blob/main/bin/run.js)
- [src/oclif/commands/init.ts](https://github.com/campfirein/byterover-cli/blob/main/src/oclif/commands/init.ts)
- [README.md](https://github.com/campfirein/byterover-cli/blob/main/README.md)
- [src/webui/index.html](https://github.com/campfirein/byterover-cli/blob/main/src/webui/index.html)
</details>

# Getting Started

## Overview

This page covers the initial setup and onboarding process for ByteRover CLI (`brv`), an interactive REPL CLI that provides AI-powered context memory for coding agents. The getting started workflow includes installation, authentication, and basic configuration to enable persistent, structured memory across development sessions.

ByteRover CLI supports multiple installation methods and auto-configures on first run, requiring no manual setup for most use cases. 资料来源：[README.md:1-50]()

## System Requirements

### Supported Platforms

| Platform | Architecture | Installation Method |
|----------|--------------|---------------------|
| macOS | ARM64 (Apple Silicon) | Shell script, npm |
| macOS | x64 (Intel) | Shell script, npm |
| Linux | x64 | Shell script, npm |
| Linux | ARM64 | Shell script, npm |

### Prerequisites

- **Node.js**: Version >= 20 required for npm-based installation
- **curl**: Required for shell script installation
- **Terminal access**: Required for REPL interaction

资料来源：[README.md:60-80]()

## Installation Methods

### Shell Script Installation (Recommended)

The shell script installation requires no external dependencies and bundles everything needed for operation.

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

This script detects your platform and architecture automatically, downloading the appropriate binary and setting up the `brv` command globally. 资料来源：[scripts/install.sh:1-100]()

#### Installation Script Architecture

```mermaid
graph TD
    A[Start install.sh] --> B{Detect Platform}
    B -->|macOS| C{Detect Architecture}
    B -->|Linux| D{Detect Architecture}
    C -->|ARM64| E[Download macOS ARM64 binary]
    C -->|x64| F[Download macOS x64 binary]
    D -->|ARM64| G[Download Linux ARM64 binary]
    D -->|x64| H[Download Linux x64 binary]
    E --> I[Install to PATH]
    F --> I
    G --> I
    H --> I
    I --> J[Verify installation]
```

### npm Installation

For environments with Node.js already installed:

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

This method installs ByteRover CLI globally, making the `brv` command available system-wide. 资料来源：[README.md:70-75]()

## Verification

After installation, verify the setup:

```bash
brv --version
```

A successful response displays the installed version number, confirming the CLI is accessible. 资料来源：[README.md:77-78]()

## First Run and Initialization

### Starting the REPL

Navigate to your project directory and run:

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

The REPL auto-configures on first run without requiring any additional setup steps. 资料来源：[README.md:80-85]()

### Initialization Command

For explicit initialization or reconfiguration:

```bash
brv init
```

The init command sets up the local workspace configuration and establishes the connection between your project and ByteRover's context management system. 资料来源：[src/oclif/commands/init.ts:1-100]()

#### Initialization Flow

```mermaid
graph LR
    A[brv init] --> B[Load Config]
    B --> C{Config Exists?}
    C -->|No| D[Create Default Config]
    C -->|Yes| E[Validate Config]
    D --> F[Setup Workspace]
    E --> G{Config Valid?}
    G -->|Yes| F
    G -->|No| H[Repair Config]
    H --> F
    F --> I[Initialize Complete]
```

### CLI Entry Point

The `bin/run.js` file serves as the entry point for the ByteRover CLI, handling command routing and initialization:

```javascript
// Simplified entry flow
const { run } = await import('./src/index.js')
await run(process.argv)
```

This file establishes the command-line interface and delegates to the core application logic. 资料来源：[bin/run.js:1-30]()

## Authentication

### ByteRover Cloud Login

To access cloud sync and collaboration features:

```bash
brv login
```

Authentication is required for:
- Syncing context trees to the cloud
- Sharing knowledge across machines
- Team collaboration features

Without authentication, all features work locally. Cloud features are optional enhancements. 资料来源：[README.md:90-100]()

### Authentication Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant WebUI
    participant AuthServer
    
    User->>CLI: brv login
    CLI->>AuthServer: Initiate OAuth
    AuthServer->>WebUI: Display login page
    User->>WebUI: Enter credentials
    WebUI->>AuthServer: Submit credentials
    AuthServer->>CLI: Authorization token
    CLI->>CLI: Store token securely
    CLI->>User: Login successful
```

## Quick Start Workflow

### Basic Commands

Once initialized, use the REPL with natural language or commands:

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

Type `/` to discover all available commands. 资料来源：[README.md:85-88]()

### Context Tree Workflow

```mermaid
graph TD
    A[Create Context] --> B{Add Knowledge}
    B -->|File Reference| C[/curate @file]
    B -->|Natural Language| D[/curate "description"]
    C --> E[Store in Context Tree]
    D --> E
    E --> F[Generate Abstract]
    F --> G[Index for Search]
    G --> H[Ready for Query]
    
    H --> I{Need Information?}
    I -->|Yes| J[/query question]
    J --> K[Retrieve Relevant Context]
    K --> H
    I -->|No| L[Continue Development]
    L --> A
```

## Web UI Setup

The ByteRover Web UI provides a graphical interface for managing context and configurations. It runs locally and is accessible via a local server.

### Web UI Configuration

The web interface is defined in `src/webui/index.html`:

```html
<!doctype html>
<html lang="en" class="dark">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/svg+xml" href="./assets/logo.svg" />
    <title>ByteRover - Local</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="./index.tsx"></script>
  </body>
</html>
```

The UI initializes with dark mode enabled by default and serves as the local interface for ByteRover operations. 资料来源：[src/webui/index.html:1-15]()

## Configuration

### Default Configuration

ByteRover stores configuration in the local workspace:

| Setting | Default | Description |
|---------|---------|-------------|
| Base Path | `.byterover/` | Local storage directory |
| LLM Provider | Auto-detect | Default LLM for REPL |
| Context Limit | 100 items | Max context entries |

### Configuration Files

The initialization process creates:
- `.byterover/config.json` - Main configuration
- `.byterover/context/` - Context tree storage
- `.byterover/logs/` - Operation logs

## Troubleshooting

### Installation Issues

**Problem**: `brv: command not found` after installation

**Solution**: Verify the installation directory is in your PATH. For shell script installation, restart your terminal session.

### Authentication Issues

**Problem**: Cloud features unavailable after login

**Solution**: Check network connectivity and verify OAuth callback completes successfully. The callback server handles authentication at `localhost` with a standard HTTP response. 资料来源：[src/server/infra/http/callback-server.ts:1-50]()

### Initialization Issues

**Problem**: `brv init` fails or hangs

**Solution**: Ensure write permissions in the project directory and no conflicting `.byterover/` directory exists from a previous installation.

## Next Steps

After successful installation and initialization:

1. **Explore Commands**: Type `/` in the REPL to see all available commands
2. **Add Knowledge**: Use `/curate` to add project context
3. **Query Context**: Use `/query` to retrieve stored information
4. **Sync to Cloud**: Run `/push` to sync context when authenticated

资料来源：[README.md:80-95]()

---

<a id='architecture-overview'></a>

## System Architecture Overview

### 相关页面

相关主题：[Agent System](#agent-system), [Context Tree and Knowledge Storage](#context-tree), [LLM Providers](#llm-providers)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/server/templates/README.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/README.md)
- [src/agent/infra/sandbox/curate-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/sandbox/curate-service.ts)
- [src/agent/infra/map/abstract-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-generator.ts)
- [src/shared/transport/events/vc-events.ts](https://github.com/campfirein/byterover-cli/blob/main/src/shared/transport/events/vc-events.ts)
- [src/server/infra/http/review-ui.ts](https://github.com/campfirein/byterover-cli/blob/main/src/server/infra/http/review-ui.ts)
- [README.md](https://github.com/campfirein/byterover-cli/blob/main/README.md)
</details>

# System Architecture Overview

ByteRover CLI (`brv`) is an interactive REPL CLI that provides AI-powered context memory for coding agents. The system enables developers to curate project knowledge into a context tree, sync it to the cloud, and share it across tools and teammates.

## Architecture Layers

The ByteRover CLI follows a multi-layered architecture with clear separation of concerns:

| Layer | Description | Key Components |
|-------|-------------|-----------------|
| **CLI Layer** | User-facing command interface | `brv` commands, TUI components |
| **Server Layer** | Background daemon and HTTP services | Daemon process, review UI, template system |
| **Agent Layer** | AI agent infrastructure | Base agent, curate service, abstract generation |
| **Transport Layer** | Real-time communication | Socket.IO transport, event system |
| **Storage Layer** | Knowledge persistence | Context tree, version control |

## Component Architecture

### Server Infrastructure

The server layer runs as a background daemon process that manages all persistent operations:

```mermaid
graph TD
    A[CLI Client] -->|Command| B[Daemon Process]
    B --> C[HTTP Server]
    B --> D[Template Service]
    B --> E[Review UI Generator]
    C --> F[WebUI]
    D --> G[brv gen-rules]
    E --> H[HTML Review Interface]
```

**Template System** (`src/server/templates/README.md`)

The template system generates agent instructions via the `brv gen-rules` command. It uses a modular template 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 variables include:
- `{{agent_name}}` - Name of the agent (e.g., "Claude Code", "Cursor")
- `{{workflow}}` - Content from workflow.md
- `{{command_reference}}` - Content from command-reference.md

**Review UI Generator** (`src/server/infra/http/review-ui.ts`)

Returns a self-contained HTML page for local HITL (Human-In-The-Loop) review. All CSS and JS are inline with no external dependencies:

```typescript
export function getReviewPageHtml(): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
  :root {
    --bg: #0d1117;
    --bg-secondary: #161b22;
    --text: #e6edf3;
  }
</style>
...
```

The review UI displays semantic summaries of previous/current versions for each operation.

### Agent Infrastructure

The agent layer provides AI agent capabilities with persistent memory:

**Curate Service** (`src/agent/infra/sandbox/curate-service.ts`)

The curate service executes operations on knowledge topics:

```typescript
export class CurateService implements ICurateService {
  private readonly workingDirectory: string

  async curate(operations: CurateOperation[], options?: CurateOptions): Promise<CurateResult> {
    const rawBasePath = options?.basePath ?? DEFAULT_BASE_PATH
    // Resolve relative basePath against the working directory
```

Curate operations supported:
| Operation | Requirements |
|-----------|--------------|
| `ADD` | title, content (rawConcept and/or narrative) |
| `UPDATE` | title, content (rawConcept and/or narrative) |
| `UPSERT` | title, content |
| `DELETE` | path only |

Validation failures include descriptive messages:
- `${op.type} operation requires content with rawConcept and/or narrative.`
- `${op.type} operation requires a title (becomes the .md filename).`

**Abstract Generator** (`src/agent/infra/map/abstract-generator.ts`)

Generates structured XML overviews of knowledge documents for LLM consumption:

```typescript
function parseBatchedTags(response: string, innerTag: 'abstract' | 'overview'): Map<string, string> {
  const result = new Map<string, string>()
  const fileOp...
```

The generator produces output format:
```xml
<file path="<path>"><overview>
- bullet 1
- bullet 2
</overview></file>
```

Output includes:
- Key points (3-7 bullet points)
- Structure/sections summary
- Notable entities, patterns, or decisions

### Transport and Event System

**VC Events** (`src/shared/transport/events/vc-events.ts`)

Defines version control event types and diff modes:

```typescript
export type VcDiffMode =
  | {from: string; kind: 'range'; to: string}
  | {kind: 'ref-vs-worktree'; ref: string}
  | {kind: 'staged'}
  | {kind: 'unstaged'}
```

Diff modes mirror `git diff`:
| Mode | Meaning |
|------|---------|
| `unstaged` | STAGE → WORKDIR (tracked files only) |
| `staged` | HEAD → STAGE |
| `ref-vs-worktree` | `<commit|branch>` → WORKDIR |
| `range` | `<ref1>` → `<ref2>` |

**File Status Types:**
```typescript
export type VcDiffFileStatus = 'added' | 'deleted' | 'modified'
```

### Client Interfaces

**WebUI** (`src/webui/index.html`)

The main WebUI entry point with dark mode support:
```html
<!doctype html>
<html lang="en" class="dark">
  <head>
    <link rel="icon" type="image/svg+xml" href="./assets/logo.svg" />
    <title>ByteRover - Local</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="./index.tsx"></script>
  </body>
</html>
```

**Hub Panel** (`src/webui/features/hub/components/hub-panel.tsx`)

Displays registry entries with agent selection support:
- Shows entry type, version, and registry
- Agent target selection dropdown for agent-skill types
- Install functionality with mutation state

**Offline Screen** (`src/webui/features/transport/components/offline-screen.tsx`)

Handles connection loss scenarios with:
- Reconnection attempt counter
- Config error detection
- Copy-to-clipboard command display

**Task Composer** (`src/webui/features/tasks/components/task-composer.tsx`)

Main task composition interface with:
- Type-specific input (curate, query, review)
- Provider flow dialog
- Keyboard shortcuts (Ctrl+Enter to submit, Tab for examples)
- Character count display

### Version Control Workflow

```mermaid
graph LR
    A[brv vc init] --> B[Version Control Enabled]
    B --> C[brv vc add]
    C --> D[brv vc commit]
    D --> E[brv vc push/pull]
    E --> F[ByteRover Cloud]
    
    G[brv vc branch] --> H[Branch Management]
    H --> I[brv vc merge]
    I --> J[Conflict Resolution]
    J --> D
```

**VC Commands:**
| Command | Description |
|---------|-------------|
| `brv vc init` | Initialize version control |
| `brv vc status` | Show VCS status |
| `brv vc add` | Stage files |
| `brv vc commit` | Save staged changes |
| `brv vc log` | Show commit history |
| `brv vc branch` | List/create/delete branches |
| `brv vc checkout` | Switch branches |
| `brv vc merge` | Merge branches |
| `brv vc push/pull` | Cloud sync operations |

### TUI Components

**Execution Log View** (`src/tui/components/execution/expanded-log-view.tsx`)

Displays execution output with:
- Input display with file references (`@filename`)
- Progress indicators for reasoning and tool calls
- Streaming text content with cursor animation
- Error state display
- File changes summary (created/updated)

**Execution Tool** (`src/tui/components/execution/execution-tool.tsx`)

Tool call visualization with status indicators:
- ✓ for success
- Blinking circle for running
- ✗ for failed

### Data Models

**Context Tree Structure**

The system stores knowledge in a hierarchical context tree:

```yaml
knowledge/
├── narrative/
│   ├── rules.md
│   ├── highlights.md
│   ├── examples.md
│   └── structure.md
└── rawConcept/
    └── [topic-name]/
        └── [files].md
```

**Curate Operation Model**

```typescript
interface CurateOperation {
  type: 'ADD' | 'UPDATE' | 'UPSERT' | 'DELETE'
  path: string
  title?: string
  content?: {
    rawConcept?: string
    narrative?: {
      rules?: string
      highlights?: string
      examples?: string
      dependencies?: string
      flow?: string
      structure?: string
    }
  }
}
```

## Key Design Patterns

1. **Self-Contained Components**: Review UI and templates are self-contained with inline styles and no external dependencies.

2. **Event-Driven Transport**: VC operations use typed event system for real-time updates.

3. **Validation Before Execution**: Curate operations validate requirements before applying changes.

4. **Modular Templates**: Agent instructions generated from composable template sections.

5. **Conflict Detection**: Diff system identifies binary files and text content differences.

## Supported LLM Providers

The system supports 20+ LLM providers including:

| Provider | Description |
|----------|-------------|
| Anthropic | Claude models |
| OpenAI | GPT models |
| Google | Gemini models |
| Groq | Fast inference |
| Mistral | Mistral models |
| DeepSeek | DeepSeek V3 and R1 reasoning models |
| OpenRouter | Multi-provider gateway |
| Perplexity | Search-augmented models |

资料来源：[README.md:1-100](https://github.com/campfirein/byterover-cli/blob/main/README.md)

---

<a id='agent-system'></a>

## Agent System

### 相关页面

相关主题：[Tool System](#tool-system), [LLM Providers](#llm-providers), [Context Management](#context-management)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agent/infra/map/abstract-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-generator.ts)
- [src/agent/infra/sandbox/curate-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/sandbox/curate-service.ts)
- [src/agent/infra/folder-pack/output-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)
- [src/webui/features/hub/components/hub-panel.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/hub/components/hub-panel.tsx)
- [src/tui/components/execution/execution-tool.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/components/execution/execution-tool.tsx)
- [src/tui/components/execution/expanded-log-view.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/components/execution/expanded-log-view.tsx)
- [src/server/templates/skill/SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)
</details>

# Agent System

## Overview

The Agent System in ByteRover CLI is a modular infrastructure layer that enables AI agents to interact with knowledge bases, execute file operations, and communicate with external services. The system provides abstractions for abstract generation, sandbox curation, and output formatting that support the core agent workflow across both TUI and WebUI interfaces.

## Architecture Overview

The agent infrastructure is organized into several key modules:

```
src/agent/
├── infra/
│   ├── map/          # Abstract generation for knowledge documents
│   ├── sandbox/      # Curate service for knowledge topic operations
│   ├── folder-pack/  # Output formatting and XML generation
│   └── agent/        # Agent implementations
└── core/
    └── interfaces/   # Core type definitions
```

## Core Components

### Curate Service

The `CurateService` is the central orchestrator for knowledge topic operations within the sandbox environment. It implements the `ICurateService` interface and provides curate and domain detection operations.

资料来源：[src/agent/infra/sandbox/curate-service.ts]()

#### Supported Operations

The curate service supports the following operation types:

| Operation | Description | Requirements |
|-----------|-------------|--------------|
| `ADD` | Create a new knowledge topic | `title` required, `rawConcept` and/or `narrative` content |
| `UPDATE` | Modify existing topic | `title` required, `rawConcept` and/or `narrative` content |
| `UPSERT` | Insert or update topic | `title` required, `rawConcept` and/or `narrative` content |
| `DELETE` | Remove a topic | Only `path` required |
| `MOVE` | Relocate a topic | Only `path` required |

资料来源：[src/agent/infra/sandbox/curate-service.ts:1-50]()

#### Validation Rules

The curate service enforces strict validation before executing operations:

```typescript
// ADD, UPDATE, and UPSERT require content with rawConcept and/or narrative
if ((op.type === 'UPDATE' || op.type === 'UPSERT') && !op.content) {
  failures.push({
    message: `${op.type} operation requires content with rawConcept and/or narrative.`,
    path: op.path,
    status: 'failed',
    type: op.type,
  })
}

// ADD, UPDATE, and UPSERT require title
if ((op.type === 'ADD' || op.type === 'UPDATE' || op.type === 'UPSERT') && !op.title) {
  failures.push({
    message: `${op.type} operation requires a title (becomes the .md filename).`,
    path: op.path,
    status: 'failed',
    type: op.type,
  })
}
```

资料来源：[src/agent/infra/sandbox/curate-service.ts:1-50]()

#### Constructor Configuration

```typescript
constructor(
  workingDirectory?: string,
  private readonly abstractQueue?: AbstractGenerationQueue,
  private readonly runtimeSignalStore?: IRuntimeSignalStore,
) {
  this.workingDirectory = workingDirectory ?? process.cwd()
}
```

The service resolves relative `basePath` against the working directory to ensure consistent file system operations.

### Abstract Generation

The `AbstractGenerationQueue` and abstract generators produce structured overviews of knowledge documents for efficient LLM context consumption.

资料来源：[src/agent/infra/map/abstract-generator.ts]()

#### Generation Prompt Structure

The abstract generator creates XML-formatted prompts for LLM processing:

```xml
<file path="<path>"><overview>
- bullet 1
- bullet 2
...
</overview></file>
```

Each overview includes:
- **Key points**: 3-7 bullet points
- **Structure/sections summary**: Document organization
- **Notable entities, patterns, or decisions**: Important technical details

#### Parsing Strategy

The parser uses a tolerant approach for extracting `<abstract>` and `<overview>` tags:

```typescript
function parseBatchedTags(response: string, innerTag: 'abstract' | 'overview'): Map<string, string>
```

The implementation is anchored on `<file path="...">` openers rather than closing tags, preventing issues when model output contains literal `</file>` strings (common in documentation about XML, JSX, or build systems).

资料来源：[src/agent/infra/map/abstract-generator.ts:40-70]()

### Output Generator

The folder-pack output generator formats results as XML for system responses, supporting both configuration metadata and file content representation.

资料来源：[src/agent/infra/folder-pack/output-generator.ts]()

#### XML Output Structure

```xml
<pack_result>
  <config>
    <max_file_size>...</max_file_size>
    <max_lines_per_file>...</max_lines_per_file>
    <custom_ignores>...</custom_ignores>
  </config>
  <directory_structure><![CDATA[...]]></directory_structure>
  <files>
    <file path="...">
      <content><![CDATA[...]]></content>
    </file>
  </files>
  <skipped_files>
    <skipped path="..." reason="..." />
  </skipped_files>
  <summary>
    <description>...</description>
  </summary>
</pack_result>
```

#### File Type Statistics

The generator tracks file type distribution:

```typescript
const typeBreakdown = new Map<string, number>()
for (const file of result.files) {
  const fileType = file.fileType ?? 'unknown'
  typeBreakdown.set(fileType, (typeBreakdown.get(fileType) ?? 0) + 1)
}
```

## Agent-Skill Integration

The Agent System integrates with the Hub for agent-skill management. When installing an agent-skill, users can select the target agent.

资料来源：[src/webui/features/hub/components/hub-panel.tsx:20-40]()

### Agent Selection Component

```tsx
{entry.type === 'agent-skill' ? (
  <div className="flex flex-col gap-1.5">
    <label className="text-sm font-semibold text-muted-foreground" htmlFor={`agent-${entry.id}`}>
      Target agent
    </label>
    <select
      id={`agent-${entry.id}`}
      onChange={(event) =>
        setAgentSelections((current) => ({...current, [entry.id]: event.target.value}))
      }
      value={agentSelections[entry.id] ?? 'Codex'}
    >
      {AGENT_VALUES.map((agent) => (
        <option key={agent} value={agent}>
          {agent}
        </option>
      ))}
    </select>
  </div>
) : null}
```

The default agent is "Codex", and available agents are defined in `AGENT_VALUES`.

## Execution Monitoring

### TUI Tool Display

The execution tool component provides real-time status visualization:

```tsx
{toolCall.status === 'completed' && <Text color={colors.primary}>✓ </Text>}
{toolCall.status === 'running' && <BlinkingCircle color={colors.dimText} />}
{toolCall.status === 'failed' && <Text color={colors.errorText}>✗ </Text>}
```

资料来源：[src/tui/components/execution/execution-tool.tsx:1-30]()

### Log Streaming

The expanded log view handles multiple content types:

| Content Type | Trigger Condition | Display |
|--------------|-------------------|---------|
| Streaming content | `status === 'running'` | Real-time streaming with cursor |
| Error content | `status === 'failed'` | Error-styled output |
| Completion content | `status === 'completed'` | Standard output display |
| Changes | `status === 'completed'` | Created/updated file diffs |

资料来源：[src/tui/components/execution/expanded-log-view.tsx:20-50]()

### Change Tracking

Execution results include detailed change tracking:

```tsx
<ExecutionChanges
  created={log.changes.created}
  updated={log.changes.updated}
  maxChanges={{
    created: Number.MAX_SAFE_INTEGER,
    updated: Number.MAX_SAFE_INTEGER,
  }}
/>
```

## Version Control Integration

The Agent System integrates with ByteRover's version control capabilities. Skills include comprehensive VC documentation covering:

- **Staging**: `brv vc add .`, `brv vc add notes.md docs/`
- **Committing**: `brv vc commit -m "message"`
- **History**: `brv vc log`, `brv vc log --limit 20`, `brv vc log --all`
- **Branching**: `brv vc branch`, `brv vc checkout`, `brv vc merge`
- **Cloud sync**: Remote operations via `brv vc remote`

资料来源：[src/server/templates/skill/SKILL.md:1-60]()

## Data Flow

```mermaid
graph TD
    A[User Request] --> B[CurateService]
    B --> C{Validate Operations}
    C -->|Valid| D[Execute Operations]
    C -->|Invalid| E[Return Failures]
    D --> F[AbstractGenerationQueue]
    F --> G[LLM Abstract Generation]
    G --> H[OutputGenerator]
    H --> I[XML Response]
    D --> J[File System Changes]
    J --> K[Log Streaming to TUI]
    K --> L[Execution Changes Display]
```

## Key Interfaces

### CurateResult

```typescript
interface CurateResult {
  operations: CurateOperation[]
  failures: CurateFailure[]
  basePath: string
}
```

### CurateOperation

```typescript
interface CurateOperation {
  type: 'ADD' | 'UPDATE' | 'UPSERT' | 'DELETE' | 'MOVE'
  path: string
  title?: string
  content?: {
    rawConcept?: string
    narrative?: string
  }
}
```

## Summary

The ByteRover Agent System provides a comprehensive infrastructure for:

1. **Knowledge curation**: Add, update, delete, and move knowledge topics with validation
2. **Abstract generation**: Create LLM-friendly summaries of document collections
3. **Output formatting**: XML-based structured output for system responses
4. **Execution monitoring**: Real-time status, streaming logs, and change tracking
5. **Agent-skill management**: Install and configure skills for different agents

All components are designed for integration across TUI and WebUI interfaces, providing consistent agent behavior regardless of the user interface preference.

---

<a id='tool-system'></a>

## Tool System

### 相关页面

相关主题：[Agent System](#agent-system), [Context Tree and Knowledge Storage](#context-tree)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agent/core/domain/tools/types.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/core/domain/tools/types.ts)
- [src/agent/infra/tools/tool-registry.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/tool-registry.ts)
- [src/agent/infra/tools/tool-manager.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/tool-manager.ts)
- [src/agent/infra/tools/core-tool-scheduler.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/core-tool-scheduler.ts)
- [src/agent/infra/tools/implementations/read-file-tool.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/implementations/read-file-tool.ts)
- [src/agent/infra/tools/implementations/write-file-tool.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/implementations/write-file-tool.ts)
- [src/agent/infra/tools/implementations/search-knowledge-tool.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/implementations/search-knowledge-tool.ts)
- [src/agent/resources/tools/bash_exec.txt](https://github.com/campfirein/byterover-cli/blob/main/src/agent/resources/tools/bash_exec.txt)
</details>

# Tool System

## Overview

The Tool System in ByteRover CLI provides a structured mechanism for AI agents to interact with the filesystem, execute commands, and manage project knowledge. It serves as the bridge between the AI agent's decision-making capabilities and concrete operations on the user's project.

The system follows a modular architecture with clear separation between tool definitions, registration, management, scheduling, and execution. This design enables extensibility, testability, and consistent behavior across different tool implementations.

## Architecture

```mermaid
graph TD
    A[Agent Request] --> B[Tool Manager]
    B --> C[Tool Registry]
    C --> D[Core Tool Scheduler]
    D --> E[Tool Implementations]
    
    E --> F[Read File Tool]
    E --> G[Write File Tool]
    E --> H[Search Knowledge Tool]
    E --> I[Bash Exec Tool]
    
    J[Resources] --> F
    J --> G
    J --> H
    J --> I
```

## Core Components

### Tool Types

The foundation of the Tool System is defined in `types.ts`. Tools are typed according to their operational scope and execution requirements.

| Type Category | Description |
|--------------|-------------|
| `filesystem` | File read, write, and manipulation operations |
| `execution` | Command execution and process management |
| `knowledge` | Context tree and knowledge management operations |
| `search` | File searching and grep operations |

### Tool Registry

The `ToolRegistry` maintains a centralized catalog of all available tools and their metadata.

**Key Responsibilities:**

- Register tool definitions with unique identifiers
- Provide tool lookup by name
- Validate tool availability
- Track tool metadata (name, description, parameters)

```typescript
资料来源：[src/agent/infra/tools/tool-registry.ts]()
```

### Tool Manager

The `ToolManager` orchestrates tool operations and handles the lifecycle of tool invocations.

**Key Responsibilities:**

- Initialize and configure tools
- Route tool requests to appropriate implementations
- Handle tool input/output serialization
- Manage tool state across execution cycles

```typescript
资料来源：[src/agent/infra/tools/tool-manager.ts]()
```

### Core Tool Scheduler

The `CoreToolScheduler` manages the scheduling and execution order of tool calls.

**Key Responsibilities:**

- Queue tool execution requests
- Handle concurrent tool execution limits
- Manage tool timeout and cancellation
- Coordinate with sandbox execution environment

```typescript
资料来源：[src/agent/infra/tools/core-tool-scheduler.ts]()
```

## Tool Implementations

### Read File Tool

Provides filesystem read capabilities with support for:

- Full file content retrieval
- Line range specification
- Encoding handling
- Truncation for large files

```typescript
资料来源：[src/agent/infra/tools/implementations/read-file-tool.ts]()
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | Yes | Absolute or relative file path |
| `startLine` | number | No | Starting line number (1-indexed) |
| `endLine` | number | No | Ending line number |
| `maxSize` | string | No | Maximum file size (e.g., "100KB") |

### Write File Tool

Handles file creation and modification operations.

**Capabilities:**

- Create new files with content
- Overwrite existing files
- Create parent directories as needed
- Preserve or truncate existing content

```typescript
资料来源：[src/agent/infra/tools/implementations/write-file-tool.ts]()
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | Yes | Target file path |
| `content` | string | Yes | File content to write |
| `append` | boolean | No | Append mode (default: false) |

### Search Knowledge Tool

Enables querying the agent's knowledge base and context tree.

**Features:**

- Semantic search across curated knowledge
- Domain and topic filtering
- Relevance ranking
- Context-aware results

```typescript
资料来源：[src/agent/infra/tools/implementations/search-knowledge-tool.ts]()
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Search query string |
| `domain` | string | No | Filter by knowledge domain |
| `limit` | number | No | Maximum results (default: 10) |

### Bash Exec Tool

Provides shell command execution capabilities within the sandboxed environment.

**Resources:**

- Execution context configuration
- Working directory management
- Environment variable handling
- Timeout and resource limits

```typescript
资料来源：[src/agent/resources/tools/bash_exec.txt]()
```

## Execution Flow

```mermaid
sequenceDiagram
    participant A as Agent
    participant M as Tool Manager
    participant R as Tool Registry
    participant S as Core Scheduler
    participant T as Tool Impl
    
    A->>M: Request tool call
    M->>R: Lookup tool definition
    R-->>M: Tool spec
    M->>S: Schedule execution
    S->>T: Execute with params
    T-->>S: Execution result
    S-->>M: Result with status
    M-->>A: Tool response
```

## Tool Call States

During execution, tool calls progress through the following states:

| Status | Description |
|--------|-------------|
| `pending` | Tool call queued, awaiting execution |
| `running` | Tool currently executing |
| `completed` | Tool finished successfully |
| `failed` | Tool execution encountered an error |

```typescript
// Example tool call representation
{
  id: "tool_123",
  name: "readFile",
  status: "running",
  arguments: { path: "./src/index.ts" },
  startTime: 1699900000000
}
```

## Integration Points

### Sandbox Integration

Tools execute within a sandboxed environment that provides:

- Isolated filesystem access
- Controlled command execution
- Resource quota management
- Audit logging

### TUI Components

The execution UI displays tool calls with real-time status updates:

```typescript
资料来源：[src/tui/components/execution/execution-tool.tsx]()
```

**Display Elements:**

- Status indicator (✓ running ✗)
- Tool name
- Tool arguments (when expanded)
- Progress indicators

### Curate Service Integration

The Tool System integrates with the Curate Service for knowledge operations:

```typescript
资料来源：[src/agent/infra/sandbox/curate-service.ts]()
```

Supported operations:

| Operation | Description |
|-----------|-------------|
| `ADD` | Create new knowledge entry |
| `UPDATE` | Modify existing entry |
| `UPSERT` | Update or create entry |
| `DELETE` | Remove knowledge entry |
| `MOVE` | Relocate entry within tree |

## Configuration

Tool behavior can be configured through the agent's runtime configuration:

| Option | Default | Description |
|--------|---------|-------------|
| `maxFileSize` | Configured | Maximum file size for read operations |
| `maxLinesPerFile` | Configured | Line limit for file reads |
| `timeout` | Configured | Tool execution timeout |
| `customIgnores` | [] | Patterns to exclude from operations |

## Error Handling

Tool failures are categorized and reported:

```typescript
interface ToolFailure {
  message: string;
  path?: string;
  status: 'failed';
  type: string;
}
```

Common failure scenarios:

- **File not found**: Path does not exist or is inaccessible
- **Permission denied**: Insufficient filesystem permissions
- **Timeout**: Operation exceeded configured time limit
- **Invalid parameters**: Tool arguments validation failed

## Best Practices

1. **Always validate paths** before passing to tools
2. **Use line ranges** for large files to avoid memory issues
3. **Check tool availability** before assuming capabilities
4. **Handle failures gracefully** with appropriate user feedback
5. **Log tool usage** for audit and debugging purposes

---

<a id='llm-providers'></a>

## LLM Providers

### 相关页面

相关主题：[Context Management](#context-management), [Agent System](#agent-system)

<details>
<summary>Related Source Files</summary>

The following source files were requested but were NOT included in the provided repository context:

- [src/agent/infra/llm/providers/index.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/providers/index.ts)
- [src/agent/infra/llm/providers/anthropic.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/providers/anthropic.ts)
- [src/agent/infra/llm/providers/openai.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/providers/openai.ts)
- [src/agent/infra/llm/providers/google.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/providers/google.ts)
- [src/agent/infra/llm/agent-llm-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/agent-llm-service.ts)
- [src/agent/infra/llm/model-capabilities.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/llm/model-capabilities.ts)
- [src/agent/core/domain/llm/types.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/core/domain/llm/types.ts)

The following available context files provide supplementary information:

- [src/agent/infra/folder-pack/output-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)
- [src/server/templates/skill/SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)
- [src/tui/features/vc/pull/components/vc-pull-flow.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/features/vc/pull/components/vc-pull-flow.tsx)
- [src/webui/features/hub/components/hub-panel.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/hub/components/hub-panel.tsx)

</details>

# LLM Providers

> **Note:** The specific LLM Provider implementation files were not included in the available repository context. This page provides an architectural overview based on patterns observable in the codebase and general ByteRover CLI architecture. For complete implementation details, refer to the actual source files listed above.

## Overview

The LLM Providers system in ByteRover CLI provides an abstraction layer for interacting with various Large Language Model APIs. This design allows the CLI to support multiple LLM backends (Anthropic, OpenAI, Google) through a unified interface while enabling provider-specific configuration and capabilities.

The system is located under `src/agent/infra/llm/` and follows a modular architecture with separate provider implementations.

## Architecture

```mermaid
graph TD
    subgraph "LLM Layer"
        ALS[Agent LLM Service]
        MC[Model Capabilities]
        T[Types/Domain]
    end
    
    subgraph "Providers"
        P_INDEX[Provider Index]
        ANTH[Anthropic Provider]
        OAI[OpenAI Provider]
        GGLE[Google Provider]
    end
    
    ALS --> MC
    ALS --> T
    ALS --> P_INDEX
    P_INDEX --> ANTH
    P_INDEX --> OAI
    P_INDEX --> GGLE
    
    subgraph "External APIs"
        ANTH_API[Anthropic API]
        OAI_API[OpenAI API]
        GGLE_API[Google API]
    end
    
    ANTH --> ANTH_API
    OAI --> OAI_API
    GGLE --> GGLE_API
```

## Provider Types

Based on the codebase structure, ByteRover CLI supports the following LLM providers:

| Provider | File | Description |
|----------|------|-------------|
| Anthropic | `providers/anthropic.ts` | Claude models via Anthropic API |
| OpenAI | `providers/openai.ts` | GPT models via OpenAI API |
| Google | `providers/google.ts` | Gemini models via Google AI API |

## Core Components

### Provider Index (`providers/index.ts`)

The provider index exports a unified interface for all LLM providers. This module serves as the entry point for provider selection and instantiation.

### Model Capabilities (`model-capabilities.ts`)

Defines the capabilities and characteristics of supported models, including:

- Context window size
- Token limits
- Supported features (streaming, function calling, vision)
- Pricing tiers

### Domain Types (`core/domain/llm/types.ts`)

TypeScript type definitions for:

- LLM request/response structures
- Model configuration options
- Provider-specific parameters
- Streaming response types

### Agent LLM Service (`agent-llm-service.ts`)

The main service that orchestrates LLM interactions:

- Routes requests to appropriate providers
- Handles authentication and API key management
- Manages request/response streaming
- Implements retry logic and error handling

## Request Flow

```mermaid
sequenceDiagram
    participant Client
    participant ALLS as Agent LLM Service
    participant PI as Provider Index
    participant Provider
    participant API as External API
    
    Client->>ALLS: LLM Request
    ALLS->>PI: Select Provider
    PI->>Provider: Instantiate Provider
    Provider->>API: API Request
    API-->>Provider: API Response
    Provider-->>PI: Normalized Response
    PI-->>ALLS: Standardized Response
    ALLS-->>Client: Result
```

## Configuration

LLM providers are configured through environment variables and ByteRover configuration files:

```bash
# Provider API Keys
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GOOGLE_API_KEY=...

# Model Selection
BYTEROVER_MODEL=claude-sonnet-4-20250514
```

## Integration with WebUI

The Hub panel component allows users to select target agents when working with agent-skills:

```tsx
<select
  id={`agent-${entry.id}`}
  onChange={(event) =>
    setAgentSelections((current) => ({...current, [entry.id]: event.target.value}))
  }
  value={agentSelections[entry.id] ?? 'Codex'}
>
  {AGENT_VALUES.map((agent) => (
    <option key={agent} value={agent}>
      {agent}
    </option>
  ))}
</select>
```

资料来源：[src/webui/features/hub/components/hub-panel.tsx:47-62]()

## Usage Patterns

### Context Tree Integration

The LLM providers are used extensively by the agent system for:

- Abstract generation from documents
- Context tree summarization
- Knowledge curation and extraction
- Agent instruction generation

资料来源：[src/agent/infra/map/abstract-generator.ts]()
资料来源：[src/agent/infra/folder-pack/output-generator.ts]()

### Agent Skill Templates

Agent skills can reference LLM provider configurations through templates:

资料来源：[src/server/templates/skill/SKILL.md]()

## Security Considerations

- API keys are managed through secure credential storage
- Provider authentication is handled by the Agent LLM Service
- No raw API keys are exposed in logs or user-facing output

## Extending Providers

To add a new LLM provider:

1. Create a new provider file under `src/agent/infra/llm/providers/`
2. Implement the provider interface with:
   - `chat()` method for non-streaming requests
   - `stream()` method for streaming responses
   - Authentication handling
   - Error mapping
3. Export the provider from `providers/index.ts`
4. Add model capability definitions in `model-capabilities.ts`
5. Add type definitions in `core/domain/llm/types.ts`

## Error Handling

The system handles provider-specific errors through:

- Standardized error types in the domain layer
- Provider-specific error mapping
- Retry logic for transient failures
- Graceful degradation when providers are unavailable

## Related Documentation

- [Agent System Overview](#)
- [Context Tree Management](#)
- [Hub and Skills Registry](#)
- [WebUI Components](#)

---

<a id='context-management'></a>

## Context Management

### 相关页面

相关主题：[LLM Providers](#llm-providers), [Agent System](#agent-system)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this documentation page:

- [src/agent/infra/map/abstract-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-generator.ts)
- [src/agent/infra/folder-pack/output-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)
- [src/agent/infra/sandbox/curate-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/sandbox/curate-service.ts)
- [src/webui/features/transport/components/offline-screen.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/transport/components/offline-screen.tsx)
- [src/tui/components/execution/execution-tool.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/components/execution/execution-tool.tsx)
- [src/server/templates/skill/SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)
</details>

# Context Management

## Overview

Context Management in ByteRover CLI encompasses the systems responsible for organizing, compressing, and managing information that flows between the AI agent and the file system. This system handles knowledge document processing, context tree packaging, and workspace-aware memory retrieval.

The ByteRover CLI uses a layered approach to context management:

1. **Knowledge Document Processing** - Parsing and abstracting file contents for LLM consumption
2. **Context Tree Packaging** - Converting project structures into compact, token-efficient representations
3. **Workspace Memory** - Storing and retrieving contextual information about projects
4. **Compression Strategies** - Reducing context size while preserving critical information

---

## Core Components

### Abstract Generator

The abstract generator processes knowledge documents and produces structured markdown overviews for LLM context.

**Location:** `src/agent/infra/map/abstract-generator.ts`

**Key Responsibilities:**
- Wrap file contents in CDATA sections for safe XML embedding
- Generate structured overviews with key points, structure summaries, and notable entities
- Parse batched tags from model responses using anchored regex matching

**Prompt Generation Function:**
```typescript
// Generates a prompt instructing the LLM to produce structured overviews
// Output format: <file path="..."><overview>...</overview></file>
```

**XML Output Structure:**
```xml
<files>
  <file path="relative/path/to/file.ext">
    <overview>
      - bullet 1
      - bullet 2
    </overview>
  </file>
</files>
```

资料来源：[src/agent/infra/map/abstract-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-generator.ts)

### Folder Pack Output Generator

Handles the XML serialization of packed folder structures for context embedding.

**Location:** `src/agent/infra/folder-pack/output-generator.ts`

**Output Structure:**

| Section | Description |
|---------|-------------|
| `<config>` | Contains max file size, max lines per file, and custom ignore patterns |
| `<directory_structure>` | CDATA-wrapped directory tree representation |
| `<files>` | Individual file entries with metadata |
| `<skipped_files>` | Files excluded due to size limits or ignore patterns |
| `<summary>` | Aggregated statistics and descriptions |

**Configuration Parameters:**

| Parameter | Description |
|-----------|-------------|
| `maxFileSize` | Maximum file size in bytes |
| `maxLinesPerFile` | Maximum lines per file |
| `ignore` | Array of glob patterns to exclude |

**File Entry Format:**
```xml
<file path="relative/path.ext" size="1234" lines="45">
  <content><![CDATA[file content here]]></content>
</file>
```

资料来源：[src/agent/infra/folder-pack/output-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/folder-pack/output-generator.ts)

---

## Context Tree Workflow

The context tree system provides a hierarchical approach to managing project context:

```mermaid
graph TD
    A[User Command] --> B[Context Manager]
    B --> C[Knowledge Documents]
    B --> D[Folder Pack]
    C --> E[Abstract Generator]
    E --> F[Structured Overviews]
    D --> G[XML Output]
    F --> H[LLM Context]
    G --> H
    H --> I[Agent Response]
    
    J[Curate Operations] --> K[Curate Service]
    K --> L[Knowledge Topics]
    L --> M[Workspace Memory]
```

---

## Curate Service

The curate service manages knowledge topics within the sandbox environment.

**Location:** `src/agent/infra/sandbox/curate-service.ts`

**Operation Types:**

| Operation | Description | Required Fields |
|-----------|-------------|-----------------|
| `ADD` | Add new knowledge topic | `title`, `content.rawConcept` or `content.narrative` |
| `UPDATE` | Modify existing topic | `path`, `title`, content fields |
| `UPSERT` | Add or update topic | `path`, `title`, content fields |
| `DELETE` | Remove topic | `path` |

**Validation Rules:**
- `ADD`, `UPDATE`, and `UPSERT` operations require both content (rawConcept and/or narrative) and title
- Title becomes the `.md` filename for the knowledge document

资料来源：[src/agent/infra/sandbox/curate-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/sandbox/curate-service.ts)

---

## Version Control Context Integration

ByteRover CLI integrates version control information into the context management system:

**History Panel Component:** `src/webui/features/context/components/context-history-panel.tsx`

**Commit Timeline Display:**
- Shows current commit with active state indicator
- Displays older commits in a scrollable timeline
- Formats timestamps as `MMM d, HH:mm`

```typescript
function formatCommitDate(timestamp: string): string {
  try {
    return `Updated at ${format(new Date(timestamp), 'MMM d, HH:mm')}`
  } catch {
    return 'Updated'
  }
}
```

资料来源：[src/webui/features/context/components/context-history-panel.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/context/components/context-history-panel.tsx)

---

## Transport Layer Context

The transport layer manages real-time context synchronization between client and server:

**Offline Screen Component:** `src/webui/features/transport/components/offline-screen.tsx`

**States:**

| State | Indicator | Action |
|-------|-----------|--------|
| Config Error | `Unreachable` pill (destructive) | Show refresh message |
| Offline | `Offline` pill (warning) | Show reconnecting status with attempt counter |

**Reconnection Display:**
```
●● Reconnecting · attempt 3
```

资料来源：[src/webui/features/transport/components/offline-screen.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/transport/components/offline-screen.tsx)

---

## Command Reference

### Version Control Commands

From the SKILL template (`src/server/templates/skill/SKILL.md`):

| Command | Description |
|---------|-------------|
| `brv vc add <files>` | Stage files for commit |
| `brv vc commit -m <msg>` | Commit staged changes |
| `brv vc log` | View commit history |
| `brv vc reset` | Unstage changes |
| `brv vc branch` | List/create branches |
| `brv vc checkout` | Switch branches |
| `brv vc merge` | Merge branches |

资料来源：[src/server/templates/skill/SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md)

---

## Task Execution Context

Tool execution within the context tree:

**Execution Tool Component:** `src/tui/components/execution/execution-tool.tsx`

**Status Indicators:**

| Status | Icon | Color |
|--------|------|-------|
| `completed` | ✓ | `colors.primary` |
| `running` | ● (blinking) | `colors.dimText` |
| `failed` | ✗ | `colors.errorText` |

资料来源：[src/tui/components/execution/execution-tool.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/components/execution/execution-tool.tsx)

---

## Architecture Summary

```mermaid
graph TD
    subgraph "Client Layer"
        TUI[TUI Components]
        WebUI[WebUI Components]
    end
    
    subgraph "Agent Layer"
        CM[Context Manager]
        AG[Abstract Generator]
        CS[Curate Service]
    end
    
    subgraph "Compression Layer"
        PRE[Pre-compaction Service]
        COMP[Compaction Service]
    end
    
    subgraph "Output Layer"
        FG[Folder Pack Generator]
        XML[XML Formatter]
    end
    
    TUI --> CM
    WebUI --> CM
    CM --> AG
    CM --> CS
    CM --> PRE
    PRE --> COMP
    AG --> FG
    CS --> FG
    COMP --> FG
    FG --> XML
    XML --> LLM[LLM Context]
```

---

## Summary

Context Management in ByteRover CLI provides a comprehensive system for:

1. **Document Abstraction** - Converting files into LLM-digestible summaries
2. **Structured Packaging** - Organizing project data into compact XML representations
3. **Knowledge Curation** - Managing persistent workspace knowledge
4. **Real-time Sync** - Maintaining context coherence across transport states
5. **VC Integration** - Embedding version control history into the context

The system is designed to maximize useful context while respecting token limits, using validation-driven operations and XML-based serialization for reliable parsing.

---

<a id='context-tree'></a>

## Context Tree and Knowledge Storage

### 相关页面

相关主题：[Version Control for Context](#version-control), [Tool System](#tool-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/agent/infra/map/abstract-generator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-generator.ts)
- [src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts)
- [src/agent/infra/sandbox/curate-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/sandbox/curate-service.ts)
- [src/agent/infra/map/abstract-queue.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/map/abstract-queue.ts)
- [src/agent/infra/tools/implementations/expand-knowledge-tool.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/tools/implementations/expand-knowledge-tool.ts)
- [src/shared/transport/events/vc-events.ts](https://github.com/campfirein/byterover-cli/blob/main/src/shared/transport/events/vc-events.ts)
</details>

# Context Tree and Knowledge Storage

The Context Tree is ByteRover's hierarchical knowledge management system that organizes curated information into a structured, searchable repository within each project. It serves as the long-term memory layer for the agent, enabling persistent storage and retrieval of domain-specific knowledge, architectural decisions, patterns, and operational insights.

## Architecture Overview

The Context Tree operates as a file-based knowledge store where each piece of curated information is persisted as a Markdown document within the `.brv/context-tree/` directory structure. The system combines human-readable file storage with automated processing for summaries and overviews.

```mermaid
graph TD
    A[User/Agent] -->|Curate Operations| B[CurateService]
    B --> C[File System: .brv/context-tree/]
    
    C --> D[Domains]
    D --> E[Topics]
    E --> F[context.md files]
    E --> G[Subfolders with context.md]
    
    H[AbstractGenerationQueue] -->|Background Processing| I[.abstract.md files]
    I --> J[_index.md auto-summaries]
    
    K[Search/Query] -->|Retrieve| L[expand-knowledge-tool]
    L --> F
    L --> J
    L -->|_archived| M[Archived Entries]
```

## Directory Structure

The Context Tree follows a predictable directory hierarchy that enables both human navigation and programmatic access.

| Element | Type | Description |
|---------|------|-------------|
| `domains` | Directory | Top-level folders representing knowledge areas |
| `context.md` | File | Primary knowledge content within topics |
| `.overview.md` | File | L1 structured overview for quick retrieval |
| `.abstract.md` | File | One-line summary of the content |
| `_index.md` | File | Auto-generated directory summaries |
| `_archived/` | Directory | Archived low-importance entries |

资料来源：[context-tree-structure-contributor.ts:32-45]()

### Domain Organization

Domains are dynamically created based on the semantics of curated content. Domain names use `snake_case` naming convention (e.g., `architecture`, `market_trends`, `risk_analysis`). Before creating a new domain, the system checks whether existing domains could accommodate the new content to prevent fragmentation.

## Curate Operations

The curation system supports a comprehensive set of operations for managing knowledge entries. These operations are validated and executed through `CurateService`.

### Supported Operation Types

| Operation | Description | Required Fields |
|-----------|-------------|-----------------|
| `ADD` | Create new knowledge entry | `title`, `content` (rawConcept and/or narrative) |
| `UPDATE` | Modify existing entry | `path`, `title`, `content` |
| `UPSERT` | Update or create entry | `path`, `title`, `content` |
| `DELETE` | Remove knowledge entry | `path` |
| `ARCHIVE` | Move to archived storage | `path` |
| `RESTORE` | Recover from archive | `path` |

资料来源：[curate-service.ts:35-55]()

### Validation Rules

The curate service enforces strict validation before executing operations:

1. **Content requirement**: `ADD`, `UPDATE`, and `UPSERT` operations must include content with either `rawConcept` and/or `narrative` fields
2. **Title requirement**: These operations must also include a `title` field that becomes the `.md` filename
3. **Path validation**: Paths outside the project root are rejected

```mermaid
graph LR
    A[CurateOperation] --> B{Valid?}
    B -->|Missing Content| C[FAIL: operation requires content]
    B -->|Missing Title| D[FAIL: operation requires title]
    B -->|Valid| E[Execute Operation]
    E --> F[Write to .brv/context-tree/]
    F --> G[Trigger Abstract Generation Queue]
```

## Abstract Generation System

The abstract generation system provides automated summarization of curated knowledge entries. It operates asynchronously through a queue-based architecture.

### Generation Types

| Type | Purpose | Token Limit |
|------|---------|-------------|
| `abstract` | One-line summary | Max 80 tokens |
| `overview` | Structured markdown | Under 1500 tokens |

The abstract captures the core topic and key insight in a single complete sentence, while the overview provides detailed structure including key points (3-7 bullets), section summaries, and notable entities or decisions.

资料来源：[abstract-generator.ts:40-65]()

### Batched Prompt Building

The system processes files in batches using XML-formatted prompts with CDATA wrapping to safely handle special characters:

```xml
<file path="path/to/file.md">
<document><![CDATA[file content here]]></document>
</file>
```

The `wrapCdata` function uses a standard CDATA-in-CDATA escape technique:

```typescript
function wrapCdata(content: string): string {
  return `<![CDATA[${content.replaceAll(']]>', ']]]]><![CDATA[>')}]]>`
}
```

资料来源：[abstract-generator.ts:30-35]()

### Response Parsing

The parser extracts `<abstract>` or `<overview>` tags from model responses using a robust regex approach anchored on `<file path="...">` openers rather than closing tags. This prevents premature termination when the content naturally contains `</file>` sequences (common in documentation about XML, JSX, or build systems).

```mermaid
graph TD
    A[Model Response] --> B{Scan for <file path=...>}
    B -->|Found| C[Extract slice to next opener]
    C --> D[Extract inner tag content]
    D --> E[Map path to content]
    B -->|Not found| F[End of parsing]
```

## Abstract Generation Queue

The `AbstractGenerationQueue` class manages background abstract generation with reliability features.

### Queue Architecture

| Feature | Description |
|---------|-------------|
| Batch processing | Processes files in configurable batch sizes |
| Retry logic | Automatic retry with backoff for failed generations |
| Status tracking | Real-time monitoring of pending, processing, and completed items |
| Drain handling | Graceful shutdown with partial batch processing |

### Queue Status

The queue exposes status through the `AbstractQueueStatus` interface:

```typescript
interface AbstractQueueStatus {
  failed: number          // Items that failed after all retries
  pending: number         // Items waiting to be processed (including retry backoff)
  processed: number       // Successfully processed items
  processing: number      // Currently being processed
}
```

### File Filtering

The queue automatically filters out certain file types to avoid generating redundant abstracts:

- `context.md` files (hierarchy scaffolding)
- `_index.md` files (auto-generated summaries)
- `.abstract.md` files (output files themselves)
- `.overview.md` files (output files themselves)

资料来源：[abstract-queue.ts:25-35]()

## Knowledge Retrieval

ByteRover provides multiple mechanisms for retrieving stored knowledge during agent operations.

### Expand Knowledge Tool

The `expand-knowledge-tool` enables retrieval of content from the Context Tree through two primary modes:

| Mode | Use Case | Behavior |
|------|----------|----------|
| `stubPath` | Archive drill-down | Retrieves full content from archived entries |
| `overviewPath` | Quick overview | Retrieves L1 structured overview from `.overview.md` sibling files |

```typescript
interface ExpandKnowledgeToolConfig {
  baseDirectory?: string           // Custom base directory
  runtimeSignalStore?: IRuntimeSignalStore  // Signal handling
}
```

The tool description clearly identifies its purpose:

> "Retrieve full content from archived knowledge entries or L1 overview files. Use stubPath when search results include an archive_stub that you need to drill into. Use overviewPath to retrieve the structured overview for a context entry."

资料来源：[expand-knowledge-tool.ts:40-60]()

### Query Commands

Query commands search **only within the Context Tree structure**, not the entire project. This ensures focused knowledge retrieval without noise from source code or unrelated files.

### Knowledge Path Resolution

The system resolves knowledge paths relative to the project root (`.brv/context-tree/`), ensuring isolation from arbitrary file system access. Files outside this directory are not accessible through the knowledge system.

## Storage Format

### Knowledge File Structure

Individual knowledge entries are stored as Markdown files with structured frontmatter:

```markdown
# Title

## Core Concept
[rawConcept content]

## Narrative
[narrative content]

## Metadata
- Created: timestamp
- Tags: [domain, topic]
```

### Archive Format

Archived entries are stored in `_archived/` subdirectories, maintaining the same file structure but segregated for reduced visibility in default queries. The `expand_knowledge` command with `stubPath` is required to drill into archived content.

## Integration Points

### With Agent System

The Context Tree integrates with the agent's query and curate capabilities through the swarm coordinator, enabling:

- Dynamic domain creation based on content semantics
- Conflict detection between new and existing knowledge
- Memory scoring for relevance-based retrieval

### With Version Control

The `.brv/context-tree/` directory is designed for version control integration:

- Files are human-readable Markdown
- Standard git operations apply
- Cloud sync via `brv vc push` and `brv vc pull` supports knowledge collaboration

### With Sandbox Execution

The curate service runs within sandboxed environments, providing controlled access to the knowledge system. Operations are validated before execution, and results are tracked for audit purposes.

## Configuration Options

| Option | Default | Description |
|--------|---------|-------------|
| `basePath` | `.brv/context-tree/` | Root directory for knowledge storage |
| `BATCH_SIZE_CAP` | Varies | Maximum items per abstract generation batch |
| `max_file_size` | Configurable | Maximum file size for ingestion |
| `max_lines_per_file` | Configurable | Maximum lines per file |

## Best Practices

1. **Domain organization**: Before creating new domains, verify existing domains cannot accommodate the content
2. **Title conventions**: Use descriptive titles that serve as meaningful filenames
3. **Content structure**: Include both `rawConcept` (concise summary) and `narrative` (detailed explanation) when possible
4. **Archive management**: Use the archive feature for low-importance entries to keep active knowledge focused
5. **Batch operations**: When curating multiple files, the queue's batching system optimizes LLM usage

## Related Documentation

- [SKILL.md](https://github.com/campfirein/byterover-cli/blob/main/src/server/templates/skill/SKILL.md) - CLI command reference for `brv curate` and `brv query`
- [folder-pack-executor.ts](https://github.com/campfirein/byterover-cli/blob/main/src/server/infra/executor/folder-pack-executor.ts) - Folder packing for knowledge extraction

---

<a id='version-control'></a>

## Version Control for Context

### 相关页面

相关主题：[Context Tree and Knowledge Storage](#context-tree), [Agent System](#agent-system)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [src/shared/transport/events/vc-events.ts](https://github.com/campfirein/byterover-cli/blob/main/src/shared/transport/events/vc-events.ts)
- [src/server/core/interfaces/services/i-git-service.ts](https://github.com/campfirein/byterover-cli/blob/main/src/server/core/interfaces/services/i-git-service.ts)
- [src/agent/infra/process/command-validator.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/process/command-validator.ts)
- [src/webui/features/context/components/context-history-panel.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/context/components/context-history-panel.tsx)
- [src/tui/features/vc/push/components/vc-push-flow.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/tui/features/vc/push/components/vc-push-flow.tsx)
- [src/agent/resources/tools/bash_exec.txt](https://github.com/campfirein/byterover-cli/blob/main/src/agent/resources/tools/bash_exec.txt)
- [src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts](https://github.com/campfirein/byterover-cli/blob/main/src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts)
</details>

# Version Control for Context

Version Control for Context (VC) provides git-based version control for ByteRover's knowledge base (context tree). It enables tracking, branching, committing, merging, and syncing curated knowledge using familiar git semantics, with all operations working locally without authentication. Remote sync with a team is optional.

## Overview

ByteRover's Version Control system extends standard git functionality to manage the `.brv/context-tree/` directory where curated knowledge is stored. This system allows users to track changes to their knowledge base, create feature branches for experimental knowledge curation, collaborate with team members through remote sync, and maintain a complete history of knowledge evolution.

The VC system is built on top of an abstracted git service layer that provides cross-platform git operations, with additional intelligence for knowledge-specific use cases like tracking abstract generations and managing context tree structure. 资料来源：[src/shared/transport/events/vc-events.ts:1-50]()

## Architecture

```mermaid
graph TD
    subgraph "User Interface Layer"
        CLI[CLI - brv vc]
        WebUI[WebUI]
        TUI[TUI Components]
    end
    
    subgraph "Command Layer"
        VCCommands[VC Commands]
        BranchCmd[Branch Command]
        CommitCmd[Commit Command]
        MergeCmd[Merge Command]
        PushCmd[Push Command]
    end
    
    subgraph "Service Layer"
        GitService[Git Service Interface]
        CurateService[Curate Service]
        CommandValidator[Command Validator]
    end
    
    subgraph "Infrastructure Layer"
        GitImpl[Isomorphic Git]
        FileSystem[File System]
        Events[VC Events Transport]
    end
    
    subgraph "Data Layer"
        ContextTree[.brv/context-tree/]
        GitStorage[Git Repository]
    end
    
    CLI --> VCCommands
    WebUI --> VCCommands
    TUI --> VCCommands
    
    VCCommands --> GitService
    VCCommands --> CommitCmd
    VCCommands --> BranchCmd
    VCCommands --> MergeCmd
    
    GitService --> GitImpl
    GitService --> FileSystem
    GitService --> Events
    
    CommitCmd --> ContextTree
    CurateService --> ContextTree
    
    ContextTree --> GitStorage
    GitImpl --> GitStorage
```

## Diff Modes

The VC system supports four diff modes that mirror `git diff` semantics, allowing precise comparison of knowledge changes across different stages and references. 资料来源：[src/shared/transport/events/vc-events.ts:16-27]()

| Mode | Git Equivalent | Comparison | Use Case |
|------|---------------|------------|----------|
| `unstaged` | `git diff` | Stage → Workdir | Tracked files with uncommitted changes |
| `staged` | `git diff --staged` | HEAD → Stage | Committed changes ready to be finalized |
| `ref-vs-worktree` | `git diff <ref>` | Commit/Branch → Workdir | Compare any reference against working tree |
| `range` | `git diff <ref1>..<ref2>` | Ref1 → Ref2 | Compare two commits or branches |

```typescript
export type VcDiffMode =
  | {from: string; kind: 'range'; to: string}
  | {kind: 'ref-vs-worktree'; ref: string}
  | {kind: 'staged'}
  | {kind: 'unstaged'}
```

## Diff File Model

Each file entry in a diff response includes comprehensive metadata about the change. 资料来源：[src/shared/transport/events/vc-events.ts:35-50]()

| Field | Type | Description |
|-------|------|-------------|
| `binary` | `boolean` | True when either side contains NUL byte; content fields are empty |
| `newContent` | `string` | The new file content |
| `oldContent` | `string` | The previous file content (empty for additions) |
| `path` | `string` | Relative path to the file |
| `newOid` | `string` | 7-character short OID (omitted for deletions) |
| `oldOid` | `string` | Previous commit's OID |
| `status` | `string` | Change type: `added`, `deleted`, `modified` |

Binary files are filtered out of diff responses upstream, ensuring consumers only receive text content. Legacy WebUI consumers read `oldContent`, `newContent`, and `path` fields while ignoring additional fields for forward compatibility.

## Git Service Interface

The `IGitService` interface defines the complete set of git operations available for version control. 资料来源：[src/server/core/interfaces/services/i-git-service.ts:1-100]()

### Core Methods

| Method | Returns | Description |
|--------|---------|-------------|
| `getTextBlob` | `Promise<TextBlob \| undefined>` | Retrieves blob content without double-read pattern |
| `getTrackingBranch` | `Promise<TrackingBranch \| undefined>` | Returns upstream tracking branch config |
| `hashBlob` | `Promise<string>` | Computes 7-char short OID via `git hash-object` |
| `init` | `Promise<void>` | Initializes a new git repository |
| `isAncestor` | `Promise<boolean>` | Checks if ancestor commit is reachable from commit |
| `isEmptyRepository` | `Promise<boolean>` | Checks if repo has no commits, remotes, branches, tags, or untracked files |
| `isInitialized` | `Promise<boolean>` | Checks if `.git` directory exists |
| `listBranches` | `Promise<GitBranch[]>` | Lists local branches, optionally including remote-tracking |

### Blob Operations

The `hashBlob` method computes the 7-character short OID that git would assign to content, using `git hash-object`. This is essential for rendering working-tree diff headers since the working tree has no stored OID. 资料来源：[src/server/core/interfaces/services/i-git-service.ts:20-27]()

## Command Validation

Git operations executed through the sandbox are validated for security and safety. The command validator enforces patterns that control which git operations are permitted. 资料来源：[src/agent/infra/process/command-validator.ts:1-50]()

### Allowed Read-Only Operations

The following git operations are permitted in validated contexts:

```typescript
/git\s+(status|log|diff|show|branch|tag|fetch|pull)(?!\s+-)/i
```

### Recommended Git Workflow

The bash execution guidelines recommend this workflow for git operations: 资料来源：[src/agent/resources/tools/bash_exec.txt:1-30]()

1. Run `git status` to see changes
2. Run `git diff` to review changes
3. Stage files with `git add`
4. Commit with a meaningful message

For pull requests:
1. Check branch status with `git status`
2. Push to remote with `git push -u origin <branch>`
3. Create PR using `gh pr create`

## Commit History Display

The WebUI provides a commit history panel that displays the timeline of knowledge changes. 资料来源：[src/webui/features/context/components/context-history-panel.tsx:1-60]()

```typescript
function formatCommitDate(timestamp: string): string {
  try {
    return `Updated at ${format(new Date(timestamp), 'MMM d, HH:mm')}`
  } catch {
    return 'Updated'
  }
}
```

The history panel renders timeline items with:
- Commit author name
- Timestamp formatted as "MMM d, HH:mm"
- Visual distinction between current commit (active) and older commits

## Push Flow

The TUI push flow handles the process of pushing commits to remote repositories. It includes remote URL validation and status display during the push operation. 资料来源：[src/tui/features/vc/push/components/vc-push-flow.tsx:1-80]()

```typescript
return (
  <Text>
    <Spinner type="dots" /> {branch ? `Pushing to origin/${branch}...` : 'Pushing...'}
  </Text>
)
```

The push flow requires:
- Remote URL configuration
- Remote URL validation before submission
- Branch name determination for the push target

## Context Tree Structure

The context tree is organized in `.brv/context-tree/` and includes version control information in system prompts. 资料来源：[src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts:1-100]()

### Structure Rules

- Each top-level folder is a **domain** (dynamically created based on content)
- Inside domains are **topics** as `.md` files or subfolders with `context.md`
- `context.md` files contain the curated knowledge content
- `_index.md` files are auto-generated summaries at each directory level
- `_archived/` contains archived low-importance entries

### Domain Management

Domains are created dynamically based on the semantics of curated content. Domain names use snake_case (e.g., `architecture`, `market_trends`, `risk_analysis`). Before creating a new domain, the system checks if existing domains could accommodate the content.

### VC Integration

The system prompt contributor includes version control information:
- Query commands search only within the context tree structure
- Curate commands check existing domains/topics before creating new ones
- Archived entries can be accessed using `expand_knowledge` to drill into them

## Workflow Diagram

```mermaid
graph LR
    subgraph "Local Operations"
        A[Curate Knowledge] --> B[brv vc add]
        B --> C[brv vc commit]
        C --> D[brv vc status]
        D --> E{Changes?}
        E -->|Yes| F[Review Changes]
        E -->|No| G[Done]
        F --> H[brv vc log]
    end
    
    subgraph "Branch Management"
        I[brv vc branch feature/auth] --> J[brv vc checkout feature/auth]
        J --> K[Develop Knowledge]
        K --> L[brv vc merge]
    end
    
    subgraph "Remote Sync"
        M[brv vc push] --> N[brv vc pull]
        N --> O[brv vc fetch]
    end
    
    H --> I
    L --> M
```

## Key Features Summary

| Feature | Description |
|---------|-------------|
| **Local-First** | All operations work locally without authentication |
| **Git Semantics** | Familiar git commands and workflows |
| **Branch Support** | Create, switch, merge, and delete branches |
| **History Tracking** | Complete commit history with author and timestamp |
| **Remote Sync** | Optional push/pull to team ByteRover spaces |
| **Diff Modes** | Four modes matching git diff semantics |
| **Binary Filtering** | Automatic filtering of binary files from diffs |
| **Security Validation** | Command validation prevents dangerous operations |

## Remote Operations

Remote sync requires ByteRover authentication (`brv login`) and a configured remote. The following operations are supported:

| Command | Description |
|---------|-------------|
| `brv vc remote` | Show current remote configuration |
| `brv vc remote add origin <url>` | Add a new remote |
| `brv vc remote set-url origin <url>` | Update remote URL |
| `brv vc fetch` | Fetch remote refs |
| `brv vc pull` | Fetch and merge remote commits |
| `brv vc push` | Push commits to cloud |
| `brv vc push -u origin main` | Push and set upstream tracking |
| `brv vc clone` | Clone a team space repository |

## Related Documentation

- [ByteRover CLI Template System](src/server/templates/README.md) - Agent instruction generation
- [Curate Service](src/agent/infra/sandbox/curate-service.ts) - Knowledge curation operations
- [Context Tree Structure Contributor](src/agent/infra/system-prompt/contributors/context-tree-structure-contributor.ts) - System prompt integration

---

<a id='webui-dashboard'></a>

## WebUI Dashboard

### 相关页面

相关主题：[System Architecture Overview](#architecture-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/webui/router.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/router.tsx)
- [src/webui/pages/home-page.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/pages/home-page.tsx)
- [src/webui/features/context/components/context-layout.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/context/components/context-layout.tsx)
- [src/webui/features/tasks/components/task-list-view.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/tasks/components/task-list-view.tsx)
- [src/webui/features/vc/components/diff-view.tsx](https://github.com/campfirein/byterover-cli/blob/main/src/webui/features/vc/components/diff-view.tsx)
- [src/webui/lib/api-client.ts](https://github.com/campfirein/byterover-cli/blob/main/src/webui/lib/api-client.ts)
- [src/server/infra/webui/webui-server.ts](https://github.com/campfirein/byterover-cli/blob/main/src/server/infra/webui/webui-server.ts)
</details>

# WebUI Dashboard

The WebUI Dashboard is a React-based web interface served locally by the ByteRover daemon, providing developers with a graphical way to interact with the ByteRover CLI system. It serves as the primary user-facing component for managing AI coding agents, version control operations, context knowledge bases, task monitoring, and provider configurations through a modern, dark-themed interface.

## Architecture Overview

The WebUI operates as a client-side React application that communicates with the server-side daemon via a WebSocket-based transport layer. The architecture follows a feature-based folder structure where related components, hooks, and utilities are co-located.

```mermaid
graph TD
    Client["WebUI Client<br/>(React + Tailwind)"]
    Server["WebUI Server<br/>(webui-server.ts)"]
    API["API Client<br/>(api-client.ts)"]
    Transport["WebSocket Transport"]
    Daemon["ByteRover Daemon"]
    Providers["LLM Providers"]
    
    Client --> API
    API --> Transport
    Transport --> Server
    Server --> Daemon
    Server --> Providers
    
    subgraph WebUI_Features ["WebUI Features"]
        Context["Context/Knowledge Management"]
        Tasks["Task Monitoring"]
        VC["Version Control"]
        Providers["Provider Configuration"]
        Hub["Hub/Marketplace"]
        Project["Project Management"]
    end
    
    Client --> Context
    Client --> Tasks
    Client --> VC
    Client --> Providers
    Client --> Hub
    Client --> Project
```

## Core Components

### Header Layout

The `header.tsx` file defines the main navigation header component that provides persistent access to key functionality across all pages.

**Key Features:**

| Element | Purpose |
|---------|---------|
| Provider Selector | Shows current LLM provider with connection status indicator |
| Status Indicator | Visual dot showing active provider state (green/amber) |
| Credit Pill | Displays remaining credits when using ByteRover billing |
| Tooltip Triggers | Contextual help for user actions |

资料来源：[src/webui/layouts/header.tsx:1-60]()

```tsx
<TooltipTrigger
  render={
    <Button
      className={cn('whitespace-nowrap', triggerToneClass)}
      onClick={() => setProviderDialogOpen(true)}
      size="sm"
      variant="ghost"
    />
  }
>
  <span className="relative mr-1 inline-flex size-4 shrink-0">
    <Plug className="size-4" />
    {activeProvider && (
      <StatusDot
        className="border-background absolute -right-0.5 -bottom-0.5 size-2 border-2"
        tone={isByteRoverActive && needsPickPrompt ? 'amber' : STATUS_DOT_TONE[billingTone]}
      />
    )}
  </span>
  {providerLabel}
</TooltipTrigger>
```

### Page Routing

The application uses file-based routing through `router.tsx`, mapping URL paths to React page components. The router serves as the central navigation hub, enabling deep linking and browser history integration.

资料来源：[src/webui/router.tsx]()

## Feature Panels

### Context/Knowledge Management

The context panel provides an interface for managing the knowledge base used by AI agents. It displays the curated knowledge topics, allows navigation through the context tree structure, and shows search functionality.

资料来源：[src/webui/features/context/components/context-layout.tsx]()

Key operations supported:

- View knowledge topics organized in a tree structure
- Search and filter within the knowledge base
- Expand/collapse topic hierarchies
- Navigate to detailed topic views

### Task Monitoring

The task list view component displays active, completed, and failed tasks from the agent execution history. It integrates with the task history system defined in the server domain layer.

资料来源：[src/webui/features/tasks/components/task-list-view.tsx]()

The TUI's expanded log view provides a reference for expected task display behavior:

```tsx
{log.status === 'completed' && (
  <Box paddingX={1}>
    <ExecutionChanges
      created={log.changes.created}
      isExpanded
      maxChanges={{
        created: Number.MAX_SAFE_INTEGER,
        updated: Number.MAX_SAFE_INTEGER,
      }}
      updated={log.changes.updated}
    />
  </Box>
)}
```

资料来源：[src/tui/components/execution/expanded-log-view.tsx:60-70]()

### Version Control Panel

The VC components handle git-like operations including push and pull functionality. The UI provides visual feedback during sync operations and handles remote URL configuration.

资料来源：[src/webui/features/vc/components/remotes-panel.tsx]()

**Push Flow States:**

| State | UI Display |
|-------|------------|
| No Remote | Prompts user to configure remote URL |
| Pending | Shows spinner with branch name |
| Success | Confirmation message |
| Error | Error details with retry option |

资料来源：[src/tui/features/vc/push/components/vc-push-flow.tsx:40-50]()

### Provider Configuration

The providers panel enables users to configure LLM providers, set API keys, and manage OAuth authentication flows. It supports multiple authentication methods and provides validation before saving.

资料来源：[src/webui/features/provider/components/providers-panel.tsx]()

```tsx
<div className="flex flex-wrap gap-2.5">
  <Button onClick={() => handleValidate(provider.id)} size="lg" variant="outline">
    Validate key
  </Button>
  <Button onClick={() => handleConnect(provider.id)} size="lg">
    Connect provider
  </Button>
</div>
```

#### OAuth Callback Handling

OAuth flows use a dedicated callback server that displays success or error pages:

```tsx
function successHtml(): string {
  return `<!DOCTYPE html>
<html>
<head><title>ByteRover - Authorization Successful</title></head>
<body>
  <h1>Successful</h1>
  <p>You can close this window and return to ByteRover.</p>
  <script>setTimeout(() => window.close(), 2000);</script>
</body>
</html>`
}
```

资料来源：[src/server/infra/provider-oauth/callback-server.ts:1-30]()

### Hub/Marketplace

The hub panel provides access to a marketplace of agent skills and capabilities. Users can browse available entries, select target agents, and install new functionality.

资料来源：[src/webui/features/hub/components/hub-panel.tsx]()

### Project Management

The project dropdown component allows switching between different project workspaces, displaying project names and remote space associations.

资料来源：[src/webui/features/project/components/project-dropdown.tsx]()

```tsx
const remoteLabel = teamName && spaceName ? `${teamName} / ${spaceName}` : undefined

<DropdownMenuItem className="gap-2 rounded-md" onClick={onSelect}>
  <ProjectItemRow name={name} project={project} remoteLabel={remoteLabel} />
</DropdownMenuItem>
```

## API Communication

The WebUI communicates with the server through the API client located in `src/webui/lib/api-client.ts`. This client handles:

- RESTful API calls for CRUD operations
- WebSocket connection management for real-time updates
- Authentication token handling
- Error response normalization

资料来源：[src/webui/lib/api-client.ts]()

### Offline Handling

When the connection to the daemon is lost, the WebUI displays an offline screen with reconnection status:

```tsx
footer={
  <>
    {isConfigError ? (
      <span className="text-muted-foreground/80 text-xs">Refresh once the host is back.</span>
    ) : (
      <>
        <span aria-hidden className="bg-muted-foreground/60 size-1.5 animate-pulse rounded-full" />
        <span className="text-muted-foreground text-xs">
          Reconnecting<span className="opacity-60"> · attempt </span>
          <span className="text-foreground tabular-nums">{reconnectCount}</span>
        </span>
      </>
    )}
  </>
}
```

资料来源：[src/webui/features/transport/components/offline-screen.tsx:50-70]()

## WebUI Server

The server-side component (`webui-server.ts`) hosts the React application, serves static assets, and manages WebSocket connections for real-time communication with the client.

资料来源：[src/server/infra/webui/webui-server.ts]()

## Styling System

The WebUI uses Tailwind CSS with custom CSS variables for theming. The dark theme follows GitHub's design language with a cohesive color system:

```css
:root {
  --bg: #0d1117;
  --bg-secondary: #161b22;
  --bg-tertiary: #21262d;
  --border: #30363d;
  --text: #e6edf3;
  --text-muted: #8b949e;
  --green: #238636;
  --red: #da3633;
  --blue: #58a6ff;
  --yellow: #d29922;
}
```

资料来源：[src/webui/styles/index.css:1-30]()

### Typography

The application uses Geist for sans-serif text and JetBrains Mono for monospace/code display:

```css
--font-sans: 'Geist', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
```

## HITL Review UI

The WebUI also includes a standalone HITL (Human-in-the-Loop) review interface served by the HTTP server for reviewing agent operations before committing changes:

```tsx
export function getReviewPageHtml(): string {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ByteRover Review</title>
<style>
  :root {
    --bg: #0d1117;
    --bg-secondary: #161b22;
    /* ... additional styles */
  }
</style>
```

资料来源：[src/server/infra/http/review-ui.ts:1-30]()

## State Management

The WebUI follows a pattern where:

1. **Local State**: Component-specific state managed via React hooks (`useState`)
2. **Server State**: Data fetched and cached through query utilities (`useGetProjectConfig`, etc.)
3. **Transport State**: Connection status managed by the transport layer

```mermaid
graph LR
    subgraph State ["State Layers"]
        Local["Local UI State<br/>(useState)"]
        Server["Server State<br/>(useQuery)"]
        Transport["Transport State<br/>(WebSocket)"]
    end
    
    Local --> UI["React Components"]
    Server --> UI
    Transport --> UI
```

## Data Flow

User interactions trigger the following flow:

1. User action in WebUI component
2. Component calls API client method
3. API client sends request via transport layer
4. Server processes request and returns response
5. React query cache updates
6. Components re-render with new data

## Summary

The WebUI Dashboard provides a comprehensive graphical interface for all ByteRover CLI operations. Its modular architecture allows independent feature development while maintaining consistent styling and interaction patterns. The dark theme, real-time updates, and thoughtful error handling create a professional developer experience aligned with modern IDE design principles.

---

---

## Doramagic 踩坑日志

项目：campfirein/byterover-cli

摘要：发现 19 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Curator can copy prompt example facts into the context tree when using Gemini Flash-Lite。

## 1. 安装坑 · 来源证据：Curator can copy prompt example facts into the context tree when using Gemini Flash-Lite

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Curator can copy prompt example facts into the context tree when using Gemini Flash-Lite
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f0927b3fa77c4e7ab29ba04f3c4b7ed7 | https://github.com/campfirein/byterover-cli/issues/647 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：Visual corruption while browsing a long model list

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Visual corruption while browsing a long model list
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3112b1ba6fc54e0a8d973b277ab8d106 | https://github.com/campfirein/byterover-cli/issues/620 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：ByteRover CLI 3.10.1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.10.1
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c21085e93cad46a5b79d8ff2353f156c | https://github.com/campfirein/byterover-cli/releases/tag/v3.10.1 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：ByteRover CLI 3.10.3

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.10.3
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_5ada5377aa504edeac454b6a66310a47 | https://github.com/campfirein/byterover-cli/releases/tag/v3.10.3 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 5. 安装坑 · 来源证据：ByteRover CLI 3.8.1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.8.1
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_370b6c20f13544c28427013da0519f1f | https://github.com/campfirein/byterover-cli/releases/tag/v3.8.1 | 来源类型 github_release 暴露的待验证使用条件。

## 6. 安装坑 · 来源证据：ByteRover CLI 3.8.2

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.8.2
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_48b470d455aa406480648e100bc08c94 | https://github.com/campfirein/byterover-cli/releases/tag/v3.8.2 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 7. 安装坑 · 来源证据：ByteRover CLI 3.8.3

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.8.3
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_70d8761f65864cf2897a70138eabb5b7 | https://github.com/campfirein/byterover-cli/releases/tag/v3.8.3 | 来源类型 github_release 暴露的待验证使用条件。

## 8. 安装坑 · 来源证据：ByteRover CLI 3.9.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：ByteRover CLI 3.9.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_955f12701a864106895fc95c8ef7fd05 | https://github.com/campfirein/byterover-cli/releases/tag/v3.9.0 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 9. 安装坑 · 来源证据：`brv mcp` client stuck in infinite exception loop consuming 75–90% CPU for hours

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：`brv mcp` client stuck in infinite exception loop consuming 75–90% CPU for hours
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_50500a3417394344864f50cf765157ea | https://github.com/campfirein/byterover-cli/issues/660 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 10. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | README/documentation is current enough for a first validation pass.

## 11. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | last_activity_observed missing

## 12. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | no_demo; severity=medium

## 13. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | no_demo; severity=medium

## 14. 安全/权限坑 · 来源证据：ByteRover CLI 3.10.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：ByteRover CLI 3.10.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_78241481b8c647e4a05827b06eafdc99 | https://github.com/campfirein/byterover-cli/releases/tag/v3.10.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 15. 安全/权限坑 · 来源证据：ByteRover CLI 3.10.2

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：ByteRover CLI 3.10.2
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2af62a087710490b8250f23ac6258644 | https://github.com/campfirein/byterover-cli/releases/tag/v3.10.2 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 16. 安全/权限坑 · 来源证据：ByteRover CLI 3.11.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：ByteRover CLI 3.11.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ea3c8b32846b4edfaef28f8aa1cca40f | https://github.com/campfirein/byterover-cli/releases/tag/v3.11.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 17. 安全/权限坑 · 来源证据：ByteRover CLI 3.12.0

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：ByteRover CLI 3.12.0
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_917109bf273c4c09a26a50f00fd1b6e4 | https://github.com/campfirein/byterover-cli/releases/tag/v3.12.0 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 18. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | issue_or_pr_quality=unknown

## 19. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1005233473 | https://github.com/campfirein/byterover-cli | release_recency=unknown

<!-- canonical_name: campfirein/byterover-cli; human_manual_source: deepwiki_human_wiki -->
