# Managing CodeBuddy's Memory

> Learn how to manage CodeBuddy Code's memory across sessions using different memory locations and best practices.

CodeBuddy Code can remember your preferences across sessions, such as code style guides and common commands in your workflow.

## Determining Memory Types

CodeBuddy Code provides four hierarchically structured memory locations, each serving a different purpose:

| Memory Type | Location | Purpose | Example Use Cases | Shared With |
|-------------|----------|---------|-------------------|-------------|
| **User Memory** | `~/.codebuddy/CODEBUDDY.md` | Personal preferences across all projects | Code style preferences, personal tool shortcuts | Only you (across all projects) |
| **User Rules** | `~/.codebuddy/rules/*.md` | Modular personal rules | Personal coding habits, common workflows | Only you (across all projects) |
| **Project Memory** | `./CODEBUDDY.md` or `./.codebuddy/CODEBUDDY.md` | Team-shared instructions for a project | Project architecture, coding standards, common workflows | Team members via source control |
| **Project Rules** | `./.codebuddy/rules/*.md` | Modular, topic-specific project instructions | Language-specific guidelines, testing specifications, API standards | Team members via source control |
| **Project Memory (Local)** | `./CODEBUDDY.local.md` | Personal project-specific preferences | Your sandbox URL, preferred test data | Only you (current project) |

All memory files are automatically loaded into CodeBuddy Code's context at startup. The loading order is as follows:

1. **User-level**: Load main files like `~/.codebuddy/CODEBUDDY.md` and all rules under `~/.codebuddy/rules/`
2. **Project-level main files**: Recursively load all `CODEBUDDY.md` and `CODEBUDDY.local.md` from current working directory upward
3. **Project-level rules**: Only load rules under `.codebuddy/rules/` in the current working directory (not parent directories)
4. **Subdirectory memory**: When CodeBuddy operates on files in subdirectories, dynamically load that subdirectory's `CODEBUDDY.md`
5. **Local memory**: Load `./CODEBUDDY.local.md`

> **Tip**: CODEBUDDY.local.md files are automatically added to .gitignore, making them ideal for storing private project-specific preferences that should not be committed to version control.

## CODEBUDDY.md Imports

CODEBUDDY.md files can import additional files using the `@path/to/import` syntax. The following example imports 3 files:

```markdown
See @README for project overview, and @package.json for available npm commands.

# Additional Instructions
- Git workflow @docs/git-instructions.md
```

Both relative and absolute paths are supported. In particular, importing files from the user's home directory is a convenient way for team members to provide personal instructions that are not committed to the repository. Imports are an alternative to CODEBUDDY.local.md and work better with multiple git worktrees.

```markdown
# Personal Preferences
- @~/.codebuddy/my-project-instructions.md
```

To avoid potential conflicts, imports within code blocks and code spans are not parsed.

```markdown
This code span won't be treated as an import: `@tencent-ai/codebuddy-code`
```

Imported files can recursively import additional files, up to a maximum depth of 5 levels. You can view which memory files are loaded by running the `/memory` command.

## How CodeBuddy Finds Memory

CodeBuddy Code reads memory recursively: Starting from the current working directory, CodeBuddy Code recurses up to (but not including) the root directory `/`, and reads any CODEBUDDY.md or CODEBUDDY.local.md files it finds. This works particularly well in large repositories where you run CodeBuddy Code in `foo/bar/`, with memories in both `foo/CODEBUDDY.md` and `foo/bar/CODEBUDDY.md`.

CodeBuddy also discovers CODEBUDDY.md files nested in subtrees below the current working directory. These files are not loaded at startup, but are only included when CodeBuddy reads files in those subtrees.

## Managing Memory with `/memory`

Use the `/memory` slash command during a session to open the memory management panel. In this panel you can:

- Open the Auto Memory directory
- Open the `MEMORY.md` index file
- Toggle the Auto Memory switch

## Setting Up Project Memory

