# user data

Claude Code 收集特定的用户数据以提供功能和改进服务。本文档详细说明收集的数据类型和用途。

## 收集的数据类型

### 1. 系统信息

#### 操作系统信息

```typescript
interface SystemInfo {
  platform: string;        // 'darwin' | 'linux' | 'win32'
  arch: string;            // 'x64' | 'arm64'
  osVersion: string;      // 操作系统版本
  nodeVersion: string;    // Node.js 版本
  shell: string;          // 'bash' | 'zsh' | 'fish' | 'powershell'
}

// 收集方式
const systemInfo = {
  platform: process.platform,
  arch: process.arch,
  osVersion: os.release(),
  nodeVersion: process.version,
  shell: process.env.SHELL || 'unknown',
};
```

**用途**:

* 平台特定功能适配
* Bug 报告和诊断
* 性能优化

**是否发送到服务器**: 否（仅本地使用）

#### 工作目录信息

```typescript
interface WorkspaceInfo {
  cwd: string;              // 当前工作目录
  gitRoot?: string;         // Git 仓库根目录
  hasGit: boolean;          // 是否是 Git 仓库
  projectType?: string;     // 'node' | 'python' | 'rust' 等
}
```

**用途**:

* 提供上下文相关的建议
* 工具执行的工作目录

**是否发送到服务器**: 否（路径信息不发送）

### 2. 使用数据

#### 命令执行历史

```typescript
interface CommandHistory {
  command: string;          // 执行的命令
  timestamp: number;        // 时间戳
  success: boolean;         // 是否成功
  duration: number;         // 执行时间（毫秒）
}

// 存储位置
const historyPath = path.join(
  os.homedir(),
  '.claude-code',
  'history',
  'commands.json'
);
```

**用途**:

* 命令补全和建议
* 使用模式分析
* 性能优化

**是否发送到服务器**: 否（仅本地存储）

#### 工具调用统计

```typescript
interface ToolUsageStats {
  toolName: string;         // 工具名称
  callCount: number;        // 调用次数
  successCount: number;     // 成功次数
  failureCount: number;     // 失败次数
  avgDuration: number;      // 平均执行时间
  lastUsed: number;         // 最后使用时间
}
```

**用途**:

* 性能监控
* 功能使用分析
* 优化工具优先级

**是否发送到服务器**: 是（匿名统计数据）

#### 错误日志

```typescript
interface ErrorLog {
  timestamp: number;
  errorType: string;        // 错误类型
  errorMessage: string;     // 错误消息（已脱敏）
  stackTrace?: string;      // 堆栈跟踪（已脱敏）
  context: {
    tool?: string;          // 相关工具
    command?: string;       // 相关命令（已脱敏）
  };
}
```

**用途**:

* Bug 修复
* 稳定性改进
* 用户支持

**是否发送到服务器**: 是（可选，需用户同意）

### 3. 会话数据

#### 对话历史

```typescript
interface ConversationHistory {
  sessionId: string;
  messages: Message[];      // 对话消息
  createdAt: number;
  updatedAt: number;
}

// 存储位置
const sessionPath = path.join(
  os.homedir(),
  '.claude-code',
  'sessions',
  `${sessionId}.json`
);
```

**用途**:

* 会话恢复
* 上下文保持
* 历史搜索

**是否发送到服务器**: 部分（仅发送当前会话到 Anthropic API）

#### 文件访问记录

```typescript
interface FileAccessLog {
  path: string;             // 文件路径（已脱敏）
  operation: string;        // 'read' | 'write' | 'delete'
  timestamp: number;
  success: boolean;
}
```

**用途**:

* 审计日志
* 安全监控
* 撤销功能

**是否发送到服务器**: 否（仅本地存储）

### 4. 配置数据

#### 用户配置

```typescript
interface UserConfig {
  model: string;            // 使用的模型
  temperature: number;      // 温度参数
  maxTokens: number;        // 最大 token 数
  permissionMode: string;   // 权限模式
  autoCompact: boolean;     // 自动压缩
  theme: string;            // 主题
}
```

**用途**:

* 个性化体验
* 功能配置
* 偏好设置

**是否发送到服务器**: 否（仅本地存储）

#### 扩展配置

```typescript
interface ExtensionConfig {
  skills: string[];         // 启用的 Skills
  plugins: string[];        // 启用的 Plugins
  mcpServers: MCPServerConfig[];
  hooks: Hook[];
}
```

**用途**:

* 扩展管理
* 功能定制

**是否发送到服务器**: 否（仅本地存储）

### 5. 性能指标

#### 性能数据

```typescript
interface PerformanceMetrics {
  startupTime: number;      // 启动时间
  firstResponseTime: number; // 首次响应时间
  toolExecutionTimes: Map<string, number[]>;
  tokenCounts: number[];
  cacheHitRate: number;
  memoryUsage: {
    heapUsed: number;
    heapTotal: number;
  };
}
```

**用途**:

* 性能优化
* 问题诊断
* 用户体验改进

**是否发送到服务器**: 是（匿名统计数据）

## 数据脱敏

### 敏感信息过滤

