Skip to content
Claude How To

記憶指南 (Memory Guide)

記憶 (Memory) 使 Claude 能夠跨工作階段 (Sessions) 與對話保留脈絡 (Context)。它有兩種存在形式:claude.ai 中的自動綜合 (Automatic Synthesis),以及 Claude Code 中基於檔案系統的 CLAUDE.md

概述 (Overview)

Claude Code 中的記憶 (Memory) 提供持久的脈絡 (Persistent Context),可跨多個工作階段與對話延續。與臨時的脈絡視窗 (Context Window) 不同,記憶檔案允許您:

  • 在團隊中共享專案標準 (Project Standards)
  • 儲存個人開發偏好 (Personal Development Preferences)
  • 維護特定目錄的規則與設定
  • 匯入外部說明文件
  • 將記憶作為專案的一部分進行版本控制 (Version Control)

記憶系統運作於多個層級,從全域個人偏好到特定的子目錄,允許對 Claude 記憶的內容及其應用方式進行精細控制。

記憶指令速查表 (Memory Commands Quick Reference)

指令目的用法何時使用
/init初始化專案記憶 (Initialize Project Memory)/init開始新專案、首次設定 CLAUDE.md
/memory在編輯器中編輯記憶檔案/memory大量更新、重組、檢視內容
# 前綴快速單行新增記憶 已廢棄改用 /memory 或透過對話請求
@path/to/file匯入外部內容@README.md@docs/api.mdCLAUDE.md 中引用現有說明文件

快速入門:初始化記憶 (Quick Start: Initializing Memory)

/init 指令 (The /init Command)

/init 指令是在 Claude Code 中設定專案記憶 (Project Memory) 最快的方式。它會利用基礎專案文件初始化一個 CLAUDE.md 檔案。

用法:

bash
/init