Suppose you want to set up a CODEBUDDY.md file to store important project information, conventions, and commonly used commands. Project memory can be stored in `./CODEBUDDY.md` or `./.codebuddy/CODEBUDDY.md`.

Bootstrap a CODEBUDDY.md for your codebase using the following command:

```
> /init
```

> **Tips**:
> - Include common commands (build, test, lint) to avoid repetitive searches
> - Document code style preferences and naming conventions
> - Add project-specific important architectural patterns
> - CODEBUDDY.md memory can be used for both team-shared instructions and personal preferences

## Modular Rules with `.codebuddy/rules/`

For larger projects, you can use the `.codebuddy/rules/` directory to organize instructions into multiple files. This allows teams to maintain focused, well-organized rule files instead of a single large CODEBUDDY.md.

### Basic Structure

Place markdown files in your project's `.codebuddy/rules/` directory:

```
your-project/
├── .codebuddy/
│   ├── CODEBUDDY.md           # Main project instructions
│   └── rules/
│       ├── code-style.md      # Code style guidelines
│       ├── testing.md         # Testing specifications
│       └── security.md        # Security requirements
```

All `.md` files in `.codebuddy/rules/` are automatically loaded as project memory with the same priority as `.codebuddy/CODEBUDDY.md`.

> **Note**: Project-level rules are only loaded from `.codebuddy/rules/` in the current working directory (workDir), not from parent directories. This ensures clear rule scoping.

### Rule Control Fields

Rule files support the following YAML frontmatter fields to control loading and application behavior:

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | boolean | `true` | Whether to load this rule. When set to `false`, the rule is not loaded at all |
| `alwaysApply` | boolean | `true` | Whether to always apply this rule |
| `paths` | string/string[] | - | File path glob patterns that trigger the rule |

#### Rule Type Determination

Rule type is determined by both `alwaysApply` and `paths`:

| alwaysApply | paths | Rule Type | Behavior |
|-------------|-------|-----------|----------|
| `true` (default) | any | ALWAYS | Always injected into context |
| `false` | has value | MANUAL (conditional trigger) | Only triggered when operating on matching files |
| `false` | none | Not supported | Rule will not be loaded |

#### Examples

**Always-applied rule** (default behavior):

```markdown

# General Code Standards

- Use 2-space indentation
- Keep blank line at end of file
```

**Conditionally triggered rule**:

```markdown
---
alwaysApply: false
paths: src/api/**/*.ts
---

# API Development Rules

- All API endpoints must include input validation
- Use standard error response format
- Include OpenAPI documentation comments
```

**Disabled rule** (temporarily turned off):

```markdown
---
enabled: false
---

# Rules not currently in use
```

> **Note**: The `paths` field is not limited to `.codebuddy/rules/` directory; it can be used in all memory files (including CODEBUDDY.md, CODEBUDDY.local.md).

### Glob Patterns

The `paths` field supports standard glob patterns with the `matchBase` option enabled:

| Pattern | Matches |
|---------|---------|
| `**/*.ts` | All TypeScript files in any directory |
| `*.ts` | All TypeScript files in any directory (matchBase mode) |
| `src/**/*` | All files under the `src/` directory |
| `*.md` | Markdown files in any directory |
| `src/components/*.tsx` | React components in a specific directory |

> **matchBase explanation**: With matchBase enabled, patterns without path separators (like `*.ts`) match files in any directory. For example, `*.ts` can match `src/utils/helper.ts`.

You can use braces to efficiently match multiple patterns:

```markdown
---
paths: src/**/*.{ts,tsx}
---

# TypeScript/React Rules
```

This expands to match `src/**/*.ts` and `src/**/*.tsx`. You can also combine multiple patterns with commas:

```markdown
---
paths: {src,lib}/**/*.ts, tests/**/*.test.ts
---
```

### Subdirectories

Rules can be organized into subdirectories for better structure:

```
.codebuddy/rules/
├── frontend/
│   ├── react.md
│   └── styles.md
├── backend/
│   ├── api.md
│   └── database.md
└── general.md
```