```typescript
function sanitizeData(data: any): any {
  // 移除 PII
  data = removePII(data);
  
  // 移除路径信息
  data = removePathInfo(data);
  
  // 移除 API 密钥
  data = removeAPIKeys(data);
  
  return data;
}

function removePII(text: string): string {
  return text
    .replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]')
    .replace(/\b[\w.-]+@[\w.-]+\.\w+\b/g, '[EMAIL]')
    .replace(/\b\d{16}\b/g, '[CREDIT_CARD]')
    .replace(/sk-[a-zA-Z0-9]{48}/g, '[API_KEY]');
}

function removePathInfo(text: string): string {
  return text
    .replace(/\/Users\/[^\/]+/g, '/Users/[USER]')
    .replace(/C:\\Users\\[^\\]+/g, 'C:\\Users\\[USER]')
    .replace(/\/home\/[^\/]+/g, '/home/[USER]');
}
```

### 路径哈希

```typescript
function hashPath(path: string): string {
  // 使用哈希而非原始路径
  return crypto
    .createHash('sha256')
    .update(path)
    .digest('hex')
    .substring(0, 16);
}
```

## 数据存储

### 本地存储位置

```
~/.claude-code/
├── config.json           # 用户配置
├── sessions/             # 会话历史
│   ├── session-1.json
│   └── session-2.json
├── history/              # 命令历史
│   └── commands.json
├── cache/                # 缓存数据
│   ├── prompts/
│   └── tools/
└── logs/                 # 日志文件
    ├── error.log
    └── usage.log
```

### 数据加密

```typescript
// 敏感数据加密存储
import { encrypt, decrypt } from './crypto';

async function saveSecureData(key: string, data: any): Promise<void> {
  const encrypted = encrypt(JSON.stringify(data), SECRET_KEY);
  await fs.writeFile(getSecurePath(key), encrypted);
}

async function loadSecureData(key: string): Promise<any> {
  const encrypted = await fs.readFile(getSecurePath(key));
  const decrypted = decrypt(encrypted, SECRET_KEY);
  return JSON.parse(decrypted);
}
```

## 数据发送

### 发送到 Anthropic API

```typescript
// 发送到 Anthropic 的数据
interface APIRequest {
  model: string;
  messages: Message[];      // 当前会话消息
  system: string;           // System Prompt
  tools: ToolDefinition[];  // 工具定义
}

// 不发送的数据
// - 完整文件路径
// - 用户个人信息
// - API 密钥
// - 本地配置
```

### 遥测数据（可选）

```typescript
interface TelemetryData {
  // 匿名使用统计
  toolUsage: {
    [toolName: string]: number;
  };
  
  // 性能指标
  performance: {
    avgStartupTime: number;
    avgResponseTime: number;
  };
  
  // 错误统计
  errors: {
    [errorType: string]: number;
  };
  
  // 不包含任何个人信息
  userId: string;  // 匿名 ID（哈希）
}
```

## 用户控制

### 数据收集级别

```json
{
  "telemetry": {
    "level": "full",  // 'none' | 'minimal' | 'full'
    "errorReporting": true,
    "usageStats": true,
    "performanceMetrics": true
  }
}
```

### 禁用数据收集

```bash
# 完全禁用遥测
claude-code config set telemetry.level none

# 只禁用错误报告
claude-code config set telemetry.errorReporting false
```

### 查看收集的数据

```bash
# 查看本地存储的数据
claude-code data show

# 导出数据
claude-code data export --output data.json

# 删除所有数据
claude-code data clear
```

## 数据保留

### 保留期限

* **会话历史**: 30 天（可配置）
* **命令历史**: 90 天
* **错误日志**: 7 天
* **缓存数据**: 24 小时

### 自动清理

```typescript
async function cleanupOldData(): Promise<void> {
  const now = Date.now();
  const retentionPeriods = {
    sessions: 30 * 24 * 60 * 60 * 1000,  // 30 天
    commands: 90 * 24 * 60 * 60 * 1000,  // 90 天
    errors: 7 * 24 * 60 * 60 * 1000,     // 7 天
    cache: 24 * 60 * 60 * 1000,          // 24 小时
  };
  
  // 清理过期数据
  await cleanupSessions(now - retentionPeriods.sessions);
  await cleanupCommands(now - retentionPeriods.commands);
  await cleanupErrors(now - retentionPeriods.errors);
  await cleanupCache(now - retentionPeriods.cache);
}
```

## 隐私保护

### GDPR 合规

* ✅ 数据最小化原则
* ✅ 用户同意机制
* ✅ 数据访问权
* ✅ 数据删除权
* ✅ 数据可移植性

### 数据请求

```bash
# 请求数据副本
claude-code privacy export

# 删除所有数据
claude-code privacy delete

# 查看隐私政策
claude-code privacy policy
```

## 下一步

* 查看 [隐私与安全](https://halls-organization-2.gitbook.io/halls-organization/api/broken-reference) 的详细措施
* 了解 [Anthropic API](https://halls-organization-2.gitbook.io/halls-organization/api/broken-reference) 的数据传输
* 探索 [工具 API](https://halls-organization-2.gitbook.io/halls-organization/api/broken-reference) 的数据访问