它的作用:

  • 在專案中建立新的 CLAUDE.md 檔案(通常位於 ./CLAUDE.md./.claude/CLAUDE.md
  • 建立專案慣例 (Conventions) 與指南
  • 建立跨工作階段脈絡持久性 (Context Persistence) 的基礎
  • 提供用以記錄專案標準的範本結構

強化的互動模式: 設定 CLAUDE_CODE_NEW_INIT=1 可啟用多階段互動流程,引導您一步步完成專案設定:

bash
CLAUDE_CODE_NEW_INIT=1 claude
/init

何時使用 /init

  • 使用 Claude Code 開始新專案
  • 建立團隊程式碼編寫標準與慣例
  • 建立有關程式碼庫結構的說明文件
  • 為協同開發設定記憶層級架構 (Memory Hierarchy)

範例工作流程:

markdown
# 在您的專案目錄中
/init

# Claude 建立包含如下結構的 CLAUDE.md:
# Project Configuration
## Project Overview
- Name: Your Project
- Tech Stack: [Your technologies]
- Team Size: [Number of developers]

## Development Standards
- Code style preferences
- Testing requirements
- Git workflow conventions

快速記憶更新 (Quick Memory Updates)

注意:用於內聯新增記憶的 # 快速鍵已經廢棄。請使用 /memory 直接編輯記憶檔案,或透過對話要求 Claude 記住某些內容(例如「記住我們在此專案中總是使用 TypeScript 嚴格模式」)。

推薦向記憶新增資訊的方式有:

選項 1:使用 /memory 指令

bash
/memory

在您的系統編輯器中開啟記憶檔案進行直接編輯。

選項 2:透過對話請求

Remember that we always use TypeScript strict mode in this project.
Please add to memory: prefer async/await over promise chains.

Claude 會根據您的請求更新相應的 CLAUDE.md 檔案。

歷史參考(已不再有效):

# 前綴快速鍵以往允許內聯新增規則:

markdown
# Always use TypeScript strict mode in this project  ← 已不再有效

如果您依賴此模式,請切換至 /memory 指令或對話請求。

/memory 指令 (The /memory Command)

/memory 指令提供在 Claude Code 工作階段中直接存取與編輯 CLAUDE.md 記憶檔案的功能。它會在您的系統編輯器中開啟記憶檔案以進行全面編輯。當檔案在 GUI 編輯器中開啟時,工作階段不再因檔案開啟而阻塞,因此您可以平行保持工作(v2.1.216);終端機編輯器(如 Vim)則仍會佔用終端機直到您退出。

用法:

bash
/memory

它的作用:

  • 在系統預設編輯器中開啟您的記憶檔案
  • 允許您進行大量的新增、修改與重組
  • 提供對階層中所有記憶檔案的直接存取
  • 使您能夠管理跨工作階段的持久脈絡 (Persistent Context)

比較:/memory vs /init

面向/memory/init
目的編輯現有記憶檔案初始化新 CLAUDE.md
何時使用更新/修改專案脈絡開始新專案
動作開啟編輯器進行修改產生入門範本
工作流程持續維護一次性設定

範例工作流程:

markdown
# 開啟記憶進行編輯
/memory

# Claude 顯示選項:
# 1. Managed Policy Memory
# 2. Project Memory (./CLAUDE.md)
# 3. User Memory (~/.claude/CLAUDE.md)
# 4. Local Project Memory

# 選擇選項 2 (Project Memory)
# 預設編輯器開啟並顯示 ./CLAUDE.md 內容

# 進行修改、儲存並關閉編輯器
# Claude 自動重新載入更新後的記憶

使用記憶匯入 (Memory Imports):

CLAUDE.md 檔案支援使用 @path/to/file 語法來包含外部內容:

markdown
# Project Documentation
See @README.md for project overview
See @package.json for available npm commands
See @docs/architecture.md for system design

# Import from home directory using absolute path
@~/.claude/my-project-instructions.md

匯入功能特色:

  • 同時支援相對路徑與絕對路徑(例如 @docs/api.md@~/.claude/my-project-instructions.md
  • 支援遞迴匯入 (Recursive Imports),最大深度為 4 次跳轉 (Hops)
  • 首次從外部位置匯入時會觸發核准對話方塊以維護安全性
  • 匯入指令在 Markdown 程式碼跨度 (Code Spans) 或程式碼區塊 (Code Blocks) 內部不會被求值(因此在範例中記錄它們是安全的)
  • 透過引用現有文件避免重複
  • 自動將引用的內容包含在 Claude 的脈絡中

記憶架構 (Memory Architecture)

Claude Code 中的記憶採用階層式系統 (Hierarchical System),不同的範疇 (Scope) 服務於不同的目的。與 Claude Web/Desktop 的 24 小時綜合週期不同(參見下文 Claude Web/Desktop 中的記憶),Claude Code 有兩個記憶系統,它們都在每次工作階段開始時載入並持續更新,而不是定時更新:

mermaid
graph TB
    A["工作階段開始 (Session Start)"]
    B["CLAUDE.md 檔案<br/>(由您撰寫)"]
    C["自動記憶 Auto Memory<br/>(由 Claude 撰寫)"]
    D["Claude 工作階段"]
    E["您的更正 /<br/>偏好設定"]

    B -->|完整載入| A
    C -->|MEMORY.md 已載入| A
    A --> D
    D -->|"記住..."| E
    E -->|在工作階段中寫入| C
    D -->|"將此新增至 CLAUDE.md"| B

Claude Code 中的記憶層級架構 (Memory Hierarchy in Claude Code)

Claude Code 擁有兩個互補的記憶系統,皆在每次對話開始時載入:CLAUDE.md 檔案(您撰寫的指令)與自動記憶 (Auto Memory)(Claude 自己撰寫的筆記)。CLAUDE.md 檔案是串接 (Concatenated) 進入脈絡而非相互覆寫 — 這並非較高層級替換較低層級的嚴格優先順序鏈。.claude/rules/*.md 檔案則是針對特定主題或路徑範疇指令的另一個相關機制。

CLAUDE.md 檔案位置,按載入順序(從最廣範疇到最具體):

範疇 (Scope)位置目的
管理策略 (Managed Policy)macOS: /Library/Application Support/ClaudeCode/CLAUDE.md
Linux/WSL: /etc/claude-code/CLAUDE.md
Windows: C:\Program Files\ClaudeCode\CLAUDE.md
由 IT/DevOps 管理的全組織指令。無法被個人設定排除。
使用者指令 (User Instructions)~/.claude/CLAUDE.md適用於所有專案的個人偏好
專案指令 (Project Instructions)./CLAUDE.md./.claude/CLAUDE.md團隊共享指令,受版本控制
本地指令 (Local Instructions)./CLAUDE.local.md個人特定專案的偏好;應新增至 .gitignore

在目錄樹中,Claude Code 會從您的工作目錄向上尋找:若您從 foo/bar/ 啟動,foo/CLAUDE.md 會比 foo/bar/CLAUDE.md 先載入,因此距離您啟動位置越近的指令會被最後讀取 — 這在覆寫語意上並非「最高優先級」,只是在脈絡中最新。在每個目錄中,CLAUDE.local.md 會附加在 CLAUDE.md 之後。位於您工作目錄下方子目錄中的 CLAUDE.mdCLAUDE.local.md 檔案,會在 Claude 讀取該子目錄中的檔案時按需載入 (On-demand),而非在啟動時載入。

組織也可以透過 claudeMd 鍵值將管理的 CLAUDE.md 內容直接放入 managed-settings.json 中,而無需部署獨立檔案。此設定僅在管理/策略設定中有效 — 在使用者或專案設定中設定 claudeMd 沒有任何效果。

.claude/rules/*.md — 模組化、特定主題的指令,可選擇性透過 paths 前置資料 (Frontmatter) 限定適用路徑。沒有 paths 欄位的規則會無條件載入,其優先順序與 .claude/CLAUDE.md 相同;限定路徑的規則會在 Claude 讀取相符檔案時按需載入。使用者層級規則 (~/.claude/rules/) 會在專案規則之前載入。

自動記憶 (Auto Memory) (~/.claude/projects/<project>/memory/) 是一個獨立的系統:它是 Claude 自己寫的筆記,並非 CLAUDE.md 內容,亦不屬於上述串接順序的一部分。參見下文 自動記憶 (Auto Memory)

注意CLAUDE.local.md 已獲得完整支援並記錄於官方文件中。它提供未提交至版本控制的個人特定專案偏好設定。請將 CLAUDE.local.md 新增至您的 .gitignore 中。

記憶搜尋行為 (Memory Discovery Behavior):

mermaid
graph TD
    A["管理策略 Managed Policy<br/>/Library/.../ClaudeCode/CLAUDE.md"] -->|最先載入| B["使用者指令 User Instructions<br/>~/.claude/CLAUDE.md"]
    B --> C["專案指令 Project Instructions<br/>./CLAUDE.md 或 ./.claude/CLAUDE.md"]
    C --> D["本地指令 Local Instructions<br/>./CLAUDE.local.md"]

    C -->|匯入| H["@docs/architecture.md"]
    H -->|匯入| I["@docs/api-standards.md"]

    style A fill:#fce4ec,stroke:#333,color:#333
    style B fill:#f3e5f5,stroke:#333,color:#333
    style C fill:#e1f5fe,stroke:#333,color:#333
    style D fill:#e8f5e9,stroke:#333,color:#333
    style H fill:#e1f5fe,stroke:#333,color:#333
    style I fill:#e1f5fe,stroke:#333,color:#333

圖中顯示的所有檔案都會串接至同一個脈絡中,而非透過覆寫進行選擇 — 較後出現的方塊在脈絡中位置較後,而非「取代」較早的方塊。

使用 claudeMdExcludes 排除 CLAUDE.md 檔案

在大型 Monorepo (單體式儲存庫) 中,某些 CLAUDE.md 檔案可能與您目前的工作無關。claudeMdExcludes 設定允許您跳過特定的 CLAUDE.md 檔案,使其不會載入至脈絡中:

jsonc
// 位於 ~/.claude/settings.json 或 .claude/settings.json
{
  "claudeMdExcludes": [
    "packages/legacy-app/CLAUDE.md",
    "vendors/**/CLAUDE.md"
  ]
}