All `.md` files are discovered recursively.

### Symlinks

The `.codebuddy/rules/` directory supports symlinks, allowing you to share common rules across multiple projects:

```bash
# Symlink a shared rules directory
ln -s ~/shared-codebuddy-rules .codebuddy/rules/shared

# Symlink individual rule files
ln -s ~/company-standards/security.md .codebuddy/rules/security.md
```

Symlinks are resolved and their contents are loaded normally. Circular symlinks are detected and handled gracefully.

### User-Level Rules

You can create personal rules that apply to all projects in `~/.codebuddy/rules/`:

```
~/.codebuddy/rules/
├── preferences.md    # Your personal coding preferences
└── workflows.md      # Your preferred workflows
```

User-level rules are loaded before project rules, giving project rules higher priority.

> **Best Practices**:
> - **Keep rules focused**: Each file should cover one topic (e.g., `testing.md`, `api-design.md`)
> - **Use descriptive filenames**: Filenames should indicate what the rules cover
> - **Use conditional rules sparingly**: Only add `paths` frontmatter when rules truly apply to specific file types
> - **Organize with subdirectories**: Group related rules (e.g., `frontend/`, `backend/`)

## Memory Best Practices

- **Be specific**: "Use 2-space indentation" is better than "Format code properly".
- **Use structured organization**: Format each memory as a bullet point and group related memories under descriptive markdown headings.
- **Regular reviews**: Update memory as the project evolves to ensure CodeBuddy always uses the latest information and context.

## Setting Language Preferences