模式會相對於專案根目錄進行路徑比對。這對於以下情況特別有用:

  • 擁有許多子專案且僅部分相關的 Monorepo
  • 包含廠商 (Vendored) 或第三方 CLAUDE.md 檔案的儲存庫
  • 透過排除過時或無關的指令來減少 Claude 脈絡視窗中的雜訊

設定檔案階層架構 (Settings File Hierarchy)

Claude Code 設定(包括 autoMemoryDirectoryclaudeMdExcludes 及其他配置)透過優先順序進行解析 — 與上述 CLAUDE.md 檔案不同,設定是真正的覆寫 (Override) 而非串接。當同一設定出現在多個範疇中時,較高層級勝出:

層級位置範疇 (Scope)
1 (最高)管理層級 — managed-settings.json、plist/登錄檔或伺服器管理組織範圍的強制規範;無法被覆寫
2命令列引數 (Command line arguments)臨時工作階段覆寫
3.claude/settings.local.json本地覆寫(已被 git 忽略)
4.claude/settings.json專案層級(已提交至 git)
5 (最低)~/.claude/settings.json使用者偏好設定

管理設定還支援在 managed-settings.json 旁邊放置 Drop-in 目錄 managed-settings.d/:基礎檔案先進行合併,接著 Drop-in 目錄中的 *.json 檔案按字母順序合併至上方(標量覆寫,陣列串接並去重,物件進行深層合併 Deep-merge)。這使不同團隊能夠部署獨立的策略片段,而無需編輯共享檔案。請注意這是 settings.json 的機制,非 CLAUDE.md 的機制 — 它不適用於上述的 CLAUDE.md 檔案位置。

權限規則 (allow/ask/deny) 的運作方式與其他設定不同:它們會跨範疇合併,而非較高層級取代較低層級。

特定平台配置 (v2.1.51+):

設定亦可透過以下方式配置:

  • macOS:屬性清單 (plist) 檔案
  • Windows:Windows 登錄檔 (Windows Registry)

這些平台原生機制會與 JSON 設定檔案一同讀取,並遵循相同的優先順序規則。

注意 (v2.1.119)/config 的變更現已持久化至 ~/.claude/settings.json。透過 /config 寫入的值會參與上述正常的策略/本地/專案優先順序鏈 — 它們不再僅限於工作階段。使用 /config 進行互動式編輯,並直接編輯 settings.json 檔案以進行指令稿或管理配置。

保留與清理設定 (Retention and Cleanup Settings)

設定型別預設值說明
cleanupPeriodDays整數 (天)30磁碟構件 (Artifacts) 的保留時間視窗。自 v2.1.117 起,它適用於以下四者:檢查點 (checkpoints, ~/.claude/checkpoints/)、任務 (tasks, ~/.claude/tasks/)、shell 快照 (shell-snapshots, ~/.claude/shell-snapshots/) 以及備份 (backups, ~/.claude/backups/)。早於視窗的檔案會在啟動時清理。
jsonc
// ~/.claude/settings.json
{
  "cleanupPeriodDays": 14
}

署名、語音與 PR URL 設定 (Attribution, Voice, and PR URL Settings)

設定型別說明
attribution.commit布林值 (boolean)為 Claude 建立的提交新增 Co-Authored-By: Claude 結尾標記 (trailer)。取代已廢棄的 includeCoAuthoredBy 旗標。
attribution.pr布林值 (boolean)在 Pull Request 描述中新增 Claude 署名。取代 PR 中已廢棄的 includeCoAuthoredBy 旗標。
attribution.sessionUrl布林值 (boolean)在 Web 與遠端控制 (Remote Control) 工作階段中建立的提交與 PR 忽略 claude.ai 工作階段連結 (v2.1.183+)。
voice.enabled布林值 (boolean)啟用按鍵語音聽寫 (Push-to-talk voice dictation, /voice)。取代已廢棄的 voiceEnabled 旗標。
prUrlTemplate字串 (string)v2.1.119 新增。 頁尾 PR 徽章的自訂 URL 範本;適用於 GitLab、Bitbucket 或內部程式碼審查平台。支援 預留位置。
jsonc
// ~/.claude/settings.json
{
  "attribution": {
    "commit": false,
    "pr": true
  },
  "voice": {
    "enabled": true
  },
  "prUrlTemplate": "https://gitlab.internal/{{owner}}/{{repo}}/-/merge_requests/{{number}}"
}

已廢棄的設定名稱 (Deprecated setting names)

以下舊版設定鍵值仍可運作但已被廢棄。建議使用上述替代選項。

廢棄鍵值替代選項附註
includeCoAuthoredByattribution.commit / attribution.pr舊的單一旗標拆分為獨立的 commit 與 PR 開關。舊安載版本的使用者可保留舊鍵值;新專案應使用巢狀形式。
voiceEnabledvoice.enabled歸類於 voice 命名空間下,與未來的語音相關選項並列。

模組化規則系統 (Modular Rules System)

使用 .claude/rules/ 目錄結構建立有組織、特定路徑的規則。規則可以在專案層級與使用者層級定義:

your-project/
├── .claude/
│   ├── CLAUDE.md
│   └── rules/
│       ├── code-style.md
│       ├── testing.md
│       ├── security.md
│       └── api/                  # 支援子目錄
│           ├── conventions.md
│           └── validation.md

~/.claude/
├── CLAUDE.md
└── rules/                        # 使用者層級規則(所有專案)
    ├── personal-style.md
    └── preferred-patterns.md

規則會在 rules/ 目錄(包含任何子目錄)中被遞迴搜尋。位於 ~/.claude/rules/ 的使用者層級規則會在專案層級規則之前載入,允許定義可被專案覆寫的個人預設值。

帶有 YAML Frontmatter 的特定路徑規則

定義僅適用於特定檔案路徑的規則:

markdown
---
paths: src/api/**/*.ts
---

# API Development Rules

- All API endpoints must include input validation
- Use Zod for schema validation
- Document all parameters and response types
- Include error handling for all operations

Glob 模式範例:

  • **/*.ts - 所有 TypeScript 檔案
  • src/**/* - src/ 下的所有檔案
  • src/**/*.{ts,tsx} - 多種副檔名
  • {src,lib}/**/*.ts, tests/**/*.test.ts - 多種模式

.claude/rules/ 中的規則支援兩種組織特性:

  • 子目錄:規則會被遞迴搜尋,因此您可以將其組織至基於主題的資料夾中(例如 rules/api/rules/testing/rules/security/
  • 符號連結 (Symlinks):支援符號連結以跨多個專案共享規則。例如,您可以將中央位置的共享規則檔案符號連結至每個專案的 .claude/rules/ 目錄中

記憶位置對照表 (Memory Locations Table)

CLAUDE.md 檔案與規則會串接至脈絡中,而非透過嚴格覆寫進行選擇 — 下表中的「載入順序」是指它出現在脈絡中的位置,而非哪一個勝出。自動記憶 (Auto Memory) 是一個獨立的機制,擁有自己的儲存位置。

位置型別載入順序共享存取權限最適合用於
/Library/Application Support/ClaudeCode/CLAUDE.md (macOS)管理策略第 1(最先載入)全組織系統公司範圍的策略
/etc/claude-code/CLAUDE.md (Linux/WSL)管理策略第 1(最先載入)全組織系統組織標準
C:\Program Files\ClaudeCode\CLAUDE.md (Windows)管理策略第 1(最先載入)全組織系統企業指南
~/.claude/rules/*.md使用者規則第 2個人檔案系統個人規則(所有專案)
~/.claude/CLAUDE.md使用者記憶第 3個人檔案系統個人偏好設定(所有專案)
./.claude/rules/*.md專案規則第 4團隊Git特定路徑的模組化規則
./CLAUDE.md./.claude/CLAUDE.md專案記憶第 5團隊Git團隊標準、共享架構
./CLAUDE.local.md專案本地第 6(最後載入)個人Git (已忽略)個人特定專案的偏好設定
~/.claude/projects/<project>/memory/自動記憶不適用 — 獨立機制個人檔案系統Claude 自動記錄的筆記與學習心得

記憶更新生命週期 (Memory Update Lifecycle)

以下是記憶更新如何在您的 Claude Code 工作階段中流動:

mermaid
sequenceDiagram
    participant User as 使用者
    participant Claude as Claude Code
    participant Editor as 檔案系統
    participant Memory as CLAUDE.md

    User->>Claude: "Remember: use async/await"
    Claude->>User: "Which memory file?"
    User->>Claude: "Project memory"
    Claude->>Editor: 開啟 ~/.claude/settings.json
    Claude->>Memory: 寫入 ./CLAUDE.md
    Memory-->>Claude: 檔案已儲存
    Claude->>Claude: 載入更新後的記憶
    Claude-->>User: "Memory saved!"

自動記憶 (Auto Memory)

自動記憶 (Auto Memory) 是一個持久目錄,Claude 在與您的專案合作時,會自動在其中記錄學習心得、模式與洞察。與由您手動撰寫與維護的 CLAUDE.md 檔案不同,自動記憶是由 Claude 本人在工作階段期間撰寫的。

自動記憶的運作方式

  • 位置~/.claude/projects/<project>/memory/
  • 入口點MEMORY.md 作為自動記憶目錄中的主檔案
  • 主題檔案 (Topic files):針對特定主題的選擇性額外檔案(例如 debugging.mdapi-conventions.md
  • 載入行為MEMORY.md 的前 200 行(或前 25KB,以先到者為準)會在工作階段啟動時載入至脈絡中。主題檔案是按需載入 (On-demand),非啟動時載入。
  • 讀取/寫入:Claude 在工作階段發現模式與專案特定知識時,會讀取與寫入記憶檔案
  • Frontmatter:以 YAML frontmatter 開頭的檔案會包含 modified 欄位 — 這是 Claude Code 每次寫入檔案時記錄的 ISO 8601 時間戳記 (v2.1.214)

自動記憶架構 (Auto Memory Architecture)

mermaid
graph TD
    A["Claude 工作階段開始"] --> B["載入 MEMORY.md<br/>(前 200 行 / 25KB)"]
    B --> C["工作階段作用中"]
    C --> D["Claude 發現<br/>模式與洞察"]
    D --> E{"寫入至<br/>自動記憶"}
    E -->|一般筆記| F["MEMORY.md"]
    E -->|特定主題| G["debugging.md"]
    E -->|特定主題| H["api-conventions.md"]
    C --> I["按需載入<br/>主題檔案"]
    I --> C

    style A fill:#e1f5fe,stroke:#333,color:#333
    style B fill:#e1f5fe,stroke:#333,color:#333
    style C fill:#e8f5e9,stroke:#333,color:#333
    style D fill:#f3e5f5,stroke:#333,color:#333
    style E fill:#fff3e0,stroke:#333,color:#333
    style F fill:#fce4ec,stroke:#333,color:#333
    style G fill:#fce4ec,stroke:#333,color:#333
    style H fill:#fce4ec,stroke:#333,color:#333
    style I fill:#f3e5f5,stroke:#333,color:#333

自動記憶目錄結構 (Auto Memory Directory Structure)

~/.claude/projects/<project>/memory/
├── MEMORY.md              # 入口點(啟動時載入前 200 行 / 25KB)
├── debugging.md           # 主題檔案(按需載入)
├── api-conventions.md     # 主題檔案(按需載入)
└── testing-patterns.md    # 主題檔案(按需載入)

版本需求

自動記憶需要 Claude Code v2.1.59 或更高版本。若您使用的是舊版本,請先進行升級:

bash
npm install -g @anthropic-ai/claude-code@latest

開啟或關閉自動記憶

自動記憶預設為開啟。由 autoMemoryEnabled 設定(預設為 true)進行控制;當設為 false 時,Claude 既不會從自動記憶目錄讀取,也不會向其寫入。您亦可在工作階段期間使用 /memory 進行切換。

json
{
  "autoMemoryEnabled": false
}

若要透過環境變數停用,請設定 CLAUDE_CODE_DISABLE_AUTO_MEMORY=1。將其設為 0 可強制開啟自動記憶,即使在 --bare 模式或 autoMemoryEnabled: false 原本會停用它的情況下亦然。

自訂自動記憶目錄 (Custom Auto Memory Directory)

預設情況下,自動記憶儲存於 ~/.claude/projects/<project>/memory/。您可以透過 autoMemoryDirectory 設定變更此位置(自 v2.1.74 起可用):

jsonc
// 位於 ~/.claude/settings.json 或 .claude/settings.local.json(僅限使用者/本地設定)
{
  "autoMemoryDirectory": "/path/to/custom/memory/directory"
}

注意autoMemoryDirectory 只能在使用者層級 (~/.claude/settings.json) 或本地設定 (.claude/settings.local.json) 中設定,不能在專案或管理策略設定中設定。

這在以下情況時非常有幫助:

  • 將自動記憶儲存於共享或同步位置
  • 將自動記憶與預設的 Claude 配置目錄拆分
  • 在預設階層架構之外使用專案特定的路徑

工作樹與儲存庫共享 (Worktree and Repository Sharing)

同一 Git 儲存庫內的所有工作樹 (Worktrees) 與子目錄都會共享單一自動記憶目錄。這意味著在工作樹之間切換或在同一儲存庫的不同子目錄中工作時,都會讀取與寫入相同的記憶檔案。

子代理記憶 (Subagent Memory)

子代理 (Subagents)(透過 Task 或平行執行等工具產生)可以擁有自己的記憶脈絡。在子代理定義中使用 memory frontmatter 欄位可指定要載入哪些記憶範疇:

yaml
memory: user      # 僅載入使用者層級記憶
memory: project   # 僅載入專案層級記憶
memory: local     # 僅載入本地記憶

這允許子代理在專注的脈絡下運作,而非繼承完整的記憶階層架構。

注意:子代理也可以維護自己的自動記憶。詳情請參閱官方子代理記憶文件

控制自動記憶

自動記憶可透過 CLAUDE_CODE_DISABLE_AUTO_MEMORY 環境變數進行控制:

數值行為
0強制開啟自動記憶
1強制關閉自動記憶
(未設定)預設行為(啟用自動記憶)
bash
# 為某個工作階段停用自動記憶
CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 claude

# 明確強制開啟自動記憶
CLAUDE_CODE_DISABLE_AUTO_MEMORY=0 claude

使用 --add-dir 載入附加目錄

--add-dir 旗標允許 Claude Code 從當前工作目錄之外的附加目錄載入 CLAUDE.md 檔案。這對於來自其他目錄的脈絡與目前相關的 Monorepo 或多專案設定非常有用。

若要啟用此功能,請設定環境變數:

bash
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1

然後帶著旗標啟動 Claude Code:

bash
claude --add-dir /path/to/other/project

Claude 會從指定的附加目錄載入 CLAUDE.md,並與來自您當前工作目錄的記憶檔案一同載入。

實務範例 (Practical Examples)

範例 1:專案記憶結構

檔案: ./CLAUDE.md

markdown
# Project Configuration

## Project Overview
- **Name**: E-commerce Platform
- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker
- **Team Size**: 5 developers
- **Deadline**: Q4 2025

## Architecture
@docs/architecture.md
@docs/api-standards.md
@docs/database-schema.md

## Development Standards

### Code Style
- Use Prettier for formatting
- Use ESLint with airbnb config
- Maximum line length: 100 characters
- Use 2-space indentation

### Naming Conventions
- **Files**: kebab-case (user-controller.js)
- **Classes**: PascalCase (UserService)
- **Functions/Variables**: camelCase (getUserById)
- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)
- **Database Tables**: snake_case (user_accounts)

### Git Workflow
- Branch names: `feature/description` or `fix/description`
- Commit messages: Follow conventional commits
- PR required before merge
- All CI/CD checks must pass
- Minimum 1 approval required

### Testing Requirements
- Minimum 80% code coverage
- All critical paths must have tests
- Use Jest for unit tests
- Use Cypress for E2E tests
- Test filenames: `*.test.ts` or `*.spec.ts`

### API Standards
- RESTful endpoints only
- JSON request/response
- Use HTTP status codes correctly
- Version API endpoints: `/api/v1/`
- Document all endpoints with examples

### Database
- Use migrations for schema changes
- Never hardcode credentials
- Use connection pooling
- Enable query logging in development
- Regular backups required

### Deployment
- Docker-based deployment
- Kubernetes orchestration
- Blue-green deployment strategy
- Automatic rollback on failure
- Database migrations run before deploy

## Common Commands

| Command | Purpose |
|---------|---------|
| `npm run dev` | Start development server |
| `npm test` | Run test suite |
| `npm run lint` | Check code style |
| `npm run build` | Build for production |
| `npm run migrate` | Run database migrations |

## Team Contacts
- Tech Lead: Sarah Chen (@sarah.chen)
- Product Manager: Mike Johnson (@mike.j)
- DevOps: Alex Kim (@alex.k)

## Known Issues & Workarounds
- PostgreSQL connection pooling limited to 20 during peak hours
- Workaround: Implement query queuing
- Safari 14 compatibility issues with async generators
- Workaround: Use Babel transpiler

## Related Projects
- Analytics Dashboard: `/projects/analytics`
- Mobile App: `/projects/mobile`
- Admin Panel: `/projects/admin`

範例 2:特定目錄的記憶

檔案: ./src/api/CLAUDE.md

markdown
# API Module Standards

This file supplements root CLAUDE.md for everything in /src/api/. Memory files are
concatenated, not overridden — the root CLAUDE.md still applies, and Claude Code
loads this file on demand when it reads files in this subtree.

## API-Specific Standards

### Request Validation
- Use Zod for schema validation
- Always validate input
- Return 400 with validation errors
- Include field-level error details

### Authentication
- All endpoints require JWT token
- Token in Authorization header
- Token expires after 24 hours
- Implement refresh token mechanism

### Response Format

All responses must follow this structure:

```json
{
  "success": true,
  "data": { /* actual data */ },
  "timestamp": "2025-11-06T10:30:00Z",
  "version": "1.0"
}
```

Error responses:
```json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "User message",
    "details": { /* field errors */ }
  },
  "timestamp": "2025-11-06T10:30:00Z"
}
```

### Pagination
- Use cursor-based pagination (not offset)
- Include `hasMore` boolean
- Limit max page size to 100
- Default page size: 20

### Rate Limiting
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints
- Return 429 when exceeded
- Include retry-after header

### Caching
- Use Redis for session caching
- Cache duration: 5 minutes default
- Invalidate on write operations
- Tag cache keys with resource type

範例 3:個人記憶

檔案: ~/.claude/CLAUDE.md

markdown
# My Development Preferences

## About Me
- **Experience Level**: 8 years full-stack development
- **Preferred Languages**: TypeScript, Python
- **Communication Style**: Direct, with examples
- **Learning Style**: Visual diagrams with code

## Code Preferences

### Error Handling
I prefer explicit error handling with try-catch blocks and meaningful error messages.
Avoid generic errors. Always log errors for debugging.

### Comments
Use comments for WHY, not WHAT. Code should be self-documenting.
Comments should explain business logic or non-obvious decisions.

### Testing
I prefer TDD (test-driven development).
Write tests first, then implementation.
Focus on behavior, not implementation details.

### Architecture
I prefer modular, loosely-coupled design.
Use dependency injection for testability.
Separate concerns (Controllers, Services, Repositories).

## Debugging Preferences
- Use console.log with prefix: `[DEBUG]`
- Include context: function name, relevant variables
- Use stack traces when available
- Always include timestamps in logs

## Communication
- Explain complex concepts with diagrams
- Show concrete examples before explaining theory
- Include before/after code snippets
- Summarize key points at the end

## Project Organization
I organize my projects as:

   project/
   ├── src/
   │   ├── api/
   │   ├── services/
   │   ├── models/
   │   └── utils/
   ├── tests/
   ├── docs/
   └── docker/

## Tooling
- **IDE**: VS Code with vim keybindings
- **Terminal**: Zsh with Oh-My-Zsh
- **Format**: Prettier (100 char line length)
- **Linter**: ESLint with airbnb config
- **Test Framework**: Jest with React Testing Library

我的測試 要求 Claude 儲存新規則

Ask Claude to save a new rule Claude 沒有儲存該規則,因為我在任何地方都沒有 Claude.md 檔案。然後要求 Claude 確認位置。

Ask Claude to save a new rule

範例 4:工作階段期間的記憶更新

您可以在作用中的 Claude Code 工作階段期間透過對話要求新增新規則至記憶:

markdown
User: Remember that I prefer using React hooks instead of class components
     for all new components.

Claude: I'm adding that to your memory. Which memory file should this go in?
        1. Project memory (./CLAUDE.md)
        2. Personal memory (~/.claude/CLAUDE.md)

User: Project memory

Claude: ✅ Memory saved!

Added to ./CLAUDE.md:
---

### Component Development
- Use functional components with React Hooks
- Prefer hooks over class components
- Custom hooks for reusable logic
- Use useCallback for event handlers
- Use useMemo for expensive computations

或使用 /memory 直接編輯記憶檔案以進行大量更新或重組。

新增記憶的技巧

  • 在規則中保持具體且具可操作性
  • 將相關規則分組在小節標題之下
  • 更新現有章節而非複製重複的內容
  • 選擇合適的記憶範疇(專案 vs 個人)

記憶功能比較 (Memory Features Comparison)

功能Claude Web/DesktopClaude Code (CLAUDE.md)
自動綜合 (Auto-synthesis)✅ 每 24 小時✅ 自動記憶
跨專案 (Cross-project)✅ 共享❌ 特定專案
團隊存取 (Team access)✅ 共享專案✅ Git 追蹤
可搜尋 (Searchable)✅ 內建✅ 透過 /memory
可編輯 (Editable)✅ 聊天內✅ 直接檔案編輯
匯入/匯出 (Import/Export)✅ 是✅ 複製/貼上
持久性 (Persistent)✅ 24h+✅ 永久

Claude Web/Desktop 中的記憶 (Memory in Claude Web/Desktop)

記憶綜合時間線 (Memory Synthesis Timeline)

mermaid
graph LR
    A["第 1 天:使用者<br/>對話"] -->|24 小時| B["第 2 天:記憶<br/>綜合 Synthesis"]
    B -->|自動| C["記憶已更新<br/>已摘要"]
    C -->|載入至| D["第 2-N 天:<br/>新對話"]
    D -->|新增至| E["記憶"]
    E -->|24 小時後| F["記憶已重整"]

範例記憶摘要:

markdown
## Claude's Memory of User

### Professional Background
- Senior full-stack developer with 8 years experience
- Focus on TypeScript/Node.js backends and React frontends
- Active open source contributor
- Interested in AI and machine learning

### Project Context
- Currently building e-commerce platform
- Tech stack: Node.js, PostgreSQL, React 18, Docker
- Working with team of 5 developers
- Using CI/CD and blue-green deployments

### Communication Preferences
- Prefers direct, concise explanations
- Likes visual diagrams and examples
- Appreciates code snippets
- Explains business logic in comments

### Current Goals
- Improve API performance
- Increase test coverage to 90%
- Implement caching strategy
- Document architecture

最佳實踐 (Best Practices)

正確做法 — 應該包含的內容 (Do's - What To Include)

  • 保持具體與詳細:使用清晰詳細的指令而非模糊的指引

    • ✅ 良好:「所有 JavaScript 檔案皆使用 2 個空格縮排」
    • ❌ 避免:「遵循最佳實踐」
  • 保持條理:使用清晰的 Markdown 章節與標題組織記憶檔案

  • 使用適當的層級

    • 管理策略 (Managed policy):公司範圍的策略、安全性標準、合規需求
    • 專案記憶 (Project memory):團隊標準、架構、程式碼編寫慣例(提交至 Git)
    • 使用者記憶 (User memory):個人偏好、溝通風格、工具選擇
    • 目錄記憶 (Directory memory):模組特定的規則與覆寫
  • 善用匯入 (Imports):使用 @path/to/file 語法引用現有文件

    • 遞迴匯入支援最大 4 次跳轉 (Hops) 的深度
    • 避免跨記憶檔案的內容重複
    • 範例:See @README.md for project overview
  • 記錄常用指令:包含您重複使用的指令以節省時間

  • 對專案記憶進行版本控制:將專案層級的 CLAUDE.md 檔案提交至 Git 以使團隊受益

  • 定期審視:隨著專案演進與需求變更,定期更新記憶

  • 提供具體範例:包含程式碼片段與具體情境

錯誤做法 — 應該避免的內容 (Don'ts - What To Avoid)

  • 切勿儲存金鑰/秘密:絕不包含 API 金鑰、密碼、權杖 (Tokens) 或憑證

  • 切勿包含敏感資料:禁止個人可識別資訊 (PII)、隱私資訊或專有秘密

  • 切勿複製重複內容:改用匯入 (@path) 來引用現有說明文件

  • 切勿模稜兩可:避免像「遵循最佳實踐」或「寫出優良程式碼」這類通用陳述

  • 切勿使內容過長:目標為每個 CLAUDE.md 控制在 200 行以內。較長的檔案雖然仍會完整載入,但指令遵循度會下降 — 參見下文 保持 CLAUDE.md 精簡

  • 切勿過度組織:策略性地使用層級架構;不要建立過多的子目錄覆寫

  • 切勿忘記更新:過時的記憶會導致混淆與陳舊的做法

  • 切勿超過巢狀限制:記憶匯入最高支援 4 次跳轉深度

保持 CLAUDE.md 精簡 (Keeping CLAUDE.md Small)

Anthropic 目前的指引與「把所有東西都放進 CLAUDE.md」正好相反。該檔案會載入至每一個工作階段中,因此您新增的每一行都會在無關的任務中競爭注意力。

經驗法則:保持 CLAUDE.md 在 200 行以內。 較長的檔案仍會完整載入,但隨著檔案增大,指令的遵循度會有所下降。

當檔案開始膨脹時,應將內容移出而非僅精簡文句:

內容應該放置的位置原因
多步驟程序 (Multi-step procedures)一項技能 (Skill)僅在相關時按需載入 (Loads on demand)
目錄或檔案型別特定的規則帶有 paths: frontmatter 的 .claude/rules/*.md由 glob 設定範疇;僅在您觸及相符檔案時載入
參考資料與長範例技能的 references/ 目錄僅在技能需要時讀取
Claude 應該記住關於的事項自動記憶 (Auto Memory)(預設開啟)自動寫入與載入

注意@path 匯入可以組織大型 CLAUDE.md,但無法節省脈絡 — 匯入的檔案在載入時同樣會被拉入。拆分為特定路徑範疇的規則 (Path-scoped rules) 才是真正減少載入內容的方法。

/doctor(v2.1.206+)會檢查您的配置,並在 CLAUDE.md 成長至失去實用性時提出精簡建議。

切勿撰寫驗證提醒事項 (Don't Write Verification Reminders)

舊的指引曾鼓勵加入「在聲明完成前務必執行測試」或「重複檢查您的工作」等語句。在 Claude Opus 5 與 Fable 5 上,這些現在會導致過度驗證 (Over-verification) — Claude 會重新檢查已經正確的工作,消耗對話輪數與權杖 (Tokens)。

Anthropic 為 Claude 5 世代刪除了 Claude Code 本身系統提示詞 (System Prompt) 中超過 80% 的內容,且未測得任何效能退化。同樣的原則亦適用於您的 CLAUDE.md:傾向於陳述目標並讓 Claude 自行發揮判斷力,而非列舉其應執行的檢查項目。

從針對 Opus 5 或 Fable 5 的現有 CLAUDE.md 檔案中刪除驗證提醒事項。請保留真正非顯而易見的專案需求 —「整合測試需要 Docker 執行」屬於資訊,而非提醒事項。

記憶管理技巧 (Memory Management Tips)

選擇正確的記憶層級:

使用案例記憶層級理據
公司安全性策略管理策略 (Managed Policy)適用於全組織的所有專案
團隊程式碼風格指南專案 (Project)透過 Git 與團隊共享
您偏好的編輯器快速鍵使用者 (User)個人偏好,不共享
API 模組標準目錄 (Directory)僅適用於該特定模組

快速更新工作流程:

  1. 對於單一規則:使用 /memory 開啟編輯器,或透過對話請求
  2. 對於多項變更:使用 /memory 開啟編輯器
  3. 對於初始設定:使用 /init 建立範本

匯入最佳實踐:

markdown
# Good: Reference existing docs
@README.md
@docs/architecture.md
@package.json

# Avoid: Copying content that exists elsewhere
# Instead of copying README content into CLAUDE.md, just import it

安裝指南 (Installation Instructions)

設定專案記憶 (Setup Project Memory)

方法 1:使用 /init 指令(推薦)

設定專案記憶最快的方法:

  1. 導覽至您的專案目錄:

    bash
    cd /path/to/your/project
  2. 在 Claude Code 中執行 init 指令:

    bash
    /init
  3. Claude 將會建立並以範本結構填入 CLAUDE.md

  4. 自訂產生的檔案以符合您的專案需求

  5. 提交至 Git:

    bash
    git add CLAUDE.md
    git commit -m "Initialize project memory with /init"

方法 2:手動建立

若您偏好手動設定:

  1. 在專案根目錄建立 CLAUDE.md

    bash
    cd /path/to/your/project
    touch CLAUDE.md
  2. 新增專案標準:

    bash
    cat > CLAUDE.md << 'EOF'
    # Project Configuration
    
    ## Project Overview
    - **Name**: Your Project Name
    - **Tech Stack**: List your technologies
    - **Team Size**: Number of developers
    
    ## Development Standards
    - Your coding standards
    - Naming conventions
    - Testing requirements
    EOF
  3. 提交至 Git:

    bash
    git add CLAUDE.md
    git commit -m "Add project memory configuration"

設定個人記憶 (Setup Personal Memory)

  1. 建立 ~/.claude 目錄:

    bash
    mkdir -p ~/.claude
  2. 建立個人 CLAUDE.md

    bash
    touch ~/.claude/CLAUDE.md
  3. 新增您的偏好設定:

    bash
    cat > ~/.claude/CLAUDE.md << 'EOF'
    # My Development Preferences
    
    ## About Me
    - Experience Level: [Your level]
    - Preferred Languages: [Your languages]
    - Communication Style: [Your style]
    
    ## Code Preferences
    - [Your preferences]
    EOF

設定特定目錄的記憶 (Setup Directory-Specific Memory)

  1. 為特定目錄建立記憶:

    bash
    mkdir -p /path/to/directory/.claude
    touch /path/to/directory/CLAUDE.md
  2. 新增目錄特定的規則:

    bash
    cat > /path/to/directory/CLAUDE.md << 'EOF'
    # [Directory Name] Standards
    
    This file supplements root CLAUDE.md for this directory. Memory files are
    concatenated, not overridden — Claude Code loads this file on demand when it
    reads files in this directory.
    
    ## [Specific Standards]
    EOF
  3. 提交至版本控制:

    bash
    git add /path/to/directory/CLAUDE.md
    git commit -m "Add [directory] memory configuration"

驗證設定 (Verify Setup)

  1. 檢查記憶位置:

    bash
    # 專案根目錄記憶
    ls -la ./CLAUDE.md
    
    # 個人記憶
    ls -la ~/.claude/CLAUDE.md
  2. Claude Code 將會自動載入啟動工作階段時的這些檔案

  3. 使用 Claude Code 進行測試:在您的專案中啟動新的工作階段

官方說明文件 (Official Documentation)

如需最新資訊,請參考官方 Claude Code 說明文件:

來自官方文件的關鍵技術細節 (Key Technical Details from Official Docs)

記憶載入 (Memory Loading):

  • 當 Claude Code 啟動時,所有記憶檔案皆會自動載入
  • Claude 會從當前工作目錄向上巡覽以搜尋 CLAUDE.md 檔案
  • 子樹檔案會在存取這些目錄時,依據脈絡被搜尋與載入

匯入語法 (Import Syntax):

  • 使用 @path/to/file 包含外部內容(例如 @~/.claude/my-project-instructions.md
  • 同時支援相對路徑與絕對路徑(相對路徑相對於包含匯入指令的檔案解析,而非工作目錄)
  • 支援遞迴匯入,最大深度為 4 次跳轉 (Hops)
  • 首次外部匯入會觸發核准對話方塊
  • 在 Markdown 程式碼跨度或程式碼區塊內部不會被求值
  • 自動將引用的內容包含在 Claude 的脈絡中

CLAUDE.md 載入順序(串接進入脈絡,而非嚴格覆寫 — 請參見上文 Claude Code 中的記憶層級架構):

  1. 管理策略 (Managed Policy)(最先載入)
  2. 使用者層級規則 (User-Level Rules, ~/.claude/rules/)
  3. 使用者記憶 (User Memory)
  4. 專案規則 (Project Rules, .claude/rules/)
  5. 專案記憶 (Project Memory)
  6. 本地專案記憶 (Local Project Memory)(最後載入)

自動記憶 (Auto Memory) 是一個獨立的機制 (~/.claude/projects/<project>/memory/),不屬於此串接順序的一部分。

整合點 (Integration Points)


最後更新:2026 年 8 月 25 日 Claude Code 版本:2.1.245 來源

Released under the MIT License.