It is recommended to use the `/config` command to configure your preferred response language (see [Settings Configuration](settings.md#available-settings)), which is the simplest and most direct way:

```
> /config
# Select Language, enter your preferred language, e.g., "Simplified Chinese"
```

If you need more granular control (such as code comment language, commit message language), you can add to your memory file:

```markdown
## CodeBuddy Added Memories

### Language Preferences
- Code comments in Chinese
- Commit messages in Chinese
```

Project-level language settings override user-level settings.

## Hierarchical Memory Strategy Example

### User-Level Memory (`~/.codebuddy/CODEBUDDY.md`)

```markdown
## CodeBuddy Added Memories

### Tool Preferences
- Use pnpm instead of npm

### Code Preferences
- Prefer functional programming style
- Prioritize code readability
```

> **Tip**: Response language is recommended to be set via `/config` rather than configured in memory files.

### Project-Level Memory (`./CODEBUDDY.md`)

```markdown
## CodeBuddy Added Memories

### Project Architecture
- Using microservices architecture
- Frontend: React + TypeScript
- Backend: Node.js + Express

### Team Conventions
- PRs require 2 reviewers
- Follow Conventional Commits
```

### Local Project Memory (`./CODEBUDDY.local.md`)

```markdown
## CodeBuddy Added Memories

### Local Development Configuration
- Database port: 5433
- Use debug mode
- Skip CI for quick testing
```

## Auto Memory System

Auto Memory is CodeBuddy Code's automatic memory system, allowing CodeBuddy to automatically save and retrieve persistent memories across sessions. Unlike the static memory of CODEBUDDY.md, Auto Memory is managed autonomously by CodeBuddy as it works.

### Storage Location

- **Project memory**: `~/.codebuddy/memories/{project-id}/`
- **Global memory**: `~/.codebuddy/memories/global/`

Each project has a `MEMORY.md` index file, whose first 200 lines are automatically loaded into the session context. Detailed memory content should be stored in separate topic files (e.g., `preferences.md`, `decisions.md`) and linked from MEMORY.md.

### Enabling and Disabling

- Toggle Auto Memory via the `/config` panel
- Toggle via the `/memory` command panel
- Configure via `settings.json`: `"memory": { "autoMemoryEnabled": false }`
- Via environment variable: `CODEBUDDY_DISABLE_AUTO_MEMORY=1`

### Typed Memory Mode

Typed Memory is an enhanced version of Auto Memory that provides a structured memory type system (enabled by default). Memory files are managed using YAML frontmatter and 4 types.

**4 memory types:**

| Type | Purpose | Example |
|------|---------|---------|
| `user` | User's role, goals, preferences, and knowledge background | "User is a senior backend engineer proficient in Go" |
| `feedback` | User's corrections and guidance on CodeBuddy behavior | "Don't mock the database in tests" |
| `project` | Ongoing project work, goals, and decisions | "Freeze non-critical merges starting next Wednesday" |
| `reference` | References to external systems and resources | "Bug tracking in Linear project INGEST" |

**Memory file format:**

```markdown
---
name: User Role
description: User's professional background and technical expertise
type: user
---

The user is a senior backend engineer with 10 years of Go experience, but new to the project's React frontend.
```

**How to disable (if you need to fall back to the general format):**

- Configure via `settings.json`: `"memory": { "typedMemory": false }`
- Via environment variable: `CODEBUDDY_TYPED_MEMORY_ENABLED=false`

> **Tip**: Typed Memory is enabled by default. If disabled, Auto Memory uses a simplified general format without a type system or YAML frontmatter.

## Cache and Reload

| Operation | Reloads | Notes |
|-----------|---------|-------|
| Process restart | Yes | Cache cleared |
| Edit via /memory | Yes | Cache automatically cleared |
| /clear command | No | Only clears message history |
| Manual file modification | No | Requires manual restart |
| Add/delete rule files | No | Requires manual restart |

## Frequently Asked Questions

**What is the difference between AGENTS.md and CODEBUDDY.md?**

CodeBuddy Code supports both AGENTS.md and CODEBUDDY.md as project memory files:

- **AGENTS.md Support**: If a `CODEBUDDY.md` file exists in the project, project-level memory will use CODEBUDDY.md, otherwise it will use AGENTS.md
- **Auto-detection**: The system automatically detects whether an AGENTS.md file exists in the project

### Recommended: Use CODEBUDDY.md

While we maintain support for AGENTS.md, it is recommended that new projects use CODEBUDDY.md as the memory filename to maintain consistency with the CodeBuddy Code brand.

**How to migrate AGENTS.md to CODEBUDDY.md?**

Simply rename `AGENTS.md` to `CODEBUDDY.md`. The system will auto-detect, and CODEBUDDY.md takes priority.

**How are memory files synchronized?**

- **Project Memory**: Synced with team via Git
- **User Memory**: Stored locally, not synced
- **Local Project Memory**: Stored locally, automatically added to .gitignore

**When do conditional rules trigger?**

They trigger in these situations:
- When referencing a file with `@path/to/file`
- When using file operation tools like Read, Glob, Grep, Edit, Write

Once triggered, matching rules are injected into the current message context as system reminders. When all conditional rules have been injected, they won't be injected again.

**How to debug rule loading issues?**

1. Run `/memory` to view the list of loaded rules
2. Check if frontmatter format is correct (`---` separators)
3. Confirm glob patterns are matching
4. Restart CodeBuddy to clear cache

**Is there a size limit for rule files?**

It's recommended to keep them concise. For particularly large specification documents, use `@import` syntax to reference them rather than including directly.

## Compatibility with CodeBuddy IDE

CodeBuddy Code CLI and CodeBuddy IDE both support memory/rules functionality, but conditional rules trigger differently:

- **CLI**: Conditional rules trigger automatically through glob pattern matching on file operations (including @ references and tool calls), without support for model-intelligent rule selection
- **IDE**: Conditional rules support manual user references via @RuleName, and also support model-based intelligent decision activation based on context


## Related Resources

- [Settings Configuration](settings.md) - Configure CodeBuddy Code behavior
- [Slash Commands](slash-commands.md) - All available commands
- [Quick Start](quickstart.md) - Quick start guide

---

*Through effective memory management, make CodeBuddy Code better understand your needs and preferences*
